Showing preview only (7,921K chars total). Download the full file or copy to clipboard to get everything.
Repository: 3Alan/DocsMind
Branch: main
Commit: 056fe21553d0
Files: 66
Total size: 7.5 MB
Directory structure:
gitextract_phhhif57/
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ └── config.yml
│ └── workflows/
│ └── issue.yml
├── .gitignore
├── Deployment.md
├── LICENSE
├── README.md
├── client/
│ ├── .eslintrc.json
│ ├── .prettierrc
│ ├── index.html
│ ├── package.json
│ ├── postcss.config.cjs
│ ├── src/
│ │ ├── App.tsx
│ │ ├── components/
│ │ │ ├── chatWindow/
│ │ │ │ ├── Loading.tsx
│ │ │ │ ├── Message.tsx
│ │ │ │ ├── constants.ts
│ │ │ │ └── index.tsx
│ │ │ ├── fileCard/
│ │ │ │ └── index.tsx
│ │ │ ├── htmlViewer/
│ │ │ │ └── index.tsx
│ │ │ ├── pageSpin/
│ │ │ │ └── index.tsx
│ │ │ ├── pdfViewer/
│ │ │ │ └── index.tsx
│ │ │ ├── settingsModal/
│ │ │ │ └── index.tsx
│ │ │ ├── sideMenu/
│ │ │ │ └── index.tsx
│ │ │ └── upload/
│ │ │ └── index.tsx
│ │ ├── constants/
│ │ │ └── fileItem.ts
│ │ ├── context/
│ │ │ └── currentFile.ts
│ │ ├── main.tsx
│ │ ├── pages/
│ │ │ └── Home.tsx
│ │ ├── routes.tsx
│ │ ├── styles/
│ │ │ └── globals.scss
│ │ ├── utils/
│ │ │ ├── eventEmitter.ts
│ │ │ ├── fetch.ts
│ │ │ ├── isDev.ts
│ │ │ ├── isPdf.ts
│ │ │ ├── request.ts
│ │ │ └── useOpenAiKey.ts
│ │ └── vite-env.d.ts
│ ├── tailwind.config.js
│ ├── tsconfig.json
│ ├── tsconfig.node.json
│ └── vite.config.ts
├── docker/
│ ├── Dockerfile.client
│ └── Dockerfile.server
├── docker-compose.yml
├── nginx.conf
├── server/
│ ├── Procfile
│ ├── app.py
│ ├── create_index.py
│ ├── custom_loader.py
│ ├── pdf_loader.py
│ ├── requirements.txt
│ └── static/
│ ├── file/
│ │ ├── AA-README.html
│ │ ├── TypeScript入门学习总结.html
│ │ ├── clean-code-javascript.html
│ │ └── heading-test.html
│ ├── index/
│ │ ├── AA-README.json
│ │ ├── TypeScript入门学习总结.json
│ │ ├── clean-code-javascript.json
│ │ ├── github-privacy.json
│ │ └── heading-test.json
│ └── testFiles/
│ ├── TypeScript入门学习总结.md
│ ├── clean-code-javascript.md
│ ├── heading-test.md
│ └── no-match-heading-test.md
└── vercel.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
server/static/** linguist-detectable=false
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: 🐞 Bug Report
description: Create a report to help us improve
title: "[Bug]: "
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
- type: textarea
id: description
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is. If applicable, add screenshots to help explain your problem.
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Please copy and paste any relevant log located at `logs/app.log` and the client error (browser console) so that I can better understand the issue. If there are no errors, fill in no
render: shell
validations:
required: true
- type: checkboxes
id: validations
attributes:
label: Validations
description: Before submitting the issue, please make sure you do the following
options:
- label: Already read the README
required: true
- label: Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
required: true
validations:
required: true
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: 🚀 New feature proposal
url: https://github.com/3Alan/DocsMind/discussions
about: Request for new features.
================================================
FILE: .github/workflows/issue.yml
================================================
name: 'Close stale issues'
permissions:
contents: write # only for delete-branch option
issues: write
pull-requests: write
on:
schedule:
- cron: '30 1 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v8
with:
stale-issue-message: 'This issue is stale because it has been open 5 days with no activity. Remove stale label or comment or this will be closed in 2 days.'
close-issue-message: 'This issue was closed because it has been stalled for 2 days with no activity.'
days-before-issue-stale: 5
days-before-issue-close: 2
days-before-pr-close: -1
================================================
FILE: .gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.env
# python
.vercel
*.pyc
__pycache__/
.venv/
*.pyo
*.pyd
instance/
build
*.spec
temp
data
================================================
FILE: Deployment.md
================================================
The first thing you need to know is that this project includes frontend (UI) and backend. I strongly recommend using Docker for deployment.
If you just want to try it out instead of using it in a production environment, you can deploy it using Vercel + Railway.
## Docker
Fork the repository and clone the code to your local machine.
> **Warning**
>
> Please check if you can access OpenAI in your region, you can refer to the [issue](https://github.com/3Alan/DocsMind/issues/3#issuecomment-1511470063) for more information.
1. Create .env
Create a `.env` file and copy the contents of `.env.example` to modify it.
2. Run App
```bash
docker-compose up -d
```
Please add `--build` to rebuild the image after each code update.
```bash
docker-compose up -d --build
```
now you can access the app at `http://localhost:8081`
All data will be saved in the `./data` directory.
## Vercel + Railway
> **Warning**
>
> ❗❗❗ if you want to use this project in a production environment, do not deploy it in this way. All data will be cleared when you redeploy.
We will deploy the code separately to Vercel and Railway.
Please follow the steps one by one.
### Railway
Deploy the backend using the following template.
[](https://railway.app/template/HcW7kc?referralCode=Hk0oZ6)
Do not check Private repository.

After deployment, you will receive a domain. Copy it as it will be used later.

You can also customize the domain.

### Vercel
1. Select the repository created by Railway.
2. Change the Root Directory to "client".
3. Change the Framework Preset to "Vite".
4. Add an environment variable `VITE_SERVICES_URL` with the value of Railway's Domain.


Now you can upload your files, ❗❗❗ but please be reminded that all data will be cleared once you redeploy.
**If you have a better deployment method, please feel free to share the tutorial and submit a pull request.**
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: README.md
================================================
# DocsMind
DocsMind is an open-source project that allows you to chat with your docs.

It is currently under development and there may be major changes at any time.
## 🎬 Demo
[Demo Site](https://docs-mind.alanwang.site/)
> **Warning**
>
> Due to the free plan of Railway only providing 500 hours per month, the Demo on the 21st day of each month will not be available. Please clone it locally for use at that time.
## 🌟 Features
- 🤖 Ask a question with your docs
- 📝 Summarize docs
- 🖍️ Highlight source
- 📤 Upload docs .pdf,.md(best support)
- 💾 Data saved locally
- 💰 Token usage tracker
- 🐳 Dockerize
## 🚀 Road Map
- [ ] Chat mode
- [ ] Dark mode
- [ ] / command (/fetch /summarize)
- [ ] Reduce the size of the server image.
- [ ] Support for more docs formats: txt...
- [ ] Download docs from the internet
- [ ] Markdown-formatted message
- [ ] i18n
- [ ] Desktop application
If you find this project helpful, please consider giving it a star 🌟
## 💻 Environment Variables
| Name | Description | Optional |
| -------------------- | -------------------------------------- | -------- |
| OPENAI_PROXY | will replace https://api.openai.com/v1 | ✅ |
| VITE_SERVICES_URL | backend url for frontend code | ✅ |
| VITE_DISABLED_UPLOAD | DISABLED_UPLOAD | ✅ |
## ❓ FAQ
This project includes both frontend (/client) and backend (/server) code. The frontend code is used to display the UI, while the backend code provides services to the UI.
### How to deploy?
[More details](https://github.com/3Alan/DocsMind/blob/main/Deployment.md)
### How to run?
> **Warning**
>
> Please check if you can access OpenAI in your region, you can refer to the [issue](https://github.com/3Alan/DocsMind/issues/3#issuecomment-1511470063) for more information.
1. Create .env
Create a `.env` file and copy the contents of `.env.example` to modify it.
2. Run App
```bash
docker-compose up -d
```
Please add `--build` to rebuild the image after each code update.
```bash
docker-compose up -d --build
```
now you can access the app at `http://localhost:8081`
All data will be saved in the `./data` directory.
### Local Development
<details>
<summary>Detail</summary>
#### Create .env
Create a `.env` file and copy the contents of `.env.example` to modify it.
#### Run Frontend UI
1. Install dependencies
```
yarn
```
2. Run app
```
yarn dev
```
#### Run Backend Services
you need a python environment
1. Create virtual environment
```
cd server
python -m venv .venv
```
2. Active virtual environment
windows
```
.venv\Scripts\activate
```
mac
```
. .venv/bin/activate
```
3. Install dependencies
```
pip install -r requirements.txt
```
4. Run Services
```
flask run --reload --port=8080
```
</details>
## 📝 License
[AGPL-3.0 License](https://github.com/3Alan/DocsMind/blob/main/LICENSE)
## ☕ Buy me a coffee
[](https://ko-fi.com/N4N1L5Y7V)
<details>
<summary>Alipay and Wechat</summary>
<img height="300" src="https://raw.githubusercontent.com/3Alan/images/master/img/%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98%E5%AE%9D%E4%BA%8C%E5%90%88%E4%B8%80%E6%94%B6%E6%AC%BE%E7%A0%81.jpg" />
</details>
================================================
FILE: client/.eslintrc.json
================================================
{
"env": {
"browser": true,
"es2021": true
},
"extends": ["eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"overrides": [],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["react", "react-hooks", "@typescript-eslint", "prettier"],
"rules": {
"react/react-in-jsx-scope": "off",
"@typescript-eslint/no-explicit-any": "off",
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
}
]
},
"settings": {
"import/resolver": {
"typescript": {}
}
}
}
================================================
FILE: client/.prettierrc
================================================
{
"printWidth": 100,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none"
}
================================================
FILE: client/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DocsMind</title>
<meta
name="description"
content="DocsMind allows you to chat with your docs and summarize your docs, support pdf, md."
/>
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="DocsMind" />
<meta
name="twitter:description"
content="DocsMind allows you to chat with your docs and summarize your docs, support pdf, md."
/>
<meta
name="twitter:image"
content="https://raw.githubusercontent.com/3Alan/images/master/img/20230507230412.png"
/>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
================================================
FILE: client/package.json
================================================
{
"name": "docs-mind",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "eslint --ext js,jsx,ts,tsx src",
"lint:fix": "eslint --ext js,jsx,ts,tsx src --fix"
},
"dependencies": {
"@ant-design/icons": "^5.0.1",
"@types/lodash": "^4.14.191",
"@vercel/analytics": "^0.1.11",
"antd": "^5.3.0",
"axios": "^1.3.4",
"canvas-confetti": "^1.6.0",
"classnames": "^2.3.2",
"github-markdown-css": "^5.2.0",
"lodash": "^4.17.21",
"mitt": "^3.0.0",
"query-string": "^8.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-pdf": "^6.2.2",
"react-router-dom": "^6.9.0"
},
"devDependencies": {
"@types/canvas-confetti": "^1.6.0",
"@types/react": "^18.0.28",
"@types/react-dom": "^18.0.11",
"@types/react-pdf": "^6.2.0",
"@typescript-eslint/eslint-plugin": "^5.57.0",
"@typescript-eslint/parser": "^5.57.0",
"@vitejs/plugin-react": "^3.1.0",
"autoprefixer": "^10.4.14",
"eslint": "^8.37.0",
"eslint-config-prettier": "^8.8.0",
"eslint-import-resolver-typescript": "^3.5.4",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"postcss": "^8.4.21",
"prettier": "^2.8.7",
"sass": "^1.62.1",
"tailwindcss": "^3.3.0",
"typescript": "^4.9.3",
"vite": "^4.2.0"
}
}
================================================
FILE: client/postcss.config.cjs
================================================
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
================================================
FILE: client/src/App.tsx
================================================
import './styles/globals.scss';
import 'github-markdown-css/github-markdown-light.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import routes from './routes';
import SideMenu from './components/sideMenu';
import SettingsModal from './components/settingsModal';
import { useEffect, useState } from 'react';
import request from './utils/request';
import FileItem from './constants/fileItem';
import { CurrentFileContext } from './context/currentFile';
import eventEmitter from './utils/eventEmitter';
const App = () => {
const [currentFile, setCurrentFile] = useState<FileItem | null>(null);
const [fileList, setFileList] = useState<FileItem[]>([]);
const [showSettingModal, setShowSettingModal] = useState(false);
async function getFileList() {
const res = await request('/api/file-list');
setFileList(res.data);
if (res.data.length > 0) {
setCurrentFile(res.data[0]);
}
}
function handleFileClick(item: any) {
const file = fileList.find((f) => f.name === item.name) || null;
setCurrentFile(file);
}
function toggleSettingModal(open: boolean) {
setShowSettingModal(open);
}
useEffect(() => {
getFileList();
eventEmitter.on('refreshFileList', getFileList);
return () => {
eventEmitter.off('refreshFileList', getFileList);
};
}, []);
return (
<BrowserRouter>
<main className="bg-slate-100 h-screen flex">
<SideMenu
onFileClick={handleFileClick}
fileList={fileList}
activeFile={currentFile?.name || ''}
onOpenSetting={() => toggleSettingModal(true)}
/>
<SettingsModal open={showSettingModal} onChange={toggleSettingModal} />
<div className="flex flex-1 h-full overflow-hidden">
<CurrentFileContext.Provider value={currentFile}>
<Routes>
{routes.map((route) => (
<Route key={route.path} path={route.path} element={route.element} />
))}
</Routes>
</CurrentFileContext.Provider>
</div>
</main>
</BrowserRouter>
);
};
export default App;
================================================
FILE: client/src/components/chatWindow/Loading.tsx
================================================
export default function Loading() {
return (
<span className="py-2 px-4 shadow rounded-lg mb-5 bg-blue-50">
<svg
className="text-2xl"
width="1em"
viewBox="0 0 120 30"
xmlns="http://www.w3.org/2000/svg"
fill="#94a3b8"
>
<circle cx="15" cy="15" r="15">
<animate
attributeName="r"
from="15"
to="15"
begin="0s"
dur="0.8s"
values="15;9;15"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="fill-opacity"
from="1"
to="1"
begin="0s"
dur="0.8s"
values="1;.5;1"
calcMode="linear"
repeatCount="indefinite"
/>
</circle>
<circle cx="60" cy="15" r="9" fillOpacity="0.3">
<animate
attributeName="r"
from="9"
to="9"
begin="0s"
dur="0.8s"
values="9;15;9"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="fill-opacity"
from="0.5"
to="0.5"
begin="0s"
dur="0.8s"
values=".5;1;.5"
calcMode="linear"
repeatCount="indefinite"
/>
</circle>
<circle cx="105" cy="15" r="15">
<animate
attributeName="r"
from="15"
to="15"
begin="0s"
dur="0.8s"
values="15;9;15"
calcMode="linear"
repeatCount="indefinite"
/>
<animate
attributeName="fill-opacity"
from="1"
to="1"
begin="0s"
dur="0.8s"
values="1;.5;1"
calcMode="linear"
repeatCount="indefinite"
/>
</circle>
</svg>
</span>
);
}
================================================
FILE: client/src/components/chatWindow/Message.tsx
================================================
import { DollarOutlined, HighlightOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { FC, MouseEvent, PropsWithChildren, ReactNode, useEffect, useState } from 'react';
import { MessageItem } from './constants';
import Loading from './Loading';
import { isEmpty, isString } from 'lodash';
import { Collapse, Space, Tooltip } from 'antd';
const { Panel } = Collapse;
interface MessageProps extends PropsWithChildren {
isQuestion?: boolean;
loading?: boolean;
text: ReactNode;
item?: MessageItem;
chunkIdList?: number[];
error?: boolean;
onSourceClick?: (data: any) => void;
}
const Message: FC<MessageProps> = ({
text = '',
isQuestion,
item,
loading,
error,
onSourceClick
}) => {
const [words, setWords] = useState<string[]>([]);
const [showSources, setShowSources] = useState<boolean>(false);
useEffect(() => {
if (!error && isString(text)) {
setWords(text.split(' '));
}
}, [text]);
if (loading) {
return <Loading />;
}
function handleSourceClick(e: MouseEvent, item: any) {
e.stopPropagation();
onSourceClick?.(item);
}
function toggleShowSource() {
setShowSources(!showSources);
}
return (
<div
className={classNames('flex flex-col pt-2 mb-5', {
['self-end']: isQuestion,
['w-full']: !isQuestion
})}
>
<div
className={classNames('flex mb-1 justify-between', {
['self-end']: isQuestion
})}
>
<Space className="text-gray-400">
<strong className="text-gray-400 pr-2 ">{isQuestion ? 'You' : 'AI'}</strong>
{item?.cost && (
<Tooltip title={`Estimated cost ${item.cost} tokens`}>
<span className="cursor-pointer">
<DollarOutlined /> cost
</span>
</Tooltip>
)}
</Space>
{!isEmpty(item?.sources) && (
<div
className="cursor-pointer text-gray-400 text-xs items-center flex"
onClick={toggleShowSource}
>
{showSources ? 'Hide Sources' : 'Show Source'}
</div>
)}
</div>
{showSources && (
<Collapse accordion expandIconPosition="end" size="small" className="mb-3">
{item?.sources?.map((item, index) => (
<Panel
header={`Source ${index + 1}`}
key={index + 1}
extra={
<HighlightOutlined
className="text-gray-400 hover:text-gray-800"
onClick={(e) => handleSourceClick(e, item)}
/>
}
>
{item.text}
</Panel>
))}
</Collapse>
)}
<div
className={classNames(
'flex flex-col pt-2 shadow rounded-lg mb-5 whitespace-pre-wrap',
isQuestion ? 'bg-blue-500 self-end text-white' : 'bg-blue-50 w-full'
)}
>
{isQuestion ? (
<div className="px-3 pb-2">{text}</div>
) : (
<div className="px-3 pb-2 text-gray-800">
{error && text}
{words.map((word, index) => (
<span key={index}>{word} </span>
))}
</div>
)}
</div>
</div>
);
};
export default Message;
================================================
FILE: client/src/components/chatWindow/constants.ts
================================================
import { ReactNode } from 'react';
export interface MessageItem {
question?: string;
reply?: ReactNode;
cost?: number;
sources?: any[];
error?: boolean;
}
================================================
FILE: client/src/components/chatWindow/index.tsx
================================================
import { ProfileOutlined, SendOutlined, WarningTwoTone } from '@ant-design/icons';
import { Button, Card, Input, message, Popconfirm, Tooltip } from 'antd';
import classNames from 'classnames';
import { isEmpty } from 'lodash';
import { FC, Fragment, KeyboardEvent, useEffect, useLayoutEffect, useRef, useState } from 'react';
import eventEmitter from '../../utils/eventEmitter';
import fetchRequest from '../../utils/fetch';
import useOpenAiKey from '../../utils/useOpenAiKey';
import { MessageItem } from './constants';
import Message from './Message';
interface ChatWindowProps {
fileName: string;
fullFileName: string;
className?: string;
onReplyComplete: (data: any) => void;
onSourceClick: (data: any) => void;
}
const ChatWindow: FC<ChatWindowProps> = ({
fileName,
fullFileName,
className,
onReplyComplete,
onSourceClick
}) => {
const chatWindowRef = useRef<HTMLDivElement>(null);
const [loading, setLoading] = useState(false);
const [query, setQuery] = useState('');
const [messageList, setMessageList] = useState<MessageItem[]>([]);
const openAiKey = useOpenAiKey();
function cleanChat() {
setMessageList([]);
}
useEffect(() => {
eventEmitter.on('cleanChat', cleanChat);
return () => {
eventEmitter.off('cleanChat', cleanChat);
};
}, []);
useLayoutEffect(() => {
requestAnimationFrame(() => scrollToBottom());
}, [messageList]);
const scrollToBottom = () => {
const chatWindow = chatWindowRef.current;
chatWindow && (chatWindow.scrollTop = chatWindow?.scrollHeight || 0);
};
const updateMessageList = (message: string) => {
setMessageList((pre) => {
return [
...pre.slice(0, -1),
{
...pre.slice(-1)[0],
reply: pre.slice(-1)[0].reply + message
}
];
});
};
const onReply = async (value: string, summarize = false) => {
try {
let res: Response;
setLoading(true);
if (summarize) {
res = await fetchRequest('/api/summarize', {
file: fullFileName,
openAiKey
});
} else {
res = await fetchRequest('/api/query', {
query: value,
index: fileName,
openAiKey
});
}
setLoading(false);
const reader = res?.body?.getReader() as ReadableStreamDefaultReader;
const decoder = new TextDecoder();
let done = false;
let metaData: any;
while (!done) {
const { value, done: doneReading } = await reader.read();
done = doneReading;
const chunkValue = decoder.decode(value);
const hasMeta = chunkValue.includes('\n ###endjson### \n\n');
if (hasMeta) {
const [metaDataStr, message] = chunkValue.split('\n ###endjson### \n\n');
metaData = JSON.parse(metaDataStr);
updateMessageList(message.trim());
} else {
updateMessageList(chunkValue);
}
}
setMessageList((pre) => {
return [
...pre.slice(0, -1),
{
...pre.slice(-1)[0],
cost: metaData.cost,
sources: metaData.sources
}
];
});
onReplyComplete({ ...metaData?.sources[0] });
} catch (error) {
setLoading(false);
setMessageList((pre) => {
return [
...pre.slice(0, -1),
{
...pre.slice(-1),
reply: (
<>
<WarningTwoTone /> please retry
</>
),
error: true
}
];
});
console.log(error);
}
};
const onSearch = async () => {
if (!openAiKey) {
message.error('Please set your openAI key');
return;
}
setQuery('');
setMessageList([...messageList, { question: query }, { reply: '' }]);
onReply(query);
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.shiftKey) return;
if (e.key === 'Enter') {
e.preventDefault();
onSearch();
}
};
const onSummarize = async () => {
setMessageList([...messageList, { question: 'Summarize the Document' }, { reply: '' }]);
onReply('', true);
};
const onSummarizeClick = () => {
if (!isEmpty(fileName)) {
onSummarize();
}
};
return (
<Card
style={{ width: 390 }}
className={classNames(className, 'rounded-none')}
bodyStyle={{
flex: 1,
overflow: 'auto',
display: 'flex',
flexDirection: 'column',
padding: '24px 0'
}}
title={fileName ? `Chat with ${fileName}` : 'Select File'}
extra={
<Popconfirm
disabled={!openAiKey}
title="This will consume a large amount of tokens"
description="Do you want to continue?"
okText="Yes"
cancelText="No"
onConfirm={onSummarizeClick}
>
<Tooltip title="Summarize">
<Button icon={<ProfileOutlined />} disabled={!openAiKey}></Button>
</Tooltip>
</Popconfirm>
}
bordered={false}
>
<div ref={chatWindowRef} className="flex flex-col items-start flex-1 overflow-auto px-6">
{messageList.map((item, index) => (
<Fragment key={index}>
{item.question ? (
<Message isQuestion text={item.question} />
) : (
<Message
loading={loading && index === messageList.length - 1}
item={item}
text={item.reply || ''}
onSourceClick={onSourceClick}
error={item.error}
/>
)}
</Fragment>
))}
</div>
<div className="p-4 pb-0 border-t border-t-gray-200 border-solid border-x-0 border-b-0">
<div className="relative">
<Input.TextArea
disabled={loading || !openAiKey}
size="large"
placeholder={openAiKey ? 'Input your question' : 'Configure your OpenAI key'}
value={query}
className="pr-[36px]"
onKeyDown={onKeyDown}
autoSize
onChange={(e) => setQuery(e.target.value)}
/>
<Button
style={{ width: 32 }}
size="small"
type="text"
className="absolute right-1 top-2"
icon={<SendOutlined style={{ color: '#3f95ff' }} />}
onClick={onSearch}
></Button>
</div>
</div>
</Card>
);
};
export default ChatWindow;
================================================
FILE: client/src/components/fileCard/index.tsx
================================================
import { FilePdfTwoTone, FileTextTwoTone } from '@ant-design/icons';
import { Card, Space } from 'antd';
import classNames from 'classnames';
import { MouseEventHandler } from 'react';
import FileItem from '../../constants/fileItem';
import isPdf from '../../utils/isPdf';
interface FileCardProps {
item: FileItem;
active?: boolean;
onClick: MouseEventHandler<HTMLDivElement>;
}
export default function FileCard({ item, onClick, active }: FileCardProps) {
return (
<Card
bodyStyle={{ padding: '12px 10px' }}
className={classNames('p-0 text-sm mb-3 cursor-pointer hover:border-blue-500', {
['border-blue-50 bg-card-blue']: active
})}
onClick={onClick}
>
<Space className="flex items-start">
{isPdf(item.ext) ? <FilePdfTwoTone twoToneColor="#e94847" /> : <FileTextTwoTone />}
<div>{item.name.split(item.ext)}</div>
</Space>
</Card>
);
}
================================================
FILE: client/src/components/htmlViewer/index.tsx
================================================
import { useEffect, useRef } from 'react';
import PageSpin from '../pageSpin';
export default function HtmlViewer({ html, loading }: { html: string; loading: boolean }) {
const htmlRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (htmlRef.current) {
htmlRef.current.scrollTop = 0;
}
}, [html]);
return (
<div
ref={htmlRef}
className="markdown-body h-full rounded-lg overflow-auto relative w-[700px] shadow-md"
>
{loading ? <PageSpin /> : <div dangerouslySetInnerHTML={{ __html: html }} />}
</div>
);
}
================================================
FILE: client/src/components/pageSpin/index.tsx
================================================
import { Spin } from 'antd';
export default function PageSpin() {
return (
<div className="w-full h-full flex justify-center items-center">
<Spin delay={500} />
</div>
);
}
================================================
FILE: client/src/components/pdfViewer/index.tsx
================================================
import { Document, Page } from 'react-pdf/dist/esm/entry.vite';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import type { PDFDocumentProxy } from 'pdfjs-dist';
import { useEffect, useRef, useState } from 'react';
import eventEmitter from '../../utils/eventEmitter';
import PageSpin from '../pageSpin';
export default function PdfViewer({ file }: { file: Blob }) {
const [numPages, setNumPages] = useState<number>();
const pdfRef = useRef<HTMLDivElement>(null);
function scrollToPage(meta: { pageNo: number; time: number }) {
const { pageNo, time } = meta;
setTimeout(() => {
if (pdfRef?.current) {
pdfRef.current?.children[pageNo - 1].scrollIntoView();
}
}, time);
}
useEffect(() => {
eventEmitter.on('scrollToPage', scrollToPage);
return () => {
eventEmitter.off('scrollToPage', scrollToPage);
};
}, []);
function onDocumentLoadSuccess({ numPages: nextNumPages }: PDFDocumentProxy) {
setNumPages(nextNumPages);
}
return (
<Document
inputRef={pdfRef}
loading={<PageSpin />}
className="w-[700px] bg-white h-full overflow-auto relative scroll-smooth rounded-lg shadow-md"
file={file}
onLoadSuccess={onDocumentLoadSuccess}
options={{
cMapUrl: 'cmaps/',
standardFontDataUrl: 'standard_fonts/'
}}
>
{Array.from(new Array(numPages), (_el, index) => (
<Page width={690} key={`page_${index + 1}`} pageNumber={index + 1} />
))}
</Document>
);
}
================================================
FILE: client/src/components/settingsModal/index.tsx
================================================
import { Form, Input, Modal } from 'antd';
import { useEffect, useRef } from 'react';
import eventEmitter from '../../utils/eventEmitter';
interface SettingsModalProps {
open: boolean;
onChange: (open: boolean) => void;
}
export default function SettingsModal({ open, onChange }: SettingsModalProps) {
const settings = useRef<any>(null);
const [form] = Form.useForm();
useEffect(() => {
const localSettings = JSON.parse(localStorage.getItem('settings') as string);
settings.current = localSettings;
}, [open]);
const onSaveSettings = () => {
form
.validateFields()
.then((values) => {
localStorage.setItem('settings', JSON.stringify(values));
onChange(false);
eventEmitter.emit('refreshSettings');
})
.catch((info) => {
console.log('Validate Failed:', info);
});
};
return (
<Modal title="Settings" open={open} onOk={onSaveSettings} onCancel={() => onChange(false)}>
<Form
form={form}
initialValues={{
apiKey: settings.current?.apiKey
}}
>
<Form.Item
label="apiKey"
name="apiKey"
rules={[{ required: true, message: 'Please input your apiKey!' }]}
>
<Input />
</Form.Item>
</Form>
</Modal>
);
}
================================================
FILE: client/src/components/sideMenu/index.tsx
================================================
import { Alert, Button, Divider, Space } from 'antd';
import FileItem from '../../constants/fileItem';
import FileCard from '../fileCard';
import FileUpload from '../upload';
import { GithubOutlined, SettingOutlined } from '@ant-design/icons';
interface SideMenuProps {
fileList: FileItem[];
activeFile: string;
onFileClick: (item: FileItem) => void;
onOpenSetting: () => void;
}
const disableUpload = import.meta.env.VITE_DISABLED_UPLOAD;
export default function SideMenu({
fileList,
onFileClick,
activeFile,
onOpenSetting
}: SideMenuProps) {
return (
<div className="flex flex-col w-[250px] h-full bg-white py-4 px-2 justify-between">
<div className="flex-1 overflow-auto">
{fileList.map((item) => (
<FileCard
key={item.name}
active={activeFile === item.name}
onClick={() => onFileClick(item)}
item={item}
/>
))}
</div>
<Divider />
{disableUpload ? (
<Alert
type="warning"
description={
<>
The upload is not available on the current website. You can
<a href="https://github.com/3Alan/DocsMind" target="__blank">
{' '}
fork and clone the project{' '}
</a>
to your local device to complete the upload.
</>
}
/>
) : (
<FileUpload />
)}
<div className="mt-2 flex justify-between items-center">
<span className="text-xs text-gray-500">Made by Alan</span>
<Space>
<Button
href="https://github.com/3Alan/DocsMind"
target="__blank"
icon={<GithubOutlined />}
></Button>
<Button icon={<SettingOutlined />} onClick={onOpenSetting}></Button>
</Space>
</div>
</div>
);
}
================================================
FILE: client/src/components/upload/index.tsx
================================================
import { InboxOutlined } from '@ant-design/icons';
import { message, Spin, Upload } from 'antd';
import { useState } from 'react';
import confetti from 'canvas-confetti';
import { baseURL } from '../../utils/request';
import useOpenAiKey from '../../utils/useOpenAiKey';
import eventEmitter from '../../utils/eventEmitter';
const { Dragger } = Upload;
function generateConfetti() {
confetti({
spread: 90,
particleCount: 80,
origin: { y: 0.5 },
ticks: 300
});
}
export default function FileUpload() {
const [uploading, setUploading] = useState(false);
const openAiKey = useOpenAiKey();
const onUploadChange = (info: any) => {
setUploading(true);
const { status } = info.file;
if (status === 'done' || status === 'success') {
generateConfetti();
void message.success({
content: `${info.file.name} file uploaded successfully. token usage: 💰 ${info.file.response}`,
duration: 8
});
eventEmitter.emit('refreshFileList');
setUploading(false);
} else if (status === 'error') {
void message.error(
`${info.file.name} file upload failed. ${JSON.stringify(info.file.response)}`
);
setUploading(false);
}
};
return (
<div className="w-full">
<Spin spinning={uploading}>
<Dragger
action={`${baseURL}/api/upload`}
data={{ openAiKey }}
multiple={false}
showUploadList={false}
name="file"
accept=".md,.pdf"
onChange={onUploadChange}
disabled={!openAiKey}
>
<p className="text-blue-500">
<InboxOutlined style={{ fontSize: 32 }} />
</p>
<p className="text-sm">Click or drag file to this area to upload</p>
<p className="text-xs text-gray-400">Support .md,.pdf</p>
</Dragger>
</Spin>
</div>
);
}
================================================
FILE: client/src/constants/fileItem.ts
================================================
export default interface FileItem {
name: string;
fullName: string;
path: string;
ext: string;
}
================================================
FILE: client/src/context/currentFile.ts
================================================
import { createContext } from 'react';
import FileItem from '../constants/fileItem';
export const CurrentFileContext = createContext<FileItem | null>(null);
================================================
FILE: client/src/main.tsx
================================================
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { inject } from '@vercel/analytics';
inject();
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
================================================
FILE: client/src/pages/Home.tsx
================================================
import { Empty } from 'antd';
import { useContext, useEffect, useState } from 'react';
import ChatWindow from '../components/chatWindow';
import request from '../utils/request';
import eventEmitter from '../utils/eventEmitter';
import PdfViewer from '../components/pdfViewer';
import { isEmpty, has } from 'lodash';
import FileItem from '../constants/fileItem';
import { CurrentFileContext } from '../context/currentFile';
import isPdf from '../utils/isPdf';
import HtmlViewer from '../components/htmlViewer';
function removeHighLight() {
const highLightElements = document.querySelectorAll('.hl-source');
highLightElements?.forEach((element) => {
element.classList.remove('hl-source');
});
}
function addHighLight(chunkId: string, time = 400) {
removeHighLight();
const firstElement = document.querySelector(`[data-chunk_id=${chunkId}]`);
setTimeout(() => {
firstElement?.scrollIntoView({ behavior: 'smooth' });
}, time);
const highLightElements = document.querySelectorAll(`[data-chunk_id=${chunkId}]`);
highLightElements?.forEach((element) => {
element.classList.add('hl-source');
});
}
async function downloadFile(fileItem: FileItem) {
let res;
if (isPdf(fileItem.ext)) {
res = await request(fileItem.path, {
responseType: 'blob'
});
} else {
res = await request(fileItem.path);
}
return res.data;
}
const Home = () => {
const [file, setFile] = useState(null);
const [loading, setLoading] = useState(false);
const currentFile = useContext(CurrentFileContext);
useEffect(() => {
eventEmitter.emit('cleanChat');
getFile();
}, [currentFile]);
async function getFile() {
if (currentFile) {
setLoading(true);
const file = await downloadFile(currentFile);
setLoading(false);
setFile(file);
}
}
function handleHighLight(item: any, time = 400) {
if (isEmpty(item)) {
return;
}
// PDF
if (has(item.extraInfo, 'page_no')) {
eventEmitter.emit('scrollToPage', { pageNo: item.extraInfo.page_no, time });
} else {
addHighLight(item.extraInfo.chunk_id, time);
}
}
return (
<div className="w-full flex">
<div className="flex h-full overflow-auto flex-1 justify-center py-3">
{file ? (
<>
{isPdf(currentFile?.ext || '') ? (
<PdfViewer file={file} />
) : (
<HtmlViewer html={file} loading={loading} />
)}
</>
) : (
<Empty
className="mt-24"
image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
imageStyle={{ height: 60 }}
description={<span>No uploaded file.</span>}
/>
)}
</div>
<ChatWindow
fullFileName={currentFile?.fullName || ''}
fileName={currentFile?.name.split(currentFile.ext)[0] || ''}
className="flex flex-col"
onReplyComplete={handleHighLight}
onSourceClick={(item) => handleHighLight(item, 0)}
/>
</div>
);
};
export default Home;
================================================
FILE: client/src/routes.tsx
================================================
import Home from './pages/Home';
const routes = [
{
path: '/',
element: <Home />
}
];
export default routes;
================================================
FILE: client/src/styles/globals.scss
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
* {
margin: 0;
box-sizing: border-box;
}
body {
position: fixed;
width: 100%;
height: 100%;
overflow: hidden;
}
.markdown-body {
table {
&.hl-source {
border-radius: 0;
tr, td {
background-color: #eff6ff;
border-radius: 0;
}
}
}
.hl-source {
background-color: #eff6ff;
border-radius: 6px;
pre {
background-color: #eff6ff !important;
}
}
}
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 20px 40px;
}
/* 修改滚动条的宽度和颜色 */
::-webkit-scrollbar {
width: 8px;
height: 8px;
background-color: #f2f2f2;
}
/* 修改滚动条滑块的样式 */
::-webkit-scrollbar-thumb {
background-color: #ccc;
border-radius: 5px;
}
/* 修改滚动条滑块悬停时的样式 */
::-webkit-scrollbar-thumb:hover {
background-color: #999;
}
/* 修改滚动条轨道的样式 */
::-webkit-scrollbar-track {
background-color: #fff;
border-radius: 8px;
}
.markdown-body video {
width: 100%;
}
// TODO: 使用 antd 的 Token实现
.ant-menu-item {
padding-left: 16px !important;
}
.ant-menu-item-active {
background-color: #eff6ff;
}
.ant-collapse-header {
padding: 4px 12px;
}
.ant-collapse-content-box {
font-size: 12px;
padding: 8px 12px !important;
}
.react-pdf__message--loading {
height: 100%;
}
@media (prefers-color-scheme: dark) {
}
================================================
FILE: client/src/utils/eventEmitter.ts
================================================
import mitt from 'mitt';
type Events = {
scrollToPage: { pageNo: number; time: number };
cleanChat?: null;
refreshFileList?: null;
refreshSettings?: null;
};
const eventEmitter = mitt<Events>();
export default eventEmitter;
================================================
FILE: client/src/utils/fetch.ts
================================================
import { baseURL } from './request';
import queryString from 'query-string';
export default async function fetchRequest(url: string, params: { [key: string]: any }) {
const combineUrl = queryString.stringifyUrl({
url: `${baseURL}${url}`,
query: params
});
const res = await fetch(combineUrl);
if (res.ok) {
return res;
}
return Promise.reject(res.statusText);
}
================================================
FILE: client/src/utils/isDev.ts
================================================
export const isDev = import.meta.env.DEV;
================================================
FILE: client/src/utils/isPdf.ts
================================================
export default function isPdf(ext: string) {
return ext === '.pdf';
}
================================================
FILE: client/src/utils/request.ts
================================================
import { message } from 'antd';
import axios from 'axios';
export const baseURL = import.meta.env.VITE_SERVICES_URL || 'http://localhost:8080';
const request = axios.create({
baseURL
});
request.interceptors.response.use(
function (response) {
return response;
},
function (error) {
message.error(error.response.data.message);
return Promise.reject(error);
}
);
export default request;
================================================
FILE: client/src/utils/useOpenAiKey.ts
================================================
import { useEffect, useState } from 'react';
import eventEmitter from './eventEmitter';
export default function useOpenAiKey() {
const [apiKey, setApiKey] = useState(null);
const getApiKey = () => {
const apiKey = JSON.parse(localStorage.getItem('settings') as string)?.apiKey || null;
setApiKey(apiKey);
};
useEffect(() => {
getApiKey();
eventEmitter.on('refreshSettings', getApiKey);
return () => {
eventEmitter.off('refreshSettings', getApiKey);
};
}, []);
return apiKey;
}
================================================
FILE: client/src/vite-env.d.ts
================================================
/// <reference types="vite/client" />
================================================
FILE: client/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {
colors: {
'card-blue': '#e6f4ff'
}
}
},
plugins: [],
corePlugins: {
preflight: false
}
};
================================================
FILE: client/tsconfig.json
================================================
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
================================================
FILE: client/tsconfig.node.json
================================================
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
================================================
FILE: client/vite.config.ts
================================================
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()]
});
================================================
FILE: docker/Dockerfile.client
================================================
FROM node:16-alpine as client
WORKDIR /client
COPY ./client .
RUN yarn install
RUN yarn build
RUN rm -rf node_modules
RUN rm -rf src
FROM nginx:1.23.4-alpine
COPY --from=client /client/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
================================================
FILE: docker/Dockerfile.server
================================================
FROM python:3.9-slim-buster
WORKDIR /server
COPY ./server/requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY ./server .
COPY .env .
EXPOSE 8080
CMD ["flask", "run", "--host", "0.0.0.0", "--port", "8080"]
================================================
FILE: docker-compose.yml
================================================
version: '3'
services:
client:
build:
context: .
dockerfile: docker/Dockerfile.client
ports:
- "8081:80"
server:
build:
context: .
dockerfile: docker/Dockerfile.server
ports:
- "8080:8080"
volumes:
- ./data:/server/static
- ./logs:/server/logs
================================================
FILE: nginx.conf
================================================
server {
listen 80;
location ~ /(api|static) {
proxy_pass http://server:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
alias /usr/share/nginx/html/;
try_files $uri /index.html;
if ($request_filename ~ .*\.(htm|html)$) {
add_header Cache-Control 'no-store, no-cache, must-revalidate';
}
}
}
================================================
FILE: server/Procfile
================================================
web: gunicorn app:app
================================================
FILE: server/app.py
================================================
import json
import logging
import os
from pathlib import Path
import openai
from create_index import create_index
from dotenv import load_dotenv
from flask import Flask, Response, jsonify, request, stream_with_context
from flask_cors import CORS
from llama_index import (
GPTListIndex,
GPTSimpleVectorIndex,
MockEmbedding,
MockLLMPredictor,
ServiceContext,
download_loader,
)
from llama_index.optimization.optimizer import SentenceEmbeddingOptimizer
openai_proxy = os.environ.get("OPENAI_PROXY", "https://api.openai.com/v1")
openai.api_base = openai_proxy
staticPath = "static"
if not os.path.exists(f"{staticPath}/file"):
os.makedirs(f"{staticPath}/file")
if not os.path.exists(f"{staticPath}/index"):
os.makedirs(f"{staticPath}/index")
if not os.path.exists(f"{staticPath}/temp"):
os.makedirs(f"{staticPath}/temp")
if not os.path.exists(f"logs"):
os.makedirs(f"logs")
app = Flask(__name__, static_folder=f"{staticPath}")
CORS(app)
logger = logging.getLogger(__name__)
file_handler = logging.FileHandler("logs/app.log", encoding="utf-8")
formatter = logging.Formatter(
"%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.ERROR)
logger.addHandler(file_handler)
load_dotenv()
@app.errorhandler(Exception)
def handle_error(error):
"""全局错误处理"""
message = str(error)
status_code = 500
if hasattr(error, "status_code"):
status_code = error.status_code
print("some error:", error)
response = jsonify({"message": message})
response.status_code = status_code
logger.error(error, exc_info=True)
return response
@app.route("/api/summarize", methods=["GET"])
def summarize_index():
file = request.args.get("file")
open_ai_key = request.args.get("openAiKey")
if open_ai_key:
os.environ["OPENAI_API_KEY"] = open_ai_key
UnstructuredReader = download_loader("UnstructuredReader")
loader = UnstructuredReader()
documents = loader.load_data(file=Path(f"./{staticPath}/file/{file}"))
index = GPTListIndex.from_documents(documents)
# predictor cost
llm_predictor = MockLLMPredictor(max_tokens=256)
embed_model = MockEmbedding(embed_dim=1536)
service_context = ServiceContext.from_defaults(
llm_predictor=llm_predictor, embed_model=embed_model
)
# TODO: Format everything as markdown
prompt = f"""
Summarize this document and provide three questions related to the summary. Try to use your own words when possible. Keep your answer under 5 sentences.
Use the following format:
<summary text>
Questions you may want to ask 🤔
1. <question text>
2. <question text>
3. <question text>
"""
index.query(
prompt,
response_mode="tree_summarize",
service_context=service_context,
optimizer=SentenceEmbeddingOptimizer(percentile_cutoff=0.8),
)
res = index.query(
prompt,
streaming=True,
response_mode="tree_summarize",
optimizer=SentenceEmbeddingOptimizer(percentile_cutoff=0.8),
)
cost = embed_model.last_token_usage + llm_predictor.last_token_usage
def response_generator():
yield json.dumps({"cost": cost, "sources": []})
yield "\n ###endjson### \n\n"
for text in res.response_gen:
yield text
# 用完了就删掉,防止key被反复使用
if open_ai_key:
os.environ["OPENAI_API_KEY"] = ""
return Response(stream_with_context(response_generator()))
@app.route("/api/query", methods=["GET"])
def query_index():
query_text = request.args.get("query")
index_name = request.args.get("index")
open_ai_key = request.args.get("openAiKey")
if open_ai_key:
os.environ["OPENAI_API_KEY"] = open_ai_key
index = GPTSimpleVectorIndex.load_from_disk(f"{staticPath}/index/{index_name}.json")
# predictor cost
llm_predictor = MockLLMPredictor(max_tokens=256)
embed_model = MockEmbedding(embed_dim=1536)
service_context = ServiceContext.from_defaults(
llm_predictor=llm_predictor, embed_model=embed_model
)
# 不支持 streaming,所以需要另外执行
index.query(query_text, service_context=service_context)
res = index.query(query_text, streaming=True)
cost = embed_model.last_token_usage + llm_predictor.last_token_usage
sources = [
{"extraInfo": x.node.extra_info, "text": x.node.text} for x in res.source_nodes
]
def response_generator():
yield json.dumps({"cost": cost, "sources": sources})
yield "\n ###endjson### \n\n"
for text in res.response_gen:
yield text
# 用完了就删掉,防止key被反复使用
if open_ai_key:
os.environ["OPENAI_API_KEY"] = ""
return Response(stream_with_context(response_generator()))
@app.route("/api/upload", methods=["POST"])
def upload_file():
filepath = None
try:
open_ai_key = request.form["openAiKey"]
if open_ai_key:
os.environ["OPENAI_API_KEY"] = open_ai_key
uploaded_file = request.files["file"]
filename = uploaded_file.filename
print(os.getcwd(), os.path.abspath(__file__))
filepath = os.path.join(f"{staticPath}/temp", os.path.basename(filename))
uploaded_file.save(filepath)
token_usage = create_index(filepath, filename)
except Exception as e:
logger.error(e, exc_info=True)
# cleanup temp file
print(e, "upload error")
if filepath is not None and os.path.exists(filepath):
os.remove(filepath)
# 用完了就删掉,防止key被反复使用
if open_ai_key:
os.environ["OPENAI_API_KEY"] = ""
return "Error: {}".format(str(e)), 500
# cleanup temp file
if filepath is not None and os.path.exists(filepath):
os.remove(filepath)
# 用完了就删掉,防止key被反复使用
if open_ai_key:
os.environ["OPENAI_API_KEY"] = ""
return jsonify(token_usage), 200
@app.route("/api/index-list", methods=["GET"])
def get_index_files():
dir = f"{staticPath}/index"
files = os.listdir(dir)
return files
@app.route("/api/file-list", methods=["GET"])
def get_html_files():
dir = f"{staticPath}/file"
files = os.listdir(dir)
file_list = [
{
"path": f"/{dir}/{file}",
"name": os.path.splitext(file)[0],
"ext": os.path.splitext(file)[1],
"fullName": file,
}
for file in files
]
return sorted(file_list, key=lambda x: x["name"].lower())
if __name__ == "__main__":
app.run()
================================================
FILE: server/create_index.py
================================================
import os
import markdown
from custom_loader import CustomReader
from llama_index import GPTSimpleVectorIndex, MockEmbedding, ServiceContext
from pdf_loader import CJKPDFReader
staticPath = "static"
def create_index(filepath, filename) -> int:
name, ext = os.path.splitext(filename)
if ext == ".pdf":
loader = CJKPDFReader()
documents = loader.load_data(filepath=filepath, filename=filename)
elif ext == ".md":
with open(filepath, "r", encoding="utf-8") as f:
file_text = f.read()
html = markdown.markdown(
file_text, extensions=["pymdownx.superfences", "tables", "pymdownx.details"]
)
# TODO: 利用 langchain splitter重写 https://python.langchain.com/en/latest/modules/indexes/text_splitters/examples/markdown.html
# 直接将markdown分段再分别转化成html,最后将所有html拼接起来并加上chunk_id
loader = CustomReader()
documents = loader.load_data(html=html, filename=name)
elif ext == ".html":
# TODO:
pass
# predictor cost
embed_model = MockEmbedding(embed_dim=1536)
service_context = ServiceContext.from_defaults(embed_model=embed_model)
index = GPTSimpleVectorIndex.from_documents(
documents, service_context=service_context
)
index = GPTSimpleVectorIndex.from_documents(documents)
# save to disk
index.save_to_disk(f"{staticPath}/index/{name}.json")
return embed_model.last_token_usage
================================================
FILE: server/custom_loader.py
================================================
from typing import Any, List
import tiktoken
from bs4 import BeautifulSoup
from llama_index.readers.base import BaseReader
from llama_index.readers.schema.base import Document
staticPath = "static"
def encode_string(string: str, encoding_name: str = "p50k_base"):
encoding = tiktoken.get_encoding(encoding_name)
return encoding.encode(string)
def decode_string(token: str, encoding_name: str = "p50k_base"):
encoding = tiktoken.get_encoding(encoding_name)
return encoding.decode(token)
def num_tokens_from_string(string: str, encoding_name: str = "p50k_base") -> int:
"""Returns the number of tokens in a text string."""
encoding = tiktoken.get_encoding(encoding_name)
num_tokens = len(encoding.encode(string))
return num_tokens
def split_text_to_doc(
text: str, current_chunk_id, chunk_size: int = 400
) -> List[Document]:
"""Split text into chunks of a given size."""
chunks = []
token_len = num_tokens_from_string(text)
for i in range(0, token_len, chunk_size):
encode_text = encode_string(text)
decode_text = decode_string(encode_text[i : i + chunk_size]).strip()
chunks.append(
Document(
decode_text,
extra_info={"chunk_id": f"chunk-{current_chunk_id}"},
)
)
return chunks
class CustomReader(BaseReader):
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Init params."""
super().__init__(*args, **kwargs)
def load_data(self, html, filename) -> List[Document]:
soup = BeautifulSoup(html, "html.parser")
current_chunk_text = ""
current_chunk_id = 1
document_list = []
# 单位是token,openai限制4097,如果实现连续对话大概可以进行6轮对话
current_chunk_length = 0
chunk_size = 400
# 只处理前三级标题,其他的按照段落处理
headings = ["h1", "h2", "h3"]
heading_doms = soup.find_all(headings)
if len(heading_doms) == 0:
heading_doms = [soup.find()]
for tag in heading_doms:
tag["data-chunk_id"] = f"chunk-{current_chunk_id}"
current_chunk_text = tag.text.strip()
# 遍历所有兄弟节点,不递归遍历子节点
next_tag = tag.find_next_sibling()
while next_tag and next_tag.name not in headings:
stripped_text = next_tag.text.strip()
if (
current_chunk_length + num_tokens_from_string(stripped_text)
> chunk_size
):
document_list.append(
Document(
current_chunk_text.strip(),
extra_info={"chunk_id": f"chunk-{current_chunk_id}"},
)
)
current_chunk_text = ""
current_chunk_length = 0
current_chunk_id += 1
document_list += split_text_to_doc(stripped_text, current_chunk_id)
else:
current_chunk_text = f"{current_chunk_text} {stripped_text}"
current_chunk_length += num_tokens_from_string(stripped_text) + 1
next_tag["data-chunk_id"] = f"chunk-{current_chunk_id}"
next_tag = next_tag.find_next_sibling()
document_list.append(
Document(
current_chunk_text.strip(),
extra_info={"chunk_id": f"chunk-{current_chunk_id}"},
)
)
current_chunk_text = ""
current_chunk_length = 0
current_chunk_id += 1
# 保存修改后的HTML文件
with open(f"{staticPath}/file/{filename}.html", "w", encoding="utf-8") as f:
f.write(str(soup))
return document_list
================================================
FILE: server/pdf_loader.py
================================================
"""Read PDF files."""
import shutil
from pathlib import Path
from typing import Any, List
from llama_index.langchain_helpers.text_splitter import SentenceSplitter
from llama_index.readers.base import BaseReader
from llama_index.readers.schema.base import Document
# https://github.com/emptycrown/llama-hub/blob/main/loader_hub/file/cjk_pdf/base.py
staticPath = "static"
class CJKPDFReader(BaseReader):
"""CJK PDF reader.
Extract text from PDF including CJK (Chinese, Japanese and Korean) languages using pdfminer.six.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Init params."""
super().__init__(*args, **kwargs)
def load_data(self, filepath: Path, filename) -> List[Document]:
"""Parse file."""
# Import pdfminer
from io import StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager
from pdfminer.pdfpage import PDFPage
# Create a resource manager
rsrcmgr = PDFResourceManager()
# Create an object to store the text
retstr = StringIO()
# Create a text converter
codec = "utf-8"
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
# Create a PDF interpreter
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Open the PDF file
fp = open(filepath, "rb")
# Create a list to store the text of each page
document_list = []
# Extract text from each page
for i, page in enumerate(PDFPage.get_pages(fp)):
interpreter.process_page(page)
# Get the text
text = retstr.getvalue()
sentence_splitter = SentenceSplitter(chunk_size=400)
text_chunks = sentence_splitter.split_text(text)
document_list += [
Document(t, extra_info={"page_no": i + 1}) for t in text_chunks
]
# Clear the text
retstr.truncate(0)
retstr.seek(0)
# Close the file
fp.close()
# Close the device
device.close()
shutil.copy2(filepath, f"{staticPath}/file/{filename}")
return document_list
================================================
FILE: server/requirements.txt
================================================
aiohttp==3.8.4
aiosignal==1.3.1
anyio==3.6.2
argilla==1.5.1
async-timeout==4.0.2
attrs==22.2.0
backoff==2.2.1
beautifulsoup4==4.12.0
blinker==1.6.2
bs4==0.0.1
cachetools==5.3.0
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.1.0
click==8.1.3
colorama==0.4.6
commonmark==0.9.1
cryptography==40.0.2
dataclasses-json==0.5.7
Deprecated==1.2.13
et-xmlfile==1.1.0
Flask==2.3.2
Flask-Cors==3.0.10
frozenlist==1.3.3
geojson==2.5.0
gptcache==0.1.21
greenlet==2.0.2
gunicorn==20.1.0
h11==0.14.0
httpcore==0.16.3
httpx==0.23.3
idna==3.4
importlib-metadata==6.1.0
itsdangerous==2.1.2
Jinja2==3.1.2
joblib==1.2.0
langchain==0.0.142
llama-index==0.5.27
lxml==4.9.2
Markdown==3.4.3
MarkupSafe==2.1.2
marshmallow==3.19.0
marshmallow-enum==1.5.1
monotonic==1.6
msg-parser==1.2.0
multidict==6.0.4
mypy-extensions==1.0.0
nltk==3.8.1
numexpr==2.8.4
numpy==1.23.5
olefile==0.46
openai==0.27.2
openapi-schema-pydantic==1.2.4
openpyxl==3.1.2
packaging==23.0
pandas==1.5.3
pdfminer.six==20221105
Pillow==9.4.0
pycparser==2.21
pydantic==1.10.7
Pygments==2.14.0
pymdown-extensions==9.10
pyowm==3.3.0
pypandoc==1.11
PySocks==1.7.1
python-dateutil==2.8.2
python-docx==0.8.11
python-dotenv==1.0.0
python-magic==0.4.27
python-pptx==0.6.21
pytz==2023.3
PyYAML==6.0
regex==2023.3.23
requests==2.28.2
rfc3986==1.5.0
rich==13.0.1
six==1.16.0
sniffio==1.3.0
soupsieve==2.4
SQLAlchemy==1.4.47
tenacity==8.2.2
tiktoken==0.3.3
tqdm==4.65.0
typing-inspect==0.8.0
typing_extensions==4.5.0
unstructured==0.5.8
urllib3==1.26.15
Werkzeug==2.3.3
wrapt==1.14.1
XlsxWriter==3.0.9
yarl==1.8.2
zipp==3.15.0
================================================
FILE: server/static/file/AA-README.html
================================================
<h1 data-chunk_id="chunk-1">DocsMind</h1>
<p data-chunk_id="chunk-1">DocsMind is an open-source project that allows you to chat with your docs.</p>
<p data-chunk_id="chunk-1"><img alt="Stack" src="https://skillicons.dev/icons?i=vite,react,ts,tailwind,flask"/></p>
<h2 data-chunk_id="chunk-2">Demo</h2>
<p data-chunk_id="chunk-2"><a href="https://docs-mind.alanwang.site/">Demo Site</a></p>
<blockquote data-chunk_id="chunk-2">
<p><strong>Warning</strong></p>
<p>Due to the free plan of Railway only providing 500 hours per month, the Demo on the 21st day of each month will not be available. Please clone it locally for use at that time.</p>
</blockquote>
<h2 data-chunk_id="chunk-3">Features</h2>
<ul data-chunk_id="chunk-3">
<li>🤖 Ask a question with your docs</li>
<li>📝 Summarize docs</li>
<li>🖍️ Highlight source</li>
<li>📤 Upload docs .pdf,.md(best support)</li>
<li>💾 Data saved locally</li>
<li>💰 Token usage tracker</li>
<li>🐳 Dockerize</li>
</ul>
<h2 data-chunk_id="chunk-4">Future Development</h2>
<ul data-chunk_id="chunk-4">
<li>[ ] Chat mode</li>
<li>[ ] Dark mode</li>
<li>[ ] / command (/fetch /summarize)</li>
<li>[ ] Reduce the size of the server image.</li>
<li>[ ] Support for more docs formats: txt...</li>
<li>[ ] Download docs from the internet</li>
<li>[ ] Markdown-formatted message</li>
<li>[ ] i18n</li>
<li>[ ] Desktop application</li>
</ul>
<p data-chunk_id="chunk-4">If you find this project helpful, please consider giving it a star 🌟</p>
<h2 data-chunk_id="chunk-5">Environment Variables</h2>
<table data-chunk_id="chunk-5">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Optional</th>
</tr>
</thead>
<tbody>
<tr>
<td>OPENAI_PROXY</td>
<td>will replace https://api.openai.com/v1</td>
<td>✅</td>
</tr>
<tr>
<td>VITE_SERVICES_URL</td>
<td>backend url for frontend code</td>
<td>✅</td>
</tr>
<tr>
<td>VITE_DISABLED_UPLOAD</td>
<td>DISABLED_UPLOAD</td>
<td>✅</td>
</tr>
</tbody>
</table>
<h2 data-chunk_id="chunk-6">Q&A</h2>
<p data-chunk_id="chunk-6">This project includes both front-end (/client) and back-end (/server) code. The front-end code is used to display the UI, while the back-end code provides services to the UI.</p>
<h3 data-chunk_id="chunk-7">How to deploy?</h3>
<p data-chunk_id="chunk-7">You need to deploy this project using Docker Compose.</p>
<h3 data-chunk_id="chunk-8">Can I deploy on Vercel?</h3>
<p data-chunk_id="chunk-8">No, Vercel is a serverless platform where you can only deploy your UI code (/client).</p>
<h3 data-chunk_id="chunk-9">How to run?</h3>
<blockquote data-chunk_id="chunk-9">
<p><strong>Warning</strong></p>
<p>Please check if you can access OpenAI in your region, you can refer to the <a href="https://github.com/3Alan/DocsMind/issues/3#issuecomment-1511470063">issue</a> for more information.</p>
</blockquote>
<ol data-chunk_id="chunk-9">
<li>Create .env</li>
</ol>
<p data-chunk_id="chunk-9">Create a <code>.env</code> file and copy the contents of <code>.env.example</code> to modify it.</p>
<ol data-chunk_id="chunk-9">
<li>Run App</li>
</ol>
<div class="highlight" data-chunk_id="chunk-9"><pre><span></span><code>docker-compose<span class="w"> </span>up<span class="w"> </span>-d
</code></pre></div>
<p data-chunk_id="chunk-9">Please add <code>--build</code> to rebuild the image after each code update.</p>
<div class="highlight" data-chunk_id="chunk-9"><pre><span></span><code>docker-compose<span class="w"> </span>up<span class="w"> </span>-d<span class="w"> </span>--build
</code></pre></div>
<p data-chunk_id="chunk-9">now you can access the app at <code>http://localhost:8081</code></p>
<h3 data-chunk_id="chunk-10">Local Development</h3>
<details data-chunk_id="chunk-10">
<summary>Detail</summary>
#### Create .env
Create a `.env` file and copy the contents of `.env.example` to modify it.
#### Run Frontend UI
1. Install dependencies
<div class="highlight"><pre><span></span><code>yarn
</code></pre></div>
2. Run app
<div class="highlight"><pre><span></span><code>yarn dev
</code></pre></div>
#### Run Backend Services
you need a python environment
1. Create virtual environment
<div class="highlight"><pre><span></span><code>cd server
python -m venv .venv
</code></pre></div>
2. Active virtual environment
windows
<div class="highlight"><pre><span></span><code>.venv\Scripts\activate
</code></pre></div>
mac
<div class="highlight"><pre><span></span><code>. .venv/bin/activate
</code></pre></div>
3. Install dependencies
<div class="highlight"><pre><span></span><code>pip install -r requirements.txt
</code></pre></div>
4. Run Services
<div class="highlight"><pre><span></span><code>flask run --reload --port=8080
</code></pre></div>
</details>
<h2 data-chunk_id="chunk-11">License</h2>
<p data-chunk_id="chunk-11"><a href="https://github.com/3Alan/DocsMind/blob/main/LICENSE">AGPL-3.0 License</a></p>
<h2 data-chunk_id="chunk-12">Buy me a coffee</h2>
<details data-chunk_id="chunk-12">
<summary>QR code</summary>
<img height="300" src="https://raw.githubusercontent.com/3Alan/images/master/img/%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98%E5%AE%9D%E4%BA%8C%E5%90%88%E4%B8%80%E6%94%B6%E6%AC%BE%E7%A0%81.jpg"/>
</details>
================================================
FILE: server/static/file/TypeScript入门学习总结.html
================================================
<p>TypeScript 常用知识点总结</p>
<blockquote>
<p><a href="https://typescript.bootcss.com/basic-types.html">TypeScript 中文手册</a></p>
<p><a href="https://coding.imooc.com/class/412.html">TypeScript-系统入门到项目实战</a></p>
</blockquote>
<!-- truncate -->
<h2 data-chunk_id="chunk-1">什么是 TypeScript</h2>
<p data-chunk_id="chunk-1">TypeScript 是 JavaScript 的一个超集,在 JavaScript 的基础上增加了可选的<strong>静态类型</strong>和基于类的面向对象编程。它可以编译成纯 JavaScript,未编译的 ts 代码无法在浏览器执行。我们可以把它和 JavaScript 的关系理解成 css 和 less、sass 的关系。</p>
<h2 data-chunk_id="chunk-2">TypeScript 好在哪里</h2>
<ul data-chunk_id="chunk-2">
<li>TS 可以进行动态类型检测,可以检测出一些潜在的 bug(例如拼写错误、参数缺失、undefined 等),提升代码健壮性</li>
<li>使用 vscode 进行开发可以很好的提示代码,提高开发效率</li>
<li>代码可读性好</li>
</ul>
<h2 data-chunk_id="chunk-3">创建第一个 TypeScript 文件</h2>
<p data-chunk_id="chunk-3">首先安装 TypeScript</p>
<div class="highlight" data-chunk_id="chunk-3"><pre><span></span><code>npm install -g typescript
</code></pre></div>
<p data-chunk_id="chunk-3">安装后看是否成功</p>
<div class="highlight" data-chunk_id="chunk-3"><pre><span></span><code>tsc --version
</code></pre></div>
<p data-chunk_id="chunk-3">我安装后出现了以下问题:
<img alt="image-20200614175730166" src="https://raw.githubusercontent.com/3Alan/images/master/img/image-20200614175730166.png"/>
这种情况只需要以管理员的身份打开命令行运行以下命令:</p>
<div class="highlight" data-chunk_id="chunk-3"><pre><span></span><code>set-ExecutionPolicy RemoteSigned
</code></pre></div>
<p data-chunk_id="chunk-3">创建第一个 ts 文件<code>Hello.ts</code></p>
<div class="highlight" data-chunk_id="chunk-3"><pre><span></span><code>function sayHello(name: String) {
console.log(`Hello ${name}`);
}
let person = 'Alan';
sayHello(person);
</code></pre></div>
<p data-chunk_id="chunk-3">我们发现 ts 代码和普通的 js 代码在 <code>sayHello</code> 函数的参数上有所不同。
<code>sayHello(name: String)</code>
大致的意思就是 <code>sayHello</code> 传入一个名为 name 的参数,该参数的类型必须是 <code>String</code> ,不然无法通过 ts 的编译。
代码写好后用 tsc 编译上面的 <code>Hello.ts</code> 文件</p>
<div class="highlight" data-chunk_id="chunk-3"><pre><span></span><code>tsc Hello.ts
</code></pre></div>
<p data-chunk_id="chunk-4">编译成功后在同级目录下生成一个 <code>Hello.js</code> 文件,可以看到生成的 js 文件只是将 es6 语法转化成了 es5 语法,并没有改变其他代码。</p>
<div class="highlight" data-chunk_id="chunk-4"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">sayHello</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">'Hello '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">name</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">var</span><span class="w"> </span><span class="nx">person</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">'Alan'</span><span class="p">;</span>
<span class="nx">sayHello</span><span class="p">(</span><span class="nx">person</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-4">如果把<code>Hello.ts</code>文件改写一下</p>
<div class="highlight" data-chunk_id="chunk-4"><pre><span></span><code>function sayHello(name: String) {
const text = 3 + name;
console.log(`Hello ${name}`);
}
let person = 123;
sayHello(person);
</code></pre></div>
<p data-chunk_id="chunk-4">再次编译发现会报错但是仍然能生成 js 文件:
<img alt="image-20200614180440953" src="https://raw.githubusercontent.com/3Alan/images/master/img/image-20200614180440953.png"/></p>
<p data-chunk_id="chunk-4">上面错误的具体意思是</p>
<ul data-chunk_id="chunk-4">
<li>由于声明了函数形参 <code>name</code> 为静态类型 <code>string</code> ,而在调用时传入得是 <code>number</code> 类型 <code>123</code> ,与前面的 <code>string</code> 不符。</li>
<li>在 <code>sayHello</code> 函数中将 <code>name(string)</code> 和 <code>3(number)</code> 两种不同类型得值进行了相加。</li>
</ul>
<p data-chunk_id="chunk-5">我们发现每次都要通过 tsc 来编译 ts 文件能得到 js 文件后再去运行 js 文件,过于麻烦。可以使用插件 <code>ts-node</code> 来直接运行 ts 文件。</p>
<div class="highlight" data-chunk_id="chunk-5"><pre><span></span><code>npm i ts-node -g
</code></pre></div>
<div class="highlight" data-chunk_id="chunk-5"><pre><span></span><code>ts-node Hello.ts
</code></pre></div>
<p data-chunk_id="chunk-5">:::info</p>
<p data-chunk_id="chunk-5">ts 能够尝试分析变量类型(类型推断),ts 无法分析出的变量最好显式声明变量类型(类型注解)</p>
<p data-chunk_id="chunk-5">:::</p>
<h2 data-chunk_id="chunk-6">基础类型</h2>
<p data-chunk_id="chunk-6">变量的声明:<code>let [变量名] : [类型] = 值</code></p>
<p data-chunk_id="chunk-6">例如: <code>let age: number = 21</code></p>
<p data-chunk_id="chunk-6">TypeScript 支持与 JavaScript 几乎相同的数据类型</p>
<ul data-chunk_id="chunk-6">
<li>boolean(布尔值)</li>
<li>number(数值)</li>
<li>string(字符串)</li>
<li>[]/Array<元素类型>(数组)</li>
<li>元组 Tuple</li>
<li>enum(枚举)</li>
<li>any(任何值)</li>
<li>void(空值)</li>
<li>null</li>
<li>undefined</li>
<li>never</li>
</ul>
<h2 data-chunk_id="chunk-7">数组</h2>
<p data-chunk_id="chunk-7">有 2 种方式定义数组</p>
<div class="highlight" data-chunk_id="chunk-7"><pre><span></span><code>let arr: number[] = [1, 2, 3]; // 元素类型后接上`[]`
let arr: Array<number> = [1, 2, 3]; // 数组泛型
let arr: (number | string)[] = [1, '2', '4']; // 元素类型可以是number或string(类似元组)
</code></pre></div>
<h2 data-chunk_id="chunk-8">元组 tuple</h2>
<p data-chunk_id="chunk-8">表示一个数组(各个元素的类型不必相同)</p>
<div class="highlight" data-chunk_id="chunk-8"><pre><span></span><code>let list: [string, number]; //第一个元素为string类型,第二个为number类型
a = ['abc', 123]; //合格
b = [123, 'abc']; //不合格
</code></pre></div>
<h2 data-chunk_id="chunk-9">枚举</h2>
<p data-chunk_id="chunk-9">其实有点类似对象
看例子吧</p>
<div class="highlight" data-chunk_id="chunk-10"><pre><span></span><code>enum lan {js, ts, css};
console.log(lan.js); // 0 js对应的下标,第一个默认下标为0
enum lan {
js = 3,
ts,
css,
}
console.log(lan.js); // 3
console.log(lan.ts); // 4
console.log(lan.css); // 5
enum lan {
js,
ts = 3,
css,
}
console.log(lan.js); // 0
console.log(lan.ts); // 3
console.log(lan.css); // 4
console.log(lan[4]); // css
console.log(lan[1]); // undefined
// 第一个默认下标为0,css接着ts的值+1
enum lan {js = 'good', ts = 'nice', css = 'well'};
console.log(lan.js); // good
// const枚举,为了避免在额外生成的代码上的开销和额外的非直接的对枚举成员的访问。
const enum People {
name: 'Alan',
age: 23
}
// 编译时会自动转化成常量值,不会保留其他代码
console.log(People.name); // Alan
</code></pre></div>
<h2 data-chunk_id="chunk-11">any</h2>
<p data-chunk_id="chunk-11">顾名思义,任意值,当我们想为还不清楚类型的变量指定一个类型时, <code>any</code> 就是最好的选择 🤭</p>
<div class="highlight" data-chunk_id="chunk-11"><pre><span></span><code>let a: any = 4;
a = '123'; //合格
let arr: any[] = [1, '123', true]; // 和元组很像
arr[1] = 'good';
</code></pre></div>
<h2 data-chunk_id="chunk-12">void</h2>
<p data-chunk_id="chunk-12">常用于无返回值的函数声明</p>
<div class="highlight" data-chunk_id="chunk-12"><pre><span></span><code>function func(): void {
console.log('learning typescript...');
}
func(); //合格
function func(): void {
return 1;
}
func(); // 不合格:Type '1' is not assignable to type 'void'
</code></pre></div>
<h2 data-chunk_id="chunk-13">null 和 undefined</h2>
<p data-chunk_id="chunk-13">用处不大,默认情况下是所有类型的子类型,例如下面代码是没有问题的:</p>
<div class="highlight" data-chunk_id="chunk-13"><pre><span></span><code>let a: string;
a = undefined;
a = null;
</code></pre></div>
<p data-chunk_id="chunk-13"><strong>但是</strong>,当指定<code>--strictNullChecks</code>标记时,null 和 undefined 只能赋值给 void 和他们自己本身。</p>
<h2 data-chunk_id="chunk-14">never</h2>
<p data-chunk_id="chunk-14">表示永不存在的值的类型
never 类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型;
变量也可能是 never 类型,当它们被永不为真的类型保护所约束时。</p>
<p data-chunk_id="chunk-14">never 类型是任何类型的子类型,也可以赋值给任何类型;然而,没有类型是 never 的子类型或可以赋值给 never 类型(除了 never 本身之外)。 即使 any 也不可以赋值给 never。</p>
<div class="highlight" data-chunk_id="chunk-15"><pre><span></span><code>function error(message: string): never {
throw new Error(message);
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {}
}
</code></pre></div>
<h2 data-chunk_id="chunk-16">结构赋值的写法</h2>
<div class="highlight" data-chunk_id="chunk-16"><pre><span></span><code>function sayAge({ name, age }: { name: string | number; age: number }): void {
console.log(`${name} is ${age} years old`);
}
sayAge({ name: 'Alan', age: 22 });
sayAge({ name: 2, age: 22 });
</code></pre></div>
<h2 data-chunk_id="chunk-17">联合类型</h2>
<p data-chunk_id="chunk-17">用 <code>|</code> 来表示取值存在多种可能</p>
<div class="highlight" data-chunk_id="chunk-17"><pre><span></span><code>let a: string | number;
a = 1;
a = 'A';
</code></pre></div>
<h2 data-chunk_id="chunk-18">类型断言</h2>
<p data-chunk_id="chunk-18">可以自己指定一个值的类型
格式如下
<code><类型>值</code>
<code>值 as 类型</code></p>
<div class="highlight" data-chunk_id="chunk-18"><pre><span></span><code>interface student {
isStudent: boolean;
education: number;
}
interface worker {
isStudent: boolean;
seniority: number;
}
function Recruit(candidate: worker | student): void {
if (candidate.isStudent) {
console.log(`your education is ${(candidate as student).education}`);
} else {
console.log(`your seniority is ${(candidate as worker).seniority}`);
}
}
const a: student = { isStudent: true, education: 4 };
const b: worker = { isStudent: false, seniority: 2 };
Recruit(a);
Recruit(b);
</code></pre></div>
<p data-chunk_id="chunk-18">由于 <code>candidate</code> 使用了联合类型,所以 ts 无法判断 <code>candidate</code> 究竟是属于 <code>student</code> 还是 <code>worker</code> ,所以要使用类型断言来显式告诉 ts。</p>
<p data-chunk_id="chunk-18">当然还有其他方式来实现</p>
<div class="highlight" data-chunk_id="chunk-19"><pre><span></span><code>interface student {
isStudent: boolean;
education: number;
}
interface worker {
isStudent: boolean;
seniority: number;
}
function Recruit(candidate: worker | student): void {
'education' in candidate && console.log(`your education is ${candidate.education}`);
'seniority' in candidate && console.log(`your seniority is ${candidate.seniority}`);
}
const a: student = { isStudent: true, education: 4 };
const b: worker = { isStudent: false, seniority: 2 };
Recruit(a);
Recruit(b);
</code></pre></div>
<ul data-chunk_id="chunk-19">
<li>typeof</li>
<li>instanceof</li>
</ul>
<h2 data-chunk_id="chunk-20">非空断言</h2>
<p data-chunk_id="chunk-20"><code>!.</code> 对应 <code>--strictNullChecks</code></p>
<div class="highlight" data-chunk_id="chunk-20"><pre><span></span><code><span class="kd">interface</span><span class="w"> </span><span class="nx">person</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="kt">string</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">work</span><span class="p">(</span><span class="nx">personObj?</span><span class="o">:</span><span class="w"> </span><span class="kt">person</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// 由于 personObj 可能不传,所以 personObj 可能为 undefined,使用 !. 可以断言 personObj 不为空</span>
<span class="w"> </span><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">personObj</span><span class="o">!</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<h2 data-chunk_id="chunk-21">接口 interface</h2>
<p data-chunk_id="chunk-21">先看一个接口的例子</p>
<div class="highlight" data-chunk_id="chunk-21"><pre><span></span><code>interface person {
name: string;
}
function work(personObj: person) {
console.log(personObj.name);
}
let person1 = { name: 'Alan', age: 21 };
work(person1);
let person2 = { age: 21 };
work(person2);
</code></pre></div>
<p data-chunk_id="chunk-21"><img alt="image-20200615180720618" src="https://raw.githubusercontent.com/3Alan/images/master/img/image-20200615180720618.png"/></p>
<p data-chunk_id="chunk-21">定义接口的关键字是 <code>interface</code>
这个例子需要传入 work 的参数必须是一个带有 name(string)的对象,可以理解为我要招聘一个有名字的员工,没有名字的都不需要。当然我们的 person1 中还多了一个<code>age</code>属性,这并不会报错。可是当我们直接传递参数时是会出错的。</p>
<div class="highlight" data-chunk_id="chunk-21"><pre><span></span><code><span class="nx">work</span><span class="p">({</span><span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Alan'</span><span class="p">,</span><span class="w"> </span><span class="nx">age</span><span class="o">:</span><span class="w"> </span><span class="mf">21</span><span class="w"> </span><span class="p">});</span>
</code></pre></div>
<p data-chunk_id="chunk-22">那如果我不确定要招聘的员工除了有姓名外还需要其他什么属性时,可以像下面一样重新定义接口就可以解决上面的问题了。</p>
<div class="highlight" data-chunk_id="chunk-22"><pre><span></span><code>interface person {
name: string;
[propName: string]: any;
}
</code></pre></div>
<h3 data-chunk_id="chunk-23">可选属性</h3>
<p data-chunk_id="chunk-23">那如果我的招聘条件是最好懂 typescript 的,这个时候 typescript 就是可有可无的(最好懂,嘿嘿 😜),那我们就要用到<strong>可选属性</strong>了
<code>可选属性</code>在可选属性名后面加上一个<code>?</code></p>
<div class="highlight" data-chunk_id="chunk-23"><pre><span></span><code>interface person {
name: string;
ts?: boolean;
}
function Recruit(personObj: person): string {
if (personObj.ts) {
return `congratulations!${personObj.name}`;
} else {
return `sorry,${personObj.name}, we need a employee who know ts!`;
}
}
let person1 = { name: 'Alan', age: 21, ts: true };
console.log(Recruit(person1));
let person2 = { name: 'Bob', age: 21 };
console.log(Recruit(person2));
</code></pre></div>
<h3 data-chunk_id="chunk-24">只读属性</h3>
<p data-chunk_id="chunk-24">我们都知道人的名字都是不可以改变的(一般情况下),这个时候我们对 person 接口里面的 name 属性稍作修改,在属性名 name 前加上<code>readonly</code>。</p>
<p data-chunk_id="chunk-24">:::tip</p>
<p data-chunk_id="chunk-24">当然也可以使用 setter/getter 来实现</p>
<p data-chunk_id="chunk-24">:::</p>
<div class="highlight" data-chunk_id="chunk-24"><pre><span></span><code>interface person {
readonly name: string;
ts?: boolean;
}
let person1: person = { name: 'Alan' };
person1.name = 'Bob'; // Cannot assign to 'name' because it is a read-only property.
</code></pre></div>
<p data-chunk_id="chunk-24"><strong>我们发现 readonly 和 const 的作用好像有点相似,那我们什么时候使用 readonly 什么时候使用 const 呢?</strong>
变量---->const
属性---->readonly</p>
<h3 data-chunk_id="chunk-25">函数类型的接口</h3>
<p data-chunk_id="chunk-25">接口除了可以描述带有属性的对象外,还可以描述函数类型
这里创建一个函数来检查你有没有打卡 😁</p>
<div class="highlight" data-chunk_id="chunk-25"><pre><span></span><code>interface attendanceFunc {
(name: string, startTime: number, endTime: number): boolean;
}
let checkAttendance: attendanceFunc;
checkAttendance = function (name: string, startTime: number, endTime: number): boolean {
let result = startTime < 9 && endTime > 18;
return result;
};
console.log(checkAttendance('Alan', 10, 19)); // false
</code></pre></div>
<p data-chunk_id="chunk-25">看一下接口的声明:</p>
<div class="highlight" data-chunk_id="chunk-25"><pre><span></span><code>interface attendanceFunc {
(name: string, startTime: number, endTime: number): boolean;
}
</code></pre></div>
<p data-chunk_id="chunk-26"><code>name,startTime,endTime</code> 放在 <code>()</code> 中代表函数的参数
<code>:boolean</code> 表示函数的返回值类型
当然上面例子中的<code>checkAttendance</code>的形参以及函数的返回值来说可以不指定类型,因为 <code>checkAttendance</code> 复制给了 <code>attendanceFunc</code> 变量,类型检查器会自动(按照接口中参数的顺序)推断出参数以及返回值的类型,也就是说写成下面这样也是可以的。<strong>函数中的参数名可以不和接口中的相同</strong></p>
<div class="highlight" data-chunk_id="chunk-26"><pre><span></span><code>interface attendanceFunc {
(name: string, startTime: number, endTime: number): boolean;
}
let checkAttendance: attendanceFunc;
checkAttendance = function (n, startTime, endTime) {
let result = startTime < 9 && endTime > 18;
return result;
};
console.log(checkAttendance('Alan', 10, 19)); // false
</code></pre></div>
<h3 data-chunk_id="chunk-27">接口的继承</h3>
<p data-chunk_id="chunk-27">一个接口可以继承 1 个或者多个接口:
继承使用关键词<code>extends</code></p>
<div class="highlight" data-chunk_id="chunk-27"><pre><span></span><code>interface person {
name: string;
}
interface student {
studentId: number;
}
interface seniorStudent extends person, student {
grade: string;
}
let student1: seniorStudent = { name: 'Alan', studentId: 1, grade: 'one' };
console.log(student1);
</code></pre></div>
<h2 data-chunk_id="chunk-28">类 class</h2>
<p data-chunk_id="chunk-28">TS 中的类和 ES6 中的类很相似,这里只介绍不同的地方</p>
<h3 data-chunk_id="chunk-29">变量修饰符</h3>
<ul data-chunk_id="chunk-29">
<li>public(默认)</li>
<li>private(私有,不能在声明它的类的外部访问)</li>
<li>protected(和 private 类似,不同的是 protected 声明的变量可以在派生类(即子类)中访问)</li>
</ul>
<h3 data-chunk_id="chunk-30">静态属性 static</h3>
<div class="highlight" data-chunk_id="chunk-30"><pre><span></span><code>class Person {
static fingerNum = 5;
}
// 只能通过类来访问
console.log(Person.fingerNum);
// 不能通过实例访问
console.log(new Person().fingerNum);
</code></pre></div>
<div class="highlight" data-chunk_id="chunk-30"><pre><span></span><code>// 单例模式创建唯一的实例
class singleClass {
private static instance: singleClass;
private constructor(public name: string) {}
static getInstance() {
if (!this.instance) {
this.instance = new singleClass('Alan');
}
return this.instance;
}
}
const class1 = singleClass.getInstance();
const class2 = singleClass.getInstance();
console.log(class1.name); // Alan
console.log(class1 === class2); // true
</code></pre></div>
<h3 data-chunk_id="chunk-31">构造函数</h3>
<div class="highlight" data-chunk_id="chunk-31"><pre><span></span><code>class Person {
constructor(name, mobile, sex) {
this.name = name;
this.mobile = mobile;
this.sex = sex;
}
public name: string;
private mobile: string;
protected sex: string;
}
</code></pre></div>
<p data-chunk_id="chunk-31">上面的代码可以简写成下面这样</p>
<div class="highlight" data-chunk_id="chunk-31"><pre><span></span><code>class Person {
constructor(name: string, private mobile: string, protected sex: string) {}
}
</code></pre></div>
<h3 data-chunk_id="chunk-32">抽象类</h3>
<ul data-chunk_id="chunk-32">
<li>不能被实例化</li>
<li>要使用的话要声明其派生类,并且重写其中的抽象方法</li>
</ul>
<div class="highlight" data-chunk_id="chunk-32"><pre><span></span><code>abstract class Animal {
constructor(public name: string) {}
sayHello() {
console.log('hello');
}
// 声明抽象方法
abstract action(): void;
}
class Bird extends Animal {
constructor(name) {
super(name);
}
action() {
console.log('jijiji');
}
}
const bird = new Bird('qc');
console.log(bird);
// Bird { name: 'qc' }
</code></pre></div>
<h2 data-chunk_id="chunk-33">泛型</h2>
<blockquote data-chunk_id="chunk-33">
<p>泛型(Generics)是指在定义函数、接口或类的时候,<strong>不预先指定</strong>具体的类型,而在<strong>使用的时候</strong>再指定类型的一种特性。</p>
</blockquote>
<h3 data-chunk_id="chunk-34">函数用法:<泛型名></h3>
<div class="highlight" data-chunk_id="chunk-34"><pre><span></span><code>function Recruit<T>(name: string, props: T) {
return name + props;
}
// 显式指定为T为number类型
console.log(Recruit<number>('Alan', 123)); // Alan123
// TS自动推断为number类型,和上面效果一样
console.log(Recruit('Alan', 123)); // Alan123
console.log(Recruit('Alan', [1, 2, 3])); // Alan1,2,3
</code></pre></div>
<p data-chunk_id="chunk-34">也可以使用多个泛型名,下面的例子结合了接口来完成</p>
<div class="highlight" data-chunk_id="chunk-34"><pre><span></span><code>interface Contact {
mobile: string;
}
interface Address {
province: string;
}
function Recruit<C extends Contact, A extends Address>(name: string, contact: C, address: A) {
return `${name}'s mobile is ${contact.mobile}, live in ${address.province}`;
}
console.log(Recruit('Alan', { mobile: '666' }, { province: 'Shanghai' }));
// Alan's mobile is 666, live in Shanghai
</code></pre></div>
<h3 data-chunk_id="chunk-35">类用法</h3>
<div class="highlight" data-chunk_id="chunk-35"><pre><span></span><code>interface employee {
name: string;
age: number;
}
class RecruitManager<T extends employee> {
constructor(private data: Array<T>) {}
select(age: number): T {
return this.data.find((item) => item.age > age);
}
}
const result = new RecruitManager([
{
name: 'Alan',
age: 22
},
{
name: 'Bob',
age: 18
}
]);
console.log(result.select(20));
</code></pre></div>
<h3 data-chunk_id="chunk-36">泛型约束</h3>
<p data-chunk_id="chunk-36">使用 extends 约束泛型</p>
<div class="highlight" data-chunk_id="chunk-36"><pre><span></span><code>interface info {
mobile: string;
}
// T泛型必须满足info
function Recruit<T extends info>(name: string, props: T) {
return name + props.mobile;
}
console.log(Recruit('Alan', { mobile: '1232910830' })); // Alan1232910830
</code></pre></div>
<h2 data-chunk_id="chunk-37">React 相关</h2>
<h3 data-chunk_id="chunk-38">class 组件动态设置 state</h3>
<div class="highlight" data-chunk_id="chunk-38"><pre><span></span><code><span class="k">this</span><span class="p">.</span><span class="nx">setState</span><span class="p">({</span>
<span class="w"> </span><span class="p">[</span><span class="nx">name</span><span class="p">]</span><span class="o">:</span><span class="w"> </span><span class="nx">value</span>
<span class="p">}</span><span class="w"> </span><span class="kr">as</span><span class="w"> </span><span class="nx">Pick</span><span class="o"><</span><span class="nx">CompontentState</span><span class="p">,</span><span class="w"> </span><span class="nx">keyof</span><span class="w"> </span><span class="nx">CompontentState</span><span class="o">></span><span class="p">);</span>
</code></pre></div>
================================================
FILE: server/static/file/clean-code-javascript.html
================================================
<h1 data-chunk_id="chunk-1">clean-code-javascript</h1>
<h2 data-chunk_id="chunk-2">Table of Contents</h2>
<ol data-chunk_id="chunk-2">
<li><a href="#introduction">Introduction</a></li>
<li><a href="#variables">Variables</a></li>
<li><a href="#functions">Functions</a></li>
<li><a href="#objects-and-data-structures">Objects and Data Structures</a></li>
<li><a href="#classes">Classes</a></li>
<li><a href="#solid">SOLID</a></li>
<li><a href="#testing">Testing</a></li>
<li><a href="#concurrency">Concurrency</a></li>
<li><a href="#error-handling">Error Handling</a></li>
<li><a href="#formatting">Formatting</a></li>
<li><a href="#comments">Comments</a></li>
<li><a href="#translation">Translation</a></li>
</ol>
<h2 data-chunk_id="chunk-3">Introduction</h2>
<p data-chunk_id="chunk-3"><img alt="Humorous image of software quality estimation as a count of how many expletives
you shout when reading code" src="https://www.osnews.com/images/comics/wtfm.jpg"/></p>
<p data-chunk_id="chunk-3">Software engineering principles, from Robert C. Martin's book
<a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"><em>Clean Code</em></a>,
adapted for JavaScript. This is not a style guide. It's a guide to producing
<a href="https://github.com/ryanmcdermott/3rs-of-software-architecture">readable, reusable, and refactorable</a> software in JavaScript.</p>
<p data-chunk_id="chunk-3">Not every principle herein has to be strictly followed, and even fewer will be
universally agreed upon. These are guidelines and nothing more, but they are
ones codified over many years of collective experience by the authors of
<em>Clean Code</em>.</p>
<p data-chunk_id="chunk-3">Our craft of software engineering is just a bit over 50 years old, and we are
still learning a lot. When software architecture is as old as architecture
itself, maybe then we will have harder rules to follow. For now, let these
guidelines serve as a touchstone by which to assess the quality of the
JavaScript code that you and your team produce.</p>
<p data-chunk_id="chunk-3">One more thing: knowing these won't immediately make you a better software
developer, and working with them for many years doesn't mean you won't make
mistakes. Every piece of code starts as a first draft, like wet clay getting
shaped into its final form. Finally, we chisel away the imperfections when
we review it with our peers. Don't beat yourself up for first drafts that need
improvement. Beat up the code instead!</p>
<h2 data-chunk_id="chunk-4"><strong>Variables</strong></h2>
<h3 data-chunk_id="chunk-5">Use meaningful and pronounceable variable names</h3>
<p data-chunk_id="chunk-5"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-5"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">yyyymmdstr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">moment</span><span class="p">().</span><span class="nx">format</span><span class="p">(</span><span class="s1">'YYYY/MM/DD'</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-5"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-5"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">currentDate</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">moment</span><span class="p">().</span><span class="nx">format</span><span class="p">(</span><span class="s1">'YYYY/MM/DD'</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-5"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-6">Use the same vocabulary for the same type of variable</h3>
<p data-chunk_id="chunk-6"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-6"><pre><span></span><code><span class="nx">getUserInfo</span><span class="p">();</span>
<span class="nx">getClientData</span><span class="p">();</span>
<span class="nx">getCustomerRecord</span><span class="p">();</span>
</code></pre></div>
<p data-chunk_id="chunk-6"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-6"><pre><span></span><code><span class="nx">getUser</span><span class="p">();</span>
</code></pre></div>
<p data-chunk_id="chunk-6"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-7">Use searchable names</h3>
<p data-chunk_id="chunk-7">We will read more code than we will ever write. It's important that the code we
do write is readable and searchable. By <em>not</em> naming variables that end up
being meaningful for understanding our program, we hurt our readers.
Make your names searchable. Tools like
<a href="https://github.com/danielstjules/buddy.js">buddy.js</a> and
<a href="https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md">ESLint</a>
can help identify unnamed constants.</p>
<p data-chunk_id="chunk-7"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-7"><pre><span></span><code><span class="c1">// What the heck is 86400000 for?</span>
<span class="nx">setTimeout</span><span class="p">(</span><span class="nx">blastOff</span><span class="p">,</span><span class="w"> </span><span class="mf">86400000</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-7"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-7"><pre><span></span><code><span class="c1">// Declare them as capitalized named constants.</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">MILLISECONDS_PER_DAY</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">60</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mf">60</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mf">24</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mf">1000</span><span class="p">;</span><span class="w"> </span><span class="c1">//86400000;</span>
<span class="nx">setTimeout</span><span class="p">(</span><span class="nx">blastOff</span><span class="p">,</span><span class="w"> </span><span class="nx">MILLISECONDS_PER_DAY</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-7"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-8">Use explanatory variables</h3>
<p data-chunk_id="chunk-8"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-8"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">address</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">'One Infinite Loop, Cupertino 95014'</span><span class="p">;</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">cityZipCodeRegex</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sr">/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/</span><span class="p">;</span>
<span class="nx">saveCityZipCode</span><span class="p">(</span><span class="nx">address</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="nx">cityZipCodeRegex</span><span class="p">)[</span><span class="mf">1</span><span class="p">],</span><span class="w"> </span><span class="nx">address</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="nx">cityZipCodeRegex</span><span class="p">)[</span><span class="mf">2</span><span class="p">]);</span>
</code></pre></div>
<p data-chunk_id="chunk-8"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-8"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">address</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">'One Infinite Loop, Cupertino 95014'</span><span class="p">;</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">cityZipCodeRegex</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sr">/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/</span><span class="p">;</span>
<span class="kd">const</span><span class="w"> </span><span class="p">[</span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">city</span><span class="p">,</span><span class="w"> </span><span class="nx">zipCode</span><span class="p">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">address</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="nx">cityZipCodeRegex</span><span class="p">)</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="p">[];</span>
<span class="nx">saveCityZipCode</span><span class="p">(</span><span class="nx">city</span><span class="p">,</span><span class="w"> </span><span class="nx">zipCode</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-8"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-9">Avoid Mental Mapping</h3>
<p data-chunk_id="chunk-9">Explicit is better than implicit.</p>
<p data-chunk_id="chunk-9"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-9"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">locations</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="s1">'Austin'</span><span class="p">,</span><span class="w"> </span><span class="s1">'New York'</span><span class="p">,</span><span class="w"> </span><span class="s1">'San Francisco'</span><span class="p">];</span>
<span class="nx">locations</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">l</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">doStuff</span><span class="p">();</span>
<span class="w"> </span><span class="nx">doSomeOtherStuff</span><span class="p">();</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="c1">// Wait, what is `l` for again?</span>
<span class="w"> </span><span class="nx">dispatch</span><span class="p">(</span><span class="nx">l</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div>
<p data-chunk_id="chunk-9"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-9"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">locations</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="s1">'Austin'</span><span class="p">,</span><span class="w"> </span><span class="s1">'New York'</span><span class="p">,</span><span class="w"> </span><span class="s1">'San Francisco'</span><span class="p">];</span>
<span class="nx">locations</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">location</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">doStuff</span><span class="p">();</span>
<span class="w"> </span><span class="nx">doSomeOtherStuff</span><span class="p">();</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="nx">dispatch</span><span class="p">(</span><span class="nx">location</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div>
<p data-chunk_id="chunk-9"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-10">Don't add unneeded context</h3>
<p data-chunk_id="chunk-10">If your class/object name tells you something, don't repeat that in your
variable name.</p>
<p data-chunk_id="chunk-10"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-10"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">Car</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">carMake</span><span class="o">:</span><span class="w"> </span><span class="s1">'Honda'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">carModel</span><span class="o">:</span><span class="w"> </span><span class="s1">'Accord'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">carColor</span><span class="o">:</span><span class="w"> </span><span class="s1">'Blue'</span>
<span class="p">};</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">paintCar</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span><span class="w"> </span><span class="nx">color</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">car</span><span class="p">.</span><span class="nx">carColor</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">color</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-10"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-10"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">Car</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">make</span><span class="o">:</span><span class="w"> </span><span class="s1">'Honda'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">model</span><span class="o">:</span><span class="w"> </span><span class="s1">'Accord'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">color</span><span class="o">:</span><span class="w"> </span><span class="s1">'Blue'</span>
<span class="p">};</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">paintCar</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span><span class="w"> </span><span class="nx">color</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">car</span><span class="p">.</span><span class="nx">color</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">color</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-10"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-11">Use default parameters instead of short circuiting or conditionals</h3>
<p data-chunk_id="chunk-11">Default parameters are often cleaner than short circuiting. Be aware that if you
use them, your function will only provide default values for <code>undefined</code>
arguments. Other "falsy" values such as <code>''</code>, <code>""</code>, <code>false</code>, <code>null</code>, <code>0</code>, and
<code>NaN</code>, will not be replaced by a default value.</p>
<p data-chunk_id="chunk-11"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-11"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">createMicrobrewery</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">breweryName</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">name</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="s1">'Hipster Brew Co.'</span><span class="p">;</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-11"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-11"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">createMicrobrewery</span><span class="p">(</span><span class="nx">name</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">'Hipster Brew Co.'</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-11"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h2 data-chunk_id="chunk-12"><strong>Functions</strong></h2>
<h3 data-chunk_id="chunk-13">Function arguments (2 or fewer ideally)</h3>
<p data-chunk_id="chunk-13">Limiting the amount of function parameters is incredibly important because it
makes testing your function easier. Having more than three leads to a
combinatorial explosion where you have to test tons of different cases with
each separate argument.</p>
<p data-chunk_id="chunk-13">One or two arguments is the ideal case, and three should be avoided if possible.
Anything more than that should be consolidated. Usually, if you have
more than two arguments then your function is trying to do too much. In cases
where it's not, most of the time a higher-level object will suffice as an
argument.</p>
<p data-chunk_id="chunk-13">Since JavaScript allows you to make objects on the fly, without a lot of class
boilerplate, you can use an object if you are finding yourself needing a
lot of arguments.</p>
<p data-chunk_id="chunk-13">To make it obvious what properties the function expects, you can use the ES2015/ES6
destructuring syntax. This has a few advantages:</p>
<ol data-chunk_id="chunk-13">
<li>When someone looks at the function signature, it's immediately clear what
properties are being used.</li>
<li>It can be used to simulate named parameters.</li>
<li>Destructuring also clones the specified primitive values of the argument
object passed into the function. This can help prevent side effects. Note:
objects and arrays that are destructured from the argument object are NOT
cloned.</li>
<li>Linters can warn you about unused properties, which would be impossible
without destructuring.</li>
</ol>
<p data-chunk_id="chunk-13"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-13"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">createMenu</span><span class="p">(</span><span class="nx">title</span><span class="p">,</span><span class="w"> </span><span class="nx">body</span><span class="p">,</span><span class="w"> </span><span class="nx">buttonText</span><span class="p">,</span><span class="w"> </span><span class="nx">cancellable</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
<span class="nx">createMenu</span><span class="p">(</span><span class="s1">'Foo'</span><span class="p">,</span><span class="w"> </span><span class="s1">'Bar'</span><span class="p">,</span><span class="w"> </span><span class="s1">'Baz'</span><span class="p">,</span><span class="w"> </span><span class="kc">true</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-13"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-13"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">createMenu</span><span class="p">({</span><span class="w"> </span><span class="nx">title</span><span class="p">,</span><span class="w"> </span><span class="nx">body</span><span class="p">,</span><span class="w"> </span><span class="nx">buttonText</span><span class="p">,</span><span class="w"> </span><span class="nx">cancellable</span><span class="w"> </span><span class="p">})</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
<span class="nx">createMenu</span><span class="p">({</span>
<span class="w"> </span><span class="nx">title</span><span class="o">:</span><span class="w"> </span><span class="s1">'Foo'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">body</span><span class="o">:</span><span class="w"> </span><span class="s1">'Bar'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">buttonText</span><span class="o">:</span><span class="w"> </span><span class="s1">'Baz'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">cancellable</span><span class="o">:</span><span class="w"> </span><span class="kc">true</span>
<span class="p">});</span>
</code></pre></div>
<p data-chunk_id="chunk-13"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-14">Functions should do one thing</h3>
<p data-chunk_id="chunk-14">This is by far the most important rule in software engineering. When functions
do more than one thing, they are harder to compose, test, and reason about.
When you can isolate a function to just one action, it can be refactored
easily and your code will read much cleaner. If you take nothing else away from
this guide other than this, you'll be ahead of many developers.</p>
<p data-chunk_id="chunk-14"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-14"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">emailClients</span><span class="p">(</span><span class="nx">clients</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">clients</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">client</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">clientRecord</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">database</span><span class="p">.</span><span class="nx">lookup</span><span class="p">(</span><span class="nx">client</span><span class="p">);</span>
<span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="nx">clientRecord</span><span class="p">.</span><span class="nx">isActive</span><span class="p">())</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">email</span><span class="p">(</span><span class="nx">client</span><span class="p">);</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="p">});</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-14"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-14"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">emailActiveClients</span><span class="p">(</span><span class="nx">clients</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">clients</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="nx">isActiveClient</span><span class="p">).</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">email</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">isActiveClient</span><span class="p">(</span><span class="nx">client</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">clientRecord</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">database</span><span class="p">.</span><span class="nx">lookup</span><span class="p">(</span><span class="nx">client</span><span class="p">);</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">clientRecord</span><span class="p">.</span><span class="nx">isActive</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-14"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-15">Function names should say what they do</h3>
<p data-chunk_id="chunk-15"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-15"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">addToDate</span><span class="p">(</span><span class="nx">date</span><span class="p">,</span><span class="w"> </span><span class="nx">month</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">date</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="ow">new</span><span class="w"> </span><span class="nb">Date</span><span class="p">();</span>
<span class="c1">// It's hard to tell from the function name what is added</span>
<span class="nx">addToDate</span><span class="p">(</span><span class="nx">date</span><span class="p">,</span><span class="w"> </span><span class="mf">1</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-15"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-15"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">addMonthToDate</span><span class="p">(</span><span class="nx">month</span><span class="p">,</span><span class="w"> </span><span class="nx">date</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">date</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="ow">new</span><span class="w"> </span><span class="nb">Date</span><span class="p">();</span>
<span class="nx">addMonthToDate</span><span class="p">(</span><span class="mf">1</span><span class="p">,</span><span class="w"> </span><span class="nx">date</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-15"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-16">Functions should only be one level of abstraction</h3>
<p data-chunk_id="chunk-16">When you have more than one level of abstraction your function is usually
doing too much. Splitting up functions leads to reusability and easier
testing.</p>
<p data-chunk_id="chunk-16"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-16"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">parseBetterJSAlternative</span><span class="p">(</span><span class="nx">code</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">REGEXES</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="p">];</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">statements</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">code</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">' '</span><span class="p">);</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">tokens</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[];</span>
<span class="w"> </span><span class="nx">REGEXES</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">REGEX</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">statements</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">statement</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">ast</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[];</span>
<span class="w"> </span><span class="nx">tokens</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">token</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// lex...</span>
<span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="nx">ast</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">node</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// parse...</span>
<span class="w"> </span><span class="p">});</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-16"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-16"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">parseBetterJSAlternative</span><span class="p">(</span><span class="nx">code</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">tokens</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">tokenize</span><span class="p">(</span><span class="nx">code</span><span class="p">);</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">syntaxTree</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">parse</span><span class="p">(</span><span class="nx">tokens</span><span class="p">);</span>
<span class="w"> </span><span class="nx">syntaxTree</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">node</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// parse...</span>
<span class="w"> </span><span class="p">});</span>
<span class="p">}</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">tokenize</span><span class="p">(</span><span class="nx">code</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">REGEXES</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="p">];</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">statements</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">code</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">' '</span><span class="p">);</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">tokens</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[];</span>
<span class="w"> </span><span class="nx">REGEXES</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">REGEX</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">statements</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">statement</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">tokens</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="cm">/* ... */</span><span class="p">);</span>
<span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">tokens</span><span class="p">;</span>
<span class="p">}</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">parse</span><span class="p">(</span><span class="nx">tokens</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">syntaxTree</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[];</span>
<span class="w"> </span><span class="nx">tokens</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">token</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">syntaxTree</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="cm">/* ... */</span><span class="p">);</span>
<span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">syntaxTree</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-16"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-17">Remove duplicate code</h3>
<p data-chunk_id="chunk-17">Do your absolute best to avoid duplicate code. Duplicate code is bad because it
means that there's more than one place to alter something if you need to change
some logic.</p>
<p data-chunk_id="chunk-17">Imagine if you run a restaurant and you keep track of your inventory: all your
tomatoes, onions, garlic, spices, etc. If you have multiple lists that
you keep this on, then all have to be updated when you serve a dish with
tomatoes in them. If you only have one list, there's only one place to update!</p>
<p data-chunk_id="chunk-17">Oftentimes you have duplicate code because you have two or more slightly
different things, that share a lot in common, but their differences force you
to have two or more separate functions that do much of the same things. Removing
duplicate code means creating an abstraction that can handle this set of
different things with just one function/module/class.</p>
<p data-chunk_id="chunk-17">Getting the abstraction right is critical, that's why you should follow the
SOLID principles laid out in the <em>Classes</em> section. Bad abstractions can be
worse than duplicate code, so be careful! Having said this, if you can make
a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself
updating multiple places anytime you want to change one thing.</p>
<p data-chunk_id="chunk-17"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-18"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">showDeveloperList</span><span class="p">(</span><span class="nx">developers</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">developers</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">developer</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">expectedSalary</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">developer</span><span class="p">.</span><span class="nx">calculateExpectedSalary</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">experience</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">developer</span><span class="p">.</span><span class="nx">getExperience</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">githubLink</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">developer</span><span class="p">.</span><span class="nx">getGithubLink</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">expectedSalary</span><span class="p">,</span>
<span class="w"> </span><span class="nx">experience</span><span class="p">,</span>
<span class="w"> </span><span class="nx">githubLink</span>
<span class="w"> </span><span class="p">};</span>
<span class="w"> </span><span class="nx">render</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
<span class="w"> </span><span class="p">});</span>
<span class="p">}</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">showManagerList</span><span class="p">(</span><span class="nx">managers</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">managers</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">manager</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">expectedSalary</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">manager</span><span class="p">.</span><span class="nx">calculateExpectedSalary</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">experience</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">manager</span><span class="p">.</span><span class="nx">getExperience</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">portfolio</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">manager</span><span class="p">.</span><span class="nx">getMBAProjects</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">expectedSalary</span><span class="p">,</span>
<span class="w"> </span><span class="nx">experience</span><span class="p">,</span>
<span class="w"> </span><span class="nx">portfolio</span>
<span class="w"> </span><span class="p">};</span>
<span class="w"> </span><span class="nx">render</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
<span class="w"> </span><span class="p">});</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-18"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-18"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">showEmployeeList</span><span class="p">(</span><span class="nx">employees</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">employees</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">employee</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">expectedSalary</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">employee</span><span class="p">.</span><span class="nx">calculateExpectedSalary</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">experience</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">employee</span><span class="p">.</span><span class="nx">getExperience</span><span class="p">();</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">expectedSalary</span><span class="p">,</span>
<span class="w"> </span><span class="nx">experience</span>
<span class="w"> </span><span class="p">};</span>
<span class="w"> </span><span class="k">switch</span><span class="w"> </span><span class="p">(</span><span class="nx">employee</span><span class="p">.</span><span class="nx">type</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">case</span><span class="w"> </span><span class="s1">'manager'</span><span class="o">:</span>
<span class="w"> </span><span class="nx">data</span><span class="p">.</span><span class="nx">portfolio</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">employee</span><span class="p">.</span><span class="nx">getMBAProjects</span><span class="p">();</span>
<span class="w"> </span><span class="k">break</span><span class="p">;</span>
<span class="w"> </span><span class="k">case</span><span class="w"> </span><span class="s1">'developer'</span><span class="o">:</span>
<span class="w"> </span><span class="nx">data</span><span class="p">.</span><span class="nx">githubLink</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">employee</span><span class="p">.</span><span class="nx">getGithubLink</span><span class="p">();</span>
<span class="w"> </span><span class="k">break</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="nx">render</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
<span class="w"> </span><span class="p">});</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-18"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-19">Set default objects with Object.assign</h3>
<p data-chunk_id="chunk-19"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-19"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">menuConfig</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">title</span><span class="o">:</span><span class="w"> </span><span class="kc">null</span><span class="p">,</span>
<span class="w"> </span><span class="nx">body</span><span class="o">:</span><span class="w"> </span><span class="s1">'Bar'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">buttonText</span><span class="o">:</span><span class="w"> </span><span class="kc">null</span><span class="p">,</span>
<span class="w"> </span><span class="nx">cancellable</span><span class="o">:</span><span class="w"> </span><span class="kc">true</span>
<span class="p">};</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">createMenu</span><span class="p">(</span><span class="nx">config</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">title</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">title</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="s1">'Foo'</span><span class="p">;</span>
<span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">body</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">body</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="s1">'Bar'</span><span class="p">;</span>
<span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">buttonText</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">buttonText</span><span class="w"> </span><span class="o">||</span><span class="w"> </span><span class="s1">'Baz'</span><span class="p">;</span>
<span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">cancellable</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">cancellable</span><span class="w"> </span><span class="o">!==</span><span class="w"> </span><span class="kc">undefined</span><span class="w"> </span><span class="o">?</span><span class="w"> </span><span class="nx">config</span><span class="p">.</span><span class="nx">cancellable</span><span class="w"> </span><span class="o">:</span><span class="w"> </span><span class="kc">true</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">createMenu</span><span class="p">(</span><span class="nx">menuConfig</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-19"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-19"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">menuConfig</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">title</span><span class="o">:</span><span class="w"> </span><span class="s1">'Order'</span><span class="p">,</span>
<span class="w"> </span><span class="c1">// User did not include 'body' key</span>
<span class="w"> </span><span class="nx">buttonText</span><span class="o">:</span><span class="w"> </span><span class="s1">'Send'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">cancellable</span><span class="o">:</span><span class="w"> </span><span class="kc">true</span>
<span class="p">};</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">createMenu</span><span class="p">(</span><span class="nx">config</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="nx">finalConfig</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">Object</span><span class="p">.</span><span class="nx">assign</span><span class="p">(</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">title</span><span class="o">:</span><span class="w"> </span><span class="s1">'Foo'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">body</span><span class="o">:</span><span class="w"> </span><span class="s1">'Bar'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">buttonText</span><span class="o">:</span><span class="w"> </span><span class="s1">'Baz'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">cancellable</span><span class="o">:</span><span class="w"> </span><span class="kc">true</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="nx">config</span>
<span class="w"> </span><span class="p">);</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">finalConfig</span><span class="p">;</span>
<span class="w"> </span><span class="c1">// config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="p">}</span>
<span class="nx">createMenu</span><span class="p">(</span><span class="nx">menuConfig</span><span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-19"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-20">Don't use flags as function parameters</h3>
<p data-chunk_id="chunk-20">Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.</p>
<p data-chunk_id="chunk-20"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-20"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">createFile</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span><span class="w"> </span><span class="nx">temp</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="nx">temp</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">fs</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="sb">`./temp/</span><span class="si">${</span><span class="nx">name</span><span class="si">}</span><span class="sb">`</span><span class="p">);</span>
<span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">fs</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">name</span><span class="p">);</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-20"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-20"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">createFile</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">fs</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">name</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">createTempFile</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">createFile</span><span class="p">(</span><span class="sb">`./temp/</span><span class="si">${</span><span class="nx">name</span><span class="si">}</span><span class="sb">`</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-20"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-21">Avoid Side Effects (part 1)</h3>
<p data-chunk_id="chunk-21">A function produces a side effect if it does anything other than take a value in
and return another value or values. A side effect could be writing to a file,
modifying some global variable, or accidentally wiring all your money to a
stranger.</p>
<p data-chunk_id="chunk-21">Now, you do need to have side effects in a program on occasion. Like the previous
example, you might need to write to a file. What you want to do is to
centralize where you are doing this. Don't have several functions and classes
that write to a particular file. Have one service that does it. One and only one.</p>
<p data-chunk_id="chunk-21">The main point is to avoid common pitfalls like sharing state between objects
without any structure, using mutable data types that can be written to by anything,
and not centralizing where your side effects occur. If you can do this, you will
be happier than the vast majority of other programmers.</p>
<p data-chunk_id="chunk-21"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-21"><pre><span></span><code><span class="c1">// Global variable referenced by following function.</span>
<span class="c1">// If we had another function that used this name, now it'd be an array and it could break it.</span>
<span class="kd">let</span><span class="w"> </span><span class="nx">name</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">'Ryan McDermott'</span><span class="p">;</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">splitIntoFirstAndLastName</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">name</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">' '</span><span class="p">);</span>
<span class="p">}</span>
<span class="nx">splitIntoFirstAndLastName</span><span class="p">();</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">name</span><span class="p">);</span><span class="w"> </span><span class="c1">// ['Ryan', 'McDermott'];</span>
</code></pre></div>
<p data-chunk_id="chunk-21"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-21"><pre><span></span><code><span class="kd">function</span><span class="w"> </span><span class="nx">splitIntoFirstAndLastName</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">name</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">' '</span><span class="p">);</span>
<span class="p">}</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">name</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s1">'Ryan McDermott'</span><span class="p">;</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">newName</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">splitIntoFirstAndLastName</span><span class="p">(</span><span class="nx">name</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">name</span><span class="p">);</span><span class="w"> </span><span class="c1">// 'Ryan McDermott';</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">newName</span><span class="p">);</span><span class="w"> </span><span class="c1">// ['Ryan', 'McDermott'];</span>
</code></pre></div>
<p data-chunk_id="chunk-21"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-22">Avoid Side Effects (part 2)</h3>
<p data-chunk_id="chunk-22">In JavaScript, some values are unchangeable (immutable) and some are changeable
(mutable). Objects and arrays are two kinds of mutable values so it's important
to handle them carefully when they're passed as parameters to a function. A
JavaScript function can change an object's properties or alter the contents of
an array which could easily cause bugs elsewhere.</p>
<p data-chunk_id="chunk-22">Suppose there's a function that accepts an array parameter representing a
shopping cart. If the function makes a change in that shopping cart array -
by adding an item to purchase, for example - then any other function that
uses that same <code>cart</code> array will be affected by this addition. That may be
great, however it could also be bad. Let's imagine a bad situation:</p>
<p data-chunk_id="chunk-22">The user clicks the "Purchase" button which calls a <code>purchase</code> function that
spawns a network request and sends the <code>cart</code> array to the server. Because
of a bad network connection, the <code>purchase</code> function has to keep retrying the
request. Now, what if in the meantime the user accidentally clicks an "Add to Cart"
button on an item they don't actually want before the network request begins?
If that happens and the network request begins, then that purchase function
will send the accidentally added item because the <code>cart</code> array was modified.</p>
<p data-chunk_id="chunk-22">A great solution would be for the <code>addItemToCart</code> function to always clone the
<code>cart</code>, edit it, and return the clone. This would ensure that functions that are still
using the old shopping cart wouldn't be affected by the changes.</p>
<p data-chunk_id="chunk-22">Two caveats to mention to this approach:</p>
<ol data-chunk_id="chunk-23">
<li>
<p>There might be cases where you actually want to modify the input object,
but when you adopt this programming practice you will find that those cases
are pretty rare. Most things can be refactored to have no side effects!</p>
</li>
<li>
<p>Cloning big objects can be very expensive in terms of performance. Luckily,
this isn't a big issue in practice because there are
<a href="https://facebook.github.io/immutable-js/">great libraries</a> that allow
this kind of programming approach to be fast and not as memory intensive as
it would be for you to manually clone objects and arrays.</p>
</li>
</ol>
<p data-chunk_id="chunk-23"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-23"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">addItemToCart</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="nx">cart</span><span class="p">,</span><span class="w"> </span><span class="nx">item</span><span class="p">)</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">cart</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span><span class="w"> </span><span class="nx">item</span><span class="p">,</span><span class="w"> </span><span class="nx">date</span><span class="o">:</span><span class="w"> </span><span class="nb">Date</span><span class="p">.</span><span class="nx">now</span><span class="p">()</span><span class="w"> </span><span class="p">});</span>
<span class="p">};</span>
</code></pre></div>
<p data-chunk_id="chunk-23"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-23"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">addItemToCart</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="nx">cart</span><span class="p">,</span><span class="w"> </span><span class="nx">item</span><span class="p">)</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">[...</span><span class="nx">cart</span><span class="p">,</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nx">item</span><span class="p">,</span><span class="w"> </span><span class="nx">date</span><span class="o">:</span><span class="w"> </span><span class="nb">Date</span><span class="p">.</span><span class="nx">now</span><span class="p">()</span><span class="w"> </span><span class="p">}];</span>
<span class="p">};</span>
</code></pre></div>
<p data-chunk_id="chunk-23"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-24">Don't write to global functions</h3>
<p data-chunk_id="chunk-24">Polluting globals is a bad practice in JavaScript because you could clash with another
library and the user of your API would be none-the-wiser until they get an
exception in production. Let's think about an example: what if you wanted to
extend JavaScript's native Array method to have a <code>diff</code> method that could
show the difference between two arrays? You could write your new function
to the <code>Array.prototype</code>, but it could clash with another library that tried
to do the same thing. What if that other library was just using <code>diff</code> to find
the difference between the first and last elements of an array? This is why it
would be much better to just use ES2015/ES6 classes and simply extend the <code>Array</code> global.</p>
<p data-chunk_id="chunk-24"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-24"><pre><span></span><code><span class="nb">Array</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">diff</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="w"> </span><span class="nx">diff</span><span class="p">(</span><span class="nx">comparisonArray</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">hash</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="ow">new</span><span class="w"> </span><span class="nb">Set</span><span class="p">(</span><span class="nx">comparisonArray</span><span class="p">);</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="k">this</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="nx">elem</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="o">!</span><span class="nx">hash</span><span class="p">.</span><span class="nx">has</span><span class="p">(</span><span class="nx">elem</span><span class="p">));</span>
<span class="p">};</span>
</code></pre></div>
<p data-chunk_id="chunk-24"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-24"><pre><span></span><code><span class="kd">class</span><span class="w"> </span><span class="nx">SuperArray</span><span class="w"> </span><span class="k">extends</span><span class="w"> </span><span class="nb">Array</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">diff</span><span class="p">(</span><span class="nx">comparisonArray</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">const</span><span class="w"> </span><span class="nx">hash</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="ow">new</span><span class="w"> </span><span class="nb">Set</span><span class="p">(</span><span class="nx">comparisonArray</span><span class="p">);</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="k">this</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="nx">elem</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="o">!</span><span class="nx">hash</span><span class="p">.</span><span class="nx">has</span><span class="p">(</span><span class="nx">elem</span><span class="p">));</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-24"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-25">Favor functional programming over imperative programming</h3>
<p data-chunk_id="chunk-25">JavaScript isn't a functional language in the way that Haskell is, but it has
a functional flavor to it. Functional languages can be cleaner and easier to test.
Favor this style of programming when you can.</p>
<p data-chunk_id="chunk-25"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-25"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">programmerOutput</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Uncle Bobby'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">500</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Suzie Q'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">1500</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Jimmy Gosling'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">150</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Gracie Hopper'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">1000</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">];</span>
<span class="kd">let</span><span class="w"> </span><span class="nx">totalOutput</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">0</span><span class="p">;</span>
<span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kd">let</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">0</span><span class="p">;</span><span class="w"> </span><span class="nx">i</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="nx">programmerOutput</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span><span class="w"> </span><span class="nx">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">totalOutput</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="nx">programmerOutput</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">linesOfCode</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p data-chunk_id="chunk-25"><strong>Good:</strong></p>
<div class="highlight" data-chunk_id="chunk-25"><pre><span></span><code><span class="kd">const</span><span class="w"> </span><span class="nx">programmerOutput</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Uncle Bobby'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">500</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Suzie Q'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">1500</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Jimmy Gosling'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">150</span>
<span class="w"> </span><span class="p">},</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">name</span><span class="o">:</span><span class="w"> </span><span class="s1">'Gracie Hopper'</span><span class="p">,</span>
<span class="w"> </span><span class="nx">linesOfCode</span><span class="o">:</span><span class="w"> </span><span class="mf">1000</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">];</span>
<span class="kd">const</span><span class="w"> </span><span class="nx">totalOutput</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">programmerOutput</span><span class="p">.</span><span class="nx">reduce</span><span class="p">(</span>
<span class="w"> </span><span class="p">(</span><span class="nx">totalLines</span><span class="p">,</span><span class="w"> </span><span class="nx">output</span><span class="p">)</span><span class="w"> </span><span class="p">=></span><span class="w"> </span><span class="nx">totalLines</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">output</span><span class="p">.</span><span class="nx">linesOfCode</span><span class="p">,</span>
<span class="w"> </span><span class="mf">0</span>
<span class="p">);</span>
</code></pre></div>
<p data-chunk_id="chunk-25"><strong><a href="#table-of-contents">⬆ back to top</a></strong></p>
<h3 data-chunk_id="chunk-26">Encapsulate conditionals</h3>
<p data-chunk_id="chunk-26"><strong>Bad:</strong></p>
<div class="highlight" data-chunk_id="chunk-26"><pre><span></span><code><sp
gitextract_phhhif57/ ├── .gitattributes ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.yml │ │ └── config.yml │ └── workflows/ │ └── issue.yml ├── .gitignore ├── Deployment.md ├── LICENSE ├── README.md ├── client/ │ ├── .eslintrc.json │ ├── .prettierrc │ ├── index.html │ ├── package.json │ ├── postcss.config.cjs │ ├── src/ │ │ ├── App.tsx │ │ ├── components/ │ │ │ ├── chatWindow/ │ │ │ │ ├── Loading.tsx │ │ │ │ ├── Message.tsx │ │ │ │ ├── constants.ts │ │ │ │ └── index.tsx │ │ │ ├── fileCard/ │ │ │ │ └── index.tsx │ │ │ ├── htmlViewer/ │ │ │ │ └── index.tsx │ │ │ ├── pageSpin/ │ │ │ │ └── index.tsx │ │ │ ├── pdfViewer/ │ │ │ │ └── index.tsx │ │ │ ├── settingsModal/ │ │ │ │ └── index.tsx │ │ │ ├── sideMenu/ │ │ │ │ └── index.tsx │ │ │ └── upload/ │ │ │ └── index.tsx │ │ ├── constants/ │ │ │ └── fileItem.ts │ │ ├── context/ │ │ │ └── currentFile.ts │ │ ├── main.tsx │ │ ├── pages/ │ │ │ └── Home.tsx │ │ ├── routes.tsx │ │ ├── styles/ │ │ │ └── globals.scss │ │ ├── utils/ │ │ │ ├── eventEmitter.ts │ │ │ ├── fetch.ts │ │ │ ├── isDev.ts │ │ │ ├── isPdf.ts │ │ │ ├── request.ts │ │ │ └── useOpenAiKey.ts │ │ └── vite-env.d.ts │ ├── tailwind.config.js │ ├── tsconfig.json │ ├── tsconfig.node.json │ └── vite.config.ts ├── docker/ │ ├── Dockerfile.client │ └── Dockerfile.server ├── docker-compose.yml ├── nginx.conf ├── server/ │ ├── Procfile │ ├── app.py │ ├── create_index.py │ ├── custom_loader.py │ ├── pdf_loader.py │ ├── requirements.txt │ └── static/ │ ├── file/ │ │ ├── AA-README.html │ │ ├── TypeScript入门学习总结.html │ │ ├── clean-code-javascript.html │ │ └── heading-test.html │ ├── index/ │ │ ├── AA-README.json │ │ ├── TypeScript入门学习总结.json │ │ ├── clean-code-javascript.json │ │ ├── github-privacy.json │ │ └── heading-test.json │ └── testFiles/ │ ├── TypeScript入门学习总结.md │ ├── clean-code-javascript.md │ ├── heading-test.md │ └── no-match-heading-test.md └── vercel.json
SYMBOL INDEX (48 symbols across 22 files)
FILE: client/src/App.tsx
function getFileList (line 18) | async function getFileList() {
function handleFileClick (line 27) | function handleFileClick(item: any) {
function toggleSettingModal (line 32) | function toggleSettingModal(open: boolean) {
FILE: client/src/components/chatWindow/Loading.tsx
function Loading (line 1) | function Loading() {
FILE: client/src/components/chatWindow/Message.tsx
type MessageProps (line 11) | interface MessageProps extends PropsWithChildren {
function handleSourceClick (line 42) | function handleSourceClick(e: MouseEvent, item: any) {
function toggleShowSource (line 47) | function toggleShowSource() {
FILE: client/src/components/chatWindow/constants.ts
type MessageItem (line 3) | interface MessageItem {
FILE: client/src/components/chatWindow/index.tsx
type ChatWindowProps (line 12) | interface ChatWindowProps {
function cleanChat (line 33) | function cleanChat() {
FILE: client/src/components/fileCard/index.tsx
type FileCardProps (line 8) | interface FileCardProps {
function FileCard (line 14) | function FileCard({ item, onClick, active }: FileCardProps) {
FILE: client/src/components/htmlViewer/index.tsx
function HtmlViewer (line 4) | function HtmlViewer({ html, loading }: { html: string; loading: boolean ...
FILE: client/src/components/pageSpin/index.tsx
function PageSpin (line 3) | function PageSpin() {
FILE: client/src/components/pdfViewer/index.tsx
function PdfViewer (line 9) | function PdfViewer({ file }: { file: Blob }) {
FILE: client/src/components/settingsModal/index.tsx
type SettingsModalProps (line 5) | interface SettingsModalProps {
function SettingsModal (line 10) | function SettingsModal({ open, onChange }: SettingsModalProps) {
FILE: client/src/components/sideMenu/index.tsx
type SideMenuProps (line 7) | interface SideMenuProps {
function SideMenu (line 16) | function SideMenu({
FILE: client/src/components/upload/index.tsx
function generateConfetti (line 11) | function generateConfetti() {
function FileUpload (line 20) | function FileUpload() {
FILE: client/src/constants/fileItem.ts
type FileItem (line 1) | interface FileItem {
FILE: client/src/pages/Home.tsx
function removeHighLight (line 13) | function removeHighLight() {
function addHighLight (line 20) | function addHighLight(chunkId: string, time = 400) {
function downloadFile (line 34) | async function downloadFile(fileItem: FileItem) {
function getFile (line 58) | async function getFile() {
function handleHighLight (line 68) | function handleHighLight(item: any, time = 400) {
FILE: client/src/utils/eventEmitter.ts
type Events (line 3) | type Events = {
FILE: client/src/utils/fetch.ts
function fetchRequest (line 4) | async function fetchRequest(url: string, params: { [key: string]: any }) {
FILE: client/src/utils/isPdf.ts
function isPdf (line 1) | function isPdf(ext: string) {
FILE: client/src/utils/useOpenAiKey.ts
function useOpenAiKey (line 4) | function useOpenAiKey() {
FILE: server/app.py
function handle_error (line 55) | def handle_error(error):
function summarize_index (line 69) | def summarize_index():
function query_index (line 130) | def query_index():
function upload_file (line 168) | def upload_file():
function get_index_files (line 206) | def get_index_files():
function get_html_files (line 213) | def get_html_files():
FILE: server/create_index.py
function create_index (line 11) | def create_index(filepath, filename) -> int:
FILE: server/custom_loader.py
function encode_string (line 11) | def encode_string(string: str, encoding_name: str = "p50k_base"):
function decode_string (line 16) | def decode_string(token: str, encoding_name: str = "p50k_base"):
function num_tokens_from_string (line 21) | def num_tokens_from_string(string: str, encoding_name: str = "p50k_base"...
function split_text_to_doc (line 28) | def split_text_to_doc(
class CustomReader (line 48) | class CustomReader(BaseReader):
method __init__ (line 49) | def __init__(self, *args: Any, **kwargs: Any) -> None:
method load_data (line 53) | def load_data(self, html, filename) -> List[Document]:
FILE: server/pdf_loader.py
class CJKPDFReader (line 16) | class CJKPDFReader(BaseReader):
method __init__ (line 22) | def __init__(self, *args: Any, **kwargs: Any) -> None:
method load_data (line 26) | def load_data(self, filepath: Path, filename) -> List[Document]:
Condensed preview — 66 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (7,958K chars).
[
{
"path": ".gitattributes",
"chars": 43,
"preview": "server/static/** linguist-detectable=false\n"
},
{
"path": ".github/ISSUE_TEMPLATE/bug_report.yml",
"chars": 1242,
"preview": "name: 🐞 Bug Report\ndescription: Create a report to help us improve\ntitle: \"[Bug]: \"\nlabels: [\"bug\"]\nbody:\n - type: mark"
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 167,
"preview": "blank_issues_enabled: false\ncontact_links:\n - name: 🚀 New feature proposal\n url: https://github.com/3Alan/DocsMind/d"
},
{
"path": ".github/workflows/issue.yml",
"chars": 658,
"preview": "name: 'Close stale issues'\n\npermissions:\n contents: write # only for delete-branch option\n issues: write\n pull-reques"
},
{
"path": ".gitignore",
"chars": 349,
"preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndis"
},
{
"path": "Deployment.md",
"chars": 2413,
"preview": "The first thing you need to know is that this project includes frontend (UI) and backend. I strongly recommend using Doc"
},
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 3343,
"preview": "# DocsMind\n\nDocsMind is an open-source project that allows you to chat with your docs.\n\n {\n return (\n <span className=\"py-2 px-4 shadow rounded-lg mb-5 bg-blue-50\">\n "
},
{
"path": "client/src/components/chatWindow/Message.tsx",
"chars": 3303,
"preview": "import { DollarOutlined, HighlightOutlined } from '@ant-design/icons';\nimport classNames from 'classnames';\nimport { FC,"
},
{
"path": "client/src/components/chatWindow/constants.ts",
"chars": 166,
"preview": "import { ReactNode } from 'react';\n\nexport interface MessageItem {\n question?: string;\n reply?: ReactNode;\n cost?: nu"
},
{
"path": "client/src/components/chatWindow/index.tsx",
"chars": 6509,
"preview": "import { ProfileOutlined, SendOutlined, WarningTwoTone } from '@ant-design/icons';\nimport { Button, Card, Input, message"
},
{
"path": "client/src/components/fileCard/index.tsx",
"chars": 919,
"preview": "import { FilePdfTwoTone, FileTextTwoTone } from '@ant-design/icons';\nimport { Card, Space } from 'antd';\nimport classNam"
},
{
"path": "client/src/components/htmlViewer/index.tsx",
"chars": 567,
"preview": "import { useEffect, useRef } from 'react';\nimport PageSpin from '../pageSpin';\n\nexport default function HtmlViewer({ htm"
},
{
"path": "client/src/components/pageSpin/index.tsx",
"chars": 192,
"preview": "import { Spin } from 'antd';\n\nexport default function PageSpin() {\n return (\n <div className=\"w-full h-full flex jus"
},
{
"path": "client/src/components/pdfViewer/index.tsx",
"chars": 1565,
"preview": "import { Document, Page } from 'react-pdf/dist/esm/entry.vite';\nimport 'react-pdf/dist/esm/Page/TextLayer.css';\nimport '"
},
{
"path": "client/src/components/settingsModal/index.tsx",
"chars": 1317,
"preview": "import { Form, Input, Modal } from 'antd';\nimport { useEffect, useRef } from 'react';\nimport eventEmitter from '../../ut"
},
{
"path": "client/src/components/sideMenu/index.tsx",
"chars": 1884,
"preview": "import { Alert, Button, Divider, Space } from 'antd';\nimport FileItem from '../../constants/fileItem';\nimport FileCard f"
},
{
"path": "client/src/components/upload/index.tsx",
"chars": 1883,
"preview": "import { InboxOutlined } from '@ant-design/icons';\nimport { message, Spin, Upload } from 'antd';\nimport { useState } fro"
},
{
"path": "client/src/constants/fileItem.ts",
"chars": 105,
"preview": "export default interface FileItem {\n name: string;\n fullName: string;\n path: string;\n ext: string;\n}\n"
},
{
"path": "client/src/context/currentFile.ts",
"chars": 158,
"preview": "import { createContext } from 'react';\nimport FileItem from '../constants/fileItem';\n\nexport const CurrentFileContext = "
},
{
"path": "client/src/main.tsx",
"chars": 284,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport App from './App';\n\nimport { inject } from '@v"
},
{
"path": "client/src/pages/Home.tsx",
"chars": 3076,
"preview": "import { Empty } from 'antd';\nimport { useContext, useEffect, useState } from 'react';\nimport ChatWindow from '../compon"
},
{
"path": "client/src/routes.tsx",
"chars": 123,
"preview": "import Home from './pages/Home';\n\nconst routes = [\n {\n path: '/',\n element: <Home />\n }\n];\n\nexport default route"
},
{
"path": "client/src/styles/globals.scss",
"chars": 1741,
"preview": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n:root {\n font-family: Inter, Avenir, Helvetica, Arial, sans"
},
{
"path": "client/src/utils/eventEmitter.ts",
"chars": 235,
"preview": "import mitt from 'mitt';\n\ntype Events = {\n scrollToPage: { pageNo: number; time: number };\n cleanChat?: null;\n refres"
},
{
"path": "client/src/utils/fetch.ts",
"chars": 390,
"preview": "import { baseURL } from './request';\nimport queryString from 'query-string';\n\nexport default async function fetchRequest"
},
{
"path": "client/src/utils/isDev.ts",
"chars": 42,
"preview": "export const isDev = import.meta.env.DEV;\n"
},
{
"path": "client/src/utils/isPdf.ts",
"chars": 72,
"preview": "export default function isPdf(ext: string) {\n return ext === '.pdf';\n}\n"
},
{
"path": "client/src/utils/request.ts",
"chars": 412,
"preview": "import { message } from 'antd';\nimport axios from 'axios';\n\nexport const baseURL = import.meta.env.VITE_SERVICES_URL || "
},
{
"path": "client/src/utils/useOpenAiKey.ts",
"chars": 524,
"preview": "import { useEffect, useState } from 'react';\nimport eventEmitter from './eventEmitter';\n\nexport default function useOpen"
},
{
"path": "client/src/vite-env.d.ts",
"chars": 38,
"preview": "/// <reference types=\"vite/client\" />\n"
},
{
"path": "client/tailwind.config.js",
"chars": 255,
"preview": "/** @type {import('tailwindcss').Config} */\nexport default {\n content: ['./src/**/*.{js,ts,jsx,tsx}'],\n theme: {\n e"
},
{
"path": "client/tsconfig.json",
"chars": 559,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"useDefineForClassFields\": true,\n \"lib\": [\"DOM\", \"DOM.Iterable\","
},
{
"path": "client/tsconfig.node.json",
"chars": 184,
"preview": "{\n \"compilerOptions\": {\n \"composite\": true,\n \"module\": \"ESNext\",\n \"moduleResolution\": \"Node\",\n \"allowSynthe"
},
{
"path": "client/vite.config.ts",
"chars": 165,
"preview": "import { defineConfig } from 'vite';\nimport react from '@vitejs/plugin-react';\n\n// https://vitejs.dev/config/\nexport def"
},
{
"path": "docker/Dockerfile.client",
"chars": 313,
"preview": "FROM node:16-alpine as client\n\nWORKDIR /client\n\nCOPY ./client .\n\nRUN yarn install\n\nRUN yarn build\n\nRUN rm -rf node_modul"
},
{
"path": "docker/Dockerfile.server",
"chars": 234,
"preview": "FROM python:3.9-slim-buster\n\nWORKDIR /server\n\nCOPY ./server/requirements.txt requirements.txt\n\nRUN pip3 install -r requi"
},
{
"path": "docker-compose.yml",
"chars": 317,
"preview": "version: '3'\nservices:\n client:\n build:\n context: .\n dockerfile: docker/Dockerfile.client\n ports:\n "
},
{
"path": "nginx.conf",
"chars": 493,
"preview": "server {\n listen 80;\n\n location ~ /(api|static) {\n proxy_pass http://server:8080;\n proxy_set_header Host $host;\n"
},
{
"path": "server/Procfile",
"chars": 21,
"preview": "web: gunicorn app:app"
},
{
"path": "server/app.py",
"chars": 6600,
"preview": "import json\nimport logging\nimport os\nfrom pathlib import Path\n\nimport openai\nfrom create_index import create_index\nfrom "
},
{
"path": "server/create_index.py",
"chars": 1439,
"preview": "import os\n\nimport markdown\nfrom custom_loader import CustomReader\nfrom llama_index import GPTSimpleVectorIndex, MockEmbe"
},
{
"path": "server/custom_loader.py",
"chars": 3786,
"preview": "from typing import Any, List\n\nimport tiktoken\nfrom bs4 import BeautifulSoup\nfrom llama_index.readers.base import BaseRea"
},
{
"path": "server/pdf_loader.py",
"chars": 2333,
"preview": "\"\"\"Read PDF files.\"\"\"\n\nimport shutil\nfrom pathlib import Path\nfrom typing import Any, List\n\nfrom llama_index.langchain_h"
},
{
"path": "server/requirements.txt",
"chars": 1565,
"preview": "aiohttp==3.8.4\naiosignal==1.3.1\nanyio==3.6.2\nargilla==1.5.1\nasync-timeout==4.0.2\nattrs==22.2.0\nbackoff==2.2.1\nbeautifuls"
},
{
"path": "server/static/file/AA-README.html",
"chars": 5129,
"preview": "<h1 data-chunk_id=\"chunk-1\">DocsMind</h1>\n<p data-chunk_id=\"chunk-1\">DocsMind is an open-source project that allows you "
},
{
"path": "server/static/file/TypeScript入门学习总结.html",
"chars": 21309,
"preview": "<p>TypeScript 常用知识点总结</p>\n<blockquote>\n<p><a href=\"https://typescript.bootcss.com/basic-types.html\">TypeScript 中文手册</a><"
},
{
"path": "server/static/file/clean-code-javascript.html",
"chars": 235176,
"preview": "<h1 data-chunk_id=\"chunk-1\">clean-code-javascript</h1>\n<h2 data-chunk_id=\"chunk-2\">Table of Contents</h2>\n<ol data-chunk"
},
{
"path": "server/static/file/heading-test.html",
"chars": 936,
"preview": "<h1 data-chunk_id=\"chunk-1\">Test Markdown</h1>\n<p data-chunk_id=\"chunk-1\">The Test File chunk size is 10</p>\n<h2 data-ch"
},
{
"path": "server/static/index/AA-README.json",
"chars": 426213,
"preview": "{\"index_struct\": {\"__type__\": \"simple_dict\", \"__data__\": {\"index_id\": \"e83782ea-9a41-4304-9a48-5aad0f4bd610\", \"summary\":"
},
{
"path": "server/static/index/TypeScript入门学习总结.json",
"chars": 1574593,
"preview": "{\"index_struct\": {\"__type__\": \"simple_dict\", \"__data__\": {\"index_id\": \"04e28c4c-7567-46e3-8fac-74689ee9219b\", \"summary\":"
},
{
"path": "server/static/index/clean-code-javascript.json",
"chars": 2876109,
"preview": "{\"index_struct\": {\"__type__\": \"simple_dict\", \"__data__\": {\"index_id\": \"edd97cc0-8f63-489b-978d-4f0990fa2015\", \"summary\":"
},
{
"path": "server/static/index/github-privacy.json",
"chars": 2417462,
"preview": "{\"index_struct\": {\"__type__\": \"simple_dict\", \"__data__\": {\"index_id\": \"99081f4a-5d11-44ee-bc8a-71a0b130c02b\", \"summary\":"
},
{
"path": "server/static/index/heading-test.json",
"chars": 177295,
"preview": "{\"index_struct\": {\"__type__\": \"simple_dict\", \"__data__\": {\"index_id\": \"a9ec4a10-ca9d-4ced-a4a2-a1f055acbda7\", \"summary\":"
},
{
"path": "server/static/testFiles/TypeScript入门学习总结.md",
"chars": 12626,
"preview": "TypeScript 常用知识点总结\r\n\r\n> [TypeScript 中文手册](https://typescript.bootcss.com/basic-types.html)\r\n>\r\n> [TypeScript-系统入门到项目实战]("
},
{
"path": "server/static/testFiles/clean-code-javascript.md",
"chars": 58383,
"preview": "# clean-code-javascript\n\n## Table of Contents\n\n1. [Introduction](#introduction)\n2. [Variables](#variables)\n3. [Functions"
},
{
"path": "server/static/testFiles/heading-test.md",
"chars": 484,
"preview": "# Test Markdown\n\nThe Test File chunk size is 10\n\n## list\n\n- first\n- second\n- third\n\n## Table\n\n| Syntax | Description "
},
{
"path": "server/static/testFiles/no-match-heading-test.md",
"chars": 475,
"preview": "The Test File chunk size is 10\n\n#### list\n\n- first\n- second\n- third\n\n#### Table\n\n| Syntax | Description |\n| ---------"
},
{
"path": "vercel.json",
"chars": 41,
"preview": "{\n \"github\": {\n \"silent\": true\n }\n}\n"
}
]
About this extraction
This page contains the full source code of the 3Alan/DocsMind GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 66 files (7.5 MB), approximately 2.0M tokens, and a symbol index with 48 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.