@blamejs/core 0.4.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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
@@ -0,0 +1,1176 @@
1
+ "use strict";
2
+ /**
3
+ * safe-schema — declarative input validation, Zod-shaped surface.
4
+ *
5
+ * Built for: request-body validation, config validation, API payload
6
+ * validation, anywhere operators have an `unknown` shape they need
7
+ * to confirm before reading. Vendor-free; built on framework
8
+ * primitives. No JIT, no codegen, no chained-Promise weirdness.
9
+ *
10
+ * Public API:
11
+ * var s = b.safeSchema;
12
+ *
13
+ * var schema = s.object({
14
+ * email: s.string().email(),
15
+ * age: s.number().int().min(0).max(120),
16
+ * tags: s.array(s.string()).max(10),
17
+ * metadata: s.object({}).passthrough().optional(),
18
+ * });
19
+ *
20
+ * var result = schema.parse(input); // throws SafeSchemaError
21
+ * var safe = schema.safeParse(input); // → { ok, value?, errors? }
22
+ *
23
+ * // Errors carry per-field paths:
24
+ * // [{ path: ["age"], code: "number/too-large", message: "must be ≤ 120" }]
25
+ *
26
+ * Design choices:
27
+ * - Schemas are immutable. Chaining returns a new schema with one
28
+ * additional check; the original is untouched. Cheap because
29
+ * checks are concat'd into a small array, not deep-copied.
30
+ * - parse() throws SafeSchemaError carrying the full issues array;
31
+ * safeParse() never throws (operator-friendly for HTTP boundaries).
32
+ * - .optional() means "may be undefined"; .nullable() means "may be
33
+ * null"; .default(v) means "if undefined, substitute v";
34
+ * .catch(v) means "on ANY validation failure, substitute v".
35
+ * These compose: optional().default(0) → "may be undefined,
36
+ * in which case use 0".
37
+ * - Objects are STRICT by default: unknown keys produce an issue.
38
+ * Use .passthrough() to retain unknown keys, .strict() to flip
39
+ * back if a parent .passthrough() set the mode.
40
+ *
41
+ * Surface (every schema has these chained methods unless noted):
42
+ *
43
+ * Type constructors:
44
+ * string() .min, .max, .length, .regex, .email, .url, .uuid,
45
+ * .datetime (ISO-8601), .date (YYYY-MM-DD),
46
+ * .ip, .ipv4, .ipv6, .nonempty, .startsWith, .endsWith,
47
+ * .includes
48
+ * number() .int, .min, .max, .gt, .lt, .positive, .negative,
49
+ * .nonnegative, .nonpositive, .finite, .multipleOf
50
+ * boolean()
51
+ * literal(v)
52
+ * enum_([...]) | oneOf([...])
53
+ * null_(), undefined_(), any(), unknown()
54
+ *
55
+ * Composites:
56
+ * object({ ... }) .strict, .passthrough, .pick, .omit, .extend,
57
+ * .partial, .required (inverse of partial)
58
+ * array(item) .min, .max, .length, .nonempty
59
+ * tuple([...]) .rest(item) for variadic tails
60
+ * union([...]) first matching wins
61
+ * discriminatedUnion(key, [...]) faster + clearer-errors variant
62
+ * for tagged unions
63
+ * record(value) | record(key, value)
64
+ * lazy(() => schema) defer construction; for recursion
65
+ * preprocess(fn, schema) run fn before validation
66
+ *
67
+ * Modifiers (any schema):
68
+ * .optional() value may be undefined
69
+ * .nullable() value may be null
70
+ * .default(v|fn) undefined → v (implies optional). Function form
71
+ * is called per-parse for fresh values.
72
+ * .catch(v|fn) any failure → v (escape hatch for operator
73
+ * defaults; suppresses the error info, so use
74
+ * sparingly)
75
+ * .refine(fn, opts) custom predicate — returns false to fail
76
+ * .transform(fn) map the validated value to a new shape
77
+ * .pipe(next) feed validated output through `next` schema
78
+ * for a second round of validation
79
+ *
80
+ * Security guarantees:
81
+ * - Prototype-pollution defense: __proto__ / constructor / prototype
82
+ * keys are rejected at construction (object shape) and parse time
83
+ * (object + record input). Mirrors safe-json.js's POISONED_KEYS.
84
+ * - No code injection surface: regexes are static module-level
85
+ * constants; no string→regex parsing on the validation path; no
86
+ * eval/Function. Operator-supplied refine/transform fns are
87
+ * plain JS functions, not strings.
88
+ * - Predicate throws are caught: a refine() function throwing turns
89
+ * into a regular validation issue, not an unhandled exception.
90
+ * - Sync-only: no async refinements; operators await at the boundary.
91
+ *
92
+ * Deliberately not shipped (with structural reason):
93
+ * - z.bigint / z.date / z.map / z.set — no JSON representation; HTTP
94
+ * boundaries don't carry these. Use s.string().datetime() for
95
+ * ISO-8601 strings.
96
+ * - z.nativeEnum / z.never / z.void / z.function — TypeScript-specific.
97
+ * - z.coerce — loose-coercion is a security foot-gun (truthy/falsy
98
+ * ambiguity, "0" → 0 vs "0" → "0"). Operators do explicit
99
+ * s.preprocess(fn, schema) instead.
100
+ * - z.intersection — for object schemas use .extend(); intersections
101
+ * of unrelated schemas are structurally ambiguous.
102
+ * - z.brand — TypeScript compile-time tag with no runtime effect.
103
+ * - per-schema errorMap — operators chain .refine() with custom message.
104
+ *
105
+ * Relationship to forms.validate:
106
+ * forms.validate (HTML form spec validation) is a separate surface.
107
+ * Form specs carry HTML-specific concerns (checkbox coercion, select
108
+ * option allowlist) that don't belong on the general-purpose validator,
109
+ * so the two stay distinct rather than one wrapping the other.
110
+ */
111
+
112
+ var { defineClass } = require("./framework-error");
113
+
114
+ var SafeSchemaError = defineClass("SafeSchemaError", { alwaysPermanent: true });
115
+
116
+ // Prototype-pollution defense — these key names are rejected in object
117
+ // and record schemas regardless of mode (strict, passthrough, or lazy
118
+ // match). Mirrors safe-json.js's POISONED_KEYS set so the framework
119
+ // presents one consistent guarantee: an attacker cannot pollute
120
+ // Object.prototype by submitting a JSON body with __proto__ /
121
+ // constructor / prototype keys, even if the operator schema is
122
+ // .passthrough().
123
+ var POISONED_KEYS = new Set(["__proto__", "constructor", "prototype"]);
124
+
125
+ // Pragmatic regexes — RFC-correct is impractical without exploding the
126
+ // regex (especially email). Operators wanting deeper validation chain
127
+ // .refine() on top.
128
+ //
129
+ // All regexes are static module-level constants; nothing parses an input
130
+ // string into a regex on the validation path (no ReDoS-via-input vector,
131
+ // no dynamic regex compilation).
132
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
133
+ var URL_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s]+$/;
134
+ var UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/;
135
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
136
+ // ISO-8601 datetime with timezone (Z or ±HH:MM); fractional seconds optional.
137
+ var DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
138
+ var IPV4_RE = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
139
+ // CUID v1 / v2: 25-char base36, starts with 'c'. Common in TypeScript ecosystems.
140
+ var CUID_RE = /^c[a-z0-9]{24}$/;
141
+ // ULID: Crockford-base32, 26 chars, time-sortable.
142
+ var ULID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
143
+ // base64 (standard alphabet, with optional padding). Base64url variants
144
+ // rejected — operators chain .regex(...) for that.
145
+ var BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
146
+ // IPv6 — covers full, compressed (::), and IPv4-mapped forms. Not
147
+ // exhaustive on every legal corner, but rejects the common malformed
148
+ // inputs operators actually see at HTTP boundaries.
149
+ var IPV6_RE = /^(?:(?:[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}:){0,6}[0-9a-fA-F]{0,4}|(?:[0-9a-fA-F]{1,4}:){1,6}(?::[0-9a-fA-F]{1,4}){1,1}|(?:[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})$/;
150
+
151
+ // ---- helpers ----
152
+
153
+ function _fail(path, code, message) {
154
+ return { ok: false, issues: [{ path: path.slice(), code: code, message: message }] };
155
+ }
156
+
157
+ function _formatIssues(issues) {
158
+ if (!issues || issues.length === 0) return "(no issues)";
159
+ return issues.map(function (i) {
160
+ var p = i.path && i.path.length > 0 ? i.path.join(".") + ": " : "";
161
+ return p + i.message;
162
+ }).join("; ");
163
+ }
164
+
165
+ // Run a schema's modifier-aware pipeline. Used by both root parse() and
166
+ // child-key dispatch inside object/array/etc.
167
+ function _runWithModifiers(schema, value, path) {
168
+ // Apply default BEFORE catching, so a schema with both .default() and
169
+ // .catch() prefers the default for undefined input (predictable).
170
+ if (value === undefined) {
171
+ if (schema._hasDefault) value = typeof schema._default === "function" ? schema._default() : schema._default;
172
+ else if (schema._isOptional) return { ok: true, value: undefined };
173
+ else return _fail(path, "required", "is required");
174
+ }
175
+ if (value === null) {
176
+ if (schema._isNullable) return { ok: true, value: null };
177
+ if (schema._hasCatch) return { ok: true, value: schema._catch };
178
+ return _fail(path, "type", "must not be null");
179
+ }
180
+ var r = schema._run(value, path);
181
+ if (!r.ok && schema._hasCatch) {
182
+ return { ok: true, value: typeof schema._catch === "function" ? schema._catch() : schema._catch };
183
+ }
184
+ return r;
185
+ }
186
+
187
+ // ---- core schema factory ----
188
+ //
189
+ // Every schema stores:
190
+ // _kind — for diagnostics
191
+ // _isOptional, _isNullable, _hasDefault, _default, _hasCatch, _catch
192
+ // _run(value, path) — type check + checks pipeline
193
+ //
194
+ // Modifier methods (optional/nullable/default/catch/refine/transform) live
195
+ // on the prototype; chained methods are added by each constructor's
196
+ // builder (string adds .min/.max etc., array adds .min/.length, etc.).
197
+
198
+ function _baseSchema(spec) {
199
+ var s = {
200
+ _kind: spec.kind,
201
+ _isOptional: spec.isOptional || false,
202
+ _isNullable: spec.isNullable || false,
203
+ _hasDefault: spec.hasDefault || false,
204
+ _default: spec.defaultValue,
205
+ _hasCatch: spec.hasCatch || false,
206
+ _catch: spec.catchValue,
207
+ _run: spec.run,
208
+ };
209
+
210
+ s.parse = function (input) {
211
+ var r = _runWithModifiers(s, input, []);
212
+ if (r.ok) return r.value;
213
+ var err = new SafeSchemaError(
214
+ "safe-schema/invalid",
215
+ "validation failed: " + _formatIssues(r.issues)
216
+ );
217
+ err.issues = r.issues;
218
+ throw err;
219
+ };
220
+
221
+ s.safeParse = function (input) {
222
+ var r = _runWithModifiers(s, input, []);
223
+ if (r.ok) return { ok: true, value: r.value };
224
+ return { ok: false, errors: r.issues };
225
+ };
226
+
227
+ s.optional = function () {
228
+ return _baseSchema(_extendSpec(spec, { isOptional: true }));
229
+ };
230
+ s.nullable = function () {
231
+ return _baseSchema(_extendSpec(spec, { isNullable: true }));
232
+ };
233
+ s.default = function (v) {
234
+ return _baseSchema(_extendSpec(spec, { isOptional: true, hasDefault: true, defaultValue: v }));
235
+ };
236
+ s.catch = function (v) {
237
+ return _baseSchema(_extendSpec(spec, { hasCatch: true, catchValue: v }));
238
+ };
239
+ s.refine = function (predicate, opts) {
240
+ opts = opts || {};
241
+ var code = opts.code || "refine";
242
+ var message = opts.message || "failed custom validation";
243
+ var inner = s;
244
+ return _baseSchema(_extendSpec(spec, {
245
+ run: function (value, path) {
246
+ var r = inner._run(value, path);
247
+ if (!r.ok) return r;
248
+ try {
249
+ if (!predicate(r.value)) return _fail(path, code, message);
250
+ } catch (e) {
251
+ return _fail(path, code,
252
+ message + " (predicate threw: " + ((e && e.message) || String(e)) + ")");
253
+ }
254
+ return r;
255
+ },
256
+ }));
257
+ };
258
+ s.transform = function (fn) {
259
+ var inner = s;
260
+ return _baseSchema(_extendSpec(spec, {
261
+ run: function (value, path) {
262
+ var r = inner._run(value, path);
263
+ if (!r.ok) return r;
264
+ try {
265
+ return { ok: true, value: fn(r.value) };
266
+ } catch (e) {
267
+ return _fail(path, "transform",
268
+ "transform threw: " + ((e && e.message) || String(e)));
269
+ }
270
+ },
271
+ }));
272
+ };
273
+ // .pipe(next) — feed this schema's validated output into another
274
+ // schema for a second round of validation. Common idiom for
275
+ // "validate input shape, transform, re-validate output shape":
276
+ //
277
+ // var port = s.string().regex(/^\d+$/).transform(Number).pipe(
278
+ // s.number().int().min(1).max(65535)
279
+ // );
280
+ s.pipe = function (next) {
281
+ if (!next || typeof next._run !== "function") {
282
+ throw new SafeSchemaError("safe-schema/bad-pipe",
283
+ "pipe: argument must be a schema");
284
+ }
285
+ var inner = s;
286
+ return _baseSchema(_extendSpec(spec, {
287
+ run: function (value, path) {
288
+ var r = inner._run(value, path);
289
+ if (!r.ok) return r;
290
+ return _runWithModifiers(next, r.value, path);
291
+ },
292
+ }));
293
+ };
294
+
295
+ return s;
296
+ }
297
+
298
+ function _extendSpec(spec, overrides) {
299
+ return {
300
+ kind: overrides.kind != null ? overrides.kind : spec.kind,
301
+ isOptional: overrides.isOptional != null ? overrides.isOptional : spec.isOptional,
302
+ isNullable: overrides.isNullable != null ? overrides.isNullable : spec.isNullable,
303
+ hasDefault: overrides.hasDefault != null ? overrides.hasDefault : spec.hasDefault,
304
+ defaultValue: overrides.hasDefault != null ? overrides.defaultValue : spec.defaultValue,
305
+ hasCatch: overrides.hasCatch != null ? overrides.hasCatch : spec.hasCatch,
306
+ catchValue: overrides.hasCatch != null ? overrides.catchValue : spec.catchValue,
307
+ run: overrides.run != null ? overrides.run : spec.run,
308
+ };
309
+ }
310
+
311
+ // Adds a check fn into the schema's _run pipeline by composing it on top
312
+ // of the existing _run. Used by string/number/array builders to chain
313
+ // .min/.max/etc. onto an existing schema instance.
314
+ //
315
+ // The check fn returns either:
316
+ // { ok: true } — pass; keep the inner value unchanged
317
+ // { ok: true, value: newVal } — pass and mutate the value (used by
318
+ // ergonomic transforms like .trim())
319
+ // { ok: false, issues } — fail with the given issue
320
+ function _withCheck(schema, spec, check) {
321
+ var inner = schema;
322
+ return _baseSchema(_extendSpec(spec, {
323
+ run: function (value, path) {
324
+ var r = inner._run(value, path);
325
+ if (!r.ok) return r;
326
+ var cr = check(r.value, path);
327
+ if (!cr.ok) return cr;
328
+ if (Object.prototype.hasOwnProperty.call(cr, "value")) {
329
+ return { ok: true, value: cr.value };
330
+ }
331
+ return r;
332
+ },
333
+ }));
334
+ }
335
+
336
+ // ---- string ----
337
+
338
+ function string() {
339
+ var spec = {
340
+ kind: "string",
341
+ run: function (value, path) {
342
+ if (typeof value !== "string") return _fail(path, "type", "must be a string");
343
+ return { ok: true, value: value };
344
+ },
345
+ };
346
+ return _stringMethods(_baseSchema(spec), spec);
347
+ }
348
+
349
+ function _stringMethods(schema, spec) {
350
+ function chain(check) {
351
+ var next = _withCheck(schema, spec, check);
352
+ return _stringMethods(next, _extendSpec(spec, { run: next._run }));
353
+ }
354
+ schema.min = function (n, msg) {
355
+ return chain(function (v, p) {
356
+ return v.length >= n ? { ok: true } :
357
+ _fail(p, "string/too-short", msg || ("must be at least " + n + " characters"));
358
+ });
359
+ };
360
+ schema.max = function (n, msg) {
361
+ return chain(function (v, p) {
362
+ return v.length <= n ? { ok: true } :
363
+ _fail(p, "string/too-long", msg || ("must be at most " + n + " characters"));
364
+ });
365
+ };
366
+ schema.length = function (n, msg) {
367
+ return chain(function (v, p) {
368
+ return v.length === n ? { ok: true } :
369
+ _fail(p, "string/wrong-length", msg || ("must be exactly " + n + " characters"));
370
+ });
371
+ };
372
+ schema.nonempty = function (msg) { return schema.min(1, msg || "must not be empty"); };
373
+ schema.regex = function (re, msg) {
374
+ return chain(function (v, p) {
375
+ return re.test(v) ? { ok: true } :
376
+ _fail(p, "string/regex", msg || "does not match required pattern");
377
+ });
378
+ };
379
+ schema.startsWith = function (prefix, msg) {
380
+ return chain(function (v, p) {
381
+ return v.indexOf(prefix) === 0 ? { ok: true } :
382
+ _fail(p, "string/starts-with", msg || "must start with '" + prefix + "'");
383
+ });
384
+ };
385
+ schema.endsWith = function (suffix, msg) {
386
+ return chain(function (v, p) {
387
+ return v.length >= suffix.length && v.slice(-suffix.length) === suffix ? { ok: true } :
388
+ _fail(p, "string/ends-with", msg || "must end with '" + suffix + "'");
389
+ });
390
+ };
391
+ schema.includes = function (needle, msg) {
392
+ return chain(function (v, p) {
393
+ return v.indexOf(needle) !== -1 ? { ok: true } :
394
+ _fail(p, "string/includes", msg || "must include '" + needle + "'");
395
+ });
396
+ };
397
+ schema.email = function () {
398
+ return chain(function (v, p) {
399
+ return EMAIL_RE.test(v) ? { ok: true } :
400
+ _fail(p, "string/email", "must be a valid email address");
401
+ });
402
+ };
403
+ schema.url = function () {
404
+ return chain(function (v, p) {
405
+ return URL_RE.test(v) ? { ok: true } :
406
+ _fail(p, "string/url", "must be a valid URL");
407
+ });
408
+ };
409
+ schema.uuid = function () {
410
+ return chain(function (v, p) {
411
+ return UUID_RE.test(v) ? { ok: true } :
412
+ _fail(p, "string/uuid", "must be a valid UUID");
413
+ });
414
+ };
415
+ schema.date = function () {
416
+ return chain(function (v, p) {
417
+ return DATE_RE.test(v) ? { ok: true } :
418
+ _fail(p, "string/date", "must be a YYYY-MM-DD date");
419
+ });
420
+ };
421
+ schema.datetime = function () {
422
+ return chain(function (v, p) {
423
+ return DATETIME_RE.test(v) ? { ok: true } :
424
+ _fail(p, "string/datetime", "must be an ISO-8601 datetime with timezone");
425
+ });
426
+ };
427
+ schema.ipv4 = function () {
428
+ return chain(function (v, p) {
429
+ return IPV4_RE.test(v) ? { ok: true } :
430
+ _fail(p, "string/ipv4", "must be a valid IPv4 address");
431
+ });
432
+ };
433
+ schema.ipv6 = function () {
434
+ return chain(function (v, p) {
435
+ return IPV6_RE.test(v) ? { ok: true } :
436
+ _fail(p, "string/ipv6", "must be a valid IPv6 address");
437
+ });
438
+ };
439
+ schema.ip = function () {
440
+ return chain(function (v, p) {
441
+ return (IPV4_RE.test(v) || IPV6_RE.test(v)) ? { ok: true } :
442
+ _fail(p, "string/ip", "must be a valid IP address (v4 or v6)");
443
+ });
444
+ };
445
+ schema.cuid = function () {
446
+ return chain(function (v, p) {
447
+ return CUID_RE.test(v) ? { ok: true } :
448
+ _fail(p, "string/cuid", "must be a valid CUID");
449
+ });
450
+ };
451
+ schema.ulid = function () {
452
+ return chain(function (v, p) {
453
+ return ULID_RE.test(v) ? { ok: true } :
454
+ _fail(p, "string/ulid", "must be a valid ULID");
455
+ });
456
+ };
457
+ schema.base64 = function () {
458
+ return chain(function (v, p) {
459
+ return BASE64_RE.test(v) ? { ok: true } :
460
+ _fail(p, "string/base64", "must be valid base64 (standard alphabet)");
461
+ });
462
+ };
463
+ // Coercion-via-transform — these mutate the validated string before
464
+ // the next check runs. Apply EARLY in the chain (before .min, .email,
465
+ // etc.) so subsequent checks see the normalized form.
466
+ schema.trim = function () {
467
+ return chain(function (v) { return { ok: true, value: v.trim() }; });
468
+ };
469
+ schema.toLowerCase = function () {
470
+ return chain(function (v) { return { ok: true, value: v.toLowerCase() }; });
471
+ };
472
+ schema.toUpperCase = function () {
473
+ return chain(function (v) { return { ok: true, value: v.toUpperCase() }; });
474
+ };
475
+ return schema;
476
+ }
477
+
478
+ // ---- number ----
479
+
480
+ function number() {
481
+ var spec = {
482
+ kind: "number",
483
+ run: function (value, path) {
484
+ if (typeof value !== "number" || Number.isNaN(value)) {
485
+ return _fail(path, "type", "must be a number");
486
+ }
487
+ return { ok: true, value: value };
488
+ },
489
+ };
490
+ return _numberMethods(_baseSchema(spec), spec);
491
+ }
492
+
493
+ function _numberMethods(schema, spec) {
494
+ function chain(check) {
495
+ var next = _withCheck(schema, spec, check);
496
+ return _numberMethods(next, _extendSpec(spec, { run: next._run }));
497
+ }
498
+ schema.int = function (msg) {
499
+ return chain(function (v, p) {
500
+ return Number.isInteger(v) ? { ok: true } :
501
+ _fail(p, "number/not-integer", msg || "must be an integer");
502
+ });
503
+ };
504
+ schema.min = function (n, msg) {
505
+ return chain(function (v, p) {
506
+ return v >= n ? { ok: true } : _fail(p, "number/too-small", msg || ("must be ≥ " + n));
507
+ });
508
+ };
509
+ schema.max = function (n, msg) {
510
+ return chain(function (v, p) {
511
+ return v <= n ? { ok: true } : _fail(p, "number/too-large", msg || ("must be ≤ " + n));
512
+ });
513
+ };
514
+ schema.gt = function (n, msg) {
515
+ return chain(function (v, p) {
516
+ return v > n ? { ok: true } : _fail(p, "number/not-gt", msg || ("must be > " + n));
517
+ });
518
+ };
519
+ schema.lt = function (n, msg) {
520
+ return chain(function (v, p) {
521
+ return v < n ? { ok: true } : _fail(p, "number/not-lt", msg || ("must be < " + n));
522
+ });
523
+ };
524
+ schema.positive = function (msg) { return schema.gt(0, msg || "must be positive"); };
525
+ schema.negative = function (msg) { return schema.lt(0, msg || "must be negative"); };
526
+ schema.nonnegative = function (msg) { return schema.min(0, msg || "must be non-negative"); };
527
+ schema.nonpositive = function (msg) { return schema.max(0, msg || "must be non-positive"); };
528
+ schema.finite = function (msg) {
529
+ return chain(function (v, p) {
530
+ return Number.isFinite(v) ? { ok: true } :
531
+ _fail(p, "number/not-finite", msg || "must be a finite number");
532
+ });
533
+ };
534
+ // safe() — Number.isSafeInteger range. Important for IDs that round-trip
535
+ // through JSON (which can't represent BigInts) and need to survive without
536
+ // precision loss.
537
+ schema.safe = function (msg) {
538
+ return chain(function (v, p) {
539
+ return Number.isSafeInteger(v) ? { ok: true } :
540
+ _fail(p, "number/not-safe", msg || "must be a safe integer (within ±2^53)");
541
+ });
542
+ };
543
+ schema.multipleOf = function (n, msg) {
544
+ return chain(function (v, p) {
545
+ // Use modulo with fp tolerance — exact mod on floats is fragile.
546
+ var quot = v / n;
547
+ return Math.abs(quot - Math.round(quot)) < 1e-9 ? { ok: true } :
548
+ _fail(p, "number/not-multiple-of", msg || ("must be a multiple of " + n));
549
+ });
550
+ };
551
+ return schema;
552
+ }
553
+
554
+ // ---- boolean ----
555
+
556
+ function boolean() {
557
+ return _baseSchema({
558
+ kind: "boolean",
559
+ run: function (value, path) {
560
+ if (typeof value !== "boolean") return _fail(path, "type", "must be a boolean");
561
+ return { ok: true, value: value };
562
+ },
563
+ });
564
+ }
565
+
566
+ // ---- literal ----
567
+
568
+ function literal(expected) {
569
+ return _baseSchema({
570
+ kind: "literal",
571
+ run: function (value, path) {
572
+ if (value !== expected) {
573
+ return _fail(path, "literal", "must be exactly " + JSON.stringify(expected));
574
+ }
575
+ return { ok: true, value: value };
576
+ },
577
+ });
578
+ }
579
+
580
+ // ---- enum / oneOf ----
581
+
582
+ function enum_(values) {
583
+ if (!Array.isArray(values) || values.length === 0) {
584
+ throw new SafeSchemaError("safe-schema/bad-enum",
585
+ "enum requires a non-empty array of allowed values");
586
+ }
587
+ var allowedSet = new Set(values);
588
+ return _baseSchema({
589
+ kind: "enum",
590
+ run: function (value, path) {
591
+ if (!allowedSet.has(value)) {
592
+ return _fail(path, "enum",
593
+ "must be one of: " + values.map(function (v) { return JSON.stringify(v); }).join(", "));
594
+ }
595
+ return { ok: true, value: value };
596
+ },
597
+ });
598
+ }
599
+
600
+ // ---- null / undefined / any / unknown ----
601
+
602
+ function null_() {
603
+ return _baseSchema({
604
+ kind: "null",
605
+ isNullable: true,
606
+ run: function (value, path) {
607
+ // Modifier handler accepts null already; if we got here, value is non-null.
608
+ return _fail(path, "type", "must be null");
609
+ },
610
+ });
611
+ }
612
+
613
+ function undefined_() {
614
+ return _baseSchema({
615
+ kind: "undefined",
616
+ isOptional: true,
617
+ run: function (_value, path) {
618
+ return _fail(path, "type", "must be undefined");
619
+ },
620
+ });
621
+ }
622
+
623
+ function any() {
624
+ return _baseSchema({
625
+ kind: "any",
626
+ isOptional: true,
627
+ isNullable: true,
628
+ run: function (value) { return { ok: true, value: value }; },
629
+ });
630
+ }
631
+
632
+ function unknown() { return any(); }
633
+
634
+ // ---- object ----
635
+
636
+ function object(shape) {
637
+ if (shape == null || typeof shape !== "object") {
638
+ throw new SafeSchemaError("safe-schema/bad-shape",
639
+ "object() requires a shape object mapping field name to schema");
640
+ }
641
+ // Use getOwnPropertyNames so an operator who built the shape via
642
+ // Object.fromEntries / defineProperty (the only paths by which a
643
+ // POISONED_KEYS name can appear as an own property — object-literal
644
+ // {"__proto__": ...} syntax sets the prototype rather than creating
645
+ // such a key) gets a refusal at construction time.
646
+ var allOwnKeys = Object.getOwnPropertyNames(shape);
647
+ for (var ai = 0; ai < allOwnKeys.length; ai++) {
648
+ if (POISONED_KEYS.has(allOwnKeys[ai])) {
649
+ throw new SafeSchemaError("safe-schema/poisoned-shape-key",
650
+ "object shape: key '" + allOwnKeys[ai] + "' is forbidden (prototype-pollution defense)");
651
+ }
652
+ }
653
+ var keys = Object.keys(shape);
654
+ for (var k = 0; k < keys.length; k++) {
655
+ if (!shape[keys[k]] || typeof shape[keys[k]]._run !== "function") {
656
+ throw new SafeSchemaError("safe-schema/bad-shape",
657
+ "object shape: '" + keys[k] + "' is not a schema");
658
+ }
659
+ }
660
+ return _objectWithMode(shape, keys, "strict");
661
+ }
662
+
663
+ function _objectWithMode(shape, keys, mode) {
664
+ var spec = {
665
+ kind: "object",
666
+ run: function (value, path) {
667
+ if (typeof value !== "object" || Array.isArray(value)) {
668
+ return _fail(path, "type", "must be an object");
669
+ }
670
+ var issues = [];
671
+ var out = {};
672
+ for (var i = 0; i < keys.length; i++) {
673
+ var key = keys[i];
674
+ var sub = shape[key];
675
+ var childPath = path.concat([key]);
676
+ var r = _runWithModifiers(sub, value[key], childPath);
677
+ if (!r.ok) {
678
+ for (var j = 0; j < r.issues.length; j++) issues.push(r.issues[j]);
679
+ continue;
680
+ }
681
+ if (r.value !== undefined) out[key] = r.value;
682
+ }
683
+ var inputKeys = Object.keys(value);
684
+ for (var ii = 0; ii < inputKeys.length; ii++) {
685
+ var ik = inputKeys[ii];
686
+ if (Object.prototype.hasOwnProperty.call(shape, ik)) continue;
687
+ // Prototype-pollution defense — refuse __proto__/constructor/
688
+ // prototype regardless of mode. .passthrough() never propagates
689
+ // these because they are always rejected as input.
690
+ if (POISONED_KEYS.has(ik)) {
691
+ issues.push({
692
+ path: path.concat([ik]),
693
+ code: "object/poisoned-key",
694
+ message: "key '" + ik + "' is forbidden (prototype-pollution defense)",
695
+ });
696
+ continue;
697
+ }
698
+ if (mode === "passthrough") {
699
+ out[ik] = value[ik];
700
+ } else {
701
+ issues.push({
702
+ path: path.concat([ik]),
703
+ code: "object/unknown-key",
704
+ message: "unknown key '" + ik + "' (use .passthrough() to allow extra keys)",
705
+ });
706
+ }
707
+ }
708
+ if (issues.length > 0) return { ok: false, issues: issues };
709
+ return { ok: true, value: out };
710
+ },
711
+ };
712
+ var schema = _baseSchema(spec);
713
+ schema.shape = shape;
714
+ schema.strict = function () { return _objectWithMode(shape, keys, "strict"); };
715
+ schema.passthrough = function () { return _objectWithMode(shape, keys, "passthrough"); };
716
+
717
+ // .pick(["a","b"]) → narrow to listed keys
718
+ schema.pick = function (pickKeys) {
719
+ var newShape = {};
720
+ for (var i = 0; i < pickKeys.length; i++) {
721
+ var k = pickKeys[i];
722
+ if (Object.prototype.hasOwnProperty.call(shape, k)) newShape[k] = shape[k];
723
+ }
724
+ return _objectWithMode(newShape, Object.keys(newShape), mode);
725
+ };
726
+ // .omit(["a","b"]) → drop listed keys
727
+ schema.omit = function (omitKeys) {
728
+ var omitSet = new Set(omitKeys);
729
+ var newShape = {};
730
+ var newKeys = [];
731
+ for (var i = 0; i < keys.length; i++) {
732
+ if (!omitSet.has(keys[i])) {
733
+ newShape[keys[i]] = shape[keys[i]];
734
+ newKeys.push(keys[i]);
735
+ }
736
+ }
737
+ return _objectWithMode(newShape, newKeys, mode);
738
+ };
739
+ // .extend({ ... }) → merge additional shape; new keys override
740
+ schema.extend = function (additional) {
741
+ if (!additional || typeof additional !== "object") {
742
+ throw new SafeSchemaError("safe-schema/bad-extend",
743
+ "extend() requires a shape object");
744
+ }
745
+ var merged = Object.assign({}, shape, additional);
746
+ return _objectWithMode(merged, Object.keys(merged), mode);
747
+ };
748
+ // .partial() → mark every key optional
749
+ schema.partial = function () {
750
+ var newShape = {};
751
+ var newKeys = [];
752
+ for (var i = 0; i < keys.length; i++) {
753
+ newShape[keys[i]] = shape[keys[i]].optional();
754
+ newKeys.push(keys[i]);
755
+ }
756
+ return _objectWithMode(newShape, newKeys, mode);
757
+ };
758
+ // .required() — inverse of partial(). Strips optional + default + nullable
759
+ // off every key (operators sometimes call .partial() and then peel back
760
+ // a subset; this is the cleanest path).
761
+ schema.required = function () {
762
+ var newShape = {};
763
+ var newKeys = [];
764
+ for (var i = 0; i < keys.length; i++) {
765
+ var inner = shape[keys[i]];
766
+ // Strip modifiers by rebuilding without them. We don't have the
767
+ // pre-modifier schema cached, but we can reach it: the underlying
768
+ // _run is preserved; clone with all modifier flags off.
769
+ newShape[keys[i]] = _baseSchema({
770
+ kind: inner._kind,
771
+ isOptional: false,
772
+ isNullable: false,
773
+ hasDefault: false,
774
+ hasCatch: inner._hasCatch,
775
+ catchValue: inner._catch,
776
+ run: inner._run,
777
+ });
778
+ newKeys.push(keys[i]);
779
+ }
780
+ return _objectWithMode(newShape, newKeys, mode);
781
+ };
782
+ return schema;
783
+ }
784
+
785
+ // ---- array ----
786
+
787
+ function array(itemSchema) {
788
+ if (!itemSchema || typeof itemSchema._run !== "function") {
789
+ throw new SafeSchemaError("safe-schema/bad-item",
790
+ "array() requires an item schema");
791
+ }
792
+ var spec = {
793
+ kind: "array",
794
+ run: function (value, path) {
795
+ if (!Array.isArray(value)) return _fail(path, "type", "must be an array");
796
+ var issues = [];
797
+ var out = [];
798
+ for (var i = 0; i < value.length; i++) {
799
+ var childPath = path.concat([i]);
800
+ var r = _runWithModifiers(itemSchema, value[i], childPath);
801
+ if (!r.ok) {
802
+ for (var j = 0; j < r.issues.length; j++) issues.push(r.issues[j]);
803
+ continue;
804
+ }
805
+ out.push(r.value);
806
+ }
807
+ if (issues.length > 0) return { ok: false, issues: issues };
808
+ return { ok: true, value: out };
809
+ },
810
+ };
811
+ return _arrayMethods(_baseSchema(spec), spec);
812
+ }
813
+
814
+ function _arrayMethods(schema, spec) {
815
+ function chain(check) {
816
+ var next = _withCheck(schema, spec, check);
817
+ return _arrayMethods(next, _extendSpec(spec, { run: next._run }));
818
+ }
819
+ schema.min = function (n, msg) {
820
+ return chain(function (v, p) {
821
+ return v.length >= n ? { ok: true } :
822
+ _fail(p, "array/too-short", msg || ("must contain at least " + n + " items"));
823
+ });
824
+ };
825
+ schema.max = function (n, msg) {
826
+ return chain(function (v, p) {
827
+ return v.length <= n ? { ok: true } :
828
+ _fail(p, "array/too-long", msg || ("must contain at most " + n + " items"));
829
+ });
830
+ };
831
+ schema.length = function (n, msg) {
832
+ return chain(function (v, p) {
833
+ return v.length === n ? { ok: true } :
834
+ _fail(p, "array/wrong-length", msg || ("must contain exactly " + n + " items"));
835
+ });
836
+ };
837
+ schema.nonempty = function (msg) { return schema.min(1, msg || "must not be empty"); };
838
+ return schema;
839
+ }
840
+
841
+ // ---- tuple ----
842
+
843
+ function tuple(items) {
844
+ if (!Array.isArray(items) || items.length === 0) {
845
+ throw new SafeSchemaError("safe-schema/bad-tuple",
846
+ "tuple() requires a non-empty array of item schemas");
847
+ }
848
+ for (var i = 0; i < items.length; i++) {
849
+ if (!items[i] || typeof items[i]._run !== "function") {
850
+ throw new SafeSchemaError("safe-schema/bad-tuple",
851
+ "tuple item " + i + " is not a schema");
852
+ }
853
+ }
854
+ return _tupleWithRest(items, null);
855
+ }
856
+
857
+ function _tupleWithRest(items, restSchema) {
858
+ var schema = _baseSchema({
859
+ kind: "tuple",
860
+ run: function (value, path) {
861
+ if (!Array.isArray(value)) return _fail(path, "type", "must be an array (tuple)");
862
+ if (restSchema === null && value.length !== items.length) {
863
+ return _fail(path, "tuple/wrong-length",
864
+ "tuple must contain exactly " + items.length + " items (got " + value.length + ")");
865
+ }
866
+ if (restSchema !== null && value.length < items.length) {
867
+ return _fail(path, "tuple/wrong-length",
868
+ "tuple must contain at least " + items.length + " items (got " + value.length + ")");
869
+ }
870
+ var issues = [];
871
+ var out = [];
872
+ for (var i = 0; i < items.length; i++) {
873
+ var r = _runWithModifiers(items[i], value[i], path.concat([i]));
874
+ if (!r.ok) {
875
+ for (var j = 0; j < r.issues.length; j++) issues.push(r.issues[j]);
876
+ continue;
877
+ }
878
+ out.push(r.value);
879
+ }
880
+ // Variadic tail — every extra item is checked against restSchema.
881
+ if (restSchema !== null) {
882
+ for (var k = items.length; k < value.length; k++) {
883
+ var rr = _runWithModifiers(restSchema, value[k], path.concat([k]));
884
+ if (!rr.ok) {
885
+ for (var jj = 0; jj < rr.issues.length; jj++) issues.push(rr.issues[jj]);
886
+ continue;
887
+ }
888
+ out.push(rr.value);
889
+ }
890
+ }
891
+ if (issues.length > 0) return { ok: false, issues: issues };
892
+ return { ok: true, value: out };
893
+ },
894
+ });
895
+ // .rest(itemSchema) — append a variadic tail to the tuple. Common for
896
+ // protocol shapes like [verb, ...args] or [event, payload, ...metadata].
897
+ schema.rest = function (item) {
898
+ if (!item || typeof item._run !== "function") {
899
+ throw new SafeSchemaError("safe-schema/bad-tuple-rest",
900
+ "tuple.rest(): argument must be a schema");
901
+ }
902
+ return _tupleWithRest(items, item);
903
+ };
904
+ return schema;
905
+ }
906
+
907
+ // ---- union ----
908
+
909
+ function union(options) {
910
+ if (!Array.isArray(options) || options.length === 0) {
911
+ throw new SafeSchemaError("safe-schema/bad-union",
912
+ "union() requires a non-empty array of option schemas");
913
+ }
914
+ for (var i = 0; i < options.length; i++) {
915
+ if (!options[i] || typeof options[i]._run !== "function") {
916
+ throw new SafeSchemaError("safe-schema/bad-union",
917
+ "union option " + i + " is not a schema");
918
+ }
919
+ }
920
+ return _baseSchema({
921
+ kind: "union",
922
+ run: function (value, path) {
923
+ var collected = [];
924
+ for (var i = 0; i < options.length; i++) {
925
+ var r = _runWithModifiers(options[i], value, path);
926
+ if (r.ok) return r;
927
+ // Collect each option's issues so the operator sees the full
928
+ // failure surface; helpful for debugging which option matched
929
+ // most closely.
930
+ for (var j = 0; j < r.issues.length; j++) collected.push(r.issues[j]);
931
+ }
932
+ // No option matched — emit a union-level issue at the parent path
933
+ // plus the collected per-option issues for deep diagnostics.
934
+ var summary = _fail(path, "union",
935
+ "did not match any of the " + options.length + " allowed shapes");
936
+ summary.issues = summary.issues.concat(collected);
937
+ return summary;
938
+ },
939
+ });
940
+ }
941
+
942
+ // ---- record ----
943
+ // record(value) — string keys, schema-typed values
944
+ // record(keySchema, value) — both keys and values are schema-validated
945
+
946
+ function record(a, b) {
947
+ var keySchema, valueSchema;
948
+ if (b === undefined) {
949
+ keySchema = null; // any string key
950
+ valueSchema = a;
951
+ } else {
952
+ keySchema = a;
953
+ valueSchema = b;
954
+ }
955
+ if (!valueSchema || typeof valueSchema._run !== "function") {
956
+ throw new SafeSchemaError("safe-schema/bad-value-schema",
957
+ "record() requires a value schema");
958
+ }
959
+ if (keySchema && typeof keySchema._run !== "function") {
960
+ throw new SafeSchemaError("safe-schema/bad-key-schema",
961
+ "record(keySchema, valueSchema): keySchema must be a schema");
962
+ }
963
+ return _baseSchema({
964
+ kind: "record",
965
+ run: function (value, path) {
966
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
967
+ return _fail(path, "type", "must be a plain object (record)");
968
+ }
969
+ var issues = [];
970
+ var out = {};
971
+ var keys = Object.keys(value);
972
+ for (var i = 0; i < keys.length; i++) {
973
+ var k = keys[i];
974
+ // Prototype-pollution defense — same shape as object() schema.
975
+ if (POISONED_KEYS.has(k)) {
976
+ issues.push({
977
+ path: path.concat([k]),
978
+ code: "record/poisoned-key",
979
+ message: "key '" + k + "' is forbidden (prototype-pollution defense)",
980
+ });
981
+ continue;
982
+ }
983
+ if (keySchema) {
984
+ var kr = _runWithModifiers(keySchema, k, path.concat([k]));
985
+ if (!kr.ok) {
986
+ for (var jj = 0; jj < kr.issues.length; jj++) issues.push(kr.issues[jj]);
987
+ continue;
988
+ }
989
+ }
990
+ var r = _runWithModifiers(valueSchema, value[k], path.concat([k]));
991
+ if (!r.ok) {
992
+ for (var j = 0; j < r.issues.length; j++) issues.push(r.issues[j]);
993
+ continue;
994
+ }
995
+ if (r.value !== undefined) out[k] = r.value;
996
+ }
997
+ if (issues.length > 0) return { ok: false, issues: issues };
998
+ return { ok: true, value: out };
999
+ },
1000
+ });
1001
+ }
1002
+
1003
+ // ---- discriminatedUnion ----
1004
+ //
1005
+ // Performance + ergonomics improvement over union for the common case
1006
+ // of "tagged variants": a literal field on each option distinguishes
1007
+ // the branches, so we dispatch on that field's value directly rather
1008
+ // than trying every option in turn.
1009
+ //
1010
+ // var event = s.discriminatedUnion("kind", [
1011
+ // s.object({ kind: s.literal("created"), at: s.string().datetime() }),
1012
+ // s.object({ kind: s.literal("deleted"), reason: s.string() }),
1013
+ // ]);
1014
+ //
1015
+ // Each option must be an object schema whose `discriminator` key is a
1016
+ // literal schema. Mismatched discriminator fails fast with a clear
1017
+ // "expected one of [...]" message rather than burying the operator in
1018
+ // per-branch issues.
1019
+ function discriminatedUnion(discriminator, options) {
1020
+ if (typeof discriminator !== "string" || discriminator.length === 0) {
1021
+ throw new SafeSchemaError("safe-schema/bad-discriminator",
1022
+ "discriminatedUnion: discriminator must be a non-empty string key name");
1023
+ }
1024
+ if (POISONED_KEYS.has(discriminator)) {
1025
+ throw new SafeSchemaError("safe-schema/poisoned-discriminator",
1026
+ "discriminatedUnion: discriminator key '" + discriminator + "' is forbidden");
1027
+ }
1028
+ if (!Array.isArray(options) || options.length === 0) {
1029
+ throw new SafeSchemaError("safe-schema/bad-union",
1030
+ "discriminatedUnion: options must be a non-empty array");
1031
+ }
1032
+ for (var i = 0; i < options.length; i++) {
1033
+ var opt = options[i];
1034
+ if (!opt || opt._kind !== "object" || !opt.shape) {
1035
+ throw new SafeSchemaError("safe-schema/bad-discriminated-option",
1036
+ "discriminatedUnion option " + i + " must be an object schema");
1037
+ }
1038
+ var disc = opt.shape[discriminator];
1039
+ if (!disc || disc._kind !== "literal") {
1040
+ throw new SafeSchemaError("safe-schema/bad-discriminated-option",
1041
+ "discriminatedUnion option " + i + ": discriminator '" + discriminator +
1042
+ "' must be a literal schema");
1043
+ }
1044
+ // The literal's expected value lives in its closure; we extract via
1045
+ // a probe rather than introspection. literal(v)._run(v) succeeds.
1046
+ // We sample by trying every option's discriminator separately at
1047
+ // dispatch time (cheap; literal._run is just a triple-equals).
1048
+ }
1049
+ return _baseSchema({
1050
+ kind: "discriminatedUnion",
1051
+ run: function (value, path) {
1052
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1053
+ return _fail(path, "type", "must be an object (discriminated union)");
1054
+ }
1055
+ var disc = value[discriminator];
1056
+ // Find the option whose discriminator schema accepts disc.
1057
+ for (var i = 0; i < options.length; i++) {
1058
+ var opt = options[i];
1059
+ var d = opt.shape[discriminator];
1060
+ var dr = d._run(disc, path.concat([discriminator]));
1061
+ if (dr.ok) {
1062
+ return _runWithModifiers(opt, value, path);
1063
+ }
1064
+ }
1065
+ return _fail(path.concat([discriminator]), "discriminated-union/no-match",
1066
+ "discriminator '" + discriminator + "' did not match any option");
1067
+ },
1068
+ });
1069
+ }
1070
+
1071
+ // ---- preprocess ----
1072
+ //
1073
+ // Run a transform BEFORE validation. Common at HTTP boundaries where
1074
+ // query strings arrive as strings but the operator wants a number /
1075
+ // boolean schema downstream.
1076
+ //
1077
+ // var port = s.preprocess(function (v) { return Number(v); }, s.number().int().min(1).max(65535));
1078
+ //
1079
+ // fn errors propagate as a 'preprocess' issue at the parent path; they
1080
+ // don't crash the validate call.
1081
+ function preprocess(fn, inner) {
1082
+ if (typeof fn !== "function") {
1083
+ throw new SafeSchemaError("safe-schema/bad-preprocess",
1084
+ "preprocess: first arg must be a function");
1085
+ }
1086
+ if (!inner || typeof inner._run !== "function") {
1087
+ throw new SafeSchemaError("safe-schema/bad-preprocess",
1088
+ "preprocess: second arg must be a schema");
1089
+ }
1090
+ return _baseSchema({
1091
+ kind: "preprocess",
1092
+ run: function (value, path) {
1093
+ var preprocessed;
1094
+ try {
1095
+ preprocessed = fn(value);
1096
+ } catch (e) {
1097
+ return _fail(path, "preprocess",
1098
+ "preprocess fn threw: " + ((e && e.message) || String(e)));
1099
+ }
1100
+ return _runWithModifiers(inner, preprocessed, path);
1101
+ },
1102
+ });
1103
+ }
1104
+
1105
+ // ---- lazy (recursive schemas) ----
1106
+ //
1107
+ // Defers schema construction until first parse. Operators wanting a
1108
+ // recursive shape — comment threads, file-tree nodes, etc. — wrap the
1109
+ // recursive reference in a function that returns the schema:
1110
+ //
1111
+ // var commentSchema = s.object({
1112
+ // id: s.string(),
1113
+ // replies: s.array(s.lazy(function () { return commentSchema; })),
1114
+ // });
1115
+ //
1116
+ // The function is called lazily and cached per-call site; cycles in the
1117
+ // returned schema are fine.
1118
+ function lazy(getter) {
1119
+ if (typeof getter !== "function") {
1120
+ throw new SafeSchemaError("safe-schema/bad-lazy",
1121
+ "lazy: argument must be a function returning a schema");
1122
+ }
1123
+ var cached = null;
1124
+ return _baseSchema({
1125
+ kind: "lazy",
1126
+ run: function (value, path) {
1127
+ if (!cached) {
1128
+ cached = getter();
1129
+ if (!cached || typeof cached._run !== "function") {
1130
+ return _fail(path, "lazy",
1131
+ "lazy() function did not return a schema");
1132
+ }
1133
+ }
1134
+ return _runWithModifiers(cached, value, path);
1135
+ },
1136
+ });
1137
+ }
1138
+
1139
+ // ---- top-level modifier helpers ----
1140
+
1141
+ function optional(inner) { return inner.optional(); }
1142
+ function nullable(inner) { return inner.nullable(); }
1143
+
1144
+ module.exports = {
1145
+ // Primitives
1146
+ string: string,
1147
+ number: number,
1148
+ boolean: boolean,
1149
+ literal: literal,
1150
+ null_: null_,
1151
+ undefined_: undefined_,
1152
+ any: any,
1153
+ unknown: unknown,
1154
+
1155
+ // Composites
1156
+ object: object,
1157
+ array: array,
1158
+ tuple: tuple,
1159
+ union: union,
1160
+ discriminatedUnion: discriminatedUnion,
1161
+ record: record,
1162
+ lazy: lazy,
1163
+ preprocess: preprocess,
1164
+
1165
+ // enum is a reserved word in some tooling — ship both names
1166
+ enum_: enum_,
1167
+ oneOf: enum_,
1168
+
1169
+ // Modifier helpers (chained methods exist on every schema; these are
1170
+ // the equivalents for operators who prefer composition over chaining)
1171
+ optional: optional,
1172
+ nullable: nullable,
1173
+
1174
+ // Errors
1175
+ SafeSchemaError: SafeSchemaError,
1176
+ };