arktype 2.0.0-rc.25 → 2.0.0-rc.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.
Files changed (100) hide show
  1. package/out/attributes.d.ts +61 -241
  2. package/out/attributes.js +1 -2
  3. package/out/generic.d.ts +4 -4
  4. package/out/keywords/{constructors/Array.d.ts → Array.d.ts} +2 -2
  5. package/out/keywords/{constructors/Array.js → Array.js} +1 -1
  6. package/out/keywords/{constructors/FormData.d.ts → FormData.d.ts} +2 -2
  7. package/out/keywords/{constructors/FormData.js → FormData.js} +1 -1
  8. package/out/keywords/{constructors/TypedArray.d.ts → TypedArray.d.ts} +1 -1
  9. package/out/keywords/{constructors/TypedArray.js → TypedArray.js} +1 -1
  10. package/out/keywords/{constructors/constructors.d.ts → constructors.d.ts} +1 -1
  11. package/out/keywords/{constructors/constructors.js → constructors.js} +1 -1
  12. package/out/keywords/keywords.d.ts +6 -9
  13. package/out/keywords/keywords.js +3 -3
  14. package/out/keywords/number.d.ts +23 -0
  15. package/out/keywords/{number/epoch.js → number.js} +23 -1
  16. package/out/keywords/string.d.ts +327 -0
  17. package/out/keywords/string.js +398 -0
  18. package/out/methods/array.d.ts +6 -7
  19. package/out/methods/base.d.ts +10 -14
  20. package/out/methods/date.d.ts +5 -6
  21. package/out/methods/number.d.ts +6 -7
  22. package/out/methods/object.d.ts +5 -5
  23. package/out/methods/string.d.ts +7 -8
  24. package/out/parser/ast/generic.d.ts +17 -0
  25. package/out/parser/ast/infer.d.ts +4 -18
  26. package/out/parser/ast/validate.d.ts +10 -6
  27. package/out/parser/ast/validate.js +2 -0
  28. package/out/parser/definition.d.ts +17 -8
  29. package/out/parser/definition.js +20 -2
  30. package/out/parser/objectLiteral.d.ts +39 -39
  31. package/out/parser/objectLiteral.js +75 -49
  32. package/out/parser/property.d.ts +37 -0
  33. package/out/parser/property.js +16 -0
  34. package/out/parser/reduce/dynamic.d.ts +1 -1
  35. package/out/parser/shift/operand/enclosed.d.ts +1 -3
  36. package/out/parser/shift/operand/unenclosed.d.ts +2 -1
  37. package/out/parser/shift/operator/bounds.js +5 -4
  38. package/out/parser/shift/operator/default.d.ts +2 -1
  39. package/out/parser/shift/operator/default.js +1 -1
  40. package/out/parser/string.d.ts +5 -4
  41. package/out/parser/string.js +18 -1
  42. package/out/parser/tupleExpressions.d.ts +47 -0
  43. package/out/parser/tupleExpressions.js +67 -0
  44. package/out/parser/tupleLiteral.d.ts +80 -0
  45. package/out/parser/tupleLiteral.js +119 -0
  46. package/out/scope.d.ts +8 -7
  47. package/out/scope.js +12 -32
  48. package/out/type.d.ts +5 -5
  49. package/package.json +3 -3
  50. package/out/keywords/constructors/Date.d.ts +0 -37
  51. package/out/keywords/number/epoch.d.ts +0 -10
  52. package/out/keywords/number/integer.d.ts +0 -3
  53. package/out/keywords/number/integer.js +0 -5
  54. package/out/keywords/number/number.d.ts +0 -58
  55. package/out/keywords/number/number.js +0 -21
  56. package/out/keywords/string/alpha.d.ts +0 -7
  57. package/out/keywords/string/alpha.js +0 -2
  58. package/out/keywords/string/alphanumeric.d.ts +0 -7
  59. package/out/keywords/string/alphanumeric.js +0 -2
  60. package/out/keywords/string/base64.d.ts +0 -21
  61. package/out/keywords/string/base64.js +0 -6
  62. package/out/keywords/string/capitalize.d.ts +0 -15
  63. package/out/keywords/string/capitalize.js +0 -12
  64. package/out/keywords/string/creditCard.d.ts +0 -8
  65. package/out/keywords/string/creditCard.js +0 -37
  66. package/out/keywords/string/date.d.ts +0 -55
  67. package/out/keywords/string/date.js +0 -98
  68. package/out/keywords/string/digits.d.ts +0 -7
  69. package/out/keywords/string/digits.js +0 -2
  70. package/out/keywords/string/email.d.ts +0 -7
  71. package/out/keywords/string/email.js +0 -4
  72. package/out/keywords/string/integer.d.ts +0 -16
  73. package/out/keywords/string/integer.js +0 -16
  74. package/out/keywords/string/ip.d.ts +0 -20
  75. package/out/keywords/string/ip.js +0 -23
  76. package/out/keywords/string/json.d.ts +0 -16
  77. package/out/keywords/string/json.js +0 -54
  78. package/out/keywords/string/lower.d.ts +0 -15
  79. package/out/keywords/string/lower.js +0 -12
  80. package/out/keywords/string/normalize.d.ts +0 -88
  81. package/out/keywords/string/normalize.js +0 -43
  82. package/out/keywords/string/numeric.d.ts +0 -15
  83. package/out/keywords/string/numeric.js +0 -13
  84. package/out/keywords/string/semver.d.ts +0 -7
  85. package/out/keywords/string/semver.js +0 -4
  86. package/out/keywords/string/string.d.ts +0 -135
  87. package/out/keywords/string/string.js +0 -43
  88. package/out/keywords/string/trim.d.ts +0 -15
  89. package/out/keywords/string/trim.js +0 -14
  90. package/out/keywords/string/upper.d.ts +0 -15
  91. package/out/keywords/string/upper.js +0 -12
  92. package/out/keywords/string/url.d.ts +0 -15
  93. package/out/keywords/string/url.js +0 -37
  94. package/out/keywords/string/utils.d.ts +0 -2
  95. package/out/keywords/string/utils.js +0 -10
  96. package/out/keywords/string/uuid.d.ts +0 -42
  97. package/out/keywords/string/uuid.js +0 -19
  98. package/out/parser/tuple.d.ts +0 -148
  99. package/out/parser/tuple.js +0 -164
  100. /package/out/{keywords/constructors/Date.js → parser/ast/generic.js} +0 -0
