arktype 2.2.10 → 3.0.0-beta.1

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.
Files changed (164) hide show
  1. package/README.md +181 -15
  2. package/out/attributes.d.ts +50 -14
  3. package/out/checkers.d.ts +172 -0
  4. package/out/chunk-2U2AWCI3.js +626 -0
  5. package/out/chunk-4CUA5XIP.js +7 -0
  6. package/out/chunk-5U2ZMDNI.js +1566 -0
  7. package/out/chunk-DLWCO4RV.js +18 -0
  8. package/out/chunk-E3DZXEZK.js +72 -0
  9. package/out/chunk-EVCML554.js +47 -0
  10. package/out/chunk-G45P2CLE.js +63 -0
  11. package/out/chunk-GPNK5353.js +2529 -0
  12. package/out/chunk-MLKGABMK.js +9 -0
  13. package/out/chunk-NRIGTMPM.js +7 -0
  14. package/out/chunk-PRTMQCHS.js +3 -0
  15. package/out/chunk-R5G57XC7.js +7 -0
  16. package/out/chunk-RAZ3TXOE.js +313 -0
  17. package/out/chunk-SWOOCAHN.js +4 -0
  18. package/out/chunk-TAHPKDNM.js +3 -0
  19. package/out/chunk-UETB6YE2.js +14 -0
  20. package/out/chunk-UK5UGFOX.js +254 -0
  21. package/out/chunk-VV6YDN2D.js +6118 -0
  22. package/out/codecs.d.ts +21 -0
  23. package/out/codecs.js +7 -0
  24. package/out/config.d.ts +8 -3
  25. package/out/config.js +2 -3
  26. package/out/declare.d.ts +17 -3
  27. package/out/deferred.d.ts +10 -0
  28. package/out/errors.d.ts +1 -0
  29. package/out/errors.js +2 -0
  30. package/out/fn.d.ts +1 -1
  31. package/out/generic.d.ts +3 -3
  32. package/out/i18n.d.ts +2 -0
  33. package/out/i18n.js +2 -0
  34. package/out/index.d.ts +5 -4
  35. package/out/index.js +8 -9
  36. package/out/internal.d.ts +70 -0
  37. package/out/internal.js +17 -0
  38. package/out/island.d.ts +2 -0
  39. package/out/island.js +6 -0
  40. package/out/islandDependency.d.ts +2 -0
  41. package/out/islandDependency.js +18 -0
  42. package/out/keywords/Array.d.ts +2 -2
  43. package/out/keywords/builtins.d.ts +5 -3
  44. package/out/keywords/constructors.d.ts +9 -1
  45. package/out/keywords/functions.d.ts +254 -0
  46. package/out/keywords/keywords.d.ts +8 -9
  47. package/out/keywords/number.d.ts +2 -8
  48. package/out/keywords/phrases.d.ts +245 -0
  49. package/out/keywords/string.d.ts +14 -113
  50. package/out/keywords/ts.d.ts +35 -33
  51. package/out/keywords/ts.js +4 -82
  52. package/out/locale.d.ts +19 -0
  53. package/out/locales/de.d.ts +2 -0
  54. package/out/locales/de.js +2 -0
  55. package/out/locales/en.d.ts +4 -0
  56. package/out/locales/en.js +5 -0
  57. package/out/match.d.ts +6 -6
  58. package/out/module.d.ts +1 -1
  59. package/out/mutatesInput.js +3 -0
  60. package/out/parser/ast/generic.d.ts +6 -3
  61. package/out/parser/ast/infer.d.ts +1 -1
  62. package/out/parser/ast/validate.d.ts +11 -6
  63. package/out/parser/definition.d.ts +68 -7
  64. package/out/parser/objectLiteral.d.ts +40 -12
  65. package/out/parser/property.d.ts +3 -5
  66. package/out/parser/reduce/dynamic.d.ts +16 -7
  67. package/out/parser/reduce/shared.d.ts +4 -0
  68. package/out/parser/reduce/static.d.ts +13 -13
  69. package/out/parser/shift/operand/date.d.ts +0 -5
  70. package/out/parser/shift/operand/operand.d.ts +2 -1
  71. package/out/parser/shift/operand/unenclosed.d.ts +9 -6
  72. package/out/parser/shift/operand/unresolvable.d.ts +68 -0
  73. package/out/parser/shift/operator/bounds.d.ts +9 -4
  74. package/out/parser/shift/operator/brand.d.ts +2 -2
  75. package/out/parser/shift/operator/default.d.ts +2 -2
  76. package/out/parser/shift/operator/divisor.d.ts +2 -2
  77. package/out/parser/shift/operator/operator.d.ts +1 -1
  78. package/out/parser/shift/tokens.d.ts +9 -2
  79. package/out/parser/string.d.ts +61 -7
  80. package/out/parser/tupleExpressions.d.ts +7 -3
  81. package/out/precompiled.d.ts +1 -0
  82. package/out/precompiled.js +2 -0
  83. package/out/runtime.d.ts +181 -0
  84. package/out/runtime.js +4 -0
  85. package/out/runtimeDevelopment.d.ts +1 -0
  86. package/out/runtimeDevelopment.js +133 -0
  87. package/out/runtimeExports.d.ts +1 -0
  88. package/out/scope.d.ts +40 -11
  89. package/out/standalone/artifact.d.ts +265 -0
  90. package/out/standalone/baking.d.ts +201 -0
  91. package/out/standalone/combinators.d.ts +13 -0
  92. package/out/standalone/compilers.d.ts +23 -0
  93. package/out/standalone/creators.d.ts +41 -0
  94. package/out/standalone/fallbacks.d.ts +48 -0
  95. package/out/standalone/keys.d.ts +31 -0
  96. package/out/standalone/modules.d.ts +26 -0
  97. package/out/standalone/sites.d.ts +52 -0
  98. package/out/standalone/units.d.ts +31 -0
  99. package/out/standalone/values.d.ts +60 -0
  100. package/out/standalone.d.ts +16 -0
  101. package/out/type.d.ts +45 -6
  102. package/out/variants/array.d.ts +1 -1
  103. package/out/variants/base.d.ts +47 -27
  104. package/out/variants/date.d.ts +1 -1
  105. package/out/variants/instantiate.d.ts +4 -2
  106. package/out/variants/number.d.ts +1 -1
  107. package/out/variants/object.d.ts +17 -12
  108. package/out/variants/string.d.ts +1 -1
  109. package/package.json +169 -8
  110. package/skills/arktype/SKILL.md +278 -43
  111. package/skills/arktype/references/migrating.md +1296 -0
  112. package/skills/arktype/references/precompile.md +191 -0
  113. package/out/attributes.js +0 -3
  114. package/out/fn.js +0 -58
  115. package/out/generic.js +0 -37
  116. package/out/keywords/Array.js +0 -21
  117. package/out/keywords/FormData.js +0 -40
  118. package/out/keywords/TypedArray.js +0 -16
  119. package/out/keywords/builtins.js +0 -11
  120. package/out/keywords/constructors.js +0 -16
  121. package/out/keywords/keywords.js +0 -48
  122. package/out/keywords/number.js +0 -49
  123. package/out/keywords/string.js +0 -467
  124. package/out/match.js +0 -95
  125. package/out/module.js +0 -3
  126. package/out/nary.js +0 -1
  127. package/out/parser/ast/bounds.js +0 -1
  128. package/out/parser/ast/default.js +0 -1
  129. package/out/parser/ast/divisor.js +0 -1
  130. package/out/parser/ast/generic.js +0 -1
  131. package/out/parser/ast/infer.js +0 -1
  132. package/out/parser/ast/keyof.js +0 -1
  133. package/out/parser/ast/utils.js +0 -1
  134. package/out/parser/ast/validate.js +0 -3
  135. package/out/parser/definition.js +0 -78
  136. package/out/parser/objectLiteral.js +0 -113
  137. package/out/parser/property.js +0 -16
  138. package/out/parser/reduce/dynamic.js +0 -153
  139. package/out/parser/reduce/shared.js +0 -25
  140. package/out/parser/reduce/static.js +0 -1
  141. package/out/parser/shift/operand/date.js +0 -23
  142. package/out/parser/shift/operand/enclosed.js +0 -82
  143. package/out/parser/shift/operand/genericArgs.js +0 -16
  144. package/out/parser/shift/operand/operand.js +0 -16
  145. package/out/parser/shift/operand/unenclosed.js +0 -59
  146. package/out/parser/shift/operator/bounds.js +0 -91
  147. package/out/parser/shift/operator/brand.js +0 -6
  148. package/out/parser/shift/operator/default.js +0 -29
  149. package/out/parser/shift/operator/divisor.js +0 -13
  150. package/out/parser/shift/operator/operator.js +0 -28
  151. package/out/parser/shift/tokens.js +0 -37
  152. package/out/parser/string.js +0 -42
  153. package/out/parser/tupleExpressions.js +0 -75
  154. package/out/parser/tupleLiteral.js +0 -128
  155. package/out/scope.js +0 -106
  156. package/out/type.js +0 -55
  157. package/out/variants/array.js +0 -1
  158. package/out/variants/base.js +0 -1
  159. package/out/variants/date.js +0 -1
  160. package/out/variants/instantiate.js +0 -1
  161. package/out/variants/number.js +0 -1
  162. package/out/variants/object.js +0 -1
  163. package/out/variants/string.js +0 -1
  164. /package/out/{declare.js → mutatesInput.d.ts} +0 -0
