@kevisual/router 0.0.26-alpha.5 → 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/router.js CHANGED
@@ -166,6 +166,12 @@ class $ZodAsyncError extends Error {
166
166
  super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
167
167
  }
168
168
  }
169
+ class $ZodEncodeError extends Error {
170
+ constructor(name) {
171
+ super(`Encountered unidirectional transform during encode: ${name}`);
172
+ this.name = "ZodEncodeError";
173
+ }
174
+ }
169
175
  const globalConfig = {};
170
176
  function config(newConfig) {
171
177
  return globalConfig;
@@ -243,9 +249,6 @@ function defineLazy(object, key, getter) {
243
249
  configurable: true,
244
250
  });
245
251
  }
246
- function objectClone(obj) {
247
- return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
248
- }
249
252
  function assignProp(target, prop, value) {
250
253
  Object.defineProperty(target, prop, {
251
254
  value,
@@ -266,7 +269,7 @@ function esc(str) {
266
269
  return JSON.stringify(str);
267
270
  }
268
271
  const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
269
- function isObject(data) {
272
+ function isObject$1(data) {
270
273
  return typeof data === "object" && data !== null && !Array.isArray(data);
271
274
  }
272
275
  const allowsEval = cached(() => {
@@ -284,7 +287,7 @@ const allowsEval = cached(() => {
284
287
  }
285
288
  });
286
289
  function isPlainObject(o) {
287
- if (isObject(o) === false)
290
+ if (isObject$1(o) === false)
288
291
  return false;
289
292
  // modified constructor
290
293
  const ctor = o.constructor;
@@ -292,7 +295,7 @@ function isPlainObject(o) {
292
295
  return true;
293
296
  // modified prototype
294
297
  const prot = ctor.prototype;
295
- if (isObject(prot) === false)
298
+ if (isObject$1(prot) === false)
296
299
  return false;
297
300
  // ctor doesn't have static `isPrototypeOf`
298
301
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
@@ -303,6 +306,8 @@ function isPlainObject(o) {
303
306
  function shallowClone(o) {
304
307
  if (isPlainObject(o))
305
308
  return { ...o };
309
+ if (Array.isArray(o))
310
+ return [...o];
306
311
  return o;
307
312
  }
308
313
  const propertyKeyTypes = new Set(["string", "number", "symbol"]);
@@ -388,6 +393,11 @@ function extend(schema, shape) {
388
393
  if (!isPlainObject(shape)) {
389
394
  throw new Error("Invalid input to extend: expected a plain object");
390
395
  }
396
+ const checks = schema._zod.def.checks;
397
+ const hasChecks = checks && checks.length > 0;
398
+ if (hasChecks) {
399
+ throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
400
+ }
391
401
  const def = mergeDefs(schema._zod.def, {
392
402
  get shape() {
393
403
  const _shape = { ...schema._zod.def.shape, ...shape };
@@ -398,6 +408,21 @@ function extend(schema, shape) {
398
408
  });
399
409
  return clone(schema, def);
400
410
  }
411
+ function safeExtend(schema, shape) {
412
+ if (!isPlainObject(shape)) {
413
+ throw new Error("Invalid input to safeExtend: expected a plain object");
414
+ }
415
+ const def = {
416
+ ...schema._zod.def,
417
+ get shape() {
418
+ const _shape = { ...schema._zod.def.shape, ...shape };
419
+ assignProp(this, "shape", _shape); // self-caching
420
+ return _shape;
421
+ },
422
+ checks: schema._zod.def.checks,
423
+ };
424
+ return clone(schema, def);
425
+ }
401
426
  function merge(a, b) {
402
427
  const def = mergeDefs(a._zod.def, {
403
428
  get shape() {
@@ -488,6 +513,8 @@ function required(Class, schema, mask) {
488
513
  }
489
514
  // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom
490
515
  function aborted(x, startIndex = 0) {
516
+ if (x.aborted === true)
517
+ return true;
491
518
  for (let i = startIndex; i < x.issues.length; i++) {
492
519
  if (x.issues[i]?.continue !== true) {
493
520
  return true;
@@ -577,11 +604,7 @@ function flattenError(error, mapper = (issue) => issue.message) {
577
604
  }
578
605
  return { formErrors, fieldErrors };
579
606
  }
580
- function formatError(error, _mapper) {
581
- const mapper = _mapper ||
582
- function (issue) {
583
- return issue.message;
584
- };
607
+ function formatError(error, mapper = (issue) => issue.message) {
585
608
  const fieldErrors = { _errors: [] };
586
609
  const processError = (error) => {
587
610
  for (const issue of error.issues) {
@@ -672,6 +695,34 @@ const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
672
695
  : { success: true, data: result.value };
673
696
  };
674
697
  const safeParseAsync$1 = /* @__PURE__*/ _safeParseAsync($ZodRealError);
698
+ const _encode = (_Err) => (schema, value, _ctx) => {
699
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
700
+ return _parse(_Err)(schema, value, ctx);
701
+ };
702
+ const _decode = (_Err) => (schema, value, _ctx) => {
703
+ return _parse(_Err)(schema, value, _ctx);
704
+ };
705
+ const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
706
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
707
+ return _parseAsync(_Err)(schema, value, ctx);
708
+ };
709
+ const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
710
+ return _parseAsync(_Err)(schema, value, _ctx);
711
+ };
712
+ const _safeEncode = (_Err) => (schema, value, _ctx) => {
713
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
714
+ return _safeParse(_Err)(schema, value, ctx);
715
+ };
716
+ const _safeDecode = (_Err) => (schema, value, _ctx) => {
717
+ return _safeParse(_Err)(schema, value, _ctx);
718
+ };
719
+ const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
720
+ const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
721
+ return _safeParseAsync(_Err)(schema, value, ctx);
722
+ };
723
+ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
724
+ return _safeParseAsync(_Err)(schema, value, _ctx);
725
+ };
675
726
 
676
727
  const cuid = /^[cC][^\s-]{8,}$/;
677
728
  const cuid2 = /^[0-9a-z]+$/;
@@ -688,7 +739,7 @@ const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9
688
739
  * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */
689
740
  const uuid = (version) => {
690
741
  if (!version)
691
- 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)$/;
742
+ 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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
692
743
  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})$`);
693
744
  };
694
745
  /** Practical email validation */
@@ -699,7 +750,7 @@ function emoji() {
699
750
  return new RegExp(_emoji$1, "u");
700
751
  }
701
752
  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])$/;
702
- 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})$/;
753
+ const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
703
754
  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])$/;
704
755
  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])$/;
705
756
  // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
@@ -743,9 +794,9 @@ const string$1 = (params) => {
743
794
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
744
795
  return new RegExp(`^${regex}$`);
745
796
  };
746
- const integer = /^\d+$/;
747
- const number$1 = /^-?\d+(?:\.\d+)?/i;
748
- const boolean$1 = /true|false/i;
797
+ const integer = /^-?\d+$/;
798
+ const number$1 = /^-?\d+(?:\.\d+)?/;
799
+ const boolean$1 = /^(?:true|false)$/i;
749
800
  // regex for string with no uppercase letters
750
801
  const lowercase = /^[^A-Z]*$/;
751
802
  // regex for string with no lowercase letters
@@ -1197,8 +1248,8 @@ class Doc {
1197
1248
 
1198
1249
  const version = {
1199
1250
  major: 4,
1200
- minor: 0,
1201
- patch: 17,
1251
+ minor: 1,
1252
+ patch: 12,
1202
1253
  };
1203
1254
 
1204
1255
  const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
@@ -1212,7 +1263,6 @@ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
1212
1263
  if (inst._zod.traits.has("$ZodCheck")) {
1213
1264
  checks.unshift(inst);
1214
1265
  }
1215
- //
1216
1266
  for (const ch of checks) {
1217
1267
  for (const fn of ch._zod.onattach) {
1218
1268
  fn(inst);
@@ -1269,7 +1319,47 @@ const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
1269
1319
  }
1270
1320
  return payload;
1271
1321
  };
1322
+ // const handleChecksResult = (
1323
+ // checkResult: ParsePayload,
1324
+ // originalResult: ParsePayload,
1325
+ // ctx: ParseContextInternal
1326
+ // ): util.MaybeAsync<ParsePayload> => {
1327
+ // // if the checks mutated the value && there are no issues, re-parse the result
1328
+ // if (checkResult.value !== originalResult.value && !checkResult.issues.length)
1329
+ // return inst._zod.parse(checkResult, ctx);
1330
+ // return originalResult;
1331
+ // };
1332
+ const handleCanaryResult = (canary, payload, ctx) => {
1333
+ // abort if the canary is aborted
1334
+ if (aborted(canary)) {
1335
+ canary.aborted = true;
1336
+ return canary;
1337
+ }
1338
+ // run checks first, then
1339
+ const checkResult = runChecks(payload, checks, ctx);
1340
+ if (checkResult instanceof Promise) {
1341
+ if (ctx.async === false)
1342
+ throw new $ZodAsyncError();
1343
+ return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
1344
+ }
1345
+ return inst._zod.parse(checkResult, ctx);
1346
+ };
1272
1347
  inst._zod.run = (payload, ctx) => {
1348
+ if (ctx.skipChecks) {
1349
+ return inst._zod.parse(payload, ctx);
1350
+ }
1351
+ if (ctx.direction === "backward") {
1352
+ // run canary
1353
+ // initial pass (no checks)
1354
+ const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
1355
+ if (canary instanceof Promise) {
1356
+ return canary.then((canary) => {
1357
+ return handleCanaryResult(canary, payload, ctx);
1358
+ });
1359
+ }
1360
+ return handleCanaryResult(canary, payload, ctx);
1361
+ }
1362
+ // forward
1273
1363
  const result = inst._zod.parse(payload, ctx);
1274
1364
  if (result instanceof Promise) {
1275
1365
  if (ctx.async === false)
@@ -1489,8 +1579,11 @@ const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
1489
1579
  def.pattern ?? (def.pattern = cidrv6); // not used for validation
1490
1580
  $ZodStringFormat.init(inst, def);
1491
1581
  inst._zod.check = (payload) => {
1492
- const [address, prefix] = payload.value.split("/");
1582
+ const parts = payload.value.split("/");
1493
1583
  try {
1584
+ if (parts.length !== 2)
1585
+ throw new Error();
1586
+ const [address, prefix] = parts;
1494
1587
  if (!prefix)
1495
1588
  throw new Error();
1496
1589
  const prefixNum = Number(prefix);
@@ -1740,25 +1833,75 @@ function handlePropertyResult(result, final, key, input) {
1740
1833
  final.value[key] = result.value;
1741
1834
  }
1742
1835
  }
1836
+ function normalizeDef(def) {
1837
+ const keys = Object.keys(def.shape);
1838
+ for (const k of keys) {
1839
+ if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
1840
+ throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1841
+ }
1842
+ }
1843
+ const okeys = optionalKeys(def.shape);
1844
+ return {
1845
+ ...def,
1846
+ keys,
1847
+ keySet: new Set(keys),
1848
+ numKeys: keys.length,
1849
+ optionalKeys: new Set(okeys),
1850
+ };
1851
+ }
1852
+ function handleCatchall(proms, input, payload, ctx, def, inst) {
1853
+ const unrecognized = [];
1854
+ // iterate over input keys
1855
+ const keySet = def.keySet;
1856
+ const _catchall = def.catchall._zod;
1857
+ const t = _catchall.def.type;
1858
+ for (const key of Object.keys(input)) {
1859
+ if (keySet.has(key))
1860
+ continue;
1861
+ if (t === "never") {
1862
+ unrecognized.push(key);
1863
+ continue;
1864
+ }
1865
+ const r = _catchall.run({ value: input[key], issues: [] }, ctx);
1866
+ if (r instanceof Promise) {
1867
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1868
+ }
1869
+ else {
1870
+ handlePropertyResult(r, payload, key, input);
1871
+ }
1872
+ }
1873
+ if (unrecognized.length) {
1874
+ payload.issues.push({
1875
+ code: "unrecognized_keys",
1876
+ keys: unrecognized,
1877
+ input,
1878
+ inst,
1879
+ });
1880
+ }
1881
+ if (!proms.length)
1882
+ return payload;
1883
+ return Promise.all(proms).then(() => {
1884
+ return payload;
1885
+ });
1886
+ }
1743
1887
  const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1744
1888
  // requires cast because technically $ZodObject doesn't extend
1745
1889
  $ZodType.init(inst, def);
1746
- const _normalized = cached(() => {
1747
- const keys = Object.keys(def.shape);
1748
- for (const k of keys) {
1749
- if (!def.shape[k]._zod.traits.has("$ZodType")) {
1750
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
1751
- }
1752
- }
1753
- const okeys = optionalKeys(def.shape);
1754
- return {
1755
- shape: def.shape,
1756
- keys,
1757
- keySet: new Set(keys),
1758
- numKeys: keys.length,
1759
- optionalKeys: new Set(okeys),
1760
- };
1761
- });
1890
+ // const sh = def.shape;
1891
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
1892
+ if (!desc?.get) {
1893
+ const sh = def.shape;
1894
+ Object.defineProperty(def, "shape", {
1895
+ get: () => {
1896
+ const newSh = { ...sh };
1897
+ Object.defineProperty(def, "shape", {
1898
+ value: newSh,
1899
+ });
1900
+ return newSh;
1901
+ },
1902
+ });
1903
+ }
1904
+ const _normalized = cached(() => normalizeDef(def));
1762
1905
  defineLazy(inst._zod, "propValues", () => {
1763
1906
  const shape = def.shape;
1764
1907
  const propValues = {};
@@ -1772,6 +1915,45 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1772
1915
  }
1773
1916
  return propValues;
1774
1917
  });
1918
+ const isObject = isObject$1;
1919
+ const catchall = def.catchall;
1920
+ let value;
1921
+ inst._zod.parse = (payload, ctx) => {
1922
+ value ?? (value = _normalized.value);
1923
+ const input = payload.value;
1924
+ if (!isObject(input)) {
1925
+ payload.issues.push({
1926
+ expected: "object",
1927
+ code: "invalid_type",
1928
+ input,
1929
+ inst,
1930
+ });
1931
+ return payload;
1932
+ }
1933
+ payload.value = {};
1934
+ const proms = [];
1935
+ const shape = value.shape;
1936
+ for (const key of value.keys) {
1937
+ const el = shape[key];
1938
+ const r = el._zod.run({ value: input[key], issues: [] }, ctx);
1939
+ if (r instanceof Promise) {
1940
+ proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1941
+ }
1942
+ else {
1943
+ handlePropertyResult(r, payload, key, input);
1944
+ }
1945
+ }
1946
+ if (!catchall) {
1947
+ return proms.length ? Promise.all(proms).then(() => payload) : payload;
1948
+ }
1949
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
1950
+ };
1951
+ });
1952
+ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => {
1953
+ // requires cast because technically $ZodObject doesn't extend
1954
+ $ZodObject.init(inst, def);
1955
+ const superParse = inst._zod.parse;
1956
+ const _normalized = cached(() => normalizeDef(def));
1775
1957
  const generateFastpass = (shape) => {
1776
1958
  const doc = new Doc(["shape", "payload", "ctx"]);
1777
1959
  const normalized = _normalized.value;
@@ -1786,7 +1968,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1786
1968
  ids[key] = `key_${counter++}`;
1787
1969
  }
1788
1970
  // A: preserve key order {
1789
- doc.write(`const newResult = {}`);
1971
+ doc.write(`const newResult = {};`);
1790
1972
  for (const key of normalized.keys) {
1791
1973
  const id = ids[key];
1792
1974
  const k = esc(key);
@@ -1799,6 +1981,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1799
1981
  })));
1800
1982
  }
1801
1983
 
1984
+
1802
1985
  if (${id}.value === undefined) {
1803
1986
  if (${k} in input) {
1804
1987
  newResult[${k}] = undefined;
@@ -1806,6 +1989,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1806
1989
  } else {
1807
1990
  newResult[${k}] = ${id}.value;
1808
1991
  }
1992
+
1809
1993
  `);
1810
1994
  }
1811
1995
  doc.write(`payload.value = newResult;`);
@@ -1814,7 +1998,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1814
1998
  return (payload, ctx) => fn(shape, payload, ctx);
1815
1999
  };
1816
2000
  let fastpass;
1817
- const isObject$1 = isObject;
2001
+ const isObject = isObject$1;
1818
2002
  const jit = !globalConfig.jitless;
1819
2003
  const allowsEval$1 = allowsEval;
1820
2004
  const fastEnabled = jit && allowsEval$1.value; // && !def.catchall;
@@ -1823,7 +2007,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1823
2007
  inst._zod.parse = (payload, ctx) => {
1824
2008
  value ?? (value = _normalized.value);
1825
2009
  const input = payload.value;
1826
- if (!isObject$1(input)) {
2010
+ if (!isObject(input)) {
1827
2011
  payload.issues.push({
1828
2012
  expected: "object",
1829
2013
  code: "invalid_type",
@@ -1832,63 +2016,16 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
1832
2016
  });
1833
2017
  return payload;
1834
2018
  }
1835
- const proms = [];
1836
2019
  if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
1837
2020
  // always synchronous
1838
2021
  if (!fastpass)
1839
2022
  fastpass = generateFastpass(def.shape);
1840
2023
  payload = fastpass(payload, ctx);
2024
+ if (!catchall)
2025
+ return payload;
2026
+ return handleCatchall([], input, payload, ctx, value, inst);
1841
2027
  }
1842
- else {
1843
- payload.value = {};
1844
- const shape = value.shape;
1845
- for (const key of value.keys) {
1846
- const el = shape[key];
1847
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
1848
- if (r instanceof Promise) {
1849
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1850
- }
1851
- else {
1852
- handlePropertyResult(r, payload, key, input);
1853
- }
1854
- }
1855
- }
1856
- if (!catchall) {
1857
- return proms.length ? Promise.all(proms).then(() => payload) : payload;
1858
- }
1859
- const unrecognized = [];
1860
- // iterate over input keys
1861
- const keySet = value.keySet;
1862
- const _catchall = catchall._zod;
1863
- const t = _catchall.def.type;
1864
- for (const key of Object.keys(input)) {
1865
- if (keySet.has(key))
1866
- continue;
1867
- if (t === "never") {
1868
- unrecognized.push(key);
1869
- continue;
1870
- }
1871
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
1872
- if (r instanceof Promise) {
1873
- proms.push(r.then((r) => handlePropertyResult(r, payload, key, input)));
1874
- }
1875
- else {
1876
- handlePropertyResult(r, payload, key, input);
1877
- }
1878
- }
1879
- if (unrecognized.length) {
1880
- payload.issues.push({
1881
- code: "unrecognized_keys",
1882
- keys: unrecognized,
1883
- input,
1884
- inst,
1885
- });
1886
- }
1887
- if (!proms.length)
1888
- return payload;
1889
- return Promise.all(proms).then(() => {
1890
- return payload;
1891
- });
2028
+ return superParse(payload, ctx);
1892
2029
  };
1893
2030
  });
1894
2031
  function handleUnionResults(results, final, inst, ctx) {
@@ -2060,9 +2197,12 @@ const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
2060
2197
  });
2061
2198
  const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
2062
2199
  $ZodType.init(inst, def);
2063
- inst._zod.parse = (payload, _ctx) => {
2200
+ inst._zod.parse = (payload, ctx) => {
2201
+ if (ctx.direction === "backward") {
2202
+ throw new $ZodEncodeError(inst.constructor.name);
2203
+ }
2064
2204
  const _out = def.transform(payload.value, payload);
2065
- if (_ctx.async) {
2205
+ if (ctx.async) {
2066
2206
  const output = _out instanceof Promise ? _out : Promise.resolve(_out);
2067
2207
  return output.then((output) => {
2068
2208
  payload.value = output;
@@ -2118,6 +2258,7 @@ const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
2118
2258
  return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
2119
2259
  });
2120
2260
  inst._zod.parse = (payload, ctx) => {
2261
+ // Forward direction (decode): allow null to pass through
2121
2262
  if (payload.value === null)
2122
2263
  return payload;
2123
2264
  return def.innerType._zod.run(payload, ctx);
@@ -2129,13 +2270,18 @@ const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
2129
2270
  inst._zod.optin = "optional";
2130
2271
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2131
2272
  inst._zod.parse = (payload, ctx) => {
2273
+ if (ctx.direction === "backward") {
2274
+ return def.innerType._zod.run(payload, ctx);
2275
+ }
2276
+ // Forward direction (decode): apply defaults for undefined input
2132
2277
  if (payload.value === undefined) {
2133
2278
  payload.value = def.defaultValue;
2134
2279
  /**
2135
- * $ZodDefault always returns the default value immediately.
2280
+ * $ZodDefault returns the default value immediately in forward direction.
2136
2281
  * 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. */
2137
2282
  return payload;
2138
2283
  }
2284
+ // Forward direction: continue with default handling
2139
2285
  const result = def.innerType._zod.run(payload, ctx);
2140
2286
  if (result instanceof Promise) {
2141
2287
  return result.then((result) => handleDefaultResult(result, def));
@@ -2154,6 +2300,10 @@ const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
2154
2300
  inst._zod.optin = "optional";
2155
2301
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2156
2302
  inst._zod.parse = (payload, ctx) => {
2303
+ if (ctx.direction === "backward") {
2304
+ return def.innerType._zod.run(payload, ctx);
2305
+ }
2306
+ // Forward direction (decode): apply prefault for undefined input
2157
2307
  if (payload.value === undefined) {
2158
2308
  payload.value = def.defaultValue;
2159
2309
  }
@@ -2191,6 +2341,10 @@ const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
2191
2341
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2192
2342
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2193
2343
  inst._zod.parse = (payload, ctx) => {
2344
+ if (ctx.direction === "backward") {
2345
+ return def.innerType._zod.run(payload, ctx);
2346
+ }
2347
+ // Forward direction (decode): apply catch logic
2194
2348
  const result = def.innerType._zod.run(payload, ctx);
2195
2349
  if (result instanceof Promise) {
2196
2350
  return result.then((result) => {
@@ -2229,18 +2383,27 @@ const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
2229
2383
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
2230
2384
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
2231
2385
  inst._zod.parse = (payload, ctx) => {
2386
+ if (ctx.direction === "backward") {
2387
+ const right = def.out._zod.run(payload, ctx);
2388
+ if (right instanceof Promise) {
2389
+ return right.then((right) => handlePipeResult(right, def.in, ctx));
2390
+ }
2391
+ return handlePipeResult(right, def.in, ctx);
2392
+ }
2232
2393
  const left = def.in._zod.run(payload, ctx);
2233
2394
  if (left instanceof Promise) {
2234
- return left.then((left) => handlePipeResult(left, def, ctx));
2395
+ return left.then((left) => handlePipeResult(left, def.out, ctx));
2235
2396
  }
2236
- return handlePipeResult(left, def, ctx);
2397
+ return handlePipeResult(left, def.out, ctx);
2237
2398
  };
2238
2399
  });
2239
- function handlePipeResult(left, def, ctx) {
2400
+ function handlePipeResult(left, next, ctx) {
2240
2401
  if (left.issues.length) {
2402
+ // prevent further checks
2403
+ left.aborted = true;
2241
2404
  return left;
2242
2405
  }
2243
- return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
2406
+ return next._zod.run({ value: left.value, issues: left.issues }, ctx);
2244
2407
  }
2245
2408
  const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
2246
2409
  $ZodType.init(inst, def);
@@ -2249,6 +2412,9 @@ const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
2249
2412
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2250
2413
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2251
2414
  inst._zod.parse = (payload, ctx) => {
2415
+ if (ctx.direction === "backward") {
2416
+ return def.innerType._zod.run(payload, ctx);
2417
+ }
2252
2418
  const result = def.innerType._zod.run(payload, ctx);
2253
2419
  if (result instanceof Promise) {
2254
2420
  return result.then(handleReadonlyResult);
@@ -2294,7 +2460,7 @@ function handleRefineResult(result, payload, input, inst) {
2294
2460
 
2295
2461
  class $ZodRegistry {
2296
2462
  constructor() {
2297
- this._map = new Map();
2463
+ this._map = new WeakMap();
2298
2464
  this._idmap = new Map();
2299
2465
  }
2300
2466
  add(schema, ..._meta) {
@@ -2309,7 +2475,7 @@ class $ZodRegistry {
2309
2475
  return this;
2310
2476
  }
2311
2477
  clear() {
2312
- this._map = new Map();
2478
+ this._map = new WeakMap();
2313
2479
  this._idmap = new Map();
2314
2480
  return this;
2315
2481
  }
@@ -2787,7 +2953,7 @@ function _superRefine(fn) {
2787
2953
  _issue.code ?? (_issue.code = "custom");
2788
2954
  _issue.input ?? (_issue.input = payload.value);
2789
2955
  _issue.inst ?? (_issue.inst = ch);
2790
- _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
2956
+ _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...
2791
2957
  payload.issues.push(issue(_issue));
2792
2958
  }
2793
2959
  };
@@ -2883,22 +3049,29 @@ const parse = /* @__PURE__ */ _parse(ZodRealError);
2883
3049
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
2884
3050
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
2885
3051
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3052
+ // Codec functions
3053
+ const encode = /* @__PURE__ */ _encode(ZodRealError);
3054
+ const decode = /* @__PURE__ */ _decode(ZodRealError);
3055
+ const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3056
+ const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
3057
+ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
3058
+ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
3059
+ const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
3060
+ const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
2886
3061
 
2887
3062
  const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
2888
3063
  $ZodType.init(inst, def);
2889
3064
  inst.def = def;
3065
+ inst.type = def.type;
2890
3066
  Object.defineProperty(inst, "_def", { value: def });
2891
3067
  // base methods
2892
3068
  inst.check = (...checks) => {
2893
- return inst.clone({
2894
- ...def,
3069
+ return inst.clone(mergeDefs(def, {
2895
3070
  checks: [
2896
3071
  ...(def.checks ?? []),
2897
3072
  ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch),
2898
3073
  ],
2899
- }
2900
- // { parent: true }
2901
- );
3074
+ }));
2902
3075
  };
2903
3076
  inst.clone = (def, params) => clone(inst, def, params);
2904
3077
  inst.brand = () => inst;
@@ -2912,6 +3085,15 @@ const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
2912
3085
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
2913
3086
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
2914
3087
  inst.spa = inst.safeParseAsync;
3088
+ // encoding/decoding
3089
+ inst.encode = (data, params) => encode(inst, data, params);
3090
+ inst.decode = (data, params) => decode(inst, data, params);
3091
+ inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3092
+ inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
3093
+ inst.safeEncode = (data, params) => safeEncode(inst, data, params);
3094
+ inst.safeDecode = (data, params) => safeDecode(inst, data, params);
3095
+ inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
3096
+ inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
2915
3097
  // refinements
2916
3098
  inst.refine = (check, params) => inst.check(refine(check, params));
2917
3099
  inst.superRefine = (refinement) => inst.check(superRefine(refinement));
@@ -3193,9 +3375,11 @@ function array(element, params) {
3193
3375
  return _array(ZodArray, element, params);
3194
3376
  }
3195
3377
  const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
3196
- $ZodObject.init(inst, def);
3378
+ $ZodObjectJIT.init(inst, def);
3197
3379
  ZodType.init(inst, def);
3198
- defineLazy(inst, "shape", () => def.shape);
3380
+ defineLazy(inst, "shape", () => {
3381
+ return def.shape;
3382
+ });
3199
3383
  inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
3200
3384
  inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall });
3201
3385
  inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
@@ -3205,6 +3389,9 @@ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
3205
3389
  inst.extend = (incoming) => {
3206
3390
  return extend(inst, incoming);
3207
3391
  };
3392
+ inst.safeExtend = (incoming) => {
3393
+ return safeExtend(inst, incoming);
3394
+ };
3208
3395
  inst.merge = (other) => merge(inst, other);
3209
3396
  inst.pick = (mask) => pick$1(inst, mask);
3210
3397
  inst.omit = (mask) => omit(inst, mask);
@@ -3214,10 +3401,7 @@ const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
3214
3401
  function object(shape, params) {
3215
3402
  const def = {
3216
3403
  type: "object",
3217
- get shape() {
3218
- assignProp(this, "shape", shape ? objectClone(shape) : {});
3219
- return this.shape;
3220
- },
3404
+ shape: shape ?? {},
3221
3405
  ...normalizeParams(params),
3222
3406
  };
3223
3407
  return new ZodObject(def);
@@ -3296,6 +3480,9 @@ const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
3296
3480
  $ZodTransform.init(inst, def);
3297
3481
  ZodType.init(inst, def);
3298
3482
  inst._zod.parse = (payload, _ctx) => {
3483
+ if (_ctx.direction === "backward") {
3484
+ throw new $ZodEncodeError(inst.constructor.name);
3485
+ }
3299
3486
  payload.addIssue = (issue$1) => {
3300
3487
  if (typeof issue$1 === "string") {
3301
3488
  payload.issues.push(issue(issue$1, payload.value, def));
@@ -3501,113 +3688,1194 @@ function pick(obj, keys) {
3501
3688
  return result;
3502
3689
  }
3503
3690
 
3504
- const pickValue = ['path', 'key', 'id', 'description', 'type', 'validator', 'middleware'];
3505
- class Route {
3506
- /**
3507
- * 一级路径
3508
- */
3509
- path;
3510
- /**
3511
- * 二级路径
3512
- */
3513
- key;
3514
- id;
3515
- share = false;
3516
- run;
3517
- nextRoute; // route to run after this route
3518
- description;
3519
- metadata;
3520
- middleware; // middleware
3521
- type = 'route';
3522
- _validator;
3523
- schema;
3524
- data;
3525
- /**
3526
- * 是否需要验证
3527
- */
3528
- isVerify;
3529
- /**
3530
- * 是否开启debug,开启后会打印错误信息
3531
- */
3532
- isDebug;
3533
- constructor(path, key = '', opts) {
3534
- path = path.trim();
3535
- key = key.trim();
3536
- this.path = path;
3537
- this.key = key;
3538
- if (opts) {
3539
- this.id = opts.id || nanoid$1();
3540
- if (!opts.id && opts.idUsePath) {
3541
- const delimiter = opts.delimiter ?? '$#$';
3542
- this.id = path + delimiter + key;
3543
- }
3544
- this.run = opts.run;
3545
- this.nextRoute = opts.nextRoute;
3546
- this.description = opts.description;
3547
- this.metadata = opts.metadata;
3548
- this.type = opts.type || 'route';
3549
- this.validator = opts.validator;
3550
- this.middleware = opts.middleware || [];
3551
- this.key = opts.key || key;
3552
- this.path = opts.path || path;
3553
- this.isVerify = opts.isVerify ?? true;
3554
- this.createSchema();
3555
- }
3556
- else {
3557
- this.isVerify = true;
3558
- this.middleware = [];
3559
- this.id = nanoid$1();
3560
- }
3561
- this.isDebug = opts?.isDebug ?? false;
3562
- }
3563
- createSchema() {
3564
- try {
3565
- const validator = this.validator;
3566
- const keys = Object.keys(validator || {});
3567
- const schemaList = keys.map((key) => {
3568
- return { [key]: createSchema(validator[key]) };
3569
- });
3570
- const schema = schemaList.reduce((prev, current) => {
3571
- return { ...prev, ...current };
3572
- }, {});
3573
- this.schema = schema;
3574
- }
3575
- catch (e) {
3576
- console.error('createSchema error:', e);
3577
- }
3578
- }
3579
- /**
3580
- * set validator and create schema
3581
- * @param validator
3582
- */
3583
- set validator(validator) {
3584
- this._validator = validator;
3585
- this.createSchema();
3586
- }
3587
- get validator() {
3588
- return this._validator || {};
3691
+ /** Detect free variable `global` from Node.js. */
3692
+ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
3693
+
3694
+ /** Detect free variable `self`. */
3695
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
3696
+
3697
+ /** Used as a reference to the global object. */
3698
+ var root = freeGlobal || freeSelf || Function('return this')();
3699
+
3700
+ /** Built-in value references. */
3701
+ var Symbol$1 = root.Symbol;
3702
+
3703
+ /** Used for built-in method references. */
3704
+ var objectProto$4 = Object.prototype;
3705
+
3706
+ /** Used to check objects for own properties. */
3707
+ var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
3708
+
3709
+ /**
3710
+ * Used to resolve the
3711
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
3712
+ * of values.
3713
+ */
3714
+ var nativeObjectToString$1 = objectProto$4.toString;
3715
+
3716
+ /** Built-in value references. */
3717
+ var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;
3718
+
3719
+ /**
3720
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
3721
+ *
3722
+ * @private
3723
+ * @param {*} value The value to query.
3724
+ * @returns {string} Returns the raw `toStringTag`.
3725
+ */
3726
+ function getRawTag(value) {
3727
+ var isOwn = hasOwnProperty$3.call(value, symToStringTag$1),
3728
+ tag = value[symToStringTag$1];
3729
+
3730
+ try {
3731
+ value[symToStringTag$1] = undefined;
3732
+ var unmasked = true;
3733
+ } catch (e) {}
3734
+
3735
+ var result = nativeObjectToString$1.call(value);
3736
+ if (unmasked) {
3737
+ if (isOwn) {
3738
+ value[symToStringTag$1] = tag;
3739
+ } else {
3740
+ delete value[symToStringTag$1];
3589
3741
  }
3590
- /**
3591
- * has code, body, message in ctx, return ctx if has error
3592
- * @param ctx
3593
- * @param dev
3594
- * @returns
3595
- */
3596
- verify(ctx, dev = false) {
3597
- const query = ctx.query || {};
3598
- const schema = this.schema || {};
3599
- const validator = this.validator;
3600
- const check = () => {
3601
- const queryKeys = Object.keys(validator);
3602
- for (let i = 0; i < queryKeys.length; i++) {
3603
- const key = queryKeys[i];
3604
- const value = query[key];
3605
- if (schema[key]) {
3606
- const result = schema[key].safeParse(value);
3607
- if (!result.success) {
3608
- // TODO:
3609
- const message = 'safe error, TODO:';
3610
- throw new CustomError(500, message);
3742
+ }
3743
+ return result;
3744
+ }
3745
+
3746
+ /** Used for built-in method references. */
3747
+ var objectProto$3 = Object.prototype;
3748
+
3749
+ /**
3750
+ * Used to resolve the
3751
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
3752
+ * of values.
3753
+ */
3754
+ var nativeObjectToString = objectProto$3.toString;
3755
+
3756
+ /**
3757
+ * Converts `value` to a string using `Object.prototype.toString`.
3758
+ *
3759
+ * @private
3760
+ * @param {*} value The value to convert.
3761
+ * @returns {string} Returns the converted string.
3762
+ */
3763
+ function objectToString(value) {
3764
+ return nativeObjectToString.call(value);
3765
+ }
3766
+
3767
+ /** `Object#toString` result references. */
3768
+ var nullTag = '[object Null]',
3769
+ undefinedTag = '[object Undefined]';
3770
+
3771
+ /** Built-in value references. */
3772
+ var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;
3773
+
3774
+ /**
3775
+ * The base implementation of `getTag` without fallbacks for buggy environments.
3776
+ *
3777
+ * @private
3778
+ * @param {*} value The value to query.
3779
+ * @returns {string} Returns the `toStringTag`.
3780
+ */
3781
+ function baseGetTag(value) {
3782
+ if (value == null) {
3783
+ return value === undefined ? undefinedTag : nullTag;
3784
+ }
3785
+ return (symToStringTag && symToStringTag in Object(value))
3786
+ ? getRawTag(value)
3787
+ : objectToString(value);
3788
+ }
3789
+
3790
+ /**
3791
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
3792
+ * and has a `typeof` result of "object".
3793
+ *
3794
+ * @static
3795
+ * @memberOf _
3796
+ * @since 4.0.0
3797
+ * @category Lang
3798
+ * @param {*} value The value to check.
3799
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
3800
+ * @example
3801
+ *
3802
+ * _.isObjectLike({});
3803
+ * // => true
3804
+ *
3805
+ * _.isObjectLike([1, 2, 3]);
3806
+ * // => true
3807
+ *
3808
+ * _.isObjectLike(_.noop);
3809
+ * // => false
3810
+ *
3811
+ * _.isObjectLike(null);
3812
+ * // => false
3813
+ */
3814
+ function isObjectLike(value) {
3815
+ return value != null && typeof value == 'object';
3816
+ }
3817
+
3818
+ /** `Object#toString` result references. */
3819
+ var symbolTag = '[object Symbol]';
3820
+
3821
+ /**
3822
+ * Checks if `value` is classified as a `Symbol` primitive or object.
3823
+ *
3824
+ * @static
3825
+ * @memberOf _
3826
+ * @since 4.0.0
3827
+ * @category Lang
3828
+ * @param {*} value The value to check.
3829
+ * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
3830
+ * @example
3831
+ *
3832
+ * _.isSymbol(Symbol.iterator);
3833
+ * // => true
3834
+ *
3835
+ * _.isSymbol('abc');
3836
+ * // => false
3837
+ */
3838
+ function isSymbol(value) {
3839
+ return typeof value == 'symbol' ||
3840
+ (isObjectLike(value) && baseGetTag(value) == symbolTag);
3841
+ }
3842
+
3843
+ /**
3844
+ * A specialized version of `_.map` for arrays without support for iteratee
3845
+ * shorthands.
3846
+ *
3847
+ * @private
3848
+ * @param {Array} [array] The array to iterate over.
3849
+ * @param {Function} iteratee The function invoked per iteration.
3850
+ * @returns {Array} Returns the new mapped array.
3851
+ */
3852
+ function arrayMap(array, iteratee) {
3853
+ var index = -1,
3854
+ length = array == null ? 0 : array.length,
3855
+ result = Array(length);
3856
+
3857
+ while (++index < length) {
3858
+ result[index] = iteratee(array[index], index, array);
3859
+ }
3860
+ return result;
3861
+ }
3862
+
3863
+ /**
3864
+ * Checks if `value` is classified as an `Array` object.
3865
+ *
3866
+ * @static
3867
+ * @memberOf _
3868
+ * @since 0.1.0
3869
+ * @category Lang
3870
+ * @param {*} value The value to check.
3871
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
3872
+ * @example
3873
+ *
3874
+ * _.isArray([1, 2, 3]);
3875
+ * // => true
3876
+ *
3877
+ * _.isArray(document.body.children);
3878
+ * // => false
3879
+ *
3880
+ * _.isArray('abc');
3881
+ * // => false
3882
+ *
3883
+ * _.isArray(_.noop);
3884
+ * // => false
3885
+ */
3886
+ var isArray = Array.isArray;
3887
+
3888
+ /** Used to convert symbols to primitives and strings. */
3889
+ var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined,
3890
+ symbolToString = symbolProto ? symbolProto.toString : undefined;
3891
+
3892
+ /**
3893
+ * The base implementation of `_.toString` which doesn't convert nullish
3894
+ * values to empty strings.
3895
+ *
3896
+ * @private
3897
+ * @param {*} value The value to process.
3898
+ * @returns {string} Returns the string.
3899
+ */
3900
+ function baseToString(value) {
3901
+ // Exit early for strings to avoid a performance hit in some environments.
3902
+ if (typeof value == 'string') {
3903
+ return value;
3904
+ }
3905
+ if (isArray(value)) {
3906
+ // Recursively convert values (susceptible to call stack limits).
3907
+ return arrayMap(value, baseToString) + '';
3908
+ }
3909
+ if (isSymbol(value)) {
3910
+ return symbolToString ? symbolToString.call(value) : '';
3911
+ }
3912
+ var result = (value + '');
3913
+ return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
3914
+ }
3915
+
3916
+ /**
3917
+ * Checks if `value` is the
3918
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
3919
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
3920
+ *
3921
+ * @static
3922
+ * @memberOf _
3923
+ * @since 0.1.0
3924
+ * @category Lang
3925
+ * @param {*} value The value to check.
3926
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
3927
+ * @example
3928
+ *
3929
+ * _.isObject({});
3930
+ * // => true
3931
+ *
3932
+ * _.isObject([1, 2, 3]);
3933
+ * // => true
3934
+ *
3935
+ * _.isObject(_.noop);
3936
+ * // => true
3937
+ *
3938
+ * _.isObject(null);
3939
+ * // => false
3940
+ */
3941
+ function isObject(value) {
3942
+ var type = typeof value;
3943
+ return value != null && (type == 'object' || type == 'function');
3944
+ }
3945
+
3946
+ /** `Object#toString` result references. */
3947
+ var asyncTag = '[object AsyncFunction]',
3948
+ funcTag = '[object Function]',
3949
+ genTag = '[object GeneratorFunction]',
3950
+ proxyTag = '[object Proxy]';
3951
+
3952
+ /**
3953
+ * Checks if `value` is classified as a `Function` object.
3954
+ *
3955
+ * @static
3956
+ * @memberOf _
3957
+ * @since 0.1.0
3958
+ * @category Lang
3959
+ * @param {*} value The value to check.
3960
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
3961
+ * @example
3962
+ *
3963
+ * _.isFunction(_);
3964
+ * // => true
3965
+ *
3966
+ * _.isFunction(/abc/);
3967
+ * // => false
3968
+ */
3969
+ function isFunction(value) {
3970
+ if (!isObject(value)) {
3971
+ return false;
3972
+ }
3973
+ // The use of `Object#toString` avoids issues with the `typeof` operator
3974
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
3975
+ var tag = baseGetTag(value);
3976
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
3977
+ }
3978
+
3979
+ /** Used to detect overreaching core-js shims. */
3980
+ var coreJsData = root['__core-js_shared__'];
3981
+
3982
+ /** Used to detect methods masquerading as native. */
3983
+ var maskSrcKey = (function() {
3984
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
3985
+ return uid ? ('Symbol(src)_1.' + uid) : '';
3986
+ }());
3987
+
3988
+ /**
3989
+ * Checks if `func` has its source masked.
3990
+ *
3991
+ * @private
3992
+ * @param {Function} func The function to check.
3993
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
3994
+ */
3995
+ function isMasked(func) {
3996
+ return !!maskSrcKey && (maskSrcKey in func);
3997
+ }
3998
+
3999
+ /** Used for built-in method references. */
4000
+ var funcProto$1 = Function.prototype;
4001
+
4002
+ /** Used to resolve the decompiled source of functions. */
4003
+ var funcToString$1 = funcProto$1.toString;
4004
+
4005
+ /**
4006
+ * Converts `func` to its source code.
4007
+ *
4008
+ * @private
4009
+ * @param {Function} func The function to convert.
4010
+ * @returns {string} Returns the source code.
4011
+ */
4012
+ function toSource(func) {
4013
+ if (func != null) {
4014
+ try {
4015
+ return funcToString$1.call(func);
4016
+ } catch (e) {}
4017
+ try {
4018
+ return (func + '');
4019
+ } catch (e) {}
4020
+ }
4021
+ return '';
4022
+ }
4023
+
4024
+ /**
4025
+ * Used to match `RegExp`
4026
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
4027
+ */
4028
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
4029
+
4030
+ /** Used to detect host constructors (Safari). */
4031
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
4032
+
4033
+ /** Used for built-in method references. */
4034
+ var funcProto = Function.prototype,
4035
+ objectProto$2 = Object.prototype;
4036
+
4037
+ /** Used to resolve the decompiled source of functions. */
4038
+ var funcToString = funcProto.toString;
4039
+
4040
+ /** Used to check objects for own properties. */
4041
+ var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
4042
+
4043
+ /** Used to detect if a method is native. */
4044
+ var reIsNative = RegExp('^' +
4045
+ funcToString.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&')
4046
+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
4047
+ );
4048
+
4049
+ /**
4050
+ * The base implementation of `_.isNative` without bad shim checks.
4051
+ *
4052
+ * @private
4053
+ * @param {*} value The value to check.
4054
+ * @returns {boolean} Returns `true` if `value` is a native function,
4055
+ * else `false`.
4056
+ */
4057
+ function baseIsNative(value) {
4058
+ if (!isObject(value) || isMasked(value)) {
4059
+ return false;
4060
+ }
4061
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
4062
+ return pattern.test(toSource(value));
4063
+ }
4064
+
4065
+ /**
4066
+ * Gets the value at `key` of `object`.
4067
+ *
4068
+ * @private
4069
+ * @param {Object} [object] The object to query.
4070
+ * @param {string} key The key of the property to get.
4071
+ * @returns {*} Returns the property value.
4072
+ */
4073
+ function getValue(object, key) {
4074
+ return object == null ? undefined : object[key];
4075
+ }
4076
+
4077
+ /**
4078
+ * Gets the native function at `key` of `object`.
4079
+ *
4080
+ * @private
4081
+ * @param {Object} object The object to query.
4082
+ * @param {string} key The key of the method to get.
4083
+ * @returns {*} Returns the function if it's native, else `undefined`.
4084
+ */
4085
+ function getNative(object, key) {
4086
+ var value = getValue(object, key);
4087
+ return baseIsNative(value) ? value : undefined;
4088
+ }
4089
+
4090
+ /**
4091
+ * Performs a
4092
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
4093
+ * comparison between two values to determine if they are equivalent.
4094
+ *
4095
+ * @static
4096
+ * @memberOf _
4097
+ * @since 4.0.0
4098
+ * @category Lang
4099
+ * @param {*} value The value to compare.
4100
+ * @param {*} other The other value to compare.
4101
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
4102
+ * @example
4103
+ *
4104
+ * var object = { 'a': 1 };
4105
+ * var other = { 'a': 1 };
4106
+ *
4107
+ * _.eq(object, object);
4108
+ * // => true
4109
+ *
4110
+ * _.eq(object, other);
4111
+ * // => false
4112
+ *
4113
+ * _.eq('a', 'a');
4114
+ * // => true
4115
+ *
4116
+ * _.eq('a', Object('a'));
4117
+ * // => false
4118
+ *
4119
+ * _.eq(NaN, NaN);
4120
+ * // => true
4121
+ */
4122
+ function eq(value, other) {
4123
+ return value === other || (value !== value && other !== other);
4124
+ }
4125
+
4126
+ /** Used to match property names within property paths. */
4127
+ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
4128
+ reIsPlainProp = /^\w*$/;
4129
+
4130
+ /**
4131
+ * Checks if `value` is a property name and not a property path.
4132
+ *
4133
+ * @private
4134
+ * @param {*} value The value to check.
4135
+ * @param {Object} [object] The object to query keys on.
4136
+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
4137
+ */
4138
+ function isKey(value, object) {
4139
+ if (isArray(value)) {
4140
+ return false;
4141
+ }
4142
+ var type = typeof value;
4143
+ if (type == 'number' || type == 'symbol' || type == 'boolean' ||
4144
+ value == null || isSymbol(value)) {
4145
+ return true;
4146
+ }
4147
+ return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
4148
+ (object != null && value in Object(object));
4149
+ }
4150
+
4151
+ /* Built-in method references that are verified to be native. */
4152
+ var nativeCreate = getNative(Object, 'create');
4153
+
4154
+ /**
4155
+ * Removes all key-value entries from the hash.
4156
+ *
4157
+ * @private
4158
+ * @name clear
4159
+ * @memberOf Hash
4160
+ */
4161
+ function hashClear() {
4162
+ this.__data__ = nativeCreate ? nativeCreate(null) : {};
4163
+ this.size = 0;
4164
+ }
4165
+
4166
+ /**
4167
+ * Removes `key` and its value from the hash.
4168
+ *
4169
+ * @private
4170
+ * @name delete
4171
+ * @memberOf Hash
4172
+ * @param {Object} hash The hash to modify.
4173
+ * @param {string} key The key of the value to remove.
4174
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4175
+ */
4176
+ function hashDelete(key) {
4177
+ var result = this.has(key) && delete this.__data__[key];
4178
+ this.size -= result ? 1 : 0;
4179
+ return result;
4180
+ }
4181
+
4182
+ /** Used to stand-in for `undefined` hash values. */
4183
+ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
4184
+
4185
+ /** Used for built-in method references. */
4186
+ var objectProto$1 = Object.prototype;
4187
+
4188
+ /** Used to check objects for own properties. */
4189
+ var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
4190
+
4191
+ /**
4192
+ * Gets the hash value for `key`.
4193
+ *
4194
+ * @private
4195
+ * @name get
4196
+ * @memberOf Hash
4197
+ * @param {string} key The key of the value to get.
4198
+ * @returns {*} Returns the entry value.
4199
+ */
4200
+ function hashGet(key) {
4201
+ var data = this.__data__;
4202
+ if (nativeCreate) {
4203
+ var result = data[key];
4204
+ return result === HASH_UNDEFINED$1 ? undefined : result;
4205
+ }
4206
+ return hasOwnProperty$1.call(data, key) ? data[key] : undefined;
4207
+ }
4208
+
4209
+ /** Used for built-in method references. */
4210
+ var objectProto = Object.prototype;
4211
+
4212
+ /** Used to check objects for own properties. */
4213
+ var hasOwnProperty = objectProto.hasOwnProperty;
4214
+
4215
+ /**
4216
+ * Checks if a hash value for `key` exists.
4217
+ *
4218
+ * @private
4219
+ * @name has
4220
+ * @memberOf Hash
4221
+ * @param {string} key The key of the entry to check.
4222
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4223
+ */
4224
+ function hashHas(key) {
4225
+ var data = this.__data__;
4226
+ return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
4227
+ }
4228
+
4229
+ /** Used to stand-in for `undefined` hash values. */
4230
+ var HASH_UNDEFINED = '__lodash_hash_undefined__';
4231
+
4232
+ /**
4233
+ * Sets the hash `key` to `value`.
4234
+ *
4235
+ * @private
4236
+ * @name set
4237
+ * @memberOf Hash
4238
+ * @param {string} key The key of the value to set.
4239
+ * @param {*} value The value to set.
4240
+ * @returns {Object} Returns the hash instance.
4241
+ */
4242
+ function hashSet(key, value) {
4243
+ var data = this.__data__;
4244
+ this.size += this.has(key) ? 0 : 1;
4245
+ data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
4246
+ return this;
4247
+ }
4248
+
4249
+ /**
4250
+ * Creates a hash object.
4251
+ *
4252
+ * @private
4253
+ * @constructor
4254
+ * @param {Array} [entries] The key-value pairs to cache.
4255
+ */
4256
+ function Hash(entries) {
4257
+ var index = -1,
4258
+ length = entries == null ? 0 : entries.length;
4259
+
4260
+ this.clear();
4261
+ while (++index < length) {
4262
+ var entry = entries[index];
4263
+ this.set(entry[0], entry[1]);
4264
+ }
4265
+ }
4266
+
4267
+ // Add methods to `Hash`.
4268
+ Hash.prototype.clear = hashClear;
4269
+ Hash.prototype['delete'] = hashDelete;
4270
+ Hash.prototype.get = hashGet;
4271
+ Hash.prototype.has = hashHas;
4272
+ Hash.prototype.set = hashSet;
4273
+
4274
+ /**
4275
+ * Removes all key-value entries from the list cache.
4276
+ *
4277
+ * @private
4278
+ * @name clear
4279
+ * @memberOf ListCache
4280
+ */
4281
+ function listCacheClear() {
4282
+ this.__data__ = [];
4283
+ this.size = 0;
4284
+ }
4285
+
4286
+ /**
4287
+ * Gets the index at which the `key` is found in `array` of key-value pairs.
4288
+ *
4289
+ * @private
4290
+ * @param {Array} array The array to inspect.
4291
+ * @param {*} key The key to search for.
4292
+ * @returns {number} Returns the index of the matched value, else `-1`.
4293
+ */
4294
+ function assocIndexOf(array, key) {
4295
+ var length = array.length;
4296
+ while (length--) {
4297
+ if (eq(array[length][0], key)) {
4298
+ return length;
4299
+ }
4300
+ }
4301
+ return -1;
4302
+ }
4303
+
4304
+ /** Used for built-in method references. */
4305
+ var arrayProto = Array.prototype;
4306
+
4307
+ /** Built-in value references. */
4308
+ var splice = arrayProto.splice;
4309
+
4310
+ /**
4311
+ * Removes `key` and its value from the list cache.
4312
+ *
4313
+ * @private
4314
+ * @name delete
4315
+ * @memberOf ListCache
4316
+ * @param {string} key The key of the value to remove.
4317
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4318
+ */
4319
+ function listCacheDelete(key) {
4320
+ var data = this.__data__,
4321
+ index = assocIndexOf(data, key);
4322
+
4323
+ if (index < 0) {
4324
+ return false;
4325
+ }
4326
+ var lastIndex = data.length - 1;
4327
+ if (index == lastIndex) {
4328
+ data.pop();
4329
+ } else {
4330
+ splice.call(data, index, 1);
4331
+ }
4332
+ --this.size;
4333
+ return true;
4334
+ }
4335
+
4336
+ /**
4337
+ * Gets the list cache value for `key`.
4338
+ *
4339
+ * @private
4340
+ * @name get
4341
+ * @memberOf ListCache
4342
+ * @param {string} key The key of the value to get.
4343
+ * @returns {*} Returns the entry value.
4344
+ */
4345
+ function listCacheGet(key) {
4346
+ var data = this.__data__,
4347
+ index = assocIndexOf(data, key);
4348
+
4349
+ return index < 0 ? undefined : data[index][1];
4350
+ }
4351
+
4352
+ /**
4353
+ * Checks if a list cache value for `key` exists.
4354
+ *
4355
+ * @private
4356
+ * @name has
4357
+ * @memberOf ListCache
4358
+ * @param {string} key The key of the entry to check.
4359
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4360
+ */
4361
+ function listCacheHas(key) {
4362
+ return assocIndexOf(this.__data__, key) > -1;
4363
+ }
4364
+
4365
+ /**
4366
+ * Sets the list cache `key` to `value`.
4367
+ *
4368
+ * @private
4369
+ * @name set
4370
+ * @memberOf ListCache
4371
+ * @param {string} key The key of the value to set.
4372
+ * @param {*} value The value to set.
4373
+ * @returns {Object} Returns the list cache instance.
4374
+ */
4375
+ function listCacheSet(key, value) {
4376
+ var data = this.__data__,
4377
+ index = assocIndexOf(data, key);
4378
+
4379
+ if (index < 0) {
4380
+ ++this.size;
4381
+ data.push([key, value]);
4382
+ } else {
4383
+ data[index][1] = value;
4384
+ }
4385
+ return this;
4386
+ }
4387
+
4388
+ /**
4389
+ * Creates an list cache object.
4390
+ *
4391
+ * @private
4392
+ * @constructor
4393
+ * @param {Array} [entries] The key-value pairs to cache.
4394
+ */
4395
+ function ListCache(entries) {
4396
+ var index = -1,
4397
+ length = entries == null ? 0 : entries.length;
4398
+
4399
+ this.clear();
4400
+ while (++index < length) {
4401
+ var entry = entries[index];
4402
+ this.set(entry[0], entry[1]);
4403
+ }
4404
+ }
4405
+
4406
+ // Add methods to `ListCache`.
4407
+ ListCache.prototype.clear = listCacheClear;
4408
+ ListCache.prototype['delete'] = listCacheDelete;
4409
+ ListCache.prototype.get = listCacheGet;
4410
+ ListCache.prototype.has = listCacheHas;
4411
+ ListCache.prototype.set = listCacheSet;
4412
+
4413
+ /* Built-in method references that are verified to be native. */
4414
+ var Map$1 = getNative(root, 'Map');
4415
+
4416
+ /**
4417
+ * Removes all key-value entries from the map.
4418
+ *
4419
+ * @private
4420
+ * @name clear
4421
+ * @memberOf MapCache
4422
+ */
4423
+ function mapCacheClear() {
4424
+ this.size = 0;
4425
+ this.__data__ = {
4426
+ 'hash': new Hash,
4427
+ 'map': new (Map$1 || ListCache),
4428
+ 'string': new Hash
4429
+ };
4430
+ }
4431
+
4432
+ /**
4433
+ * Checks if `value` is suitable for use as unique object key.
4434
+ *
4435
+ * @private
4436
+ * @param {*} value The value to check.
4437
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
4438
+ */
4439
+ function isKeyable(value) {
4440
+ var type = typeof value;
4441
+ return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
4442
+ ? (value !== '__proto__')
4443
+ : (value === null);
4444
+ }
4445
+
4446
+ /**
4447
+ * Gets the data for `map`.
4448
+ *
4449
+ * @private
4450
+ * @param {Object} map The map to query.
4451
+ * @param {string} key The reference key.
4452
+ * @returns {*} Returns the map data.
4453
+ */
4454
+ function getMapData(map, key) {
4455
+ var data = map.__data__;
4456
+ return isKeyable(key)
4457
+ ? data[typeof key == 'string' ? 'string' : 'hash']
4458
+ : data.map;
4459
+ }
4460
+
4461
+ /**
4462
+ * Removes `key` and its value from the map.
4463
+ *
4464
+ * @private
4465
+ * @name delete
4466
+ * @memberOf MapCache
4467
+ * @param {string} key The key of the value to remove.
4468
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4469
+ */
4470
+ function mapCacheDelete(key) {
4471
+ var result = getMapData(this, key)['delete'](key);
4472
+ this.size -= result ? 1 : 0;
4473
+ return result;
4474
+ }
4475
+
4476
+ /**
4477
+ * Gets the map value for `key`.
4478
+ *
4479
+ * @private
4480
+ * @name get
4481
+ * @memberOf MapCache
4482
+ * @param {string} key The key of the value to get.
4483
+ * @returns {*} Returns the entry value.
4484
+ */
4485
+ function mapCacheGet(key) {
4486
+ return getMapData(this, key).get(key);
4487
+ }
4488
+
4489
+ /**
4490
+ * Checks if a map value for `key` exists.
4491
+ *
4492
+ * @private
4493
+ * @name has
4494
+ * @memberOf MapCache
4495
+ * @param {string} key The key of the entry to check.
4496
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4497
+ */
4498
+ function mapCacheHas(key) {
4499
+ return getMapData(this, key).has(key);
4500
+ }
4501
+
4502
+ /**
4503
+ * Sets the map `key` to `value`.
4504
+ *
4505
+ * @private
4506
+ * @name set
4507
+ * @memberOf MapCache
4508
+ * @param {string} key The key of the value to set.
4509
+ * @param {*} value The value to set.
4510
+ * @returns {Object} Returns the map cache instance.
4511
+ */
4512
+ function mapCacheSet(key, value) {
4513
+ var data = getMapData(this, key),
4514
+ size = data.size;
4515
+
4516
+ data.set(key, value);
4517
+ this.size += data.size == size ? 0 : 1;
4518
+ return this;
4519
+ }
4520
+
4521
+ /**
4522
+ * Creates a map cache object to store key-value pairs.
4523
+ *
4524
+ * @private
4525
+ * @constructor
4526
+ * @param {Array} [entries] The key-value pairs to cache.
4527
+ */
4528
+ function MapCache(entries) {
4529
+ var index = -1,
4530
+ length = entries == null ? 0 : entries.length;
4531
+
4532
+ this.clear();
4533
+ while (++index < length) {
4534
+ var entry = entries[index];
4535
+ this.set(entry[0], entry[1]);
4536
+ }
4537
+ }
4538
+
4539
+ // Add methods to `MapCache`.
4540
+ MapCache.prototype.clear = mapCacheClear;
4541
+ MapCache.prototype['delete'] = mapCacheDelete;
4542
+ MapCache.prototype.get = mapCacheGet;
4543
+ MapCache.prototype.has = mapCacheHas;
4544
+ MapCache.prototype.set = mapCacheSet;
4545
+
4546
+ /** Error message constants. */
4547
+ var FUNC_ERROR_TEXT = 'Expected a function';
4548
+
4549
+ /**
4550
+ * Creates a function that memoizes the result of `func`. If `resolver` is
4551
+ * provided, it determines the cache key for storing the result based on the
4552
+ * arguments provided to the memoized function. By default, the first argument
4553
+ * provided to the memoized function is used as the map cache key. The `func`
4554
+ * is invoked with the `this` binding of the memoized function.
4555
+ *
4556
+ * **Note:** The cache is exposed as the `cache` property on the memoized
4557
+ * function. Its creation may be customized by replacing the `_.memoize.Cache`
4558
+ * constructor with one whose instances implement the
4559
+ * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
4560
+ * method interface of `clear`, `delete`, `get`, `has`, and `set`.
4561
+ *
4562
+ * @static
4563
+ * @memberOf _
4564
+ * @since 0.1.0
4565
+ * @category Function
4566
+ * @param {Function} func The function to have its output memoized.
4567
+ * @param {Function} [resolver] The function to resolve the cache key.
4568
+ * @returns {Function} Returns the new memoized function.
4569
+ * @example
4570
+ *
4571
+ * var object = { 'a': 1, 'b': 2 };
4572
+ * var other = { 'c': 3, 'd': 4 };
4573
+ *
4574
+ * var values = _.memoize(_.values);
4575
+ * values(object);
4576
+ * // => [1, 2]
4577
+ *
4578
+ * values(other);
4579
+ * // => [3, 4]
4580
+ *
4581
+ * object.a = 2;
4582
+ * values(object);
4583
+ * // => [1, 2]
4584
+ *
4585
+ * // Modify the result cache.
4586
+ * values.cache.set(object, ['a', 'b']);
4587
+ * values(object);
4588
+ * // => ['a', 'b']
4589
+ *
4590
+ * // Replace `_.memoize.Cache`.
4591
+ * _.memoize.Cache = WeakMap;
4592
+ */
4593
+ function memoize(func, resolver) {
4594
+ if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
4595
+ throw new TypeError(FUNC_ERROR_TEXT);
4596
+ }
4597
+ var memoized = function() {
4598
+ var args = arguments,
4599
+ key = resolver ? resolver.apply(this, args) : args[0],
4600
+ cache = memoized.cache;
4601
+
4602
+ if (cache.has(key)) {
4603
+ return cache.get(key);
4604
+ }
4605
+ var result = func.apply(this, args);
4606
+ memoized.cache = cache.set(key, result) || cache;
4607
+ return result;
4608
+ };
4609
+ memoized.cache = new (memoize.Cache || MapCache);
4610
+ return memoized;
4611
+ }
4612
+
4613
+ // Expose `MapCache`.
4614
+ memoize.Cache = MapCache;
4615
+
4616
+ /** Used as the maximum memoize cache size. */
4617
+ var MAX_MEMOIZE_SIZE = 500;
4618
+
4619
+ /**
4620
+ * A specialized version of `_.memoize` which clears the memoized function's
4621
+ * cache when it exceeds `MAX_MEMOIZE_SIZE`.
4622
+ *
4623
+ * @private
4624
+ * @param {Function} func The function to have its output memoized.
4625
+ * @returns {Function} Returns the new memoized function.
4626
+ */
4627
+ function memoizeCapped(func) {
4628
+ var result = memoize(func, function(key) {
4629
+ if (cache.size === MAX_MEMOIZE_SIZE) {
4630
+ cache.clear();
4631
+ }
4632
+ return key;
4633
+ });
4634
+
4635
+ var cache = result.cache;
4636
+ return result;
4637
+ }
4638
+
4639
+ /** Used to match property names within property paths. */
4640
+ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
4641
+
4642
+ /** Used to match backslashes in property paths. */
4643
+ var reEscapeChar = /\\(\\)?/g;
4644
+
4645
+ /**
4646
+ * Converts `string` to a property path array.
4647
+ *
4648
+ * @private
4649
+ * @param {string} string The string to convert.
4650
+ * @returns {Array} Returns the property path array.
4651
+ */
4652
+ var stringToPath = memoizeCapped(function(string) {
4653
+ var result = [];
4654
+ if (string.charCodeAt(0) === 46 /* . */) {
4655
+ result.push('');
4656
+ }
4657
+ string.replace(rePropName, function(match, number, quote, subString) {
4658
+ result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
4659
+ });
4660
+ return result;
4661
+ });
4662
+
4663
+ /**
4664
+ * Converts `value` to a string. An empty string is returned for `null`
4665
+ * and `undefined` values. The sign of `-0` is preserved.
4666
+ *
4667
+ * @static
4668
+ * @memberOf _
4669
+ * @since 4.0.0
4670
+ * @category Lang
4671
+ * @param {*} value The value to convert.
4672
+ * @returns {string} Returns the converted string.
4673
+ * @example
4674
+ *
4675
+ * _.toString(null);
4676
+ * // => ''
4677
+ *
4678
+ * _.toString(-0);
4679
+ * // => '-0'
4680
+ *
4681
+ * _.toString([1, 2, 3]);
4682
+ * // => '1,2,3'
4683
+ */
4684
+ function toString(value) {
4685
+ return value == null ? '' : baseToString(value);
4686
+ }
4687
+
4688
+ /**
4689
+ * Casts `value` to a path array if it's not one.
4690
+ *
4691
+ * @private
4692
+ * @param {*} value The value to inspect.
4693
+ * @param {Object} [object] The object to query keys on.
4694
+ * @returns {Array} Returns the cast property path array.
4695
+ */
4696
+ function castPath(value, object) {
4697
+ if (isArray(value)) {
4698
+ return value;
4699
+ }
4700
+ return isKey(value, object) ? [value] : stringToPath(toString(value));
4701
+ }
4702
+
4703
+ /**
4704
+ * Converts `value` to a string key if it's not a string or symbol.
4705
+ *
4706
+ * @private
4707
+ * @param {*} value The value to inspect.
4708
+ * @returns {string|symbol} Returns the key.
4709
+ */
4710
+ function toKey(value) {
4711
+ if (typeof value == 'string' || isSymbol(value)) {
4712
+ return value;
4713
+ }
4714
+ var result = (value + '');
4715
+ return (result == '0' && (1 / value) == -Infinity) ? '-0' : result;
4716
+ }
4717
+
4718
+ /**
4719
+ * The base implementation of `_.get` without support for default values.
4720
+ *
4721
+ * @private
4722
+ * @param {Object} object The object to query.
4723
+ * @param {Array|string} path The path of the property to get.
4724
+ * @returns {*} Returns the resolved value.
4725
+ */
4726
+ function baseGet(object, path) {
4727
+ path = castPath(path, object);
4728
+
4729
+ var index = 0,
4730
+ length = path.length;
4731
+
4732
+ while (object != null && index < length) {
4733
+ object = object[toKey(path[index++])];
4734
+ }
4735
+ return (index && index == length) ? object : undefined;
4736
+ }
4737
+
4738
+ /**
4739
+ * Gets the value at `path` of `object`. If the resolved value is
4740
+ * `undefined`, the `defaultValue` is returned in its place.
4741
+ *
4742
+ * @static
4743
+ * @memberOf _
4744
+ * @since 3.7.0
4745
+ * @category Object
4746
+ * @param {Object} object The object to query.
4747
+ * @param {Array|string} path The path of the property to get.
4748
+ * @param {*} [defaultValue] The value returned for `undefined` resolved values.
4749
+ * @returns {*} Returns the resolved value.
4750
+ * @example
4751
+ *
4752
+ * var object = { 'a': [{ 'b': { 'c': 3 } }] };
4753
+ *
4754
+ * _.get(object, 'a[0].b.c');
4755
+ * // => 3
4756
+ *
4757
+ * _.get(object, ['a', '0', 'b', 'c']);
4758
+ * // => 3
4759
+ *
4760
+ * _.get(object, 'a.b.c', 'default');
4761
+ * // => 'default'
4762
+ */
4763
+ function get(object, path, defaultValue) {
4764
+ var result = object == null ? undefined : baseGet(object, path);
4765
+ return result === undefined ? defaultValue : result;
4766
+ }
4767
+
4768
+ const pickValue = ['path', 'key', 'id', 'description', 'type', 'validator', 'middleware'];
4769
+ class Route {
4770
+ /**
4771
+ * 一级路径
4772
+ */
4773
+ path;
4774
+ /**
4775
+ * 二级路径
4776
+ */
4777
+ key;
4778
+ id;
4779
+ share = false;
4780
+ run;
4781
+ nextRoute; // route to run after this route
4782
+ description;
4783
+ metadata;
4784
+ middleware; // middleware
4785
+ type = 'route';
4786
+ _validator;
4787
+ schema;
4788
+ data;
4789
+ /**
4790
+ * 是否需要验证
4791
+ */
4792
+ isVerify;
4793
+ /**
4794
+ * 是否开启debug,开启后会打印错误信息
4795
+ */
4796
+ isDebug;
4797
+ constructor(path, key = '', opts) {
4798
+ path = path.trim();
4799
+ key = key.trim();
4800
+ this.path = path;
4801
+ this.key = key;
4802
+ if (opts) {
4803
+ this.id = opts.id || nanoid$1();
4804
+ if (!opts.id && opts.idUsePath) {
4805
+ const delimiter = opts.delimiter ?? '$#$';
4806
+ this.id = path + delimiter + key;
4807
+ }
4808
+ this.run = opts.run;
4809
+ this.nextRoute = opts.nextRoute;
4810
+ this.description = opts.description;
4811
+ this.metadata = opts.metadata;
4812
+ this.type = opts.type || 'route';
4813
+ this.validator = opts.validator;
4814
+ this.middleware = opts.middleware || [];
4815
+ this.key = opts.key || key;
4816
+ this.path = opts.path || path;
4817
+ this.isVerify = opts.isVerify ?? true;
4818
+ this.createSchema();
4819
+ }
4820
+ else {
4821
+ this.isVerify = true;
4822
+ this.middleware = [];
4823
+ this.id = nanoid$1();
4824
+ }
4825
+ this.isDebug = opts?.isDebug ?? false;
4826
+ }
4827
+ createSchema() {
4828
+ try {
4829
+ const validator = this.validator;
4830
+ const keys = Object.keys(validator || {});
4831
+ const schemaList = keys.map((key) => {
4832
+ return { [key]: createSchema(validator[key]) };
4833
+ });
4834
+ const schema = schemaList.reduce((prev, current) => {
4835
+ return { ...prev, ...current };
4836
+ }, {});
4837
+ this.schema = schema;
4838
+ }
4839
+ catch (e) {
4840
+ console.error('createSchema error:', e);
4841
+ }
4842
+ }
4843
+ /**
4844
+ * set validator and create schema
4845
+ * @param validator
4846
+ */
4847
+ set validator(validator) {
4848
+ this._validator = validator;
4849
+ this.createSchema();
4850
+ }
4851
+ get validator() {
4852
+ return this._validator || {};
4853
+ }
4854
+ /**
4855
+ * has code, body, message in ctx, return ctx if has error
4856
+ * @param ctx
4857
+ * @param dev
4858
+ * @returns
4859
+ */
4860
+ verify(ctx, dev = false) {
4861
+ const query = ctx.query || {};
4862
+ const schema = this.schema || {};
4863
+ const validator = this.validator;
4864
+ const check = () => {
4865
+ const queryKeys = Object.keys(validator);
4866
+ for (let i = 0; i < queryKeys.length; i++) {
4867
+ const key = queryKeys[i];
4868
+ const value = query[key];
4869
+ if (schema[key]) {
4870
+ const result = schema[key].safeParse(value);
4871
+ if (!result.success) {
4872
+ const path = result.error.errors[0]?.path?.join?.('.properties.');
4873
+ let message = 'Invalid params';
4874
+ if (path) {
4875
+ const keyS = `${key}.properties.${path}.message`;
4876
+ message = get(validator, keyS, 'Invalid params');
4877
+ }
4878
+ throw new CustomError(500, message);
3611
4879
  }
3612
4880
  }
3613
4881
  }
@@ -4130,6 +5398,70 @@ class QueryRouterServer extends QueryRouter {
4130
5398
  }
4131
5399
  }
4132
5400
 
5401
+ class Connect {
5402
+ path;
5403
+ key;
5404
+ _fn;
5405
+ description;
5406
+ connects;
5407
+ share = false;
5408
+ constructor(path) {
5409
+ this.path = path;
5410
+ this.key = nanoid$1();
5411
+ }
5412
+ use(path) {
5413
+ this.connects.push({ path });
5414
+ }
5415
+ useList(paths) {
5416
+ paths.forEach((path) => {
5417
+ this.connects.push({ path });
5418
+ });
5419
+ }
5420
+ useConnect(connect) {
5421
+ this.connects.push({ path: connect.path, key: connect.key });
5422
+ }
5423
+ useConnectList(connects) {
5424
+ connects.forEach((connect) => {
5425
+ this.connects.push({ path: connect.path, key: connect.key });
5426
+ });
5427
+ }
5428
+ getPathList() {
5429
+ return this.connects.map((c) => c.path).filter(Boolean);
5430
+ }
5431
+ set fn(fn) {
5432
+ this._fn = fn;
5433
+ }
5434
+ get fn() {
5435
+ return this._fn;
5436
+ }
5437
+ }
5438
+ class QueryConnect {
5439
+ connects;
5440
+ constructor() {
5441
+ this.connects = [];
5442
+ }
5443
+ add(connect) {
5444
+ const has = this.connects.find((c) => c.path === connect.path && c.key === connect.key);
5445
+ if (has) {
5446
+ // remove the old connect
5447
+ console.log('[replace connect]:', connect.path, connect.key);
5448
+ this.connects = this.connects.filter((c) => c.path !== connect.path && c.key !== connect.key);
5449
+ }
5450
+ this.connects.push(connect);
5451
+ }
5452
+ remove(connect) {
5453
+ this.connects = this.connects.filter((c) => c.path !== connect.path && c.key !== connect.key);
5454
+ }
5455
+ getList() {
5456
+ return this.connects.map((c) => {
5457
+ return {
5458
+ path: c.path,
5459
+ key: c.key,
5460
+ };
5461
+ });
5462
+ }
5463
+ }
5464
+
4133
5465
  const parseBody = async (req) => {
4134
5466
  return new Promise((resolve, reject) => {
4135
5467
  const arr = [];
@@ -9595,9 +10927,10 @@ var websocketServerExports = requireWebsocketServer();
9595
10927
  var WebSocketServer = /*@__PURE__*/getDefaultExportFromCjs(websocketServerExports);
9596
10928
 
9597
10929
  const parseIfJson = (input) => {
10930
+ const str = typeof input === 'string' ? input : input.toString();
9598
10931
  try {
9599
10932
  // 尝试解析 JSON
9600
- const parsed = JSON.parse(input);
10933
+ const parsed = JSON.parse(str);
9601
10934
  // 检查解析结果是否为对象(数组或普通对象)
9602
10935
  if (typeof parsed === 'object' && parsed !== null) {
9603
10936
  return parsed;
@@ -9606,7 +10939,7 @@ const parseIfJson = (input) => {
9606
10939
  catch (e) {
9607
10940
  // 如果解析失败,直接返回原始字符串
9608
10941
  }
9609
- return input;
10942
+ return str;
9610
10943
  };
9611
10944
 
9612
10945
  // @ts-type=ws
@@ -9635,7 +10968,8 @@ class WsServerBase {
9635
10968
  ws.on('message', async (message) => {
9636
10969
  const data = parseIfJson(message);
9637
10970
  if (typeof data === 'string') {
9638
- ws.emit('string', data);
10971
+ const cleanMessage = data.trim().replace(/^["']|["']$/g, '');
10972
+ ws.emit('string', cleanMessage);
9639
10973
  return;
9640
10974
  }
9641
10975
  const { type, data: typeData, ...rest } = data;
@@ -9671,7 +11005,7 @@ class WsServerBase {
9671
11005
  if (message === 'close') {
9672
11006
  ws.close();
9673
11007
  }
9674
- if (message === 'ping') {
11008
+ if (message == 'ping') {
9675
11009
  ws.send('pong');
9676
11010
  }
9677
11011
  });
@@ -9965,4 +11299,4 @@ class App {
9965
11299
  }
9966
11300
  }
9967
11301
 
9968
- export { App, CustomError, QueryRouter, QueryRouterServer, QueryUtil, Route, Server, createSchema, define, handleServer, util };
11302
+ export { App, Connect, CustomError, QueryConnect, QueryRouter, QueryRouterServer, QueryUtil, Route, Server, createSchema, define, handleServer, util };