ffreemt commited on
Commit
813eca2
1 Parent(s): 3bec37b

Update local files instead of git clone

Browse files
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ node_modules
Dockerfile CHANGED
@@ -1,14 +1,11 @@
1
  FROM node:18-bullseye-slim
2
- RUN apt-get update && \
3
- apt-get install -y git
4
- RUN git clone https://github.com/LLM-Red-Team/deepseek-free-api.git /app
5
  WORKDIR /app
6
  RUN chown -R 1000:1000 /app
7
  USER 1000
 
8
  RUN npm install
9
- COPY Dockerfile greeting.md* .env* ./
10
  RUN npm run build
11
  EXPOSE 7860
12
  ENV NODE_ENV=production
13
  ENV NODE_OPTIONS="--max-old-space-size=12882"
14
- CMD [ "node", "dist/index.js" ]
 
1
  FROM node:18-bullseye-slim
 
 
 
2
  WORKDIR /app
3
  RUN chown -R 1000:1000 /app
4
  USER 1000
5
+ RUN cp . .
6
  RUN npm install
 
7
  RUN npm run build
8
  EXPOSE 7860
9
  ENV NODE_ENV=production
10
  ENV NODE_OPTIONS="--max-old-space-size=12882"
11
+ CMD [ "npm", "start" ]
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
configs/dev/service.yml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # 服务名称
2
+ name: deepseek-free-api
3
+ # 服务绑定主机地址
4
+ host: '0.0.0.0'
5
+ # 服务绑定端口
6
+ port: 7860
configs/dev/system.yml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 是否开启请求日志
2
+ requestLog: true
3
+ # 临时目录路径
4
+ tmpDir: ./tmp
5
+ # 日志目录路径
6
+ logDir: ./logs
7
+ # 日志写入间隔(毫秒)
8
+ logWriteInterval: 200
9
+ # 日志文件有效期(毫秒)
10
+ logFileExpires: 2626560000
11
+ # 公共目录路径
12
+ publicDir: ./public
13
+ # 临时文件有效期(毫秒)
14
+ tmpFileExpires: 86400000
dist/index.cjs ADDED
@@ -0,0 +1,1651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // src/lib/environment.ts
26
+ var import_path = __toESM(require("path"), 1);
27
+ var import_fs_extra = __toESM(require("fs-extra"), 1);
28
+ var import_minimist = __toESM(require("minimist"), 1);
29
+ var import_lodash = __toESM(require("lodash"), 1);
30
+ var cmdArgs = (0, import_minimist.default)(process.argv.slice(2));
31
+ var envVars = process.env;
32
+ var Environment = class {
33
+ /** 命令行参数 */
34
+ cmdArgs;
35
+ /** 环境变量 */
36
+ envVars;
37
+ /** 环境名称 */
38
+ env;
39
+ /** 服务名称 */
40
+ name;
41
+ /** 服务地址 */
42
+ host;
43
+ /** 服务端口 */
44
+ port;
45
+ /** 包参数 */
46
+ package;
47
+ constructor(options = {}) {
48
+ const { cmdArgs: cmdArgs2, envVars: envVars2, package: _package } = options;
49
+ this.cmdArgs = cmdArgs2;
50
+ this.envVars = envVars2;
51
+ this.env = import_lodash.default.defaultTo(cmdArgs2.env || envVars2.SERVER_ENV, "dev");
52
+ this.name = cmdArgs2.name || envVars2.SERVER_NAME || void 0;
53
+ this.host = cmdArgs2.host || envVars2.SERVER_HOST || void 0;
54
+ this.port = Number(cmdArgs2.port || envVars2.SERVER_PORT) ? Number(cmdArgs2.port || envVars2.SERVER_PORT) : void 0;
55
+ this.package = _package;
56
+ }
57
+ };
58
+ var environment_default = new Environment({
59
+ cmdArgs,
60
+ envVars,
61
+ package: JSON.parse(import_fs_extra.default.readFileSync(import_path.default.join(import_path.default.resolve(), "package.json")).toString())
62
+ });
63
+
64
+ // src/lib/configs/service-config.ts
65
+ var import_path3 = __toESM(require("path"), 1);
66
+ var import_fs_extra3 = __toESM(require("fs-extra"), 1);
67
+ var import_yaml = __toESM(require("yaml"), 1);
68
+ var import_lodash3 = __toESM(require("lodash"), 1);
69
+
70
+ // src/lib/util.ts
71
+ var import_os = __toESM(require("os"), 1);
72
+ var import_path2 = __toESM(require("path"), 1);
73
+ var import_crypto = __toESM(require("crypto"), 1);
74
+ var import_stream = require("stream");
75
+ var import_colors = require("colors");
76
+ var import_mime = __toESM(require("mime"), 1);
77
+ var import_axios = __toESM(require("axios"), 1);
78
+ var import_fs_extra2 = __toESM(require("fs-extra"), 1);
79
+ var import_uuid = require("uuid");
80
+ var import_date_fns = require("date-fns");
81
+ var import_crc_32 = __toESM(require("crc-32"), 1);
82
+ var import_randomstring = __toESM(require("randomstring"), 1);
83
+ var import_lodash2 = __toESM(require("lodash"), 1);
84
+ var import_cron = require("cron");
85
+
86
+ // src/lib/http-status-codes.ts
87
+ var http_status_codes_default = {
88
+ CONTINUE: 100,
89
+ //客户端应当继续发送请求。这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝。客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应
90
+ SWITCHING_PROTOCOLS: 101,
91
+ //服务器已经理解了客户端的请求,并将通过Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后,服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。例如,切换到新的HTTP 版本比旧版本更有优势,或者切换到一个实时且同步的协议以传送利用此类特性的资源
92
+ PROCESSING: 102,
93
+ //处理将被继续执行
94
+ OK: 200,
95
+ //请求已成功,请求所希望的响应头或数据体将随此响应返回
96
+ CREATED: 201,
97
+ //请求已经被实现,而且有一个新的资源已经依据请求的需要而建立,且其 URI 已经随Location 头信息返回。假如需要的资源无法及时建立的话,应当返回 '202 Accepted'
98
+ ACCEPTED: 202,
99
+ //服务器已接受请求,但尚未处理。正如它可能被拒绝一样,最终该请求可能会也可能不会被执行。在异步操作的场合下,没有比发送这个状态码更方便的做法了。返回202状态码的响应的目的是允许服务器接受其他过程的请求(例如某个每天只执行一次的基于批处理的操作),而不必让客户端一直保持与服务器的连接直到批处理操作全部完成。在接受请求处理并返回202状态码的响应应当在返回的实体中包含一些指示处理当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便用户能够估计操作是否已经完成
100
+ NON_AUTHORITATIVE_INFO: 203,
101
+ //服务器已成功处理了请求,但返回的实体头部元信息不是在原始服务器上有效的确定集合,而是来自本地或者第三方的拷贝。当前的信息可能是原始版本的子集或者超集。例如,包含资源的元数据可能导致原始服务器知道元信息的超级。使用此状态码不是必须的,而且只有在响应不使用此状态码便会返回200 OK的情况下才是合适的
102
+ NO_CONTENT: 204,
103
+ //服务器成功处理了请求,但不需要返回任何实体内容,并且希望返回更新了的元信息。响应可能通过实体头部的形式,返回新的或更新后的元信息。如果存在这些头部信息,则应当与所请求的变量相呼应。如果客户端是浏览器的话,那么用户浏览器应保留发送了该请求的页面,而不产生任何文档视图上的变化,即使按照规范新的或更新后的元信息应当被应用到用户浏览器活动视图中的文档。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾
104
+ RESET_CONTENT: 205,
105
+ //服务器成功处理了请求,且没有返回任何内容。但是与204响应不同,返回此状态码的响应要求请求者重置文档视图。该响应主要是被用于接受用户输入后,立即重置表单,以便用户能够轻松地开始另一次输入。与204响应一样,该响应也被禁止包含任何消息体,且以消息头后的第一个空行结束
106
+ PARTIAL_CONTENT: 206,
107
+ //服务器已经成功处理了部分 GET 请求。类似于FlashGet或者迅雷这类的HTTP下载工具都是使用此类响应实现断点续传或者将一个大文档分解为多个下载段同时下载。该请求必须包含 Range 头信息来指示客户端希望得到的内容范围,并且可能包含 If-Range 来作为请求条件。响应必须包含如下的头部域:Content-Range 用以指示本次响应中返回的内容的范围;如果是Content-Type为multipart/byteranges的多段下载,则每一段multipart中都应包含Content-Range域用以指示本段的内容范围。假如响应中包含Content-Length,那么它的数值必须匹配它返回的内容范围的真实字节数。Date和ETag或Content-Location,假如同样的请求本应该返回200响应。Expires, Cache-Control,和/或 Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了 If-Range 强缓存验证,那么本次响应不应该包含其他实体头;假如本响应的请求使用了 If-Range 弱缓存验证,那么本次响应禁止包含其他实体头;这避免了缓存的实体内容和更新了的实体头信息之间的不一致。否则,本响应就应当包含所有本应该返回200响应中应当返回的所有实体头部域。假如 ETag 或 Latest-Modified 头部不能精确匹配的话,则客户端缓存应禁止将206响应返回的内容与之前任何缓存过的内容组合在一起。任何不支持 Range 以及 Content-Range 头的缓存都禁止缓存206响应返回的内容
108
+ MULTIPLE_STATUS: 207,
109
+ //代表之后的消息体将是一个XML消息,并且可能依照之前子请求数量的不同,包含一系列独立的响应代码
110
+ MULTIPLE_CHOICES: 300,
111
+ //被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。除非这是一个HEAD请求,否则该响应应当包括一个资源特性及地址的列表的实体,以便用户或浏览器从中选择最合适的重定向地址。这个实体的格式由Content-Type定义的格式所决定。浏览器可能根据响应的格式以及浏览器自身能力,自动作出最合适的选择。当然,RFC 2616规范并没有规定这样的自动选择该如何进行。如果服务器本身已经有了首选的回馈选择,那么在Location中应当指明这个回馈的 URI;浏览器可能会将这个 Location 值作为自动重定向的地址。此外,除非额外指定,否则这个响应也是可缓存的
112
+ MOVED_PERMANENTLY: 301,
113
+ //被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。新的永久性的URI应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含���向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,因此浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:对于某些使用 HTTP/1.0 协议的浏览器,当它们发送的POST请求得到了一个301响应的话,接下来的重定向请求将会变成GET方式
114
+ FOUND: 302,
115
+ //请求的资源现在临时从不同的URI响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI应当在响应的 Location 域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:虽然RFC 1945和RFC 2068规范不允许客户端在重定向时改变请求的方法,但是很多现存的浏览器将302响应视作为303响应,并且使用GET方式访问在Location中规定的URI,而无视原先请求的方法。状态码303和307被添加了进来,用以明确服务器期待客户端进行何种反应
116
+ SEE_OTHER: 303,
117
+ //对应当前请求的响应可以在另一个URI上被找到,而且客户端应当采用 GET 的方式访问那个资源。这个方法的存在主要是为了允许由脚本激活的POST请求输出重定向到一个新的资源。这个新的 URI 不是原始资源的替代引用。同时,303响应禁止被缓存。当然,第二个请求(重定向)可能被缓存。新的 URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。注意:许多 HTTP/1.1 版以前的浏览器不能正确理解303状态。如果需要考虑与这些浏览器之间的互动,302状态码应该可以胜任,因为大多数的浏览器处理302响应时的方式恰恰就是上述规范要求客户端处理303响应时应当做的
118
+ NOT_MODIFIED: 304,
119
+ //如果客户端发送了一个带条件的GET请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个状态码。304响应禁止包含消息体,因此始终以消息头后的第一个空行结尾。该响应必须包含以下的头信息:Date,除非这个服务器没有时钟。假如没有时钟的服务器也遵守这些规则,那么代理服务器以及客户端可以自行将Date字段添加到接收到的响应头中去(正如RFC 2068中规定的一样),缓存机制将会正常工作。ETag或 Content-Location,假如同样的请求本应返回200响应。Expires, Cache-Control,和/或Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了强缓存验证,那么本次响应不应该包含其他实体头;否则(例如,某个带条件的 GET 请求使用了弱缓存验证),本次响应禁止包含其他实体头;这避免了缓存了的实体内容和更新了的实体头信息之间的不一致。假如某个304响应指明了当前某个实体没有缓存,那么缓存系统必须忽视这个响应,并且重复发送不包含限制条件的请求。假如接收到一个要求更新某个缓存条目的304响应,那么缓存系统必须更新整个条目以反映所有在响应中被更新的字段的值
120
+ USE_PROXY: 305,
121
+ //被请求的资源必须通过指定的代理才能被访问。Location域中将给出指定的代理所在的URI信息,接收者需要重复发送一个单独的请求,通过这个代理才能访问相应资源。只有原始服务器才能建立305响应。注意:RFC 2068中没有明确305响应是为了重定向一个单独的请求,而且只能被原始服务器建立。忽视这些限制可能导致严重的安全后果
122
+ UNUSED: 306,
123
+ //在最新版的规范中,306状态码已经不再被使用
124
+ TEMPORARY_REDIRECT: 307,
125
+ //请求的资源现在临时从不同的URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI 的超链接及简短说明。因为部分浏览器不能识别307响应,因此需要添加上述必要信息以便用户能够理解并向新的 URI 发出访问请求。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化
126
+ BAD_REQUEST: 400,
127
+ //1.语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求 2.请求参���有误
128
+ UNAUTHORIZED: 401,
129
+ //当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617
130
+ PAYMENT_REQUIRED: 402,
131
+ //该状态码是为了将来可能的需求而预留的
132
+ FORBIDDEN: 403,
133
+ //服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个HEAD请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息
134
+ NOT_FOUND: 404,
135
+ //请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下
136
+ METHOD_NOT_ALLOWED: 405,
137
+ //请求行中指定的请求方法不能被用于请求相应的资源。该响应必须返回一个Allow 头信息用以表示出当前资源能够接受的请求方法的列表。鉴于PUT,DELETE方法会对服务器上的资源进行写操作,因而绝大部分的网页服务器都不支持或者在默认配置下不允许上述请求方法,对于此类请求均会返回405错误
138
+ NO_ACCEPTABLE: 406,
139
+ //请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体。除非这是一个 HEAD 请求,否则该响应就应当返回一个包含可以让用户或者浏览器从中选择最合适的实体特性以及地址列表的实体。实体的格式由Content-Type头中定义的媒体类型决定。浏览器可以根据格式及自身能力自行作出最佳选择。但是,规范中并没有定义任何作出此类自动选择的标准
140
+ PROXY_AUTHENTICATION_REQUIRED: 407,
141
+ //与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个Proxy-Authenticate用以进行身份询问。客户端可以返回一个Proxy-Authorization信息头用以验证。参见RFC 2617
142
+ REQUEST_TIMEOUT: 408,
143
+ //请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改
144
+ CONFLICT: 409,
145
+ //由于和被请求的资源的当前状态之间存在冲突,请求无法完成。这个代码只允许用在这样的情况下才能被使用:用户被认为能够解决冲突,并且会重新提交新的请求。该响应应当包含足够的信息以便用户发现冲突的源头。冲突通常发生于对PUT请求的处理中。例如,在采用版本检查的环境下,某次PUT提交的对特定资源的修改请求所附带的版本信息与之前的某个(第三方)请求向冲突,那么此时服务器就应该返回一个409错误,告知用户请求无法完成。此时,响应实体中很可能会包含两个冲突版本之间的差异比较,以便用户重新提交归并以后的新版本
146
+ GONE: 410,
147
+ //被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址。这样的状况应当被认为是永久性的。如果可能,拥有链接编辑功能的客户端应当在获得用户许可后删除所有指向这个地址的引用。如果服务器不知道或者无法确定这个状况是否是永久的,那么就应该使用404状态码。除非额外说明,否则这个响应是可缓存的。410响应的目的主要是帮助网站管理员维护网站,通知用户该资源已经不再可用,并且服务器拥有者希望所有指向这个资源的远端连接也被删除。这类事件在限时、增值服务中很普遍。同样,410响应也被用于通知客户端在当前服务器站点上,原本属于某个个人的资源已经不再可用。当然,是否需要把所有永久不可用的资源标记为'410 Gone',以及是否需要保持此标记多长时间,完全取决于服务器拥有者
148
+ LENGTH_REQUIRED: 411,
149
+ //服务器拒绝在没有定义Content-Length头的情况下接受请求。在添加了表明请求消息体长度的有效Content-Length头之后,客户端可以再次提交该请求
150
+ PRECONDITION_FAILED: 412,
151
+ //服务器在验证在请求���头字段中给出先决条件时,没能满足其中的一个或多个。这个状态码允许客户端在获取资源时在请求的元信息(请求头字段数据)中设置先决条件,以此避免该请求方法被应用到其希望的内容以外的资源上
152
+ REQUEST_ENTITY_TOO_LARGE: 413,
153
+ //服务器拒绝处理当前请求,因为该请求提交的实体数据大小超过了服务器愿意或者能够处理的范围。此种情况下,服务器可以关闭连接以免客户端继续发送此请求。如果这个状况是临时的,服务器应当返回一个 Retry-After 的响应头,以告知客户端可以在多少时间以后重新尝试
154
+ REQUEST_URI_TOO_LONG: 414,
155
+ //请求的URI长度超过了服务器能够解释的长度,因此服务器拒绝对该请求提供服务。这比较少见,通常的情况包括:本应使用POST方法的表单提交变成了GET方法,导致查询字符串(Query String)过长。重定向URI “黑洞”,例如每次重定向把旧的URI作为新的URI的一部分,导致在若干次重定向后URI超长。客户端正在尝试利用某些服务器中存在的安全漏洞攻击服务器。这类服务器使用固定长度的缓冲读取或操作请求的URI,当GET后的参数超过某个数值后,可能会产生缓冲区溢出,导致任意代码被执行[1]。没有此类漏洞的服务器,应当返回414状态码
156
+ UNSUPPORTED_MEDIA_TYPE: 415,
157
+ //对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
158
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416,
159
+ //如果请求中包含了Range请求头,并且Range中指定的任何数据范围都与当前资源的可用范围不重合,同时请求中又没有定义If-Range请求头,那么服务器就应当返回416状态码。假如Range使用的是字节范围,那么这种情况就是指请求指定的所有数据范围的首字节位置都超过了当前资源的长度。服务器也应当在返回416状态码的同时,包含一个Content-Range实体头,用以指明当前资源的长度。这个响应也被禁止使用multipart/byteranges作为其 Content-Type
160
+ EXPECTION_FAILED: 417,
161
+ //在请求头Expect中指定的预期内容无法被服务器满足,或者这个服务器是一个代理服务器,它有明显的证据证明在当前路由的下一个节点上,Expect的内容无法被满足
162
+ TOO_MANY_CONNECTIONS: 421,
163
+ //从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围。通常,这里的IP地址指的是从服务器上看到的客户端地址(比如用户的网关或者代理服务器地址)。在这种情况下,连接数的计算可能涉及到不止一个终端用户
164
+ UNPROCESSABLE_ENTITY: 422,
165
+ //请求格式正确,但是由于含有语义错误,无法响应
166
+ FAILED_DEPENDENCY: 424,
167
+ //由于之前的某个请求发生的错误,导致当前请求失败,例如PROPPATCH
168
+ UNORDERED_COLLECTION: 425,
169
+ //在WebDav Advanced Collections 草案中定义,但是未出现在《WebDAV 顺序集协议》(RFC 3658)中
170
+ UPGRADE_REQUIRED: 426,
171
+ //客户端应当切换到TLS/1.0
172
+ RETRY_WITH: 449,
173
+ //由微软扩展,代表请求应当在执行完适当的操作后进行重试
174
+ INTERNAL_SERVER_ERROR: 500,
175
+ //服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现
176
+ NOT_IMPLEMENTED: 501,
177
+ //服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法,并且无法支持其对任何资源的请求
178
+ BAD_GATEWAY: 502,
179
+ //作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应
180
+ SERVICE_UNAVAILABLE: 503,
181
+ //由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 Retry-After 头用以标明这个延迟时间。如果没有给出这个 Retry-After 信息,那么客户端应当以处理500响应的方式处理它。注意:503状态码的存在并不意味着服务器在过载的时候必须使用它。某些服务器只不过是希望拒绝客户端的连接
182
+ GATEWAY_TIMEOUT: 504,
183
+ //作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应。注意:某些代理服务器在DNS查询超时时会返回400或者500错误
184
+ HTTP_VERSION_NOT_SUPPORTED: 505,
185
+ //服务器不支持,或者拒绝支持在请求中使用的HTTP版本。这暗示着服务器不能或不愿使用与客户端相同的版本。响应中应当包含一个描述了为何版本不被支持以及服务器支持哪些协议的实体
186
+ VARIANT_ALSO_NEGOTIATES: 506,
187
+ //服务器存在内部配置错误:被请求的协商变元资源被配置为在透明内容协商中使用自己,因此在一个协商处理中不是一个合适的重点
188
+ INSUFFICIENT_STORAGE: 507,
189
+ //服务器无法存储完成请求所必须的内容。这个状况被认为是临时的
190
+ BANDWIDTH_LIMIT_EXCEEDED: 509,
191
+ //服务器达到带宽限制。这不是一个官方的状态码,但是仍被广泛使用
192
+ NOT_EXTENDED: 510
193
+ //获取资源所需要的策略并没有没满足
194
+ };
195
+
196
+ // src/lib/util.ts
197
+ var autoIdMap = /* @__PURE__ */ new Map();
198
+ var util = {
199
+ is2DArrays(value) {
200
+ return import_lodash2.default.isArray(value) && (!value[0] || import_lodash2.default.isArray(value[0]) && import_lodash2.default.isArray(value[value.length - 1]));
201
+ },
202
+ uuid: (separator = true) => separator ? (0, import_uuid.v1)() : (0, import_uuid.v1)().replace(/\-/g, ""),
203
+ autoId: (prefix = "") => {
204
+ let index = autoIdMap.get(prefix);
205
+ if (index > 999999) index = 0;
206
+ autoIdMap.set(prefix, (index || 0) + 1);
207
+ return `${prefix}${index || 1}`;
208
+ },
209
+ ignoreJSONParse(value) {
210
+ const result = import_lodash2.default.attempt(() => JSON.parse(value));
211
+ if (import_lodash2.default.isError(result)) return null;
212
+ return result;
213
+ },
214
+ generateRandomString(options) {
215
+ return import_randomstring.default.generate(options);
216
+ },
217
+ getResponseContentType(value) {
218
+ return value.headers ? value.headers["content-type"] || value.headers["Content-Type"] : null;
219
+ },
220
+ mimeToExtension(value) {
221
+ let extension = import_mime.default.getExtension(value);
222
+ if (extension == "mpga") return "mp3";
223
+ return extension;
224
+ },
225
+ extractURLExtension(value) {
226
+ const extname = import_path2.default.extname(new URL(value).pathname);
227
+ return extname.substring(1).toLowerCase();
228
+ },
229
+ createCronJob(cronPatterns, callback) {
230
+ if (!import_lodash2.default.isFunction(callback))
231
+ throw new Error("callback must be an Function");
232
+ return new import_cron.CronJob(
233
+ cronPatterns,
234
+ () => callback(),
235
+ null,
236
+ false,
237
+ "Asia/Shanghai"
238
+ );
239
+ },
240
+ getDateString(format = "yyyy-MM-dd", date = /* @__PURE__ */ new Date()) {
241
+ return (0, import_date_fns.format)(date, format);
242
+ },
243
+ getIPAddressesByIPv4() {
244
+ const interfaces = import_os.default.networkInterfaces();
245
+ const addresses = [];
246
+ for (let name in interfaces) {
247
+ const networks = interfaces[name];
248
+ const results = networks.filter(
249
+ (network) => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal
250
+ );
251
+ if (results[0] && results[0].address) addresses.push(results[0].address);
252
+ }
253
+ return addresses;
254
+ },
255
+ getMACAddressesByIPv4() {
256
+ const interfaces = import_os.default.networkInterfaces();
257
+ const addresses = [];
258
+ for (let name in interfaces) {
259
+ const networks = interfaces[name];
260
+ const results = networks.filter(
261
+ (network) => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal
262
+ );
263
+ if (results[0] && results[0].mac) addresses.push(results[0].mac);
264
+ }
265
+ return addresses;
266
+ },
267
+ generateSSEData(event, data, retry) {
268
+ return `event: ${event || "message"}
269
+ data: ${(data || "").replace(/\n/g, "\\n").replace(/\s/g, "\\s")}
270
+ retry: ${retry || 3e3}
271
+
272
+ `;
273
+ },
274
+ buildDataBASE64(type, ext, buffer) {
275
+ return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString(
276
+ "base64"
277
+ )}`;
278
+ },
279
+ isLinux() {
280
+ return import_os.default.platform() !== "win32";
281
+ },
282
+ isIPAddress(value) {
283
+ return import_lodash2.default.isString(value) && (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(
284
+ value
285
+ ) || /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(
286
+ value
287
+ ));
288
+ },
289
+ isPort(value) {
290
+ return import_lodash2.default.isNumber(value) && value > 0 && value < 65536;
291
+ },
292
+ isReadStream(value) {
293
+ return value && (value instanceof import_stream.Readable || "readable" in value || value.readable);
294
+ },
295
+ isWriteStream(value) {
296
+ return value && (value instanceof import_stream.Writable || "writable" in value || value.writable);
297
+ },
298
+ isHttpStatusCode(value) {
299
+ return import_lodash2.default.isNumber(value) && Object.values(http_status_codes_default).includes(value);
300
+ },
301
+ isURL(value) {
302
+ return !import_lodash2.default.isUndefined(value) && /^(http|https)/.test(value);
303
+ },
304
+ isSrc(value) {
305
+ return !import_lodash2.default.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value);
306
+ },
307
+ isBASE64(value) {
308
+ return !import_lodash2.default.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value);
309
+ },
310
+ isBASE64Data(value) {
311
+ return /^data:/.test(value);
312
+ },
313
+ extractBASE64DataFormat(value) {
314
+ const match = value.trim().match(/^data:(.+);base64,/);
315
+ if (!match) return null;
316
+ return match[1];
317
+ },
318
+ removeBASE64DataHeader(value) {
319
+ return value.replace(/^data:(.+);base64,/, "");
320
+ },
321
+ isDataString(value) {
322
+ return /^(base64|json):/.test(value);
323
+ },
324
+ isStringNumber(value) {
325
+ return import_lodash2.default.isFinite(Number(value));
326
+ },
327
+ isUnixTimestamp(value) {
328
+ return /^[0-9]{10}$/.test(`${value}`);
329
+ },
330
+ isTimestamp(value) {
331
+ return /^[0-9]{13}$/.test(`${value}`);
332
+ },
333
+ isEmail(value) {
334
+ return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
335
+ value
336
+ );
337
+ },
338
+ isAsyncFunction(value) {
339
+ return Object.prototype.toString.call(value) === "[object AsyncFunction]";
340
+ },
341
+ async isAPNG(filePath) {
342
+ let head;
343
+ const readStream = import_fs_extra2.default.createReadStream(filePath, { start: 37, end: 40 });
344
+ const readPromise = new Promise((resolve, reject) => {
345
+ readStream.once("end", resolve);
346
+ readStream.once("error", reject);
347
+ });
348
+ readStream.once("data", (data) => head = data);
349
+ await readPromise;
350
+ return head.compare(Buffer.from([97, 99, 84, 76])) === 0;
351
+ },
352
+ unixTimestamp() {
353
+ return parseInt(`${Date.now() / 1e3}`);
354
+ },
355
+ timestamp() {
356
+ return Date.now();
357
+ },
358
+ urlJoin(...values) {
359
+ let url = "";
360
+ for (let i = 0; i < values.length; i++)
361
+ url += `${i > 0 ? "/" : ""}${values[i].replace(/^\/*/, "").replace(/\/*$/, "")}`;
362
+ return url;
363
+ },
364
+ millisecondsToHmss(milliseconds) {
365
+ if (import_lodash2.default.isString(milliseconds)) return milliseconds;
366
+ milliseconds = parseInt(milliseconds);
367
+ const sec = Math.floor(milliseconds / 1e3);
368
+ const hours = Math.floor(sec / 3600);
369
+ const minutes = Math.floor((sec - hours * 3600) / 60);
370
+ const seconds = sec - hours * 3600 - minutes * 60;
371
+ const ms = milliseconds % 6e4 - seconds * 1e3;
372
+ return `${hours > 9 ? hours : "0" + hours}:${minutes > 9 ? minutes : "0" + minutes}:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
373
+ },
374
+ millisecondsToTimeString(milliseconds) {
375
+ if (milliseconds < 1e3) return `${milliseconds}ms`;
376
+ if (milliseconds < 6e4)
377
+ return `${parseFloat((milliseconds / 1e3).toFixed(2))}s`;
378
+ return `${Math.floor(milliseconds / 1e3 / 60)}m${Math.floor(
379
+ milliseconds / 1e3 % 60
380
+ )}s`;
381
+ },
382
+ rgbToHex(r, g, b) {
383
+ return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
384
+ },
385
+ hexToRgb(hex) {
386
+ const value = parseInt(hex.replace(/^#/, ""), 16);
387
+ return [value >> 16 & 255, value >> 8 & 255, value & 255];
388
+ },
389
+ md5(value) {
390
+ return import_crypto.default.createHash("md5").update(value).digest("hex");
391
+ },
392
+ crc32(value) {
393
+ return import_lodash2.default.isBuffer(value) ? import_crc_32.default.buf(value) : import_crc_32.default.str(value);
394
+ },
395
+ arrayParse(value) {
396
+ return import_lodash2.default.isArray(value) ? value : [value];
397
+ },
398
+ booleanParse(value) {
399
+ return value === "true" || value === true ? true : false;
400
+ },
401
+ encodeBASE64(value) {
402
+ return Buffer.from(value).toString("base64");
403
+ },
404
+ decodeBASE64(value) {
405
+ return Buffer.from(value, "base64").toString();
406
+ },
407
+ async fetchFileBASE64(url) {
408
+ const result = await import_axios.default.get(url, {
409
+ responseType: "arraybuffer"
410
+ });
411
+ return result.data.toString("base64");
412
+ }
413
+ };
414
+ var util_default = util;
415
+
416
+ // src/lib/configs/service-config.ts
417
+ var CONFIG_PATH = import_path3.default.join(import_path3.default.resolve(), "configs/", environment_default.env, "/service.yml");
418
+ var ServiceConfig = class _ServiceConfig {
419
+ /** 服务名称 */
420
+ name;
421
+ /** @type {string} 服务绑定主机地址 */
422
+ host;
423
+ /** @type {number} 服务绑定端口 */
424
+ port;
425
+ /** @type {string} 服务路由前缀 */
426
+ urlPrefix;
427
+ /** @type {string} 服务绑定地址(外部访问地址) */
428
+ bindAddress;
429
+ constructor(options) {
430
+ const { name, host, port, urlPrefix, bindAddress } = options || {};
431
+ this.name = import_lodash3.default.defaultTo(name, "deepseek-free-api");
432
+ this.host = import_lodash3.default.defaultTo(host, "0.0.0.0");
433
+ this.port = import_lodash3.default.defaultTo(port, 5566);
434
+ this.urlPrefix = import_lodash3.default.defaultTo(urlPrefix, "");
435
+ this.bindAddress = bindAddress;
436
+ }
437
+ get addressHost() {
438
+ if (this.bindAddress) return this.bindAddress;
439
+ const ipAddresses = util_default.getIPAddressesByIPv4();
440
+ for (let ipAddress of ipAddresses) {
441
+ if (ipAddress === this.host)
442
+ return ipAddress;
443
+ }
444
+ return ipAddresses[0] || "127.0.0.1";
445
+ }
446
+ get address() {
447
+ return `${this.addressHost}:${this.port}`;
448
+ }
449
+ get pageDirUrl() {
450
+ return `http://127.0.0.1:${this.port}/page`;
451
+ }
452
+ get publicDirUrl() {
453
+ return `http://127.0.0.1:${this.port}/public`;
454
+ }
455
+ static load() {
456
+ const external = import_lodash3.default.pickBy(environment_default, (v, k) => ["name", "host", "port"].includes(k) && !import_lodash3.default.isUndefined(v));
457
+ if (!import_fs_extra3.default.pathExistsSync(CONFIG_PATH)) return new _ServiceConfig(external);
458
+ const data = import_yaml.default.parse(import_fs_extra3.default.readFileSync(CONFIG_PATH).toString());
459
+ return new _ServiceConfig({ ...data, ...external });
460
+ }
461
+ };
462
+ var service_config_default = ServiceConfig.load();
463
+
464
+ // src/lib/configs/system-config.ts
465
+ var import_path4 = __toESM(require("path"), 1);
466
+ var import_fs_extra4 = __toESM(require("fs-extra"), 1);
467
+ var import_yaml2 = __toESM(require("yaml"), 1);
468
+ var import_lodash4 = __toESM(require("lodash"), 1);
469
+ var CONFIG_PATH2 = import_path4.default.join(import_path4.default.resolve(), "configs/", environment_default.env, "/system.yml");
470
+ var SystemConfig = class _SystemConfig {
471
+ /** 是否开启请求日志 */
472
+ requestLog;
473
+ /** 临时目录路径 */
474
+ tmpDir;
475
+ /** 日志目录路径 */
476
+ logDir;
477
+ /** 日志写入间隔(毫秒) */
478
+ logWriteInterval;
479
+ /** 日志文件有效期(毫秒) */
480
+ logFileExpires;
481
+ /** 公共目录路径 */
482
+ publicDir;
483
+ /** 临时文件有效期(毫秒) */
484
+ tmpFileExpires;
485
+ /** 请求体配置 */
486
+ requestBody;
487
+ /** 是否调试模式 */
488
+ debug;
489
+ constructor(options) {
490
+ const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, publicDir, tmpFileExpires, requestBody, debug } = options || {};
491
+ this.requestLog = import_lodash4.default.defaultTo(requestLog, false);
492
+ this.tmpDir = import_lodash4.default.defaultTo(tmpDir, "./tmp");
493
+ this.logDir = import_lodash4.default.defaultTo(logDir, "./logs");
494
+ this.logWriteInterval = import_lodash4.default.defaultTo(logWriteInterval, 200);
495
+ this.logFileExpires = import_lodash4.default.defaultTo(logFileExpires, 262656e4);
496
+ this.publicDir = import_lodash4.default.defaultTo(publicDir, "./public");
497
+ this.tmpFileExpires = import_lodash4.default.defaultTo(tmpFileExpires, 864e5);
498
+ this.requestBody = Object.assign(requestBody || {}, {
499
+ enableTypes: ["json", "form", "text", "xml"],
500
+ encoding: "utf-8",
501
+ formLimit: "100mb",
502
+ jsonLimit: "100mb",
503
+ textLimit: "100mb",
504
+ xmlLimit: "100mb",
505
+ formidable: {
506
+ maxFileSize: "100mb"
507
+ },
508
+ multipart: true,
509
+ parsedMethods: ["POST", "PUT", "PATCH"]
510
+ });
511
+ this.debug = import_lodash4.default.defaultTo(debug, true);
512
+ }
513
+ get rootDirPath() {
514
+ return import_path4.default.resolve();
515
+ }
516
+ get tmpDirPath() {
517
+ return import_path4.default.resolve(this.tmpDir);
518
+ }
519
+ get logDirPath() {
520
+ return import_path4.default.resolve(this.logDir);
521
+ }
522
+ get publicDirPath() {
523
+ return import_path4.default.resolve(this.publicDir);
524
+ }
525
+ static load() {
526
+ if (!import_fs_extra4.default.pathExistsSync(CONFIG_PATH2)) return new _SystemConfig();
527
+ const data = import_yaml2.default.parse(import_fs_extra4.default.readFileSync(CONFIG_PATH2).toString());
528
+ return new _SystemConfig(data);
529
+ }
530
+ };
531
+ var system_config_default = SystemConfig.load();
532
+
533
+ // src/lib/config.ts
534
+ var Config = class {
535
+ /** 服务配置 */
536
+ service = service_config_default;
537
+ /** 系统配置 */
538
+ system = system_config_default;
539
+ };
540
+ var config_default = new Config();
541
+
542
+ // src/lib/logger.ts
543
+ var import_path5 = __toESM(require("path"), 1);
544
+ var import_util2 = __toESM(require("util"), 1);
545
+ var import_colors2 = require("colors");
546
+ var import_lodash5 = __toESM(require("lodash"), 1);
547
+ var import_fs_extra5 = __toESM(require("fs-extra"), 1);
548
+ var import_date_fns2 = require("date-fns");
549
+ var isVercelEnv = process.env.VERCEL;
550
+ var LogWriter = class {
551
+ #buffers = [];
552
+ constructor() {
553
+ !isVercelEnv && import_fs_extra5.default.ensureDirSync(config_default.system.logDirPath);
554
+ !isVercelEnv && this.work();
555
+ }
556
+ push(content) {
557
+ const buffer = Buffer.from(content);
558
+ this.#buffers.push(buffer);
559
+ }
560
+ writeSync(buffer) {
561
+ !isVercelEnv && import_fs_extra5.default.appendFileSync(import_path5.default.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), buffer);
562
+ }
563
+ async write(buffer) {
564
+ !isVercelEnv && await import_fs_extra5.default.appendFile(import_path5.default.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), buffer);
565
+ }
566
+ flush() {
567
+ if (!this.#buffers.length) return;
568
+ !isVercelEnv && import_fs_extra5.default.appendFileSync(import_path5.default.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), Buffer.concat(this.#buffers));
569
+ }
570
+ work() {
571
+ if (!this.#buffers.length) return setTimeout(this.work.bind(this), config_default.system.logWriteInterval);
572
+ const buffer = Buffer.concat(this.#buffers);
573
+ this.#buffers = [];
574
+ this.write(buffer).finally(() => setTimeout(this.work.bind(this), config_default.system.logWriteInterval)).catch((err) => console.error("Log write error:", err));
575
+ }
576
+ };
577
+ var LogText = class {
578
+ /** @type {string} 日志级别 */
579
+ level;
580
+ /** @type {string} 日志文本 */
581
+ text;
582
+ /** @type {string} 日志来源 */
583
+ source;
584
+ /** @type {Date} 日志发生时间 */
585
+ time = /* @__PURE__ */ new Date();
586
+ constructor(level, ...params) {
587
+ this.level = level;
588
+ this.text = import_util2.default.format.apply(null, params);
589
+ this.source = this.#getStackTopCodeInfo();
590
+ }
591
+ #getStackTopCodeInfo() {
592
+ const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 };
593
+ const stackArray = new Error().stack.split("\n");
594
+ const text = stackArray[4];
595
+ if (!text)
596
+ return unknownInfo;
597
+ const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/);
598
+ if (!match || !import_lodash5.default.isString(match[2] || match[1]))
599
+ return unknownInfo;
600
+ const temp = match[2] || match[1];
601
+ const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/);
602
+ if (!_match)
603
+ return unknownInfo;
604
+ const [, scriptPath, codeLine, codeColumn] = _match;
605
+ return {
606
+ name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown",
607
+ path: scriptPath || null,
608
+ codeLine: parseInt(codeLine || 0),
609
+ codeColumn: parseInt(codeColumn || 0)
610
+ };
611
+ }
612
+ toString() {
613
+ return `[${(0, import_date_fns2.format)(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`;
614
+ }
615
+ };
616
+ var Logger = class _Logger {
617
+ /** @type {Object} 系统配置 */
618
+ config = {};
619
+ /** @type {Object} 日志级别映射 */
620
+ static Level = {
621
+ Success: "success",
622
+ Info: "info",
623
+ Log: "log",
624
+ Debug: "debug",
625
+ Warning: "warning",
626
+ Error: "error",
627
+ Fatal: "fatal"
628
+ };
629
+ /** @type {Object} 日志级别文本颜色樱色 */
630
+ static LevelColor = {
631
+ [_Logger.Level.Success]: "green",
632
+ [_Logger.Level.Info]: "brightCyan",
633
+ [_Logger.Level.Debug]: "white",
634
+ [_Logger.Level.Warning]: "brightYellow",
635
+ [_Logger.Level.Error]: "brightRed",
636
+ [_Logger.Level.Fatal]: "red"
637
+ };
638
+ #writer;
639
+ constructor() {
640
+ this.#writer = new LogWriter();
641
+ }
642
+ header() {
643
+ this.#writer.writeSync(Buffer.from(`
644
+
645
+ ===================== LOG START ${(0, import_date_fns2.format)(/* @__PURE__ */ new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================
646
+
647
+ `));
648
+ }
649
+ footer() {
650
+ this.#writer.flush();
651
+ this.#writer.writeSync(Buffer.from(`
652
+
653
+ ===================== LOG END ${(0, import_date_fns2.format)(/* @__PURE__ */ new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================
654
+
655
+ `));
656
+ }
657
+ success(...params) {
658
+ const content = new LogText(_Logger.Level.Success, ...params).toString();
659
+ console.info(content[_Logger.LevelColor[_Logger.Level.Success]]);
660
+ this.#writer.push(content + "\n");
661
+ }
662
+ info(...params) {
663
+ const content = new LogText(_Logger.Level.Info, ...params).toString();
664
+ console.info(content[_Logger.LevelColor[_Logger.Level.Info]]);
665
+ this.#writer.push(content + "\n");
666
+ }
667
+ log(...params) {
668
+ const content = new LogText(_Logger.Level.Log, ...params).toString();
669
+ console.log(content[_Logger.LevelColor[_Logger.Level.Log]]);
670
+ this.#writer.push(content + "\n");
671
+ }
672
+ debug(...params) {
673
+ if (!config_default.system.debug) return;
674
+ const content = new LogText(_Logger.Level.Debug, ...params).toString();
675
+ console.debug(content[_Logger.LevelColor[_Logger.Level.Debug]]);
676
+ this.#writer.push(content + "\n");
677
+ }
678
+ warn(...params) {
679
+ const content = new LogText(_Logger.Level.Warning, ...params).toString();
680
+ console.warn(content[_Logger.LevelColor[_Logger.Level.Warning]]);
681
+ this.#writer.push(content + "\n");
682
+ }
683
+ error(...params) {
684
+ const content = new LogText(_Logger.Level.Error, ...params).toString();
685
+ console.error(content[_Logger.LevelColor[_Logger.Level.Error]]);
686
+ this.#writer.push(content);
687
+ }
688
+ fatal(...params) {
689
+ const content = new LogText(_Logger.Level.Fatal, ...params).toString();
690
+ console.error(content[_Logger.LevelColor[_Logger.Level.Fatal]]);
691
+ this.#writer.push(content);
692
+ }
693
+ destory() {
694
+ this.#writer.destory();
695
+ }
696
+ };
697
+ var logger_default = new Logger();
698
+
699
+ // src/lib/initialize.ts
700
+ process.setMaxListeners(Infinity);
701
+ process.on("uncaughtException", (err, origin) => {
702
+ logger_default.error(`An unhandled error occurred: ${origin}`, err);
703
+ });
704
+ process.on("unhandledRejection", (_15, promise) => {
705
+ promise.catch((err) => logger_default.error("An unhandled rejection occurred:", err));
706
+ });
707
+ process.on("warning", (warning) => logger_default.warn("System warning: ", warning));
708
+ process.on("exit", () => {
709
+ logger_default.info("Service exit");
710
+ logger_default.footer();
711
+ });
712
+ process.on("SIGTERM", () => {
713
+ logger_default.warn("received kill signal");
714
+ process.exit(2);
715
+ });
716
+ process.on("SIGINT", () => {
717
+ process.exit(0);
718
+ });
719
+
720
+ // src/lib/server.ts
721
+ var import_koa = __toESM(require("koa"), 1);
722
+ var import_koa_router = __toESM(require("koa-router"), 1);
723
+ var import_koa_range = __toESM(require("koa-range"), 1);
724
+ var import_koa2_cors = __toESM(require("koa2-cors"), 1);
725
+ var import_koa_body = __toESM(require("koa-body"), 1);
726
+ var import_lodash11 = __toESM(require("lodash"), 1);
727
+
728
+ // src/lib/request/Request.ts
729
+ var import_lodash7 = __toESM(require("lodash"), 1);
730
+
731
+ // src/lib/exceptions/Exception.ts
732
+ var import_assert = __toESM(require("assert"), 1);
733
+ var import_lodash6 = __toESM(require("lodash"), 1);
734
+ var Exception = class extends Error {
735
+ /** 错误码 */
736
+ errcode;
737
+ /** 错误消息 */
738
+ errmsg;
739
+ /** 数据 */
740
+ data;
741
+ /** HTTP状态码 */
742
+ httpStatusCode;
743
+ /**
744
+ * 构造异常
745
+ *
746
+ * @param exception 异常
747
+ * @param _errmsg 异常消息
748
+ */
749
+ constructor(exception, _errmsg) {
750
+ (0, import_assert.default)(import_lodash6.default.isArray(exception), "Exception must be Array");
751
+ const [errcode, errmsg] = exception;
752
+ (0, import_assert.default)(import_lodash6.default.isFinite(errcode), "Exception errcode invalid");
753
+ (0, import_assert.default)(import_lodash6.default.isString(errmsg), "Exception errmsg invalid");
754
+ super(_errmsg || errmsg);
755
+ this.errcode = errcode;
756
+ this.errmsg = _errmsg || errmsg;
757
+ }
758
+ compare(exception) {
759
+ const [errcode] = exception;
760
+ return this.errcode == errcode;
761
+ }
762
+ setHTTPStatusCode(value) {
763
+ this.httpStatusCode = value;
764
+ return this;
765
+ }
766
+ setData(value) {
767
+ this.data = import_lodash6.default.defaultTo(value, null);
768
+ return this;
769
+ }
770
+ };
771
+
772
+ // src/lib/exceptions/APIException.ts
773
+ var APIException = class extends Exception {
774
+ /**
775
+ * 构造异常
776
+ *
777
+ * @param {[number, string]} exception 异常
778
+ */
779
+ constructor(exception, errmsg) {
780
+ super(exception, errmsg);
781
+ }
782
+ };
783
+
784
+ // src/api/consts/exceptions.ts
785
+ var exceptions_default = {
786
+ API_TEST: [-9999, "API\u5F02\u5E38\u9519\u8BEF"],
787
+ API_REQUEST_PARAMS_INVALID: [-2e3, "\u8BF7\u6C42\u53C2\u6570\u975E\u6CD5"],
788
+ API_REQUEST_FAILED: [-2001, "\u8BF7\u6C42\u5931\u8D25"],
789
+ API_TOKEN_EXPIRES: [-2002, "Token\u5DF2\u5931\u6548"],
790
+ API_FILE_URL_INVALID: [-2003, "\u8FDC\u7A0B\u6587\u4EF6URL\u975E\u6CD5"],
791
+ API_FILE_EXECEEDS_SIZE: [-2004, "\u8FDC\u7A0B\u6587\u4EF6\u8D85\u51FA\u5927\u5C0F"],
792
+ API_CHAT_STREAM_PUSHING: [-2005, "\u5DF2\u6709\u5BF9\u8BDD\u6D41\u6B63\u5728\u8F93\u51FA"],
793
+ API_CONTENT_FILTERED: [-2006, "\u5185\u5BB9\u7531\u4E8E\u5408\u89C4\u95EE\u9898\u5DF2\u88AB\u963B\u6B62\u751F\u6210"],
794
+ API_IMAGE_GENERATION_FAILED: [-2007, "\u56FE\u50CF\u751F\u6210\u5931\u8D25"]
795
+ };
796
+
797
+ // src/lib/request/Request.ts
798
+ var Request = class {
799
+ /** 请求方法 */
800
+ method;
801
+ /** 请求URL */
802
+ url;
803
+ /** 请求路径 */
804
+ path;
805
+ /** 请求载荷类型 */
806
+ type;
807
+ /** 请求headers */
808
+ headers;
809
+ /** 请求原始查询字符串 */
810
+ search;
811
+ /** 请求查询参数 */
812
+ query;
813
+ /** 请求URL参数 */
814
+ params;
815
+ /** 请求载荷 */
816
+ body;
817
+ /** 上传的文件 */
818
+ files;
819
+ /** 客户端IP地址 */
820
+ remoteIP;
821
+ /** 请求接受时间戳(毫秒) */
822
+ time;
823
+ constructor(ctx, options = {}) {
824
+ const { time } = options;
825
+ this.method = ctx.request.method;
826
+ this.url = ctx.request.url;
827
+ this.path = ctx.request.path;
828
+ this.type = ctx.request.type;
829
+ this.headers = ctx.request.headers || {};
830
+ this.search = ctx.request.search;
831
+ this.query = ctx.query || {};
832
+ this.params = ctx.params || {};
833
+ this.body = ctx.request.body || {};
834
+ this.files = ctx.request.files || {};
835
+ this.remoteIP = this.headers["X-Real-IP"] || this.headers["x-real-ip"] || this.headers["X-Forwarded-For"] || this.headers["x-forwarded-for"] || ctx.ip || null;
836
+ this.time = Number(import_lodash7.default.defaultTo(time, util_default.timestamp()));
837
+ }
838
+ validate(key, fn) {
839
+ try {
840
+ const value = import_lodash7.default.get(this, key);
841
+ if (fn) {
842
+ if (fn(value) === false)
843
+ throw `[Mismatch] -> ${fn}`;
844
+ } else if (import_lodash7.default.isUndefined(value))
845
+ throw "[Undefined]";
846
+ } catch (err) {
847
+ logger_default.warn(`Params ${key} invalid:`, err);
848
+ throw new APIException(exceptions_default.API_REQUEST_PARAMS_INVALID, `Params ${key} invalid`);
849
+ }
850
+ return this;
851
+ }
852
+ };
853
+
854
+ // src/lib/response/Response.ts
855
+ var import_mime2 = __toESM(require("mime"), 1);
856
+ var import_lodash9 = __toESM(require("lodash"), 1);
857
+
858
+ // src/lib/response/Body.ts
859
+ var import_lodash8 = __toESM(require("lodash"), 1);
860
+ var Body = class _Body {
861
+ /** 状态码 */
862
+ code;
863
+ /** 状态消息 */
864
+ message;
865
+ /** 载荷 */
866
+ data;
867
+ /** HTTP状态码 */
868
+ statusCode;
869
+ constructor(options = {}) {
870
+ const { code, message, data, statusCode } = options;
871
+ this.code = Number(import_lodash8.default.defaultTo(code, 0));
872
+ this.message = import_lodash8.default.defaultTo(message, "OK");
873
+ this.data = import_lodash8.default.defaultTo(data, null);
874
+ this.statusCode = Number(import_lodash8.default.defaultTo(statusCode, 200));
875
+ }
876
+ toObject() {
877
+ return {
878
+ code: this.code,
879
+ message: this.message,
880
+ data: this.data
881
+ };
882
+ }
883
+ static isInstance(value) {
884
+ return value instanceof _Body;
885
+ }
886
+ };
887
+
888
+ // src/lib/response/Response.ts
889
+ var Response = class _Response {
890
+ /** 响应HTTP状态码 */
891
+ statusCode;
892
+ /** 响应内容类型 */
893
+ type;
894
+ /** 响应headers */
895
+ headers;
896
+ /** 重定向目标 */
897
+ redirect;
898
+ /** 响应载荷 */
899
+ body;
900
+ /** 响应载荷大小 */
901
+ size;
902
+ /** 响应时间戳 */
903
+ time;
904
+ constructor(body, options = {}) {
905
+ const { statusCode, type, headers, redirect, size, time } = options;
906
+ this.statusCode = Number(import_lodash9.default.defaultTo(statusCode, Body.isInstance(body) ? body.statusCode : void 0));
907
+ this.type = type;
908
+ this.headers = headers;
909
+ this.redirect = redirect;
910
+ this.size = size;
911
+ this.time = Number(import_lodash9.default.defaultTo(time, util_default.timestamp()));
912
+ this.body = body;
913
+ }
914
+ injectTo(ctx) {
915
+ this.redirect && ctx.redirect(this.redirect);
916
+ this.statusCode && (ctx.status = this.statusCode);
917
+ this.type && (ctx.type = import_mime2.default.getType(this.type) || this.type);
918
+ const headers = this.headers || {};
919
+ if (this.size && !headers["Content-Length"] && !headers["content-length"])
920
+ headers["Content-Length"] = this.size;
921
+ ctx.set(headers);
922
+ if (Body.isInstance(this.body))
923
+ ctx.body = this.body.toObject();
924
+ else
925
+ ctx.body = this.body;
926
+ }
927
+ static isInstance(value) {
928
+ return value instanceof _Response;
929
+ }
930
+ };
931
+
932
+ // src/lib/response/FailureBody.ts
933
+ var import_lodash10 = __toESM(require("lodash"), 1);
934
+
935
+ // src/lib/consts/exceptions.ts
936
+ var exceptions_default2 = {
937
+ SYSTEM_ERROR: [-1e3, "\u7CFB\u7EDF\u5F02\u5E38"],
938
+ SYSTEM_REQUEST_VALIDATION_ERROR: [-1001, "\u8BF7\u6C42\u53C2\u6570\u6821\u9A8C\u9519\u8BEF"],
939
+ SYSTEM_NOT_ROUTE_MATCHING: [-1002, "\u65E0\u5339\u914D\u7684\u8DEF\u7531"]
940
+ };
941
+
942
+ // src/lib/response/FailureBody.ts
943
+ var FailureBody = class _FailureBody extends Body {
944
+ constructor(error, _data) {
945
+ let errcode, errmsg, data = _data, httpStatusCode = http_status_codes_default.OK;
946
+ ;
947
+ if (import_lodash10.default.isString(error))
948
+ error = new Exception(exceptions_default2.SYSTEM_ERROR, error);
949
+ else if (error instanceof APIException || error instanceof Exception)
950
+ ({ errcode, errmsg, data, httpStatusCode } = error);
951
+ else if (import_lodash10.default.isError(error))
952
+ ({ errcode, errmsg, data, httpStatusCode } = new Exception(exceptions_default2.SYSTEM_ERROR, error.message));
953
+ super({
954
+ code: errcode || -1,
955
+ message: errmsg || "Internal error",
956
+ data,
957
+ statusCode: httpStatusCode
958
+ });
959
+ }
960
+ static isInstance(value) {
961
+ return value instanceof _FailureBody;
962
+ }
963
+ };
964
+
965
+ // src/lib/server.ts
966
+ var Server = class {
967
+ app;
968
+ router;
969
+ constructor() {
970
+ this.app = new import_koa.default();
971
+ this.app.use((0, import_koa2_cors.default)());
972
+ this.app.use(import_koa_range.default);
973
+ this.router = new import_koa_router.default({ prefix: config_default.service.urlPrefix });
974
+ this.app.use(async (ctx, next) => {
975
+ if (ctx.request.type === "application/xml" || ctx.request.type === "application/ssml+xml")
976
+ ctx.req.headers["content-type"] = "text/xml";
977
+ try {
978
+ await next();
979
+ } catch (err) {
980
+ logger_default.error(err);
981
+ const failureBody = new FailureBody(err);
982
+ new Response(failureBody).injectTo(ctx);
983
+ }
984
+ });
985
+ this.app.use((0, import_koa_body.default)(import_lodash11.default.clone(config_default.system.requestBody)));
986
+ this.app.on("error", (err) => {
987
+ if (["ECONNRESET", "ECONNABORTED", "EPIPE", "ECANCELED"].includes(err.code)) return;
988
+ logger_default.error(err);
989
+ });
990
+ logger_default.success("Server initialized");
991
+ }
992
+ /**
993
+ * 附加路由
994
+ *
995
+ * @param routes 路由列表
996
+ */
997
+ attachRoutes(routes) {
998
+ routes.forEach((route) => {
999
+ const prefix = route.prefix || "";
1000
+ for (let method in route) {
1001
+ if (method === "prefix") continue;
1002
+ if (!import_lodash11.default.isObject(route[method])) {
1003
+ logger_default.warn(`Router ${prefix} ${method} invalid`);
1004
+ continue;
1005
+ }
1006
+ for (let uri in route[method]) {
1007
+ this.router[method](`${prefix}${uri}`, async (ctx) => {
1008
+ const { request, response } = await this.#requestProcessing(ctx, route[method][uri]);
1009
+ if (response != null && config_default.system.requestLog)
1010
+ logger_default.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
1011
+ });
1012
+ }
1013
+ }
1014
+ logger_default.info(`Route ${config_default.service.urlPrefix || ""}${prefix} attached`);
1015
+ });
1016
+ this.app.use(this.router.routes());
1017
+ this.app.use((ctx) => {
1018
+ const request = new Request(ctx);
1019
+ logger_default.debug(`-> ${ctx.request.method} ${ctx.request.url} request is not supported - ${request.remoteIP || "unknown"}`);
1020
+ const message = `[\u8BF7\u6C42\u6709\u8BEF]: \u6B63\u786E\u8BF7\u6C42\u4E3A POST -> /v1/chat/completions\uFF0C\u5F53\u524D\u8BF7\u6C42\u4E3A ${ctx.request.method} -> ${ctx.request.url} \u8BF7\u7EA0\u6B63`;
1021
+ logger_default.warn(message);
1022
+ const failureBody = new FailureBody(new Error(message));
1023
+ const response = new Response(failureBody);
1024
+ response.injectTo(ctx);
1025
+ if (config_default.system.requestLog)
1026
+ logger_default.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
1027
+ });
1028
+ }
1029
+ /**
1030
+ * 请求处理
1031
+ *
1032
+ * @param ctx 上下文
1033
+ * @param routeFn 路由方法
1034
+ */
1035
+ #requestProcessing(ctx, routeFn) {
1036
+ return new Promise((resolve) => {
1037
+ const request = new Request(ctx);
1038
+ try {
1039
+ if (config_default.system.requestLog)
1040
+ logger_default.info(`-> ${request.method} ${request.url}`);
1041
+ routeFn(request).then((response) => {
1042
+ try {
1043
+ if (!Response.isInstance(response)) {
1044
+ const _response = new Response(response);
1045
+ _response.injectTo(ctx);
1046
+ return resolve({ request, response: _response });
1047
+ }
1048
+ response.injectTo(ctx);
1049
+ resolve({ request, response });
1050
+ } catch (err) {
1051
+ logger_default.error(err);
1052
+ const failureBody = new FailureBody(err);
1053
+ const response2 = new Response(failureBody);
1054
+ response2.injectTo(ctx);
1055
+ resolve({ request, response: response2 });
1056
+ }
1057
+ }).catch((err) => {
1058
+ try {
1059
+ logger_default.error(err);
1060
+ const failureBody = new FailureBody(err);
1061
+ const response = new Response(failureBody);
1062
+ response.injectTo(ctx);
1063
+ resolve({ request, response });
1064
+ } catch (err2) {
1065
+ logger_default.error(err2);
1066
+ const failureBody = new FailureBody(err2);
1067
+ const response = new Response(failureBody);
1068
+ response.injectTo(ctx);
1069
+ resolve({ request, response });
1070
+ }
1071
+ });
1072
+ } catch (err) {
1073
+ logger_default.error(err);
1074
+ const failureBody = new FailureBody(err);
1075
+ const response = new Response(failureBody);
1076
+ response.injectTo(ctx);
1077
+ resolve({ request, response });
1078
+ }
1079
+ });
1080
+ }
1081
+ /**
1082
+ * 监听端口
1083
+ */
1084
+ async listen() {
1085
+ const host = config_default.service.host;
1086
+ const port = config_default.service.port;
1087
+ await Promise.all([
1088
+ new Promise((resolve, reject) => {
1089
+ if (host === "0.0.0.0" || host === "localhost" || host === "127.0.0.1")
1090
+ return resolve(null);
1091
+ this.app.listen(port, "localhost", (err) => {
1092
+ if (err) return reject(err);
1093
+ resolve(null);
1094
+ });
1095
+ }),
1096
+ new Promise((resolve, reject) => {
1097
+ this.app.listen(port, host, (err) => {
1098
+ if (err) return reject(err);
1099
+ resolve(null);
1100
+ });
1101
+ })
1102
+ ]);
1103
+ logger_default.success(`Server listening on port ${port} (${host})`);
1104
+ }
1105
+ };
1106
+ var server_default = new Server();
1107
+
1108
+ // src/api/routes/index.ts
1109
+ var import_fs_extra6 = __toESM(require("fs-extra"), 1);
1110
+
1111
+ // src/api/routes/chat.ts
1112
+ var import_lodash13 = __toESM(require("lodash"), 1);
1113
+
1114
+ // src/api/controllers/chat.ts
1115
+ var import_stream2 = require("stream");
1116
+ var import_lodash12 = __toESM(require("lodash"), 1);
1117
+ var import_async_lock = __toESM(require("async-lock"), 1);
1118
+ var import_axios2 = __toESM(require("axios"), 1);
1119
+ var import_eventsource_parser = require("eventsource-parser");
1120
+ var MODEL_NAME = "deepseek-chat";
1121
+ var ACCESS_TOKEN_EXPIRES = 3600;
1122
+ var MAX_RETRY_COUNT = 3;
1123
+ var RETRY_DELAY = 5e3;
1124
+ var FAKE_HEADERS = {
1125
+ Accept: "*/*",
1126
+ "Accept-Encoding": "gzip, deflate, br, zstd",
1127
+ "Accept-Language": "zh-CN,zh;q=0.9",
1128
+ Origin: "https://chat.deepseek.com",
1129
+ Pragma: "no-cache",
1130
+ Referer: "https://chat.deepseek.com/",
1131
+ "Sec-Ch-Ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
1132
+ "Sec-Ch-Ua-Mobile": "?0",
1133
+ "Sec-Ch-Ua-Platform": '"Windows"',
1134
+ "Sec-Fetch-Dest": "empty",
1135
+ "Sec-Fetch-Mode": "cors",
1136
+ "Sec-Fetch-Site": "same-origin",
1137
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
1138
+ "X-App-Version": "20240126.0"
1139
+ };
1140
+ var accessTokenMap = /* @__PURE__ */ new Map();
1141
+ var accessTokenRequestQueueMap = {};
1142
+ var chatLock = new import_async_lock.default();
1143
+ async function requestToken(refreshToken) {
1144
+ if (accessTokenRequestQueueMap[refreshToken])
1145
+ return new Promise(
1146
+ (resolve) => accessTokenRequestQueueMap[refreshToken].push(resolve)
1147
+ );
1148
+ accessTokenRequestQueueMap[refreshToken] = [];
1149
+ logger_default.info(`Refresh token: ${refreshToken}`);
1150
+ const result = await (async () => {
1151
+ const result2 = await import_axios2.default.get(
1152
+ "https://chat.deepseek.com/api/v0/users/current",
1153
+ {
1154
+ headers: {
1155
+ Authorization: `Bearer ${refreshToken}`,
1156
+ ...FAKE_HEADERS
1157
+ },
1158
+ timeout: 15e3,
1159
+ validateStatus: () => true
1160
+ }
1161
+ );
1162
+ const { token } = checkResult(result2, refreshToken);
1163
+ return {
1164
+ accessToken: token,
1165
+ refreshToken: token,
1166
+ refreshTime: util_default.unixTimestamp() + ACCESS_TOKEN_EXPIRES
1167
+ };
1168
+ })().then((result2) => {
1169
+ if (accessTokenRequestQueueMap[refreshToken]) {
1170
+ accessTokenRequestQueueMap[refreshToken].forEach(
1171
+ (resolve) => resolve(result2)
1172
+ );
1173
+ delete accessTokenRequestQueueMap[refreshToken];
1174
+ }
1175
+ logger_default.success(`Refresh successful`);
1176
+ return result2;
1177
+ }).catch((err) => {
1178
+ if (accessTokenRequestQueueMap[refreshToken]) {
1179
+ accessTokenRequestQueueMap[refreshToken].forEach(
1180
+ (resolve) => resolve(err)
1181
+ );
1182
+ delete accessTokenRequestQueueMap[refreshToken];
1183
+ }
1184
+ return err;
1185
+ });
1186
+ if (import_lodash12.default.isError(result)) throw result;
1187
+ return result;
1188
+ }
1189
+ async function acquireToken(refreshToken) {
1190
+ let result = accessTokenMap.get(refreshToken);
1191
+ if (!result) {
1192
+ result = await requestToken(refreshToken);
1193
+ accessTokenMap.set(refreshToken, result);
1194
+ }
1195
+ if (util_default.unixTimestamp() > result.refreshTime) {
1196
+ result = await requestToken(refreshToken);
1197
+ accessTokenMap.set(refreshToken, result);
1198
+ }
1199
+ return result.accessToken;
1200
+ }
1201
+ async function clearContext(model, refreshToken) {
1202
+ const token = await acquireToken(refreshToken);
1203
+ const result = await import_axios2.default.post(
1204
+ "https://chat.deepseek.com/api/v0/chat/clear_context",
1205
+ {
1206
+ model_class: model,
1207
+ append_welcome_message: false
1208
+ },
1209
+ {
1210
+ headers: {
1211
+ Authorization: `Bearer ${token}`,
1212
+ ...FAKE_HEADERS
1213
+ },
1214
+ timeout: 15e3,
1215
+ validateStatus: () => true
1216
+ }
1217
+ );
1218
+ checkResult(result, refreshToken);
1219
+ }
1220
+ async function createCompletion(model = MODEL_NAME, messages, refreshToken, retryCount = 0) {
1221
+ return (async () => {
1222
+ logger_default.info(messages);
1223
+ const result = await chatLock.acquire(refreshToken, async () => {
1224
+ await clearContext(model, refreshToken);
1225
+ const token = await acquireToken(refreshToken);
1226
+ return await import_axios2.default.post(
1227
+ "https://chat.deepseek.com/api/v0/chat/completions",
1228
+ {
1229
+ message: messagesPrepare(messages),
1230
+ stream: true,
1231
+ model_preference: null,
1232
+ model_class: model,
1233
+ temperature: 0
1234
+ },
1235
+ {
1236
+ headers: {
1237
+ Authorization: `Bearer ${token}`,
1238
+ ...FAKE_HEADERS
1239
+ },
1240
+ // 120秒超时
1241
+ timeout: 12e4,
1242
+ validateStatus: () => true,
1243
+ responseType: "stream"
1244
+ }
1245
+ );
1246
+ });
1247
+ if (result.headers["content-type"].indexOf("text/event-stream") == -1) {
1248
+ result.data.on("data", (buffer) => logger_default.error(buffer.toString()));
1249
+ throw new APIException(
1250
+ exceptions_default.API_REQUEST_FAILED,
1251
+ `Stream response Content-Type invalid: ${result.headers["content-type"]}`
1252
+ );
1253
+ }
1254
+ const streamStartTime = util_default.timestamp();
1255
+ const answer = await receiveStream(model, result.data);
1256
+ logger_default.success(
1257
+ `Stream has completed transfer ${util_default.timestamp() - streamStartTime}ms`
1258
+ );
1259
+ return answer;
1260
+ })().catch((err) => {
1261
+ if (retryCount < MAX_RETRY_COUNT) {
1262
+ logger_default.error(`Stream response error: ${err.stack}`);
1263
+ logger_default.warn(`Try again after ${RETRY_DELAY / 1e3}s...`);
1264
+ return (async () => {
1265
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
1266
+ return createCompletion(
1267
+ model,
1268
+ messages,
1269
+ refreshToken,
1270
+ retryCount + 1
1271
+ );
1272
+ })();
1273
+ }
1274
+ throw err;
1275
+ });
1276
+ }
1277
+ async function createCompletionStream(model = MODEL_NAME, messages, refreshToken, retryCount = 0) {
1278
+ return (async () => {
1279
+ logger_default.info(messages);
1280
+ const result = await chatLock.acquire(refreshToken, async () => {
1281
+ await clearContext(model, refreshToken);
1282
+ const token = await acquireToken(refreshToken);
1283
+ return await import_axios2.default.post(
1284
+ "https://chat.deepseek.com/api/v0/chat/completions",
1285
+ {
1286
+ message: messagesPrepare(messages),
1287
+ stream: true,
1288
+ model_preference: null,
1289
+ model_class: model,
1290
+ temperature: 0
1291
+ },
1292
+ {
1293
+ headers: {
1294
+ Authorization: `Bearer ${token}`,
1295
+ ...FAKE_HEADERS
1296
+ },
1297
+ // 120秒超时
1298
+ timeout: 12e4,
1299
+ validateStatus: () => true,
1300
+ responseType: "stream"
1301
+ }
1302
+ );
1303
+ });
1304
+ if (result.headers["content-type"].indexOf("text/event-stream") == -1) {
1305
+ logger_default.error(
1306
+ `Invalid response Content-Type:`,
1307
+ result.headers["content-type"]
1308
+ );
1309
+ result.data.on("data", (buffer) => logger_default.error(buffer.toString()));
1310
+ const transStream = new import_stream2.PassThrough();
1311
+ transStream.end(
1312
+ `data: ${JSON.stringify({
1313
+ id: "",
1314
+ model: MODEL_NAME,
1315
+ object: "chat.completion.chunk",
1316
+ choices: [
1317
+ {
1318
+ index: 0,
1319
+ delta: {
1320
+ role: "assistant",
1321
+ content: "\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u7B2C\u4E09\u65B9\u54CD\u5E94\u9519\u8BEF"
1322
+ },
1323
+ finish_reason: "stop"
1324
+ }
1325
+ ],
1326
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
1327
+ created: util_default.unixTimestamp()
1328
+ })}
1329
+
1330
+ `
1331
+ );
1332
+ return transStream;
1333
+ }
1334
+ const streamStartTime = util_default.timestamp();
1335
+ return createTransStream(model, result.data, () => {
1336
+ logger_default.success(
1337
+ `Stream has completed transfer ${util_default.timestamp() - streamStartTime}ms`
1338
+ );
1339
+ });
1340
+ })().catch((err) => {
1341
+ if (retryCount < MAX_RETRY_COUNT) {
1342
+ logger_default.error(`Stream response error: ${err.stack}`);
1343
+ logger_default.warn(`Try again after ${RETRY_DELAY / 1e3}s...`);
1344
+ return (async () => {
1345
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
1346
+ return createCompletionStream(
1347
+ model,
1348
+ messages,
1349
+ refreshToken,
1350
+ retryCount + 1
1351
+ );
1352
+ })();
1353
+ }
1354
+ throw err;
1355
+ });
1356
+ }
1357
+ function messagesPrepare(messages) {
1358
+ let content;
1359
+ if (messages.length < 2) {
1360
+ content = messages.reduce((content2, message) => {
1361
+ if (import_lodash12.default.isArray(message.content)) {
1362
+ return message.content.reduce((_content, v) => {
1363
+ if (!import_lodash12.default.isObject(v) || v["type"] != "text") return _content;
1364
+ return _content + (v["text"] || "") + "\n";
1365
+ }, content2);
1366
+ }
1367
+ return content2 + `${message.content}
1368
+ `;
1369
+ }, "");
1370
+ logger_default.info("\n\u900F\u4F20\u5185\u5BB9\uFF1A\n" + content);
1371
+ } else {
1372
+ content = (messages.reduce((content2, message) => {
1373
+ if (import_lodash12.default.isArray(message.content)) {
1374
+ return message.content.reduce((_content, v) => {
1375
+ if (!import_lodash12.default.isObject(v) || v["type"] != "text") return _content;
1376
+ return _content + (`${message.role}:` + v["text"] || "") + "\n";
1377
+ }, content2);
1378
+ }
1379
+ return content2 += `${message.role}:${message.content}
1380
+ `;
1381
+ }, "") + "assistant:").replace(/\!\[.+\]\(.+\)/g, "");
1382
+ logger_default.info("\n\u5BF9\u8BDD\u5408\u5E76\uFF1A\n" + content);
1383
+ }
1384
+ return content;
1385
+ }
1386
+ function checkResult(result, refreshToken) {
1387
+ if (!result.data) return null;
1388
+ const { code, data, msg } = result.data;
1389
+ if (!import_lodash12.default.isFinite(code)) return result.data;
1390
+ if (code === 0) return data;
1391
+ if (code == 40003) accessTokenMap.delete(refreshToken);
1392
+ throw new APIException(exceptions_default.API_REQUEST_FAILED, `[\u8BF7\u6C42deepseek\u5931\u8D25]: ${msg}`);
1393
+ }
1394
+ async function receiveStream(model, stream) {
1395
+ return new Promise((resolve, reject) => {
1396
+ const data = {
1397
+ id: "",
1398
+ model,
1399
+ object: "chat.completion",
1400
+ choices: [
1401
+ {
1402
+ index: 0,
1403
+ message: { role: "assistant", content: "" },
1404
+ finish_reason: "stop"
1405
+ }
1406
+ ],
1407
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
1408
+ created: util_default.unixTimestamp()
1409
+ };
1410
+ const parser = (0, import_eventsource_parser.createParser)((event) => {
1411
+ try {
1412
+ if (event.type !== "event") return;
1413
+ const result = import_lodash12.default.attempt(() => JSON.parse(event.data));
1414
+ if (import_lodash12.default.isError(result))
1415
+ throw new Error(`Stream response invalid: ${event.data}`);
1416
+ if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == " ")
1417
+ return;
1418
+ data.choices[0].message.content += result.choices[0].delta.content;
1419
+ if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop")
1420
+ resolve(data);
1421
+ } catch (err) {
1422
+ logger_default.error(err);
1423
+ reject(err);
1424
+ }
1425
+ });
1426
+ stream.on("data", (buffer) => parser.feed(buffer.toString()));
1427
+ stream.once("error", (err) => reject(err));
1428
+ stream.once("close", () => resolve(data));
1429
+ });
1430
+ }
1431
+ function createTransStream(model, stream, endCallback) {
1432
+ const created = util_default.unixTimestamp();
1433
+ const transStream = new import_stream2.PassThrough();
1434
+ !transStream.closed && transStream.write(
1435
+ `data: ${JSON.stringify({
1436
+ id: "",
1437
+ model,
1438
+ object: "chat.completion.chunk",
1439
+ choices: [
1440
+ {
1441
+ index: 0,
1442
+ delta: { role: "assistant", content: "" },
1443
+ finish_reason: null
1444
+ }
1445
+ ],
1446
+ created
1447
+ })}
1448
+
1449
+ `
1450
+ );
1451
+ const parser = (0, import_eventsource_parser.createParser)((event) => {
1452
+ try {
1453
+ if (event.type !== "event") return;
1454
+ const result = import_lodash12.default.attempt(() => JSON.parse(event.data));
1455
+ if (import_lodash12.default.isError(result))
1456
+ throw new Error(`Stream response invalid: ${event.data}`);
1457
+ if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == " ")
1458
+ return;
1459
+ result.model = model;
1460
+ transStream.write(`data: ${JSON.stringify({
1461
+ id: result.id,
1462
+ model: result.model,
1463
+ object: "chat.completion.chunk",
1464
+ choices: [
1465
+ {
1466
+ index: 0,
1467
+ delta: { role: "assistant", content: result.choices[0].delta.content },
1468
+ finish_reason: null
1469
+ }
1470
+ ],
1471
+ created
1472
+ })}
1473
+
1474
+ `);
1475
+ if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop") {
1476
+ transStream.write(`data: ${JSON.stringify({
1477
+ id: result.id,
1478
+ model: result.model,
1479
+ object: "chat.completion.chunk",
1480
+ choices: [
1481
+ {
1482
+ index: 0,
1483
+ delta: { role: "assistant", content: "" },
1484
+ finish_reason: "stop"
1485
+ }
1486
+ ],
1487
+ created
1488
+ })}
1489
+
1490
+ `);
1491
+ !transStream.closed && transStream.end("data: [DONE]\n\n");
1492
+ }
1493
+ } catch (err) {
1494
+ logger_default.error(err);
1495
+ !transStream.closed && transStream.end("data: [DONE]\n\n");
1496
+ }
1497
+ });
1498
+ stream.on("data", (buffer) => parser.feed(buffer.toString()));
1499
+ stream.once(
1500
+ "error",
1501
+ () => !transStream.closed && transStream.end("data: [DONE]\n\n")
1502
+ );
1503
+ stream.once(
1504
+ "close",
1505
+ () => !transStream.closed && transStream.end("data: [DONE]\n\n")
1506
+ );
1507
+ return transStream;
1508
+ }
1509
+ function tokenSplit(authorization) {
1510
+ return authorization.replace("Bearer ", "").split(",");
1511
+ }
1512
+ async function getTokenLiveStatus(refreshToken) {
1513
+ const token = await acquireToken(refreshToken);
1514
+ const result = await import_axios2.default.get(
1515
+ "https://chat.deepseek.com/api/v0/users/current",
1516
+ {
1517
+ headers: {
1518
+ Authorization: `Bearer ${token}`,
1519
+ ...FAKE_HEADERS
1520
+ },
1521
+ timeout: 15e3,
1522
+ validateStatus: () => true
1523
+ }
1524
+ );
1525
+ try {
1526
+ const { token: token2 } = checkResult(result, refreshToken);
1527
+ return !!token2;
1528
+ } catch (err) {
1529
+ return false;
1530
+ }
1531
+ }
1532
+ var chat_default = {
1533
+ createCompletion,
1534
+ createCompletionStream,
1535
+ getTokenLiveStatus,
1536
+ tokenSplit
1537
+ };
1538
+
1539
+ // src/api/routes/chat.ts
1540
+ var chat_default2 = {
1541
+ prefix: "/v1/chat",
1542
+ post: {
1543
+ "/completions": async (request) => {
1544
+ request.validate("body.conversation_id", (v) => import_lodash13.default.isUndefined(v) || import_lodash13.default.isString(v)).validate("body.messages", import_lodash13.default.isArray).validate("headers.authorization", import_lodash13.default.isString);
1545
+ const tokens = chat_default.tokenSplit(request.headers.authorization);
1546
+ const token = import_lodash13.default.sample(tokens);
1547
+ let { model, messages, stream } = request.body;
1548
+ if (["deepseek_chat", "deepseek_code", "deepseek-chat*", "deepseek-chat", "deepseek-coder"].includes(model))
1549
+ model = {
1550
+ "deepseek-chat*": "deepseek_chat",
1551
+ "deepseek-chat": "deepseek_chat",
1552
+ "deepseek-coder": "deepseek_code"
1553
+ }[model] || model;
1554
+ else
1555
+ model = "deepseek_chat";
1556
+ if (stream) {
1557
+ const stream2 = await chat_default.createCompletionStream(model, messages, token);
1558
+ return new Response(stream2, {
1559
+ type: "text/event-stream"
1560
+ });
1561
+ } else
1562
+ return await chat_default.createCompletion(model, messages, token);
1563
+ }
1564
+ }
1565
+ };
1566
+
1567
+ // src/api/routes/ping.ts
1568
+ var ping_default = {
1569
+ prefix: "/ping",
1570
+ get: {
1571
+ "": async () => "pong"
1572
+ }
1573
+ };
1574
+
1575
+ // src/api/routes/token.ts
1576
+ var import_lodash14 = __toESM(require("lodash"), 1);
1577
+ var token_default = {
1578
+ prefix: "/token",
1579
+ post: {
1580
+ "/check": async (request) => {
1581
+ request.validate("body.token", import_lodash14.default.isString);
1582
+ const live = await chat_default.getTokenLiveStatus(request.body.token);
1583
+ return {
1584
+ live
1585
+ };
1586
+ }
1587
+ }
1588
+ };
1589
+
1590
+ // src/api/routes/models.ts
1591
+ var models_default = {
1592
+ prefix: "/v1",
1593
+ get: {
1594
+ "/models": async () => {
1595
+ return {
1596
+ "data": [
1597
+ {
1598
+ "id": "deepseek-chat",
1599
+ "object": "model",
1600
+ "owned_by": "deepseek-free-api"
1601
+ },
1602
+ {
1603
+ "id": "deepseek-coder",
1604
+ "object": "model",
1605
+ "owned_by": "deepseek-free-api"
1606
+ }
1607
+ ]
1608
+ };
1609
+ }
1610
+ }
1611
+ };
1612
+
1613
+ // src/api/routes/index.ts
1614
+ var routes_default = [
1615
+ {
1616
+ get: {
1617
+ "/": async () => {
1618
+ const content = await import_fs_extra6.default.readFile("public/welcome.html");
1619
+ return new Response(content, {
1620
+ type: "html",
1621
+ headers: {
1622
+ Expires: "-1"
1623
+ }
1624
+ });
1625
+ }
1626
+ }
1627
+ },
1628
+ chat_default2,
1629
+ ping_default,
1630
+ token_default,
1631
+ models_default
1632
+ ];
1633
+
1634
+ // src/index.ts
1635
+ var startupTime = performance.now();
1636
+ (async () => {
1637
+ logger_default.header();
1638
+ logger_default.info("<<<< deepseek free server >>>>");
1639
+ logger_default.info("Version:", environment_default.package.version);
1640
+ logger_default.info("Process id:", process.pid);
1641
+ logger_default.info("Environment:", environment_default.env);
1642
+ logger_default.info("Service name:", config_default.service.name);
1643
+ server_default.attachRoutes(routes_default);
1644
+ await server_default.listen();
1645
+ config_default.service.bindAddress && logger_default.success("Service bind address:", config_default.service.bindAddress);
1646
+ })().then(
1647
+ () => logger_default.success(
1648
+ `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)`
1649
+ )
1650
+ ).catch((err) => console.error(err));
1651
+ //# sourceMappingURL=index.cjs.map
dist/index.cjs.map ADDED
The diff for this file is too large to render. See raw diff
 
dist/index.d.cts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+
2
+ export { }
dist/index.d.ts ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+
2
+ export { }
dist/index.js ADDED
@@ -0,0 +1,1627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // src/lib/environment.ts
2
+ import path from "path";
3
+ import fs from "fs-extra";
4
+ import minimist from "minimist";
5
+ import _ from "lodash";
6
+ var cmdArgs = minimist(process.argv.slice(2));
7
+ var envVars = process.env;
8
+ var Environment = class {
9
+ /** 命令行参数 */
10
+ cmdArgs;
11
+ /** 环境变量 */
12
+ envVars;
13
+ /** 环境名称 */
14
+ env;
15
+ /** 服务名称 */
16
+ name;
17
+ /** 服务地址 */
18
+ host;
19
+ /** 服务端口 */
20
+ port;
21
+ /** 包参数 */
22
+ package;
23
+ constructor(options = {}) {
24
+ const { cmdArgs: cmdArgs2, envVars: envVars2, package: _package } = options;
25
+ this.cmdArgs = cmdArgs2;
26
+ this.envVars = envVars2;
27
+ this.env = _.defaultTo(cmdArgs2.env || envVars2.SERVER_ENV, "dev");
28
+ this.name = cmdArgs2.name || envVars2.SERVER_NAME || void 0;
29
+ this.host = cmdArgs2.host || envVars2.SERVER_HOST || void 0;
30
+ this.port = Number(cmdArgs2.port || envVars2.SERVER_PORT) ? Number(cmdArgs2.port || envVars2.SERVER_PORT) : void 0;
31
+ this.package = _package;
32
+ }
33
+ };
34
+ var environment_default = new Environment({
35
+ cmdArgs,
36
+ envVars,
37
+ package: JSON.parse(fs.readFileSync(path.join(path.resolve(), "package.json")).toString())
38
+ });
39
+
40
+ // src/lib/configs/service-config.ts
41
+ import path3 from "path";
42
+ import fs3 from "fs-extra";
43
+ import yaml from "yaml";
44
+ import _3 from "lodash";
45
+
46
+ // src/lib/util.ts
47
+ import os from "os";
48
+ import path2 from "path";
49
+ import crypto from "crypto";
50
+ import { Readable, Writable } from "stream";
51
+ import "colors";
52
+ import mime from "mime";
53
+ import axios from "axios";
54
+ import fs2 from "fs-extra";
55
+ import { v1 as uuid } from "uuid";
56
+ import { format as dateFormat } from "date-fns";
57
+ import CRC32 from "crc-32";
58
+ import randomstring from "randomstring";
59
+ import _2 from "lodash";
60
+ import { CronJob } from "cron";
61
+
62
+ // src/lib/http-status-codes.ts
63
+ var http_status_codes_default = {
64
+ CONTINUE: 100,
65
+ //客户端应当继续发送请求。这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝。客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应
66
+ SWITCHING_PROTOCOLS: 101,
67
+ //服务器已经理解了客户端的请求,并将通过Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后,服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。例如,切换到新的HTTP 版本比旧版本更有优势,或者切换到一个实时且同步的协议以传送利用此类特性的资源
68
+ PROCESSING: 102,
69
+ //处理将被继续执行
70
+ OK: 200,
71
+ //请求已成功,请求所希望的响应头或数据体将随此响应返回
72
+ CREATED: 201,
73
+ //请求已经被实现,而且有一个新的资源已经依据请求的需要而建立,且其 URI 已经随Location 头信息返回。假如需要的资源无法及时建立的话,应当返回 '202 Accepted'
74
+ ACCEPTED: 202,
75
+ //服务器已接受请求,但尚未处理。正如它可能被拒绝一样,最终该请求可能会也可能不会被执行。在异步操作的场合下,没有比发送这个状态码更方便的做法了。返回202状态码的响应的目的是允许服务器接受其他过程的请求(例如某个每天只执行一次的基于批处理的操作),而不必让客户端一直保持与服务器的连接直到批处理操作全部完成。在接受请求处理并返回202状态码的响应应当在返回的实体中包含一些指示处理当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便用户能够估计操作是否已经完成
76
+ NON_AUTHORITATIVE_INFO: 203,
77
+ //服务器已成功处理了请求,但返回的实体头部元信息不是在原始服务器上有效的确定集合,而是来自本地或者第三方的拷贝。当前的信息可能是原始版本的子集或者超集。例如,包含资源的元数据可能导致原始服务器知道元信息的超级。使用此状态码不是必须的,而且只有在响应不使用此状态码便会返回200 OK的情况下才是合适的
78
+ NO_CONTENT: 204,
79
+ //服务器成功处理了请求,但不需要返回任何实体内容,并且希望返回更新了的元信息。响应可能通过实体头部的形式,返回新的或更新后的元信息。如果存在这些头部信息,则应当与所请求的变量相呼应。如果客户端是浏览器的话,那么用户浏览器应保留发送了该请求的页面,而不产生任何文档视图上的变化,即使按照规范新的或更新后的元信息应当被应用到用户浏览器活动视图中的文档。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾
80
+ RESET_CONTENT: 205,
81
+ //服务器成功处理了请求,且没有返回任何内容。但是与204响应不同,返回此状态码的响应要求请求者重置文档视图。该响应主要是被用于接受用户输入后,立即重置表单,以便用户能够轻松地开始另一次输入。与204响应一样,该响应也被禁止包含任何消息体,且以消息头后的第一个空行结束
82
+ PARTIAL_CONTENT: 206,
83
+ //服务器已经成功处理了部分 GET 请求。类似于FlashGet或者迅雷这类的HTTP下载工具都是使用此类响应实现断点续传或者将一个大文档分解为多个下载段同时下载。该请求必须包含 Range 头信息来指示客户端希望得到的内容范围,并且可能包含 If-Range 来作为请求条件。响应必须包含如下的头部域:Content-Range 用以指示本次响应中返回的内容的范围;如果是Content-Type为multipart/byteranges的多段下载,则每一段multipart中都应包含Content-Range域用以指示本段的内容范围。假如响应中包含Content-Length,那么它的数值必须匹配它返回的内容范围的真实字节数。Date和ETag或Content-Location,假如同样的请求本应该返回200响应。Expires, Cache-Control,和/或 Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了 If-Range 强缓存验证,那么本次响应不应该包含其他实体头;假如本响应的请求使用了 If-Range 弱缓存验证,那么本次响应禁止包含其他实体头;这避免了缓存的实体内容和更新了的实体头信息之间的不一致。否则,本响应就应当包含所有本应该返回200响应中应当返回的所有实体头部域。假如 ETag 或 Latest-Modified 头部不能精确匹配的话,则客户端缓存应禁止将206响应返回的内容与之前任何缓存过的内容组合在一起。任何不支持 Range 以及 Content-Range 头的缓存都禁止缓存206响应返回的内容
84
+ MULTIPLE_STATUS: 207,
85
+ //代表之后的消息体将是一个XML消息,并且可能依照之前子请求数量的不同,包含一系列独立的响应代码
86
+ MULTIPLE_CHOICES: 300,
87
+ //被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。除非这是一个HEAD请求,否则该响应应当包括一个资源特性及地址的列表的实体,以便用户或浏览器从中选择最合适的重定向地址。这个实体的格式由Content-Type定义的格式所决定。浏览器可能根据响应的格式以及浏览器自身能力,自动作出最合适的选择。当然,RFC 2616规范并没有规定这样的自动选择该如何进行。如果服务器本身已经有了首选的回馈选择,那么在Location中应当指明这个回馈的 URI;浏览器可能会将这个 Location 值作为自动重定向的地址。此外,除非额外指定,否则这个响应也是可缓存的
88
+ MOVED_PERMANENTLY: 301,
89
+ //被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。新的永久性的URI应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,因此浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:对于某些使用 HTTP/1.0 协议的浏览器,当它们发送的POST请求得到了一个301响应的话,接下来的重定向请求将会变成GET方式
90
+ FOUND: 302,
91
+ //请求的资源现在临时从不同的URI响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI应当在响应的 Location 域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:虽然RFC 1945和RFC 2068规范不允许客户端在重定向时改变请求的方法,但是很多现存的浏览器将302响应视作为303响应,并且使用GET方式访问在Location中规定的URI,而无视原先请求的方法。状态码303和307被添加了进来,用以明确服务器期待客户端进行何种反应
92
+ SEE_OTHER: 303,
93
+ //对应当前请求的响应可以在另一个URI上被找到,而且客户端应当采用 GET 的方式访问那个资源。这个方法的存在主要是为了允许由脚本激活的POST请求输出重定向到一个新的资源。这个新的 URI 不是原始资源的替代引用。同时,303响应禁止被缓存。当然,第二个请求(��定向)可能被缓存。新的 URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。注意:许多 HTTP/1.1 版以前的浏览器不能正确理解303状态。如果需要考虑与这些浏览器之间的互动,302状态码应该可以胜任,因为大多数的浏览器处理302响应时的方式恰恰就是上述规范要求客户端处理303响应时应当做的
94
+ NOT_MODIFIED: 304,
95
+ //如果客户端发送了一个带条件的GET请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个状态码。304响应禁止包含消息体,因此始终以消息头后的第一个空行结尾。该响应必须包含以下的头信息:Date,除非这个服务器没有时钟。假如没有时钟的服务器也遵守这些规则,那么代理服务器以及客户端可以自行将Date字段添加到接收到的响应头中去(正如RFC 2068中规定的一样),缓存机制将会正常工作。ETag或 Content-Location,假如同样的请求本应返回200响应。Expires, Cache-Control,和/或Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了强缓存验证,那么本次响应不应该包含其他实体头;否则(例如,某个带条件的 GET 请求使用了弱缓存验证),本次响应禁止包含其他实体头;这避免了缓存了的实体内容和更新了的实体头信息之间的不一致。假如某个304响应指明了当前某个实体没有缓存,那么缓存系统必须忽视这个响应,并且重复发送不包含限制条件的请求。假如接收到一个要求更新某个缓存条目的304响应,那么缓存系统必须更新整个条目以反映所有在响应中被更新的字段的值
96
+ USE_PROXY: 305,
97
+ //被请求的资源必须通过指定的代理才能被访问。Location域中将给出指定的代理所在的URI信息,接收者需要重复发送一个单独的请求,通过这个代理才能访问相应资源。只有原始服务器才能建立305响应。注意:RFC 2068中没有明确305响应是为了重定向一个单独的请求,而且只能被原始服务器建立。忽视这些限制可能导致严重的安全后果
98
+ UNUSED: 306,
99
+ //在最新版的规范中,306状态码已经不再被使用
100
+ TEMPORARY_REDIRECT: 307,
101
+ //请求的资源现在临时从不同的URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI 的超链接及简短说明。因为部分浏览器不能识别307响应,因此需要添加上述必要信息以便用户能够理解并向新的 URI 发出访问请求。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化
102
+ BAD_REQUEST: 400,
103
+ //1.语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求 2.请求参数有误
104
+ UNAUTHORIZED: 401,
105
+ //当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617
106
+ PAYMENT_REQUIRED: 402,
107
+ //该状态码是为了将来可能的需求而预留的
108
+ FORBIDDEN: 403,
109
+ //服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个HEAD请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息
110
+ NOT_FOUND: 404,
111
+ //请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下
112
+ METHOD_NOT_ALLOWED: 405,
113
+ //请求行中指定的请求方法不能被用于请求相应的资源。该响应必须返回一个Allow 头信息用以表示出当前资源能够接受的请求方法的列表。鉴于PUT,DELETE方法会对服务器上的资源进行写操作,因而绝大部分的网页服务器都不支持或者在默认配置下不允许上述请求方法,对于此类请求均会返回405错误
114
+ NO_ACCEPTABLE: 406,
115
+ //请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体。除非这是一个 HEAD 请求,否则该响应就应当返回一个包含可以让用户或者浏览器从中选择最合适的实体特性以及地址列表的实体。实体的格式由Content-Type头中定义的媒体类型决定。浏览器可以根据格式及自身能力自行作出最佳选择。但是,规范中并没有定义任何作出此类自动选择的标准
116
+ PROXY_AUTHENTICATION_REQUIRED: 407,
117
+ //与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个Proxy-Authenticate用以进行身份询问。客户端可以返回一个Proxy-Authorization信息头用以验证。参见RFC 2617
118
+ REQUEST_TIMEOUT: 408,
119
+ //请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改
120
+ CONFLICT: 409,
121
+ //由于和被请求的资源的当前状态之间存在冲突,请求无法完成。这个代码只允许用在这样的情况下才能被使用:用户被认为能够解决冲突,并且会重新提交新的请求。该响应应当包含足够的信息以便用户发现冲突的源头。冲突通常发生于对PUT请求的处理中。例如,在采用版本检查的环境下,某次PUT提交的对特定资源的修改请求所附带的版本信息与之前的某个(第三方)请求向冲突,那么此时服务器就应该返回一个409错误,告知用户请求无法完成。此时,响应实体中很可能会包含两个冲突版本之间的差异比较,以便用户重新提交归并以后的新版本
122
+ GONE: 410,
123
+ //被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址。这样的状况应当被认为是永久性的。如果可能,拥有链接编辑功能的客户端应当在获得用户许可后删除所有指向这个地址的引用。如果服务器不知道或者无法确定这个状况是否是永久的,那么就应该使用404状态码。除非额外说明,否则这个响应是可缓存的。410响应的目的主要是帮助网站管理员维护网站,通知用户该资源已经不再可用,并且服务器拥有者希望所有指向这个资源的远端连接也被删除。这类事件在限时、增值服务中很普遍。同样,410响应也被用于通知客户端在当前服务器站点上,原本属于某个个人的资源已经不再可用。当然,是否需要把所有永久不可用的资源标记为'410 Gone',以及是否需要保持此标记多长时间,完全取决于服务器拥有者
124
+ LENGTH_REQUIRED: 411,
125
+ //服务器拒绝在没有定义Content-Length头的情况下接受请求。在添加了表明请求消息体长度的有效Content-Length头之后,客户端可以再次提交该请求
126
+ PRECONDITION_FAILED: 412,
127
+ //服务器在验证在请求的头字段中给出先决条件时,没能满足其中的一个或多个。这个状态码允许客户端在获取资源时在请求的元信息(请求头字段数据)中设置先决条件,以此避免该请求方法被应用到其希望的内容以外的资源上
128
+ REQUEST_ENTITY_TOO_LARGE: 413,
129
+ //服务器拒绝处理当前请求,因为该请求提交的实体数据大小超过了服务器愿意或者能够处理的范围。此种情况下,服务器可以关闭连接以免客户端继续发送此请求。如果这个状况是临时的,服务器应当返回一个 Retry-After 的响应头,以告知客户端可以在多少时间以后重新尝试
130
+ REQUEST_URI_TOO_LONG: 414,
131
+ //请求的URI长度超过了服务器能够解释的长度,因此服务器拒绝对该请求提供服务。这比较少见,通常的情况包括:本应使用POST方法的表单提交变成了GET方法,导致查询字符串(Query String)过长。重定向URI “黑洞”,例如每次重定向把旧的URI作为新的URI的一部分,导致在若干次重定向后URI超长。客户端正在尝试利用某些服务器中存在的安全漏洞攻击服务器。这类服务器使用固定长度的缓冲读取或操作请求的URI,当GET后的参数超过某个数值后,可能会产生缓冲区溢出,导致任意代码被执行[1]。没有此类漏洞的服务器,应当返回414状态码
132
+ UNSUPPORTED_MEDIA_TYPE: 415,
133
+ //对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
134
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416,
135
+ //如果请求中包含了Range请求头,并且Range中指定的任何���据范围都与当前资源的可用范围不重合,同时请求中又没有定义If-Range请求头,那么服务器就应当返回416状态码。假如Range使用的是字节范围,那么这种情况就是指请求指定的所有数据范围的首字节位置都超过了当前资源的长度。服务器也应当在返回416状态码的同时,包含一个Content-Range实体头,用以指明当前资源的长度。这个响应也被禁止使用multipart/byteranges作为其 Content-Type
136
+ EXPECTION_FAILED: 417,
137
+ //在请求头Expect中指定的预期内容无法被服务器满足,或者这个服务器是一个代理服务器,它有明显的证据证明在当前路由的下一个节点上,Expect的内容无法被满足
138
+ TOO_MANY_CONNECTIONS: 421,
139
+ //从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围。通常,这里的IP地址指的是从服务器上看到的客户端地址(比如用户的网关或者代理服务器地址)。在这种情况下,连接数的计算可能涉及到不止一个终端用户
140
+ UNPROCESSABLE_ENTITY: 422,
141
+ //请求格式正确,但是由于含有语义错误,无法响应
142
+ FAILED_DEPENDENCY: 424,
143
+ //由于之前的某个请求发生的错误,导致当前请求失败,例如PROPPATCH
144
+ UNORDERED_COLLECTION: 425,
145
+ //在WebDav Advanced Collections 草案中定义,但是未出现在《WebDAV 顺序集协议》(RFC 3658)中
146
+ UPGRADE_REQUIRED: 426,
147
+ //客户端应当切换到TLS/1.0
148
+ RETRY_WITH: 449,
149
+ //由微软扩展,代表请求应当在执行完适当的操作后进行重试
150
+ INTERNAL_SERVER_ERROR: 500,
151
+ //服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现
152
+ NOT_IMPLEMENTED: 501,
153
+ //服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法,并且无法支持其对任何资源的请求
154
+ BAD_GATEWAY: 502,
155
+ //作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应
156
+ SERVICE_UNAVAILABLE: 503,
157
+ //由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 Retry-After 头用以标明这个延迟时间。如果没有给出这个 Retry-After 信息,那么客户端应当以处理500响应的方式处理它。注意:503状态码的存在并不意味着服务器在过载的时候必须使用它。某些服务器只不过是希望拒绝客户端的连接
158
+ GATEWAY_TIMEOUT: 504,
159
+ //作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应。注意:某些代理服务器在DNS查询超时时会返回400或者500错误
160
+ HTTP_VERSION_NOT_SUPPORTED: 505,
161
+ //服务器不支持,或者拒绝支持在请求中使用的HTTP版本。这暗示着服务器不能或不愿使用与客户端相同的版本。响应中应当包含一个描述了为何版本不被支持以及服务器支持哪些协议的实体
162
+ VARIANT_ALSO_NEGOTIATES: 506,
163
+ //服务器存在内部配置错误:被请求的协商变元资源被配置为在透明内容协商中使用自己,因此在一个协商处理中不是一个合适的重点
164
+ INSUFFICIENT_STORAGE: 507,
165
+ //服务器无法存储完成请求所必须的内容。这个状况被认为是临时的
166
+ BANDWIDTH_LIMIT_EXCEEDED: 509,
167
+ //服务器达到带宽限制。这不是一个官方的状态码,但是仍被广泛使用
168
+ NOT_EXTENDED: 510
169
+ //获取资源所需要的策略并没有没满足
170
+ };
171
+
172
+ // src/lib/util.ts
173
+ var autoIdMap = /* @__PURE__ */ new Map();
174
+ var util = {
175
+ is2DArrays(value) {
176
+ return _2.isArray(value) && (!value[0] || _2.isArray(value[0]) && _2.isArray(value[value.length - 1]));
177
+ },
178
+ uuid: (separator = true) => separator ? uuid() : uuid().replace(/\-/g, ""),
179
+ autoId: (prefix = "") => {
180
+ let index = autoIdMap.get(prefix);
181
+ if (index > 999999) index = 0;
182
+ autoIdMap.set(prefix, (index || 0) + 1);
183
+ return `${prefix}${index || 1}`;
184
+ },
185
+ ignoreJSONParse(value) {
186
+ const result = _2.attempt(() => JSON.parse(value));
187
+ if (_2.isError(result)) return null;
188
+ return result;
189
+ },
190
+ generateRandomString(options) {
191
+ return randomstring.generate(options);
192
+ },
193
+ getResponseContentType(value) {
194
+ return value.headers ? value.headers["content-type"] || value.headers["Content-Type"] : null;
195
+ },
196
+ mimeToExtension(value) {
197
+ let extension = mime.getExtension(value);
198
+ if (extension == "mpga") return "mp3";
199
+ return extension;
200
+ },
201
+ extractURLExtension(value) {
202
+ const extname = path2.extname(new URL(value).pathname);
203
+ return extname.substring(1).toLowerCase();
204
+ },
205
+ createCronJob(cronPatterns, callback) {
206
+ if (!_2.isFunction(callback))
207
+ throw new Error("callback must be an Function");
208
+ return new CronJob(
209
+ cronPatterns,
210
+ () => callback(),
211
+ null,
212
+ false,
213
+ "Asia/Shanghai"
214
+ );
215
+ },
216
+ getDateString(format = "yyyy-MM-dd", date = /* @__PURE__ */ new Date()) {
217
+ return dateFormat(date, format);
218
+ },
219
+ getIPAddressesByIPv4() {
220
+ const interfaces = os.networkInterfaces();
221
+ const addresses = [];
222
+ for (let name in interfaces) {
223
+ const networks = interfaces[name];
224
+ const results = networks.filter(
225
+ (network) => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal
226
+ );
227
+ if (results[0] && results[0].address) addresses.push(results[0].address);
228
+ }
229
+ return addresses;
230
+ },
231
+ getMACAddressesByIPv4() {
232
+ const interfaces = os.networkInterfaces();
233
+ const addresses = [];
234
+ for (let name in interfaces) {
235
+ const networks = interfaces[name];
236
+ const results = networks.filter(
237
+ (network) => network.family === "IPv4" && network.address !== "127.0.0.1" && !network.internal
238
+ );
239
+ if (results[0] && results[0].mac) addresses.push(results[0].mac);
240
+ }
241
+ return addresses;
242
+ },
243
+ generateSSEData(event, data, retry) {
244
+ return `event: ${event || "message"}
245
+ data: ${(data || "").replace(/\n/g, "\\n").replace(/\s/g, "\\s")}
246
+ retry: ${retry || 3e3}
247
+
248
+ `;
249
+ },
250
+ buildDataBASE64(type, ext, buffer) {
251
+ return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString(
252
+ "base64"
253
+ )}`;
254
+ },
255
+ isLinux() {
256
+ return os.platform() !== "win32";
257
+ },
258
+ isIPAddress(value) {
259
+ return _2.isString(value) && (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(
260
+ value
261
+ ) || /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(
262
+ value
263
+ ));
264
+ },
265
+ isPort(value) {
266
+ return _2.isNumber(value) && value > 0 && value < 65536;
267
+ },
268
+ isReadStream(value) {
269
+ return value && (value instanceof Readable || "readable" in value || value.readable);
270
+ },
271
+ isWriteStream(value) {
272
+ return value && (value instanceof Writable || "writable" in value || value.writable);
273
+ },
274
+ isHttpStatusCode(value) {
275
+ return _2.isNumber(value) && Object.values(http_status_codes_default).includes(value);
276
+ },
277
+ isURL(value) {
278
+ return !_2.isUndefined(value) && /^(http|https)/.test(value);
279
+ },
280
+ isSrc(value) {
281
+ return !_2.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value);
282
+ },
283
+ isBASE64(value) {
284
+ return !_2.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value);
285
+ },
286
+ isBASE64Data(value) {
287
+ return /^data:/.test(value);
288
+ },
289
+ extractBASE64DataFormat(value) {
290
+ const match = value.trim().match(/^data:(.+);base64,/);
291
+ if (!match) return null;
292
+ return match[1];
293
+ },
294
+ removeBASE64DataHeader(value) {
295
+ return value.replace(/^data:(.+);base64,/, "");
296
+ },
297
+ isDataString(value) {
298
+ return /^(base64|json):/.test(value);
299
+ },
300
+ isStringNumber(value) {
301
+ return _2.isFinite(Number(value));
302
+ },
303
+ isUnixTimestamp(value) {
304
+ return /^[0-9]{10}$/.test(`${value}`);
305
+ },
306
+ isTimestamp(value) {
307
+ return /^[0-9]{13}$/.test(`${value}`);
308
+ },
309
+ isEmail(value) {
310
+ return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
311
+ value
312
+ );
313
+ },
314
+ isAsyncFunction(value) {
315
+ return Object.prototype.toString.call(value) === "[object AsyncFunction]";
316
+ },
317
+ async isAPNG(filePath) {
318
+ let head;
319
+ const readStream = fs2.createReadStream(filePath, { start: 37, end: 40 });
320
+ const readPromise = new Promise((resolve, reject) => {
321
+ readStream.once("end", resolve);
322
+ readStream.once("error", reject);
323
+ });
324
+ readStream.once("data", (data) => head = data);
325
+ await readPromise;
326
+ return head.compare(Buffer.from([97, 99, 84, 76])) === 0;
327
+ },
328
+ unixTimestamp() {
329
+ return parseInt(`${Date.now() / 1e3}`);
330
+ },
331
+ timestamp() {
332
+ return Date.now();
333
+ },
334
+ urlJoin(...values) {
335
+ let url = "";
336
+ for (let i = 0; i < values.length; i++)
337
+ url += `${i > 0 ? "/" : ""}${values[i].replace(/^\/*/, "").replace(/\/*$/, "")}`;
338
+ return url;
339
+ },
340
+ millisecondsToHmss(milliseconds) {
341
+ if (_2.isString(milliseconds)) return milliseconds;
342
+ milliseconds = parseInt(milliseconds);
343
+ const sec = Math.floor(milliseconds / 1e3);
344
+ const hours = Math.floor(sec / 3600);
345
+ const minutes = Math.floor((sec - hours * 3600) / 60);
346
+ const seconds = sec - hours * 3600 - minutes * 60;
347
+ const ms = milliseconds % 6e4 - seconds * 1e3;
348
+ return `${hours > 9 ? hours : "0" + hours}:${minutes > 9 ? minutes : "0" + minutes}:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
349
+ },
350
+ millisecondsToTimeString(milliseconds) {
351
+ if (milliseconds < 1e3) return `${milliseconds}ms`;
352
+ if (milliseconds < 6e4)
353
+ return `${parseFloat((milliseconds / 1e3).toFixed(2))}s`;
354
+ return `${Math.floor(milliseconds / 1e3 / 60)}m${Math.floor(
355
+ milliseconds / 1e3 % 60
356
+ )}s`;
357
+ },
358
+ rgbToHex(r, g, b) {
359
+ return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
360
+ },
361
+ hexToRgb(hex) {
362
+ const value = parseInt(hex.replace(/^#/, ""), 16);
363
+ return [value >> 16 & 255, value >> 8 & 255, value & 255];
364
+ },
365
+ md5(value) {
366
+ return crypto.createHash("md5").update(value).digest("hex");
367
+ },
368
+ crc32(value) {
369
+ return _2.isBuffer(value) ? CRC32.buf(value) : CRC32.str(value);
370
+ },
371
+ arrayParse(value) {
372
+ return _2.isArray(value) ? value : [value];
373
+ },
374
+ booleanParse(value) {
375
+ return value === "true" || value === true ? true : false;
376
+ },
377
+ encodeBASE64(value) {
378
+ return Buffer.from(value).toString("base64");
379
+ },
380
+ decodeBASE64(value) {
381
+ return Buffer.from(value, "base64").toString();
382
+ },
383
+ async fetchFileBASE64(url) {
384
+ const result = await axios.get(url, {
385
+ responseType: "arraybuffer"
386
+ });
387
+ return result.data.toString("base64");
388
+ }
389
+ };
390
+ var util_default = util;
391
+
392
+ // src/lib/configs/service-config.ts
393
+ var CONFIG_PATH = path3.join(path3.resolve(), "configs/", environment_default.env, "/service.yml");
394
+ var ServiceConfig = class _ServiceConfig {
395
+ /** 服务名称 */
396
+ name;
397
+ /** @type {string} 服务绑定主机地址 */
398
+ host;
399
+ /** @type {number} 服务绑定端口 */
400
+ port;
401
+ /** @type {string} 服务路由前缀 */
402
+ urlPrefix;
403
+ /** @type {string} 服务绑定地址(外部访问地址) */
404
+ bindAddress;
405
+ constructor(options) {
406
+ const { name, host, port, urlPrefix, bindAddress } = options || {};
407
+ this.name = _3.defaultTo(name, "deepseek-free-api");
408
+ this.host = _3.defaultTo(host, "0.0.0.0");
409
+ this.port = _3.defaultTo(port, 5566);
410
+ this.urlPrefix = _3.defaultTo(urlPrefix, "");
411
+ this.bindAddress = bindAddress;
412
+ }
413
+ get addressHost() {
414
+ if (this.bindAddress) return this.bindAddress;
415
+ const ipAddresses = util_default.getIPAddressesByIPv4();
416
+ for (let ipAddress of ipAddresses) {
417
+ if (ipAddress === this.host)
418
+ return ipAddress;
419
+ }
420
+ return ipAddresses[0] || "127.0.0.1";
421
+ }
422
+ get address() {
423
+ return `${this.addressHost}:${this.port}`;
424
+ }
425
+ get pageDirUrl() {
426
+ return `http://127.0.0.1:${this.port}/page`;
427
+ }
428
+ get publicDirUrl() {
429
+ return `http://127.0.0.1:${this.port}/public`;
430
+ }
431
+ static load() {
432
+ const external = _3.pickBy(environment_default, (v, k) => ["name", "host", "port"].includes(k) && !_3.isUndefined(v));
433
+ if (!fs3.pathExistsSync(CONFIG_PATH)) return new _ServiceConfig(external);
434
+ const data = yaml.parse(fs3.readFileSync(CONFIG_PATH).toString());
435
+ return new _ServiceConfig({ ...data, ...external });
436
+ }
437
+ };
438
+ var service_config_default = ServiceConfig.load();
439
+
440
+ // src/lib/configs/system-config.ts
441
+ import path4 from "path";
442
+ import fs4 from "fs-extra";
443
+ import yaml2 from "yaml";
444
+ import _4 from "lodash";
445
+ var CONFIG_PATH2 = path4.join(path4.resolve(), "configs/", environment_default.env, "/system.yml");
446
+ var SystemConfig = class _SystemConfig {
447
+ /** 是否开启请求日志 */
448
+ requestLog;
449
+ /** 临时目录路径 */
450
+ tmpDir;
451
+ /** 日志目录路径 */
452
+ logDir;
453
+ /** 日志写入间隔(毫秒) */
454
+ logWriteInterval;
455
+ /** 日志文件有效期(毫秒) */
456
+ logFileExpires;
457
+ /** 公共目录路径 */
458
+ publicDir;
459
+ /** 临时文件有效期(毫秒) */
460
+ tmpFileExpires;
461
+ /** 请求体配置 */
462
+ requestBody;
463
+ /** 是否调试模式 */
464
+ debug;
465
+ constructor(options) {
466
+ const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, publicDir, tmpFileExpires, requestBody, debug } = options || {};
467
+ this.requestLog = _4.defaultTo(requestLog, false);
468
+ this.tmpDir = _4.defaultTo(tmpDir, "./tmp");
469
+ this.logDir = _4.defaultTo(logDir, "./logs");
470
+ this.logWriteInterval = _4.defaultTo(logWriteInterval, 200);
471
+ this.logFileExpires = _4.defaultTo(logFileExpires, 262656e4);
472
+ this.publicDir = _4.defaultTo(publicDir, "./public");
473
+ this.tmpFileExpires = _4.defaultTo(tmpFileExpires, 864e5);
474
+ this.requestBody = Object.assign(requestBody || {}, {
475
+ enableTypes: ["json", "form", "text", "xml"],
476
+ encoding: "utf-8",
477
+ formLimit: "100mb",
478
+ jsonLimit: "100mb",
479
+ textLimit: "100mb",
480
+ xmlLimit: "100mb",
481
+ formidable: {
482
+ maxFileSize: "100mb"
483
+ },
484
+ multipart: true,
485
+ parsedMethods: ["POST", "PUT", "PATCH"]
486
+ });
487
+ this.debug = _4.defaultTo(debug, true);
488
+ }
489
+ get rootDirPath() {
490
+ return path4.resolve();
491
+ }
492
+ get tmpDirPath() {
493
+ return path4.resolve(this.tmpDir);
494
+ }
495
+ get logDirPath() {
496
+ return path4.resolve(this.logDir);
497
+ }
498
+ get publicDirPath() {
499
+ return path4.resolve(this.publicDir);
500
+ }
501
+ static load() {
502
+ if (!fs4.pathExistsSync(CONFIG_PATH2)) return new _SystemConfig();
503
+ const data = yaml2.parse(fs4.readFileSync(CONFIG_PATH2).toString());
504
+ return new _SystemConfig(data);
505
+ }
506
+ };
507
+ var system_config_default = SystemConfig.load();
508
+
509
+ // src/lib/config.ts
510
+ var Config = class {
511
+ /** 服务配置 */
512
+ service = service_config_default;
513
+ /** 系统配置 */
514
+ system = system_config_default;
515
+ };
516
+ var config_default = new Config();
517
+
518
+ // src/lib/logger.ts
519
+ import path5 from "path";
520
+ import _util from "util";
521
+ import "colors";
522
+ import _5 from "lodash";
523
+ import fs5 from "fs-extra";
524
+ import { format as dateFormat2 } from "date-fns";
525
+ var isVercelEnv = process.env.VERCEL;
526
+ var LogWriter = class {
527
+ #buffers = [];
528
+ constructor() {
529
+ !isVercelEnv && fs5.ensureDirSync(config_default.system.logDirPath);
530
+ !isVercelEnv && this.work();
531
+ }
532
+ push(content) {
533
+ const buffer = Buffer.from(content);
534
+ this.#buffers.push(buffer);
535
+ }
536
+ writeSync(buffer) {
537
+ !isVercelEnv && fs5.appendFileSync(path5.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), buffer);
538
+ }
539
+ async write(buffer) {
540
+ !isVercelEnv && await fs5.appendFile(path5.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), buffer);
541
+ }
542
+ flush() {
543
+ if (!this.#buffers.length) return;
544
+ !isVercelEnv && fs5.appendFileSync(path5.join(config_default.system.logDirPath, `/${util_default.getDateString()}.log`), Buffer.concat(this.#buffers));
545
+ }
546
+ work() {
547
+ if (!this.#buffers.length) return setTimeout(this.work.bind(this), config_default.system.logWriteInterval);
548
+ const buffer = Buffer.concat(this.#buffers);
549
+ this.#buffers = [];
550
+ this.write(buffer).finally(() => setTimeout(this.work.bind(this), config_default.system.logWriteInterval)).catch((err) => console.error("Log write error:", err));
551
+ }
552
+ };
553
+ var LogText = class {
554
+ /** @type {string} 日志级别 */
555
+ level;
556
+ /** @type {string} 日志文本 */
557
+ text;
558
+ /** @type {string} 日志来源 */
559
+ source;
560
+ /** @type {Date} 日志发生时间 */
561
+ time = /* @__PURE__ */ new Date();
562
+ constructor(level, ...params) {
563
+ this.level = level;
564
+ this.text = _util.format.apply(null, params);
565
+ this.source = this.#getStackTopCodeInfo();
566
+ }
567
+ #getStackTopCodeInfo() {
568
+ const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 };
569
+ const stackArray = new Error().stack.split("\n");
570
+ const text = stackArray[4];
571
+ if (!text)
572
+ return unknownInfo;
573
+ const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/);
574
+ if (!match || !_5.isString(match[2] || match[1]))
575
+ return unknownInfo;
576
+ const temp = match[2] || match[1];
577
+ const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/);
578
+ if (!_match)
579
+ return unknownInfo;
580
+ const [, scriptPath, codeLine, codeColumn] = _match;
581
+ return {
582
+ name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown",
583
+ path: scriptPath || null,
584
+ codeLine: parseInt(codeLine || 0),
585
+ codeColumn: parseInt(codeColumn || 0)
586
+ };
587
+ }
588
+ toString() {
589
+ return `[${dateFormat2(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`;
590
+ }
591
+ };
592
+ var Logger = class _Logger {
593
+ /** @type {Object} 系统配置 */
594
+ config = {};
595
+ /** @type {Object} 日志级别映射 */
596
+ static Level = {
597
+ Success: "success",
598
+ Info: "info",
599
+ Log: "log",
600
+ Debug: "debug",
601
+ Warning: "warning",
602
+ Error: "error",
603
+ Fatal: "fatal"
604
+ };
605
+ /** @type {Object} 日志级别文本颜色樱色 */
606
+ static LevelColor = {
607
+ [_Logger.Level.Success]: "green",
608
+ [_Logger.Level.Info]: "brightCyan",
609
+ [_Logger.Level.Debug]: "white",
610
+ [_Logger.Level.Warning]: "brightYellow",
611
+ [_Logger.Level.Error]: "brightRed",
612
+ [_Logger.Level.Fatal]: "red"
613
+ };
614
+ #writer;
615
+ constructor() {
616
+ this.#writer = new LogWriter();
617
+ }
618
+ header() {
619
+ this.#writer.writeSync(Buffer.from(`
620
+
621
+ ===================== LOG START ${dateFormat2(/* @__PURE__ */ new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================
622
+
623
+ `));
624
+ }
625
+ footer() {
626
+ this.#writer.flush();
627
+ this.#writer.writeSync(Buffer.from(`
628
+
629
+ ===================== LOG END ${dateFormat2(/* @__PURE__ */ new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================
630
+
631
+ `));
632
+ }
633
+ success(...params) {
634
+ const content = new LogText(_Logger.Level.Success, ...params).toString();
635
+ console.info(content[_Logger.LevelColor[_Logger.Level.Success]]);
636
+ this.#writer.push(content + "\n");
637
+ }
638
+ info(...params) {
639
+ const content = new LogText(_Logger.Level.Info, ...params).toString();
640
+ console.info(content[_Logger.LevelColor[_Logger.Level.Info]]);
641
+ this.#writer.push(content + "\n");
642
+ }
643
+ log(...params) {
644
+ const content = new LogText(_Logger.Level.Log, ...params).toString();
645
+ console.log(content[_Logger.LevelColor[_Logger.Level.Log]]);
646
+ this.#writer.push(content + "\n");
647
+ }
648
+ debug(...params) {
649
+ if (!config_default.system.debug) return;
650
+ const content = new LogText(_Logger.Level.Debug, ...params).toString();
651
+ console.debug(content[_Logger.LevelColor[_Logger.Level.Debug]]);
652
+ this.#writer.push(content + "\n");
653
+ }
654
+ warn(...params) {
655
+ const content = new LogText(_Logger.Level.Warning, ...params).toString();
656
+ console.warn(content[_Logger.LevelColor[_Logger.Level.Warning]]);
657
+ this.#writer.push(content + "\n");
658
+ }
659
+ error(...params) {
660
+ const content = new LogText(_Logger.Level.Error, ...params).toString();
661
+ console.error(content[_Logger.LevelColor[_Logger.Level.Error]]);
662
+ this.#writer.push(content);
663
+ }
664
+ fatal(...params) {
665
+ const content = new LogText(_Logger.Level.Fatal, ...params).toString();
666
+ console.error(content[_Logger.LevelColor[_Logger.Level.Fatal]]);
667
+ this.#writer.push(content);
668
+ }
669
+ destory() {
670
+ this.#writer.destory();
671
+ }
672
+ };
673
+ var logger_default = new Logger();
674
+
675
+ // src/lib/initialize.ts
676
+ process.setMaxListeners(Infinity);
677
+ process.on("uncaughtException", (err, origin) => {
678
+ logger_default.error(`An unhandled error occurred: ${origin}`, err);
679
+ });
680
+ process.on("unhandledRejection", (_15, promise) => {
681
+ promise.catch((err) => logger_default.error("An unhandled rejection occurred:", err));
682
+ });
683
+ process.on("warning", (warning) => logger_default.warn("System warning: ", warning));
684
+ process.on("exit", () => {
685
+ logger_default.info("Service exit");
686
+ logger_default.footer();
687
+ });
688
+ process.on("SIGTERM", () => {
689
+ logger_default.warn("received kill signal");
690
+ process.exit(2);
691
+ });
692
+ process.on("SIGINT", () => {
693
+ process.exit(0);
694
+ });
695
+
696
+ // src/lib/server.ts
697
+ import Koa from "koa";
698
+ import KoaRouter from "koa-router";
699
+ import koaRange from "koa-range";
700
+ import koaCors from "koa2-cors";
701
+ import koaBody from "koa-body";
702
+ import _11 from "lodash";
703
+
704
+ // src/lib/request/Request.ts
705
+ import _7 from "lodash";
706
+
707
+ // src/lib/exceptions/Exception.ts
708
+ import assert from "assert";
709
+ import _6 from "lodash";
710
+ var Exception = class extends Error {
711
+ /** 错误码 */
712
+ errcode;
713
+ /** 错误消息 */
714
+ errmsg;
715
+ /** 数据 */
716
+ data;
717
+ /** HTTP状态码 */
718
+ httpStatusCode;
719
+ /**
720
+ * 构造异常
721
+ *
722
+ * @param exception 异常
723
+ * @param _errmsg 异常消息
724
+ */
725
+ constructor(exception, _errmsg) {
726
+ assert(_6.isArray(exception), "Exception must be Array");
727
+ const [errcode, errmsg] = exception;
728
+ assert(_6.isFinite(errcode), "Exception errcode invalid");
729
+ assert(_6.isString(errmsg), "Exception errmsg invalid");
730
+ super(_errmsg || errmsg);
731
+ this.errcode = errcode;
732
+ this.errmsg = _errmsg || errmsg;
733
+ }
734
+ compare(exception) {
735
+ const [errcode] = exception;
736
+ return this.errcode == errcode;
737
+ }
738
+ setHTTPStatusCode(value) {
739
+ this.httpStatusCode = value;
740
+ return this;
741
+ }
742
+ setData(value) {
743
+ this.data = _6.defaultTo(value, null);
744
+ return this;
745
+ }
746
+ };
747
+
748
+ // src/lib/exceptions/APIException.ts
749
+ var APIException = class extends Exception {
750
+ /**
751
+ * 构造异常
752
+ *
753
+ * @param {[number, string]} exception 异常
754
+ */
755
+ constructor(exception, errmsg) {
756
+ super(exception, errmsg);
757
+ }
758
+ };
759
+
760
+ // src/api/consts/exceptions.ts
761
+ var exceptions_default = {
762
+ API_TEST: [-9999, "API\u5F02\u5E38\u9519\u8BEF"],
763
+ API_REQUEST_PARAMS_INVALID: [-2e3, "\u8BF7\u6C42\u53C2\u6570\u975E\u6CD5"],
764
+ API_REQUEST_FAILED: [-2001, "\u8BF7\u6C42\u5931\u8D25"],
765
+ API_TOKEN_EXPIRES: [-2002, "Token\u5DF2\u5931\u6548"],
766
+ API_FILE_URL_INVALID: [-2003, "\u8FDC\u7A0B\u6587\u4EF6URL\u975E\u6CD5"],
767
+ API_FILE_EXECEEDS_SIZE: [-2004, "\u8FDC\u7A0B\u6587\u4EF6\u8D85\u51FA\u5927\u5C0F"],
768
+ API_CHAT_STREAM_PUSHING: [-2005, "\u5DF2\u6709\u5BF9\u8BDD\u6D41\u6B63\u5728\u8F93\u51FA"],
769
+ API_CONTENT_FILTERED: [-2006, "\u5185\u5BB9\u7531\u4E8E\u5408\u89C4\u95EE\u9898\u5DF2\u88AB\u963B\u6B62\u751F\u6210"],
770
+ API_IMAGE_GENERATION_FAILED: [-2007, "\u56FE\u50CF\u751F\u6210\u5931\u8D25"]
771
+ };
772
+
773
+ // src/lib/request/Request.ts
774
+ var Request = class {
775
+ /** 请求方法 */
776
+ method;
777
+ /** 请求URL */
778
+ url;
779
+ /** 请求路径 */
780
+ path;
781
+ /** 请求载荷类型 */
782
+ type;
783
+ /** 请求headers */
784
+ headers;
785
+ /** 请求原始查询字符串 */
786
+ search;
787
+ /** 请求查询参数 */
788
+ query;
789
+ /** 请求URL参数 */
790
+ params;
791
+ /** 请求载荷 */
792
+ body;
793
+ /** 上传的文件 */
794
+ files;
795
+ /** 客户端IP地址 */
796
+ remoteIP;
797
+ /** 请求接受时间戳(毫秒) */
798
+ time;
799
+ constructor(ctx, options = {}) {
800
+ const { time } = options;
801
+ this.method = ctx.request.method;
802
+ this.url = ctx.request.url;
803
+ this.path = ctx.request.path;
804
+ this.type = ctx.request.type;
805
+ this.headers = ctx.request.headers || {};
806
+ this.search = ctx.request.search;
807
+ this.query = ctx.query || {};
808
+ this.params = ctx.params || {};
809
+ this.body = ctx.request.body || {};
810
+ this.files = ctx.request.files || {};
811
+ this.remoteIP = this.headers["X-Real-IP"] || this.headers["x-real-ip"] || this.headers["X-Forwarded-For"] || this.headers["x-forwarded-for"] || ctx.ip || null;
812
+ this.time = Number(_7.defaultTo(time, util_default.timestamp()));
813
+ }
814
+ validate(key, fn) {
815
+ try {
816
+ const value = _7.get(this, key);
817
+ if (fn) {
818
+ if (fn(value) === false)
819
+ throw `[Mismatch] -> ${fn}`;
820
+ } else if (_7.isUndefined(value))
821
+ throw "[Undefined]";
822
+ } catch (err) {
823
+ logger_default.warn(`Params ${key} invalid:`, err);
824
+ throw new APIException(exceptions_default.API_REQUEST_PARAMS_INVALID, `Params ${key} invalid`);
825
+ }
826
+ return this;
827
+ }
828
+ };
829
+
830
+ // src/lib/response/Response.ts
831
+ import mime2 from "mime";
832
+ import _9 from "lodash";
833
+
834
+ // src/lib/response/Body.ts
835
+ import _8 from "lodash";
836
+ var Body = class _Body {
837
+ /** 状态码 */
838
+ code;
839
+ /** 状态消息 */
840
+ message;
841
+ /** 载荷 */
842
+ data;
843
+ /** HTTP状态码 */
844
+ statusCode;
845
+ constructor(options = {}) {
846
+ const { code, message, data, statusCode } = options;
847
+ this.code = Number(_8.defaultTo(code, 0));
848
+ this.message = _8.defaultTo(message, "OK");
849
+ this.data = _8.defaultTo(data, null);
850
+ this.statusCode = Number(_8.defaultTo(statusCode, 200));
851
+ }
852
+ toObject() {
853
+ return {
854
+ code: this.code,
855
+ message: this.message,
856
+ data: this.data
857
+ };
858
+ }
859
+ static isInstance(value) {
860
+ return value instanceof _Body;
861
+ }
862
+ };
863
+
864
+ // src/lib/response/Response.ts
865
+ var Response = class _Response {
866
+ /** 响应HTTP状态码 */
867
+ statusCode;
868
+ /** 响应内容类型 */
869
+ type;
870
+ /** 响应headers */
871
+ headers;
872
+ /** 重定向目标 */
873
+ redirect;
874
+ /** 响应载荷 */
875
+ body;
876
+ /** 响应载荷大小 */
877
+ size;
878
+ /** 响应时间戳 */
879
+ time;
880
+ constructor(body, options = {}) {
881
+ const { statusCode, type, headers, redirect, size, time } = options;
882
+ this.statusCode = Number(_9.defaultTo(statusCode, Body.isInstance(body) ? body.statusCode : void 0));
883
+ this.type = type;
884
+ this.headers = headers;
885
+ this.redirect = redirect;
886
+ this.size = size;
887
+ this.time = Number(_9.defaultTo(time, util_default.timestamp()));
888
+ this.body = body;
889
+ }
890
+ injectTo(ctx) {
891
+ this.redirect && ctx.redirect(this.redirect);
892
+ this.statusCode && (ctx.status = this.statusCode);
893
+ this.type && (ctx.type = mime2.getType(this.type) || this.type);
894
+ const headers = this.headers || {};
895
+ if (this.size && !headers["Content-Length"] && !headers["content-length"])
896
+ headers["Content-Length"] = this.size;
897
+ ctx.set(headers);
898
+ if (Body.isInstance(this.body))
899
+ ctx.body = this.body.toObject();
900
+ else
901
+ ctx.body = this.body;
902
+ }
903
+ static isInstance(value) {
904
+ return value instanceof _Response;
905
+ }
906
+ };
907
+
908
+ // src/lib/response/FailureBody.ts
909
+ import _10 from "lodash";
910
+
911
+ // src/lib/consts/exceptions.ts
912
+ var exceptions_default2 = {
913
+ SYSTEM_ERROR: [-1e3, "\u7CFB\u7EDF\u5F02\u5E38"],
914
+ SYSTEM_REQUEST_VALIDATION_ERROR: [-1001, "\u8BF7\u6C42\u53C2\u6570\u6821\u9A8C\u9519\u8BEF"],
915
+ SYSTEM_NOT_ROUTE_MATCHING: [-1002, "\u65E0\u5339\u914D\u7684\u8DEF\u7531"]
916
+ };
917
+
918
+ // src/lib/response/FailureBody.ts
919
+ var FailureBody = class _FailureBody extends Body {
920
+ constructor(error, _data) {
921
+ let errcode, errmsg, data = _data, httpStatusCode = http_status_codes_default.OK;
922
+ ;
923
+ if (_10.isString(error))
924
+ error = new Exception(exceptions_default2.SYSTEM_ERROR, error);
925
+ else if (error instanceof APIException || error instanceof Exception)
926
+ ({ errcode, errmsg, data, httpStatusCode } = error);
927
+ else if (_10.isError(error))
928
+ ({ errcode, errmsg, data, httpStatusCode } = new Exception(exceptions_default2.SYSTEM_ERROR, error.message));
929
+ super({
930
+ code: errcode || -1,
931
+ message: errmsg || "Internal error",
932
+ data,
933
+ statusCode: httpStatusCode
934
+ });
935
+ }
936
+ static isInstance(value) {
937
+ return value instanceof _FailureBody;
938
+ }
939
+ };
940
+
941
+ // src/lib/server.ts
942
+ var Server = class {
943
+ app;
944
+ router;
945
+ constructor() {
946
+ this.app = new Koa();
947
+ this.app.use(koaCors());
948
+ this.app.use(koaRange);
949
+ this.router = new KoaRouter({ prefix: config_default.service.urlPrefix });
950
+ this.app.use(async (ctx, next) => {
951
+ if (ctx.request.type === "application/xml" || ctx.request.type === "application/ssml+xml")
952
+ ctx.req.headers["content-type"] = "text/xml";
953
+ try {
954
+ await next();
955
+ } catch (err) {
956
+ logger_default.error(err);
957
+ const failureBody = new FailureBody(err);
958
+ new Response(failureBody).injectTo(ctx);
959
+ }
960
+ });
961
+ this.app.use(koaBody(_11.clone(config_default.system.requestBody)));
962
+ this.app.on("error", (err) => {
963
+ if (["ECONNRESET", "ECONNABORTED", "EPIPE", "ECANCELED"].includes(err.code)) return;
964
+ logger_default.error(err);
965
+ });
966
+ logger_default.success("Server initialized");
967
+ }
968
+ /**
969
+ * 附加路由
970
+ *
971
+ * @param routes 路由列表
972
+ */
973
+ attachRoutes(routes) {
974
+ routes.forEach((route) => {
975
+ const prefix = route.prefix || "";
976
+ for (let method in route) {
977
+ if (method === "prefix") continue;
978
+ if (!_11.isObject(route[method])) {
979
+ logger_default.warn(`Router ${prefix} ${method} invalid`);
980
+ continue;
981
+ }
982
+ for (let uri in route[method]) {
983
+ this.router[method](`${prefix}${uri}`, async (ctx) => {
984
+ const { request, response } = await this.#requestProcessing(ctx, route[method][uri]);
985
+ if (response != null && config_default.system.requestLog)
986
+ logger_default.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
987
+ });
988
+ }
989
+ }
990
+ logger_default.info(`Route ${config_default.service.urlPrefix || ""}${prefix} attached`);
991
+ });
992
+ this.app.use(this.router.routes());
993
+ this.app.use((ctx) => {
994
+ const request = new Request(ctx);
995
+ logger_default.debug(`-> ${ctx.request.method} ${ctx.request.url} request is not supported - ${request.remoteIP || "unknown"}`);
996
+ const message = `[\u8BF7\u6C42\u6709\u8BEF]: \u6B63\u786E\u8BF7\u6C42\u4E3A POST -> /v1/chat/completions\uFF0C\u5F53\u524D\u8BF7\u6C42\u4E3A ${ctx.request.method} -> ${ctx.request.url} \u8BF7\u7EA0\u6B63`;
997
+ logger_default.warn(message);
998
+ const failureBody = new FailureBody(new Error(message));
999
+ const response = new Response(failureBody);
1000
+ response.injectTo(ctx);
1001
+ if (config_default.system.requestLog)
1002
+ logger_default.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
1003
+ });
1004
+ }
1005
+ /**
1006
+ * 请求处理
1007
+ *
1008
+ * @param ctx 上下文
1009
+ * @param routeFn 路由方法
1010
+ */
1011
+ #requestProcessing(ctx, routeFn) {
1012
+ return new Promise((resolve) => {
1013
+ const request = new Request(ctx);
1014
+ try {
1015
+ if (config_default.system.requestLog)
1016
+ logger_default.info(`-> ${request.method} ${request.url}`);
1017
+ routeFn(request).then((response) => {
1018
+ try {
1019
+ if (!Response.isInstance(response)) {
1020
+ const _response = new Response(response);
1021
+ _response.injectTo(ctx);
1022
+ return resolve({ request, response: _response });
1023
+ }
1024
+ response.injectTo(ctx);
1025
+ resolve({ request, response });
1026
+ } catch (err) {
1027
+ logger_default.error(err);
1028
+ const failureBody = new FailureBody(err);
1029
+ const response2 = new Response(failureBody);
1030
+ response2.injectTo(ctx);
1031
+ resolve({ request, response: response2 });
1032
+ }
1033
+ }).catch((err) => {
1034
+ try {
1035
+ logger_default.error(err);
1036
+ const failureBody = new FailureBody(err);
1037
+ const response = new Response(failureBody);
1038
+ response.injectTo(ctx);
1039
+ resolve({ request, response });
1040
+ } catch (err2) {
1041
+ logger_default.error(err2);
1042
+ const failureBody = new FailureBody(err2);
1043
+ const response = new Response(failureBody);
1044
+ response.injectTo(ctx);
1045
+ resolve({ request, response });
1046
+ }
1047
+ });
1048
+ } catch (err) {
1049
+ logger_default.error(err);
1050
+ const failureBody = new FailureBody(err);
1051
+ const response = new Response(failureBody);
1052
+ response.injectTo(ctx);
1053
+ resolve({ request, response });
1054
+ }
1055
+ });
1056
+ }
1057
+ /**
1058
+ * 监听端口
1059
+ */
1060
+ async listen() {
1061
+ const host = config_default.service.host;
1062
+ const port = config_default.service.port;
1063
+ await Promise.all([
1064
+ new Promise((resolve, reject) => {
1065
+ if (host === "0.0.0.0" || host === "localhost" || host === "127.0.0.1")
1066
+ return resolve(null);
1067
+ this.app.listen(port, "localhost", (err) => {
1068
+ if (err) return reject(err);
1069
+ resolve(null);
1070
+ });
1071
+ }),
1072
+ new Promise((resolve, reject) => {
1073
+ this.app.listen(port, host, (err) => {
1074
+ if (err) return reject(err);
1075
+ resolve(null);
1076
+ });
1077
+ })
1078
+ ]);
1079
+ logger_default.success(`Server listening on port ${port} (${host})`);
1080
+ }
1081
+ };
1082
+ var server_default = new Server();
1083
+
1084
+ // src/api/routes/index.ts
1085
+ import fs6 from "fs-extra";
1086
+
1087
+ // src/api/routes/chat.ts
1088
+ import _13 from "lodash";
1089
+
1090
+ // src/api/controllers/chat.ts
1091
+ import { PassThrough } from "stream";
1092
+ import _12 from "lodash";
1093
+ import AsyncLock from "async-lock";
1094
+ import axios2 from "axios";
1095
+ import { createParser } from "eventsource-parser";
1096
+ var MODEL_NAME = "deepseek-chat";
1097
+ var ACCESS_TOKEN_EXPIRES = 3600;
1098
+ var MAX_RETRY_COUNT = 3;
1099
+ var RETRY_DELAY = 5e3;
1100
+ var FAKE_HEADERS = {
1101
+ Accept: "*/*",
1102
+ "Accept-Encoding": "gzip, deflate, br, zstd",
1103
+ "Accept-Language": "zh-CN,zh;q=0.9",
1104
+ Origin: "https://chat.deepseek.com",
1105
+ Pragma: "no-cache",
1106
+ Referer: "https://chat.deepseek.com/",
1107
+ "Sec-Ch-Ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
1108
+ "Sec-Ch-Ua-Mobile": "?0",
1109
+ "Sec-Ch-Ua-Platform": '"Windows"',
1110
+ "Sec-Fetch-Dest": "empty",
1111
+ "Sec-Fetch-Mode": "cors",
1112
+ "Sec-Fetch-Site": "same-origin",
1113
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
1114
+ "X-App-Version": "20240126.0"
1115
+ };
1116
+ var accessTokenMap = /* @__PURE__ */ new Map();
1117
+ var accessTokenRequestQueueMap = {};
1118
+ var chatLock = new AsyncLock();
1119
+ async function requestToken(refreshToken) {
1120
+ if (accessTokenRequestQueueMap[refreshToken])
1121
+ return new Promise(
1122
+ (resolve) => accessTokenRequestQueueMap[refreshToken].push(resolve)
1123
+ );
1124
+ accessTokenRequestQueueMap[refreshToken] = [];
1125
+ logger_default.info(`Refresh token: ${refreshToken}`);
1126
+ const result = await (async () => {
1127
+ const result2 = await axios2.get(
1128
+ "https://chat.deepseek.com/api/v0/users/current",
1129
+ {
1130
+ headers: {
1131
+ Authorization: `Bearer ${refreshToken}`,
1132
+ ...FAKE_HEADERS
1133
+ },
1134
+ timeout: 15e3,
1135
+ validateStatus: () => true
1136
+ }
1137
+ );
1138
+ const { token } = checkResult(result2, refreshToken);
1139
+ return {
1140
+ accessToken: token,
1141
+ refreshToken: token,
1142
+ refreshTime: util_default.unixTimestamp() + ACCESS_TOKEN_EXPIRES
1143
+ };
1144
+ })().then((result2) => {
1145
+ if (accessTokenRequestQueueMap[refreshToken]) {
1146
+ accessTokenRequestQueueMap[refreshToken].forEach(
1147
+ (resolve) => resolve(result2)
1148
+ );
1149
+ delete accessTokenRequestQueueMap[refreshToken];
1150
+ }
1151
+ logger_default.success(`Refresh successful`);
1152
+ return result2;
1153
+ }).catch((err) => {
1154
+ if (accessTokenRequestQueueMap[refreshToken]) {
1155
+ accessTokenRequestQueueMap[refreshToken].forEach(
1156
+ (resolve) => resolve(err)
1157
+ );
1158
+ delete accessTokenRequestQueueMap[refreshToken];
1159
+ }
1160
+ return err;
1161
+ });
1162
+ if (_12.isError(result)) throw result;
1163
+ return result;
1164
+ }
1165
+ async function acquireToken(refreshToken) {
1166
+ let result = accessTokenMap.get(refreshToken);
1167
+ if (!result) {
1168
+ result = await requestToken(refreshToken);
1169
+ accessTokenMap.set(refreshToken, result);
1170
+ }
1171
+ if (util_default.unixTimestamp() > result.refreshTime) {
1172
+ result = await requestToken(refreshToken);
1173
+ accessTokenMap.set(refreshToken, result);
1174
+ }
1175
+ return result.accessToken;
1176
+ }
1177
+ async function clearContext(model, refreshToken) {
1178
+ const token = await acquireToken(refreshToken);
1179
+ const result = await axios2.post(
1180
+ "https://chat.deepseek.com/api/v0/chat/clear_context",
1181
+ {
1182
+ model_class: model,
1183
+ append_welcome_message: false
1184
+ },
1185
+ {
1186
+ headers: {
1187
+ Authorization: `Bearer ${token}`,
1188
+ ...FAKE_HEADERS
1189
+ },
1190
+ timeout: 15e3,
1191
+ validateStatus: () => true
1192
+ }
1193
+ );
1194
+ checkResult(result, refreshToken);
1195
+ }
1196
+ async function createCompletion(model = MODEL_NAME, messages, refreshToken, retryCount = 0) {
1197
+ return (async () => {
1198
+ logger_default.info(messages);
1199
+ const result = await chatLock.acquire(refreshToken, async () => {
1200
+ await clearContext(model, refreshToken);
1201
+ const token = await acquireToken(refreshToken);
1202
+ return await axios2.post(
1203
+ "https://chat.deepseek.com/api/v0/chat/completions",
1204
+ {
1205
+ message: messagesPrepare(messages),
1206
+ stream: true,
1207
+ model_preference: null,
1208
+ model_class: model,
1209
+ temperature: 0
1210
+ },
1211
+ {
1212
+ headers: {
1213
+ Authorization: `Bearer ${token}`,
1214
+ ...FAKE_HEADERS
1215
+ },
1216
+ // 120秒超时
1217
+ timeout: 12e4,
1218
+ validateStatus: () => true,
1219
+ responseType: "stream"
1220
+ }
1221
+ );
1222
+ });
1223
+ if (result.headers["content-type"].indexOf("text/event-stream") == -1) {
1224
+ result.data.on("data", (buffer) => logger_default.error(buffer.toString()));
1225
+ throw new APIException(
1226
+ exceptions_default.API_REQUEST_FAILED,
1227
+ `Stream response Content-Type invalid: ${result.headers["content-type"]}`
1228
+ );
1229
+ }
1230
+ const streamStartTime = util_default.timestamp();
1231
+ const answer = await receiveStream(model, result.data);
1232
+ logger_default.success(
1233
+ `Stream has completed transfer ${util_default.timestamp() - streamStartTime}ms`
1234
+ );
1235
+ return answer;
1236
+ })().catch((err) => {
1237
+ if (retryCount < MAX_RETRY_COUNT) {
1238
+ logger_default.error(`Stream response error: ${err.stack}`);
1239
+ logger_default.warn(`Try again after ${RETRY_DELAY / 1e3}s...`);
1240
+ return (async () => {
1241
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
1242
+ return createCompletion(
1243
+ model,
1244
+ messages,
1245
+ refreshToken,
1246
+ retryCount + 1
1247
+ );
1248
+ })();
1249
+ }
1250
+ throw err;
1251
+ });
1252
+ }
1253
+ async function createCompletionStream(model = MODEL_NAME, messages, refreshToken, retryCount = 0) {
1254
+ return (async () => {
1255
+ logger_default.info(messages);
1256
+ const result = await chatLock.acquire(refreshToken, async () => {
1257
+ await clearContext(model, refreshToken);
1258
+ const token = await acquireToken(refreshToken);
1259
+ return await axios2.post(
1260
+ "https://chat.deepseek.com/api/v0/chat/completions",
1261
+ {
1262
+ message: messagesPrepare(messages),
1263
+ stream: true,
1264
+ model_preference: null,
1265
+ model_class: model,
1266
+ temperature: 0
1267
+ },
1268
+ {
1269
+ headers: {
1270
+ Authorization: `Bearer ${token}`,
1271
+ ...FAKE_HEADERS
1272
+ },
1273
+ // 120秒超时
1274
+ timeout: 12e4,
1275
+ validateStatus: () => true,
1276
+ responseType: "stream"
1277
+ }
1278
+ );
1279
+ });
1280
+ if (result.headers["content-type"].indexOf("text/event-stream") == -1) {
1281
+ logger_default.error(
1282
+ `Invalid response Content-Type:`,
1283
+ result.headers["content-type"]
1284
+ );
1285
+ result.data.on("data", (buffer) => logger_default.error(buffer.toString()));
1286
+ const transStream = new PassThrough();
1287
+ transStream.end(
1288
+ `data: ${JSON.stringify({
1289
+ id: "",
1290
+ model: MODEL_NAME,
1291
+ object: "chat.completion.chunk",
1292
+ choices: [
1293
+ {
1294
+ index: 0,
1295
+ delta: {
1296
+ role: "assistant",
1297
+ content: "\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u7B2C\u4E09\u65B9\u54CD\u5E94\u9519\u8BEF"
1298
+ },
1299
+ finish_reason: "stop"
1300
+ }
1301
+ ],
1302
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
1303
+ created: util_default.unixTimestamp()
1304
+ })}
1305
+
1306
+ `
1307
+ );
1308
+ return transStream;
1309
+ }
1310
+ const streamStartTime = util_default.timestamp();
1311
+ return createTransStream(model, result.data, () => {
1312
+ logger_default.success(
1313
+ `Stream has completed transfer ${util_default.timestamp() - streamStartTime}ms`
1314
+ );
1315
+ });
1316
+ })().catch((err) => {
1317
+ if (retryCount < MAX_RETRY_COUNT) {
1318
+ logger_default.error(`Stream response error: ${err.stack}`);
1319
+ logger_default.warn(`Try again after ${RETRY_DELAY / 1e3}s...`);
1320
+ return (async () => {
1321
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
1322
+ return createCompletionStream(
1323
+ model,
1324
+ messages,
1325
+ refreshToken,
1326
+ retryCount + 1
1327
+ );
1328
+ })();
1329
+ }
1330
+ throw err;
1331
+ });
1332
+ }
1333
+ function messagesPrepare(messages) {
1334
+ let content;
1335
+ if (messages.length < 2) {
1336
+ content = messages.reduce((content2, message) => {
1337
+ if (_12.isArray(message.content)) {
1338
+ return message.content.reduce((_content, v) => {
1339
+ if (!_12.isObject(v) || v["type"] != "text") return _content;
1340
+ return _content + (v["text"] || "") + "\n";
1341
+ }, content2);
1342
+ }
1343
+ return content2 + `${message.content}
1344
+ `;
1345
+ }, "");
1346
+ logger_default.info("\n\u900F\u4F20\u5185\u5BB9\uFF1A\n" + content);
1347
+ } else {
1348
+ content = (messages.reduce((content2, message) => {
1349
+ if (_12.isArray(message.content)) {
1350
+ return message.content.reduce((_content, v) => {
1351
+ if (!_12.isObject(v) || v["type"] != "text") return _content;
1352
+ return _content + (`${message.role}:` + v["text"] || "") + "\n";
1353
+ }, content2);
1354
+ }
1355
+ return content2 += `${message.role}:${message.content}
1356
+ `;
1357
+ }, "") + "assistant:").replace(/\!\[.+\]\(.+\)/g, "");
1358
+ logger_default.info("\n\u5BF9\u8BDD\u5408\u5E76\uFF1A\n" + content);
1359
+ }
1360
+ return content;
1361
+ }
1362
+ function checkResult(result, refreshToken) {
1363
+ if (!result.data) return null;
1364
+ const { code, data, msg } = result.data;
1365
+ if (!_12.isFinite(code)) return result.data;
1366
+ if (code === 0) return data;
1367
+ if (code == 40003) accessTokenMap.delete(refreshToken);
1368
+ throw new APIException(exceptions_default.API_REQUEST_FAILED, `[\u8BF7\u6C42deepseek\u5931\u8D25]: ${msg}`);
1369
+ }
1370
+ async function receiveStream(model, stream) {
1371
+ return new Promise((resolve, reject) => {
1372
+ const data = {
1373
+ id: "",
1374
+ model,
1375
+ object: "chat.completion",
1376
+ choices: [
1377
+ {
1378
+ index: 0,
1379
+ message: { role: "assistant", content: "" },
1380
+ finish_reason: "stop"
1381
+ }
1382
+ ],
1383
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
1384
+ created: util_default.unixTimestamp()
1385
+ };
1386
+ const parser = createParser((event) => {
1387
+ try {
1388
+ if (event.type !== "event") return;
1389
+ const result = _12.attempt(() => JSON.parse(event.data));
1390
+ if (_12.isError(result))
1391
+ throw new Error(`Stream response invalid: ${event.data}`);
1392
+ if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == " ")
1393
+ return;
1394
+ data.choices[0].message.content += result.choices[0].delta.content;
1395
+ if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop")
1396
+ resolve(data);
1397
+ } catch (err) {
1398
+ logger_default.error(err);
1399
+ reject(err);
1400
+ }
1401
+ });
1402
+ stream.on("data", (buffer) => parser.feed(buffer.toString()));
1403
+ stream.once("error", (err) => reject(err));
1404
+ stream.once("close", () => resolve(data));
1405
+ });
1406
+ }
1407
+ function createTransStream(model, stream, endCallback) {
1408
+ const created = util_default.unixTimestamp();
1409
+ const transStream = new PassThrough();
1410
+ !transStream.closed && transStream.write(
1411
+ `data: ${JSON.stringify({
1412
+ id: "",
1413
+ model,
1414
+ object: "chat.completion.chunk",
1415
+ choices: [
1416
+ {
1417
+ index: 0,
1418
+ delta: { role: "assistant", content: "" },
1419
+ finish_reason: null
1420
+ }
1421
+ ],
1422
+ created
1423
+ })}
1424
+
1425
+ `
1426
+ );
1427
+ const parser = createParser((event) => {
1428
+ try {
1429
+ if (event.type !== "event") return;
1430
+ const result = _12.attempt(() => JSON.parse(event.data));
1431
+ if (_12.isError(result))
1432
+ throw new Error(`Stream response invalid: ${event.data}`);
1433
+ if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == " ")
1434
+ return;
1435
+ result.model = model;
1436
+ transStream.write(`data: ${JSON.stringify({
1437
+ id: result.id,
1438
+ model: result.model,
1439
+ object: "chat.completion.chunk",
1440
+ choices: [
1441
+ {
1442
+ index: 0,
1443
+ delta: { role: "assistant", content: result.choices[0].delta.content },
1444
+ finish_reason: null
1445
+ }
1446
+ ],
1447
+ created
1448
+ })}
1449
+
1450
+ `);
1451
+ if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop") {
1452
+ transStream.write(`data: ${JSON.stringify({
1453
+ id: result.id,
1454
+ model: result.model,
1455
+ object: "chat.completion.chunk",
1456
+ choices: [
1457
+ {
1458
+ index: 0,
1459
+ delta: { role: "assistant", content: "" },
1460
+ finish_reason: "stop"
1461
+ }
1462
+ ],
1463
+ created
1464
+ })}
1465
+
1466
+ `);
1467
+ !transStream.closed && transStream.end("data: [DONE]\n\n");
1468
+ }
1469
+ } catch (err) {
1470
+ logger_default.error(err);
1471
+ !transStream.closed && transStream.end("data: [DONE]\n\n");
1472
+ }
1473
+ });
1474
+ stream.on("data", (buffer) => parser.feed(buffer.toString()));
1475
+ stream.once(
1476
+ "error",
1477
+ () => !transStream.closed && transStream.end("data: [DONE]\n\n")
1478
+ );
1479
+ stream.once(
1480
+ "close",
1481
+ () => !transStream.closed && transStream.end("data: [DONE]\n\n")
1482
+ );
1483
+ return transStream;
1484
+ }
1485
+ function tokenSplit(authorization) {
1486
+ return authorization.replace("Bearer ", "").split(",");
1487
+ }
1488
+ async function getTokenLiveStatus(refreshToken) {
1489
+ const token = await acquireToken(refreshToken);
1490
+ const result = await axios2.get(
1491
+ "https://chat.deepseek.com/api/v0/users/current",
1492
+ {
1493
+ headers: {
1494
+ Authorization: `Bearer ${token}`,
1495
+ ...FAKE_HEADERS
1496
+ },
1497
+ timeout: 15e3,
1498
+ validateStatus: () => true
1499
+ }
1500
+ );
1501
+ try {
1502
+ const { token: token2 } = checkResult(result, refreshToken);
1503
+ return !!token2;
1504
+ } catch (err) {
1505
+ return false;
1506
+ }
1507
+ }
1508
+ var chat_default = {
1509
+ createCompletion,
1510
+ createCompletionStream,
1511
+ getTokenLiveStatus,
1512
+ tokenSplit
1513
+ };
1514
+
1515
+ // src/api/routes/chat.ts
1516
+ var chat_default2 = {
1517
+ prefix: "/v1/chat",
1518
+ post: {
1519
+ "/completions": async (request) => {
1520
+ request.validate("body.conversation_id", (v) => _13.isUndefined(v) || _13.isString(v)).validate("body.messages", _13.isArray).validate("headers.authorization", _13.isString);
1521
+ const tokens = chat_default.tokenSplit(request.headers.authorization);
1522
+ const token = _13.sample(tokens);
1523
+ let { model, messages, stream } = request.body;
1524
+ if (["deepseek_chat", "deepseek_code", "deepseek-chat*", "deepseek-chat", "deepseek-coder"].includes(model))
1525
+ model = {
1526
+ "deepseek-chat*": "deepseek_chat",
1527
+ "deepseek-chat": "deepseek_chat",
1528
+ "deepseek-coder": "deepseek_code"
1529
+ }[model] || model;
1530
+ else
1531
+ model = "deepseek_chat";
1532
+ if (stream) {
1533
+ const stream2 = await chat_default.createCompletionStream(model, messages, token);
1534
+ return new Response(stream2, {
1535
+ type: "text/event-stream"
1536
+ });
1537
+ } else
1538
+ return await chat_default.createCompletion(model, messages, token);
1539
+ }
1540
+ }
1541
+ };
1542
+
1543
+ // src/api/routes/ping.ts
1544
+ var ping_default = {
1545
+ prefix: "/ping",
1546
+ get: {
1547
+ "": async () => "pong"
1548
+ }
1549
+ };
1550
+
1551
+ // src/api/routes/token.ts
1552
+ import _14 from "lodash";
1553
+ var token_default = {
1554
+ prefix: "/token",
1555
+ post: {
1556
+ "/check": async (request) => {
1557
+ request.validate("body.token", _14.isString);
1558
+ const live = await chat_default.getTokenLiveStatus(request.body.token);
1559
+ return {
1560
+ live
1561
+ };
1562
+ }
1563
+ }
1564
+ };
1565
+
1566
+ // src/api/routes/models.ts
1567
+ var models_default = {
1568
+ prefix: "/v1",
1569
+ get: {
1570
+ "/models": async () => {
1571
+ return {
1572
+ "data": [
1573
+ {
1574
+ "id": "deepseek-chat",
1575
+ "object": "model",
1576
+ "owned_by": "deepseek-free-api"
1577
+ },
1578
+ {
1579
+ "id": "deepseek-coder",
1580
+ "object": "model",
1581
+ "owned_by": "deepseek-free-api"
1582
+ }
1583
+ ]
1584
+ };
1585
+ }
1586
+ }
1587
+ };
1588
+
1589
+ // src/api/routes/index.ts
1590
+ var routes_default = [
1591
+ {
1592
+ get: {
1593
+ "/": async () => {
1594
+ const content = await fs6.readFile("public/welcome.html");
1595
+ return new Response(content, {
1596
+ type: "html",
1597
+ headers: {
1598
+ Expires: "-1"
1599
+ }
1600
+ });
1601
+ }
1602
+ }
1603
+ },
1604
+ chat_default2,
1605
+ ping_default,
1606
+ token_default,
1607
+ models_default
1608
+ ];
1609
+
1610
+ // src/index.ts
1611
+ var startupTime = performance.now();
1612
+ (async () => {
1613
+ logger_default.header();
1614
+ logger_default.info("<<<< deepseek free server >>>>");
1615
+ logger_default.info("Version:", environment_default.package.version);
1616
+ logger_default.info("Process id:", process.pid);
1617
+ logger_default.info("Environment:", environment_default.env);
1618
+ logger_default.info("Service name:", config_default.service.name);
1619
+ server_default.attachRoutes(routes_default);
1620
+ await server_default.listen();
1621
+ config_default.service.bindAddress && logger_default.success("Service bind address:", config_default.service.bindAddress);
1622
+ })().then(
1623
+ () => logger_default.success(
1624
+ `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)`
1625
+ )
1626
+ ).catch((err) => console.error(err));
1627
+ //# sourceMappingURL=index.js.map
dist/index.js.map ADDED
The diff for this file is too large to render. See raw diff
 
dist/welcome.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <title>🚀 服务已启动</title>
6
+ </head>
7
+ <body>
8
+ <p>deepseek-free-api已启动!<br>请通过LobeChat / NextChat / Dify等客户端或OpenAI SDK接入!</p>
9
+ </body>
10
+ </html>
doc/example-0.png ADDED
doc/example-1.png ADDED
doc/example-2.png ADDED
libs.d.ts ADDED
File without changes
logs/2024-06-15.log ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ ===================== LOG START 2024-06-15 18:38:42.920 =====================
4
+
5
+ [2024-06-15 18:38:42.909][success][index<966,20>] Server initialized
6
+ [2024-06-15 18:38:42.924][info][index<1614,18>] <<<< deepseek free server >>>>
7
+ [2024-06-15 18:38:42.926][info][index<1615,18>] Version: 0.0.6
8
+ [2024-06-15 18:38:42.927][info][index<1616,18>] Process id: 27624
9
+ [2024-06-15 18:38:42.928][info][index<1617,18>] Environment: dev
10
+ [2024-06-15 18:38:42.929][info][index<1618,18>] Service name: deepseek-free-api
11
+ [2024-06-15 18:38:42.933][info][index<990,22>] Route attached
12
+ [2024-06-15 18:38:42.934][info][index<990,22>] Route /v1/chat attached
13
+ [2024-06-15 18:38:42.934][info][index<990,22>] Route /ping attached
14
+ [2024-06-15 18:38:42.936][info][index<990,22>] Route /token attached
15
+ [2024-06-15 18:38:42.937][info][index<990,22>] Route /v1 attached
16
+ [2024-06-15 18:38:42.979][success][index<1079,20>] Server listening on port 8000 (0.0.0.0)
17
+ [2024-06-15 18:38:42.980][success][index<1623,24>] Service startup completed (59ms)
18
+ [2024-06-15 18:41:50.757][info][index<1016,26>] -> GET /
19
+ [2024-06-15 18:41:50.770][info][index<986,30>] <- GET / 10ms
20
+ [2024-06-15 18:42:00.157][debug][index<995,22>] -> GET /v1 request is not supported - 127.0.0.1
21
+ [2024-06-15 18:42:00.159][warning][index<997,22>] [请求有误]: 正确请求为 POST -> /v1/chat/completions,当前请求为 GET -> /v1 请纠正
22
+ [2024-06-15 18:42:00.167][info][index<1002,24>] <- GET /v1 8ms
23
+ [2024-06-15 18:42:20.540][debug][index<995,22>] -> GET /v1/chat/completions request is not supported - 127.0.0.1
24
+ [2024-06-15 18:42:20.543][warning][index<997,22>] [请求有误]: 正确请求为 POST -> /v1/chat/completions,当前请求为 GET -> /v1/chat/completions 请纠正
25
+ [2024-06-15 18:42:20.545][info][index<1002,24>] <- GET /v1/chat/completions 4ms
26
+ [2024-06-15 18:42:38.630][info][index<1016,26>] -> POST /v1/chat/completions
27
+ [2024-06-15 18:42:38.635][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
28
+ [2024-06-15 18:42:38.638][error][index<1035,28>] APIException [Error]: Params body.messages invalid
29
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
30
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
31
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
32
+ at new Promise (<anonymous>)
33
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
34
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
35
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
36
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
37
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
38
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
39
+ errcode: -2000,
40
+ errmsg: 'Params body.messages invalid',
41
+ data: undefined,
42
+ httpStatusCode: undefined
43
+ }[2024-06-15 18:42:38.649][info][index<986,30>] <- POST /v1/chat/completions 19ms
44
+ [2024-06-15 18:43:00.943][info][index<1016,26>] -> POST /v1/chat/completions
45
+ [2024-06-15 18:43:00.944][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
46
+ [2024-06-15 18:43:00.945][error][index<1035,28>] APIException [Error]: Params body.messages invalid
47
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
48
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
49
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
50
+ at new Promise (<anonymous>)
51
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
52
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
53
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
54
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
55
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
56
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
57
+ errcode: -2000,
58
+ errmsg: 'Params body.messages invalid',
59
+ data: undefined,
60
+ httpStatusCode: undefined
61
+ }[2024-06-15 18:43:00.946][info][index<986,30>] <- POST /v1/chat/completions 3ms
62
+ [2024-06-15 18:43:10.914][info][index<1016,26>] -> POST /v1/chat/completions
63
+ [2024-06-15 18:43:10.916][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
64
+ [2024-06-15 18:43:10.917][error][index<1035,28>] APIException [Error]: Params body.messages invalid
65
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
66
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
67
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
68
+ at new Promise (<anonymous>)
69
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
70
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
71
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
72
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
73
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
74
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
75
+ errcode: -2000,
76
+ errmsg: 'Params body.messages invalid',
77
+ data: undefined,
78
+ httpStatusCode: undefined
79
+ }[2024-06-15 18:43:10.918][info][index<986,30>] <- POST /v1/chat/completions 4ms
80
+ [2024-06-15 18:43:25.253][info][index<1016,26>] -> POST /v1/chat/completions
81
+ [2024-06-15 18:43:25.254][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
82
+ [2024-06-15 18:43:25.254][error][index<1035,28>] APIException [Error]: Params body.messages invalid
83
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
84
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
85
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
86
+ at new Promise (<anonymous>)
87
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
88
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
89
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
90
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
91
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
92
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
93
+ errcode: -2000,
94
+ errmsg: 'Params body.messages invalid',
95
+ data: undefined,
96
+ httpStatusCode: undefined
97
+ }[2024-06-15 18:43:25.256][info][index<986,30>] <- POST /v1/chat/completions 3ms
98
+ [2024-06-15 18:45:22.774][info][index<1016,26>] -> POST /v1/chat/completions
99
+ [2024-06-15 18:45:22.776][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
100
+ [2024-06-15 18:45:22.777][error][index<1035,28>] APIException [Error]: Params body.messages invalid
101
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
102
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
103
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
104
+ at new Promise (<anonymous>)
105
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
106
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
107
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
108
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
109
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
110
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
111
+ errcode: -2000,
112
+ errmsg: 'Params body.messages invalid',
113
+ data: undefined,
114
+ httpStatusCode: undefined
115
+ }[2024-06-15 18:45:22.783][info][index<986,30>] <- POST /v1/chat/completions 9ms
116
+ [2024-06-15 18:46:25.059][info][index<1016,26>] -> POST /v1/chat/completions
117
+ [2024-06-15 18:46:25.061][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
118
+ [2024-06-15 18:46:25.063][error][index<1035,28>] APIException [Error]: Params body.messages invalid
119
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
120
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
121
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
122
+ at new Promise (<anonymous>)
123
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
124
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
125
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
126
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
127
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
128
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
129
+ errcode: -2000,
130
+ errmsg: 'Params body.messages invalid',
131
+ data: undefined,
132
+ httpStatusCode: undefined
133
+ }[2024-06-15 18:46:25.065][info][index<986,30>] <- POST /v1/chat/completions 7ms
134
+ [2024-06-15 18:47:12.358][info][index<1016,26>] -> POST /v1/chat/completions
135
+ [2024-06-15 18:47:12.359][warning][index<823,22>] Params body.messages invalid: [Mismatch] -> function isArray() { [native code] }
136
+ [2024-06-15 18:47:12.360][error][index<1035,28>] APIException [Error]: Params body.messages invalid
137
+ at Request.validate (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:824:13)
138
+ at /completions (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1520:94)
139
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1017:9
140
+ at new Promise (<anonymous>)
141
+ at #requestProcessing (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1012:12)
142
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:984:72
143
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
144
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-router\lib\router.js:423:16
145
+ at dispatch (C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:42:32)
146
+ at C:\mat-dir\playground\huggingface-stuff\deepseek-free-api\node_modules\koa-compose\index.js:34:12 {
147
+ errcode: -2000,
148
+ errmsg: 'Params body.messages invalid',
149
+ data: undefined,
150
+ httpStatusCode: undefined
151
+ }[2024-06-15 18:47:12.361][info][index<986,30>] <- POST /v1/chat/completions 3ms
152
+ [2024-06-15 18:48:18.406][info][index<1016,26>] -> POST /v1/chat/completions
153
+ [2024-06-15 18:48:18.407][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
154
+ [2024-06-15 18:48:18.409][info][index<1125,18>] Refresh token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzc29faWQiOiIwYzM1ZjQ1Mi1kOGUxLTQzYTAtODcwMC0xNGI3NjI2Njc3MjkiLCJpc19vYXV0aCI6MSwib2F1dGhfcHJvdmlkZXIiOiJnb29nbGUiLCJ0b2tlbl90eXBlIjoiQmVhcmVyIiwiYWNjZXNzX3Rva2VuIjoieWEyOS5hMEFYb29DZ3VCclN6alp5UUZjb25SSFhKR01rMWdWMUN4TkNXekxMMU1XWF8zbkJUTEYxZEVnM25OTTdfaDFGVTRLS1Fqb0FGU0hnNzZGcE1sRGpBNVBuNXV3NWJIb1BtdW9NRUh1U0poSndnVENxQmlRTTZxRW50XzdsWlgyYkpTX0FUY2NnQmJjN1JMWkVyVlNwOGhyVGVSVG51VXlpVnJmMzZNWlFhQ2dZS0FVZ1NBUklTRlFIR1gyTWktdGxuSFlic3pqTHE2Tm5nOHlBUE13MDE3MyIsImV4cGlyYXRpb25fZGF0ZSI6MTcxODQyMzU3OC43MTI1MTkyLCJyZWZyZXNoX3Rva2VuIjoiMS8vMGd6V2Z6eG81X2ZwVUNnWUlBUkFBR0JBU053Ri1MOUlyalduNmc0QlozWTc0NjlkZTl1VWd4eHVGYmVqTUc2alZRcVFsbktTYzcyMFpVQzVUeFhRa2RKb3h1UEVZcTEtMW5aSSIsImlkX3Byb2ZpbGUiOnsicHJvdmlkZXIiOiJHT09HTEUiLCJpZCI6IjExMjg0MDk2ODEwMTI4MDY5Mzc2OCIsIm5hbWUiOiJjb25nIHl1IiwicGljdHVyZSI6Imh0dHBzOi8vbGgzLmdvb2dsZXVzZXJjb250ZW50LmNvbS9hL0FDZzhvY0prMmlwcmR3ZGE4cFNtMnJUTDBzTEp2a1Fad0JVOUtRT3NBbE9zSTducWNJZzd3Zz1zOTYtYyIsImxvY2FsZSI6ImVuX1VTIiwiZW1haWwiOiJ5dWNvbmdvQGdtYWlsLmNvbSJ9LCJlbWFpbCI6IiIsIm1vYmlsZV9udW1iZXIiOiIiLCJhcmVhX2NvZGUiOiIiLCJtb2JpbGUiOiIiLCJleHAiOjE3MTkwNTM2MzAsImF1ZCI6IjY1MjhhZDM5NmZhYTEzNjdmZWU2ZDE2YyJ9.ZPzXbJ3Vg-ZbD4sZXcgz2wALe6RqkpCP5n_nu62zsFM
155
+ [2024-06-15 18:48:19.532][success][index<1151,20>] Refresh successful
156
+ [2024-06-15 18:48:20.012][info][index<1346,20>]
157
+ 透传内容:
158
+ Say this is a test!
159
+
160
+ [2024-06-15 18:48:21.723][success][index<1232,20>] Stream has completed transfer 1205ms
161
+ [2024-06-15 18:48:21.725][info][index<986,30>] <- POST /v1/chat/completions 3318ms
162
+ [2024-06-15 18:49:24.604][info][index<1016,26>] -> POST /v1/chat/completions
163
+ [2024-06-15 18:49:24.606][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
164
+ [2024-06-15 18:49:24.607][info][index<1125,18>] Refresh token: none
165
+ [2024-06-15 18:49:25.165][error][index<1238,22>] Stream response error: Error: [请求deepseek失败]: Authorization Failed (jwt)
166
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
167
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
168
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
169
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
170
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
171
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
172
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7[2024-06-15 18:49:25.167][warning][index<1239,22>] Try again after 5s...
173
+ [2024-06-15 18:49:30.168][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
174
+ [2024-06-15 18:49:30.170][info][index<1125,18>] Refresh token: none
175
+ [2024-06-15 18:49:30.670][error][index<1238,22>] Stream response error: Error: [请求deepseek失败]: Authorization Failed (jwt)
176
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
177
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
178
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
179
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
180
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
181
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
182
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7[2024-06-15 18:49:30.672][warning][index<1239,22>] Try again after 5s...
183
+ [2024-06-15 18:49:35.683][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
184
+ [2024-06-15 18:49:35.686][info][index<1125,18>] Refresh token: none
185
+ [2024-06-15 18:49:36.129][error][index<1238,22>] Stream response error: Error: [请求deepseek失败]: Authorization Failed (jwt)
186
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
187
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
188
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
189
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
190
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
191
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
192
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7[2024-06-15 18:49:36.131][warning][index<1239,22>] Try again after 5s...
193
+ [2024-06-15 18:49:41.142][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
194
+ [2024-06-15 18:49:41.143][info][index<1125,18>] Refresh token: none
195
+ [2024-06-15 18:49:41.578][error][index<1035,28>] APIException [Error]: [请求deepseek失败]: Authorization Failed (jwt)
196
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
197
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
198
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
199
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
200
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
201
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
202
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7 {
203
+ errcode: -2001,
204
+ errmsg: '[请求deepseek失败]: Authorization Failed (jwt)',
205
+ data: undefined,
206
+ httpStatusCode: undefined
207
+ }[2024-06-15 18:49:41.581][info][index<986,30>] <- POST /v1/chat/completions 16976ms
208
+ [2024-06-15 18:49:54.381][info][index<1016,26>] -> POST /v1/chat/completions
209
+ [2024-06-15 18:49:54.382][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
210
+ [2024-06-15 18:49:54.383][info][index<1125,18>] Refresh token: any
211
+ [2024-06-15 18:49:54.803][error][index<1238,22>] Stream response error: Error: [请求deepseek失败]: Authorization Failed (jwt)
212
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
213
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
214
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
215
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
216
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
217
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
218
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7[2024-06-15 18:49:54.804][warning][index<1239,22>] Try again after 5s...
219
+ [2024-06-15 18:49:59.822][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
220
+ [2024-06-15 18:49:59.824][info][index<1125,18>] Refresh token: any
221
+ [2024-06-15 18:50:00.295][error][index<1238,22>] Stream response error: Error: [请求deepseek失败]: Authorization Failed (jwt)
222
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
223
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
224
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
225
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
226
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
227
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
228
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7[2024-06-15 18:50:00.297][warning][index<1239,22>] Try again after 5s...
229
+ [2024-06-15 18:50:05.299][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
230
+ [2024-06-15 18:50:05.301][info][index<1125,18>] Refresh token: any
231
+ [2024-06-15 18:50:05.774][error][index<1238,22>] Stream response error: Error: [请求deepseek失败]: Authorization Failed (jwt)
232
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
233
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
234
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
235
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
236
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
237
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
238
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7[2024-06-15 18:50:05.775][warning][index<1239,22>] Try again after 5s...
239
+ [2024-06-15 18:50:10.781][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
240
+ [2024-06-15 18:50:10.783][info][index<1125,18>] Refresh token: any
241
+ [2024-06-15 18:50:11.212][error][index<1035,28>] APIException [Error]: [请求deepseek失败]: Authorization Failed (jwt)
242
+ at checkResult (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1368:9)
243
+ at file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1138:23
244
+ at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
245
+ at async requestToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1126:18)
246
+ at async acquireToken (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1168:14)
247
+ at async clearContext (file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1178:17)
248
+ at async file:///C:/mat-dir/playground/huggingface-stuff/deepseek-free-api/dist/index.js:1200:7 {
249
+ errcode: -2001,
250
+ errmsg: '[请求deepseek失败]: Authorization Failed (jwt)',
251
+ data: undefined,
252
+ httpStatusCode: undefined
253
+ }[2024-06-15 18:50:11.218][info][index<986,30>] <- POST /v1/chat/completions 16837ms
254
+ [2024-06-15 18:50:54.317][info][index<1016,26>] -> POST /v1/chat/completions
255
+ [2024-06-15 18:50:54.318][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
256
+ [2024-06-15 18:50:54.850][info][index<1346,20>]
257
+ 透传内容:
258
+ Say this is a test!
259
+
260
+ [2024-06-15 18:50:56.462][success][index<1232,20>] Stream has completed transfer 1112ms
261
+ [2024-06-15 18:50:56.464][info][index<986,30>] <- POST /v1/chat/completions 2147ms
262
+ [2024-06-15 18:51:56.925][info][index<685,18>] Service exit
263
+
264
+
265
+ ===================== LOG END 2024-06-15 18:51:56.930 =====================
266
+
267
+
268
+
269
+ ===================== LOG START 2024-06-15 18:52:31.175 =====================
270
+
271
+ [2024-06-15 18:52:31.165][success][index<966,20>] Server initialized
272
+ [2024-06-15 18:52:31.177][info][index<1614,18>] <<<< deepseek free server >>>>
273
+ [2024-06-15 18:52:31.180][info][index<1615,18>] Version: 0.0.6
274
+ [2024-06-15 18:52:31.181][info][index<1616,18>] Process id: 12044
275
+ [2024-06-15 18:52:31.183][info][index<1617,18>] Environment: dev
276
+ [2024-06-15 18:52:31.186][info][index<1618,18>] Service name: deepseek-free-api
277
+ [2024-06-15 18:52:31.191][info][index<990,22>] Route attached
278
+ [2024-06-15 18:52:31.192][info][index<990,22>] Route /v1/chat attached
279
+ [2024-06-15 18:52:31.193][info][index<990,22>] Route /ping attached
280
+ [2024-06-15 18:52:31.194][info][index<990,22>] Route /token attached
281
+ [2024-06-15 18:52:31.195][info][index<990,22>] Route /v1 attached
282
+ [2024-06-15 18:52:31.237][success][index<1079,20>] Server listening on port 7860 (0.0.0.0)
283
+ [2024-06-15 18:52:31.238][success][index<1623,24>] Service startup completed (63ms)
284
+ [2024-06-15 18:53:08.610][info][index<1016,26>] -> POST /v1/chat/completions
285
+ [2024-06-15 18:53:08.615][info][index<1198,20>] [ { role: 'user', content: 'Say this is a test!' } ]
286
+ [2024-06-15 18:53:08.620][info][index<1125,18>] Refresh token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzc29faWQiOiIwYzM1ZjQ1Mi1kOGUxLTQzYTAtODcwMC0xNGI3NjI2Njc3MjkiLCJpc19vYXV0aCI6MSwib2F1dGhfcHJvdmlkZXIiOiJnb29nbGUiLCJ0b2tlbl90eXBlIjoiQmVhcmVyIiwiYWNjZXNzX3Rva2VuIjoieWEyOS5hMEFYb29DZ3VCclN6alp5UUZjb25SSFhKR01rMWdWMUN4TkNXekxMMU1XWF8zbkJUTEYxZEVnM25OTTdfaDFGVTRLS1Fqb0FGU0hnNzZGcE1sRGpBNVBuNXV3NWJIb1BtdW9NRUh1U0poSndnVENxQmlRTTZxRW50XzdsWlgyYkpTX0FUY2NnQmJjN1JMWkVyVlNwOGhyVGVSVG51VXlpVnJmMzZNWlFhQ2dZS0FVZ1NBUklTRlFIR1gyTWktdGxuSFlic3pqTHE2Tm5nOHlBUE13MDE3MyIsImV4cGlyYXRpb25fZGF0ZSI6MTcxODQyMzU3OC43MTI1MTkyLCJyZWZyZXNoX3Rva2VuIjoiMS8vMGd6V2Z6eG81X2ZwVUNnWUlBUkFBR0JBU053Ri1MOUlyalduNmc0QlozWTc0NjlkZTl1VWd4eHVGYmVqTUc2alZRcVFsbktTYzcyMFpVQzVUeFhRa2RKb3h1UEVZcTEtMW5aSSIsImlkX3Byb2ZpbGUiOnsicHJvdmlkZXIiOiJHT09HTEUiLCJpZCI6IjExMjg0MDk2ODEwMTI4MDY5Mzc2OCIsIm5hbWUiOiJjb25nIHl1IiwicGljdHVyZSI6Imh0dHBzOi8vbGgzLmdvb2dsZXVzZXJjb250ZW50LmNvbS9hL0FDZzhvY0prMmlwcmR3ZGE4cFNtMnJUTDBzTEp2a1Fad0JVOUtRT3NBbE9zSTducWNJZzd3Zz1zOTYtYyIsImxvY2FsZSI6ImVuX1VTIiwiZW1haWwiOiJ5dWNvbmdvQGdtYWlsLmNvbSJ9LCJlbWFpbCI6IiIsIm1vYmlsZV9udW1iZXIiOiIiLCJhcmVhX2NvZGUiOiIiLCJtb2JpbGUiOiIiLCJleHAiOjE3MTkwNTM2MzAsImF1ZCI6IjY1MjhhZDM5NmZhYTEzNjdmZWU2ZDE2YyJ9.ZPzXbJ3Vg-ZbD4sZXcgz2wALe6RqkpCP5n_nu62zsFM
287
+ [2024-06-15 18:53:09.740][success][index<1151,20>] Refresh successful
288
+ [2024-06-15 18:53:10.216][info][index<1346,20>]
289
+ 透传内容:
290
+ Say this is a test!
291
+
292
+ [2024-06-15 18:53:11.787][success][index<1232,20>] Stream has completed transfer 1164ms
293
+ [2024-06-15 18:53:11.795][info][index<986,30>] <- POST /v1/chat/completions 3180ms
294
+ [2024-06-15 18:53:33.474][info][index<685,18>] Service exit
295
+
296
+
297
+ ===================== LOG END 2024-06-15 18:53:33.482 =====================
298
+
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "deepseek-free-api",
3
+ "version": "0.0.6",
4
+ "description": "DeepSeek Free API Server",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.mjs",
8
+ "types": "dist/index.d.ts",
9
+ "directories": {
10
+ "dist": "dist"
11
+ },
12
+ "files": [
13
+ "dist/"
14
+ ],
15
+ "scripts": {
16
+ "dev": "tsup src/index.ts --format cjs,esm --sourcemap --dts --publicDir public --watch --onSuccess \"node dist/index.js\"",
17
+ "start": "node dist/index.js",
18
+ "build": "tsup src/index.ts --format cjs,esm --sourcemap --dts --clean --publicDir public"
19
+ },
20
+ "author": "Vinlic",
21
+ "license": "ISC",
22
+ "dependencies": {
23
+ "@types/async-lock": "^1.4.2",
24
+ "async-lock": "^1.4.1",
25
+ "axios": "^1.6.7",
26
+ "colors": "^1.4.0",
27
+ "crc-32": "^1.2.2",
28
+ "cron": "^3.1.6",
29
+ "date-fns": "^3.3.1",
30
+ "eventsource-parser": "^1.1.2",
31
+ "fs-extra": "^11.2.0",
32
+ "koa": "^2.15.0",
33
+ "koa-body": "^5.0.0",
34
+ "koa-bodyparser": "^4.4.1",
35
+ "koa-range": "^0.3.0",
36
+ "koa-router": "^12.0.1",
37
+ "koa2-cors": "^2.0.6",
38
+ "lodash": "^4.17.21",
39
+ "mime": "^4.0.1",
40
+ "minimist": "^1.2.8",
41
+ "randomstring": "^1.3.0",
42
+ "uuid": "^9.0.1",
43
+ "yaml": "^2.3.4"
44
+ },
45
+ "devDependencies": {
46
+ "@types/lodash": "^4.14.202",
47
+ "@types/mime": "^3.0.4",
48
+ "tsup": "^8.0.2",
49
+ "typescript": "^5.3.3"
50
+ }
51
+ }
public/welcome.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8"/>
5
+ <title>🚀 服务已启动</title>
6
+ </head>
7
+ <body>
8
+ <p>deepseek-free-api已启动!<br>请通过LobeChat / NextChat / Dify等客户端或OpenAI SDK接入!</p>
9
+ </body>
10
+ </html>
src/api/consts/exceptions.ts ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+ API_TEST: [-9999, 'API异常错误'],
3
+ API_REQUEST_PARAMS_INVALID: [-2000, '请求参数非法'],
4
+ API_REQUEST_FAILED: [-2001, '请求失败'],
5
+ API_TOKEN_EXPIRES: [-2002, 'Token已失效'],
6
+ API_FILE_URL_INVALID: [-2003, '远程文件URL非法'],
7
+ API_FILE_EXECEEDS_SIZE: [-2004, '远程文件超出大小'],
8
+ API_CHAT_STREAM_PUSHING: [-2005, '已有对话流正在输出'],
9
+ API_CONTENT_FILTERED: [-2006, '内容由于合规问题已被阻止生成'],
10
+ API_IMAGE_GENERATION_FAILED: [-2007, '图像生成失败']
11
+ }
src/api/controllers/chat.ts ADDED
@@ -0,0 +1,557 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { PassThrough } from "stream";
2
+ import _ from "lodash";
3
+ import AsyncLock from "async-lock";
4
+ import axios, { AxiosResponse } from "axios";
5
+
6
+ import APIException from "@/lib/exceptions/APIException.ts";
7
+ import EX from "@/api/consts/exceptions.ts";
8
+ import { createParser } from "eventsource-parser";
9
+ import logger from "@/lib/logger.ts";
10
+ import util from "@/lib/util.ts";
11
+
12
+ // 模型名称
13
+ const MODEL_NAME = "deepseek-chat";
14
+ // access_token有效期
15
+ const ACCESS_TOKEN_EXPIRES = 3600;
16
+ // 最大重试次数
17
+ const MAX_RETRY_COUNT = 3;
18
+ // 重试延迟
19
+ const RETRY_DELAY = 5000;
20
+ // 伪装headers
21
+ const FAKE_HEADERS = {
22
+ Accept: "*/*",
23
+ "Accept-Encoding": "gzip, deflate, br, zstd",
24
+ "Accept-Language": "zh-CN,zh;q=0.9",
25
+ Origin: "https://chat.deepseek.com",
26
+ Pragma: "no-cache",
27
+ Referer: "https://chat.deepseek.com/",
28
+ "Sec-Ch-Ua":
29
+ '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
30
+ "Sec-Ch-Ua-Mobile": "?0",
31
+ "Sec-Ch-Ua-Platform": '"Windows"',
32
+ "Sec-Fetch-Dest": "empty",
33
+ "Sec-Fetch-Mode": "cors",
34
+ "Sec-Fetch-Site": "same-origin",
35
+ "User-Agent":
36
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
37
+ "X-App-Version": "20240126.0",
38
+ };
39
+ // access_token映射
40
+ const accessTokenMap = new Map();
41
+ // access_token请求队列映射
42
+ const accessTokenRequestQueueMap: Record<string, Function[]> = {};
43
+
44
+ // 聊天异步锁
45
+ const chatLock = new AsyncLock();
46
+
47
+ /**
48
+ * 请求access_token
49
+ *
50
+ * 使用refresh_token去刷新获得access_token
51
+ *
52
+ * @param refreshToken 用于刷新access_token的refresh_token
53
+ */
54
+ async function requestToken(refreshToken: string) {
55
+ if (accessTokenRequestQueueMap[refreshToken])
56
+ return new Promise((resolve) =>
57
+ accessTokenRequestQueueMap[refreshToken].push(resolve)
58
+ );
59
+ accessTokenRequestQueueMap[refreshToken] = [];
60
+ logger.info(`Refresh token: ${refreshToken}`);
61
+ const result = await (async () => {
62
+ const result = await axios.get(
63
+ "https://chat.deepseek.com/api/v0/users/current",
64
+ {
65
+ headers: {
66
+ Authorization: `Bearer ${refreshToken}`,
67
+ ...FAKE_HEADERS,
68
+ },
69
+ timeout: 15000,
70
+ validateStatus: () => true,
71
+ }
72
+ );
73
+ const { token } = checkResult(result, refreshToken);
74
+ return {
75
+ accessToken: token,
76
+ refreshToken: token,
77
+ refreshTime: util.unixTimestamp() + ACCESS_TOKEN_EXPIRES,
78
+ };
79
+ })()
80
+ .then((result) => {
81
+ if (accessTokenRequestQueueMap[refreshToken]) {
82
+ accessTokenRequestQueueMap[refreshToken].forEach((resolve) =>
83
+ resolve(result)
84
+ );
85
+ delete accessTokenRequestQueueMap[refreshToken];
86
+ }
87
+ logger.success(`Refresh successful`);
88
+ return result;
89
+ })
90
+ .catch((err) => {
91
+ if (accessTokenRequestQueueMap[refreshToken]) {
92
+ accessTokenRequestQueueMap[refreshToken].forEach((resolve) =>
93
+ resolve(err)
94
+ );
95
+ delete accessTokenRequestQueueMap[refreshToken];
96
+ }
97
+ return err;
98
+ });
99
+ if (_.isError(result)) throw result;
100
+ return result;
101
+ }
102
+
103
+ /**
104
+ * 获取缓存中的access_token
105
+ *
106
+ * 避免短时间大量刷新token,未加锁,如果有并发要求还需加锁
107
+ *
108
+ * @param refreshToken 用于刷新access_token的refresh_token
109
+ */
110
+ async function acquireToken(refreshToken: string): Promise<string> {
111
+ let result = accessTokenMap.get(refreshToken);
112
+ if (!result) {
113
+ result = await requestToken(refreshToken);
114
+ accessTokenMap.set(refreshToken, result);
115
+ }
116
+ if (util.unixTimestamp() > result.refreshTime) {
117
+ result = await requestToken(refreshToken);
118
+ accessTokenMap.set(refreshToken, result);
119
+ }
120
+ return result.accessToken;
121
+ }
122
+
123
+ /**
124
+ * 清除上下文
125
+ *
126
+ * @param model 模型名称
127
+ * @param refreshToken 用于刷新access_token的refresh_token
128
+ */
129
+ async function clearContext(model: string, refreshToken: string) {
130
+ const token = await acquireToken(refreshToken);
131
+ const result = await axios.post(
132
+ "https://chat.deepseek.com/api/v0/chat/clear_context",
133
+ {
134
+ model_class: model,
135
+ append_welcome_message: false
136
+ },
137
+ {
138
+ headers: {
139
+ Authorization: `Bearer ${token}`,
140
+ ...FAKE_HEADERS,
141
+ },
142
+ timeout: 15000,
143
+ validateStatus: () => true,
144
+ }
145
+ );
146
+ checkResult(result, refreshToken);
147
+ }
148
+
149
+ /**
150
+ * 同步对话补全
151
+ *
152
+ * @param model 模型名称
153
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
154
+ * @param refreshToken 用于刷新access_token的refresh_token
155
+ * @param retryCount 重试次数
156
+ */
157
+ async function createCompletion(
158
+ model = MODEL_NAME,
159
+ messages: any[],
160
+ refreshToken: string,
161
+ retryCount = 0
162
+ ) {
163
+ return (async () => {
164
+ logger.info(messages);
165
+
166
+ // 确保当前请求有干净上下文
167
+ const result = await chatLock.acquire(refreshToken, async () => {
168
+ // 清除上下文
169
+ await clearContext(model, refreshToken);
170
+ // 请求流
171
+ const token = await acquireToken(refreshToken);
172
+ return await axios.post(
173
+ "https://chat.deepseek.com/api/v0/chat/completions",
174
+ {
175
+ message: messagesPrepare(messages),
176
+ stream: true,
177
+ model_preference: null,
178
+ model_class: model,
179
+ temperature: 0
180
+ },
181
+ {
182
+ headers: {
183
+ Authorization: `Bearer ${token}`,
184
+ ...FAKE_HEADERS
185
+ },
186
+ // 120秒超时
187
+ timeout: 120000,
188
+ validateStatus: () => true,
189
+ responseType: "stream",
190
+ }
191
+ );
192
+ });
193
+
194
+ if (result.headers["content-type"].indexOf("text/event-stream") == -1) {
195
+ result.data.on("data", buffer => logger.error(buffer.toString()));
196
+ throw new APIException(
197
+ EX.API_REQUEST_FAILED,
198
+ `Stream response Content-Type invalid: ${result.headers["content-type"]}`
199
+ );
200
+ }
201
+
202
+ const streamStartTime = util.timestamp();
203
+ // 接收流为输出文本
204
+ const answer = await receiveStream(model, result.data);
205
+ logger.success(
206
+ `Stream has completed transfer ${util.timestamp() - streamStartTime}ms`
207
+ );
208
+
209
+ return answer;
210
+ })().catch((err) => {
211
+ if (retryCount < MAX_RETRY_COUNT) {
212
+ logger.error(`Stream response error: ${err.stack}`);
213
+ logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`);
214
+ return (async () => {
215
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
216
+ return createCompletion(
217
+ model,
218
+ messages,
219
+ refreshToken,
220
+ retryCount + 1
221
+ );
222
+ })();
223
+ }
224
+ throw err;
225
+ });
226
+ }
227
+
228
+ /**
229
+ * 流式对话补全
230
+ *
231
+ * @param model 模型名称
232
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
233
+ * @param refreshToken 用于刷新access_token的refresh_token
234
+ * @param retryCount 重试次数
235
+ */
236
+ async function createCompletionStream(
237
+ model = MODEL_NAME,
238
+ messages: any[],
239
+ refreshToken: string,
240
+ retryCount = 0
241
+ ) {
242
+ return (async () => {
243
+ logger.info(messages);
244
+
245
+ const result = await chatLock.acquire(refreshToken, async () => {
246
+ // 清除上下文
247
+ await clearContext(model, refreshToken);
248
+ // 请求流
249
+ const token = await acquireToken(refreshToken);
250
+ return await axios.post(
251
+ "https://chat.deepseek.com/api/v0/chat/completions",
252
+ {
253
+ message: messagesPrepare(messages),
254
+ stream: true,
255
+ model_preference: null,
256
+ model_class: model,
257
+ temperature: 0
258
+ },
259
+ {
260
+ headers: {
261
+ Authorization: `Bearer ${token}`,
262
+ ...FAKE_HEADERS
263
+ },
264
+ // 120秒超时
265
+ timeout: 120000,
266
+ validateStatus: () => true,
267
+ responseType: "stream",
268
+ }
269
+ );
270
+ });
271
+
272
+ if (result.headers["content-type"].indexOf("text/event-stream") == -1) {
273
+ logger.error(
274
+ `Invalid response Content-Type:`,
275
+ result.headers["content-type"]
276
+ );
277
+ result.data.on("data", buffer => logger.error(buffer.toString()));
278
+ const transStream = new PassThrough();
279
+ transStream.end(
280
+ `data: ${JSON.stringify({
281
+ id: "",
282
+ model: MODEL_NAME,
283
+ object: "chat.completion.chunk",
284
+ choices: [
285
+ {
286
+ index: 0,
287
+ delta: {
288
+ role: "assistant",
289
+ content: "服务暂时不可用,第三方响应错误",
290
+ },
291
+ finish_reason: "stop",
292
+ },
293
+ ],
294
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
295
+ created: util.unixTimestamp(),
296
+ })}\n\n`
297
+ );
298
+ return transStream;
299
+ }
300
+ const streamStartTime = util.timestamp();
301
+ // 创建转换流将消息格式转换为gpt兼容格式
302
+ return createTransStream(model, result.data, () => {
303
+ logger.success(
304
+ `Stream has completed transfer ${util.timestamp() - streamStartTime}ms`
305
+ );
306
+ });
307
+ })().catch((err) => {
308
+ if (retryCount < MAX_RETRY_COUNT) {
309
+ logger.error(`Stream response error: ${err.stack}`);
310
+ logger.warn(`Try again after ${RETRY_DELAY / 1000}s...`);
311
+ return (async () => {
312
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
313
+ return createCompletionStream(
314
+ model,
315
+ messages,
316
+ refreshToken,
317
+ retryCount + 1
318
+ );
319
+ })();
320
+ }
321
+ throw err;
322
+ });
323
+ }
324
+
325
+ /**
326
+ * 消息预处理
327
+ *
328
+ * 由于接口只取第一条消息,此处会将多条消息合并为一条,实现多轮对话效果
329
+ *
330
+ * @param messages 参考gpt系列消息格式,多轮对话请完整提供上下文
331
+ */
332
+ function messagesPrepare(messages: any[]) {
333
+ let content;
334
+ if (messages.length < 2) {
335
+ content = messages.reduce((content, message) => {
336
+ if (_.isArray(message.content)) {
337
+ return (
338
+ message.content.reduce((_content, v) => {
339
+ if (!_.isObject(v) || v["type"] != "text") return _content;
340
+ return _content + (v["text"] || "") + "\n";
341
+ }, content)
342
+ );
343
+ }
344
+ return content + `${message.content}\n`;
345
+ }, "");
346
+ logger.info("\n透传内容:\n" + content);
347
+ }
348
+ else {
349
+ content = (
350
+ messages.reduce((content, message) => {
351
+ if (_.isArray(message.content)) {
352
+ return (
353
+ message.content.reduce((_content, v) => {
354
+ if (!_.isObject(v) || v["type"] != "text") return _content;
355
+ return _content + (`${message.role}:` + v["text"] || "") + "\n";
356
+ }, content)
357
+ );
358
+ }
359
+ return (content += `${message.role}:${message.content}\n`);
360
+ }, "") + "assistant:"
361
+ )
362
+ // 移除MD图像URL避免幻觉
363
+ .replace(/\!\[.+\]\(.+\)/g, "");
364
+ logger.info("\n对话合并:\n" + content);
365
+ }
366
+ return content;
367
+ }
368
+
369
+ /**
370
+ * 检查请求结果
371
+ *
372
+ * @param result 结果
373
+ * @param refreshToken 用于刷新access_token的refresh_token
374
+ */
375
+ function checkResult(result: AxiosResponse, refreshToken: string) {
376
+ if (!result.data) return null;
377
+ const { code, data, msg } = result.data;
378
+ if (!_.isFinite(code)) return result.data;
379
+ if (code === 0) return data;
380
+ if (code == 40003) accessTokenMap.delete(refreshToken);
381
+ throw new APIException(EX.API_REQUEST_FAILED, `[请求deepseek失败]: ${msg}`);
382
+ }
383
+
384
+ /**
385
+ * 从流接收完整的消息内容
386
+ *
387
+ * @param model 模型名称
388
+ * @param stream 消息流
389
+ */
390
+ async function receiveStream(model: string, stream: any): Promise<any> {
391
+ return new Promise((resolve, reject) => {
392
+ // 消息初始化
393
+ const data = {
394
+ id: "",
395
+ model,
396
+ object: "chat.completion",
397
+ choices: [
398
+ {
399
+ index: 0,
400
+ message: { role: "assistant", content: "" },
401
+ finish_reason: "stop",
402
+ },
403
+ ],
404
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
405
+ created: util.unixTimestamp(),
406
+ };
407
+ const parser = createParser((event) => {
408
+ try {
409
+ if (event.type !== "event") return;
410
+ // 解析JSON
411
+ const result = _.attempt(() => JSON.parse(event.data));
412
+ if (_.isError(result))
413
+ throw new Error(`Stream response invalid: ${event.data}`);
414
+ if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == ' ')
415
+ return;
416
+ data.choices[0].message.content += result.choices[0].delta.content;
417
+ if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop")
418
+ resolve(data);
419
+ } catch (err) {
420
+ logger.error(err);
421
+ reject(err);
422
+ }
423
+ });
424
+ // 将流数据喂给SSE转换器
425
+ stream.on("data", (buffer) => parser.feed(buffer.toString()));
426
+ stream.once("error", (err) => reject(err));
427
+ stream.once("close", () => resolve(data));
428
+ });
429
+ }
430
+
431
+ /**
432
+ * 创建转换流
433
+ *
434
+ * 将流格式转换为gpt兼容流格式
435
+ *
436
+ * @param model 模型名称
437
+ * @param stream 消息流
438
+ * @param endCallback 传输结束回调
439
+ */
440
+ function createTransStream(model: string, stream: any, endCallback?: Function) {
441
+ // 消息创建时间
442
+ const created = util.unixTimestamp();
443
+ // 创建转换流
444
+ const transStream = new PassThrough();
445
+ !transStream.closed &&
446
+ transStream.write(
447
+ `data: ${JSON.stringify({
448
+ id: "",
449
+ model,
450
+ object: "chat.completion.chunk",
451
+ choices: [
452
+ {
453
+ index: 0,
454
+ delta: { role: "assistant", content: "" },
455
+ finish_reason: null,
456
+ },
457
+ ],
458
+ created,
459
+ })}\n\n`
460
+ );
461
+ const parser = createParser((event) => {
462
+ try {
463
+ if (event.type !== "event") return;
464
+ // 解析JSON
465
+ const result = _.attempt(() => JSON.parse(event.data));
466
+ if (_.isError(result))
467
+ throw new Error(`Stream response invalid: ${event.data}`);
468
+ if (!result.choices || !result.choices[0] || !result.choices[0].delta || !result.choices[0].delta.content || result.choices[0].delta.content == ' ')
469
+ return;
470
+ result.model = model;
471
+ transStream.write(`data: ${JSON.stringify({
472
+ id: result.id,
473
+ model: result.model,
474
+ object: "chat.completion.chunk",
475
+ choices: [
476
+ {
477
+ index: 0,
478
+ delta: { role: "assistant", content: result.choices[0].delta.content },
479
+ finish_reason: null,
480
+ },
481
+ ],
482
+ created,
483
+ })}\n\n`);
484
+ if (result.choices && result.choices[0] && result.choices[0].finish_reason === "stop") {
485
+ transStream.write(`data: ${JSON.stringify({
486
+ id: result.id,
487
+ model: result.model,
488
+ object: "chat.completion.chunk",
489
+ choices: [
490
+ {
491
+ index: 0,
492
+ delta: { role: "assistant", content: "" },
493
+ finish_reason: "stop"
494
+ },
495
+ ],
496
+ created,
497
+ })}\n\n`);
498
+ !transStream.closed && transStream.end("data: [DONE]\n\n");
499
+ }
500
+ } catch (err) {
501
+ logger.error(err);
502
+ !transStream.closed && transStream.end("data: [DONE]\n\n");
503
+ }
504
+ });
505
+ // 将流数据喂给SSE转换器
506
+ stream.on("data", (buffer) => parser.feed(buffer.toString()));
507
+ stream.once(
508
+ "error",
509
+ () => !transStream.closed && transStream.end("data: [DONE]\n\n")
510
+ );
511
+ stream.once(
512
+ "close",
513
+ () => !transStream.closed && transStream.end("data: [DONE]\n\n")
514
+ );
515
+ return transStream;
516
+ }
517
+
518
+ /**
519
+ * Token切分
520
+ *
521
+ * @param authorization 认证字符串
522
+ */
523
+ function tokenSplit(authorization: string) {
524
+ return authorization.replace("Bearer ", "").split(",");
525
+ }
526
+
527
+ /**
528
+ * 获取Token存活状态
529
+ */
530
+ async function getTokenLiveStatus(refreshToken: string) {
531
+ const token = await acquireToken(refreshToken);
532
+ const result = await axios.get(
533
+ "https://chat.deepseek.com/api/v0/users/current",
534
+ {
535
+ headers: {
536
+ Authorization: `Bearer ${token}`,
537
+ ...FAKE_HEADERS,
538
+ },
539
+ timeout: 15000,
540
+ validateStatus: () => true,
541
+ }
542
+ );
543
+ try {
544
+ const { token } = checkResult(result, refreshToken);
545
+ return !!token;
546
+ }
547
+ catch (err) {
548
+ return false;
549
+ }
550
+ }
551
+
552
+ export default {
553
+ createCompletion,
554
+ createCompletionStream,
555
+ getTokenLiveStatus,
556
+ tokenSplit,
557
+ };
src/api/routes/chat.ts ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import chat from '@/api/controllers/chat.ts';
6
+
7
+ export default {
8
+
9
+ prefix: '/v1/chat',
10
+
11
+ post: {
12
+
13
+ '/completions': async (request: Request) => {
14
+ request
15
+ .validate('body.conversation_id', v => _.isUndefined(v) || _.isString(v))
16
+ .validate('body.messages', _.isArray)
17
+ .validate('headers.authorization', _.isString)
18
+ // token切分
19
+ const tokens = chat.tokenSplit(request.headers.authorization);
20
+ // 随机挑选一个token
21
+ const token = _.sample(tokens);
22
+ let { model, messages, stream } = request.body;
23
+ if(['deepseek_chat', 'deepseek_code', 'deepseek-chat*', 'deepseek-chat', 'deepseek-coder'].includes(model))
24
+ model = {
25
+ 'deepseek-chat*': 'deepseek_chat',
26
+ 'deepseek-chat': 'deepseek_chat',
27
+ 'deepseek-coder': 'deepseek_code'
28
+ }[model] || model;
29
+ else
30
+ model = 'deepseek_chat';
31
+ if (stream) {
32
+ const stream = await chat.createCompletionStream(model, messages, token);
33
+ return new Response(stream, {
34
+ type: "text/event-stream"
35
+ });
36
+ }
37
+ else
38
+ return await chat.createCompletion(model, messages, token);
39
+ }
40
+
41
+ }
42
+
43
+ }
src/api/routes/index.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'fs-extra';
2
+
3
+ import Response from '@/lib/response/Response.ts';
4
+ import chat from "./chat.ts";
5
+ import ping from "./ping.ts";
6
+ import token from './token.js';
7
+ import models from './models.ts';
8
+
9
+ export default [
10
+ {
11
+ get: {
12
+ '/': async () => {
13
+ const content = await fs.readFile('public/welcome.html');
14
+ return new Response(content, {
15
+ type: 'html',
16
+ headers: {
17
+ Expires: '-1'
18
+ }
19
+ });
20
+ }
21
+ }
22
+ },
23
+ chat,
24
+ ping,
25
+ token,
26
+ models
27
+ ];
src/api/routes/models.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ export default {
4
+
5
+ prefix: '/v1',
6
+
7
+ get: {
8
+ '/models': async () => {
9
+ return {
10
+ "data": [
11
+ {
12
+ "id": "deepseek-chat",
13
+ "object": "model",
14
+ "owned_by": "deepseek-free-api"
15
+ },
16
+ {
17
+ "id": "deepseek-coder",
18
+ "object": "model",
19
+ "owned_by": "deepseek-free-api"
20
+ }
21
+ ]
22
+ };
23
+ }
24
+
25
+ }
26
+ }
src/api/routes/ping.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ prefix: '/ping',
3
+ get: {
4
+ '': async () => "pong"
5
+ }
6
+ }
src/api/routes/token.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Request from '@/lib/request/Request.ts';
4
+ import Response from '@/lib/response/Response.ts';
5
+ import chat from '@/api/controllers/chat.ts';
6
+ import logger from '@/lib/logger.ts';
7
+
8
+ export default {
9
+
10
+ prefix: '/token',
11
+
12
+ post: {
13
+
14
+ '/check': async (request: Request) => {
15
+ request
16
+ .validate('body.token', _.isString)
17
+ const live = await chat.getTokenLiveStatus(request.body.token);
18
+ return {
19
+ live
20
+ }
21
+ }
22
+
23
+ }
24
+
25
+ }
src/daemon.ts ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * 守护进程
3
+ */
4
+
5
+ import process from 'process';
6
+ import path from 'path';
7
+ import { spawn } from 'child_process';
8
+
9
+ import fs from 'fs-extra';
10
+ import { format as dateFormat } from 'date-fns';
11
+ import 'colors';
12
+
13
+ const CRASH_RESTART_LIMIT = 600; //进程崩溃重启次数限制
14
+ const CRASH_RESTART_DELAY = 5000; //进程崩溃重启延迟
15
+ const LOG_PATH = path.resolve("./logs/daemon.log"); //守护进程日志路径
16
+ let crashCount = 0; //进程崩溃次数
17
+ let currentProcess; //当前运行进程
18
+
19
+ /**
20
+ * 写入守护进程日志
21
+ */
22
+ function daemonLog(value, color?: string) {
23
+ try {
24
+ const head = `[daemon][${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")}] `;
25
+ value = head + value;
26
+ console.log(color ? value[color] : value);
27
+ fs.ensureDirSync(path.dirname(LOG_PATH));
28
+ fs.appendFileSync(LOG_PATH, value + "\n");
29
+ }
30
+ catch(err) {
31
+ console.error("daemon log write error:", err);
32
+ }
33
+ }
34
+
35
+ daemonLog(`daemon pid: ${process.pid}`);
36
+
37
+ function createProcess() {
38
+ const childProcess = spawn("node", ["index.js", ...process.argv.slice(2)]); //启动子进程
39
+ childProcess.stdout.pipe(process.stdout, { end: false }); //将子进程输出管道到当前进程输出
40
+ childProcess.stderr.pipe(process.stderr, { end: false }); //将子进程错误输出管道到当前进程输出
41
+ currentProcess = childProcess; //更新当前进程
42
+ daemonLog(`process(${childProcess.pid}) has started`);
43
+ childProcess.on("error", err => daemonLog(`process(${childProcess.pid}) error: ${err.stack}`, "red"));
44
+ childProcess.on("close", code => {
45
+ if(code === 0) //进程正常退出
46
+ daemonLog(`process(${childProcess.pid}) has exited`);
47
+ else if(code === 2) //进程已被杀死
48
+ daemonLog(`process(${childProcess.pid}) has been killed!`, "bgYellow");
49
+ else if(code === 3) { //进程主动重启
50
+ daemonLog(`process(${childProcess.pid}) has restart`, "yellow");
51
+ createProcess(); //重新创建进程
52
+ }
53
+ else { //进程发生崩溃
54
+ if(crashCount++ < CRASH_RESTART_LIMIT) { //进程崩溃次数未达重启次数上限前尝试重启
55
+ daemonLog(`process(${childProcess.pid}) has crashed! delay ${CRASH_RESTART_DELAY}ms try restarting...(${crashCount})`, "bgRed");
56
+ setTimeout(() => createProcess(), CRASH_RESTART_DELAY); //延迟指定时长后再重启
57
+ }
58
+ else //进程已崩溃,且无法重启
59
+ daemonLog(`process(${childProcess.pid}) has crashed! unable to restart`, "bgRed");
60
+ }
61
+ }); //子进程关闭监听
62
+ }
63
+
64
+ process.on("exit", code => {
65
+ if(code === 0)
66
+ daemonLog("daemon process exited");
67
+ else if(code === 2)
68
+ daemonLog("daemon process has been killed!");
69
+ }); //守护进程退出事件
70
+
71
+ process.on("SIGTERM", () => {
72
+ daemonLog("received kill signal", "yellow");
73
+ currentProcess && currentProcess.kill("SIGINT");
74
+ process.exit(2);
75
+ }); //kill退出守护进程
76
+
77
+ process.on("SIGINT", () => {
78
+ currentProcess && currentProcess.kill("SIGINT");
79
+ process.exit(0);
80
+ }); //主动退出守护进程
81
+
82
+ createProcess(); //创建进程
src/index.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+
3
+ import environment from "@/lib/environment.ts";
4
+ import config from "@/lib/config.ts";
5
+ import "@/lib/initialize.ts";
6
+ import server from "@/lib/server.ts";
7
+ import routes from "@/api/routes/index.ts";
8
+ import logger from "@/lib/logger.ts";
9
+
10
+ const startupTime = performance.now();
11
+
12
+ (async () => {
13
+ logger.header();
14
+
15
+ logger.info("<<<< deepseek free server >>>>");
16
+ logger.info("Version:", environment.package.version);
17
+ logger.info("Process id:", process.pid);
18
+ logger.info("Environment:", environment.env);
19
+ logger.info("Service name:", config.service.name);
20
+
21
+ server.attachRoutes(routes);
22
+ await server.listen();
23
+
24
+ config.service.bindAddress &&
25
+ logger.success("Service bind address:", config.service.bindAddress);
26
+ })()
27
+ .then(() =>
28
+ logger.success(
29
+ `Service startup completed (${Math.floor(performance.now() - startupTime)}ms)`
30
+ )
31
+ )
32
+ .catch((err) => console.error(err));
src/lib/config.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import serviceConfig from "./configs/service-config.ts";
2
+ import systemConfig from "./configs/system-config.ts";
3
+
4
+ class Config {
5
+
6
+ /** 服务配置 */
7
+ service = serviceConfig;
8
+
9
+ /** 系统配置 */
10
+ system = systemConfig;
11
+
12
+ }
13
+
14
+ export default new Config();
src/lib/configs/service-config.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import yaml from 'yaml';
5
+ import _ from 'lodash';
6
+
7
+ import environment from '../environment.ts';
8
+ import util from '../util.ts';
9
+
10
+ const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/service.yml");
11
+
12
+ /**
13
+ * 服务配置
14
+ */
15
+ export class ServiceConfig {
16
+
17
+ /** 服务名称 */
18
+ name: string;
19
+ /** @type {string} 服务绑定主机地址 */
20
+ host;
21
+ /** @type {number} 服务绑定端口 */
22
+ port;
23
+ /** @type {string} 服务路由前缀 */
24
+ urlPrefix;
25
+ /** @type {string} 服务绑定地址(外部访问地址) */
26
+ bindAddress;
27
+
28
+ constructor(options?: any) {
29
+ const { name, host, port, urlPrefix, bindAddress } = options || {};
30
+ this.name = _.defaultTo(name, 'deepseek-free-api');
31
+ this.host = _.defaultTo(host, '0.0.0.0');
32
+ this.port = _.defaultTo(port, 5566);
33
+ this.urlPrefix = _.defaultTo(urlPrefix, '');
34
+ this.bindAddress = bindAddress;
35
+ }
36
+
37
+ get addressHost() {
38
+ if(this.bindAddress) return this.bindAddress;
39
+ const ipAddresses = util.getIPAddressesByIPv4();
40
+ for(let ipAddress of ipAddresses) {
41
+ if(ipAddress === this.host)
42
+ return ipAddress;
43
+ }
44
+ return ipAddresses[0] || "127.0.0.1";
45
+ }
46
+
47
+ get address() {
48
+ return `${this.addressHost}:${this.port}`;
49
+ }
50
+
51
+ get pageDirUrl() {
52
+ return `http://127.0.0.1:${this.port}/page`;
53
+ }
54
+
55
+ get publicDirUrl() {
56
+ return `http://127.0.0.1:${this.port}/public`;
57
+ }
58
+
59
+ static load() {
60
+ const external = _.pickBy(environment, (v, k) => ["name", "host", "port"].includes(k) && !_.isUndefined(v));
61
+ if(!fs.pathExistsSync(CONFIG_PATH)) return new ServiceConfig(external);
62
+ const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString());
63
+ return new ServiceConfig({ ...data, ...external });
64
+ }
65
+
66
+ }
67
+
68
+ export default ServiceConfig.load();
src/lib/configs/system-config.ts ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import yaml from 'yaml';
5
+ import _ from 'lodash';
6
+
7
+ import environment from '../environment.ts';
8
+
9
+ const CONFIG_PATH = path.join(path.resolve(), 'configs/', environment.env, "/system.yml");
10
+
11
+ /**
12
+ * 系统配置
13
+ */
14
+ export class SystemConfig {
15
+
16
+ /** 是否开启请求日志 */
17
+ requestLog: boolean;
18
+ /** 临时目录路径 */
19
+ tmpDir: string;
20
+ /** 日志目录路径 */
21
+ logDir: string;
22
+ /** 日志写入间隔(毫秒) */
23
+ logWriteInterval: number;
24
+ /** 日志文件有效期(毫秒) */
25
+ logFileExpires: number;
26
+ /** 公共目录路径 */
27
+ publicDir: string;
28
+ /** 临时文件有效期(毫秒) */
29
+ tmpFileExpires: number;
30
+ /** 请求体配置 */
31
+ requestBody: any;
32
+ /** 是否调试模式 */
33
+ debug: boolean;
34
+
35
+ constructor(options?: any) {
36
+ const { requestLog, tmpDir, logDir, logWriteInterval, logFileExpires, publicDir, tmpFileExpires, requestBody, debug } = options || {};
37
+ this.requestLog = _.defaultTo(requestLog, false);
38
+ this.tmpDir = _.defaultTo(tmpDir, './tmp');
39
+ this.logDir = _.defaultTo(logDir, './logs');
40
+ this.logWriteInterval = _.defaultTo(logWriteInterval, 200);
41
+ this.logFileExpires = _.defaultTo(logFileExpires, 2626560000);
42
+ this.publicDir = _.defaultTo(publicDir, './public');
43
+ this.tmpFileExpires = _.defaultTo(tmpFileExpires, 86400000);
44
+ this.requestBody = Object.assign(requestBody || {}, {
45
+ enableTypes: ['json', 'form', 'text', 'xml'],
46
+ encoding: 'utf-8',
47
+ formLimit: '100mb',
48
+ jsonLimit: '100mb',
49
+ textLimit: '100mb',
50
+ xmlLimit: '100mb',
51
+ formidable: {
52
+ maxFileSize: '100mb'
53
+ },
54
+ multipart: true,
55
+ parsedMethods: ['POST', 'PUT', 'PATCH']
56
+ });
57
+ this.debug = _.defaultTo(debug, true);
58
+ }
59
+
60
+ get rootDirPath() {
61
+ return path.resolve();
62
+ }
63
+
64
+ get tmpDirPath() {
65
+ return path.resolve(this.tmpDir);
66
+ }
67
+
68
+ get logDirPath() {
69
+ return path.resolve(this.logDir);
70
+ }
71
+
72
+ get publicDirPath() {
73
+ return path.resolve(this.publicDir);
74
+ }
75
+
76
+ static load() {
77
+ if (!fs.pathExistsSync(CONFIG_PATH)) return new SystemConfig();
78
+ const data = yaml.parse(fs.readFileSync(CONFIG_PATH).toString());
79
+ return new SystemConfig(data);
80
+ }
81
+
82
+ }
83
+
84
+ export default SystemConfig.load();
src/lib/consts/exceptions.ts ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export default {
2
+ SYSTEM_ERROR: [-1000, '系统异常'],
3
+ SYSTEM_REQUEST_VALIDATION_ERROR: [-1001, '请求参数校验错误'],
4
+ SYSTEM_NOT_ROUTE_MATCHING: [-1002, '无匹配的路由']
5
+ } as Record<string, [number, string]>
src/lib/environment.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+
3
+ import fs from 'fs-extra';
4
+ import minimist from 'minimist';
5
+ import _ from 'lodash';
6
+
7
+ const cmdArgs = minimist(process.argv.slice(2)); //获取命令行参数
8
+ const envVars = process.env; //获取环境变量
9
+
10
+ class Environment {
11
+
12
+ /** 命令行参数 */
13
+ cmdArgs: any;
14
+ /** 环境变量 */
15
+ envVars: any;
16
+ /** 环境名称 */
17
+ env?: string;
18
+ /** 服务名称 */
19
+ name?: string;
20
+ /** 服务地址 */
21
+ host?: string;
22
+ /** 服务端口 */
23
+ port?: number;
24
+ /** 包参数 */
25
+ package: any;
26
+
27
+ constructor(options: any = {}) {
28
+ const { cmdArgs, envVars, package: _package } = options;
29
+ this.cmdArgs = cmdArgs;
30
+ this.envVars = envVars;
31
+ this.env = _.defaultTo(cmdArgs.env || envVars.SERVER_ENV, 'dev');
32
+ this.name = cmdArgs.name || envVars.SERVER_NAME || undefined;
33
+ this.host = cmdArgs.host || envVars.SERVER_HOST || undefined;
34
+ this.port = Number(cmdArgs.port || envVars.SERVER_PORT) ? Number(cmdArgs.port || envVars.SERVER_PORT) : undefined;
35
+ this.package = _package;
36
+ }
37
+
38
+ }
39
+
40
+ export default new Environment({
41
+ cmdArgs,
42
+ envVars,
43
+ package: JSON.parse(fs.readFileSync(path.join(path.resolve(), "package.json")).toString())
44
+ });
src/lib/exceptions/APIException.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Exception from './Exception.js';
2
+
3
+ export default class APIException extends Exception {
4
+
5
+ /**
6
+ * 构造异常
7
+ *
8
+ * @param {[number, string]} exception 异常
9
+ */
10
+ constructor(exception: (string | number)[], errmsg?: string) {
11
+ super(exception, errmsg);
12
+ }
13
+
14
+ }
src/lib/exceptions/Exception.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import assert from 'assert';
2
+
3
+ import _ from 'lodash';
4
+
5
+ export default class Exception extends Error {
6
+
7
+ /** 错误码 */
8
+ errcode: number;
9
+ /** 错误消息 */
10
+ errmsg: string;
11
+ /** 数据 */
12
+ data: any;
13
+ /** HTTP状态码 */
14
+ httpStatusCode: number;
15
+
16
+ /**
17
+ * 构造异常
18
+ *
19
+ * @param exception 异常
20
+ * @param _errmsg 异常消息
21
+ */
22
+ constructor(exception: (string | number)[], _errmsg?: string) {
23
+ assert(_.isArray(exception), 'Exception must be Array');
24
+ const [errcode, errmsg] = exception as [number, string];
25
+ assert(_.isFinite(errcode), 'Exception errcode invalid');
26
+ assert(_.isString(errmsg), 'Exception errmsg invalid');
27
+ super(_errmsg || errmsg);
28
+ this.errcode = errcode;
29
+ this.errmsg = _errmsg || errmsg;
30
+ }
31
+
32
+ compare(exception: (string | number)[]) {
33
+ const [errcode] = exception as [number, string];
34
+ return this.errcode == errcode;
35
+ }
36
+
37
+ setHTTPStatusCode(value: number) {
38
+ this.httpStatusCode = value;
39
+ return this;
40
+ }
41
+
42
+ setData(value: any) {
43
+ this.data = _.defaultTo(value, null);
44
+ return this;
45
+ }
46
+
47
+ }
src/lib/http-status-codes.ts ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+
3
+ CONTINUE: 100, //客户端应当继续发送请求。这个临时响应是用来通知客户端它的部分请求已经被服务器接收,且仍未被拒绝。客户端应当继续发送请求的剩余部分,或者如果请求已经完成,忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应
4
+ SWITCHING_PROTOCOLS: 101, //服务器已经理解了客户端的请求,并将通过Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后,服务器将会切换到在Upgrade 消息头中定义的那些协议。只有在切换新的协议更有好处的时候才应该采取类似措施。例如,切换到新的HTTP 版本比旧版本更有优势,或者切换到一个实时且同步的协议以传送利用此类特性的资源
5
+ PROCESSING: 102, //处理将被继续执行
6
+
7
+ OK: 200, //请求已成功,请求所希望的响应头或数据体将随此响应返回
8
+ CREATED: 201, //请求已经被实现,而且有一个新的资源已经依据请求的需要而建立,且其 URI 已经随Location 头信息返回。假如需要的资源无法及时建立的话,应当返回 '202 Accepted'
9
+ ACCEPTED: 202, //服务器已接受请求,但尚未处理。正如它可能被拒绝一样,最终该请求可能会也可能不会被执行。在异步操作的场合下,没有比发送这个状态码更方便的做法了。返回202状态码的响应的目的是允许服务器接受其他过程的请求(例如某个每天只执行一次的基于批处理的操作),而不必让客户端一直保持与服务器的连接直到批处理操作全部完成。在接受请求处理并返回202状态码的响应应当在返回的实体中包含一些指示处理当前状态的信息,以及指向处理状态监视器或状态预测的指针,以便用户能够估计操作是否已经完成
10
+ NON_AUTHORITATIVE_INFO: 203, //服务器已成功处理了请求,但返回的实体头部元信息不是在原始服务器上有效的确定集合,而是来自本地或者第三方的拷贝。当前的信息可能是原始版本的子集或者超集。例如,包含资源的元数据可能导致原始服务器知道元信息的超级。使用此状态码不是必须的,而且只有在响应不使用此状态码便会返回200 OK的情况下才是合适的
11
+ NO_CONTENT: 204, //服务器成功处理了请求,但不需要返回任何实体内容,并且希望返回更新了的元信息。响应可能通过实体头部的形式,返回新的或更新后的元信息。如果存在这些头部信息,则应当与所请求的变量相呼应。如果客户端是浏览器的话,那么用户浏览器应保留发送了该请求的页面,而不产生任何文档视图上的变化,即使按照规范新的或更新后的元信息应当被应用到用户浏览器活动视图中的文档。由于204响应被禁止包含任何消息体,因此它始终以消息头后的第一个空行结尾
12
+ RESET_CONTENT: 205, //服务器成功处理了请求,且没有返回任何内容。但是与204响应不同,返回此状态码的响应要求请求者重置文档视图。该响应主要是被用于接受用户输入后,立即重置表单,以便用户能够轻松地开始另一次输入。与204响应一样,该响应也被禁止包含任何消息体,且以消息头后的第一个空行结束
13
+ PARTIAL_CONTENT: 206, //服务器已经成功处理了部分 GET 请求。类似于FlashGet或者迅雷这类的HTTP下载工具都是使用此类响应实现断点续传或者将一个大文档分解为多个下载段同时下载。该请求必须包含 Range 头信息来指示客户端希望得到的内容范围,并且可能包含 If-Range 来作为请求条件。响应必须包含如下的头部域:Content-Range 用以指示本次响应中返回的内容的范围;如果是Content-Type为multipart/byteranges的多段下载,则每一段multipart中都应包含Content-Range域用以指示本段的内容范围。假如响应中包含Content-Length,那么它的数值必须匹配它返回的内容范围的真实字节数。Date和ETag或Content-Location,假如同样的请求本应该返回200响应。Expires, Cache-Control,和/或 Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了 If-Range 强缓存验证,那么本次响应不应该包含其他实体头;假如本响应的请求使用了 If-Range 弱缓存验证,那么本次响应禁止包含其他实体头;这避免了缓存的实体内容和更新了的实体头信息之间的不一致。否则,本响应就应当包含所有本应该返回200响应中应当返回的所有实体头部域。假如 ETag 或 Latest-Modified 头部不能精确匹配的话,则客户端缓存应禁止将206响应返回的内容与之前任何缓存过的内容组合在一起。任何不支持 Range 以及 Content-Range 头的缓存都禁止缓存206响应返���的内容
14
+ MULTIPLE_STATUS: 207, //代表之后的消息体将是一个XML消息,并且可能依照之前子请求数量的不同,包含一系列独立的响应代码
15
+
16
+ MULTIPLE_CHOICES: 300, //被请求的资源有一系列可供选择的回馈信息,每个都有自己特定的地址和浏览器驱动的商议信息。用户或浏览器能够自行选择一个首选的地址进行重定向。除非这是一个HEAD请求,否则该响应应当包括一个资源特性及地址的列表的实体,以便用户或浏览器从中选择最合适的重定向地址。这个实体的格式由Content-Type定义的格式所决定。浏览器可能根据响应的格式以及浏览器自身能力,自动作出最合适的选择。当然,RFC 2616规范并没有规定这样的自动选择该如何进行。如果服务器本身已经有了首选的回馈选择,那么在Location中应当指明这个回馈的 URI;浏览器可能会将这个 Location 值作为自动重定向的地址。此外,除非额外指定,否则这个响应也是可缓存的
17
+ MOVED_PERMANENTLY: 301, //被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一。如果可能,拥有链接编辑功能的客户端应当自动把请求的地址修改为从服务器反馈回来的地址。除非额外指定,否则这个响应也是可缓存的。新的永久性的URI应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,因此浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:对于某些使用 HTTP/1.0 协议的浏览器,当它们发送的POST请求得到了一个301响应的话,接下来的重定向请求将会变成GET方式
18
+ FOUND: 302, //请求的资源现在临时从不同的URI响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI应当在响应的 Location 域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化。注意:虽然RFC 1945和RFC 2068规范不允许客户端在重定向时改变请求的方法,但是很多现存的浏览器将302响应视作为303响应,并且使用GET方式访问在Location中规定的URI,而无视原先请求的方法。状态码303和307被添加了进来,用以明确服务器期待客户端进行何种反应
19
+ SEE_OTHER: 303, //对应当前请求的响应可以在另一个URI上被找到,而且客户端应当采用 GET 的方式访问那个资源。这个方法的存在主要是为了允许由脚本激活的POST请求输出重定向到一个新的资源。这个新的 URI 不是原始资源的替代引用。同时,303响应禁止被缓存。当然,第二个请求(重定向)可能被缓存。新的 URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI的超链接及简短说明。注意:许多 HTTP/1.1 版以前的浏览器不能正确理解303状态。如果需要考虑与这些浏览器之间的互动,302状态码应该可以胜任,因为大多数的浏览器处理302响应时的方式恰恰就是上述规范要求客户端处理303响应时应当做的
20
+ NOT_MODIFIED: 304, //如果客户端发送了一个带条件的GET请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个状态码。304响应禁止包含消息体,因此始终以消息头后的第一个空行结尾。该响应必须包含以下的头信息:Date,除非这个服务器没有时钟。假如没有时钟的服务器也遵守这些规则,那么代理服务器以及客户端可以自行将Date字段添加到接收到的响应头中去(正如RFC 2068中规定的一样),缓存机制将会正常工作。ETag或 Content-Location,假如同样的请求本应返回200响应。Expires, Cache-Control,和/或Vary,假如其值可能与之前相同变量的其他响应对应的值不同的话。假如本响应请求使用了强缓存验证,那么本次响应不应该包含其他实体头;否则(例如,某个带条件的 GET 请求使用了弱缓存验证),本次响应禁止包含其他实体头;这避免了缓存了的实体内容和更新了的实体头信息之间的不一致。假如某个304响应指明了当前某个实体没有缓存,那么缓存系统必须忽视这个响应,并且重复发送不包含限制条件的请求。假如接收到一个要求更新某个缓存条目的304响应,那么缓存系统必须更新整个条目以反映所有在响应中被更新的字段的值
21
+ USE_PROXY: 305, //被请求的资源必须通过指定的代理才能被访问。Location域中将给出指定的代理所在的URI信息,接收者需要重复发送一个单独的请求,通过这个代理才能访问相应资源。只有原始服务器才能建立305响应。注意:RFC 2068中没有明确305响应是为了重定向一个单独的请求,而且只能被原始服务器建立。忽视这些限制可能导致严重的安全后果
22
+ UNUSED: 306, //在最新版的规范中,306状态码已经不再被使用
23
+ TEMPORARY_REDIRECT: 307, //请求的资源现在临时从不同的URI 响应请求。由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求。只有在Cache-Control或Expires中进行了指定的情况下,这个响应才是可缓存的。新的临时性的URI 应当在响应的Location域中返回。除非这是一个HEAD请求,否则响应的实体中应当包含指向新的URI 的超链接及简短说明。因为部分浏览器不能识别307响应,因此需要添加上述必要信息以便用户能够理解并向新的 URI 发出访问请求。如果这不是一个GET或者HEAD请求,那么浏览器禁止自动进行重定向,除非得到用户的确认,因为请求的条件可能因此发生变化
24
+
25
+ BAD_REQUEST: 400, //1.语义有误,当前请求无法被服务器理解。除非进行修改,否则客户端不应该重复提交这个请求 2.请求参数有误
26
+ UNAUTHORIZED: 401, //当前请求需要用户验证。该响应必须包含一个适用于被请求资源的 WWW-Authenticate 信息头用以询问用户信息。客户端可以重复提交一个包含恰当的 Authorization 头信息的请求。如果当前请求已经包含了 Authorization 证书,那么401响应代表着服务器验证已经拒绝了那些证书。如果401响应包含了与前一个响应相同的身份验证询问,且浏览器已经至少尝试了一次验证,那么浏览器应当向用户展示响应中包含的实体信息,因为这个实体信息中可能包含了相关诊断信息。参见RFC 2617
27
+ PAYMENT_REQUIRED: 402, //该状态码是为了将来可能的需求而预留的
28
+ FORBIDDEN: 403, //服务器已经理解请求,但是拒绝执行它。与401响应不同的是,身份验证并不能提供任何帮助,而且这个请求也不应该被重复提交。如果这不是一个HEAD请求,而且服务器希望能够讲清楚为何请求不能被执行,那么就应该在实体内描述拒绝的原因。当然服务器也可以返回一个404响应,假如它不希望让客户端获得任何信息
29
+ NOT_FOUND: 404, //请求失败,请求所希望得到的资源未被在服务器上发现。没有信息能够告诉用户这个状况到底是暂时的还是永久的。假如服务器知道情况的话,应当使用410状态码来告知旧资源因为某些内部的配置机制问题,已经永久的不可用,而且没有任何可以跳转的地址。404这个状态码被广泛应用于当服务器不想揭示到底为何请求被拒绝或者没有其他适合的响应可用的情况下
30
+ METHOD_NOT_ALLOWED: 405, //请求行中指定的请求方法不能被用于请求相应的资源。该响应必须返回一个Allow 头信息用以表示出当前资源能够接受的请求方法的列表。鉴于PUT,DELETE方法会对服务器上的资源进行写操作,因而绝大部分的网页服务器都不支持或者在默认配置下不允许上述请求方法,对于此类请求均会返回405错误
31
+ NO_ACCEPTABLE: 406, //请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体。除非这是一个 HEAD 请求,否则该响应就应当返回一个包含可以让用户或者浏览器从中选择最合适的实体特性以及地址列表的实体。实体的格式由Content-Type头中定义的媒体类型决定。浏览器可以根据格式及自身能力自行作出最佳选择。但是,规范中并没有定义任何作出此类自动选择的标准
32
+ PROXY_AUTHENTICATION_REQUIRED: 407, //与401响应类似,只不过客户端必须在代理服务器上进行身份验证。代理服务器必须返回一个Proxy-Authenticate用以进行身份询问。客户端可以返回一个Proxy-Authorization信息头用以验证。参见RFC 2617
33
+ REQUEST_TIMEOUT: 408, //请求超时。客户端没有在服务器预备等待的时间内完成一个请求的发送。客户端可以随时再次提交这一请求而无需进行任何更改
34
+ CONFLICT: 409, //由于和被请求的资源的当前状态之间存在冲突,请求无法完成。这个代码只允许用在这样的情况下才能被使用:用户被认为能够解决冲突,并且会重新提交新的请求。该响应应当包含足够的信息以便用户发现冲突的源头。冲突通常发生于对PUT请求的处理中。例如,在采用版本检查的环境下,某次PUT提交的对特定资源���修改请求所附带的版本信息与之前的某个(第三方)请求向冲突,那么此时服务器就应该返回一个409错误,告知用户请求无法完成。此时,响应实体中很可能会包含两个冲突版本之间的差异比较,以便用户重新提交归并以后的新版本
35
+ GONE: 410, //被请求的资源在服务器上已经不再可用,而且没有任何已知的转发地址。这样的状况应当被认为是永久性的。如果可能,拥有链接编辑功能的客户端应当在获得用户许可后删除所有指向这个地址的引用。如果服务器不知道或者无法确定这个状况是否是永久的,那么就应该使用404状态码。除非额外说明,否则这个响应是可缓存的。410响应的目的主要是帮助网站管理员维护网站,通知用户该资源已经不再可用,并且服务器拥有者希望所有指向这个资源的远端连接也被删除。这类事件在限时、增值服务中很普遍。同样,410响应也被用于通知客户端在当前服务器站点上,原本属于某个个人的资源已经不再可用。当然,是否需要把所有永久不可用的资源标记为'410 Gone',以及是否需要保持此标记多长时间,完全取决于服务器拥有者
36
+ LENGTH_REQUIRED: 411, //服务器拒绝在没有定义Content-Length头的情况下接受请求。在添加了表明请求消息体长度的有效Content-Length头之后,客户端可以再次提交该请求
37
+ PRECONDITION_FAILED: 412, //服务器在验证在请求的头字段中给出先决条件时,没能满足其中的一个或多个。这个状态码允许客户端在获取资源时在请求的元信息(请求头字段数据)中设置先决条件,以此避免该请求方法被应用到其希望的内容以外的资源上
38
+ REQUEST_ENTITY_TOO_LARGE: 413, //服务器拒绝处理当前请求,因为该请求提交的实体数据大小超过了服务器愿意或者能够处理的范围。此种情况下,服务器可以关闭连接以免客户端继续发送此请求。如果这个状况是临时的,服务器应当返回一个 Retry-After 的响应头,以告知客户端可以在多少时间以后重新尝试
39
+ REQUEST_URI_TOO_LONG: 414, //请求的URI长度超过了服务器能够解释的长度,因此服务器拒绝对该请求提供服务。这比较少见,通常的情况包括:本应使用POST方法的表单提交变成了GET方法,导致查询字符串(Query String)过长。重定向URI “黑洞”,例如每次重定向把旧的URI作为新的URI的一部分,导致在若干次重定向后URI超长。客户端正在尝试利用某些服务器中存在的安全漏洞攻击服务器。这类服务器使用固定长度的缓冲读取或操作请求的URI,当GET后的参数超过某个数值后,可能会产生缓冲区溢出,导致任意代码被执行[1]。没有此类漏洞的服务器,应当返回414状态码
40
+ UNSUPPORTED_MEDIA_TYPE: 415, //对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
41
+ REQUESTED_RANGE_NOT_SATISFIABLE: 416, //如果请求中包含了Range请求头,并且Range中指定的任何数据范围都与当前资源的可用范围不重合,同时请求中又没有定义If-Range请求头,那么服务器就应当返回416状态码。假如Range使用的是字节范围,那么这种情况就是指请求指定的所有数据范围的首字节位置都超过了当前资源的长度。服务器也应当在返回416状态码的同时,包含一个Content-Range实体头,用以指明当前资源的长度。这个响应也被禁止使用multipart/byteranges作为其 Content-Type
42
+ EXPECTION_FAILED: 417, //在请求头Expect中指定的预期内容无法被服务器满足,或者这个服务器是一个代理服务器,它有明显的证据证明在当前路由的下一个节点上,Expect的内容无法被满足
43
+ TOO_MANY_CONNECTIONS: 421, //从当前客户端所在的IP地址到服务器的连接数超过了服务器许可的最大范围。通常,这里的IP地址指的是从服务器上看到的客户端地址(比如用户的网关或者代理服务器地址)。在这种情况下,连接数的计算可能涉及到不止一个终端用户
44
+ UNPROCESSABLE_ENTITY: 422, //请求格式正确,但是由于含有语义错误,无法响应
45
+ FAILED_DEPENDENCY: 424, //由于之前的某个请求发生的错误,导致当前请求失败,例如PROPPATCH
46
+ UNORDERED_COLLECTION: 425, //在WebDav Advanced Collections 草案中定义,但是未出现在《WebDAV 顺序集协议》(RFC 3658)中
47
+ UPGRADE_REQUIRED: 426, //客户端应当切换到TLS/1.0
48
+ RETRY_WITH: 449, //由微软扩展,代表请求应当在执行完适当的操作后进行重试
49
+
50
+ INTERNAL_SERVER_ERROR: 500, //服务器遇到了一个未曾预料的状况,导致了它无法完成对请求的处理。一般来说,这个问题都会在服务器的程序码出错时出现
51
+ NOT_IMPLEMENTED: 501, //服务器不支持当前请求所需要的某个功能。当服务器无法识别请求的方法,并且无法支持其对任何资源的请求
52
+ BAD_GATEWAY: 502, //作为网关或者代理工作的服务器尝试执行请求时,从上游服务器接收到无效的响应
53
+ SERVICE_UNAVAILABLE: 503, //由于临时的服务器维护或者过载,服务器当前无法处理请求。这个状况是临时的,并且将在一段时间以后恢复。如果能够预计延迟时间,那么响应中可以包含一个 Retry-After 头用以标明这个延迟时间。如果没有给出这个 Retry-After 信息,那么客户端应当以处理500响应的方式处理它。注意:503状态码的存在并不意味着服务器在过载的时候必须使用它。某些服务器只不过是希望拒绝客户端的连接
54
+ GATEWAY_TIMEOUT: 504, //作为网关或者代理工作的服务器尝试执行请求时,未能及时从上游服务器(URI标识出的服务器,例如HTTP、FTP、LDAP)或者辅助服务器(例如DNS)收到响应。注意:某些代理服务器在DNS查询超时时会返回400或者500错误
55
+ HTTP_VERSION_NOT_SUPPORTED: 505, //服务器不支持,或者拒绝支持在请求中使用的HTTP版本。这暗示着服务器不能或不愿使用与客户端相同的版本。响应中应当包含一个描述了为何版本不被支持以及服务器支持哪些协议的实体
56
+ VARIANT_ALSO_NEGOTIATES: 506, //服务器存在内部配置错误:被请求的协商变元资源被配置为在透明内容协商中使用自己,因此在一个协商处理中不是一个合适的重点
57
+ INSUFFICIENT_STORAGE: 507, //服务器无法存储完成请求所必须的内容。这个状况被认为是临时的
58
+ BANDWIDTH_LIMIT_EXCEEDED: 509, //服务器达到带宽限制。这不是一个官方的状态码,但是仍被广泛使用
59
+ NOT_EXTENDED: 510 //获取资源所需要的策略并没有没满足
60
+
61
+ };
src/lib/initialize.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logger from './logger.js';
2
+
3
+ // 允许无限量的监听器
4
+ process.setMaxListeners(Infinity);
5
+ // 输出未捕获异常
6
+ process.on("uncaughtException", (err, origin) => {
7
+ logger.error(`An unhandled error occurred: ${origin}`, err);
8
+ });
9
+ // 输出未处理的Promise.reject
10
+ process.on("unhandledRejection", (_, promise) => {
11
+ promise.catch(err => logger.error("An unhandled rejection occurred:", err));
12
+ });
13
+ // 输出系统警告信息
14
+ process.on("warning", warning => logger.warn("System warning: ", warning));
15
+ // 进程退出监听
16
+ process.on("exit", () => {
17
+ logger.info("Service exit");
18
+ logger.footer();
19
+ });
20
+ // 进程被kill
21
+ process.on("SIGTERM", () => {
22
+ logger.warn("received kill signal");
23
+ process.exit(2);
24
+ });
25
+ // Ctrl-C进程退出
26
+ process.on("SIGINT", () => {
27
+ process.exit(0);
28
+ });
src/lib/interfaces/ICompletionMessage.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export default interface ICompletionMessage {
2
+ role: 'system' | 'assistant' | 'user' | 'function';
3
+ content: string;
4
+ }
src/lib/logger.ts ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import path from 'path';
2
+ import _util from 'util';
3
+
4
+ import 'colors';
5
+ import _ from 'lodash';
6
+ import fs from 'fs-extra';
7
+ import { format as dateFormat } from 'date-fns';
8
+
9
+ import config from './config.ts';
10
+ import util from './util.ts';
11
+
12
+ const isVercelEnv = process.env.VERCEL;
13
+
14
+ class LogWriter {
15
+
16
+ #buffers = [];
17
+
18
+ constructor() {
19
+ !isVercelEnv && fs.ensureDirSync(config.system.logDirPath);
20
+ !isVercelEnv && this.work();
21
+ }
22
+
23
+ push(content) {
24
+ const buffer = Buffer.from(content);
25
+ this.#buffers.push(buffer);
26
+ }
27
+
28
+ writeSync(buffer) {
29
+ !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer);
30
+ }
31
+
32
+ async write(buffer) {
33
+ !isVercelEnv && await fs.appendFile(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), buffer);
34
+ }
35
+
36
+ flush() {
37
+ if(!this.#buffers.length) return;
38
+ !isVercelEnv && fs.appendFileSync(path.join(config.system.logDirPath, `/${util.getDateString()}.log`), Buffer.concat(this.#buffers));
39
+ }
40
+
41
+ work() {
42
+ if (!this.#buffers.length) return setTimeout(this.work.bind(this), config.system.logWriteInterval);
43
+ const buffer = Buffer.concat(this.#buffers);
44
+ this.#buffers = [];
45
+ this.write(buffer)
46
+ .finally(() => setTimeout(this.work.bind(this), config.system.logWriteInterval))
47
+ .catch(err => console.error("Log write error:", err));
48
+ }
49
+
50
+ }
51
+
52
+ class LogText {
53
+
54
+ /** @type {string} 日志级别 */
55
+ level;
56
+ /** @type {string} 日志文本 */
57
+ text;
58
+ /** @type {string} 日志来源 */
59
+ source;
60
+ /** @type {Date} 日志发生时间 */
61
+ time = new Date();
62
+
63
+ constructor(level, ...params) {
64
+ this.level = level;
65
+ this.text = _util.format.apply(null, params);
66
+ this.source = this.#getStackTopCodeInfo();
67
+ }
68
+
69
+ #getStackTopCodeInfo() {
70
+ const unknownInfo = { name: "unknown", codeLine: 0, codeColumn: 0 };
71
+ const stackArray = new Error().stack.split("\n");
72
+ const text = stackArray[4];
73
+ if (!text)
74
+ return unknownInfo;
75
+ const match = text.match(/at (.+) \((.+)\)/) || text.match(/at (.+)/);
76
+ if (!match || !_.isString(match[2] || match[1]))
77
+ return unknownInfo;
78
+ const temp = match[2] || match[1];
79
+ const _match = temp.match(/([a-zA-Z0-9_\-\.]+)\:(\d+)\:(\d+)$/);
80
+ if (!_match)
81
+ return unknownInfo;
82
+ const [, scriptPath, codeLine, codeColumn] = _match as any;
83
+ return {
84
+ name: scriptPath ? scriptPath.replace(/.js$/, "") : "unknown",
85
+ path: scriptPath || null,
86
+ codeLine: parseInt(codeLine || 0),
87
+ codeColumn: parseInt(codeColumn || 0)
88
+ };
89
+ }
90
+
91
+ toString() {
92
+ return `[${dateFormat(this.time, "yyyy-MM-dd HH:mm:ss.SSS")}][${this.level}][${this.source.name}<${this.source.codeLine},${this.source.codeColumn}>] ${this.text}`;
93
+ }
94
+
95
+ }
96
+
97
+ class Logger {
98
+
99
+ /** @type {Object} 系统配置 */
100
+ config = {};
101
+ /** @type {Object} 日志级别映射 */
102
+ static Level = {
103
+ Success: "success",
104
+ Info: "info",
105
+ Log: "log",
106
+ Debug: "debug",
107
+ Warning: "warning",
108
+ Error: "error",
109
+ Fatal: "fatal"
110
+ };
111
+ /** @type {Object} 日志级别文本颜色樱色 */
112
+ static LevelColor = {
113
+ [Logger.Level.Success]: "green",
114
+ [Logger.Level.Info]: "brightCyan",
115
+ [Logger.Level.Debug]: "white",
116
+ [Logger.Level.Warning]: "brightYellow",
117
+ [Logger.Level.Error]: "brightRed",
118
+ [Logger.Level.Fatal]: "red"
119
+ };
120
+ #writer;
121
+
122
+ constructor() {
123
+ this.#writer = new LogWriter();
124
+ }
125
+
126
+ header() {
127
+ this.#writer.writeSync(Buffer.from(`\n\n===================== LOG START ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`));
128
+ }
129
+
130
+ footer() {
131
+ this.#writer.flush(); //将未写入文件的日志缓存写入
132
+ this.#writer.writeSync(Buffer.from(`\n\n===================== LOG END ${dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")} =====================\n\n`));
133
+ }
134
+
135
+ success(...params) {
136
+ const content = new LogText(Logger.Level.Success, ...params).toString();
137
+ console.info(content[Logger.LevelColor[Logger.Level.Success]]);
138
+ this.#writer.push(content + "\n");
139
+ }
140
+
141
+ info(...params) {
142
+ const content = new LogText(Logger.Level.Info, ...params).toString();
143
+ console.info(content[Logger.LevelColor[Logger.Level.Info]]);
144
+ this.#writer.push(content + "\n");
145
+ }
146
+
147
+ log(...params) {
148
+ const content = new LogText(Logger.Level.Log, ...params).toString();
149
+ console.log(content[Logger.LevelColor[Logger.Level.Log]]);
150
+ this.#writer.push(content + "\n");
151
+ }
152
+
153
+ debug(...params) {
154
+ if(!config.system.debug) return; //非调试模式忽略debug
155
+ const content = new LogText(Logger.Level.Debug, ...params).toString();
156
+ console.debug(content[Logger.LevelColor[Logger.Level.Debug]]);
157
+ this.#writer.push(content + "\n");
158
+ }
159
+
160
+ warn(...params) {
161
+ const content = new LogText(Logger.Level.Warning, ...params).toString();
162
+ console.warn(content[Logger.LevelColor[Logger.Level.Warning]]);
163
+ this.#writer.push(content + "\n");
164
+ }
165
+
166
+ error(...params) {
167
+ const content = new LogText(Logger.Level.Error, ...params).toString();
168
+ console.error(content[Logger.LevelColor[Logger.Level.Error]]);
169
+ this.#writer.push(content);
170
+ }
171
+
172
+ fatal(...params) {
173
+ const content = new LogText(Logger.Level.Fatal, ...params).toString();
174
+ console.error(content[Logger.LevelColor[Logger.Level.Fatal]]);
175
+ this.#writer.push(content);
176
+ }
177
+
178
+ destory() {
179
+ this.#writer.destory();
180
+ }
181
+
182
+ }
183
+
184
+ export default new Logger();
src/lib/request/Request.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import APIException from '@/lib/exceptions/APIException.ts';
4
+ import EX from '@/api/consts/exceptions.ts';
5
+ import logger from '@/lib/logger.ts';
6
+ import util from '@/lib/util.ts';
7
+
8
+ export interface RequestOptions {
9
+ time?: number;
10
+ }
11
+
12
+ export default class Request {
13
+
14
+ /** 请求方法 */
15
+ method: string;
16
+ /** 请求URL */
17
+ url: string;
18
+ /** 请求路径 */
19
+ path: string;
20
+ /** 请求载荷类型 */
21
+ type: string;
22
+ /** 请求headers */
23
+ headers: any;
24
+ /** 请求原始查询字符串 */
25
+ search: string;
26
+ /** 请求查询参数 */
27
+ query: any;
28
+ /** 请求URL参数 */
29
+ params: any;
30
+ /** 请求载荷 */
31
+ body: any;
32
+ /** 上传的文件 */
33
+ files: any[];
34
+ /** 客户端IP地址 */
35
+ remoteIP: string | null;
36
+ /** 请求接受时间戳(毫秒) */
37
+ time: number;
38
+
39
+ constructor(ctx, options: RequestOptions = {}) {
40
+ const { time } = options;
41
+ this.method = ctx.request.method;
42
+ this.url = ctx.request.url;
43
+ this.path = ctx.request.path;
44
+ this.type = ctx.request.type;
45
+ this.headers = ctx.request.headers || {};
46
+ this.search = ctx.request.search;
47
+ this.query = ctx.query || {};
48
+ this.params = ctx.params || {};
49
+ this.body = ctx.request.body || {};
50
+ this.files = ctx.request.files || {};
51
+ this.remoteIP = this.headers["X-Real-IP"] || this.headers["x-real-ip"] || this.headers["X-Forwarded-For"] || this.headers["x-forwarded-for"] || ctx.ip || null;
52
+ this.time = Number(_.defaultTo(time, util.timestamp()));
53
+ }
54
+
55
+ validate(key: string, fn?: Function) {
56
+ try {
57
+ const value = _.get(this, key);
58
+ if (fn) {
59
+ if (fn(value) === false)
60
+ throw `[Mismatch] -> ${fn}`;
61
+ }
62
+ else if (_.isUndefined(value))
63
+ throw '[Undefined]';
64
+ }
65
+ catch (err) {
66
+ logger.warn(`Params ${key} invalid:`, err);
67
+ throw new APIException(EX.API_REQUEST_PARAMS_INVALID, `Params ${key} invalid`);
68
+ }
69
+ return this;
70
+ }
71
+
72
+ }
src/lib/response/Body.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ export interface BodyOptions {
4
+ code?: number;
5
+ message?: string;
6
+ data?: any;
7
+ statusCode?: number;
8
+ }
9
+
10
+ export default class Body {
11
+
12
+ /** 状态码 */
13
+ code: number;
14
+ /** 状态消息 */
15
+ message: string;
16
+ /** 载荷 */
17
+ data: any;
18
+ /** HTTP状态码 */
19
+ statusCode: number;
20
+
21
+ constructor(options: BodyOptions = {}) {
22
+ const { code, message, data, statusCode } = options;
23
+ this.code = Number(_.defaultTo(code, 0));
24
+ this.message = _.defaultTo(message, 'OK');
25
+ this.data = _.defaultTo(data, null);
26
+ this.statusCode = Number(_.defaultTo(statusCode, 200));
27
+ }
28
+
29
+ toObject() {
30
+ return {
31
+ code: this.code,
32
+ message: this.message,
33
+ data: this.data
34
+ };
35
+ }
36
+
37
+ static isInstance(value) {
38
+ return value instanceof Body;
39
+ }
40
+
41
+ }
src/lib/response/FailureBody.ts ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Body from './Body.ts';
4
+ import Exception from '../exceptions/Exception.ts';
5
+ import APIException from '../exceptions/APIException.ts';
6
+ import EX from '../consts/exceptions.ts';
7
+ import HTTP_STATUS_CODES from '../http-status-codes.ts';
8
+
9
+ export default class FailureBody extends Body {
10
+
11
+ constructor(error: APIException | Exception | Error, _data?: any) {
12
+ let errcode, errmsg, data = _data, httpStatusCode = HTTP_STATUS_CODES.OK;;
13
+ if(_.isString(error))
14
+ error = new Exception(EX.SYSTEM_ERROR, error);
15
+ else if(error instanceof APIException || error instanceof Exception)
16
+ ({ errcode, errmsg, data, httpStatusCode } = error);
17
+ else if(_.isError(error))
18
+ ({ errcode, errmsg, data, httpStatusCode } = new Exception(EX.SYSTEM_ERROR, error.message));
19
+ super({
20
+ code: errcode || -1,
21
+ message: errmsg || 'Internal error',
22
+ data,
23
+ statusCode: httpStatusCode
24
+ });
25
+ }
26
+
27
+ static isInstance(value) {
28
+ return value instanceof FailureBody;
29
+ }
30
+
31
+ }
src/lib/response/Response.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mime from 'mime';
2
+ import _ from 'lodash';
3
+
4
+ import Body from './Body.ts';
5
+ import util from '../util.ts';
6
+
7
+ export interface ResponseOptions {
8
+ statusCode?: number;
9
+ type?: string;
10
+ headers?: Record<string, any>;
11
+ redirect?: string;
12
+ body?: any;
13
+ size?: number;
14
+ time?: number;
15
+ }
16
+
17
+ export default class Response {
18
+
19
+ /** 响应HTTP状态码 */
20
+ statusCode: number;
21
+ /** 响应内容类型 */
22
+ type: string;
23
+ /** 响应headers */
24
+ headers: Record<string, any>;
25
+ /** 重定向目标 */
26
+ redirect: string;
27
+ /** 响应载荷 */
28
+ body: any;
29
+ /** 响应载荷大小 */
30
+ size: number;
31
+ /** 响应时间戳 */
32
+ time: number;
33
+
34
+ constructor(body: any, options: ResponseOptions = {}) {
35
+ const { statusCode, type, headers, redirect, size, time } = options;
36
+ this.statusCode = Number(_.defaultTo(statusCode, Body.isInstance(body) ? body.statusCode : undefined))
37
+ this.type = type;
38
+ this.headers = headers;
39
+ this.redirect = redirect;
40
+ this.size = size;
41
+ this.time = Number(_.defaultTo(time, util.timestamp()));
42
+ this.body = body;
43
+ }
44
+
45
+ injectTo(ctx) {
46
+ this.redirect && ctx.redirect(this.redirect);
47
+ this.statusCode && (ctx.status = this.statusCode);
48
+ this.type && (ctx.type = mime.getType(this.type) || this.type);
49
+ const headers = this.headers || {};
50
+ if(this.size && !headers["Content-Length"] && !headers["content-length"])
51
+ headers["Content-Length"] = this.size;
52
+ ctx.set(headers);
53
+ if(Body.isInstance(this.body))
54
+ ctx.body = this.body.toObject();
55
+ else
56
+ ctx.body = this.body;
57
+ }
58
+
59
+ static isInstance(value) {
60
+ return value instanceof Response;
61
+ }
62
+
63
+ }
src/lib/response/SuccessfulBody.ts ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import _ from 'lodash';
2
+
3
+ import Body from './Body.ts';
4
+
5
+ export default class SuccessfulBody extends Body {
6
+
7
+ constructor(data: any, message?: string) {
8
+ super({
9
+ code: 0,
10
+ message: _.defaultTo(message, "OK"),
11
+ data
12
+ });
13
+ }
14
+
15
+ static isInstance(value) {
16
+ return value instanceof SuccessfulBody;
17
+ }
18
+
19
+ }
src/lib/server.ts ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Koa from 'koa';
2
+ import KoaRouter from 'koa-router';
3
+ import koaRange from 'koa-range';
4
+ import koaCors from "koa2-cors";
5
+ import koaBody from 'koa-body';
6
+ import _ from 'lodash';
7
+
8
+ import Exception from './exceptions/Exception.ts';
9
+ import Request from './request/Request.ts';
10
+ import Response from './response/Response.js';
11
+ import FailureBody from './response/FailureBody.ts';
12
+ import EX from './consts/exceptions.ts';
13
+ import logger from './logger.ts';
14
+ import config from './config.ts';
15
+
16
+ class Server {
17
+
18
+ app;
19
+ router;
20
+
21
+ constructor() {
22
+ this.app = new Koa();
23
+ this.app.use(koaCors());
24
+ // 范围请求支持
25
+ this.app.use(koaRange);
26
+ this.router = new KoaRouter({ prefix: config.service.urlPrefix });
27
+ // 前置处理异常拦截
28
+ this.app.use(async (ctx: any, next: Function) => {
29
+ if(ctx.request.type === "application/xml" || ctx.request.type === "application/ssml+xml")
30
+ ctx.req.headers["content-type"] = "text/xml";
31
+ try { await next() }
32
+ catch (err) {
33
+ logger.error(err);
34
+ const failureBody = new FailureBody(err);
35
+ new Response(failureBody).injectTo(ctx);
36
+ }
37
+ });
38
+ // 载荷解析器支持
39
+ this.app.use(koaBody(_.clone(config.system.requestBody)));
40
+ this.app.on("error", (err: any) => {
41
+ // 忽略连接重试、中断、管道、取消错误
42
+ if (["ECONNRESET", "ECONNABORTED", "EPIPE", "ECANCELED"].includes(err.code)) return;
43
+ logger.error(err);
44
+ });
45
+ logger.success("Server initialized");
46
+ }
47
+
48
+ /**
49
+ * 附加路由
50
+ *
51
+ * @param routes 路由列表
52
+ */
53
+ attachRoutes(routes: any[]) {
54
+ routes.forEach((route: any) => {
55
+ const prefix = route.prefix || "";
56
+ for (let method in route) {
57
+ if(method === "prefix") continue;
58
+ if (!_.isObject(route[method])) {
59
+ logger.warn(`Router ${prefix} ${method} invalid`);
60
+ continue;
61
+ }
62
+ for (let uri in route[method]) {
63
+ this.router[method](`${prefix}${uri}`, async ctx => {
64
+ const { request, response } = await this.#requestProcessing(ctx, route[method][uri]);
65
+ if(response != null && config.system.requestLog)
66
+ logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
67
+ });
68
+ }
69
+ }
70
+ logger.info(`Route ${config.service.urlPrefix || ""}${prefix} attached`);
71
+ });
72
+ this.app.use(this.router.routes());
73
+ this.app.use((ctx: any) => {
74
+ const request = new Request(ctx);
75
+ logger.debug(`-> ${ctx.request.method} ${ctx.request.url} request is not supported - ${request.remoteIP || "unknown"}`);
76
+ // const failureBody = new FailureBody(new Exception(EX.SYSTEM_NOT_ROUTE_MATCHING, "Request is not supported"));
77
+ // const response = new Response(failureBody);
78
+ const message = `[请求有误]: 正确请求为 POST -> /v1/chat/completions,当前请求为 ${ctx.request.method} -> ${ctx.request.url} 请纠正`;
79
+ logger.warn(message);
80
+ const failureBody = new FailureBody(new Error(message));
81
+ const response = new Response(failureBody);
82
+ response.injectTo(ctx);
83
+ if(config.system.requestLog)
84
+ logger.info(`<- ${request.method} ${request.url} ${response.time - request.time}ms`);
85
+ });
86
+ }
87
+
88
+ /**
89
+ * 请求处理
90
+ *
91
+ * @param ctx 上下文
92
+ * @param routeFn 路由方法
93
+ */
94
+ #requestProcessing(ctx: any, routeFn: Function): Promise<any> {
95
+ return new Promise(resolve => {
96
+ const request = new Request(ctx);
97
+ try {
98
+ if(config.system.requestLog)
99
+ logger.info(`-> ${request.method} ${request.url}`);
100
+ routeFn(request)
101
+ .then(response => {
102
+ try {
103
+ if(!Response.isInstance(response)) {
104
+ const _response = new Response(response);
105
+ _response.injectTo(ctx);
106
+ return resolve({ request, response: _response });
107
+ }
108
+ response.injectTo(ctx);
109
+ resolve({ request, response });
110
+ }
111
+ catch(err) {
112
+ logger.error(err);
113
+ const failureBody = new FailureBody(err);
114
+ const response = new Response(failureBody);
115
+ response.injectTo(ctx);
116
+ resolve({ request, response });
117
+ }
118
+ })
119
+ .catch(err => {
120
+ try {
121
+ logger.error(err);
122
+ const failureBody = new FailureBody(err);
123
+ const response = new Response(failureBody);
124
+ response.injectTo(ctx);
125
+ resolve({ request, response });
126
+ }
127
+ catch(err) {
128
+ logger.error(err);
129
+ const failureBody = new FailureBody(err);
130
+ const response = new Response(failureBody);
131
+ response.injectTo(ctx);
132
+ resolve({ request, response });
133
+ }
134
+ });
135
+ }
136
+ catch(err) {
137
+ logger.error(err);
138
+ const failureBody = new FailureBody(err);
139
+ const response = new Response(failureBody);
140
+ response.injectTo(ctx);
141
+ resolve({ request, response });
142
+ }
143
+ });
144
+ }
145
+
146
+ /**
147
+ * 监听端口
148
+ */
149
+ async listen() {
150
+ const host = config.service.host;
151
+ const port = config.service.port;
152
+ await Promise.all([
153
+ new Promise((resolve, reject) => {
154
+ if(host === "0.0.0.0" || host === "localhost" || host === "127.0.0.1")
155
+ return resolve(null);
156
+ this.app.listen(port, "localhost", err => {
157
+ if(err) return reject(err);
158
+ resolve(null);
159
+ });
160
+ }),
161
+ new Promise((resolve, reject) => {
162
+ this.app.listen(port, host, err => {
163
+ if(err) return reject(err);
164
+ resolve(null);
165
+ });
166
+ })
167
+ ]);
168
+ logger.success(`Server listening on port ${port} (${host})`);
169
+ }
170
+
171
+ }
172
+
173
+ export default new Server();
src/lib/util.ts ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os from "os";
2
+ import path from "path";
3
+ import crypto from "crypto";
4
+ import { Readable, Writable } from "stream";
5
+
6
+ import "colors";
7
+ import mime from "mime";
8
+ import axios from "axios";
9
+ import fs from "fs-extra";
10
+ import { v1 as uuid } from "uuid";
11
+ import { format as dateFormat } from "date-fns";
12
+ import CRC32 from "crc-32";
13
+ import randomstring from "randomstring";
14
+ import _ from "lodash";
15
+ import { CronJob } from "cron";
16
+
17
+ import HTTP_STATUS_CODE from "./http-status-codes.ts";
18
+
19
+ const autoIdMap = new Map();
20
+
21
+ const util = {
22
+ is2DArrays(value: any) {
23
+ return (
24
+ _.isArray(value) &&
25
+ (!value[0] || (_.isArray(value[0]) && _.isArray(value[value.length - 1])))
26
+ );
27
+ },
28
+
29
+ uuid: (separator = true) => (separator ? uuid() : uuid().replace(/\-/g, "")),
30
+
31
+ autoId: (prefix = "") => {
32
+ let index = autoIdMap.get(prefix);
33
+ if (index > 999999) index = 0; //超过最大数字则重置为0
34
+ autoIdMap.set(prefix, (index || 0) + 1);
35
+ return `${prefix}${index || 1}`;
36
+ },
37
+
38
+ ignoreJSONParse(value: string) {
39
+ const result = _.attempt(() => JSON.parse(value));
40
+ if (_.isError(result)) return null;
41
+ return result;
42
+ },
43
+
44
+ generateRandomString(options: any): string {
45
+ return randomstring.generate(options);
46
+ },
47
+
48
+ getResponseContentType(value: any): string | null {
49
+ return value.headers
50
+ ? value.headers["content-type"] || value.headers["Content-Type"]
51
+ : null;
52
+ },
53
+
54
+ mimeToExtension(value: string) {
55
+ let extension = mime.getExtension(value);
56
+ if (extension == "mpga") return "mp3";
57
+ return extension;
58
+ },
59
+
60
+ extractURLExtension(value: string) {
61
+ const extname = path.extname(new URL(value).pathname);
62
+ return extname.substring(1).toLowerCase();
63
+ },
64
+
65
+ createCronJob(cronPatterns: any, callback?: Function) {
66
+ if (!_.isFunction(callback))
67
+ throw new Error("callback must be an Function");
68
+ return new CronJob(
69
+ cronPatterns,
70
+ () => callback(),
71
+ null,
72
+ false,
73
+ "Asia/Shanghai"
74
+ );
75
+ },
76
+
77
+ getDateString(format = "yyyy-MM-dd", date = new Date()) {
78
+ return dateFormat(date, format);
79
+ },
80
+
81
+ getIPAddressesByIPv4(): string[] {
82
+ const interfaces = os.networkInterfaces();
83
+ const addresses = [];
84
+ for (let name in interfaces) {
85
+ const networks = interfaces[name];
86
+ const results = networks.filter(
87
+ (network) =>
88
+ network.family === "IPv4" &&
89
+ network.address !== "127.0.0.1" &&
90
+ !network.internal
91
+ );
92
+ if (results[0] && results[0].address) addresses.push(results[0].address);
93
+ }
94
+ return addresses;
95
+ },
96
+
97
+ getMACAddressesByIPv4(): string[] {
98
+ const interfaces = os.networkInterfaces();
99
+ const addresses = [];
100
+ for (let name in interfaces) {
101
+ const networks = interfaces[name];
102
+ const results = networks.filter(
103
+ (network) =>
104
+ network.family === "IPv4" &&
105
+ network.address !== "127.0.0.1" &&
106
+ !network.internal
107
+ );
108
+ if (results[0] && results[0].mac) addresses.push(results[0].mac);
109
+ }
110
+ return addresses;
111
+ },
112
+
113
+ generateSSEData(event?: string, data?: string, retry?: number) {
114
+ return `event: ${event || "message"}\ndata: ${(data || "")
115
+ .replace(/\n/g, "\\n")
116
+ .replace(/\s/g, "\\s")}\nretry: ${retry || 3000}\n\n`;
117
+ },
118
+
119
+ buildDataBASE64(type, ext, buffer) {
120
+ return `data:${type}/${ext.replace("jpg", "jpeg")};base64,${buffer.toString(
121
+ "base64"
122
+ )}`;
123
+ },
124
+
125
+ isLinux() {
126
+ return os.platform() !== "win32";
127
+ },
128
+
129
+ isIPAddress(value) {
130
+ return (
131
+ _.isString(value) &&
132
+ (/^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/.test(
133
+ value
134
+ ) ||
135
+ /\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*/.test(
136
+ value
137
+ ))
138
+ );
139
+ },
140
+
141
+ isPort(value) {
142
+ return _.isNumber(value) && value > 0 && value < 65536;
143
+ },
144
+
145
+ isReadStream(value): boolean {
146
+ return (
147
+ value &&
148
+ (value instanceof Readable || "readable" in value || value.readable)
149
+ );
150
+ },
151
+
152
+ isWriteStream(value): boolean {
153
+ return (
154
+ value &&
155
+ (value instanceof Writable || "writable" in value || value.writable)
156
+ );
157
+ },
158
+
159
+ isHttpStatusCode(value) {
160
+ return _.isNumber(value) && Object.values(HTTP_STATUS_CODE).includes(value);
161
+ },
162
+
163
+ isURL(value) {
164
+ return !_.isUndefined(value) && /^(http|https)/.test(value);
165
+ },
166
+
167
+ isSrc(value) {
168
+ return !_.isUndefined(value) && /^\/.+\.[0-9a-zA-Z]+(\?.+)?$/.test(value);
169
+ },
170
+
171
+ isBASE64(value) {
172
+ return !_.isUndefined(value) && /^[a-zA-Z0-9\/\+]+(=?)+$/.test(value);
173
+ },
174
+
175
+ isBASE64Data(value) {
176
+ return /^data:/.test(value);
177
+ },
178
+
179
+ extractBASE64DataFormat(value): string | null {
180
+ const match = value.trim().match(/^data:(.+);base64,/);
181
+ if (!match) return null;
182
+ return match[1];
183
+ },
184
+
185
+ removeBASE64DataHeader(value): string {
186
+ return value.replace(/^data:(.+);base64,/, "");
187
+ },
188
+
189
+ isDataString(value): boolean {
190
+ return /^(base64|json):/.test(value);
191
+ },
192
+
193
+ isStringNumber(value) {
194
+ return _.isFinite(Number(value));
195
+ },
196
+
197
+ isUnixTimestamp(value) {
198
+ return /^[0-9]{10}$/.test(`${value}`);
199
+ },
200
+
201
+ isTimestamp(value) {
202
+ return /^[0-9]{13}$/.test(`${value}`);
203
+ },
204
+
205
+ isEmail(value) {
206
+ return /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
207
+ value
208
+ );
209
+ },
210
+
211
+ isAsyncFunction(value) {
212
+ return Object.prototype.toString.call(value) === "[object AsyncFunction]";
213
+ },
214
+
215
+ async isAPNG(filePath) {
216
+ let head;
217
+ const readStream = fs.createReadStream(filePath, { start: 37, end: 40 });
218
+ const readPromise = new Promise((resolve, reject) => {
219
+ readStream.once("end", resolve);
220
+ readStream.once("error", reject);
221
+ });
222
+ readStream.once("data", (data) => (head = data));
223
+ await readPromise;
224
+ return head.compare(Buffer.from([0x61, 0x63, 0x54, 0x4c])) === 0;
225
+ },
226
+
227
+ unixTimestamp() {
228
+ return parseInt(`${Date.now() / 1000}`);
229
+ },
230
+
231
+ timestamp() {
232
+ return Date.now();
233
+ },
234
+
235
+ urlJoin(...values) {
236
+ let url = "";
237
+ for (let i = 0; i < values.length; i++)
238
+ url += `${i > 0 ? "/" : ""}${values[i]
239
+ .replace(/^\/*/, "")
240
+ .replace(/\/*$/, "")}`;
241
+ return url;
242
+ },
243
+
244
+ millisecondsToHmss(milliseconds) {
245
+ if (_.isString(milliseconds)) return milliseconds;
246
+ milliseconds = parseInt(milliseconds);
247
+ const sec = Math.floor(milliseconds / 1000);
248
+ const hours = Math.floor(sec / 3600);
249
+ const minutes = Math.floor((sec - hours * 3600) / 60);
250
+ const seconds = sec - hours * 3600 - minutes * 60;
251
+ const ms = (milliseconds % 60000) - seconds * 1000;
252
+ return `${hours > 9 ? hours : "0" + hours}:${
253
+ minutes > 9 ? minutes : "0" + minutes
254
+ }:${seconds > 9 ? seconds : "0" + seconds}.${ms}`;
255
+ },
256
+
257
+ millisecondsToTimeString(milliseconds) {
258
+ if (milliseconds < 1000) return `${milliseconds}ms`;
259
+ if (milliseconds < 60000)
260
+ return `${parseFloat((milliseconds / 1000).toFixed(2))}s`;
261
+ return `${Math.floor(milliseconds / 1000 / 60)}m${Math.floor(
262
+ (milliseconds / 1000) % 60
263
+ )}s`;
264
+ },
265
+
266
+ rgbToHex(r, g, b): string {
267
+ return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
268
+ },
269
+
270
+ hexToRgb(hex) {
271
+ const value = parseInt(hex.replace(/^#/, ""), 16);
272
+ return [(value >> 16) & 255, (value >> 8) & 255, value & 255];
273
+ },
274
+
275
+ md5(value) {
276
+ return crypto.createHash("md5").update(value).digest("hex");
277
+ },
278
+
279
+ crc32(value) {
280
+ return _.isBuffer(value) ? CRC32.buf(value) : CRC32.str(value);
281
+ },
282
+
283
+ arrayParse(value): any[] {
284
+ return _.isArray(value) ? value : [value];
285
+ },
286
+
287
+ booleanParse(value) {
288
+ return value === "true" || value === true ? true : false;
289
+ },
290
+
291
+ encodeBASE64(value) {
292
+ return Buffer.from(value).toString("base64");
293
+ },
294
+
295
+ decodeBASE64(value) {
296
+ return Buffer.from(value, "base64").toString();
297
+ },
298
+
299
+ async fetchFileBASE64(url: string) {
300
+ const result = await axios.get(url, {
301
+ responseType: "arraybuffer",
302
+ });
303
+ return result.data.toString("base64");
304
+ },
305
+ };
306
+
307
+ export default util;
tsconfig.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "baseUrl": ".",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "allowImportingTsExtensions": true,
7
+ "allowSyntheticDefaultImports": true,
8
+ "noEmit": true,
9
+ "paths": {
10
+ "@/*": ["src/*"]
11
+ },
12
+ "outDir": "./dist"
13
+ },
14
+ "include": ["src/**/*", "libs.d.ts"],
15
+ "exclude": ["node_modules", "dist"]
16
+ }
vercel.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "builds": [
3
+ {
4
+ "src": "./dist/*.html",
5
+ "use": "@vercel/static"
6
+ },
7
+ {
8
+ "src": "./dist/index.js",
9
+ "use": "@vercel/node"
10
+ }
11
+ ],
12
+ "routes": [
13
+ {
14
+ "src": "/",
15
+ "dest": "/dist/welcome.html"
16
+ },
17
+ {
18
+ "src": "/(.*)",
19
+ "dest": "/dist",
20
+ "headers": {
21
+ "Access-Control-Allow-Credentials": "true",
22
+ "Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT",
23
+ "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Content-Type, Authorization"
24
+ }
25
+ }
26
+ ]
27
+ }