@@ -1,467 +0,0 @@
1
- import { ArkErrors, intrinsic, node, rootSchema } from "@ark/schema";
2
- import { flatMorph, numericStringMatcher, wellFormedIntegerMatcher } from "@ark/util";
3
- import { Scope } from "../scope.js";
4
- import { number } from "./number.js";
5
- // non-trivial expressions should have an explanation or attribution
6
- export const regexStringNode = (regex, description, jsonSchemaFormat) => {
7
- const schema = {
8
- domain: "string",
9
- pattern: {
10
- rule: regex.source,
11
- flags: regex.flags,
12
- meta: description
13
- }
14
- };
15
- if (jsonSchemaFormat)
16
- schema.meta = { format: jsonSchemaFormat };
17
- return node("intersection", schema);
18
- };
19
- const stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher, "a well-formed integer string");
20
- export const stringInteger = Scope.module({
21
- root: stringIntegerRoot,
22
- parse: rootSchema({
23
- in: stringIntegerRoot,
24
- morphs: (s, ctx) => {
25
- const parsed = Number.parseInt(s);
26
- return Number.isSafeInteger(parsed) ? parsed : (ctx.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER"));
27
- },
28
- declaredOut: intrinsic.integer
29
- })
30
- }, {
31
- name: "string.integer"
32
- });
33
- const hex = regexStringNode(/^[\dA-Fa-f]+$/, "hex characters only");
34
- const base58 = regexStringNode(/^[1-9A-HJ-NP-Za-km-z]+$/, "base58-encoded");
35
- const base64 = Scope.module({
36
- root: regexStringNode(/^(?:[\d+/A-Za-z]{4})*(?:[\d+/A-Za-z]{2}==|[\d+/A-Za-z]{3}=)?$/, "base64-encoded"),
37
- url: regexStringNode(/^(?:[\w-]{4})*(?:[\w-]{2}(?:==|%3D%3D)?|[\w-]{3}(?:=|%3D)?)?$/, "base64url-encoded")
38
- }, {
39
- name: "string.base64"
40
- });
41
- const preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized");
42
- export const capitalize = Scope.module({
43
- root: rootSchema({
44
- in: "string",
45
- morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1),
46
- declaredOut: preformattedCapitalize
47
- }),
48
- preformatted: preformattedCapitalize
49
- }, {
50
- name: "string.capitalize"
51
- });
52
- // https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js
53
- export const isLuhnValid = (creditCardInput) => {
54
- const sanitized = creditCardInput.replace(/[ -]+/g, "");
55
- let sum = 0;
56
- let digit;
57
- let tmpNum;
58
- let shouldDouble = false;
59
- for (let i = sanitized.length - 1; i >= 0; i--) {
60
- digit = sanitized.substring(i, i + 1);
61
- tmpNum = Number.parseInt(digit, 10);
62
- if (shouldDouble) {
63
- tmpNum *= 2;
64
- sum += tmpNum >= 10 ? (tmpNum % 10) + 1 : tmpNum;
65
- }
66
- else
67
- sum += tmpNum;
68
- shouldDouble = !shouldDouble;
69
- }
70
- return !!(sum % 10 === 0 ? sanitized : false);
71
- };
72
- // https://github.com/validatorjs/validator.js/blob/master/src/lib/isCreditCard.js
73
- const creditCardMatcher = /^(?:4\d{12}(?:\d{3,6})?|5[1-5]\d{14}|(222[1-9]|22[3-9]\d|2[3-6]\d{2}|27[01]\d|2720)\d{12}|6(?:011|5\d\d)\d{12,15}|3[47]\d{13}|3(?:0[0-5]|[68]\d)\d{11}|(?:2131|1800|35\d{3})\d{11}|6[27]\d{14}|^(81\d{14,17}))$/;
74
- export const creditCard = rootSchema({
75
- domain: "string",
76
- pattern: {
77
- meta: "a credit card number",
78
- rule: creditCardMatcher.source
79
- },
80
- predicate: {
81
- meta: "a credit card number",
82
- predicate: isLuhnValid
83
- }
84
- });
85
- const dayDelimiterMatcher = /^[./-]$/;
86
- // ISO 8601 date/time modernized from https://github.com/validatorjs/validator.js/blob/master/src/lib/isISO8601.js
87
- // Based on https://tc39.es/ecma262/#sec-date-time-string-format, the T
88
- // delimiter for date/time is mandatory. Regex from validator.js strict matcher:
89
- export const iso8601Matcher = /^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))(T((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([,.]\d+(?!:))?)?(\17[0-5]\d([,.]\d+)?)?([Zz]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
90
- const isValidDateInstance = (date) => !Number.isNaN(+date);
91
- const writeFormattedExpected = (format) => `a ${format}-formatted date`;
92
- export const tryParseDatePattern = (data, opts) => {
93
- if (!opts?.format) {
94
- const result = new Date(data);
95
- return isValidDateInstance(result) ? result : "a valid date";
96
- }
97
- if (opts.format === "iso") {
98
- return iso8601Matcher.test(data) ?
99
- new Date(data)
100
- : writeFormattedExpected("iso");
101
- }
102
- const dataParts = data.split(dayDelimiterMatcher);
103
- // will be the first delimiter matched, if there is one
104
- const delimiter = data[dataParts[0].length];
105
- const formatParts = delimiter ? opts.format.split(delimiter) : [opts.format];
106
- if (dataParts.length !== formatParts.length)
107
- return writeFormattedExpected(opts.format);
108
- const parsedParts = {};
109
- for (let i = 0; i < formatParts.length; i++) {
110
- if (dataParts[i].length !== formatParts[i].length &&
111
- // if format is "m" or "d", data is allowed to be 1 or 2 characters
112
- !(formatParts[i].length === 1 && dataParts[i].length === 2))
113
- return writeFormattedExpected(opts.format);
114
- parsedParts[formatParts[i][0]] = dataParts[i];
115
- }
116
- const date = new Date(`${parsedParts.m}/${parsedParts.d}/${parsedParts.y}`);
117
- if (`${date.getDate()}` === parsedParts.d)
118
- return date;
119
- return writeFormattedExpected(opts.format);
120
- };
121
- const isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf());
122
- const parsableDate = rootSchema({
123
- domain: "string",
124
- predicate: {
125
- meta: "a parsable date",
126
- predicate: isParsableDate
127
- }
128
- }).assertHasKind("intersection");
129
- const epochRoot = stringInteger.root.internal
130
- .narrow((s, ctx) => {
131
- // this is safe since it has already
132
- // been validated as an integer string
133
- const n = Number.parseInt(s);
134
- const out = number.epoch(n);
135
- if (out instanceof ArkErrors) {
136
- ctx.errors.merge(out);
137
- return false;
138
- }
139
- return true;
140
- })
141
- .configure({
142
- description: "an integer string representing a safe Unix timestamp"
143
- }, "self")
144
- .assertHasKind("intersection");
145
- const epoch = Scope.module({
146
- root: epochRoot,
147
- parse: rootSchema({
148
- in: epochRoot,
149
- // parse as a number so the string is treated as milliseconds
150
- // rather than passed to the Date string parser
151
- morphs: (s) => new Date(Number.parseInt(s)),
152
- declaredOut: intrinsic.Date
153
- })
154
- }, {
155
- name: "string.date.epoch"
156
- });
157
- const isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
158
- const iso = Scope.module({
159
- root: isoRoot,
160
- parse: rootSchema({
161
- in: isoRoot,
162
- morphs: (s) => new Date(s),
163
- declaredOut: intrinsic.Date
164
- })
165
- }, {
166
- name: "string.date.iso"
167
- });
168
- export const stringDate = Scope.module({
169
- root: parsableDate,
170
- parse: rootSchema({
171
- declaredIn: parsableDate,
172
- in: "string",
173
- morphs: (s, ctx) => {
174
- const date = new Date(s);
175
- if (Number.isNaN(date.valueOf()))
176
- return ctx.error("a parsable date");
177
- return date;
178
- },
179
- declaredOut: intrinsic.Date
180
- }),
181
- iso,
182
- epoch
183
- }, {
184
- name: "string.date"
185
- });
186
- const email = regexStringNode(
187
- // considered https://colinhacks.com/essays/reasonable-email-regex but it includes a lookahead
188
- // which breaks some integrations e.g. fast-check
189
- // regex based on:
190
- // https://www.regular-expressions.info/email.html
191
- /^[\w%+.-]+@[\d.A-Za-z-]+\.[A-Za-z]{2,}$/, "an email address", "email");
192
- // based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isIP.js
193
- const ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
194
- const ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`;
195
- const ipv4Matcher = new RegExp(`^${ipv4Address}$`);
196
- const ipv6Segment = "(?:[0-9a-fA-F]{1,4})";
197
- const ipv6Matcher = new RegExp("^(" +
198
- `(?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|` +
199
- `(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|` +
200
- `(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|` +
201
- `(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|` +
202
- `(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|` +
203
- `(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|` +
204
- `(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|` +
205
- `(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:))` +
206
- ")(%[0-9a-zA-Z.]{1,})?$");
207
- export const ip = Scope.module({
208
- root: ["v4 | v6", "@", "an IP address"],
209
- v4: regexStringNode(ipv4Matcher, "an IPv4 address", "ipv4"),
210
- v6: regexStringNode(ipv6Matcher, "an IPv6 address", "ipv6")
211
- }, {
212
- name: "string.ip"
213
- });
214
- const jsonStringDescription = "a JSON string";
215
- export const writeJsonSyntaxErrorProblem = (error) => {
216
- if (!(error instanceof SyntaxError))
217
- throw error;
218
- return `must be ${jsonStringDescription} (${error})`;
219
- };
220
- const jsonRoot = rootSchema({
221
- meta: jsonStringDescription,
222
- domain: "string",
223
- predicate: {
224
- meta: jsonStringDescription,
225
- predicate: (s, ctx) => {
226
- try {
227
- JSON.parse(s);
228
- return true;
229
- }
230
- catch (e) {
231
- return ctx.reject({
232
- code: "predicate",
233
- expected: jsonStringDescription,
234
- problem: writeJsonSyntaxErrorProblem(e)
235
- });
236
- }
237
- }
238
- }
239
- });
240
- const parseJson = (s, ctx) => {
241
- if (s.length === 0) {
242
- return ctx.error({
243
- code: "predicate",
244
- expected: jsonStringDescription,
245
- actual: "empty"
246
- });
247
- }
248
- try {
249
- return JSON.parse(s);
250
- }
251
- catch (e) {
252
- return ctx.error({
253
- code: "predicate",
254
- expected: jsonStringDescription,
255
- problem: writeJsonSyntaxErrorProblem(e)
256
- });
257
- }
258
- };
259
- export const json = Scope.module({
260
- root: jsonRoot,
261
- parse: rootSchema({
262
- meta: "safe JSON string parser",
263
- in: "string",
264
- morphs: parseJson,
265
- declaredOut: intrinsic.jsonObject
266
- })
267
- }, {
268
- name: "string.json"
269
- });
270
- const preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters");
271
- const lower = Scope.module({
272
- root: rootSchema({
273
- in: "string",
274
- morphs: (s) => s.toLowerCase(),
275
- declaredOut: preformattedLower
276
- }),
277
- preformatted: preformattedLower
278
- }, {
279
- name: "string.lower"
280
- });
281
- export const normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"];
282
- const preformattedNodes = flatMorph(normalizedForms, (i, form) => [
283
- form,
284
- rootSchema({
285
- domain: "string",
286
- predicate: (s) => s.normalize(form) === s,
287
- meta: `${form}-normalized unicode`
288
- })
289
- ]);
290
- const normalizeNodes = flatMorph(normalizedForms, (i, form) => [
291
- form,
292
- rootSchema({
293
- in: "string",
294
- morphs: (s) => s.normalize(form),
295
- declaredOut: preformattedNodes[form]
296
- })
297
- ]);
298
- export const NFC = Scope.module({
299
- root: normalizeNodes.NFC,
300
- preformatted: preformattedNodes.NFC
301
- }, {
302
- name: "string.normalize.NFC"
303
- });
304
- export const NFD = Scope.module({
305
- root: normalizeNodes.NFD,
306
- preformatted: preformattedNodes.NFD
307
- }, {
308
- name: "string.normalize.NFD"
309
- });
310
- export const NFKC = Scope.module({
311
- root: normalizeNodes.NFKC,
312
- preformatted: preformattedNodes.NFKC
313
- }, {
314
- name: "string.normalize.NFKC"
315
- });
316
- export const NFKD = Scope.module({
317
- root: normalizeNodes.NFKD,
318
- preformatted: preformattedNodes.NFKD
319
- }, {
320
- name: "string.normalize.NFKD"
321
- });
322
- export const normalize = Scope.module({
323
- root: "NFC",
324
- NFC,
325
- NFD,
326
- NFKC,
327
- NFKD
328
- }, {
329
- name: "string.normalize"
330
- });
331
- const numericRoot = regexStringNode(numericStringMatcher, "a well-formed numeric string");
332
- export const stringNumeric = Scope.module({
333
- root: numericRoot,
334
- parse: rootSchema({
335
- in: numericRoot,
336
- morphs: (s) => Number.parseFloat(s),
337
- declaredOut: intrinsic.number
338
- })
339
- }, {
340
- name: "string.numeric"
341
- });
342
- const regexPatternDescription = "a regex pattern";
343
- const regex = rootSchema({
344
- domain: "string",
345
- predicate: {
346
- meta: regexPatternDescription,
347
- predicate: (s, ctx) => {
348
- try {
349
- new RegExp(s);
350
- return true;
351
- }
352
- catch (e) {
353
- return ctx.reject({
354
- code: "predicate",
355
- expected: regexPatternDescription,
356
- problem: String(e)
357
- });
358
- }
359
- }
360
- },
361
- meta: { format: "regex" }
362
- });
363
- const semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][\dA-Za-z-]*))*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/;
364
- const semver = regexStringNode(semverMatcher, "a semantic version (see https://semver.org/)");
365
- const preformattedTrim = regexStringNode(
366
- // no leading or trailing whitespace
367
- /^\S.*\S$|^\S?$/, "trimmed");
368
- const trim = Scope.module({
369
- root: rootSchema({
370
- in: "string",
371
- morphs: (s) => s.trim(),
372
- declaredOut: preformattedTrim
373
- }),
374
- preformatted: preformattedTrim
375
- }, {
376
- name: "string.trim"
377
- });
378
- const preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters");
379
- const upper = Scope.module({
380
- root: rootSchema({
381
- in: "string",
382
- morphs: (s) => s.toUpperCase(),
383
- declaredOut: preformattedUpper
384
- }),
385
- preformatted: preformattedUpper
386
- }, {
387
- name: "string.upper"
388
- });
389
- const isParsableUrl = (s) => URL.canParse(s);
390
- const urlRoot = rootSchema({
391
- domain: "string",
392
- predicate: {
393
- meta: "a URL string",
394
- predicate: isParsableUrl
395
- },
396
- // URL.canParse allows a subset of the RFC-3986 URI spec
397
- // since there is no other serializable validation, best include a format
398
- meta: { format: "uri" }
399
- });
400
- export const url = Scope.module({
401
- root: urlRoot,
402
- parse: rootSchema({
403
- declaredIn: urlRoot,
404
- in: "string",
405
- morphs: (s, ctx) => {
406
- try {
407
- return new URL(s);
408
- }
409
- catch {
410
- return ctx.error("a URL string");
411
- }
412
- },
413
- declaredOut: rootSchema(URL)
414
- })
415
- }, {
416
- name: "string.url"
417
- });
418
- // based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js
419
- export const uuid = Scope.module({
420
- // the meta tuple expression ensures the error message does not delegate
421
- // to the individual branches, which are too detailed
422
- root: [
423
- "versioned | nil | max",
424
- "@",
425
- { description: "a UUID", format: "uuid" }
426
- ],
427
- "#nil": "'00000000-0000-0000-0000-000000000000'",
428
- "#max": "'ffffffff-ffff-ffff-ffff-ffffffffffff'",
429
- "#versioned": /^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-[1-8][\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/,
430
- v1: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-1[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv1"),
431
- v2: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-2[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv2"),
432
- v3: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-3[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv3"),
433
- v4: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-4[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv4"),
434
- v5: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-5[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv5"),
435
- v6: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-6[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv6"),
436
- v7: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-7[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv7"),
437
- v8: regexStringNode(/^[\dA-Fa-f]{8}-[\dA-Fa-f]{4}-8[\dA-Fa-f]{3}-[89ABab][\dA-Fa-f]{3}-[\dA-Fa-f]{12}$/, "a UUIDv8")
438
- }, {
439
- name: "string.uuid"
440
- });
441
- export const string = Scope.module({
442
- root: intrinsic.string,
443
- alpha: regexStringNode(/^[A-Za-z]*$/, "only letters"),
444
- alphanumeric: regexStringNode(/^[\dA-Za-z]*$/, "only letters and digits 0-9"),
445
- hex,
446
- base58,
447
- base64,
448
- capitalize,
449
- creditCard,
450
- date: stringDate,
451
- digits: regexStringNode(/^\d*$/, "only digits 0-9"),
452
- email,
453
- integer: stringInteger,
454
- ip,
455
- json,
456
- lower,
457
- normalize,
458
- numeric: stringNumeric,
459
- regex,
460
- semver,
461
- trim,
462
- upper,
463
- url,
464
- uuid
465
- }, {
466
- name: "string"
467
- });
package/out/match.js DELETED
@@ -1,95 +0,0 @@
1
- import { intrinsic } from "@ark/schema";
2
- import { Callable, domainOf, throwParseError } from "@ark/util";
3
- export class InternalMatchParser extends Callable {
4
- $;
5
- constructor($) {
6
- super((...args) => new InternalChainedMatchParser($)(...args), {
7
- bind: $
8
- });
9
- this.$ = $;
10
- }
11
- in(def) {
12
- return new InternalChainedMatchParser(this.$, def === undefined ? undefined : this.$.parse(def));
13
- }
14
- at(key, cases) {
15
- return new InternalChainedMatchParser(this.$).at(key, cases);
16
- }
17
- case(when, then) {
18
- return new InternalChainedMatchParser(this.$).case(when, then);
19
- }
20
- }
21
- export class InternalChainedMatchParser extends Callable {
22
- $;
23
- in;
24
- key;
25
- branches = [];
26
- constructor($, In) {
27
- super(cases => this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ? [k, v] : [this.$.parse(k), v])));
28
- this.$ = $;
29
- this.in = In;
30
- }
31
- at(key, cases) {
32
- if (this.key)
33
- throwParseError(doubleAtMessage);
34
- if (this.branches.length)
35
- throwParseError(chainedAtMessage);
36
- this.key = key;
37
- return cases ? this.match(cases) : this;
38
- }
39
- case(def, resolver) {
40
- return this.caseEntry(this.$.parse(def), resolver);
41
- }
42
- caseEntry(node, resolver) {
43
- const wrappableNode = this.key ? this.$.parse({ [this.key]: node }) : node;
44
- const branch = wrappableNode.pipe(resolver);
45
- this.branches.push(branch);
46
- return this;
47
- }
48
- match(cases) {
49
- return this(cases);
50
- }
51
- strings(cases) {
52
- return this.caseEntries(Object.entries(cases).map(([k, v]) => k === "default" ?
53
- [k, v]
54
- : [this.$.node("unit", { unit: k }), v]));
55
- }
56
- caseEntries(entries) {
57
- for (let i = 0; i < entries.length; i++) {
58
- const [k, v] = entries[i];
59
- if (k === "default") {
60
- if (i !== entries.length - 1) {
61
- throwParseError(`default may only be specified as the last key of a switch definition`);
62
- }
63
- return this.default(v);
64
- }
65
- if (typeof v !== "function") {
66
- return throwParseError(`Value for case "${k}" must be a function (was ${domainOf(v)})`);
67
- }
68
- this.caseEntry(k, v);
69
- }
70
- return this;
71
- }
72
- default(defaultCase) {
73
- if (typeof defaultCase === "function")
74
- this.case(intrinsic.unknown, defaultCase);
75
- const schema = {
76
- branches: this.branches,
77
- ordered: true
78
- };
79
- if (defaultCase === "never" || defaultCase === "assert")
80
- schema.meta = { onFail: throwOnDefault };
81
- const cases = this.$.node("union", schema);
82
- if (!this.in)
83
- return this.$.finalize(cases);
84
- let inputValidatedCases = this.in.pipe(cases);
85
- if (defaultCase === "never" || defaultCase === "assert") {
86
- inputValidatedCases = inputValidatedCases.configureReferences({
87
- onFail: throwOnDefault
88
- }, "self");
89
- }
90
- return this.$.finalize(inputValidatedCases);
91
- }
92
- }
93
- export const throwOnDefault = errors => errors.throw();
94
- export const chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;
95
- export const doubleAtMessage = `At most one key matcher may be specified per expression`;
package/out/module.js DELETED
@@ -1,3 +0,0 @@
1
- import { RootModule } from "@ark/schema";
2
- export const Module = RootModule;
3
- export const BoundModule = RootModule;
package/out/nary.js DELETED
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export const writeDoubleRightBoundMessage = (root) => `Expression ${root} must have at most one right bound`;
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1,3 +0,0 @@
1
- export const writePrefixedPrivateReferenceMessage = (name) => `Private type references should not include '#'. Use '${name}' instead.`;
2
- export const shallowOptionalMessage = "Optional definitions like 'string?' are only valid as properties in an object or tuple";
3
- export const shallowDefaultableMessage = "Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";
@@ -1,78 +0,0 @@
1
- import { hasArkKind } from "@ark/schema";
2
- import { domainOf, hasDomain, isThunk, objectKindOf, printable, throwParseError, uncapitalize } from "@ark/util";
3
- import { parseObjectLiteral } from "./objectLiteral.js";
4
- import { parseString } from "./string.js";
5
- import { maybeParseTupleExpression } from "./tupleExpressions.js";
6
- import { parseTupleLiteral } from "./tupleLiteral.js";
7
- const parseCache = new WeakMap();
8
- export const parseInnerDefinition = (def, ctx) => {
9
- if (typeof def === "string") {
10
- if (ctx.args && Object.keys(ctx.args).some(k => def.includes(k))) {
11
- // we can only rely on the cache if there are no contextual
12
- // resolutions like "this" or generic args
13
- return parseString(def, ctx);
14
- }
15
- let scopeCache = parseCache.get(ctx.$);
16
- if (!scopeCache) {
17
- scopeCache = {};
18
- parseCache.set(ctx.$, scopeCache);
19
- }
20
- return (scopeCache[def] ??= parseString(def, ctx));
21
- }
22
- return hasDomain(def, "object") ?
23
- parseObject(def, ctx)
24
- : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
25
- };
26
- export const parseObject = (def, ctx) => {
27
- const objectKind = objectKindOf(def);
28
- switch (objectKind) {
29
- case undefined:
30
- if (hasArkKind(def, "root"))
31
- return def;
32
- if ("~standard" in def)
33
- return parseStandardSchema(def, ctx);
34
- return parseObjectLiteral(def, ctx);
35
- case "Array":
36
- return parseTuple(def, ctx);
37
- case "RegExp":
38
- return ctx.$.node("intersection", {
39
- domain: "string",
40
- pattern: def
41
- }, { prereduced: true });
42
- case "Function": {
43
- const resolvedDef = isThunk(def) ? def() : def;
44
- if (hasArkKind(resolvedDef, "root"))
45
- return resolvedDef;
46
- return throwParseError(writeBadDefinitionTypeMessage("Function"));
47
- }
48
- default:
49
- return throwParseError(writeBadDefinitionTypeMessage(objectKind ?? printable(def)));
50
- }
51
- };
52
- const parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx) => {
53
- const result = def["~standard"].validate(v);
54
- if (!result.issues)
55
- return result.value;
56
- for (const { message, path } of result.issues) {
57
- if (path) {
58
- if (path.length) {
59
- ctx.error({
60
- problem: uncapitalize(message),
61
- relativePath: path.map(k => (typeof k === "object" ? k.key : k))
62
- });
63
- }
64
- else {
65
- ctx.error({
66
- message
67
- });
68
- }
69
- }
70
- else {
71
- ctx.error({
72
- message
73
- });
74
- }
75
- }
76
- });
77
- export const parseTuple = (def, ctx) => maybeParseTupleExpression(def, ctx) ?? parseTupleLiteral(def, ctx);
78
- export const writeBadDefinitionTypeMessage = (actual) => `Type definitions must be strings or objects (was ${actual})`;