@kevisual/router 0.0.26 → 0.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auto.js DELETED
@@ -1,4789 +0,0 @@
1
- import { webcrypto } from 'node:crypto';
2
- import { createConnection } from 'node:net';
3
-
4
- const getRuntime = () => {
5
- // @ts-ignore
6
- if (typeof Deno !== 'undefined') {
7
- return { isDeno: true, engine: 'deno' };
8
- }
9
- // @ts-ignore
10
- if (typeof Bun !== 'undefined') {
11
- return { isBun: true, engine: 'bun' };
12
- }
13
- return { isNode: true, engine: 'node' };
14
- };
15
-
16
- const glob = async (match = './*.ts', { cwd = process.cwd() } = {}) => {
17
- const fs = await import('node:fs');
18
- const path = await import('node:path');
19
- // 将 glob 模式转换为正则表达式
20
- const globToRegex = (pattern) => {
21
- const escaped = pattern
22
- .replace(/\./g, '\\.')
23
- .replace(/\*\*/g, '__DOUBLE_STAR__') // 临时替换 **
24
- .replace(/\*/g, '[^/]*') // * 匹配除 / 外的任意字符
25
- .replace(/__DOUBLE_STAR__/g, '.*') // ** 匹配任意字符包括 /
26
- .replace(/\?/g, '[^/]'); // ? 匹配除 / 外的单个字符
27
- return new RegExp(`^${escaped}$`);
28
- };
29
- // 递归读取目录
30
- const readDirRecursive = async (dir) => {
31
- const files = [];
32
- try {
33
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
34
- for (const entry of entries) {
35
- const fullPath = path.join(dir, entry.name);
36
- if (entry.isFile()) {
37
- files.push(fullPath);
38
- }
39
- else if (entry.isDirectory()) {
40
- // 递归搜索子目录
41
- const subFiles = await readDirRecursive(fullPath);
42
- files.push(...subFiles);
43
- }
44
- }
45
- }
46
- catch (error) {
47
- // 忽略无法访问的目录
48
- }
49
- return files;
50
- };
51
- // 解析模式是否包含递归搜索
52
- const hasRecursive = match.includes('**');
53
- try {
54
- let allFiles = [];
55
- if (hasRecursive) {
56
- // 处理递归模式
57
- const basePath = match.split('**')[0];
58
- const startDir = path.resolve(cwd, basePath || '.');
59
- allFiles = await readDirRecursive(startDir);
60
- }
61
- else {
62
- // 处理非递归模式
63
- const dir = path.resolve(cwd, path.dirname(match));
64
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
65
- for (const entry of entries) {
66
- if (entry.isFile()) {
67
- allFiles.push(path.join(dir, entry.name));
68
- }
69
- }
70
- }
71
- // 创建相对于 cwd 的匹配模式
72
- const normalizedMatch = path.resolve(cwd, match);
73
- const regex = globToRegex(normalizedMatch);
74
- // 过滤匹配的文件
75
- const matchedFiles = allFiles.filter(file => {
76
- const normalizedFile = path.resolve(file);
77
- return regex.test(normalizedFile);
78
- });
79
- return matchedFiles;
80
- }
81
- catch (error) {
82
- console.error(`Error in glob pattern "${match}":`, error);
83
- return [];
84
- }
85
- };
86
-
87
- const getMatchFiles = async (match = './*.ts', { cwd = process.cwd() } = {}) => {
88
- const runtime = getRuntime();
89
- if (runtime.isNode) {
90
- console.error(`Node.js is not supported`);
91
- return [];
92
- }
93
- if (runtime.isDeno) {
94
- // Deno 环境下
95
- return await glob(match);
96
- }
97
- if (runtime.isBun) {
98
- // Bun 环境下
99
- // @ts-ignore
100
- const { Glob } = await import('bun');
101
- const path = await import('node:path');
102
- // @ts-ignore
103
- const glob = new Glob(match, { cwd, absolute: true, onlyFiles: true });
104
- const files = [];
105
- for await (const file of glob.scan('.')) {
106
- files.push(path.join(cwd, file));
107
- }
108
- // @ts-ignore
109
- return Array.from(files);
110
- }
111
- return [];
112
- };
113
- const loadTS = async (match = './*.ts', { cwd = process.cwd(), load } = {}) => {
114
- const files = await getMatchFiles(match, { cwd });
115
- return Promise.all(files.map((file) => (load ? load(file) : import(file))));
116
- };
117
-
118
- const urlAlphabet =
119
- 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
120
-
121
- const POOL_SIZE_MULTIPLIER = 128;
122
- let pool, poolOffset;
123
- function fillPool(bytes) {
124
- if (!pool || pool.length < bytes) {
125
- pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
126
- webcrypto.getRandomValues(pool);
127
- poolOffset = 0;
128
- } else if (poolOffset + bytes > pool.length) {
129
- webcrypto.getRandomValues(pool);
130
- poolOffset = 0;
131
- }
132
- poolOffset += bytes;
133
- }
134
- function nanoid$1(size = 21) {
135
- fillPool((size |= 0));
136
- let id = '';
137
- for (let i = poolOffset - size; i < poolOffset; i++) {
138
- id += urlAlphabet[pool[i] & 63];
139
- }
140
- return id
141
- }
142
-
143
- /** 自定义错误 */
144
- class CustomError extends Error {
145
- code;
146
- data;
147
- message;
148
- tips;
149
- constructor(code, message, tips) {
150
- super(message || String(code));
151
- this.name = 'CustomError';
152
- if (typeof code === 'number') {
153
- this.code = code;
154
- this.message = message;
155
- }
156
- else {
157
- this.code = 500;
158
- this.message = code;
159
- }
160
- this.tips = tips;
161
- // 这一步可不写,默认会保存堆栈追踪信息到自定义错误构造函数之前,
162
- // 而如果写成 `Error.captureStackTrace(this)` 则自定义错误的构造函数也会被保存到堆栈追踪信息
163
- Error.captureStackTrace(this, this.constructor);
164
- }
165
- static fromCode(code) {
166
- return new this(code);
167
- }
168
- static fromErrorData(code, data) {
169
- const error = new this(code);
170
- error.data = data;
171
- return error;
172
- }
173
- static parseError(e) {
174
- return {
175
- code: e?.code,
176
- data: e?.data,
177
- message: e?.message,
178
- tips: e?.tips,
179
- };
180
- }
181
- /**
182
- * 判断 throw 的错误是否不是当前这个错误
183
- * @param err
184
- * @returns
185
- */
186
- static isError(err) {
187
- if (err instanceof CustomError || err?.code) {
188
- return true;
189
- }
190
- return false;
191
- }
192
- parse(e) {
193
- if (e) {
194
- return CustomError.parseError(e);
195
- }
196
- else {
197
- const e = this;
198
- return {
199
- code: e?.code,
200
- data: e?.data,
201
- message: e?.message,
202
- tips: e?.tips,
203
- };
204
- }
205
- }
206
- }
207
- /*
208
- try {
209
- //
210
- } catch(e) {
211
- if (e instanceof CustomError) {
212
- const errorInfo = e.parse();
213
- if (dev) {
214
- return {
215
- error: errorInfo,
216
- };
217
- } else {
218
- return errorInfo;
219
- }
220
- }
221
- }
222
- */
223
-
224
- /** A special constant with type `never` */
225
- function $constructor(name, initializer, params) {
226
- function init(inst, def) {
227
- var _a;
228
- Object.defineProperty(inst, "_zod", {
229
- value: inst._zod ?? {},
230
- enumerable: false,
231
- });
232
- (_a = inst._zod).traits ?? (_a.traits = new Set());
233
- inst._zod.traits.add(name);
234
- initializer(inst, def);
235
- // support prototype modifications
236
- for (const k in _.prototype) {
237
- if (!(k in inst))
238
- Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
239
- }
240
- inst._zod.constr = _;
241
- inst._zod.def = def;
242
- }
243
- // doesn't work if Parent has a constructor with arguments
244
- const Parent = params?.Parent ?? Object;
245
- class Definition extends Parent {
246
- }
247
- Object.defineProperty(Definition, "name", { value: name });
248
- function _(def) {
249
- var _a;
250
- const inst = params?.Parent ? new Definition() : this;
251
- init(inst, def);
252
- (_a = inst._zod).deferred ?? (_a.deferred = []);
253
- for (const fn of inst._zod.deferred) {
254
- fn();
255
- }
256
- return inst;
257
- }
258
- Object.defineProperty(_, "init", { value: init });
259
- Object.defineProperty(_, Symbol.hasInstance, {
260
- value: (inst) => {
261
- if (params?.Parent && inst instanceof params.Parent)
262
- return true;
263
- return inst?._zod?.traits?.has(name);
264
- },
265
- });
266
- Object.defineProperty(_, "name", { value: name });
267
- return _;
268
- }
269
- class $ZodAsyncError extends Error {
270
- constructor() {
271
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
272
- }
273
- }
274
- const globalConfig = {};
275
- function config(newConfig) {
276
- return globalConfig;
277
- }
278
-
279
- // functions
280
- function getEnumValues(entries) {
281
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
282
- const values = Object.entries(entries)
283
- .filter(([k, _]) => numericValues.indexOf(+k) === -1)
284
- .map(([_, v]) => v);
285
- return values;
286
- }
287
- function jsonStringifyReplacer(_, value) {
288
- if (typeof value === "bigint")
289
- return value.toString();
290
- return value;
291
- }
292
- function cached(getter) {
293
- return {
294
- get value() {
295
- {
296
- const value = getter();
297
- Object.defineProperty(this, "value", { value });
298
- return value;
299
- }
300
- },
301
- };
302
- }
303
- function nullish(input) {
304
- return input === null || input === undefined;
305
- }
306
- function cleanRegex(source) {
307
- const start = source.startsWith("^") ? 1 : 0;
308
- const end = source.endsWith("$") ? source.length - 1 : source.length;
309
- return source.slice(start, end);
310
- }
311
- function floatSafeRemainder(val, step) {
312
- const valDecCount = (val.toString().split(".")[1] || "").length;
313
- const stepString = step.toString();
314
- let stepDecCount = (stepString.split(".")[1] || "").length;
315
- if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
316
- const match = stepString.match(/\d?e-(\d?)/);
317
- if (match?.[1]) {
318
- stepDecCount = Number.parseInt(match[1]);
319
- }
320
- }
321
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
322
- const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
323
- const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
324
- return (valInt % stepInt) / 10 ** decCount;
325
- }
326
- const EVALUATING = Symbol("evaluating");
327
- function defineLazy(object, key, getter) {
328
- let value = undefined;
329
- Object.defineProperty(object, key, {
330
- get() {
331
- if (value === EVALUATING) {
332
- // Circular reference detected, return undefined to break the cycle
333
- return undefined;
334
- }
335
- if (value === undefined) {
336
- value = EVALUATING;
337
- value = getter();
338
- }
339
- return value;
340
- },
341
- set(v) {
342
- Object.defineProperty(object, key, {
343
- value: v,
344
- // configurable: true,
345
- });
346
- // object[key] = v;
347
- },
348
- configurable: true,
349
- });
350
- }
351
- function objectClone(obj) {
352
- return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
353
- }
354
- function assignProp(target, prop, value) {
355
- Object.defineProperty(target, prop, {
356
- value,
357
- writable: true,
358
- enumerable: true,
359
- configurable: true,
360
- });
361
- }
362
- function mergeDefs(...defs) {
363
- const mergedDescriptors = {};
364
- for (const def of defs) {
365
- const descriptors = Object.getOwnPropertyDescriptors(def);
366
- Object.assign(mergedDescriptors, descriptors);
367
- }
368
- return Object.defineProperties({}, mergedDescriptors);
369
- }
370
- function esc(str) {
371
- return JSON.stringify(str);
372
- }
373
- const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
374
- function isObject(data) {
375
- return typeof data === "object" && data !== null && !Array.isArray(data);
376
- }
377
- const allowsEval = cached(() => {
378
- // @ts-ignore
379
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
380
- return false;
381
- }
382
- try {
383
- const F = Function;
384
- new F("");
385
- return true;
386
- }
387
- catch (_) {
388
- return false;
389
- }
390
- });
391
- function isPlainObject(o) {
392
- if (isObject(o) === false)
393
- return false;
394
- // modified constructor
395
- const ctor = o.constructor;
396
- if (ctor === undefined)
397
- return true;
398
- // modified prototype
399
- const prot = ctor.prototype;
400
- if (isObject(prot) === false)
401
- return false;
402
- // ctor doesn't have static `isPrototypeOf`
403
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
404
- return false;
405
- }
406
- return true;
407
- }
408
- function shallowClone(o) {
409
- if (isPlainObject(o))
410
- return { ...o };
411
- return o;
412
- }
413
- const propertyKeyTypes = new Set(["string", "number", "symbol"]);
414
- function escapeRegex(str) {
415
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
416
- }
417
- // zod-specific utils
418
- function clone(inst, def, params) {
419
- const cl = new inst._zod.constr(def ?? inst._zod.def);
420
- if (!def || params?.parent)
421
- cl._zod.parent = inst;
422
- return cl;
423
- }
424
- function normalizeParams(_params) {
425
- const params = _params;
426
- if (!params)
427
- return {};
428
- if (typeof params === "string")
429
- return { error: () => params };
430
- if (params?.message !== undefined) {
431
- if (params?.error !== undefined)
432
- throw new Error("Cannot specify both `message` and `error` params");
433
- params.error = params.message;
434
- }
435
- delete params.message;
436
- if (typeof params.error === "string")
437
- return { ...params, error: () => params.error };
438
- return params;
439
- }
440
- function optionalKeys(shape) {
441
- return Object.keys(shape).filter((k) => {
442
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
443
- });
444
- }
445
- const NUMBER_FORMAT_RANGES = {
446
- safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
447
- int32: [-2147483648, 2147483647],
448
- uint32: [0, 4294967295],
449
- float32: [-34028234663852886e22, 3.4028234663852886e38],
450
- float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
451
- };
452
- function pick$1(schema, mask) {
453
- const currDef = schema._zod.def;
454
- const def = mergeDefs(schema._zod.def, {
455
- get shape() {
456
- const newShape = {};
457
- for (const key in mask) {
458
- if (!(key in currDef.shape)) {
459
- throw new Error(`Unrecognized key: "${key}"`);
460
- }
461
- if (!mask[key])
462
- continue;
463
- newShape[key] = currDef.shape[key];
464
- }
465
- assignProp(this, "shape", newShape); // self-caching
466
- return newShape;
467
- },
468
- checks: [],
469
- });
470
- return clone(schema, def);
471
- }
472
- function omit(schema, mask) {
473
- const currDef = schema._zod.def;
474
- const def = mergeDefs(schema._zod.def, {
475
- get shape() {
476
- const newShape = { ...schema._zod.def.shape };
477
- for (const key in mask) {
478
- if (!(key in currDef.shape)) {
479
- throw new Error(`Unrecognized key: "${key}"`);
480
- }
481
- if (!mask[key])
482
- continue;
483
- delete newShape[key];
484
- }
485
- assignProp(this, "shape", newShape); // self-caching
486
- return newShape;
487
- },
488
- checks: [],
489
- });
490
- return clone(schema, def);
491
- }
492
- function extend(schema, shape) {
493
- if (!isPlainObject(shape)) {
494
- throw new Error("Invalid input to extend: expected a plain object");
495
- }
496
- const def = mergeDefs(schema._zod.def, {
497
- get shape() {
498
- const _shape = { ...schema._zod.def.shape, ...shape };
499
- assignProp(this, "shape", _shape); // self-caching
500
- return _shape;
501
- },
502
- checks: [],
503
- });
504
- return clone(schema, def);
505
- }
506
- function merge(a, b) {
507
- const def = mergeDefs(a._zod.def, {
508
- get shape() {
509
- const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
510
- assignProp(this, "shape", _shape); // self-caching
511
- return _shape;
512
- },
513
- get catchall() {
514
- return b._zod.def.catchall;
515
- },
516
- checks: [], // delete existing checks
517
- });
518
- return clone(a, def);
519
- }
520
- function partial(Class, schema, mask) {
521
- const def = mergeDefs(schema._zod.def, {
522
- get shape() {
523
- const oldShape = schema._zod.def.shape;
524
- const shape = { ...oldShape };
525
- if (mask) {
526
- for (const key in mask) {
527
- if (!(key in oldShape)) {
528
- throw new Error(`Unrecognized key: "${key}"`);
529
- }
530
- if (!mask[key])
531
- continue;
532
- // if (oldShape[key]!._zod.optin === "optional") continue;
533
- shape[key] = Class
534
- ? new Class({
535
- type: "optional",
536
- innerType: oldShape[key],
537
- })
538
- : oldShape[key];
539
- }
540
- }
541
- else {
542
- for (const key in oldShape) {
543
- // if (oldShape[key]!._zod.optin === "optional") continue;
544
- shape[key] = Class
545
- ? new Class({
546
- type: "optional",
547
- innerType: oldShape[key],
548
- })
549
- : oldShape[key];
550
- }
551
- }
552
- assignProp(this, "shape", shape); // self-caching
553
- return shape;
554
- },
555
- checks: [],
556
- });
557
- return clone(schema, def);
558
- }
559
- function required(Class, schema, mask) {
560
- const def = mergeDefs(schema._zod.def, {
561
- get shape() {
562
- const oldShape = schema._zod.def.shape;
563
- const shape = { ...oldShape };
564
- if (mask) {
565
- for (const key in mask) {
566
- if (!(key in shape)) {
567
- throw new Error(`Unrecognized key: "${key}"`);
568
- }
569
- if (!mask[key])
570
- continue;
571
- // overwrite with non-optional
572
- shape[key] = new Class({
573
- type: "nonoptional",
574
- innerType: oldShape[key],
575
- });
576
- }
577
- }
578
- else {
579
- for (const key in oldShape) {
580
- // overwrite with non-optional
581
- shape[key] = new Class({
582
- type: "nonoptional",
583
- innerType: oldShape[key],
584
- });
585
- }
586
- }
587
- assignProp(this, "shape", shape); // self-caching
588
- return shape;
589
- },
590
- checks: [],
591
- });
592
- return clone(schema, def);
593
- }
594
- // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
595
- function aborted(x, startIndex = 0) {
596
- for (let i = startIndex; i < x.issues.length; i++) {
597
- if (x.issues[i]?.continue !== true) {
598
- return true;
599
- }
600
- }
601
- return false;
602
- }
603
- function prefixIssues(path, issues) {
604
- return issues.map((iss) => {
605
- var _a;
606
- (_a = iss).path ?? (_a.path = []);
607
- iss.path.unshift(path);
608
- return iss;
609
- });
610
- }
611
- function unwrapMessage(message) {
612
- return typeof message === "string" ? message : message?.message;
613
- }
614
- function finalizeIssue(iss, ctx, config) {
615
- const full = { ...iss, path: iss.path ?? [] };
616
- // for backwards compatibility
617
- if (!iss.message) {
618
- const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??
619
- unwrapMessage(ctx?.error?.(iss)) ??
620
- unwrapMessage(config.customError?.(iss)) ??
621
- unwrapMessage(config.localeError?.(iss)) ??
622
- "Invalid input";
623
- full.message = message;
624
- }
625
- // delete (full as any).def;
626
- delete full.inst;
627
- delete full.continue;
628
- if (!ctx?.reportInput) {
629
- delete full.input;
630
- }
631
- return full;
632
- }
633
- function getLengthableOrigin(input) {
634
- if (Array.isArray(input))
635
- return "array";
636
- if (typeof input === "string")
637
- return "string";
638
- return "unknown";
639
- }
640
- function issue(...args) {
641
- const [iss, input, inst] = args;
642
- if (typeof iss === "string") {
643
- return {
644
- message: iss,
645
- code: "custom",
646
- input,
647
- inst,
648
- };
649
- }
650
- return { ...iss };
651
- }
652
-
653
- const initializer$1 = (inst, def) => {
654
- inst.name = "$ZodError";
655
- Object.defineProperty(inst, "_zod", {
656
- value: inst._zod,
657
- enumerable: false,
658
- });
659
- Object.defineProperty(inst, "issues", {
660
- value: def,
661
- enumerable: false,
662
- });
663
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
664
- Object.defineProperty(inst, "toString", {
665
- value: () => inst.message,
666
- enumerable: false,
667
- });
668
- };
669
- const $ZodError = $constructor("$ZodError", initializer$1);
670
- const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
671
- function flattenError(error, mapper = (issue) => issue.message) {
672
- const fieldErrors = {};
673
- const formErrors = [];
674
- for (const sub of error.issues) {
675
- if (sub.path.length > 0) {
676
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
677
- fieldErrors[sub.path[0]].push(mapper(sub));
678
- }
679
- else {
680
- formErrors.push(mapper(sub));
681
- }
682
- }
683
- return { formErrors, fieldErrors };
684
- }
685
- function formatError(error, _mapper) {
686
- const mapper = _mapper ||
687
- function (issue) {
688
- return issue.message;
689
- };
690
- const fieldErrors = { _errors: [] };
691
- const processError = (error) => {
692
- for (const issue of error.issues) {
693
- if (issue.code === "invalid_union" && issue.errors.length) {
694
- issue.errors.map((issues) => processError({ issues }));
695
- }
696
- else if (issue.code === "invalid_key") {
697
- processError({ issues: issue.issues });
698
- }
699
- else if (issue.code === "invalid_element") {
700
- processError({ issues: issue.issues });
701
- }
702
- else if (issue.path.length === 0) {
703
- fieldErrors._errors.push(mapper(issue));
704
- }
705
- else {
706
- let curr = fieldErrors;
707
- let i = 0;
708
- while (i < issue.path.length) {
709
- const el = issue.path[i];
710
- const terminal = i === issue.path.length - 1;
711
- if (!terminal) {
712
- curr[el] = curr[el] || { _errors: [] };
713
- }
714
- else {
715
- curr[el] = curr[el] || { _errors: [] };
716
- curr[el]._errors.push(mapper(issue));
717
- }
718
- curr = curr[el];
719
- i++;
720
- }
721
- }
722
- }
723
- };
724
- processError(error);
725
- return fieldErrors;
726
- }
727
-
728
- const _parse = (_Err) => (schema, value, _ctx, _params) => {
729
- const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
730
- const result = schema._zod.run({ value, issues: [] }, ctx);
731
- if (result instanceof Promise) {
732
- throw new $ZodAsyncError();
733
- }
734
- if (result.issues.length) {
735
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
736
- captureStackTrace(e, _params?.callee);
737
- throw e;
738
- }
739
- return result.value;
740
- };
741
- const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
742
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
743
- let result = schema._zod.run({ value, issues: [] }, ctx);
744
- if (result instanceof Promise)
745
- result = await result;
746
- if (result.issues.length) {
747
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
748
- captureStackTrace(e, params?.callee);
749
- throw e;
750
- }
751
- return result.value;
752
- };
753
- const _safeParse = (_Err) => (schema, value, _ctx) => {
754
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
755
- const result = schema._zod.run({ value, issues: [] }, ctx);
756
- if (result instanceof Promise) {
757
- throw new $ZodAsyncError();
758
- }
759
- return result.issues.length
760
- ? {
761
- success: false,
762
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
763
- }
764
- : { success: true, data: result.value };
765
- };
766
- const safeParse$1 = /* @__PURE__*/ _safeParse($ZodRealError);
767
- const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
768
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
769
- let result = schema._zod.run({ value, issues: [] }, ctx);
770
- if (result instanceof Promise)
771
- result = await result;
772
- return result.issues.length
773
- ? {
774
- success: false,
775
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
776
- }
777
- : { success: true, data: result.value };
778
- };
779
- const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
780
-
781
- const cuid = /^[cC][^\s-]{8,}$/;
782
- const cuid2 = /^[0-9a-z]+$/;
783
- const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
784
- const xid = /^[0-9a-vA-V]{20}$/;
785
- const ksuid = /^[A-Za-z0-9]{27}$/;
786
- const nanoid = /^[a-zA-Z0-9_-]{21}$/;
787
- /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
788
- const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
789
- /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
790
- const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
791
- /** Returns a regex for validating an RFC 9562/4122 UUID.
792
- *
793
- * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
794
- const uuid = (version) => {
795
- if (!version)
796
- return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
797
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
798
- };
799
- /** Practical email validation */
800
- const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
801
- // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
802
- const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
803
- function emoji() {
804
- return new RegExp(_emoji$1, "u");
805
- }
806
- const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
807
- const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/;
808
- const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
809
- const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
810
- // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
811
- const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
812
- const base64url = /^[A-Za-z0-9_-]*$/;
813
- // based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
814
- // export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
815
- const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
816
- // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
817
- const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
818
- // const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
819
- const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
820
- const date$1 = /*@__PURE__*/ new RegExp(`^${dateSource}$`);
821
- function timeSource(args) {
822
- const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
823
- const regex = typeof args.precision === "number"
824
- ? args.precision === -1
825
- ? `${hhmm}`
826
- : args.precision === 0
827
- ? `${hhmm}:[0-5]\\d`
828
- : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`
829
- : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
830
- return regex;
831
- }
832
- function time$1(args) {
833
- return new RegExp(`^${timeSource(args)}$`);
834
- }
835
- // Adapted from https://stackoverflow.com/a/3143231
836
- function datetime$1(args) {
837
- const time = timeSource({ precision: args.precision });
838
- const opts = ["Z"];
839
- if (args.local)
840
- opts.push("");
841
- // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`);
842
- if (args.offset)
843
- opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
844
- const timeRegex = `${time}(?:${opts.join("|")})`;
845
- return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
846
- }
847
- const string$1 = (params) => {
848
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
849
- return new RegExp(`^${regex}$`);
850
- };
851
- const integer = /^\d+$/;
852
- const number$1 = /^-?\d+(?:\.\d+)?/i;
853
- const boolean$1 = /true|false/i;
854
- // regex for string with no uppercase letters
855
- const lowercase = /^[^A-Z]*$/;
856
- // regex for string with no lowercase letters
857
- const uppercase = /^[^a-z]*$/;
858
-
859
- // import { $ZodType } from "./schemas.js";
860
- const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
861
- var _a;
862
- inst._zod ?? (inst._zod = {});
863
- inst._zod.def = def;
864
- (_a = inst._zod).onattach ?? (_a.onattach = []);
865
- });
866
- const numericOriginMap = {
867
- number: "number",
868
- bigint: "bigint",
869
- object: "date",
870
- };
871
- const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => {
872
- $ZodCheck.init(inst, def);
873
- const origin = numericOriginMap[typeof def.value];
874
- inst._zod.onattach.push((inst) => {
875
- const bag = inst._zod.bag;
876
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
877
- if (def.value < curr) {
878
- if (def.inclusive)
879
- bag.maximum = def.value;
880
- else
881
- bag.exclusiveMaximum = def.value;
882
- }
883
- });
884
- inst._zod.check = (payload) => {
885
- if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
886
- return;
887
- }
888
- payload.issues.push({
889
- origin,
890
- code: "too_big",
891
- maximum: def.value,
892
- input: payload.value,
893
- inclusive: def.inclusive,
894
- inst,
895
- continue: !def.abort,
896
- });
897
- };
898
- });
899
- const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => {
900
- $ZodCheck.init(inst, def);
901
- const origin = numericOriginMap[typeof def.value];
902
- inst._zod.onattach.push((inst) => {
903
- const bag = inst._zod.bag;
904
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
905
- if (def.value > curr) {
906
- if (def.inclusive)
907
- bag.minimum = def.value;
908
- else
909
- bag.exclusiveMinimum = def.value;
910
- }
911
- });
912
- inst._zod.check = (payload) => {
913
- if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
914
- return;
915
- }
916
- payload.issues.push({
917
- origin,
918
- code: "too_small",
919
- minimum: def.value,
920
- input: payload.value,
921
- inclusive: def.inclusive,
922
- inst,
923
- continue: !def.abort,
924
- });
925
- };
926
- });
927
- const $ZodCheckMultipleOf =
928
- /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => {
929
- $ZodCheck.init(inst, def);
930
- inst._zod.onattach.push((inst) => {
931
- var _a;
932
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
933
- });
934
- inst._zod.check = (payload) => {
935
- if (typeof payload.value !== typeof def.value)
936
- throw new Error("Cannot mix number and bigint in multiple_of check.");
937
- const isMultiple = typeof payload.value === "bigint"
938
- ? payload.value % def.value === BigInt(0)
939
- : floatSafeRemainder(payload.value, def.value) === 0;
940
- if (isMultiple)
941
- return;
942
- payload.issues.push({
943
- origin: typeof payload.value,
944
- code: "not_multiple_of",
945
- divisor: def.value,
946
- input: payload.value,
947
- inst,
948
- continue: !def.abort,
949
- });
950
- };
951
- });
952
- const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
953
- $ZodCheck.init(inst, def); // no format checks
954
- def.format = def.format || "float64";
955
- const isInt = def.format?.includes("int");
956
- const origin = isInt ? "int" : "number";
957
- const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
958
- inst._zod.onattach.push((inst) => {
959
- const bag = inst._zod.bag;
960
- bag.format = def.format;
961
- bag.minimum = minimum;
962
- bag.maximum = maximum;
963
- if (isInt)
964
- bag.pattern = integer;
965
- });
966
- inst._zod.check = (payload) => {
967
- const input = payload.value;
968
- if (isInt) {
969
- if (!Number.isInteger(input)) {
970
- // invalid_format issue
971
- // payload.issues.push({
972
- // expected: def.format,
973
- // format: def.format,
974
- // code: "invalid_format",
975
- // input,
976
- // inst,
977
- // });
978
- // invalid_type issue
979
- payload.issues.push({
980
- expected: origin,
981
- format: def.format,
982
- code: "invalid_type",
983
- continue: false,
984
- input,
985
- inst,
986
- });
987
- return;
988
- // not_multiple_of issue
989
- // payload.issues.push({
990
- // code: "not_multiple_of",
991
- // origin: "number",
992
- // input,
993
- // inst,
994
- // divisor: 1,
995
- // });
996
- }
997
- if (!Number.isSafeInteger(input)) {
998
- if (input > 0) {
999
- // too_big
1000
- payload.issues.push({
1001
- input,
1002
- code: "too_big",
1003
- maximum: Number.MAX_SAFE_INTEGER,
1004
- note: "Integers must be within the safe integer range.",
1005
- inst,
1006
- origin,
1007
- continue: !def.abort,
1008
- });
1009
- }
1010
- else {
1011
- // too_small
1012
- payload.issues.push({
1013
- input,
1014
- code: "too_small",
1015
- minimum: Number.MIN_SAFE_INTEGER,
1016
- note: "Integers must be within the safe integer range.",
1017
- inst,
1018
- origin,
1019
- continue: !def.abort,
1020
- });
1021
- }
1022
- return;
1023
- }
1024
- }
1025
- if (input < minimum) {
1026
- payload.issues.push({
1027
- origin: "number",
1028
- input,
1029
- code: "too_small",
1030
- minimum,
1031
- inclusive: true,
1032
- inst,
1033
- continue: !def.abort,
1034
- });
1035
- }
1036
- if (input > maximum) {
1037
- payload.issues.push({
1038
- origin: "number",
1039
- input,
1040
- code: "too_big",
1041
- maximum,
1042
- inst,
1043
- });
1044
- }
1045
- };
1046
- });
1047
- const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
1048
- var _a;
1049
- $ZodCheck.init(inst, def);
1050
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1051
- const val = payload.value;
1052
- return !nullish(val) && val.length !== undefined;
1053
- });
1054
- inst._zod.onattach.push((inst) => {
1055
- const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);
1056
- if (def.maximum < curr)
1057
- inst._zod.bag.maximum = def.maximum;
1058
- });
1059
- inst._zod.check = (payload) => {
1060
- const input = payload.value;
1061
- const length = input.length;
1062
- if (length <= def.maximum)
1063
- return;
1064
- const origin = getLengthableOrigin(input);
1065
- payload.issues.push({
1066
- origin,
1067
- code: "too_big",
1068
- maximum: def.maximum,
1069
- inclusive: true,
1070
- input,
1071
- inst,
1072
- continue: !def.abort,
1073
- });
1074
- };
1075
- });
1076
- const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
1077
- var _a;
1078
- $ZodCheck.init(inst, def);
1079
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1080
- const val = payload.value;
1081
- return !nullish(val) && val.length !== undefined;
1082
- });
1083
- inst._zod.onattach.push((inst) => {
1084
- const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);
1085
- if (def.minimum > curr)
1086
- inst._zod.bag.minimum = def.minimum;
1087
- });
1088
- inst._zod.check = (payload) => {
1089
- const input = payload.value;
1090
- const length = input.length;
1091
- if (length >= def.minimum)
1092
- return;
1093
- const origin = getLengthableOrigin(input);
1094
- payload.issues.push({
1095
- origin,
1096
- code: "too_small",
1097
- minimum: def.minimum,
1098
- inclusive: true,
1099
- input,
1100
- inst,
1101
- continue: !def.abort,
1102
- });
1103
- };
1104
- });
1105
- const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
1106
- var _a;
1107
- $ZodCheck.init(inst, def);
1108
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
1109
- const val = payload.value;
1110
- return !nullish(val) && val.length !== undefined;
1111
- });
1112
- inst._zod.onattach.push((inst) => {
1113
- const bag = inst._zod.bag;
1114
- bag.minimum = def.length;
1115
- bag.maximum = def.length;
1116
- bag.length = def.length;
1117
- });
1118
- inst._zod.check = (payload) => {
1119
- const input = payload.value;
1120
- const length = input.length;
1121
- if (length === def.length)
1122
- return;
1123
- const origin = getLengthableOrigin(input);
1124
- const tooBig = length > def.length;
1125
- payload.issues.push({
1126
- origin,
1127
- ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }),
1128
- inclusive: true,
1129
- exact: true,
1130
- input: payload.value,
1131
- inst,
1132
- continue: !def.abort,
1133
- });
1134
- };
1135
- });
1136
- const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
1137
- var _a, _b;
1138
- $ZodCheck.init(inst, def);
1139
- inst._zod.onattach.push((inst) => {
1140
- const bag = inst._zod.bag;
1141
- bag.format = def.format;
1142
- if (def.pattern) {
1143
- bag.patterns ?? (bag.patterns = new Set());
1144
- bag.patterns.add(def.pattern);
1145
- }
1146
- });
1147
- if (def.pattern)
1148
- (_a = inst._zod).check ?? (_a.check = (payload) => {
1149
- def.pattern.lastIndex = 0;
1150
- if (def.pattern.test(payload.value))
1151
- return;
1152
- payload.issues.push({
1153
- origin: "string",
1154
- code: "invalid_format",
1155
- format: def.format,
1156
- input: payload.value,
1157
- ...(def.pattern ? { pattern: def.pattern.toString() } : {}),
1158
- inst,
1159
- continue: !def.abort,
1160
- });
1161
- });
1162
- else
1163
- (_b = inst._zod).check ?? (_b.check = () => { });
1164
- });
1165
- const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
1166
- $ZodCheckStringFormat.init(inst, def);
1167
- inst._zod.check = (payload) => {
1168
- def.pattern.lastIndex = 0;
1169
- if (def.pattern.test(payload.value))
1170
- return;
1171
- payload.issues.push({
1172
- origin: "string",
1173
- code: "invalid_format",
1174
- format: "regex",
1175
- input: payload.value,
1176
- pattern: def.pattern.toString(),
1177
- inst,
1178
- continue: !def.abort,
1179
- });
1180
- };
1181
- });
1182
- const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
1183
- def.pattern ?? (def.pattern = lowercase);
1184
- $ZodCheckStringFormat.init(inst, def);
1185
- });
1186
- const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
1187
- def.pattern ?? (def.pattern = uppercase);
1188
- $ZodCheckStringFormat.init(inst, def);
1189
- });
1190
- const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
1191
- $ZodCheck.init(inst, def);
1192
- const escapedRegex = escapeRegex(def.includes);
1193
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
1194
- def.pattern = pattern;
1195
- inst._zod.onattach.push((inst) => {
1196
- const bag = inst._zod.bag;
1197
- bag.patterns ?? (bag.patterns = new Set());
1198
- bag.patterns.add(pattern);
1199
- });
1200
- inst._zod.check = (payload) => {
1201
- if (payload.value.includes(def.includes, def.position))
1202
- return;
1203
- payload.issues.push({
1204
- origin: "string",
1205
- code: "invalid_format",
1206
- format: "includes",
1207
- includes: def.includes,
1208
- input: payload.value,
1209
- inst,
1210
- continue: !def.abort,
1211
- });
1212
- };
1213
- });
1214
- const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
1215
- $ZodCheck.init(inst, def);
1216
- const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
1217
- def.pattern ?? (def.pattern = pattern);
1218
- inst._zod.onattach.push((inst) => {
1219
- const bag = inst._zod.bag;
1220
- bag.patterns ?? (bag.patterns = new Set());
1221
- bag.patterns.add(pattern);
1222
- });
1223
- inst._zod.check = (payload) => {
1224
- if (payload.value.startsWith(def.prefix))
1225
- return;
1226
- payload.issues.push({
1227
- origin: "string",
1228
- code: "invalid_format",
1229
- format: "starts_with",
1230
- prefix: def.prefix,
1231
- input: payload.value,
1232
- inst,
1233
- continue: !def.abort,
1234
- });
1235
- };
1236
- });
1237
- const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
1238
- $ZodCheck.init(inst, def);
1239
- const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
1240
- def.pattern ?? (def.pattern = pattern);
1241
- inst._zod.onattach.push((inst) => {
1242
- const bag = inst._zod.bag;
1243
- bag.patterns ?? (bag.patterns = new Set());
1244
- bag.patterns.add(pattern);
1245
- });
1246
- inst._zod.check = (payload) => {
1247
- if (payload.value.endsWith(def.suffix))
1248
- return;
1249
- payload.issues.push({
1250
- origin: "string",
1251
- code: "invalid_format",
1252
- format: "ends_with",
1253
- suffix: def.suffix,
1254
- input: payload.value,
1255
- inst,
1256
- continue: !def.abort,
1257
- });
1258
- };
1259
- });
1260
- const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
1261
- $ZodCheck.init(inst, def);
1262
- inst._zod.check = (payload) => {
1263
- payload.value = def.tx(payload.value);
1264
- };
1265
- });
1266
-
1267
- class Doc {
1268
- constructor(args = []) {
1269
- this.content = [];
1270
- this.indent = 0;
1271
- if (this)
1272
- this.args = args;
1273
- }
1274
- indented(fn) {
1275
- this.indent += 1;
1276
- fn(this);
1277
- this.indent -= 1;
1278
- }
1279
- write(arg) {
1280
- if (typeof arg === "function") {
1281
- arg(this, { execution: "sync" });
1282
- arg(this, { execution: "async" });
1283
- return;
1284
- }
1285
- const content = arg;
1286
- const lines = content.split("\n").filter((x) => x);
1287
- const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
1288
- const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
1289
- for (const line of dedented) {
1290
- this.content.push(line);
1291
- }
1292
- }
1293
- compile() {
1294
- const F = Function;
1295
- const args = this?.args;
1296
- const content = this?.content ?? [``];
1297
- const lines = [...content.map((x) => ` ${x}`)];
1298
- // console.log(lines.join("\n"));
1299
- return new F(...args, lines.join("\n"));
1300
- }
1301
- }
1302
-
1303
- const version = {
1304
- major: 4,
1305
- minor: 0,
1306
- patch: 17,
1307
- };
1308
-
1309
- const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
1310
- var _a;
1311
- inst ?? (inst = {});
1312
- inst._zod.def = def; // set _def property
1313
- inst._zod.bag = inst._zod.bag || {}; // initialize _bag object
1314
- inst._zod.version = version;
1315
- const checks = [...(inst._zod.def.checks ?? [])];
1316
- // if inst is itself a checks.$ZodCheck, run it as a check
1317
- if (inst._zod.traits.has("$ZodCheck")) {
1318
- checks.unshift(inst);
1319
- }
1320
- //
1321
- for (const ch of checks) {
1322
- for (const fn of ch._zod.onattach) {
1323
- fn(inst);
1324
- }
1325
- }
1326
- if (checks.length === 0) {
1327
- // deferred initializer
1328
- // inst._zod.parse is not yet defined
1329
- (_a = inst._zod).deferred ?? (_a.deferred = []);
1330
- inst._zod.deferred?.push(() => {
1331
- inst._zod.run = inst._zod.parse;
1332
- });
1333
- }
1334
- else {
1335
- const runChecks = (payload, checks, ctx) => {
1336
- let isAborted = aborted(payload);
1337
- let asyncResult;
1338
- for (const ch of checks) {
1339
- if (ch._zod.def.when) {
1340
- const shouldRun = ch._zod.def.when(payload);
1341
- if (!shouldRun)
1342
- continue;
1343
- }
1344
- else if (isAborted) {
1345
- continue;
1346
- }
1347
- const currLen = payload.issues.length;
1348
- const _ = ch._zod.check(payload);
1349
- if (_ instanceof Promise && ctx?.async === false) {
1350
- throw new $ZodAsyncError();
1351
- }
1352
- if (asyncResult || _ instanceof Promise) {
1353
- asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
1354
- await _;
1355
- const nextLen = payload.issues.length;
1356
- if (nextLen === currLen)
1357
- return;
1358
- if (!isAborted)
1359
- isAborted = aborted(payload, currLen);
1360
- });
1361
- }
1362
- else {
1363
- const nextLen = payload.issues.length;
1364
- if (nextLen === currLen)
1365
- continue;
1366
- if (!isAborted)
1367
- isAborted = aborted(payload, currLen);
1368
- }
1369
- }
1370
- if (asyncResult) {
1371
- return asyncResult.then(() => {
1372
- return payload;
1373
- });
1374
- }
1375
- return payload;
1376
- };
1377
- inst._zod.run = (payload, ctx) => {
1378
- const result = inst._zod.parse(payload, ctx);
1379
- if (result instanceof Promise) {
1380
- if (ctx.async === false)
1381
- throw new $ZodAsyncError();
1382
- return result.then((result) => runChecks(result, checks, ctx));
1383
- }
1384
- return runChecks(result, checks, ctx);
1385
- };
1386
- }
1387
- inst["~standard"] = {
1388
- validate: (value) => {
1389
- try {
1390
- const r = safeParse$1(inst, value);
1391
- return r.success ? { value: r.data } : { issues: r.error?.issues };
1392
- }
1393
- catch (_) {
1394
- return safeParseAsync$1(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));
1395
- }
1396
- },
1397
- vendor: "zod",
1398
- version: 1,
1399
- };
1400
- });
1401
- const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
1402
- $ZodType.init(inst, def);
1403
- inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string$1(inst._zod.bag);
1404
- inst._zod.parse = (payload, _) => {
1405
- if (def.coerce)
1406
- try {
1407
- payload.value = String(payload.value);
1408
- }
1409
- catch (_) { }
1410
- if (typeof payload.value === "string")
1411
- return payload;
1412
- payload.issues.push({
1413
- expected: "string",
1414
- code: "invalid_type",
1415
- input: payload.value,
1416
- inst,
1417
- });
1418
- return payload;
1419
- };
1420
- });
1421
- const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
1422
- // check initialization must come first
1423
- $ZodCheckStringFormat.init(inst, def);
1424
- $ZodString.init(inst, def);
1425
- });
1426
- const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
1427
- def.pattern ?? (def.pattern = guid);
1428
- $ZodStringFormat.init(inst, def);
1429
- });
1430
- const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
1431
- if (def.version) {
1432
- const versionMap = {
1433
- v1: 1,
1434
- v2: 2,
1435
- v3: 3,
1436
- v4: 4,
1437
- v5: 5,
1438
- v6: 6,
1439
- v7: 7,
1440
- v8: 8,
1441
- };
1442
- const v = versionMap[def.version];
1443
- if (v === undefined)
1444
- throw new Error(`Invalid UUID version: "${def.version}"`);
1445
- def.pattern ?? (def.pattern = uuid(v));
1446
- }
1447
- else
1448
- def.pattern ?? (def.pattern = uuid());
1449
- $ZodStringFormat.init(inst, def);
1450
- });
1451
- const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
1452
- def.pattern ?? (def.pattern = email);
1453
- $ZodStringFormat.init(inst, def);
1454
- });
1455
- const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
1456
- $ZodStringFormat.init(inst, def);
1457
- inst._zod.check = (payload) => {
1458
- try {
1459
- // Trim whitespace from input
1460
- const trimmed = payload.value.trim();
1461
- // @ts-ignore
1462
- const url = new URL(trimmed);
1463
- if (def.hostname) {
1464
- def.hostname.lastIndex = 0;
1465
- if (!def.hostname.test(url.hostname)) {
1466
- payload.issues.push({
1467
- code: "invalid_format",
1468
- format: "url",
1469
- note: "Invalid hostname",
1470
- pattern: hostname.source,
1471
- input: payload.value,
1472
- inst,
1473
- continue: !def.abort,
1474
- });
1475
- }
1476
- }
1477
- if (def.protocol) {
1478
- def.protocol.lastIndex = 0;
1479
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) {
1480
- payload.issues.push({
1481
- code: "invalid_format",
1482
- format: "url",
1483
- note: "Invalid protocol",
1484
- pattern: def.protocol.source,
1485
- input: payload.value,
1486
- inst,
1487
- continue: !def.abort,
1488
- });
1489
- }
1490
- }
1491
- // Set the output value based on normalize flag
1492
- if (def.normalize) {
1493
- // Use normalized URL
1494
- payload.value = url.href;
1495
- }
1496
- else {
1497
- // Preserve the original input (trimmed)
1498
- payload.value = trimmed;
1499
- }
1500
- return;
1501
- }
1502
- catch (_) {
1503
- payload.issues.push({
1504
- code: "invalid_format",
1505
- format: "url",
1506
- input: payload.value,
1507
- inst,
1508
- continue: !def.abort,
1509
- });
1510
- }
1511
- };
1512
- });
1513
- const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
1514
- def.pattern ?? (def.pattern = emoji());
1515
- $ZodStringFormat.init(inst, def);
1516
- });
1517
- const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
1518
- def.pattern ?? (def.pattern = nanoid);
1519
- $ZodStringFormat.init(inst, def);
1520
- });
1521
- const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
1522
- def.pattern ?? (def.pattern = cuid);
1523
- $ZodStringFormat.init(inst, def);
1524
- });
1525
- const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
1526
- def.pattern ?? (def.pattern = cuid2);
1527
- $ZodStringFormat.init(inst, def);
1528
- });
1529
- const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
1530
- def.pattern ?? (def.pattern = ulid);
1531
- $ZodStringFormat.init(inst, def);
1532
- });
1533
- const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
1534
- def.pattern ?? (def.pattern = xid);
1535
- $ZodStringFormat.init(inst, def);
1536
- });
1537
- const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
1538
- def.pattern ?? (def.pattern = ksuid);
1539
- $ZodStringFormat.init(inst, def);
1540
- });
1541
- const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
1542
- def.pattern ?? (def.pattern = datetime$1(def));
1543
- $ZodStringFormat.init(inst, def);
1544
- });
1545
- const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
1546
- def.pattern ?? (def.pattern = date$1);
1547
- $ZodStringFormat.init(inst, def);
1548
- });
1549
- const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
1550
- def.pattern ?? (def.pattern = time$1(def));
1551
- $ZodStringFormat.init(inst, def);
1552
- });
1553
- const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
1554
- def.pattern ?? (def.pattern = duration$1);
1555
- $ZodStringFormat.init(inst, def);
1556
- });
1557
- const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
1558
- def.pattern ?? (def.pattern = ipv4);
1559
- $ZodStringFormat.init(inst, def);
1560
- inst._zod.onattach.push((inst) => {
1561
- const bag = inst._zod.bag;
1562
- bag.format = `ipv4`;
1563
- });
1564
- });
1565
- const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
1566
- def.pattern ?? (def.pattern = ipv6);
1567
- $ZodStringFormat.init(inst, def);
1568
- inst._zod.onattach.push((inst) => {
1569
- const bag = inst._zod.bag;
1570
- bag.format = `ipv6`;
1571
- });
1572
- inst._zod.check = (payload) => {
1573
- try {
1574
- // @ts-ignore
1575
- new URL(`http://[${payload.value}]`);
1576
- // return;
1577
- }
1578
- catch {
1579
- payload.issues.push({
1580
- code: "invalid_format",
1581
- format: "ipv6",
1582
- input: payload.value,
1583
- inst,
1584
- continue: !def.abort,
1585
- });
1586
- }
1587
- };
1588
- });
1589
- const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
1590
- def.pattern ?? (def.pattern = cidrv4);
1591
- $ZodStringFormat.init(inst, def);
1592
- });
1593
- const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
1594
- def.pattern ?? (def.pattern = cidrv6); // not used for validation
1595
- $ZodStringFormat.init(inst, def);
1596
- inst._zod.check = (payload) => {
1597
- const [address, prefix] = payload.value.split("/");
1598
- try {
1599
- if (!prefix)
1600
- throw new Error();
1601
- const prefixNum = Number(prefix);
1602
- if (`${prefixNum}` !== prefix)
1603
- throw new Error();
1604
- if (prefixNum < 0 || prefixNum > 128)
1605
- throw new Error();
1606
- // @ts-ignore
1607
- new URL(`http://[${address}]`);
1608
- }
1609
- catch {
1610
- payload.issues.push({
1611
- code: "invalid_format",
1612
- format: "cidrv6",
1613
- input: payload.value,
1614
- inst,
1615
- continue: !def.abort,
1616
- });
1617
- }
1618
- };
1619
- });
1620
- ////////////////////////////// ZodBase64 //////////////////////////////
1621
- function isValidBase64(data) {
1622
- if (data === "")
1623
- return true;
1624
- if (data.length % 4 !== 0)
1625
- return false;
1626
- try {
1627
- // @ts-ignore
1628
- atob(data);
1629
- return true;
1630
- }
1631
- catch {
1632
- return false;
1633
- }
1634
- }
1635
- const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
1636
- def.pattern ?? (def.pattern = base64);
1637
- $ZodStringFormat.init(inst, def);
1638
- inst._zod.onattach.push((inst) => {
1639
- inst._zod.bag.contentEncoding = "base64";
1640
- });
1641
- inst._zod.check = (payload) => {
1642
- if (isValidBase64(payload.value))
1643
- return;
1644
- payload.issues.push({
1645
- code: "invalid_format",
1646
- format: "base64",
1647
- input: payload.value,
1648
- inst,
1649
- continue: !def.abort,
1650
- });
1651
- };
1652
- });
1653
- ////////////////////////////// ZodBase64 //////////////////////////////
1654
- function isValidBase64URL(data) {
1655
- if (!base64url.test(data))
1656
- return false;
1657
- const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/"));
1658
- const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
1659
- return isValidBase64(padded);
1660
- }
1661
- const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
1662
- def.pattern ?? (def.pattern = base64url);
1663
- $ZodStringFormat.init(inst, def);
1664
- inst._zod.onattach.push((inst) => {
1665
- inst._zod.bag.contentEncoding = "base64url";
1666
- });
1667
- inst._zod.check = (payload) => {
1668
- if (isValidBase64URL(payload.value))
1669
- return;
1670
- payload.issues.push({
1671
- code: "invalid_format",
1672
- format: "base64url",
1673
- input: payload.value,
1674
- inst,
1675
- continue: !def.abort,
1676
- });
1677
- };
1678
- });
1679
- const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
1680
- def.pattern ?? (def.pattern = e164);
1681
- $ZodStringFormat.init(inst, def);
1682
- });
1683
- ////////////////////////////// ZodJWT //////////////////////////////
1684
- function isValidJWT(token, algorithm = null) {
1685
- try {
1686
- const tokensParts = token.split(".");
1687
- if (tokensParts.length !== 3)
1688
- return false;
1689
- const [header] = tokensParts;
1690
- if (!header)
1691
- return false;
1692
- // @ts-ignore
1693
- const parsedHeader = JSON.parse(atob(header));
1694
- if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
1695
- return false;
1696
- if (!parsedHeader.alg)
1697
- return false;
1698
- if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
1699
- return false;
1700
- return true;
1701
- }
1702
- catch {
1703
- return false;
1704
- }
1705
- }
1706
- const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
1707
- $ZodStringFormat.init(inst, def);
1708
- inst._zod.check = (payload) => {
1709
- if (isValidJWT(payload.value, def.alg))
1710
- return;
1711
- payload.issues.push({
1712
- code: "invalid_format",
1713
- format: "jwt",
1714
- input: payload.value,
1715
- inst,
1716
- continue: !def.abort,
1717
- });
1718
- };
1719
- });
1720
- const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1721
- $ZodType.init(inst, def);
1722
- inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
1723
- inst._zod.parse = (payload, _ctx) => {
1724
- if (def.coerce)
1725
- try {
1726
- payload.value = Number(payload.value);
1727
- }
1728
- catch (_) { }
1729
- const input = payload.value;
1730
- if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
1731
- return payload;
1732
- }
1733
- const received = typeof input === "number"
1734
- ? Number.isNaN(input)
1735
- ? "NaN"
1736
- : !Number.isFinite(input)
1737
- ? "Infinity"
1738
- : undefined
1739
- : undefined;
1740
- payload.issues.push({
1741
- expected: "number",
1742
- code: "invalid_type",
1743
- input,
1744
- inst,
1745
- ...(received ? { received } : {}),
1746
- });
1747
- return payload;
1748
- };
1749
- });
1750
- const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1751
- $ZodCheckNumberFormat.init(inst, def);
1752
- $ZodNumber.init(inst, def); // no format checksp
1753
- });
1754
- const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
1755
- $ZodType.init(inst, def);
1756
- inst._zod.pattern = boolean$1;
1757
- inst._zod.parse = (payload, _ctx) => {
1758
- if (def.coerce)
1759
- try {
1760
- payload.value = Boolean(payload.value);
1761
- }
1762
- catch (_) { }
1763
- const input = payload.value;
1764
- if (typeof input === "boolean")
1765
- return payload;
1766
- payload.issues.push({
1767
- expected: "boolean",
1768
- code: "invalid_type",
1769
- input,
1770
- inst,
1771
- });
1772
- return payload;
1773
- };
1774
- });
1775
- const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => {
1776
- $ZodType.init(inst, def);
1777
- inst._zod.parse = (payload) => payload;
1778
- });
1779
- const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
1780
- $ZodType.init(inst, def);
1781
- inst._zod.parse = (payload) => payload;
1782
- });
1783
- const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
1784
- $ZodType.init(inst, def);
1785
- inst._zod.parse = (payload, _ctx) => {
1786
- payload.issues.push({
1787
- expected: "never",
1788
- code: "invalid_type",
1789
- input: payload.value,
1790
- inst,
1791
- });
1792
- return payload;
1793
- };
1794
- });
1795
- function handleArrayResult(result, final, index) {
1796
- if (result.issues.length) {
1797
- final.issues.push(...prefixIssues(index, result.issues));
1798
- }
1799
- final.value[index] = result.value;
1800
- }
1801
- const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
1802
- $ZodType.init(inst, def);
1803
- inst._zod.parse = (payload, ctx) => {
1804
- const input = payload.value;
1805
- if (!Array.isArray(input)) {
1806
- payload.issues.push({
1807
- expected: "array",
1808
- code: "invalid_type",
1809
- input,
1810
- inst,
1811
- });
1812
- return payload;
1813
- }
1814
- payload.value = Array(input.length);
1815
- const proms = [];
1816
- for (let i = 0; i < input.length; i++) {
1817
- const item = input[i];
1818
- const result = def.element._zod.run({
1819
- value: item,
1820
- issues: [],
1821
- }, ctx);
1822
- if (result instanceof Promise) {
1823
- proms.push(result.then((result) => handleArrayResult(result, payload, i)));
1824
- }
1825
- else {
1826
- handleArrayResult(result, payload, i);
1827
- }
1828
- }
1829
- if (proms.length) {
1830
- return Promise.all(proms).then(() => payload);
1831
- }
1832
- return payload; //handleArrayResultsAsync(parseResults, final);
1833
- };
1834
- });
1835
- function handlePropertyResult(result, final, key, input) {
1836
- if (result.issues.length) {
1837
- final.issues.push(...prefixIssues(key, result.issues));
1838
- }
1839
- if (result.value === undefined) {
1840
- if (key in input) {
1841
- final.value[key] = undefined;
1842
- }
1843
- }
1844
- else {
1845
- final.value[key] = result.value;
1846
- }
1847
- }
1848
- const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1849
- // requires cast because technically $ZodObject doesn't extend
1850
- $ZodType.init(inst, def);
1851
- const _normalized = cached(() => {
1852
- const keys = Object.keys(def.shape);
1853
- for (const k of keys) {
1854
- if (!def.shape[k]._zod.traits.has("$ZodType")) {
1855
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1856
- }
1857
- }
1858
- const okeys = optionalKeys(def.shape);
1859
- return {
1860
- shape: def.shape,
1861
- keys,
1862
- keySet: new Set(keys),
1863
- numKeys: keys.length,
1864
- optionalKeys: new Set(okeys),
1865
- };
1866
- });
1867
- defineLazy(inst._zod, "propValues", () => {
1868
- const shape = def.shape;
1869
- const propValues = {};
1870
- for (const key in shape) {
1871
- const field = shape[key]._zod;
1872
- if (field.values) {
1873
- propValues[key] ?? (propValues[key] = new Set());
1874
- for (const v of field.values)
1875
- propValues[key].add(v);
1876
- }
1877
- }
1878
- return propValues;
1879
- });
1880
- const generateFastpass = (shape) => {
1881
- const doc = new Doc(["shape", "payload", "ctx"]);
1882
- const normalized = _normalized.value;
1883
- const parseStr = (key) => {
1884
- const k = esc(key);
1885
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
1886
- };
1887
- doc.write(`const input = payload.value;`);
1888
- const ids = Object.create(null);
1889
- let counter = 0;
1890
- for (const key of normalized.keys) {
1891
- ids[key] = `key_${counter++}`;
1892
- }
1893
- // A: preserve key order {
1894
- doc.write(`const newResult = {}`);
1895
- for (const key of normalized.keys) {
1896
- const id = ids[key];
1897
- const k = esc(key);
1898
- doc.write(`const ${id} = ${parseStr(key)};`);
1899
- doc.write(`
1900
- if (${id}.issues.length) {
1901
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
1902
- ...iss,
1903
- path: iss.path ? [${k}, ...iss.path] : [${k}]
1904
- })));
1905
- }
1906
-
1907
- if (${id}.value === undefined) {
1908
- if (${k} in input) {
1909
- newResult[${k}] = undefined;
1910
- }
1911
- } else {
1912
- newResult[${k}] = ${id}.value;
1913
- }
1914
- `);
1915
- }
1916
- doc.write(`payload.value = newResult;`);
1917
- doc.write(`return payload;`);
1918
- const fn = doc.compile();
1919
- return (payload, ctx) => fn(shape, payload, ctx);
1920
- };
1921
- let fastpass;
1922
- const isObject$1 = isObject;
1923
- const jit = !globalConfig.jitless;
1924
- const allowsEval$1 = allowsEval;
1925
- const fastEnabled = jit && allowsEval$1.value; // && !def.catchall;
1926
- const catchall = def.catchall;
1927
- let value;
1928
- inst._zod.parse = (payload, ctx) => {
1929
- value ?? (value = _normalized.value);
1930
- const input = payload.value;
1931
- if (!isObject$1(input)) {
1932
- payload.issues.push({
1933
- expected: "object",
1934
- code: "invalid_type",
1935
- input,
1936
- inst,
1937
- });
1938
- return payload;
1939
- }
1940
- const proms = [];
1941
- if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1942
- // always synchronous
1943
- if (!fastpass)
1944
- fastpass = generateFastpass(def.shape);
1945
- payload = fastpass(payload, ctx);
1946
- }
1947
- else {
1948
- payload.value = {};
1949
- const shape = value.shape;
1950
- for (const key of value.keys) {
1951
- const el = shape[key];
1952
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
1953
- if (r instanceof Promise) {
1954
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1955
- }
1956
- else {
1957
- handlePropertyResult(r, payload, key, input);
1958
- }
1959
- }
1960
- }
1961
- if (!catchall) {
1962
- return proms.length ? Promise.all(proms).then(() => payload) : payload;
1963
- }
1964
- const unrecognized = [];
1965
- // iterate over input keys
1966
- const keySet = value.keySet;
1967
- const _catchall = catchall._zod;
1968
- const t = _catchall.def.type;
1969
- for (const key of Object.keys(input)) {
1970
- if (keySet.has(key))
1971
- continue;
1972
- if (t === "never") {
1973
- unrecognized.push(key);
1974
- continue;
1975
- }
1976
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
1977
- if (r instanceof Promise) {
1978
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1979
- }
1980
- else {
1981
- handlePropertyResult(r, payload, key, input);
1982
- }
1983
- }
1984
- if (unrecognized.length) {
1985
- payload.issues.push({
1986
- code: "unrecognized_keys",
1987
- keys: unrecognized,
1988
- input,
1989
- inst,
1990
- });
1991
- }
1992
- if (!proms.length)
1993
- return payload;
1994
- return Promise.all(proms).then(() => {
1995
- return payload;
1996
- });
1997
- };
1998
- });
1999
- function handleUnionResults(results, final, inst, ctx) {
2000
- for (const result of results) {
2001
- if (result.issues.length === 0) {
2002
- final.value = result.value;
2003
- return final;
2004
- }
2005
- }
2006
- const nonaborted = results.filter((r) => !aborted(r));
2007
- if (nonaborted.length === 1) {
2008
- final.value = nonaborted[0].value;
2009
- return nonaborted[0];
2010
- }
2011
- final.issues.push({
2012
- code: "invalid_union",
2013
- input: final.value,
2014
- inst,
2015
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))),
2016
- });
2017
- return final;
2018
- }
2019
- const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
2020
- $ZodType.init(inst, def);
2021
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined);
2022
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
2023
- defineLazy(inst._zod, "values", () => {
2024
- if (def.options.every((o) => o._zod.values)) {
2025
- return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
2026
- }
2027
- return undefined;
2028
- });
2029
- defineLazy(inst._zod, "pattern", () => {
2030
- if (def.options.every((o) => o._zod.pattern)) {
2031
- const patterns = def.options.map((o) => o._zod.pattern);
2032
- return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
2033
- }
2034
- return undefined;
2035
- });
2036
- const single = def.options.length === 1;
2037
- const first = def.options[0]._zod.run;
2038
- inst._zod.parse = (payload, ctx) => {
2039
- if (single) {
2040
- return first(payload, ctx);
2041
- }
2042
- let async = false;
2043
- const results = [];
2044
- for (const option of def.options) {
2045
- const result = option._zod.run({
2046
- value: payload.value,
2047
- issues: [],
2048
- }, ctx);
2049
- if (result instanceof Promise) {
2050
- results.push(result);
2051
- async = true;
2052
- }
2053
- else {
2054
- if (result.issues.length === 0)
2055
- return result;
2056
- results.push(result);
2057
- }
2058
- }
2059
- if (!async)
2060
- return handleUnionResults(results, payload, inst, ctx);
2061
- return Promise.all(results).then((results) => {
2062
- return handleUnionResults(results, payload, inst, ctx);
2063
- });
2064
- };
2065
- });
2066
- const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
2067
- $ZodType.init(inst, def);
2068
- inst._zod.parse = (payload, ctx) => {
2069
- const input = payload.value;
2070
- const left = def.left._zod.run({ value: input, issues: [] }, ctx);
2071
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
2072
- const async = left instanceof Promise || right instanceof Promise;
2073
- if (async) {
2074
- return Promise.all([left, right]).then(([left, right]) => {
2075
- return handleIntersectionResults(payload, left, right);
2076
- });
2077
- }
2078
- return handleIntersectionResults(payload, left, right);
2079
- };
2080
- });
2081
- function mergeValues(a, b) {
2082
- // const aType = parse.t(a);
2083
- // const bType = parse.t(b);
2084
- if (a === b) {
2085
- return { valid: true, data: a };
2086
- }
2087
- if (a instanceof Date && b instanceof Date && +a === +b) {
2088
- return { valid: true, data: a };
2089
- }
2090
- if (isPlainObject(a) && isPlainObject(b)) {
2091
- const bKeys = Object.keys(b);
2092
- const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
2093
- const newObj = { ...a, ...b };
2094
- for (const key of sharedKeys) {
2095
- const sharedValue = mergeValues(a[key], b[key]);
2096
- if (!sharedValue.valid) {
2097
- return {
2098
- valid: false,
2099
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath],
2100
- };
2101
- }
2102
- newObj[key] = sharedValue.data;
2103
- }
2104
- return { valid: true, data: newObj };
2105
- }
2106
- if (Array.isArray(a) && Array.isArray(b)) {
2107
- if (a.length !== b.length) {
2108
- return { valid: false, mergeErrorPath: [] };
2109
- }
2110
- const newArray = [];
2111
- for (let index = 0; index < a.length; index++) {
2112
- const itemA = a[index];
2113
- const itemB = b[index];
2114
- const sharedValue = mergeValues(itemA, itemB);
2115
- if (!sharedValue.valid) {
2116
- return {
2117
- valid: false,
2118
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath],
2119
- };
2120
- }
2121
- newArray.push(sharedValue.data);
2122
- }
2123
- return { valid: true, data: newArray };
2124
- }
2125
- return { valid: false, mergeErrorPath: [] };
2126
- }
2127
- function handleIntersectionResults(result, left, right) {
2128
- if (left.issues.length) {
2129
- result.issues.push(...left.issues);
2130
- }
2131
- if (right.issues.length) {
2132
- result.issues.push(...right.issues);
2133
- }
2134
- if (aborted(result))
2135
- return result;
2136
- const merged = mergeValues(left.value, right.value);
2137
- if (!merged.valid) {
2138
- throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);
2139
- }
2140
- result.value = merged.data;
2141
- return result;
2142
- }
2143
- const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
2144
- $ZodType.init(inst, def);
2145
- const values = getEnumValues(def.entries);
2146
- const valuesSet = new Set(values);
2147
- inst._zod.values = valuesSet;
2148
- inst._zod.pattern = new RegExp(`^(${values
2149
- .filter((k) => propertyKeyTypes.has(typeof k))
2150
- .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString()))
2151
- .join("|")})$`);
2152
- inst._zod.parse = (payload, _ctx) => {
2153
- const input = payload.value;
2154
- if (valuesSet.has(input)) {
2155
- return payload;
2156
- }
2157
- payload.issues.push({
2158
- code: "invalid_value",
2159
- values,
2160
- input,
2161
- inst,
2162
- });
2163
- return payload;
2164
- };
2165
- });
2166
- const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
2167
- $ZodType.init(inst, def);
2168
- inst._zod.parse = (payload, _ctx) => {
2169
- const _out = def.transform(payload.value, payload);
2170
- if (_ctx.async) {
2171
- const output = _out instanceof Promise ? _out : Promise.resolve(_out);
2172
- return output.then((output) => {
2173
- payload.value = output;
2174
- return payload;
2175
- });
2176
- }
2177
- if (_out instanceof Promise) {
2178
- throw new $ZodAsyncError();
2179
- }
2180
- payload.value = _out;
2181
- return payload;
2182
- };
2183
- });
2184
- function handleOptionalResult(result, input) {
2185
- if (result.issues.length && input === undefined) {
2186
- return { issues: [], value: undefined };
2187
- }
2188
- return result;
2189
- }
2190
- const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
2191
- $ZodType.init(inst, def);
2192
- inst._zod.optin = "optional";
2193
- inst._zod.optout = "optional";
2194
- defineLazy(inst._zod, "values", () => {
2195
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;
2196
- });
2197
- defineLazy(inst._zod, "pattern", () => {
2198
- const pattern = def.innerType._zod.pattern;
2199
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
2200
- });
2201
- inst._zod.parse = (payload, ctx) => {
2202
- if (def.innerType._zod.optin === "optional") {
2203
- const result = def.innerType._zod.run(payload, ctx);
2204
- if (result instanceof Promise)
2205
- return result.then((r) => handleOptionalResult(r, payload.value));
2206
- return handleOptionalResult(result, payload.value);
2207
- }
2208
- if (payload.value === undefined) {
2209
- return payload;
2210
- }
2211
- return def.innerType._zod.run(payload, ctx);
2212
- };
2213
- });
2214
- const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
2215
- $ZodType.init(inst, def);
2216
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2217
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2218
- defineLazy(inst._zod, "pattern", () => {
2219
- const pattern = def.innerType._zod.pattern;
2220
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined;
2221
- });
2222
- defineLazy(inst._zod, "values", () => {
2223
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
2224
- });
2225
- inst._zod.parse = (payload, ctx) => {
2226
- if (payload.value === null)
2227
- return payload;
2228
- return def.innerType._zod.run(payload, ctx);
2229
- };
2230
- });
2231
- const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
2232
- $ZodType.init(inst, def);
2233
- // inst._zod.qin = "true";
2234
- inst._zod.optin = "optional";
2235
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2236
- inst._zod.parse = (payload, ctx) => {
2237
- if (payload.value === undefined) {
2238
- payload.value = def.defaultValue;
2239
- /**
2240
- * $ZodDefault always returns the default value immediately.
2241
- * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
2242
- return payload;
2243
- }
2244
- const result = def.innerType._zod.run(payload, ctx);
2245
- if (result instanceof Promise) {
2246
- return result.then((result) => handleDefaultResult(result, def));
2247
- }
2248
- return handleDefaultResult(result, def);
2249
- };
2250
- });
2251
- function handleDefaultResult(payload, def) {
2252
- if (payload.value === undefined) {
2253
- payload.value = def.defaultValue;
2254
- }
2255
- return payload;
2256
- }
2257
- const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
2258
- $ZodType.init(inst, def);
2259
- inst._zod.optin = "optional";
2260
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2261
- inst._zod.parse = (payload, ctx) => {
2262
- if (payload.value === undefined) {
2263
- payload.value = def.defaultValue;
2264
- }
2265
- return def.innerType._zod.run(payload, ctx);
2266
- };
2267
- });
2268
- const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
2269
- $ZodType.init(inst, def);
2270
- defineLazy(inst._zod, "values", () => {
2271
- const v = def.innerType._zod.values;
2272
- return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;
2273
- });
2274
- inst._zod.parse = (payload, ctx) => {
2275
- const result = def.innerType._zod.run(payload, ctx);
2276
- if (result instanceof Promise) {
2277
- return result.then((result) => handleNonOptionalResult(result, inst));
2278
- }
2279
- return handleNonOptionalResult(result, inst);
2280
- };
2281
- });
2282
- function handleNonOptionalResult(payload, inst) {
2283
- if (!payload.issues.length && payload.value === undefined) {
2284
- payload.issues.push({
2285
- code: "invalid_type",
2286
- expected: "nonoptional",
2287
- input: payload.value,
2288
- inst,
2289
- });
2290
- }
2291
- return payload;
2292
- }
2293
- const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
2294
- $ZodType.init(inst, def);
2295
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2296
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2297
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2298
- inst._zod.parse = (payload, ctx) => {
2299
- const result = def.innerType._zod.run(payload, ctx);
2300
- if (result instanceof Promise) {
2301
- return result.then((result) => {
2302
- payload.value = result.value;
2303
- if (result.issues.length) {
2304
- payload.value = def.catchValue({
2305
- ...payload,
2306
- error: {
2307
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
2308
- },
2309
- input: payload.value,
2310
- });
2311
- payload.issues = [];
2312
- }
2313
- return payload;
2314
- });
2315
- }
2316
- payload.value = result.value;
2317
- if (result.issues.length) {
2318
- payload.value = def.catchValue({
2319
- ...payload,
2320
- error: {
2321
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())),
2322
- },
2323
- input: payload.value,
2324
- });
2325
- payload.issues = [];
2326
- }
2327
- return payload;
2328
- };
2329
- });
2330
- const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
2331
- $ZodType.init(inst, def);
2332
- defineLazy(inst._zod, "values", () => def.in._zod.values);
2333
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
2334
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
2335
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
2336
- inst._zod.parse = (payload, ctx) => {
2337
- const left = def.in._zod.run(payload, ctx);
2338
- if (left instanceof Promise) {
2339
- return left.then((left) => handlePipeResult(left, def, ctx));
2340
- }
2341
- return handlePipeResult(left, def, ctx);
2342
- };
2343
- });
2344
- function handlePipeResult(left, def, ctx) {
2345
- if (left.issues.length) {
2346
- return left;
2347
- }
2348
- return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
2349
- }
2350
- const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
2351
- $ZodType.init(inst, def);
2352
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2353
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2354
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2355
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2356
- inst._zod.parse = (payload, ctx) => {
2357
- const result = def.innerType._zod.run(payload, ctx);
2358
- if (result instanceof Promise) {
2359
- return result.then(handleReadonlyResult);
2360
- }
2361
- return handleReadonlyResult(result);
2362
- };
2363
- });
2364
- function handleReadonlyResult(payload) {
2365
- payload.value = Object.freeze(payload.value);
2366
- return payload;
2367
- }
2368
- const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
2369
- $ZodCheck.init(inst, def);
2370
- $ZodType.init(inst, def);
2371
- inst._zod.parse = (payload, _) => {
2372
- return payload;
2373
- };
2374
- inst._zod.check = (payload) => {
2375
- const input = payload.value;
2376
- const r = def.fn(input);
2377
- if (r instanceof Promise) {
2378
- return r.then((r) => handleRefineResult(r, payload, input, inst));
2379
- }
2380
- handleRefineResult(r, payload, input, inst);
2381
- return;
2382
- };
2383
- });
2384
- function handleRefineResult(result, payload, input, inst) {
2385
- if (!result) {
2386
- const _iss = {
2387
- code: "custom",
2388
- input,
2389
- inst, // incorporates params.error into issue reporting
2390
- path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting
2391
- continue: !inst._zod.def.abort,
2392
- // params: inst._zod.def.params,
2393
- };
2394
- if (inst._zod.def.params)
2395
- _iss.params = inst._zod.def.params;
2396
- payload.issues.push(issue(_iss));
2397
- }
2398
- }
2399
-
2400
- class $ZodRegistry {
2401
- constructor() {
2402
- this._map = new Map();
2403
- this._idmap = new Map();
2404
- }
2405
- add(schema, ..._meta) {
2406
- const meta = _meta[0];
2407
- this._map.set(schema, meta);
2408
- if (meta && typeof meta === "object" && "id" in meta) {
2409
- if (this._idmap.has(meta.id)) {
2410
- throw new Error(`ID ${meta.id} already exists in the registry`);
2411
- }
2412
- this._idmap.set(meta.id, schema);
2413
- }
2414
- return this;
2415
- }
2416
- clear() {
2417
- this._map = new Map();
2418
- this._idmap = new Map();
2419
- return this;
2420
- }
2421
- remove(schema) {
2422
- const meta = this._map.get(schema);
2423
- if (meta && typeof meta === "object" && "id" in meta) {
2424
- this._idmap.delete(meta.id);
2425
- }
2426
- this._map.delete(schema);
2427
- return this;
2428
- }
2429
- get(schema) {
2430
- // return this._map.get(schema) as any;
2431
- // inherit metadata
2432
- const p = schema._zod.parent;
2433
- if (p) {
2434
- const pm = { ...(this.get(p) ?? {}) };
2435
- delete pm.id; // do not inherit id
2436
- const f = { ...pm, ...this._map.get(schema) };
2437
- return Object.keys(f).length ? f : undefined;
2438
- }
2439
- return this._map.get(schema);
2440
- }
2441
- has(schema) {
2442
- return this._map.has(schema);
2443
- }
2444
- }
2445
- // registries
2446
- function registry() {
2447
- return new $ZodRegistry();
2448
- }
2449
- const globalRegistry = /*@__PURE__*/ registry();
2450
-
2451
- function _string(Class, params) {
2452
- return new Class({
2453
- type: "string",
2454
- ...normalizeParams(params),
2455
- });
2456
- }
2457
- function _email(Class, params) {
2458
- return new Class({
2459
- type: "string",
2460
- format: "email",
2461
- check: "string_format",
2462
- abort: false,
2463
- ...normalizeParams(params),
2464
- });
2465
- }
2466
- function _guid(Class, params) {
2467
- return new Class({
2468
- type: "string",
2469
- format: "guid",
2470
- check: "string_format",
2471
- abort: false,
2472
- ...normalizeParams(params),
2473
- });
2474
- }
2475
- function _uuid(Class, params) {
2476
- return new Class({
2477
- type: "string",
2478
- format: "uuid",
2479
- check: "string_format",
2480
- abort: false,
2481
- ...normalizeParams(params),
2482
- });
2483
- }
2484
- function _uuidv4(Class, params) {
2485
- return new Class({
2486
- type: "string",
2487
- format: "uuid",
2488
- check: "string_format",
2489
- abort: false,
2490
- version: "v4",
2491
- ...normalizeParams(params),
2492
- });
2493
- }
2494
- function _uuidv6(Class, params) {
2495
- return new Class({
2496
- type: "string",
2497
- format: "uuid",
2498
- check: "string_format",
2499
- abort: false,
2500
- version: "v6",
2501
- ...normalizeParams(params),
2502
- });
2503
- }
2504
- function _uuidv7(Class, params) {
2505
- return new Class({
2506
- type: "string",
2507
- format: "uuid",
2508
- check: "string_format",
2509
- abort: false,
2510
- version: "v7",
2511
- ...normalizeParams(params),
2512
- });
2513
- }
2514
- function _url(Class, params) {
2515
- return new Class({
2516
- type: "string",
2517
- format: "url",
2518
- check: "string_format",
2519
- abort: false,
2520
- ...normalizeParams(params),
2521
- });
2522
- }
2523
- function _emoji(Class, params) {
2524
- return new Class({
2525
- type: "string",
2526
- format: "emoji",
2527
- check: "string_format",
2528
- abort: false,
2529
- ...normalizeParams(params),
2530
- });
2531
- }
2532
- function _nanoid(Class, params) {
2533
- return new Class({
2534
- type: "string",
2535
- format: "nanoid",
2536
- check: "string_format",
2537
- abort: false,
2538
- ...normalizeParams(params),
2539
- });
2540
- }
2541
- function _cuid(Class, params) {
2542
- return new Class({
2543
- type: "string",
2544
- format: "cuid",
2545
- check: "string_format",
2546
- abort: false,
2547
- ...normalizeParams(params),
2548
- });
2549
- }
2550
- function _cuid2(Class, params) {
2551
- return new Class({
2552
- type: "string",
2553
- format: "cuid2",
2554
- check: "string_format",
2555
- abort: false,
2556
- ...normalizeParams(params),
2557
- });
2558
- }
2559
- function _ulid(Class, params) {
2560
- return new Class({
2561
- type: "string",
2562
- format: "ulid",
2563
- check: "string_format",
2564
- abort: false,
2565
- ...normalizeParams(params),
2566
- });
2567
- }
2568
- function _xid(Class, params) {
2569
- return new Class({
2570
- type: "string",
2571
- format: "xid",
2572
- check: "string_format",
2573
- abort: false,
2574
- ...normalizeParams(params),
2575
- });
2576
- }
2577
- function _ksuid(Class, params) {
2578
- return new Class({
2579
- type: "string",
2580
- format: "ksuid",
2581
- check: "string_format",
2582
- abort: false,
2583
- ...normalizeParams(params),
2584
- });
2585
- }
2586
- function _ipv4(Class, params) {
2587
- return new Class({
2588
- type: "string",
2589
- format: "ipv4",
2590
- check: "string_format",
2591
- abort: false,
2592
- ...normalizeParams(params),
2593
- });
2594
- }
2595
- function _ipv6(Class, params) {
2596
- return new Class({
2597
- type: "string",
2598
- format: "ipv6",
2599
- check: "string_format",
2600
- abort: false,
2601
- ...normalizeParams(params),
2602
- });
2603
- }
2604
- function _cidrv4(Class, params) {
2605
- return new Class({
2606
- type: "string",
2607
- format: "cidrv4",
2608
- check: "string_format",
2609
- abort: false,
2610
- ...normalizeParams(params),
2611
- });
2612
- }
2613
- function _cidrv6(Class, params) {
2614
- return new Class({
2615
- type: "string",
2616
- format: "cidrv6",
2617
- check: "string_format",
2618
- abort: false,
2619
- ...normalizeParams(params),
2620
- });
2621
- }
2622
- function _base64(Class, params) {
2623
- return new Class({
2624
- type: "string",
2625
- format: "base64",
2626
- check: "string_format",
2627
- abort: false,
2628
- ...normalizeParams(params),
2629
- });
2630
- }
2631
- function _base64url(Class, params) {
2632
- return new Class({
2633
- type: "string",
2634
- format: "base64url",
2635
- check: "string_format",
2636
- abort: false,
2637
- ...normalizeParams(params),
2638
- });
2639
- }
2640
- function _e164(Class, params) {
2641
- return new Class({
2642
- type: "string",
2643
- format: "e164",
2644
- check: "string_format",
2645
- abort: false,
2646
- ...normalizeParams(params),
2647
- });
2648
- }
2649
- function _jwt(Class, params) {
2650
- return new Class({
2651
- type: "string",
2652
- format: "jwt",
2653
- check: "string_format",
2654
- abort: false,
2655
- ...normalizeParams(params),
2656
- });
2657
- }
2658
- function _isoDateTime(Class, params) {
2659
- return new Class({
2660
- type: "string",
2661
- format: "datetime",
2662
- check: "string_format",
2663
- offset: false,
2664
- local: false,
2665
- precision: null,
2666
- ...normalizeParams(params),
2667
- });
2668
- }
2669
- function _isoDate(Class, params) {
2670
- return new Class({
2671
- type: "string",
2672
- format: "date",
2673
- check: "string_format",
2674
- ...normalizeParams(params),
2675
- });
2676
- }
2677
- function _isoTime(Class, params) {
2678
- return new Class({
2679
- type: "string",
2680
- format: "time",
2681
- check: "string_format",
2682
- precision: null,
2683
- ...normalizeParams(params),
2684
- });
2685
- }
2686
- function _isoDuration(Class, params) {
2687
- return new Class({
2688
- type: "string",
2689
- format: "duration",
2690
- check: "string_format",
2691
- ...normalizeParams(params),
2692
- });
2693
- }
2694
- function _number(Class, params) {
2695
- return new Class({
2696
- type: "number",
2697
- checks: [],
2698
- ...normalizeParams(params),
2699
- });
2700
- }
2701
- function _int(Class, params) {
2702
- return new Class({
2703
- type: "number",
2704
- check: "number_format",
2705
- abort: false,
2706
- format: "safeint",
2707
- ...normalizeParams(params),
2708
- });
2709
- }
2710
- function _boolean(Class, params) {
2711
- return new Class({
2712
- type: "boolean",
2713
- ...normalizeParams(params),
2714
- });
2715
- }
2716
- function _any(Class) {
2717
- return new Class({
2718
- type: "any",
2719
- });
2720
- }
2721
- function _unknown(Class) {
2722
- return new Class({
2723
- type: "unknown",
2724
- });
2725
- }
2726
- function _never(Class, params) {
2727
- return new Class({
2728
- type: "never",
2729
- ...normalizeParams(params),
2730
- });
2731
- }
2732
- function _lt(value, params) {
2733
- return new $ZodCheckLessThan({
2734
- check: "less_than",
2735
- ...normalizeParams(params),
2736
- value,
2737
- inclusive: false,
2738
- });
2739
- }
2740
- function _lte(value, params) {
2741
- return new $ZodCheckLessThan({
2742
- check: "less_than",
2743
- ...normalizeParams(params),
2744
- value,
2745
- inclusive: true,
2746
- });
2747
- }
2748
- function _gt(value, params) {
2749
- return new $ZodCheckGreaterThan({
2750
- check: "greater_than",
2751
- ...normalizeParams(params),
2752
- value,
2753
- inclusive: false,
2754
- });
2755
- }
2756
- function _gte(value, params) {
2757
- return new $ZodCheckGreaterThan({
2758
- check: "greater_than",
2759
- ...normalizeParams(params),
2760
- value,
2761
- inclusive: true,
2762
- });
2763
- }
2764
- function _multipleOf(value, params) {
2765
- return new $ZodCheckMultipleOf({
2766
- check: "multiple_of",
2767
- ...normalizeParams(params),
2768
- value,
2769
- });
2770
- }
2771
- function _maxLength(maximum, params) {
2772
- const ch = new $ZodCheckMaxLength({
2773
- check: "max_length",
2774
- ...normalizeParams(params),
2775
- maximum,
2776
- });
2777
- return ch;
2778
- }
2779
- function _minLength(minimum, params) {
2780
- return new $ZodCheckMinLength({
2781
- check: "min_length",
2782
- ...normalizeParams(params),
2783
- minimum,
2784
- });
2785
- }
2786
- function _length(length, params) {
2787
- return new $ZodCheckLengthEquals({
2788
- check: "length_equals",
2789
- ...normalizeParams(params),
2790
- length,
2791
- });
2792
- }
2793
- function _regex(pattern, params) {
2794
- return new $ZodCheckRegex({
2795
- check: "string_format",
2796
- format: "regex",
2797
- ...normalizeParams(params),
2798
- pattern,
2799
- });
2800
- }
2801
- function _lowercase(params) {
2802
- return new $ZodCheckLowerCase({
2803
- check: "string_format",
2804
- format: "lowercase",
2805
- ...normalizeParams(params),
2806
- });
2807
- }
2808
- function _uppercase(params) {
2809
- return new $ZodCheckUpperCase({
2810
- check: "string_format",
2811
- format: "uppercase",
2812
- ...normalizeParams(params),
2813
- });
2814
- }
2815
- function _includes(includes, params) {
2816
- return new $ZodCheckIncludes({
2817
- check: "string_format",
2818
- format: "includes",
2819
- ...normalizeParams(params),
2820
- includes,
2821
- });
2822
- }
2823
- function _startsWith(prefix, params) {
2824
- return new $ZodCheckStartsWith({
2825
- check: "string_format",
2826
- format: "starts_with",
2827
- ...normalizeParams(params),
2828
- prefix,
2829
- });
2830
- }
2831
- function _endsWith(suffix, params) {
2832
- return new $ZodCheckEndsWith({
2833
- check: "string_format",
2834
- format: "ends_with",
2835
- ...normalizeParams(params),
2836
- suffix,
2837
- });
2838
- }
2839
- function _overwrite(tx) {
2840
- return new $ZodCheckOverwrite({
2841
- check: "overwrite",
2842
- tx,
2843
- });
2844
- }
2845
- // normalize
2846
- function _normalize(form) {
2847
- return _overwrite((input) => input.normalize(form));
2848
- }
2849
- // trim
2850
- function _trim() {
2851
- return _overwrite((input) => input.trim());
2852
- }
2853
- // toLowerCase
2854
- function _toLowerCase() {
2855
- return _overwrite((input) => input.toLowerCase());
2856
- }
2857
- // toUpperCase
2858
- function _toUpperCase() {
2859
- return _overwrite((input) => input.toUpperCase());
2860
- }
2861
- function _array(Class, element, params) {
2862
- return new Class({
2863
- type: "array",
2864
- element,
2865
- // get element() {
2866
- // return element;
2867
- // },
2868
- ...normalizeParams(params),
2869
- });
2870
- }
2871
- // same as _custom but defaults to abort:false
2872
- function _refine(Class, fn, _params) {
2873
- const schema = new Class({
2874
- type: "custom",
2875
- check: "custom",
2876
- fn: fn,
2877
- ...normalizeParams(_params),
2878
- });
2879
- return schema;
2880
- }
2881
- function _superRefine(fn) {
2882
- const ch = _check((payload) => {
2883
- payload.addIssue = (issue$1) => {
2884
- if (typeof issue$1 === "string") {
2885
- payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
2886
- }
2887
- else {
2888
- // for Zod 3 backwards compatibility
2889
- const _issue = issue$1;
2890
- if (_issue.fatal)
2891
- _issue.continue = false;
2892
- _issue.code ?? (_issue.code = "custom");
2893
- _issue.input ?? (_issue.input = payload.value);
2894
- _issue.inst ?? (_issue.inst = ch);
2895
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2896
- payload.issues.push(issue(_issue));
2897
- }
2898
- };
2899
- return fn(payload.value, payload);
2900
- });
2901
- return ch;
2902
- }
2903
- function _check(fn, params) {
2904
- const ch = new $ZodCheck({
2905
- check: "custom",
2906
- ...normalizeParams(params),
2907
- });
2908
- ch._zod.check = fn;
2909
- return ch;
2910
- }
2911
-
2912
- const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
2913
- $ZodISODateTime.init(inst, def);
2914
- ZodStringFormat.init(inst, def);
2915
- });
2916
- function datetime(params) {
2917
- return _isoDateTime(ZodISODateTime, params);
2918
- }
2919
- const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
2920
- $ZodISODate.init(inst, def);
2921
- ZodStringFormat.init(inst, def);
2922
- });
2923
- function date(params) {
2924
- return _isoDate(ZodISODate, params);
2925
- }
2926
- const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
2927
- $ZodISOTime.init(inst, def);
2928
- ZodStringFormat.init(inst, def);
2929
- });
2930
- function time(params) {
2931
- return _isoTime(ZodISOTime, params);
2932
- }
2933
- const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
2934
- $ZodISODuration.init(inst, def);
2935
- ZodStringFormat.init(inst, def);
2936
- });
2937
- function duration(params) {
2938
- return _isoDuration(ZodISODuration, params);
2939
- }
2940
-
2941
- const initializer = (inst, issues) => {
2942
- $ZodError.init(inst, issues);
2943
- inst.name = "ZodError";
2944
- Object.defineProperties(inst, {
2945
- format: {
2946
- value: (mapper) => formatError(inst, mapper),
2947
- // enumerable: false,
2948
- },
2949
- flatten: {
2950
- value: (mapper) => flattenError(inst, mapper),
2951
- // enumerable: false,
2952
- },
2953
- addIssue: {
2954
- value: (issue) => {
2955
- inst.issues.push(issue);
2956
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2957
- },
2958
- // enumerable: false,
2959
- },
2960
- addIssues: {
2961
- value: (issues) => {
2962
- inst.issues.push(...issues);
2963
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2964
- },
2965
- // enumerable: false,
2966
- },
2967
- isEmpty: {
2968
- get() {
2969
- return inst.issues.length === 0;
2970
- },
2971
- // enumerable: false,
2972
- },
2973
- });
2974
- // Object.defineProperty(inst, "isEmpty", {
2975
- // get() {
2976
- // return inst.issues.length === 0;
2977
- // },
2978
- // });
2979
- };
2980
- const ZodError = $constructor("ZodError", initializer);
2981
- const ZodRealError = $constructor("ZodError", initializer, {
2982
- Parent: Error,
2983
- });
2984
- // /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */
2985
- // export type ErrorMapCtx = core.$ZodErrorMapCtx;
2986
-
2987
- const parse = /* @__PURE__ */ _parse(ZodRealError);
2988
- const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2989
- const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2990
- const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
2991
-
2992
- const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
2993
- $ZodType.init(inst, def);
2994
- inst.def = def;
2995
- Object.defineProperty(inst, "_def", { value: def });
2996
- // base methods
2997
- inst.check = (...checks) => {
2998
- return inst.clone({
2999
- ...def,
3000
- checks: [
3001
- ...(def.checks ?? []),
3002
- ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
3003
- ],
3004
- }
3005
- // { parent: true }
3006
- );
3007
- };
3008
- inst.clone = (def, params) => clone(inst, def, params);
3009
- inst.brand = () => inst;
3010
- inst.register = ((reg, meta) => {
3011
- reg.add(inst, meta);
3012
- return inst;
3013
- });
3014
- // parsing
3015
- inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
3016
- inst.safeParse = (data, params) => safeParse(inst, data, params);
3017
- inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
3018
- inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
3019
- inst.spa = inst.safeParseAsync;
3020
- // refinements
3021
- inst.refine = (check, params) => inst.check(refine(check, params));
3022
- inst.superRefine = (refinement) => inst.check(superRefine(refinement));
3023
- inst.overwrite = (fn) => inst.check(_overwrite(fn));
3024
- // wrappers
3025
- inst.optional = () => optional(inst);
3026
- inst.nullable = () => nullable(inst);
3027
- inst.nullish = () => optional(nullable(inst));
3028
- inst.nonoptional = (params) => nonoptional(inst, params);
3029
- inst.array = () => array(inst);
3030
- inst.or = (arg) => union([inst, arg]);
3031
- inst.and = (arg) => intersection(inst, arg);
3032
- inst.transform = (tx) => pipe(inst, transform(tx));
3033
- inst.default = (def) => _default(inst, def);
3034
- inst.prefault = (def) => prefault(inst, def);
3035
- // inst.coalesce = (def, params) => coalesce(inst, def, params);
3036
- inst.catch = (params) => _catch(inst, params);
3037
- inst.pipe = (target) => pipe(inst, target);
3038
- inst.readonly = () => readonly(inst);
3039
- // meta
3040
- inst.describe = (description) => {
3041
- const cl = inst.clone();
3042
- globalRegistry.add(cl, { description });
3043
- return cl;
3044
- };
3045
- Object.defineProperty(inst, "description", {
3046
- get() {
3047
- return globalRegistry.get(inst)?.description;
3048
- },
3049
- configurable: true,
3050
- });
3051
- inst.meta = (...args) => {
3052
- if (args.length === 0) {
3053
- return globalRegistry.get(inst);
3054
- }
3055
- const cl = inst.clone();
3056
- globalRegistry.add(cl, args[0]);
3057
- return cl;
3058
- };
3059
- // helpers
3060
- inst.isOptional = () => inst.safeParse(undefined).success;
3061
- inst.isNullable = () => inst.safeParse(null).success;
3062
- return inst;
3063
- });
3064
- /** @internal */
3065
- const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
3066
- $ZodString.init(inst, def);
3067
- ZodType.init(inst, def);
3068
- const bag = inst._zod.bag;
3069
- inst.format = bag.format ?? null;
3070
- inst.minLength = bag.minimum ?? null;
3071
- inst.maxLength = bag.maximum ?? null;
3072
- // validations
3073
- inst.regex = (...args) => inst.check(_regex(...args));
3074
- inst.includes = (...args) => inst.check(_includes(...args));
3075
- inst.startsWith = (...args) => inst.check(_startsWith(...args));
3076
- inst.endsWith = (...args) => inst.check(_endsWith(...args));
3077
- inst.min = (...args) => inst.check(_minLength(...args));
3078
- inst.max = (...args) => inst.check(_maxLength(...args));
3079
- inst.length = (...args) => inst.check(_length(...args));
3080
- inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
3081
- inst.lowercase = (params) => inst.check(_lowercase(params));
3082
- inst.uppercase = (params) => inst.check(_uppercase(params));
3083
- // transforms
3084
- inst.trim = () => inst.check(_trim());
3085
- inst.normalize = (...args) => inst.check(_normalize(...args));
3086
- inst.toLowerCase = () => inst.check(_toLowerCase());
3087
- inst.toUpperCase = () => inst.check(_toUpperCase());
3088
- });
3089
- const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
3090
- $ZodString.init(inst, def);
3091
- _ZodString.init(inst, def);
3092
- inst.email = (params) => inst.check(_email(ZodEmail, params));
3093
- inst.url = (params) => inst.check(_url(ZodURL, params));
3094
- inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
3095
- inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
3096
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3097
- inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
3098
- inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
3099
- inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
3100
- inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
3101
- inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
3102
- inst.guid = (params) => inst.check(_guid(ZodGUID, params));
3103
- inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
3104
- inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
3105
- inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
3106
- inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
3107
- inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
3108
- inst.xid = (params) => inst.check(_xid(ZodXID, params));
3109
- inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
3110
- inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
3111
- inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
3112
- inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
3113
- inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
3114
- inst.e164 = (params) => inst.check(_e164(ZodE164, params));
3115
- // iso
3116
- inst.datetime = (params) => inst.check(datetime(params));
3117
- inst.date = (params) => inst.check(date(params));
3118
- inst.time = (params) => inst.check(time(params));
3119
- inst.duration = (params) => inst.check(duration(params));
3120
- });
3121
- function string(params) {
3122
- return _string(ZodString, params);
3123
- }
3124
- const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
3125
- $ZodStringFormat.init(inst, def);
3126
- _ZodString.init(inst, def);
3127
- });
3128
- const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
3129
- // ZodStringFormat.init(inst, def);
3130
- $ZodEmail.init(inst, def);
3131
- ZodStringFormat.init(inst, def);
3132
- });
3133
- const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
3134
- // ZodStringFormat.init(inst, def);
3135
- $ZodGUID.init(inst, def);
3136
- ZodStringFormat.init(inst, def);
3137
- });
3138
- const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
3139
- // ZodStringFormat.init(inst, def);
3140
- $ZodUUID.init(inst, def);
3141
- ZodStringFormat.init(inst, def);
3142
- });
3143
- const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
3144
- // ZodStringFormat.init(inst, def);
3145
- $ZodURL.init(inst, def);
3146
- ZodStringFormat.init(inst, def);
3147
- });
3148
- const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
3149
- // ZodStringFormat.init(inst, def);
3150
- $ZodEmoji.init(inst, def);
3151
- ZodStringFormat.init(inst, def);
3152
- });
3153
- const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
3154
- // ZodStringFormat.init(inst, def);
3155
- $ZodNanoID.init(inst, def);
3156
- ZodStringFormat.init(inst, def);
3157
- });
3158
- const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
3159
- // ZodStringFormat.init(inst, def);
3160
- $ZodCUID.init(inst, def);
3161
- ZodStringFormat.init(inst, def);
3162
- });
3163
- const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
3164
- // ZodStringFormat.init(inst, def);
3165
- $ZodCUID2.init(inst, def);
3166
- ZodStringFormat.init(inst, def);
3167
- });
3168
- const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
3169
- // ZodStringFormat.init(inst, def);
3170
- $ZodULID.init(inst, def);
3171
- ZodStringFormat.init(inst, def);
3172
- });
3173
- const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
3174
- // ZodStringFormat.init(inst, def);
3175
- $ZodXID.init(inst, def);
3176
- ZodStringFormat.init(inst, def);
3177
- });
3178
- const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
3179
- // ZodStringFormat.init(inst, def);
3180
- $ZodKSUID.init(inst, def);
3181
- ZodStringFormat.init(inst, def);
3182
- });
3183
- const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
3184
- // ZodStringFormat.init(inst, def);
3185
- $ZodIPv4.init(inst, def);
3186
- ZodStringFormat.init(inst, def);
3187
- });
3188
- const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
3189
- // ZodStringFormat.init(inst, def);
3190
- $ZodIPv6.init(inst, def);
3191
- ZodStringFormat.init(inst, def);
3192
- });
3193
- const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
3194
- $ZodCIDRv4.init(inst, def);
3195
- ZodStringFormat.init(inst, def);
3196
- });
3197
- const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
3198
- $ZodCIDRv6.init(inst, def);
3199
- ZodStringFormat.init(inst, def);
3200
- });
3201
- const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
3202
- // ZodStringFormat.init(inst, def);
3203
- $ZodBase64.init(inst, def);
3204
- ZodStringFormat.init(inst, def);
3205
- });
3206
- const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
3207
- // ZodStringFormat.init(inst, def);
3208
- $ZodBase64URL.init(inst, def);
3209
- ZodStringFormat.init(inst, def);
3210
- });
3211
- const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
3212
- // ZodStringFormat.init(inst, def);
3213
- $ZodE164.init(inst, def);
3214
- ZodStringFormat.init(inst, def);
3215
- });
3216
- const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
3217
- // ZodStringFormat.init(inst, def);
3218
- $ZodJWT.init(inst, def);
3219
- ZodStringFormat.init(inst, def);
3220
- });
3221
- const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
3222
- $ZodNumber.init(inst, def);
3223
- ZodType.init(inst, def);
3224
- inst.gt = (value, params) => inst.check(_gt(value, params));
3225
- inst.gte = (value, params) => inst.check(_gte(value, params));
3226
- inst.min = (value, params) => inst.check(_gte(value, params));
3227
- inst.lt = (value, params) => inst.check(_lt(value, params));
3228
- inst.lte = (value, params) => inst.check(_lte(value, params));
3229
- inst.max = (value, params) => inst.check(_lte(value, params));
3230
- inst.int = (params) => inst.check(int(params));
3231
- inst.safe = (params) => inst.check(int(params));
3232
- inst.positive = (params) => inst.check(_gt(0, params));
3233
- inst.nonnegative = (params) => inst.check(_gte(0, params));
3234
- inst.negative = (params) => inst.check(_lt(0, params));
3235
- inst.nonpositive = (params) => inst.check(_lte(0, params));
3236
- inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
3237
- inst.step = (value, params) => inst.check(_multipleOf(value, params));
3238
- // inst.finite = (params) => inst.check(core.finite(params));
3239
- inst.finite = () => inst;
3240
- const bag = inst._zod.bag;
3241
- inst.minValue =
3242
- Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
3243
- inst.maxValue =
3244
- Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
3245
- inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
3246
- inst.isFinite = true;
3247
- inst.format = bag.format ?? null;
3248
- });
3249
- function number(params) {
3250
- return _number(ZodNumber, params);
3251
- }
3252
- const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
3253
- $ZodNumberFormat.init(inst, def);
3254
- ZodNumber.init(inst, def);
3255
- });
3256
- function int(params) {
3257
- return _int(ZodNumberFormat, params);
3258
- }
3259
- const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
3260
- $ZodBoolean.init(inst, def);
3261
- ZodType.init(inst, def);
3262
- });
3263
- function boolean(params) {
3264
- return _boolean(ZodBoolean, params);
3265
- }
3266
- const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => {
3267
- $ZodAny.init(inst, def);
3268
- ZodType.init(inst, def);
3269
- });
3270
- function any() {
3271
- return _any(ZodAny);
3272
- }
3273
- const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
3274
- $ZodUnknown.init(inst, def);
3275
- ZodType.init(inst, def);
3276
- });
3277
- function unknown() {
3278
- return _unknown(ZodUnknown);
3279
- }
3280
- const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
3281
- $ZodNever.init(inst, def);
3282
- ZodType.init(inst, def);
3283
- });
3284
- function never(params) {
3285
- return _never(ZodNever, params);
3286
- }
3287
- const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
3288
- $ZodArray.init(inst, def);
3289
- ZodType.init(inst, def);
3290
- inst.element = def.element;
3291
- inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
3292
- inst.nonempty = (params) => inst.check(_minLength(1, params));
3293
- inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
3294
- inst.length = (len, params) => inst.check(_length(len, params));
3295
- inst.unwrap = () => inst.element;
3296
- });
3297
- function array(element, params) {
3298
- return _array(ZodArray, element, params);
3299
- }
3300
- const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
3301
- $ZodObject.init(inst, def);
3302
- ZodType.init(inst, def);
3303
- defineLazy(inst, "shape", () => def.shape);
3304
- inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
3305
- inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
3306
- inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
3307
- inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
3308
- inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
3309
- inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined });
3310
- inst.extend = (incoming) => {
3311
- return extend(inst, incoming);
3312
- };
3313
- inst.merge = (other) => merge(inst, other);
3314
- inst.pick = (mask) => pick$1(inst, mask);
3315
- inst.omit = (mask) => omit(inst, mask);
3316
- inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
3317
- inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
3318
- });
3319
- function object(shape, params) {
3320
- const def = {
3321
- type: "object",
3322
- get shape() {
3323
- assignProp(this, "shape", shape ? objectClone(shape) : {});
3324
- return this.shape;
3325
- },
3326
- ...normalizeParams(params),
3327
- };
3328
- return new ZodObject(def);
3329
- }
3330
- const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
3331
- $ZodUnion.init(inst, def);
3332
- ZodType.init(inst, def);
3333
- inst.options = def.options;
3334
- });
3335
- function union(options, params) {
3336
- return new ZodUnion({
3337
- type: "union",
3338
- options: options,
3339
- ...normalizeParams(params),
3340
- });
3341
- }
3342
- const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
3343
- $ZodIntersection.init(inst, def);
3344
- ZodType.init(inst, def);
3345
- });
3346
- function intersection(left, right) {
3347
- return new ZodIntersection({
3348
- type: "intersection",
3349
- left: left,
3350
- right: right,
3351
- });
3352
- }
3353
- const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
3354
- $ZodEnum.init(inst, def);
3355
- ZodType.init(inst, def);
3356
- inst.enum = def.entries;
3357
- inst.options = Object.values(def.entries);
3358
- const keys = new Set(Object.keys(def.entries));
3359
- inst.extract = (values, params) => {
3360
- const newEntries = {};
3361
- for (const value of values) {
3362
- if (keys.has(value)) {
3363
- newEntries[value] = def.entries[value];
3364
- }
3365
- else
3366
- throw new Error(`Key ${value} not found in enum`);
3367
- }
3368
- return new ZodEnum({
3369
- ...def,
3370
- checks: [],
3371
- ...normalizeParams(params),
3372
- entries: newEntries,
3373
- });
3374
- };
3375
- inst.exclude = (values, params) => {
3376
- const newEntries = { ...def.entries };
3377
- for (const value of values) {
3378
- if (keys.has(value)) {
3379
- delete newEntries[value];
3380
- }
3381
- else
3382
- throw new Error(`Key ${value} not found in enum`);
3383
- }
3384
- return new ZodEnum({
3385
- ...def,
3386
- checks: [],
3387
- ...normalizeParams(params),
3388
- entries: newEntries,
3389
- });
3390
- };
3391
- });
3392
- function _enum(values, params) {
3393
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
3394
- return new ZodEnum({
3395
- type: "enum",
3396
- entries,
3397
- ...normalizeParams(params),
3398
- });
3399
- }
3400
- const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
3401
- $ZodTransform.init(inst, def);
3402
- ZodType.init(inst, def);
3403
- inst._zod.parse = (payload, _ctx) => {
3404
- payload.addIssue = (issue$1) => {
3405
- if (typeof issue$1 === "string") {
3406
- payload.issues.push(issue(issue$1, payload.value, def));
3407
- }
3408
- else {
3409
- // for Zod 3 backwards compatibility
3410
- const _issue = issue$1;
3411
- if (_issue.fatal)
3412
- _issue.continue = false;
3413
- _issue.code ?? (_issue.code = "custom");
3414
- _issue.input ?? (_issue.input = payload.value);
3415
- _issue.inst ?? (_issue.inst = inst);
3416
- // _issue.continue ??= true;
3417
- payload.issues.push(issue(_issue));
3418
- }
3419
- };
3420
- const output = def.transform(payload.value, payload);
3421
- if (output instanceof Promise) {
3422
- return output.then((output) => {
3423
- payload.value = output;
3424
- return payload;
3425
- });
3426
- }
3427
- payload.value = output;
3428
- return payload;
3429
- };
3430
- });
3431
- function transform(fn) {
3432
- return new ZodTransform({
3433
- type: "transform",
3434
- transform: fn,
3435
- });
3436
- }
3437
- const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
3438
- $ZodOptional.init(inst, def);
3439
- ZodType.init(inst, def);
3440
- inst.unwrap = () => inst._zod.def.innerType;
3441
- });
3442
- function optional(innerType) {
3443
- return new ZodOptional({
3444
- type: "optional",
3445
- innerType: innerType,
3446
- });
3447
- }
3448
- const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
3449
- $ZodNullable.init(inst, def);
3450
- ZodType.init(inst, def);
3451
- inst.unwrap = () => inst._zod.def.innerType;
3452
- });
3453
- function nullable(innerType) {
3454
- return new ZodNullable({
3455
- type: "nullable",
3456
- innerType: innerType,
3457
- });
3458
- }
3459
- const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
3460
- $ZodDefault.init(inst, def);
3461
- ZodType.init(inst, def);
3462
- inst.unwrap = () => inst._zod.def.innerType;
3463
- inst.removeDefault = inst.unwrap;
3464
- });
3465
- function _default(innerType, defaultValue) {
3466
- return new ZodDefault({
3467
- type: "default",
3468
- innerType: innerType,
3469
- get defaultValue() {
3470
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3471
- },
3472
- });
3473
- }
3474
- const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
3475
- $ZodPrefault.init(inst, def);
3476
- ZodType.init(inst, def);
3477
- inst.unwrap = () => inst._zod.def.innerType;
3478
- });
3479
- function prefault(innerType, defaultValue) {
3480
- return new ZodPrefault({
3481
- type: "prefault",
3482
- innerType: innerType,
3483
- get defaultValue() {
3484
- return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
3485
- },
3486
- });
3487
- }
3488
- const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
3489
- $ZodNonOptional.init(inst, def);
3490
- ZodType.init(inst, def);
3491
- inst.unwrap = () => inst._zod.def.innerType;
3492
- });
3493
- function nonoptional(innerType, params) {
3494
- return new ZodNonOptional({
3495
- type: "nonoptional",
3496
- innerType: innerType,
3497
- ...normalizeParams(params),
3498
- });
3499
- }
3500
- const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
3501
- $ZodCatch.init(inst, def);
3502
- ZodType.init(inst, def);
3503
- inst.unwrap = () => inst._zod.def.innerType;
3504
- inst.removeCatch = inst.unwrap;
3505
- });
3506
- function _catch(innerType, catchValue) {
3507
- return new ZodCatch({
3508
- type: "catch",
3509
- innerType: innerType,
3510
- catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue),
3511
- });
3512
- }
3513
- const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
3514
- $ZodPipe.init(inst, def);
3515
- ZodType.init(inst, def);
3516
- inst.in = def.in;
3517
- inst.out = def.out;
3518
- });
3519
- function pipe(in_, out) {
3520
- return new ZodPipe({
3521
- type: "pipe",
3522
- in: in_,
3523
- out: out,
3524
- // ...util.normalizeParams(params),
3525
- });
3526
- }
3527
- const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
3528
- $ZodReadonly.init(inst, def);
3529
- ZodType.init(inst, def);
3530
- inst.unwrap = () => inst._zod.def.innerType;
3531
- });
3532
- function readonly(innerType) {
3533
- return new ZodReadonly({
3534
- type: "readonly",
3535
- innerType: innerType,
3536
- });
3537
- }
3538
- const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
3539
- $ZodCustom.init(inst, def);
3540
- ZodType.init(inst, def);
3541
- });
3542
- function refine(fn, _params = {}) {
3543
- return _refine(ZodCustom, fn, _params);
3544
- }
3545
- // superRefine
3546
- function superRefine(fn) {
3547
- return _superRefine(fn);
3548
- }
3549
-
3550
- const schemaFormRule = (rule) => {
3551
- switch (rule.type) {
3552
- case 'string':
3553
- let stringSchema = string();
3554
- if (rule.min)
3555
- stringSchema = stringSchema.min(rule.min, `String must be at least ${rule.min} characters long.`);
3556
- if (rule.max)
3557
- stringSchema = stringSchema.max(rule.max, `String must not exceed ${rule.max} characters.`);
3558
- if (rule.regex)
3559
- stringSchema = stringSchema.regex(new RegExp(rule.regex), 'Invalid format');
3560
- return stringSchema;
3561
- case 'number':
3562
- let numberSchema = number();
3563
- if (rule.min)
3564
- numberSchema = numberSchema.min(rule.min, `Number must be at least ${rule.min}.`);
3565
- if (rule.max)
3566
- numberSchema = numberSchema.max(rule.max, `Number must not exceed ${rule.max}.`);
3567
- return numberSchema;
3568
- case 'boolean':
3569
- return boolean();
3570
- case 'array':
3571
- return array(createSchema(rule.items));
3572
- case 'object':
3573
- return object(Object.fromEntries(Object.entries(rule.properties).map(([key, value]) => [key, createSchema(value)])));
3574
- case 'any':
3575
- return any();
3576
- default:
3577
- throw new Error(`Unknown rule type: ${rule?.type}`);
3578
- }
3579
- };
3580
- const createSchema = (rule) => {
3581
- try {
3582
- rule.required = rule.required ?? false;
3583
- if (!rule.required) {
3584
- // nullable is null
3585
- // nullish is null or undefined
3586
- // optional is undefined
3587
- return schemaFormRule(rule).optional();
3588
- }
3589
- return schemaFormRule(rule);
3590
- }
3591
- catch (e) {
3592
- if (e instanceof ZodError) {
3593
- console.error(e.format());
3594
- }
3595
- throw e;
3596
- }
3597
- };
3598
-
3599
- function pick(obj, keys) {
3600
- const result = {};
3601
- keys.forEach((key) => {
3602
- if (key in obj) {
3603
- result[key] = obj[key];
3604
- }
3605
- });
3606
- return result;
3607
- }
3608
-
3609
- const pickValue = ['path', 'key', 'id', 'description', 'type', 'validator', 'middleware'];
3610
- class Route {
3611
- /**
3612
- * 一级路径
3613
- */
3614
- path;
3615
- /**
3616
- * 二级路径
3617
- */
3618
- key;
3619
- id;
3620
- share = false;
3621
- run;
3622
- nextRoute; // route to run after this route
3623
- description;
3624
- metadata;
3625
- middleware; // middleware
3626
- type = 'route';
3627
- _validator;
3628
- schema;
3629
- data;
3630
- /**
3631
- * 是否需要验证
3632
- */
3633
- isVerify;
3634
- /**
3635
- * 是否开启debug,开启后会打印错误信息
3636
- */
3637
- isDebug;
3638
- constructor(path, key = '', opts) {
3639
- path = path.trim();
3640
- key = key.trim();
3641
- this.path = path;
3642
- this.key = key;
3643
- if (opts) {
3644
- this.id = opts.id || nanoid$1();
3645
- if (!opts.id && opts.idUsePath) {
3646
- const delimiter = opts.delimiter ?? '$#$';
3647
- this.id = path + delimiter + key;
3648
- }
3649
- this.run = opts.run;
3650
- this.nextRoute = opts.nextRoute;
3651
- this.description = opts.description;
3652
- this.metadata = opts.metadata;
3653
- this.type = opts.type || 'route';
3654
- this.validator = opts.validator;
3655
- this.middleware = opts.middleware || [];
3656
- this.key = opts.key || key;
3657
- this.path = opts.path || path;
3658
- this.isVerify = opts.isVerify ?? true;
3659
- this.createSchema();
3660
- }
3661
- else {
3662
- this.isVerify = true;
3663
- this.middleware = [];
3664
- this.id = nanoid$1();
3665
- }
3666
- this.isDebug = opts?.isDebug ?? false;
3667
- }
3668
- createSchema() {
3669
- try {
3670
- const validator = this.validator;
3671
- const keys = Object.keys(validator || {});
3672
- const schemaList = keys.map((key) => {
3673
- return { [key]: createSchema(validator[key]) };
3674
- });
3675
- const schema = schemaList.reduce((prev, current) => {
3676
- return { ...prev, ...current };
3677
- }, {});
3678
- this.schema = schema;
3679
- }
3680
- catch (e) {
3681
- console.error('createSchema error:', e);
3682
- }
3683
- }
3684
- /**
3685
- * set validator and create schema
3686
- * @param validator
3687
- */
3688
- set validator(validator) {
3689
- this._validator = validator;
3690
- this.createSchema();
3691
- }
3692
- get validator() {
3693
- return this._validator || {};
3694
- }
3695
- /**
3696
- * has code, body, message in ctx, return ctx if has error
3697
- * @param ctx
3698
- * @param dev
3699
- * @returns
3700
- */
3701
- verify(ctx, dev = false) {
3702
- const query = ctx.query || {};
3703
- const schema = this.schema || {};
3704
- const validator = this.validator;
3705
- const check = () => {
3706
- const queryKeys = Object.keys(validator);
3707
- for (let i = 0; i < queryKeys.length; i++) {
3708
- const key = queryKeys[i];
3709
- const value = query[key];
3710
- if (schema[key]) {
3711
- const result = schema[key].safeParse(value);
3712
- if (!result.success) {
3713
- // TODO:
3714
- const message = 'safe error, TODO:';
3715
- throw new CustomError(500, message);
3716
- }
3717
- }
3718
- }
3719
- };
3720
- check();
3721
- }
3722
- /**
3723
- * Need to manully call return ctx fn and configure body, code, message
3724
- * @param key
3725
- * @param ctx
3726
- * @param dev
3727
- * @returns
3728
- */
3729
- verifyKey(key, ctx, dev = false) {
3730
- const query = ctx.query || {};
3731
- const schema = this.schema || {};
3732
- const validator = this.validator;
3733
- const check = () => {
3734
- const value = query[key];
3735
- if (schema[key]) {
3736
- try {
3737
- schema[key].parse(value);
3738
- }
3739
- catch (e) {
3740
- if (dev) {
3741
- return {
3742
- message: validator[key].message || 'Invalid params',
3743
- path: this.path,
3744
- key: this.key,
3745
- error: e.message.toString(),
3746
- };
3747
- }
3748
- return {
3749
- message: validator[key].message || 'Invalid params',
3750
- path: this.path,
3751
- key: this.key,
3752
- };
3753
- }
3754
- }
3755
- };
3756
- const checkRes = check();
3757
- return checkRes;
3758
- }
3759
- setValidator(validator) {
3760
- this.validator = validator;
3761
- return this;
3762
- }
3763
- define(...args) {
3764
- const [path, key, opts] = args;
3765
- // 全覆盖,所以opts需要准确,不能由idUsePath 需要check的变量
3766
- const setOpts = (opts) => {
3767
- const keys = Object.keys(opts);
3768
- const checkList = ['path', 'key', 'run', 'nextRoute', 'description', 'metadata', 'middleware', 'type', 'validator', 'isVerify', 'isDebug'];
3769
- for (let item of keys) {
3770
- if (!checkList.includes(item)) {
3771
- continue;
3772
- }
3773
- if (item === 'validator') {
3774
- this.validator = opts[item];
3775
- continue;
3776
- }
3777
- if (item === 'middleware') {
3778
- this.middleware = this.middleware.concat(opts[item]);
3779
- continue;
3780
- }
3781
- this[item] = opts[item];
3782
- }
3783
- };
3784
- if (typeof path === 'object') {
3785
- setOpts(path);
3786
- return this;
3787
- }
3788
- if (typeof path === 'function') {
3789
- this.run = path;
3790
- return this;
3791
- }
3792
- if (typeof path === 'string' && typeof key === 'function') {
3793
- setOpts({ path, run: key });
3794
- return this;
3795
- }
3796
- if (typeof path === 'string' && typeof key === 'string' && typeof opts === 'function') {
3797
- setOpts({ path, key, run: opts });
3798
- return this;
3799
- }
3800
- return this;
3801
- }
3802
- addTo(router) {
3803
- router.add(this);
3804
- }
3805
- setData(data) {
3806
- this.data = data;
3807
- return this;
3808
- }
3809
- throw(...args) {
3810
- throw new CustomError(...args);
3811
- }
3812
- }
3813
- class QueryRouter {
3814
- routes;
3815
- maxNextRoute = 40;
3816
- context = {}; // default context for call
3817
- constructor() {
3818
- this.routes = [];
3819
- }
3820
- add(route) {
3821
- const has = this.routes.find((r) => r.path === route.path && r.key === route.key);
3822
- if (has) {
3823
- // remove the old route
3824
- this.routes = this.routes.filter((r) => r.id !== has.id);
3825
- }
3826
- this.routes.push(route);
3827
- }
3828
- /**
3829
- * remove route by path and key
3830
- * @param route
3831
- */
3832
- remove(route) {
3833
- this.routes = this.routes.filter((r) => r.path === route.path && r.key == route.key);
3834
- }
3835
- /**
3836
- * remove route by id
3837
- * @param uniqueId
3838
- */
3839
- removeById(unique) {
3840
- this.routes = this.routes.filter((r) => r.id !== unique);
3841
- }
3842
- /**
3843
- * 执行route
3844
- * @param path
3845
- * @param key
3846
- * @param ctx
3847
- * @returns
3848
- */
3849
- async runRoute(path, key, ctx) {
3850
- const route = this.routes.find((r) => r.path === path && r.key === key);
3851
- const maxNextRoute = this.maxNextRoute;
3852
- ctx = (ctx || {});
3853
- ctx.currentPath = path;
3854
- ctx.currentKey = key;
3855
- ctx.currentRoute = route;
3856
- ctx.index = (ctx.index || 0) + 1;
3857
- const progress = [path, key];
3858
- if (ctx.progress) {
3859
- ctx.progress.push(progress);
3860
- }
3861
- else {
3862
- ctx.progress = [progress];
3863
- }
3864
- if (ctx.index > maxNextRoute) {
3865
- ctx.code = 500;
3866
- ctx.message = 'Too many nextRoute';
3867
- ctx.body = null;
3868
- return;
3869
- }
3870
- // run middleware
3871
- if (route && route.middleware && route.middleware.length > 0) {
3872
- const errorMiddleware = [];
3873
- const getMiddleware = (m) => {
3874
- if (!m.middleware || m.middleware.length === 0)
3875
- return [];
3876
- const routeMiddleware = [];
3877
- for (let i = 0; i < m.middleware.length; i++) {
3878
- const item = m.middleware[i];
3879
- let route;
3880
- const isString = typeof item === 'string';
3881
- if (isString) {
3882
- route = this.routes.find((r) => r.id === item);
3883
- }
3884
- else {
3885
- route = this.routes.find((r) => {
3886
- if (item.id) {
3887
- return r.id === item.id;
3888
- }
3889
- else {
3890
- // key 可以是空,所以可以不严格验证
3891
- return r.path === item.path && r.key == item.key;
3892
- }
3893
- });
3894
- }
3895
- if (!route) {
3896
- if (isString) {
3897
- errorMiddleware.push({
3898
- id: item,
3899
- });
3900
- }
3901
- else
3902
- errorMiddleware.push({
3903
- path: m?.path,
3904
- key: m?.key,
3905
- });
3906
- }
3907
- const routeMiddlewarePrevious = getMiddleware(route);
3908
- if (routeMiddlewarePrevious.length > 0) {
3909
- routeMiddleware.push(...routeMiddlewarePrevious);
3910
- }
3911
- routeMiddleware.push(route);
3912
- }
3913
- return routeMiddleware;
3914
- };
3915
- const routeMiddleware = getMiddleware(route);
3916
- if (errorMiddleware.length > 0) {
3917
- console.error('middleware not found');
3918
- ctx.body = errorMiddleware;
3919
- ctx.message = 'middleware not found';
3920
- ctx.code = 404;
3921
- return ctx;
3922
- }
3923
- for (let i = 0; i < routeMiddleware.length; i++) {
3924
- const middleware = routeMiddleware[i];
3925
- if (middleware) {
3926
- if (middleware?.isVerify) {
3927
- try {
3928
- middleware.verify(ctx);
3929
- }
3930
- catch (e) {
3931
- if (middleware?.isDebug) {
3932
- console.error('=====debug====:', 'middleware verify error:', e.message);
3933
- }
3934
- ctx.message = e.message;
3935
- ctx.code = 500;
3936
- ctx.body = null;
3937
- return ctx;
3938
- }
3939
- }
3940
- try {
3941
- await middleware.run(ctx);
3942
- }
3943
- catch (e) {
3944
- if (route?.isDebug) {
3945
- console.error('=====debug====:middlerware error');
3946
- console.error('=====debug====:', e);
3947
- console.error('=====debug====:[path:key]:', `${route.path}-${route.key}`);
3948
- console.error('=====debug====:', e.message);
3949
- }
3950
- if (e instanceof CustomError || e?.code) {
3951
- ctx.code = e.code;
3952
- ctx.message = e.message;
3953
- ctx.body = null;
3954
- }
3955
- else {
3956
- console.error(`fn:${route.path}-${route.key}:${route.id}`);
3957
- console.error(`middleware:${middleware.path}-${middleware.key}:${middleware.id}`);
3958
- ctx.code = 500;
3959
- ctx.message = 'Internal Server Error';
3960
- ctx.body = null;
3961
- }
3962
- return ctx;
3963
- }
3964
- if (ctx.end) ;
3965
- }
3966
- }
3967
- }
3968
- // run route
3969
- if (route) {
3970
- if (route.run) {
3971
- if (route?.isVerify) {
3972
- try {
3973
- route.verify(ctx);
3974
- }
3975
- catch (e) {
3976
- if (route?.isDebug) {
3977
- console.error('=====debug====:', 'verify error:', e.message);
3978
- }
3979
- ctx.message = e.message;
3980
- ctx.code = 500;
3981
- ctx.body = null;
3982
- return ctx;
3983
- }
3984
- }
3985
- try {
3986
- await route.run(ctx);
3987
- }
3988
- catch (e) {
3989
- if (route?.isDebug) {
3990
- console.error('=====debug====:', 'router run error:', e.message);
3991
- }
3992
- if (e instanceof CustomError) {
3993
- ctx.code = e.code;
3994
- ctx.message = e.message;
3995
- }
3996
- else {
3997
- console.error(`[error]fn:${route.path}-${route.key}:${route.id}`);
3998
- console.error('error', e.message);
3999
- ctx.code = 500;
4000
- ctx.message = 'Internal Server Error';
4001
- }
4002
- ctx.body = null;
4003
- return ctx;
4004
- }
4005
- if (ctx.end) {
4006
- // TODO: 提前结束, 以及错误情况
4007
- return;
4008
- }
4009
- if (route.nextRoute) {
4010
- let path, key;
4011
- if (route.nextRoute.path || route.nextRoute.key) {
4012
- path = route.nextRoute.path;
4013
- key = route.nextRoute.key;
4014
- }
4015
- else if (route.nextRoute.id) {
4016
- const nextRoute = this.routes.find((r) => r.id === route.nextRoute.id);
4017
- if (nextRoute) {
4018
- path = nextRoute.path;
4019
- key = nextRoute.key;
4020
- }
4021
- }
4022
- if (!path || !key) {
4023
- ctx.message = 'nextRoute not found';
4024
- ctx.code = 404;
4025
- ctx.body = null;
4026
- return ctx;
4027
- }
4028
- ctx.query = { ...ctx.query, ...ctx.nextQuery };
4029
- ctx.nextQuery = {};
4030
- return await this.runRoute(path, key, ctx);
4031
- }
4032
- if (!ctx.code)
4033
- ctx.code = 200;
4034
- return ctx;
4035
- }
4036
- else {
4037
- // return Promise.resolve({ code: 404, body: 'Not found runing' });
4038
- // 可以不需要run的route,因为不一定是错误
4039
- return ctx;
4040
- }
4041
- }
4042
- // 如果没有找到route,返回404,这是因为出现了错误
4043
- return Promise.resolve({ code: 404, body: 'Not found' });
4044
- }
4045
- /**
4046
- * 第一次执行
4047
- * @param message
4048
- * @param ctx
4049
- * @returns
4050
- */
4051
- async parse(message, ctx) {
4052
- if (!message?.path) {
4053
- return Promise.resolve({ code: 404, body: null, message: 'Not found path' });
4054
- }
4055
- const { path, key = '', payload = {}, ...query } = message;
4056
- ctx = ctx || {};
4057
- ctx.query = { ...ctx.query, ...query, ...payload };
4058
- ctx.state = { ...ctx?.state };
4059
- ctx.throw = this.throw;
4060
- // put queryRouter to ctx
4061
- // TODO: 是否需要queryRouter,函数内部处理router路由执行,这应该是避免去内部去包含的功能过
4062
- ctx.queryRouter = this;
4063
- ctx.call = this.call.bind(this);
4064
- ctx.queryRoute = this.queryRoute.bind(this);
4065
- ctx.index = 0;
4066
- ctx.progress = ctx.progress || [];
4067
- const res = await this.runRoute(path, key, ctx);
4068
- const serialize = ctx.needSerialize ?? true; // 是否需要序列化
4069
- if (serialize) {
4070
- res.body = JSON.parse(JSON.stringify(res.body || ''));
4071
- }
4072
- return res;
4073
- }
4074
- /**
4075
- * 返回的数据包含所有的context的请求返回的内容,可做其他处理
4076
- * @param message
4077
- * @param ctx
4078
- * @returns
4079
- */
4080
- async call(message, ctx) {
4081
- let path = message.path;
4082
- message.key;
4083
- if (message.id) {
4084
- const route = this.routes.find((r) => r.id === message.id);
4085
- if (route) {
4086
- path = route.path;
4087
- route.key;
4088
- }
4089
- else {
4090
- return { code: 404, body: null, message: 'Not found route' };
4091
- }
4092
- }
4093
- else if (path) {
4094
- return await this.parse({ ...message, path }, { ...this.context, ...ctx });
4095
- }
4096
- else {
4097
- return { code: 404, body: null, message: 'Not found path' };
4098
- }
4099
- }
4100
- /**
4101
- * 请求 result 的数据
4102
- * @param message
4103
- * @param ctx
4104
- * @returns
4105
- */
4106
- async queryRoute(message, ctx) {
4107
- const res = await this.parse(message, { ...this.context, ...ctx });
4108
- return {
4109
- code: res.code,
4110
- data: res.body,
4111
- message: res.message,
4112
- };
4113
- }
4114
- /**
4115
- * 设置上下文
4116
- * @description 这里的上下文是为了在handle函数中使用
4117
- * @param ctx
4118
- */
4119
- setContext(ctx) {
4120
- this.context = ctx;
4121
- }
4122
- getList() {
4123
- return this.routes.map((r) => {
4124
- return pick(r, pickValue);
4125
- });
4126
- }
4127
- /**
4128
- * 获取handle函数, 这里会去执行parse函数
4129
- */
4130
- getHandle(router, wrapperFn, ctx) {
4131
- return async (msg, handleContext) => {
4132
- try {
4133
- const context = { ...ctx, ...handleContext };
4134
- const res = await router.parse(msg, context);
4135
- if (wrapperFn) {
4136
- res.data = res.body;
4137
- return wrapperFn(res, context);
4138
- }
4139
- const { code, body, message } = res;
4140
- return { code, data: body, message };
4141
- }
4142
- catch (e) {
4143
- return { code: 500, message: e.message };
4144
- }
4145
- };
4146
- }
4147
- exportRoutes() {
4148
- return this.routes.map((r) => {
4149
- return r;
4150
- });
4151
- }
4152
- importRoutes(routes) {
4153
- for (let route of routes) {
4154
- this.add(route);
4155
- }
4156
- }
4157
- importRouter(router) {
4158
- this.importRoutes(router.routes);
4159
- }
4160
- throw(...args) {
4161
- throw new CustomError(...args);
4162
- }
4163
- hasRoute(path, key = '') {
4164
- return this.routes.find((r) => r.path === path && r.key === key);
4165
- }
4166
- }
4167
- /**
4168
- * QueryRouterServer
4169
- * @description 移除server相关的功能,只保留router相关的功能,和http.createServer不相关,独立
4170
- */
4171
- class QueryRouterServer extends QueryRouter {
4172
- handle;
4173
- constructor(opts) {
4174
- super();
4175
- this.handle = this.getHandle(this, opts?.handleFn, opts?.context);
4176
- this.setContext({ needSerialize: false, ...opts?.context });
4177
- }
4178
- setHandle(wrapperFn, ctx) {
4179
- this.handle = this.getHandle(this, wrapperFn, ctx);
4180
- }
4181
- use(path, fn, opts) {
4182
- const route = new Route(path, '', opts);
4183
- route.run = fn;
4184
- this.add(route);
4185
- }
4186
- addRoute(route) {
4187
- this.add(route);
4188
- }
4189
- Route = Route;
4190
- route(...args) {
4191
- const [path, key, opts] = args;
4192
- if (typeof path === 'object') {
4193
- return new Route(path.path, path.key, path);
4194
- }
4195
- if (typeof path === 'string') {
4196
- if (opts) {
4197
- return new Route(path, key, opts);
4198
- }
4199
- if (key && typeof key === 'object') {
4200
- return new Route(path, key?.key || '', key);
4201
- }
4202
- return new Route(path, key);
4203
- }
4204
- return new Route(path, key, opts);
4205
- }
4206
- /**
4207
- * 等于queryRoute,但是调用了handle
4208
- * @param param0
4209
- * @returns
4210
- */
4211
- async run({ path, key, payload }) {
4212
- const handle = this.handle;
4213
- const resultError = (error, code = 500) => {
4214
- const r = {
4215
- code: code,
4216
- message: error,
4217
- };
4218
- return r;
4219
- };
4220
- try {
4221
- const end = handle({ path, key, ...payload });
4222
- return end;
4223
- }
4224
- catch (e) {
4225
- if (e.code && typeof e.code === 'number') {
4226
- return {
4227
- code: e.code,
4228
- message: e.message,
4229
- };
4230
- }
4231
- else {
4232
- return resultError('Router Server error');
4233
- }
4234
- }
4235
- }
4236
- }
4237
-
4238
- const getPid = async () => {
4239
- const runtime = getRuntime();
4240
- let pid = 0;
4241
- if (runtime.isDeno) {
4242
- // @ts-ignore
4243
- pid = Deno.pid;
4244
- }
4245
- else {
4246
- pid = process.pid;
4247
- }
4248
- return pid;
4249
- };
4250
- const writeAppid = async (pidPath = './app.pid') => {
4251
- const fs = await import('node:fs');
4252
- const pid = await getPid();
4253
- fs.writeFileSync(pidPath, pid + '');
4254
- };
4255
- const getPidFromFileAndStop = async () => {
4256
- const fs = await import('node:fs');
4257
- if (fs.existsSync('./app.pid')) {
4258
- const pid = parseInt(fs.readFileSync('./app.pid', 'utf-8'), 10);
4259
- if (!isNaN(pid)) {
4260
- if (pid === 0) {
4261
- return;
4262
- }
4263
- try {
4264
- process.kill(pid);
4265
- console.log(`Stopped process with PID ${pid}`);
4266
- }
4267
- catch (error) {
4268
- console.error(`Failed to stop process with PID ${pid}:`);
4269
- }
4270
- }
4271
- }
4272
- };
4273
- const runFirstCheck = async (path, pidPath) => {
4274
- await getPidFromFileAndStop();
4275
- await writeAppid(pidPath);
4276
- try {
4277
- const fs = await import('node:fs');
4278
- if (fs.existsSync(path)) {
4279
- fs.unlinkSync(path);
4280
- console.log(`Socket file ${path} cleaned up during first check`);
4281
- }
4282
- }
4283
- catch (error) {
4284
- console.error(`Failed to clean up socket file ${path} during first check:`, error);
4285
- }
4286
- };
4287
-
4288
- let isClean = false;
4289
- const deleteFileDetached = async (path, pidPath = './app.pid') => {
4290
- const runtime = getRuntime();
4291
- if (runtime.isDeno) {
4292
- // Deno 实现 - 启动后不等待结果
4293
- const process = new Deno.Command('sh', {
4294
- args: ['-c', `rm -f "${path}" & rm -f "${pidPath}"`],
4295
- stdout: 'null',
4296
- stderr: 'null',
4297
- });
4298
- process.spawn(); // 不等待结果
4299
- console.log(`[DEBUG] Fire-and-forget delete initiated for ${path}`);
4300
- return;
4301
- }
4302
- const { spawn } = await import('node:child_process');
4303
- const child = spawn('sh', ['-c', `rm -f "${path}" & rm -f "${pidPath}"`], {
4304
- detached: true,
4305
- stdio: 'ignore',
4306
- });
4307
- child.unref(); // 完全分离
4308
- console.log(`[DEBUG] Fire-and-forget delete initiated for ${path}`);
4309
- };
4310
- const cleanup = async ({ path, close = async () => { }, pidPath = './app.pid' }) => {
4311
- const runtime = getRuntime();
4312
- // 检查文件是否存在并删除
4313
- const cleanupFile = async () => {
4314
- if (isClean)
4315
- return;
4316
- isClean = true;
4317
- if (runtime.isDeno) {
4318
- await deleteFileDetached(path, pidPath);
4319
- }
4320
- await close();
4321
- if (!runtime.isDeno) {
4322
- await deleteFileDetached(path, pidPath);
4323
- }
4324
- };
4325
- // 根据运行时环境注册不同的退出监听器
4326
- if (runtime.isDeno) {
4327
- // Deno 环境
4328
- const handleSignal = () => {
4329
- cleanupFile();
4330
- Deno.exit(0);
4331
- };
4332
- try {
4333
- Deno.addSignalListener('SIGINT', handleSignal);
4334
- Deno.addSignalListener('SIGTERM', handleSignal);
4335
- }
4336
- catch (error) {
4337
- console.warn('[DEBUG] Failed to add signal listeners:', error);
4338
- }
4339
- // 对于 beforeunload 和 unload,使用异步清理
4340
- const handleUnload = () => {
4341
- cleanupFile();
4342
- };
4343
- globalThis.addEventListener('beforeunload', handleUnload);
4344
- globalThis.addEventListener('unload', handleUnload);
4345
- }
4346
- else if (runtime.isNode || runtime.isBun) {
4347
- // Node.js 和 Bun 环境
4348
- import('process').then(({ default: process }) => {
4349
- // 信号处理使用同步清理,然后退出
4350
- const signalHandler = async (signal) => {
4351
- await cleanupFile();
4352
- process.exit(0);
4353
- };
4354
- process.on('SIGINT', () => signalHandler());
4355
- process.on('SIGTERM', () => signalHandler());
4356
- process.on('SIGUSR1', () => signalHandler());
4357
- process.on('SIGUSR2', () => signalHandler());
4358
- process.on('exit', async () => {
4359
- await cleanupFile();
4360
- });
4361
- process.on('uncaughtException', async (error) => {
4362
- console.error('Uncaught Exception:', error);
4363
- await cleanupFile();
4364
- process.exit(1);
4365
- });
4366
- process.on('unhandledRejection', async (reason, promise) => {
4367
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
4368
- await cleanupFile();
4369
- });
4370
- });
4371
- }
4372
- // 返回手动清理函数,以便需要时主动调用
4373
- return cleanupFile;
4374
- };
4375
-
4376
- class ServerTimer {
4377
- updatedAt;
4378
- timer;
4379
- timeout;
4380
- onTimeout;
4381
- interval = 10 * 1000;
4382
- constructor(opts) {
4383
- this.timeout = opts?.timeout || 15 * 60 * 1000;
4384
- this.run();
4385
- }
4386
- startTimer() {
4387
- const that = this;
4388
- if (this.timer) {
4389
- clearInterval(this.timer);
4390
- }
4391
- this.timer = setInterval(() => {
4392
- const updatedAt = Date.now();
4393
- const timeout = that.timeout;
4394
- const onTimeout = that.onTimeout;
4395
- const isExpired = updatedAt - that.updatedAt > timeout;
4396
- if (isExpired) {
4397
- onTimeout?.();
4398
- clearInterval(that.timer);
4399
- that.timer = null;
4400
- }
4401
- }, that.interval);
4402
- }
4403
- run() {
4404
- this.updatedAt = Date.now();
4405
- return this.updatedAt;
4406
- }
4407
- }
4408
-
4409
- const server = async (req, app) => {
4410
- const runtime = getRuntime();
4411
- let data;
4412
- if (!runtime.isNode) {
4413
- data = await getRequestParams(req);
4414
- }
4415
- else {
4416
- data = await parseBody(req);
4417
- }
4418
- // @ts-ignore
4419
- const serverTimer = app.serverTimer;
4420
- if (serverTimer) {
4421
- serverTimer?.run?.();
4422
- }
4423
- const result = await app.queryRoute(data);
4424
- const response = new Response(JSON.stringify(result));
4425
- response.headers.set('Content-Type', 'application/json');
4426
- return response;
4427
- };
4428
- const closeListenSocket = () => {
4429
- console.log('Closing listen socket');
4430
- process.emit('SIGINT');
4431
- };
4432
- const serverTimer = new ServerTimer();
4433
- const listenSocket = async (options) => {
4434
- const path = options?.path || './app.sock';
4435
- const pidPath = options?.pidPath || './app.pid';
4436
- const timeout = options?.timeout || 24 * 60 * 60 * 1000; // 24 hours
4437
- const runtime = getRuntime();
4438
- serverTimer.timeout = timeout;
4439
- serverTimer.startTimer();
4440
- serverTimer.onTimeout = closeListenSocket;
4441
- let app = options?.app || globalThis.context?.app;
4442
- if (!app) {
4443
- app = new QueryRouterServer();
4444
- }
4445
- app.serverTimer = serverTimer;
4446
- await runFirstCheck(path, pidPath);
4447
- let close = async () => { };
4448
- cleanup({ path, close });
4449
- if (runtime.isDeno) {
4450
- // 检查 Deno 版本是否支持 Unix domain socket
4451
- try {
4452
- // @ts-ignore
4453
- const listener = Deno.listen({
4454
- transport: 'unix',
4455
- path: path,
4456
- });
4457
- // 处理连接
4458
- (async () => {
4459
- for await (const conn of listener) {
4460
- (async () => {
4461
- // @ts-ignore
4462
- const httpConn = Deno.serveHttp(conn);
4463
- for await (const requestEvent of httpConn) {
4464
- try {
4465
- const response = await server(requestEvent.request, app);
4466
- await requestEvent.respondWith(response);
4467
- }
4468
- catch (error) {
4469
- await requestEvent.respondWith(new Response('Internal Server Error', { status: 500 }));
4470
- }
4471
- }
4472
- })();
4473
- }
4474
- })();
4475
- close = async () => {
4476
- listener.close();
4477
- };
4478
- return listener;
4479
- }
4480
- catch (error) {
4481
- // 如果 Unix socket 不支持,回退到 HTTP 服务器
4482
- console.warn('Unix socket not supported in this Deno environment, falling back to HTTP server');
4483
- // @ts-ignore
4484
- const listener = Deno.listen({ port: 0 }); // 使用随机端口
4485
- // @ts-ignore
4486
- console.log(`Deno server listening on port ${listener.addr.port}`);
4487
- (async () => {
4488
- for await (const conn of listener) {
4489
- (async () => {
4490
- // @ts-ignore
4491
- const httpConn = Deno.serveHttp(conn);
4492
- for await (const requestEvent of httpConn) {
4493
- try {
4494
- const response = await server(requestEvent.request, app);
4495
- await requestEvent.respondWith(response);
4496
- }
4497
- catch (error) {
4498
- await requestEvent.respondWith(new Response('Internal Server Error', { status: 500 }));
4499
- }
4500
- }
4501
- })();
4502
- }
4503
- })();
4504
- return listener;
4505
- }
4506
- }
4507
- if (runtime.isBun) {
4508
- // @ts-ignore
4509
- const bunServer = Bun.serve({
4510
- unix: path,
4511
- fetch(req) {
4512
- return server(req, app);
4513
- },
4514
- });
4515
- close = async () => {
4516
- await bunServer.stop();
4517
- };
4518
- return bunServer;
4519
- }
4520
- // Node.js 环境
4521
- const http = await import('node:http');
4522
- const httpServer = http.createServer(async (req, res) => {
4523
- try {
4524
- const response = await server(req, app);
4525
- // 设置响应头
4526
- response.headers.forEach((value, key) => {
4527
- res.setHeader(key, value);
4528
- });
4529
- // 设置状态码
4530
- res.statusCode = response.status;
4531
- // 读取响应体并写入
4532
- const body = await response.text();
4533
- res.end(body);
4534
- }
4535
- catch (error) {
4536
- console.error('Error handling request:', error);
4537
- res.statusCode = 500;
4538
- res.end('Internal Server Error');
4539
- }
4540
- });
4541
- httpServer.listen(path);
4542
- close = async () => {
4543
- httpServer.close();
4544
- };
4545
- return httpServer;
4546
- };
4547
- const getRequestParams = async (req) => {
4548
- let urlParams = {};
4549
- let bodyParams = {};
4550
- // 获取URL参数
4551
- const url = new URL(req.url);
4552
- for (const [key, value] of url.searchParams.entries()) {
4553
- // 尝试解析JSON payload
4554
- if (key === 'payload') {
4555
- try {
4556
- urlParams[key] = JSON.parse(value);
4557
- }
4558
- catch {
4559
- urlParams[key] = value;
4560
- }
4561
- }
4562
- else {
4563
- urlParams[key] = value;
4564
- }
4565
- }
4566
- // 获取body参数
4567
- if (req.method.toLowerCase() === 'post' && req.body) {
4568
- const contentType = req.headers.get('content-type') || '';
4569
- if (contentType.includes('application/json')) {
4570
- try {
4571
- bodyParams = await req.json();
4572
- }
4573
- catch {
4574
- // 如果解析失败,保持空对象
4575
- }
4576
- }
4577
- else if (contentType.includes('application/x-www-form-urlencoded')) {
4578
- const formData = await req.text();
4579
- const params = new URLSearchParams(formData);
4580
- for (const [key, value] of params.entries()) {
4581
- bodyParams[key] = value;
4582
- }
4583
- }
4584
- else if (contentType.includes('multipart/form-data')) {
4585
- try {
4586
- const formData = await req.formData();
4587
- for (const [key, value] of formData.entries()) {
4588
- // @ts-ignore
4589
- bodyParams[key] = value instanceof File ? value : value.toString();
4590
- }
4591
- }
4592
- catch {
4593
- // 如果解析失败,保持空对象
4594
- }
4595
- }
4596
- }
4597
- // body参数优先,合并数据
4598
- return {
4599
- ...urlParams,
4600
- ...bodyParams,
4601
- };
4602
- };
4603
- const parseBody = async (req) => {
4604
- return new Promise((resolve, reject) => {
4605
- const arr = [];
4606
- req.on('data', (chunk) => {
4607
- arr.push(chunk);
4608
- });
4609
- req.on('end', () => {
4610
- try {
4611
- const body = Buffer.concat(arr).toString();
4612
- // 获取 Content-Type 头信息
4613
- const contentType = req.headers['content-type'] || '';
4614
- // 处理 application/json
4615
- if (contentType.includes('application/json')) {
4616
- resolve(JSON.parse(body));
4617
- return;
4618
- }
4619
- // 处理 application/x-www-form-urlencoded
4620
- if (contentType.includes('application/x-www-form-urlencoded')) {
4621
- const formData = new URLSearchParams(body);
4622
- const result = {};
4623
- formData.forEach((value, key) => {
4624
- // 尝试将值解析为 JSON,如果失败则保留原始字符串
4625
- try {
4626
- result[key] = JSON.parse(value);
4627
- }
4628
- catch {
4629
- result[key] = value;
4630
- }
4631
- });
4632
- resolve(result);
4633
- return;
4634
- }
4635
- // 默认尝试 JSON 解析
4636
- try {
4637
- resolve(JSON.parse(body));
4638
- }
4639
- catch {
4640
- resolve({});
4641
- }
4642
- }
4643
- catch (e) {
4644
- resolve({});
4645
- }
4646
- });
4647
- });
4648
- };
4649
-
4650
- const callSock = async (data, options = {}) => {
4651
- const { socketPath = './app.sock', timeout = 10000, method = 'POST' } = options;
4652
- return new Promise((resolve, reject) => {
4653
- const client = createConnection(socketPath);
4654
- let responseData = '';
4655
- let timer;
4656
- // 设置超时
4657
- if (timeout > 0) {
4658
- timer = setTimeout(() => {
4659
- client.destroy();
4660
- reject(new Error(`Socket call timeout after ${timeout}ms`));
4661
- }, timeout);
4662
- }
4663
- client.on('connect', () => {
4664
- try {
4665
- let request;
4666
- if (method === 'GET') {
4667
- // GET 请求:参数放在 URL 中
4668
- const searchParams = new URLSearchParams();
4669
- Object.entries(data).forEach(([key, value]) => {
4670
- if (key === 'payload' && typeof value === 'object') {
4671
- searchParams.append(key, JSON.stringify(value));
4672
- }
4673
- else {
4674
- searchParams.append(key, String(value));
4675
- }
4676
- });
4677
- const queryString = searchParams.toString();
4678
- const url = queryString ? `/?${queryString}` : '/';
4679
- request = [`GET ${url} HTTP/1.1`, 'Host: localhost', 'Connection: close', '', ''].join('\r\n');
4680
- }
4681
- else {
4682
- // POST 请求:数据放在 body 中
4683
- const body = JSON.stringify(data);
4684
- const contentLength = Buffer.byteLength(body, 'utf8');
4685
- request = [
4686
- 'POST / HTTP/1.1',
4687
- 'Host: localhost',
4688
- 'Content-Type: application/json',
4689
- `Content-Length: ${contentLength}`,
4690
- 'Connection: close',
4691
- '',
4692
- body,
4693
- ].join('\r\n');
4694
- }
4695
- client.write(request);
4696
- }
4697
- catch (error) {
4698
- if (timer)
4699
- clearTimeout(timer);
4700
- client.destroy();
4701
- reject(error);
4702
- }
4703
- });
4704
- client.on('data', (chunk) => {
4705
- responseData += chunk.toString();
4706
- // 检查是否收到完整的HTTP响应
4707
- if (responseData.includes('\r\n\r\n')) {
4708
- const [headerSection] = responseData.split('\r\n\r\n');
4709
- const contentLengthMatch = headerSection.match(/content-length:\s*(\d+)/i);
4710
- if (contentLengthMatch) {
4711
- const expectedLength = parseInt(contentLengthMatch[1]);
4712
- const bodyStart = responseData.indexOf('\r\n\r\n') + 4;
4713
- const currentBodyLength = Buffer.byteLength(responseData.slice(bodyStart), 'utf8');
4714
- // 如果收到了完整的响应,主动关闭连接
4715
- if (currentBodyLength >= expectedLength) {
4716
- client.end();
4717
- }
4718
- }
4719
- else if (responseData.includes('\r\n0\r\n\r\n')) {
4720
- // 检查 chunked 编码结束标记
4721
- client.end();
4722
- }
4723
- }
4724
- });
4725
- client.on('end', () => {
4726
- if (timer)
4727
- clearTimeout(timer);
4728
- try {
4729
- // 解析 HTTP 响应
4730
- const response = parseHttpResponse(responseData);
4731
- if (response.statusCode >= 400) {
4732
- reject(new Error(`HTTP ${response.statusCode}: ${response.body}`));
4733
- return;
4734
- }
4735
- // 尝试解析 JSON 响应
4736
- try {
4737
- const result = JSON.parse(response.body);
4738
- resolve(result);
4739
- }
4740
- catch {
4741
- // 如果不是 JSON,直接返回文本
4742
- resolve(response.body);
4743
- }
4744
- }
4745
- catch (error) {
4746
- reject(error);
4747
- }
4748
- });
4749
- client.on('error', (error) => {
4750
- if (timer)
4751
- clearTimeout(timer);
4752
- reject(error);
4753
- });
4754
- client.on('timeout', () => {
4755
- if (timer)
4756
- clearTimeout(timer);
4757
- client.destroy();
4758
- reject(new Error('Socket connection timeout'));
4759
- });
4760
- });
4761
- };
4762
- // 解析 HTTP 响应的辅助函数
4763
- function parseHttpResponse(responseData) {
4764
- const [headerSection, ...bodyParts] = responseData.split('\r\n\r\n');
4765
- const body = bodyParts.join('\r\n\r\n');
4766
- const lines = headerSection.split('\r\n');
4767
- const statusLine = lines[0];
4768
- const statusMatch = statusLine.match(/HTTP\/\d\.\d (\d+)/);
4769
- const statusCode = statusMatch ? parseInt(statusMatch[1]) : 200;
4770
- const headers = {};
4771
- for (let i = 1; i < lines.length; i++) {
4772
- const [key, ...valueParts] = lines[i].split(':');
4773
- if (key && valueParts.length > 0) {
4774
- headers[key.trim().toLowerCase()] = valueParts.join(':').trim();
4775
- }
4776
- }
4777
- return {
4778
- statusCode,
4779
- headers,
4780
- body: body || '',
4781
- };
4782
- }
4783
- const autoCall = (data, options) => {
4784
- return callSock(data, { ...options, method: 'POST' });
4785
- };
4786
-
4787
- const App = QueryRouterServer;
4788
-
4789
- export { App, CustomError, QueryRouter, QueryRouterServer, Route, autoCall, createSchema, getMatchFiles, listenSocket, loadTS };