@@ -0,0 +1,398 @@
1
+ import { ArkErrors, intrinsic, node, rootSchema } from "@ark/schema";
2
+ import { flatMorph, numericStringMatcher, wellFormedIntegerMatcher } from "@ark/util";
3
+ import { number } from "./number.js";
4
+ import { arkModule } from "./utils.js";
5
+ // Non-trivial expressions should have an explanation or attribution
6
+ export const regexStringNode = (regex, description) => node("intersection", {
7
+ domain: "string",
8
+ pattern: {
9
+ rule: regex.source,
10
+ flags: regex.flags,
11
+ meta: description
12
+ }
13
+ });
14
+ const stringIntegerRoot = regexStringNode(wellFormedIntegerMatcher, "a well-formed integer string");
15
+ export const stringInteger = arkModule({
16
+ root: stringIntegerRoot,
17
+ parse: rootSchema({
18
+ in: stringIntegerRoot,
19
+ morphs: (s, ctx) => {
20
+ const parsed = Number.parseInt(s);
21
+ return Number.isSafeInteger(parsed) ? parsed : (ctx.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER"));
22
+ },
23
+ declaredOut: intrinsic.integer
24
+ })
25
+ });
26
+ const base64 = arkModule({
27
+ root: regexStringNode(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, "base64-encoded"),
28
+ url: regexStringNode(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/, "base64url-encoded")
29
+ });
30
+ const preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized");
31
+ export const capitalize = arkModule({
32
+ root: rootSchema({
33
+ in: "string",
34
+ morphs: (s) => s.charAt(0).toUpperCase() + s.slice(1),
35
+ declaredOut: preformattedCapitalize
36
+ }),
37
+ preformatted: preformattedCapitalize
38
+ });
39
+ // https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js
40
+ export const isLuhnValid = (creditCardInput) => {
41
+ const sanitized = creditCardInput.replace(/[- ]+/g, "");
42
+ let sum = 0;
43
+ let digit;
44
+ let tmpNum;
45
+ let shouldDouble = false;
46
+ for (let i = sanitized.length - 1; i >= 0; i--) {
47
+ digit = sanitized.substring(i, i + 1);
48
+ tmpNum = Number.parseInt(digit, 10);
49
+ if (shouldDouble) {
50
+ tmpNum *= 2;
51
+ if (tmpNum >= 10)
52
+ sum += (tmpNum % 10) + 1;
53
+ else
54
+ sum += tmpNum;
55
+ }
56
+ else
57
+ sum += tmpNum;
58
+ shouldDouble = !shouldDouble;
59
+ }
60
+ return !!(sum % 10 === 0 ? sanitized : false);
61
+ };
62
+ // https://github.com/validatorjs/validator.js/blob/master/src/lib/isCreditCard.js
63
+ const creditCardMatcher = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/;
64
+ export const creditCard = rootSchema({
65
+ domain: "string",
66
+ pattern: {
67
+ meta: "a credit card number",
68
+ rule: creditCardMatcher.source
69
+ },
70
+ predicate: {
71
+ meta: "a credit card number",
72
+ predicate: isLuhnValid
73
+ }
74
+ });
75
+ const dayDelimiterMatcher = /^[./-]$/;
76
+ // ISO 8601 date/time modernized from https://github.com/validatorjs/validator.js/blob/master/src/lib/isISO8601.js
77
+ // Based on https://tc39.es/ecma262/#sec-date-time-string-format, the T
78
+ // delimiter for date/time is mandatory. Regex from validator.js strict matcher:
79
+ 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)?)?)?)?$/;
80
+ const isValidDateInstance = (date) => !Number.isNaN(+date);
81
+ const writeFormattedExpected = (format) => `a ${format}-formatted date`;
82
+ export const tryParseDatePattern = (data, opts) => {
83
+ if (!opts?.format) {
84
+ const result = new Date(data);
85
+ return isValidDateInstance(result) ? result : "a valid date";
86
+ }
87
+ if (opts.format === "iso") {
88
+ return iso8601Matcher.test(data) ?
89
+ new Date(data)
90
+ : writeFormattedExpected("iso");
91
+ }
92
+ const dataParts = data.split(dayDelimiterMatcher);
93
+ // will be the first delimiter matched, if there is one
94
+ const delimiter = data[dataParts[0].length];
95
+ const formatParts = delimiter ? opts.format.split(delimiter) : [opts.format];
96
+ if (dataParts.length !== formatParts.length)
97
+ return writeFormattedExpected(opts.format);
98
+ const parsedParts = {};
99
+ for (let i = 0; i < formatParts.length; i++) {
100
+ if (dataParts[i].length !== formatParts[i].length &&
101
+ // if format is "m" or "d", data is allowed to be 1 or 2 characters
102
+ !(formatParts[i].length === 1 && dataParts[i].length === 2))
103
+ return writeFormattedExpected(opts.format);
104
+ parsedParts[formatParts[i][0]] = dataParts[i];
105
+ }
106
+ const date = new Date(`${parsedParts.m}/${parsedParts.d}/${parsedParts.y}`);
107
+ if (`${date.getDate()}` === parsedParts.d)
108
+ return date;
109
+ return writeFormattedExpected(opts.format);
110
+ };
111
+ const isParsableDate = (s) => !Number.isNaN(new Date(s).valueOf());
112
+ const parsableDate = rootSchema({
113
+ domain: "string",
114
+ predicate: {
115
+ meta: "a parsable date",
116
+ predicate: isParsableDate
117
+ }
118
+ }).assertHasKind("intersection");
119
+ const epochRoot = stringInteger.root.internal
120
+ .narrow((s, ctx) => {
121
+ // we know this is safe since it has already
122
+ // been validated as an integer string
123
+ const n = Number.parseInt(s);
124
+ const out = number.epoch(n);
125
+ if (out instanceof ArkErrors) {
126
+ ctx.errors.merge(out);
127
+ return false;
128
+ }
129
+ return true;
130
+ })
131
+ .withMeta({
132
+ description: "an integer string representing a safe Unix timestamp"
133
+ })
134
+ .assertHasKind("intersection");
135
+ const epoch = arkModule({
136
+ root: epochRoot,
137
+ parse: rootSchema({
138
+ in: epochRoot,
139
+ morphs: (s) => new Date(s),
140
+ declaredOut: intrinsic.Date
141
+ })
142
+ });
143
+ const isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
144
+ const iso = arkModule({
145
+ root: isoRoot,
146
+ parse: rootSchema({
147
+ in: isoRoot,
148
+ morphs: (s) => new Date(s),
149
+ declaredOut: intrinsic.Date
150
+ })
151
+ });
152
+ export const stringDate = arkModule({
153
+ root: parsableDate,
154
+ parse: rootSchema({
155
+ declaredIn: parsableDate,
156
+ in: "string",
157
+ morphs: (s, ctx) => {
158
+ const date = new Date(s);
159
+ if (Number.isNaN(date.valueOf()))
160
+ return ctx.error("a parsable date");
161
+ return date;
162
+ },
163
+ declaredOut: intrinsic.Date
164
+ }),
165
+ iso,
166
+ epoch
167
+ });
168
+ const email = regexStringNode(
169
+ // https://www.regular-expressions.info/email.html
170
+ /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, "an email address");
171
+ // Based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isIP.js
172
+ // Adjusted to incorporate unmerged fix in https://github.com/validatorjs/validator.js/pull/2083
173
+ const ipv4Segment = "(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
174
+ const ipv4Address = `(${ipv4Segment}[.]){3}${ipv4Segment}`;
175
+ const ipv4Matcher = new RegExp(`^${ipv4Address}$`);
176
+ const ipv6Segment = "(?:[0-9a-fA-F]{1,4})";
177
+ const ipv6Matcher = new RegExp("^(" +
178
+ `(?:${ipv6Segment}:){7}(?:${ipv6Segment}|:)|` +
179
+ `(?:${ipv6Segment}:){6}(?:${ipv4Address}|:${ipv6Segment}|:)|` +
180
+ `(?:${ipv6Segment}:){5}(?::${ipv4Address}|(:${ipv6Segment}){1,2}|:)|` +
181
+ `(?:${ipv6Segment}:){4}(?:(:${ipv6Segment}){0,1}:${ipv4Address}|(:${ipv6Segment}){1,3}|:)|` +
182
+ `(?:${ipv6Segment}:){3}(?:(:${ipv6Segment}){0,2}:${ipv4Address}|(:${ipv6Segment}){1,4}|:)|` +
183
+ `(?:${ipv6Segment}:){2}(?:(:${ipv6Segment}){0,3}:${ipv4Address}|(:${ipv6Segment}){1,5}|:)|` +
184
+ `(?:${ipv6Segment}:){1}(?:(:${ipv6Segment}){0,4}:${ipv4Address}|(:${ipv6Segment}){1,6}|:)|` +
185
+ `(?::((?::${ipv6Segment}){0,5}:${ipv4Address}|(?::${ipv6Segment}){1,7}|:))` +
186
+ ")(%[0-9a-zA-Z.]{1,})?$");
187
+ export const ip = arkModule({
188
+ root: ["v4 | v6", "@", "an IP address"],
189
+ v4: regexStringNode(ipv4Matcher, "an IPv4 address"),
190
+ v6: regexStringNode(ipv6Matcher, "an IPv6 address")
191
+ });
192
+ const jsonStringDescription = "a JSON string";
193
+ export const writeJsonSyntaxErrorProblem = (error) => {
194
+ if (!(error instanceof SyntaxError))
195
+ throw error;
196
+ return `must be ${jsonStringDescription} (${error})`;
197
+ };
198
+ const jsonRoot = rootSchema({
199
+ domain: "string",
200
+ predicate: {
201
+ meta: jsonStringDescription,
202
+ predicate: (s, ctx) => {
203
+ try {
204
+ JSON.parse(s);
205
+ return true;
206
+ }
207
+ catch (e) {
208
+ return ctx.reject({
209
+ code: "predicate",
210
+ expected: jsonStringDescription,
211
+ problem: writeJsonSyntaxErrorProblem(e)
212
+ });
213
+ }
214
+ }
215
+ }
216
+ });
217
+ const parseJson = (s, ctx) => {
218
+ if (s.length === 0) {
219
+ return ctx.error({
220
+ code: "predicate",
221
+ expected: jsonStringDescription,
222
+ actual: "empty"
223
+ });
224
+ }
225
+ try {
226
+ return JSON.parse(s);
227
+ }
228
+ catch (e) {
229
+ return ctx.error({
230
+ code: "predicate",
231
+ expected: jsonStringDescription,
232
+ problem: writeJsonSyntaxErrorProblem(e)
233
+ });
234
+ }
235
+ };
236
+ export const json = arkModule({
237
+ root: jsonRoot,
238
+ parse: rootSchema({
239
+ in: "string",
240
+ morphs: parseJson,
241
+ declaredOut: intrinsic.json
242
+ })
243
+ });
244
+ const preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters");
245
+ const lower = arkModule({
246
+ root: rootSchema({
247
+ in: "string",
248
+ morphs: (s) => s.toLowerCase(),
249
+ declaredOut: preformattedLower
250
+ }),
251
+ preformatted: preformattedLower
252
+ });
253
+ export const normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"];
254
+ const preformattedNodes = flatMorph(normalizedForms, (i, form) => [
255
+ form,
256
+ rootSchema({
257
+ domain: "string",
258
+ predicate: (s) => s.normalize(form) === s,
259
+ meta: `${form}-normalized unicode`
260
+ })
261
+ ]);
262
+ const normalizeNodes = flatMorph(normalizedForms, (i, form) => [
263
+ form,
264
+ rootSchema({
265
+ in: "string",
266
+ morphs: (s) => s.normalize(form),
267
+ declaredOut: preformattedNodes[form]
268
+ })
269
+ ]);
270
+ export const NFC = arkModule({
271
+ root: normalizeNodes.NFC,
272
+ preformatted: preformattedNodes.NFC
273
+ });
274
+ export const NFD = arkModule({
275
+ root: normalizeNodes.NFD,
276
+ preformatted: preformattedNodes.NFD
277
+ });
278
+ export const NFKC = arkModule({
279
+ root: normalizeNodes.NFKC,
280
+ preformatted: preformattedNodes.NFKC
281
+ });
282
+ export const NFKD = arkModule({
283
+ root: normalizeNodes.NFKD,
284
+ preformatted: preformattedNodes.NFKD
285
+ });
286
+ export const normalize = arkModule({
287
+ root: "NFC",
288
+ NFC,
289
+ NFD,
290
+ NFKC,
291
+ NFKD
292
+ });
293
+ const numericRoot = regexStringNode(numericStringMatcher, "a well-formed numeric string");
294
+ export const numeric = arkModule({
295
+ root: numericRoot,
296
+ parse: rootSchema({
297
+ in: numericRoot,
298
+ morphs: (s) => Number.parseFloat(s),
299
+ declaredOut: intrinsic.number
300
+ })
301
+ });
302
+ // https://semver.org/
303
+ const semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
304
+ const semver = regexStringNode(semverMatcher, "a semantic version (see https://semver.org/)");
305
+ const preformattedTrim = regexStringNode(
306
+ // no leading or trailing whitespace
307
+ /^\S.*\S$|^\S?$/, "trimmed");
308
+ const trim = arkModule({
309
+ root: rootSchema({
310
+ in: "string",
311
+ morphs: (s) => s.trim(),
312
+ declaredOut: preformattedTrim
313
+ }),
314
+ preformatted: preformattedTrim
315
+ });
316
+ const preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters");
317
+ const upper = arkModule({
318
+ root: rootSchema({
319
+ in: "string",
320
+ morphs: (s) => s.toUpperCase(),
321
+ declaredOut: preformattedUpper
322
+ }),
323
+ preformatted: preformattedUpper
324
+ });
325
+ const isParsableUrl = (s) => {
326
+ if (URL.canParse)
327
+ return URL.canParse(s);
328
+ // Can be removed once Node 18 is EOL
329
+ try {
330
+ new URL(s);
331
+ return true;
332
+ }
333
+ catch {
334
+ return false;
335
+ }
336
+ };
337
+ const urlRoot = rootSchema({
338
+ domain: "string",
339
+ predicate: {
340
+ meta: "a URL string",
341
+ predicate: isParsableUrl
342
+ }
343
+ });
344
+ export const url = arkModule({
345
+ root: urlRoot,
346
+ parse: rootSchema({
347
+ declaredIn: urlRoot,
348
+ in: "string",
349
+ morphs: (s, ctx) => {
350
+ try {
351
+ return new URL(s);
352
+ }
353
+ catch {
354
+ return ctx.error("a URL string");
355
+ }
356
+ },
357
+ declaredOut: rootSchema(URL)
358
+ })
359
+ });
360
+ // Based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js
361
+ export const uuid = arkModule({
362
+ // the meta tuple expression ensures the error message does not delegate
363
+ // to the individual branches, which are too detailed
364
+ root: ["versioned | nil | max", "@", "a UUID"],
365
+ "#nil": "'00000000-0000-0000-0000-000000000000'",
366
+ "#max": "'ffffffff-ffff-ffff-ffff-ffffffffffff'",
367
+ "#versioned": /[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,
368
+ v1: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv1"),
369
+ v2: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-2[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv2"),
370
+ v3: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv3"),
371
+ v4: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv4"),
372
+ v5: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv5"),
373
+ v6: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv6"),
374
+ v7: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv7"),
375
+ v8: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv8")
376
+ });
377
+ export const string = arkModule({
378
+ root: intrinsic.string,
379
+ alpha: regexStringNode(/^[A-Za-z]*$/, "only letters"),
380
+ alphanumeric: regexStringNode(/^[A-Za-z\d]*$/, "only letters and digits 0-9"),
381
+ base64,
382
+ capitalize,
383
+ creditCard,
384
+ date: stringDate,
385
+ digits: regexStringNode(/^\d*$/, "only digits 0-9"),
386
+ email,
387
+ integer: stringInteger,
388
+ ip,
389
+ json,
390
+ lower,
391
+ normalize,
392
+ numeric,
393
+ semver,
394
+ trim,
395
+ upper,
396
+ url,
397
+ uuid
398
+ });
@@ -1,13 +1,12 @@
1
- import type { ExactLength, ExclusiveNumericRangeSchema, exclusivizeRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
2
- import type { associateAttributesFromArraySchema } from "../attributes.ts";
1
+ import type { ExactLength, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
3
2
  import type { ObjectType } from "./object.ts";
4
3
  interface Type<
5
4
  /** @ts-ignore cast variance */
6
5
  out t extends readonly unknown[] = readonly unknown[], $ = {}> extends ObjectType<t, $> {
7
- atLeastLength<const schema extends InclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromArraySchema<t, "minLength", schema>, $>;
8
- atMostLength<const schema extends InclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromArraySchema<t, "maxLength", schema>, $>;
9
- moreThanLength<const schema extends ExclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromArraySchema<t, "minLength", exclusivizeRangeSchema<schema>>, $>;
10
- lessThanLength<const schema extends ExclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromArraySchema<t, "maxLength", exclusivizeRangeSchema<schema>>, $>;
11
- exactlyLength<const schema extends ExactLength.Schema>(schema: schema): Type<associateAttributesFromArraySchema<t, "exactLength", schema>, $>;
6
+ atLeastLength(schema: InclusiveNumericRangeSchema): this;
7
+ atMostLength(schema: InclusiveNumericRangeSchema): this;
8
+ moreThanLength(schema: ExclusiveNumericRangeSchema): this;
9
+ lessThanLength(schema: ExclusiveNumericRangeSchema): this;
10
+ exactlyLength(schema: ExactLength.Schema): this;
12
11
  }
13
12
  export type { Type as ArrayType };
@@ -1,6 +1,6 @@
1
1
  import type { ArkErrors, BaseRoot, Disjoint, JsonSchema, MetaSchema, Morph, Predicate, PredicateCast, StandardSchemaV1, UndeclaredKeyBehavior } from "@ark/schema";
2
- import type { anyOrNever, array, Callable, ErrorMessage, inferred, Json, unset } from "@ark/util";
3
- import type { associateAttributes, associateAttributesFromSchema, brandAttributes, Default, DefaultFor, distill, inferIntersection, inferMorphOut, inferPipes, InferredMorph, Nominal, Optional, Out, To } from "../attributes.ts";
2
+ import type { anyOrNever, array, Callable, ErrorMessage, inferred, JsonStructure, unset } from "@ark/util";
3
+ import type { defaultFor, distill, inferIntersection, inferMorphOut, inferPipes, InferredMorph, Out, To } from "../attributes.ts";
4
4
  import type { ArkAmbient } from "../config.ts";
5
5
  import type { type } from "../keywords/keywords.ts";
6
6
  import type { Scope } from "../scope.ts";
@@ -11,8 +11,6 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
11
11
  [inferred]: t;
12
12
  t: t;
13
13
  infer: this["inferOut"];
14
- inferInWithAttributes: distill.withAttributes.In<t>;
15
- inferOutWithAttributes: distill.withAttributes.Out<t>;
16
14
  inferIntrospectableOut: distill.introspectable.Out<t>;
17
15
  inferOut: distill.Out<t>;
18
16
  inferIn: distill.In<t>;
@@ -20,8 +18,8 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
20
18
  o
21
19
  ] extends [anyOrNever] ? true : o extends To ? true : false : unknown extends t ? boolean : true;
22
20
  /** Internal JSON representation of this `Type` */
23
- json: Json;
24
- toJSON(): Json;
21
+ json: JsonStructure;
22
+ toJSON(): JsonStructure;
25
23
  meta: ArkAmbient.meta;
26
24
  precompilation: string | undefined;
27
25
  toJsonSchema(): JsonSchema;
@@ -69,14 +67,12 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
69
67
  * const branded = type(/^a/).as<`a${string}`>() // Type<`a${string}`>
70
68
  */
71
69
  as<castTo = unset>(...args: validateChainedAsArgs<castTo>): instantiateType<castTo, $>;
72
- brand<const name extends string, r = brandAttributes<t, Nominal<name>>>(name: name): instantiateType<r, $>;
73
- brandAttributes(): instantiateType<distill.brand<t>, $>;
74
- unbrandAttributes(): instantiateType<distill.unbrand<t>, $>;
70
+ brand<const name extends string, r = type.brand<t, name>>(name: name): instantiateType<r, $>;
75
71
  /**
76
72
  * A `Type` representing the deeply-extracted input of the `Type` (before morphs are applied).
77
73
  * @example const inputT = T.in
78
74
  */
79
- get in(): instantiateType<this["inferInWithAttributes"], $>;
75
+ get in(): instantiateType<this["inferIn"], $>;
80
76
  /**
81
77
  * A `Type` representing the deeply-extracted output of the `Type` (after morphs are applied).\
82
78
  * **IMPORTANT**: If your type includes morphs, their output will likely be unknown
@@ -108,8 +104,8 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
108
104
  * @example const foo = type("string").narrow((s): s is `foo${string}` => s.startsWith('foo') || ctx.mustBe('string starting with "foo"')) // Type<"foo${string}">
109
105
  * @example const unique = type('string[]').narrow((a, ctx) => new Set(a).size === a.length || ctx.mustBe('array with unique elements'))
110
106
  */
111
- narrow<narrowed extends this["infer"] = never, r = [narrowed] extends [never] ? t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<associateAttributesFromSchema<o[1], "predicate", Predicate>> : (In: i) => Out<associateAttributesFromSchema<o[1], "predicate", Predicate>> : associateAttributesFromSchema<t, "predicate", Predicate> : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed>(predicate: Predicate<this["infer"]> | PredicateCast<this["infer"], narrowed>): instantiateType<r, $>;
112
- satisfying<narrowed extends this["inferIn"] = never, r = [narrowed] extends [never] ? associateAttributesFromSchema<t, "predicate", Predicate> : t extends InferredMorph<any, infer o> ? (In: narrowed) => o : narrowed>(predicate: Predicate<this["inferIn"]> | PredicateCast<this["inferIn"], narrowed>): instantiateType<r, $>;
107
+ narrow<narrowed extends this["infer"] = never, r = [narrowed] extends [never] ? t : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed>(predicate: Predicate<this["infer"]> | PredicateCast<this["infer"], narrowed>): instantiateType<r, $>;
108
+ satisfying<narrowed extends this["inferIn"] = never, r = [narrowed] extends [never] ? t : t extends InferredMorph<any, infer o> ? (In: narrowed) => o : narrowed>(predicate: Predicate<this["inferIn"]> | PredicateCast<this["inferIn"], narrowed>): instantiateType<r, $>;
113
109
  /**
114
110
  * Create a `Type` for array with elements of this `Type`
115
111
  * @example const T = type(/^foo/); const array = T.array() // Type<string[]>
@@ -129,7 +125,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
129
125
  extract<const def, r = type.infer<def, $>>(r: type.validate<def, $>): instantiateType<Extract<t, r>, $>;
130
126
  exclude<const def, r = type.infer<def, $>>(r: type.validate<def, $>): instantiateType<Exclude<t, r>, $>;
131
127
  distribute<mapOut, reduceOut = mapOut[]>(mapBranch: (branch: Type, i: number, branches: array<Type>) => mapOut, reduceMapped?: (mappedBranches: mapOut[]) => reduceOut): reduceOut;
132
- optional<r = associateAttributes<t, Optional>>(): instantiateType<r, $>;
128
+ optional(): [this, "?"];
133
129
  /**
134
130
  * Add a default value for this `Type` when it is used as a property.\
135
131
  * Default value should be a valid input value for this `Type, or a function that returns a valid input value.\
@@ -138,7 +134,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
138
134
  * @example const withFactory = type({ foo: type("number[]").default(() => [1])) }); withFactory({baz: 'a'}) // { foo: [1], baz: 'a' }
139
135
  * @example const withMorph = type({ foo: type("string.numeric.parse").default("123") }); withMorph({}) // { foo: 123 }
140
136
  */
141
- default<const value extends this["inferIn"], r = associateAttributes<t, Default<value>>>(value: DefaultFor<value>): instantiateType<r, $>;
137
+ default<const value extends defaultFor<this["inferIn"]>>(value: value): [this, "=", value];
142
138
  "~standard": StandardSchemaV1.ArkTypeProps<this["inferIn"], this["inferOut"]>;
143
139
  /** @deprecated */
144
140
  apply: Function["apply"];
@@ -1,11 +1,10 @@
1
- import type { ExclusiveDateRangeSchema, exclusivizeRangeSchema, InclusiveDateRangeSchema } from "@ark/schema";
2
- import type { associateAttributesFromDateSchema } from "../attributes.ts";
1
+ import type { ExclusiveDateRangeSchema, InclusiveDateRangeSchema } from "@ark/schema";
3
2
  import type { ObjectType } from "./object.ts";
4
3
  /** @ts-ignore cast variance */
5
4
  interface Type<out t extends globalThis.Date = globalThis.Date, $ = {}> extends ObjectType<t, $> {
6
- atOrAfter<const schema extends InclusiveDateRangeSchema>(schema: schema): Type<associateAttributesFromDateSchema<t, "after", schema>, $>;
7
- atOrBefore<const schema extends InclusiveDateRangeSchema>(schema: schema): Type<associateAttributesFromDateSchema<t, "before", schema>, $>;
8
- laterThan<const schema extends ExclusiveDateRangeSchema>(schema: schema): Type<associateAttributesFromDateSchema<t, "after", exclusivizeRangeSchema<schema>>, $>;
9
- earlierThan<const schema extends ExclusiveDateRangeSchema>(schema: schema): Type<associateAttributesFromDateSchema<t, "before", exclusivizeRangeSchema<schema>>, $>;
5
+ atOrAfter(schema: InclusiveDateRangeSchema): this;
6
+ atOrBefore(schema: InclusiveDateRangeSchema): this;
7
+ laterThan(schema: ExclusiveDateRangeSchema): this;
8
+ earlierThan(schema: ExclusiveDateRangeSchema): this;
10
9
  }
11
10
  export type { Type as DateType };
@@ -1,12 +1,11 @@
1
- import type { Divisor, ExclusiveNumericRangeSchema, exclusivizeRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
2
- import type { associateAttributesFromNumberSchema } from "../attributes.ts";
1
+ import type { Divisor, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema } from "@ark/schema";
3
2
  import type { BaseType } from "./base.ts";
4
3
  /** @ts-ignore cast variance */
5
4
  interface Type<out t extends number = number, $ = {}> extends BaseType<t, $> {
6
- divisibleBy<const schema extends Divisor.Schema>(schema: schema): Type<associateAttributesFromNumberSchema<t, "divisor", schema>, $>;
7
- atLeast<const schema extends InclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromNumberSchema<t, "min", schema>, $>;
8
- atMost<const schema extends InclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromNumberSchema<t, "max", schema>, $>;
9
- moreThan<const schema extends ExclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromNumberSchema<t, "min", exclusivizeRangeSchema<schema>>, $>;
10
- lessThan<const schema extends ExclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromNumberSchema<t, "max", exclusivizeRangeSchema<schema>>, $>;
5
+ divisibleBy(schema: Divisor.Schema): this;
6
+ atLeast(schema: InclusiveNumericRangeSchema): this;
7
+ atMost(schema: InclusiveNumericRangeSchema): this;
8
+ moreThan(schema: ExclusiveNumericRangeSchema): this;
9
+ lessThan(schema: ExclusiveNumericRangeSchema): this;
11
10
  }
12
11
  export type { Type as NumberType };
@@ -1,6 +1,6 @@
1
1
  import type { BaseMappedPropInner, OptionalMappedPropInner, Prop } from "@ark/schema";
2
- import type { arkGet, arkIndexableOf, arkKeyOf, array, ErrorType, inferred, intersectUnion, Json, Key, listable, merge, optionalKeyOf, show, toArkKey } from "@ark/util";
3
- import type { associateAttributes, Attributes, Default, of, Optional } from "../attributes.ts";
2
+ import type { arkGet, arkIndexableOf, arkKeyOf, array, ErrorType, inferred, intersectUnion, JsonStructure, Key, listable, merge, optionalKeyOf, show, toArkKey } from "@ark/util";
3
+ import type { Default, withDefault } from "../attributes.ts";
4
4
  import type { type } from "../keywords/keywords.ts";
5
5
  import type { ArrayType } from "./array.ts";
6
6
  import type { BaseType } from "./base.ts";
@@ -61,7 +61,7 @@ interface Type<out t extends object = object, $ = {}> extends BaseType<t, $> {
61
61
  props: array<typePropOf<t, $>>;
62
62
  }
63
63
  type typePropOf<o, $> = keyof o extends infer k ? k extends keyof o ? typeProp<o, k, $> : never : never;
64
- type typeProp<o, k extends keyof o, $, t = o[k] & ({} | null)> = t extends of<infer base, infer attributes> ? attributes extends Default<infer defaultValue> ? DefaultedTypeProp<k & Key, keyof attributes extends keyof Default ? base : of<base, Omit<attributes, keyof Default> extends (infer attributes extends Attributes) ? attributes : never>, defaultValue, $> : attributes extends Optional ? BaseTypeProp<"optional", k & Key, keyof attributes extends keyof Optional ? base : of<base, Omit<attributes, keyof Default> extends (infer attributes extends Attributes) ? attributes : never>, $> : never : BaseTypeProp<k extends optionalKeyOf<o> ? "optional" : "required", k & Key, t, $>;
64
+ type typeProp<o, k extends keyof o, $, t = o[k] & ({} | null)> = t extends Default<infer t, infer defaultValue> ? DefaultedTypeProp<k & Key, t, defaultValue, $> : BaseTypeProp<k extends optionalKeyOf<o> ? "optional" : "required", k & Key, t, $>;
65
65
  export interface BaseTypeProp<kind extends Prop.Kind = Prop.Kind, k extends Key = Key,
66
66
  /** @ts-ignore cast variance */
67
67
  out v = unknown, $ = {}> {
@@ -69,7 +69,7 @@ out v = unknown, $ = {}> {
69
69
  key: k;
70
70
  value: instantiateType<v, $>;
71
71
  meta: ArkEnv.meta;
72
- toJSON: () => Json;
72
+ toJSON: () => JsonStructure;
73
73
  }
74
74
  export interface DefaultedTypeProp<k extends Key = Key, v = unknown, defaultValue = v, $ = {}> extends BaseTypeProp<"optional", k, v, $> {
75
75
  default: defaultValue;
@@ -98,7 +98,7 @@ type fromTypeProps<t, props extends array<MappedTypeProp>> = show<{
98
98
  [prop in props[number] as Extract<applyHomomorphicOptionality<t, prop>, {
99
99
  kind: "optional";
100
100
  default: unknown;
101
- }>["key"]]: associateAttributes<prop["value"][inferred], Default<prop["default" & keyof prop]>>;
101
+ }>["key"]]: withDefault<prop["value"][inferred], prop["default" & keyof prop]>;
102
102
  }>;
103
103
  type applyHomomorphicOptionality<t, prop extends MappedTypeProp> = prop["kind"] extends string ? prop : prop & {
104
104
  kind: prop["key"] extends optionalKeyOf<t> ? "optional" : "required";
@@ -1,13 +1,12 @@
1
- import type { ExactLength, ExclusiveNumericRangeSchema, exclusivizeRangeSchema, InclusiveNumericRangeSchema, Pattern } from "@ark/schema";
2
- import type { associateAttributesFromStringSchema } from "../attributes.ts";
1
+ import type { ExactLength, ExclusiveNumericRangeSchema, InclusiveNumericRangeSchema, Pattern } from "@ark/schema";
3
2
  import type { BaseType } from "./base.ts";
4
3
  /** @ts-ignore cast variance */
5
4
  interface Type<out t extends string = string, $ = {}> extends BaseType<t, $> {
6
- matching<const schema extends Pattern.Schema>(schema: schema): Type<associateAttributesFromStringSchema<t, "pattern", schema>, $>;
7
- atLeastLength<const schema extends InclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromStringSchema<t, "minLength", schema>, $>;
8
- atMostLength<const schema extends InclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromStringSchema<t, "maxLength", schema>, $>;
9
- moreThanLength<const schema extends ExclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromStringSchema<t, "minLength", exclusivizeRangeSchema<schema>>, $>;
10
- lessThanLength<const schema extends ExclusiveNumericRangeSchema>(schema: schema): Type<associateAttributesFromStringSchema<t, "maxLength", exclusivizeRangeSchema<schema>>, $>;
11
- exactlyLength<const schema extends ExactLength.Schema>(schema: schema): Type<associateAttributesFromStringSchema<t, "exactLength", schema>, $>;
5
+ matching(schema: Pattern.Schema): this;
6
+ atLeastLength(schema: InclusiveNumericRangeSchema): this;
7
+ atMostLength(schema: InclusiveNumericRangeSchema): this;
8
+ moreThanLength(schema: ExclusiveNumericRangeSchema): this;
9
+ lessThanLength(schema: ExclusiveNumericRangeSchema): this;
10
+ exactlyLength(schema: ExactLength.Schema): this;
12
11
  }
13
12
  export type { Type as StringType };
@@ -0,0 +1,17 @@
1
+ import type { GenericAst, GenericParamAst, writeUnsatisfiedParameterConstraintMessage } from "@ark/schema";
2
+ import type { array, ErrorMessage, Hkt, typeToString } from "@ark/util";
3
+ import type { UnparsedScope } from "../../scope.ts";
4
+ import type { inferDefinition } from "../definition.ts";
5
+ import type { inferAstRoot, inferExpression } from "./infer.ts";
6
+ import type { astToString } from "./utils.ts";
7
+ import type { validateAst } from "./validate.ts";
8
+ export type GenericInstantiationAst<generic extends GenericAst = GenericAst, argAsts extends unknown[] = unknown[]> = [generic, "<>", argAsts];
9
+ export type inferGenericInstantiation<g extends GenericAst, argAsts extends unknown[], $, args> = g["bodyDef"] extends Hkt ? Hkt.apply<g["bodyDef"], {
10
+ [i in keyof argAsts]: inferExpression<argAsts[i], $, args>;
11
+ }> : inferDefinition<g["bodyDef"], resolveScope<g["$"], $>, {
12
+ [i in keyof g["names"] & `${number}` as g["names"][i]]: inferExpression<argAsts[i & keyof argAsts], resolveScope<g["arg$"], $>, args>;
13
+ }>;
14
+ export type validateGenericInstantiation<g extends GenericAst, argAsts extends unknown[], $, args> = validateGenericArgs<g["paramsAst"], argAsts, $, args, []>;
15
+ type validateGenericArgs<params extends array<GenericParamAst>, argAsts extends array, $, args, indices extends 1[]> = argAsts extends readonly [infer arg, ...infer argsTail] ? validateAst<arg, $, args> extends infer e extends ErrorMessage ? e : inferAstRoot<arg, $, args> extends params[indices["length"]][1] ? validateGenericArgs<params, argsTail, $, args, [...indices, 1]> : ErrorMessage<writeUnsatisfiedParameterConstraintMessage<params[indices["length"]][0], typeToString<params[indices["length"]][1]>, astToString<arg>>> : undefined;
16
+ type resolveScope<g$, $> = g$ extends UnparsedScope ? $ : g$;
17
+ export {};