@arbol-ai/maximus 8.1.0 → 8.4.0

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 (62) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +3 -3
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +1 -1
  6. package/dist/capture/index.js +3 -4
  7. package/dist/chunks/{define-app-BxGZdNmS.js → define-app-CQpWqqqE.js} +33 -14
  8. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  9. package/dist/chunks/{digest-C7UGt760.js → digest-C51F1bhA.js} +1 -2
  10. package/dist/chunks/{errors-CWgE9uvM.js → errors-BoutSmiy.js} +2 -3
  11. package/dist/chunks/{execution-BTiAWA4n.js → execution-Bpq6s4nA.js} +9 -8
  12. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  13. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  14. package/dist/chunks/{http-layout-BvlbD__1.js → http-layout-BcYH4I2w.js} +1 -1
  15. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  16. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  17. package/dist/chunks/{openapi-BF3eCpux.js → openapi-D2rds7vy.js} +27 -116
  18. package/dist/chunks/{openapi-file-RcXoq0AF.js → openapi-file-BK8zET5U.js} +24 -6
  19. package/dist/chunks/{pages-BCksUeRf.js → pages-B7ysoFAM.js} +1 -1
  20. package/dist/chunks/result-CF4OzG9O.js +29 -0
  21. package/dist/chunks/{runtime-D5eR9-Es.js → runtime-CGtS2rOb.js} +132 -7
  22. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  23. package/dist/chunks/{server-B9C8KPwa.js → server-CVhTLNj2.js} +37 -101
  24. package/dist/chunks/{src-C-4z443M.js → src-D67OfW9B.js} +40 -19
  25. package/dist/chunks/tasks-C873C3le.js +100 -0
  26. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  27. package/dist/chunks/{types-Dqo3oGig.d.ts → types-BfGa2aJT.d.ts} +346 -138
  28. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  29. package/dist/chunks/{workers-types-BgjyDtGd.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  30. package/dist/diagnostics.d.ts +1 -1
  31. package/dist/errors.d.ts +1 -1
  32. package/dist/errors.js +1 -1
  33. package/dist/http-paths.d.ts +1 -1
  34. package/dist/http-paths.js +1 -1
  35. package/dist/index.d.ts +2 -2
  36. package/dist/index.js +11 -10
  37. package/dist/internals.d.ts +1 -1
  38. package/dist/internals.js +4 -4
  39. package/dist/mcp/index.d.ts +1 -1
  40. package/dist/mcp/index.js +1 -1
  41. package/dist/mcp/tasks.d.ts +33 -0
  42. package/dist/mcp/tasks.js +3 -0
  43. package/dist/project/config.d.ts +2 -2
  44. package/dist/project/config.js +3 -2
  45. package/dist/project/index.d.ts +2 -2
  46. package/dist/project/index.js +3 -3
  47. package/dist/schemas.d.ts +2 -2
  48. package/dist/schemas.js +3 -3
  49. package/dist/standard-failures.d.ts +1 -1
  50. package/dist/tooling/cli.js +2 -2
  51. package/dist/vite/index.d.ts +1 -1
  52. package/dist/vite/index.js +6 -5
  53. package/dist/webhooks.d.ts +13 -2
  54. package/dist/webhooks.js +38 -1
  55. package/dist/workers/runtime.d.ts +1 -1
  56. package/dist/workers/runtime.js +1 -1
  57. package/package.json +11 -3
  58. package/skills/maximus/SKILL.md +7 -4
  59. package/skills/maximus/references/routes-and-tools.md +9 -1
  60. package/dist/chunks/result-CKgZHrnj.js +0 -56
  61. package/dist/chunks/schemas-BOFxZP1c.js +0 -227
  62. package/dist/chunks/validation-DMu0rkMQ.js +0 -670
@@ -0,0 +1,813 @@
1
+ import { c as carriedIssues, d as HasCodec, f as Value, l as decodeIssues, o as SchemaValidationError, r as decodeSchema, s as carriedErrors, u as DecodeUnsafe } from "./validation-CpzAxj2_.js";
2
+ import { t as isRecord } from "./record-DQUDTpEA.js";
3
+ import { IsCodec, Type, Type as Type$1, Type as t } from "typebox";
4
+ import { Memory } from "typebox/system";
5
+
6
+ // src/internal/schema-markers.ts
7
+ /**
8
+ * The markers input codecs leave on a schema, which the codecs and the reader of secret fields share.
9
+ */
10
+ /** Whether an object drops unknown keys when read with `stripUnknown`. */
11
+ const STRIP = Symbol("maximus.schema.strip");
12
+ /** The source schema of a `pipeSchema`, which the wire value is first read as. */
13
+ const SOURCE = Symbol("maximus.schema.source");
14
+
15
+ // src/secrets.ts
16
+ /** What `visit` answers for a value that must not stay. */
17
+ const REMOVED = Symbol("maximus.schema.removed");
18
+ /** Stands for a schema that says nothing about a value, such as an unknown key of a loose object. */
19
+ const UNDESCRIBED = Object.freeze({});
20
+ /** Each schema's tree, read on first use. */
21
+ const trees = /* @__PURE__ */ new WeakMap();
22
+ /** Each `patternProperties` key, compiled once: patterns come from schemas, which are finite. */
23
+ const patterns = /* @__PURE__ */ new Map();
24
+ /** A keyword's value as a list of schemas. */
25
+ function schemaList(value) {
26
+ return Array.isArray(value) ? value : [];
27
+ }
28
+ /** A keyword's value as schemas by name. */
29
+ function schemaMap(value) {
30
+ return isRecord(value) ? value : {};
31
+ }
32
+ /** The schemas directly below a schema, whichever keyword holds them. */
33
+ function childSchemas(node) {
34
+ return [
35
+ ...Object.values(schemaMap(node.properties)),
36
+ ...Object.values(schemaMap(node.patternProperties)),
37
+ ...Object.values(schemaMap(node.$defs)),
38
+ node.additionalProperties,
39
+ node.additionalItems,
40
+ ...[node.items].flat(),
41
+ ...schemaList(node.anyOf),
42
+ ...schemaList(node.oneOf),
43
+ ...schemaList(node.allOf),
44
+ node[SOURCE]
45
+ ];
46
+ }
47
+ /** A schema's tree: what `$ref` may name in it, and whether it marks anything secret. */
48
+ function treeOf(schema) {
49
+ const known = trees.get(schema);
50
+ if (known) return known;
51
+ const definitions = /* @__PURE__ */ new Map();
52
+ /** Adds one more definition of a name; two of one name both apply. */
53
+ const define = (name, node) => {
54
+ definitions.set(name, [...definitions.get(name) ?? [], node]);
55
+ };
56
+ let secret = false;
57
+ const seen = /* @__PURE__ */ new Set();
58
+ const pending = [schema];
59
+ while (pending.length > 0) {
60
+ const node = pending.pop();
61
+ if (!isRecord(node) || seen.has(node)) continue;
62
+ seen.add(node);
63
+ secret ||= node.secret === true;
64
+ if (typeof node.$id === "string") define(node.$id, node);
65
+ for (const [name, definition] of Object.entries(schemaMap(node.$defs))) if (isRecord(definition)) define(name, definition);
66
+ pending.push(...childSchemas(node));
67
+ }
68
+ const tree = {
69
+ definitions,
70
+ secret
71
+ };
72
+ trees.set(schema, tree);
73
+ return tree;
74
+ }
75
+ /** Whether a schema marks any value secret, at any depth. */
76
+ function holdsSecrets(schema) {
77
+ return treeOf(schema).secret;
78
+ }
79
+ /**
80
+ * Adds to `leaves` the schemas a value of `schema` may match, through every reference and union member, and
81
+ * answers false when one of them marks the value secret or names nothing this tree defines: a value that
82
+ * cannot be shown to be clean is removed.
83
+ */
84
+ function collectLeaves(schema, tree, leaves, seen) {
85
+ if (seen.has(schema) || !isRecord(schema)) return true;
86
+ seen.add(schema);
87
+ const node = schema;
88
+ if (node.secret === true) return false;
89
+ const reference = typeof node.$ref === "string" ? node.$ref.replace("#/$defs/", "") : void 0;
90
+ const targets = reference === void 0 ? [] : tree.definitions.get(reference) ?? [];
91
+ if (reference !== void 0 && targets.length === 0) return false;
92
+ const members = [
93
+ ...targets,
94
+ ...schemaList(node.anyOf),
95
+ ...schemaList(node.oneOf),
96
+ ...schemaList(node.allOf)
97
+ ];
98
+ if (!members.every((member) => collectLeaves(member, tree, leaves, seen))) return false;
99
+ if (members.length === 0 || node.type !== void 0 || node.properties !== void 0 || node.patternProperties !== void 0) leaves.push(node);
100
+ return true;
101
+ }
102
+ /** Whether a schema's `type` admits a value. A TypeBox type outside JSON, such as `Date`, admits anything. */
103
+ function typeAdmits(type, value) {
104
+ switch (type) {
105
+ case "string":
106
+ case "boolean": return typeof value === type;
107
+ case "number": return typeof value === "number";
108
+ case "integer": return Number.isInteger(value);
109
+ case "null": return value === null;
110
+ case "array": return Array.isArray(value);
111
+ case "object": return isRecord(value);
112
+ default: return true;
113
+ }
114
+ }
115
+ /** Whether a schema holds no opinion on what is inside a value: nothing below it can be marked. */
116
+ function describesNothing(leaf) {
117
+ return leaf.properties === void 0 && leaf.patternProperties === void 0 && leaf.items === void 0 && (leaf.additionalProperties === void 0 || leaf.additionalProperties === true) && leaf[STRIP] !== true;
118
+ }
119
+ /** The schemas of an array's element at `position`: a tuple's position, or a list's one schema of items. */
120
+ function itemSchemas(leaf, position) {
121
+ if (!Array.isArray(leaf.items)) return leaf.items === void 0 ? [UNDESCRIBED] : [leaf.items];
122
+ if (position < leaf.items.length) return [leaf.items[position]];
123
+ return isRecord(leaf.additionalItems) ? [leaf.additionalItems] : [];
124
+ }
125
+ /** A copy of an array without what its schemas mark: a list loses the element, a tuple keeps its positions. */
126
+ function visitArray(leaves, value, tree) {
127
+ const tuple = leaves.some((leaf) => Array.isArray(leaf.items));
128
+ const kept = [];
129
+ for (const [position, element] of value.entries()) {
130
+ const schemas = leaves.flatMap((leaf) => itemSchemas(leaf, position));
131
+ const visited = schemas.length ? visit(schemas, element, tree) : REMOVED;
132
+ if (visited !== REMOVED) kept.push(visited);
133
+ else if (tuple) kept.push(null);
134
+ }
135
+ return kept;
136
+ }
137
+ /**
138
+ * The schemas one object schema gives a key: its property and the patterns the key matches, else its
139
+ * additional properties. None when the schema refuses the key: a strict object, or one that strips unknown
140
+ * keys.
141
+ */
142
+ function fieldSchemas(leaf, key) {
143
+ const declared = [...Object.hasOwn(schemaMap(leaf.properties), key) ? [schemaMap(leaf.properties)[key]] : [], ...Object.entries(schemaMap(leaf.patternProperties)).filter(([pattern]) => compiled(pattern).test(key)).map(([, schema]) => schema)];
144
+ if (declared.length) return declared;
145
+ if (leaf.additionalProperties === false || leaf[STRIP] === true) return [];
146
+ return isRecord(leaf.additionalProperties) ? [leaf.additionalProperties] : [UNDESCRIBED];
147
+ }
148
+ /** A pattern of `patternProperties`, compiled once in unicode mode, as TypeBox compiles it to check a value. */
149
+ function compiled(pattern) {
150
+ let expression = patterns.get(pattern);
151
+ if (!expression) {
152
+ expression = new RegExp(pattern, "u");
153
+ patterns.set(pattern, expression);
154
+ }
155
+ return expression;
156
+ }
157
+ /**
158
+ * A copy of an object without what its schemas mark, nor a key every schema refuses. `Object.fromEntries`
159
+ * keeps an own `__proto__` key a plain key, where assigning it would set the copy's prototype.
160
+ */
161
+ function visitObject(leaves, value, tree) {
162
+ const kept = [];
163
+ for (const [key, field] of Object.entries(value)) {
164
+ const schemas = leaves.flatMap((leaf) => fieldSchemas(leaf, key));
165
+ const visited = schemas.length ? visit(schemas, field, tree) : REMOVED;
166
+ if (visited !== REMOVED) kept.push([key, visited]);
167
+ }
168
+ return Object.fromEntries(kept);
169
+ }
170
+ /**
171
+ * A value as these schemas leave it: `REMOVED` when one marks it or none admits it, and otherwise a copy of
172
+ * what they describe. Every schema that may match applies, so a field one union member marks is removed
173
+ * whichever member the value belongs to.
174
+ */
175
+ function visit(schemas, value, tree) {
176
+ const leaves = [];
177
+ const seen = /* @__PURE__ */ new Set();
178
+ if (!schemas.every((schema) => collectLeaves(schema, tree, leaves, seen))) return REMOVED;
179
+ const admitting = leaves.filter((leaf) => typeAdmits(leaf.type, value));
180
+ if (admitting.length === 0) return REMOVED;
181
+ if (admitting.every(describesNothing)) return value;
182
+ if (Array.isArray(value)) return visitArray(admitting, value, tree);
183
+ return isRecord(value) ? visitObject(admitting, value, tree) : value;
184
+ }
185
+ /**
186
+ * A copy of a value without every field its schema marks with `secret: true`, at any depth: through objects,
187
+ * records, arrays, tuples, unions, intersections, optional fields and references. The input is never changed.
188
+ * A marked list element goes with its value, a marked tuple position becomes `null`, and a schema marked at
189
+ * its root answers `undefined`.
190
+ *
191
+ * Pass a value of the shape the schema describes: what it checked, before any codec ran. It fails closed where
192
+ * a schema cannot speak for a value: a name marked in any member of a union is removed from all of them, a
193
+ * key a strict object refuses is removed, as is a value of another type, or one under a `$ref` the schema does
194
+ * not define.
195
+ */
196
+ function withoutSecrets(schema, value) {
197
+ const kept = visit([schema], value, treeOf(schema));
198
+ return kept === REMOVED ? void 0 : kept;
199
+ }
200
+ /** Keywords whose values are data, never schemas: `secret` inside one is the data's own. */
201
+ const DATA_KEYWORDS = /* @__PURE__ */ new Set([
202
+ "const",
203
+ "default",
204
+ "enum",
205
+ "example",
206
+ "examples"
207
+ ]);
208
+ /** Keywords whose values are named schemas: `secret` directly inside one is a field's name. */
209
+ const NAMED_SCHEMAS = /* @__PURE__ */ new Set([
210
+ "properties",
211
+ "patternProperties",
212
+ "$defs"
213
+ ]);
214
+ /**
215
+ * A copy of a published schema or document without the `secret` keyword. It tells capture what to leave out,
216
+ * and no client needs it: marking a field changes no OpenAPI document and no tool listing.
217
+ */
218
+ function withoutSecretKeyword(node, named = false) {
219
+ if (Array.isArray(node)) return node.map((item) => withoutSecretKeyword(item));
220
+ if (!isRecord(node)) return node;
221
+ const kept = [];
222
+ for (const [key, child] of Object.entries(node)) if (named) kept.push([key, withoutSecretKeyword(child)]);
223
+ else if (DATA_KEYWORDS.has(key) || key.startsWith("x-")) kept.push([key, child]);
224
+ else if (!(key === "secret" && child === true)) kept.push([key, withoutSecretKeyword(child, NAMED_SCHEMAS.has(key))]);
225
+ return Object.fromEntries(kept);
226
+ }
227
+
228
+ // src/input-schemas.ts
229
+ /**
230
+ * Owner codecs on TypeBox schemas: defaults, normalizers, transforms, inspections, refinements, pipes and
231
+ * unknown-key stripping. `inputSchema()` compiles them into TypeBox codecs and refinements, so the wire is
232
+ * checked as declared and the handler receives the decoded value. Every helper copies a schema with what
233
+ * TypeBox keeps hidden on it, as `t.With` does.
234
+ */
235
+ /** The ordered codec steps a schema runs inside `inputSchema()`. */
236
+ const STEPS = Symbol("maximus.schema.steps");
237
+ /** The transforms a schema applies after its source value is valid. */
238
+ const TRANSFORMERS = Symbol("maximus.schema.transformers");
239
+ /** The normalizers a schema applies before its own checks. */
240
+ const NORMALIZERS = Symbol("maximus.schema.normalizers");
241
+ /** The inspections and refinements a schema runs on a valid value. */
242
+ const INSPECTORS = Symbol("maximus.schema.inspectors");
243
+ /**
244
+ * The schema with `options` added, keeping what TypeBox keeps hidden on it, as TypeBox's `Type.With` does;
245
+ * unlike it, a reference (`t.Ref`) is copied too, since a helper below may be given one.
246
+ */
247
+ const annotate = (schema, options) => Memory.Update(schema, {}, options);
248
+ /** A union of literals: `literalUnion(['open', 'done'])`, or the values of a list, `literalUnion(ids)`. */
249
+ const literalUnion = (values) => Type.Union(values.map((value) => Type.Literal(value)));
250
+ /**
251
+ * The schema with a default that decoding applies when the field is absent, so the field is optional on the
252
+ * wire.
253
+ */
254
+ const defaultSchema = (schema, value) => annotate(schema, { default: value });
255
+ /**
256
+ * A strict object that, read with `stripUnknown` (as `readSchema` does), drops unknown keys instead of
257
+ * refusing them. Wrap an input that uses it in `inputSchema()`.
258
+ */
259
+ const stripObject = (properties) => annotate(Type.Object(properties, { additionalProperties: false }), { [STRIP]: true });
260
+ /** The object, refusing unknown keys even where a read strips them. */
261
+ const strictObject = (schema) => annotate(schema, {
262
+ additionalProperties: false,
263
+ [STRIP]: false
264
+ });
265
+ /** The object, admitting and keeping unknown keys. */
266
+ const looseObject = (schema) => annotate(schema, {
267
+ additionalProperties: true,
268
+ [STRIP]: false
269
+ });
270
+ /** The object with more properties, keeping how it treats unknown keys. */
271
+ const extendObject = (schema, properties) => annotate(Type.Object({
272
+ ...schema.properties,
273
+ ...properties
274
+ }, { additionalProperties: schema.additionalProperties }), { [STRIP]: schema[STRIP] });
275
+ /**
276
+ * Reads a field through `normalize`. For a string, or a string that may be null, the pattern, format and
277
+ * lengths apply to the normalized value, so the wire may send a raw spelling (another case, surrounding
278
+ * spaces); any other schema checks the raw value first. The wire type stays the schema's own. Runs inside
279
+ * `inputSchema()`.
280
+ */
281
+ const normalizeSchema = (schema, normalize) => Type.Unsafe(annotate(schema, {
282
+ [NORMALIZERS]: [...schema[NORMALIZERS] ?? [], normalize],
283
+ [STEPS]: [...schema[STEPS] ?? [], {
284
+ kind: "normalize",
285
+ apply: normalize
286
+ }]
287
+ }));
288
+ /**
289
+ * Decodes a field with `transform` once its value passes `schema`: the wire sends what `schema` checks, and
290
+ * the handler receives what `transform` returns. Runs inside `inputSchema()`.
291
+ */
292
+ const transformSchema = (schema, transform) => Type.Unsafe(annotate(schema, {
293
+ [TRANSFORMERS]: [...schema[TRANSFORMERS] ?? [], transform],
294
+ [STEPS]: [...schema[STEPS] ?? [], {
295
+ kind: "transform",
296
+ apply: transform
297
+ }]
298
+ }));
299
+ /**
300
+ * Refuses a canonical schema that marks a field `secret: true` when the wire schema it is read from marks
301
+ * nothing: capture reads the value the wire schema checked, where that mark would protect nothing.
302
+ */
303
+ function requireSecretsOnWire(wire, canonical) {
304
+ if (holdsSecrets(canonical) && !holdsSecrets(wire)) throw new TypeError("A canonical schema marks a field secret: true and the wire schema it is read from does not; mark the field where the wire carries it.");
305
+ }
306
+ /**
307
+ * Admits a value as `source`, then checks and decodes the result as `target`: a wire shape read into its
308
+ * canonical one. Runs inside `inputSchema()`. A `target` that marks a field `secret: true` needs `source` to
309
+ * mark it too, or it throws a TypeError.
310
+ */
311
+ const pipeSchema = (source, target) => {
312
+ requireSecretsOnWire(source, target);
313
+ return annotate(target, { [SOURCE]: source });
314
+ };
315
+ /**
316
+ * Runs `inspect` on a value the schema admits; every `addIssue` refuses the value with that issue. Runs
317
+ * inside `inputSchema()`.
318
+ */
319
+ const inspectSchema = (schema, inspect) => annotate(schema, {
320
+ [INSPECTORS]: [...schema[INSPECTORS] ?? [], inspect],
321
+ [STEPS]: [...schema[STEPS] ?? [], {
322
+ kind: "inspect",
323
+ apply: inspect
324
+ }]
325
+ });
326
+ /**
327
+ * Refuses a value the schema admits when `predicate` rejects it, with a `custom` issue whose message and path
328
+ * `detail` gives (`Invalid value` at the field by default). Runs inside `inputSchema()`.
329
+ */
330
+ const refineSchema = (schema, predicate, detail) => inspectSchema(schema, (value, context) => {
331
+ if (!predicate(value)) context.addIssue({
332
+ code: "custom",
333
+ message: typeof detail === "string" ? detail : detail?.message ?? detail?.error ?? "Invalid value",
334
+ path: typeof detail === "object" ? detail.path ?? [] : []
335
+ });
336
+ });
337
+ /**
338
+ * A URL, of at most `maxLength` characters when given, whose protocol (without its colon, such as `https`)
339
+ * and, optionally, hostname match the given patterns. Runs inside `inputSchema()`.
340
+ */
341
+ const urlSchema = (options) => refineSchema(Type.String({
342
+ format: "uri",
343
+ ...options.maxLength ? { maxLength: options.maxLength } : {}
344
+ }), (value) => {
345
+ try {
346
+ const url = new URL(value);
347
+ return options.protocol.test(url.protocol.slice(0, -1)) && (!options.hostname || options.hostname.test(url.hostname));
348
+ } catch {
349
+ return false;
350
+ }
351
+ });
352
+ /** Whether a schema is text, or text that may be null: what a normalizer checks again once it has run. */
353
+ function textual(schema) {
354
+ return schema.type === "string" || Array.isArray(schema.anyOf) && schema.anyOf.every((branch) => branch.type === "string" || branch.type === "null");
355
+ }
356
+ /**
357
+ * A node's own codec steps, run in their order on its value once its children are decoded: the decoded value,
358
+ * or the issues that refuse it, at their paths below the node. A step that throws a `SchemaValidationError`
359
+ * refuses with its issues; anything else it throws is the codec's fault and propagates.
360
+ */
361
+ function runSteps(schema, input, strip) {
362
+ let value = input;
363
+ if (strip && value !== null && typeof value === "object" && !Array.isArray(value)) value = Object.fromEntries(Object.entries(value).filter(([key]) => key in schema.properties));
364
+ const steps = schema[STEPS] ?? [];
365
+ for (const [index, step] of steps.entries()) {
366
+ if (step.kind === "inspect") {
367
+ const issues = [];
368
+ step.apply(value, { addIssue: (issue) => issues.push(issue) });
369
+ if (issues.length) return {
370
+ value,
371
+ issues
372
+ };
373
+ continue;
374
+ }
375
+ try {
376
+ value = step.apply(value);
377
+ } catch (error) {
378
+ if (error instanceof SchemaValidationError) return {
379
+ value,
380
+ issues: error.issues
381
+ };
382
+ throw error;
383
+ }
384
+ if (step.kind === "normalize" && steps[index + 1]?.kind !== "normalize" && textual(schema) && !Value.Check(schema, value)) return {
385
+ value,
386
+ issues: [{
387
+ code: "invalid_input",
388
+ message: "The normalized value does not match its schema.",
389
+ path: []
390
+ }]
391
+ };
392
+ }
393
+ return {
394
+ value,
395
+ issues: []
396
+ };
397
+ }
398
+ /** A copy of a value decoded through a schema's codecs: a check never changes the value it checks. */
399
+ function decodedCopy(schema, value) {
400
+ return HasCodec(schema) ? DecodeUnsafe({}, schema, Value.Clone(value)) : value;
401
+ }
402
+ /**
403
+ * A node with owner steps as TypeBox runs it: a refinement that runs the steps on the value, its children
404
+ * decoded, and refuses with their issues, and a codec that decodes the value through them.
405
+ */
406
+ function ownerNode(projected, schema, strip) {
407
+ const issuesOf = (input) => runSteps(schema, decodedCopy(projected, input), strip).issues;
408
+ const refined = Type.Refine(projected, (input) => issuesOf(input).length === 0, (input) => carriedIssues(issuesOf(input)));
409
+ return Type.Codec(refined).Decode((value) => runSteps(schema, value, strip).value).Encode((value) => value);
410
+ }
411
+ /**
412
+ * A `pipeSchema` as TypeBox runs it: the value read as `source`, then defaulted, checked and decoded as
413
+ * `target`. Refused as the source refuses it, else with the target's issues at their paths.
414
+ */
415
+ function pipeNode(source, target) {
416
+ const targetInput = (input) => Value.Default(target, decodedCopy(source, input));
417
+ const refined = Type.Refine(source, (input) => !Value.Check(source, input) || Value.Check(target, targetInput(input)), (input) => carriedErrors(Value.Errors(target, targetInput(input))));
418
+ return Type.Codec(refined).Decode((value) => DecodeUnsafe({}, target, Value.Default(target, value))).Encode((value) => value);
419
+ }
420
+ /**
421
+ * Compiles owner semantics into TypeBox codecs and refinements; canonical output schemas stay strict. Every
422
+ * node is copied with what TypeBox keeps hidden on it, a refinement or a codec among them.
423
+ */
424
+ const projectOwnerInput = (schema, stripUnknown) => {
425
+ const node = schema;
426
+ if (node[SOURCE]) return pipeNode(projectOwnerInput(node[SOURCE], stripUnknown), projectOwnerInput(Memory.Update(node, {}, { [SOURCE]: void 0 }), stripUnknown));
427
+ const projected = Memory.Update(node, {}, {});
428
+ const properties = node.properties;
429
+ if (properties) {
430
+ projected.properties = Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, projectOwnerInput(value, stripUnknown)]));
431
+ projected.required = node.required?.filter((key) => !("default" in (properties[key] ?? {})));
432
+ if (stripUnknown && node[STRIP]) projected.additionalProperties = true;
433
+ }
434
+ if (node.items) projected.items = Array.isArray(node.items) ? node.items.map((value) => projectOwnerInput(value, stripUnknown)) : projectOwnerInput(node.items, stripUnknown);
435
+ const normalizers = node[NORMALIZERS] ?? [];
436
+ if (Array.isArray(node.anyOf)) projected.anyOf = node.anyOf.map((value) => {
437
+ if (normalizers.length > 0 && value.type === "string") {
438
+ const source = Memory.Update(value, {}, {});
439
+ delete source.pattern;
440
+ delete source.format;
441
+ delete source.minLength;
442
+ delete source.maxLength;
443
+ return projectOwnerInput(source, stripUnknown);
444
+ }
445
+ return projectOwnerInput(value, stripUnknown);
446
+ });
447
+ if (node.patternProperties) projected.patternProperties = Object.fromEntries(Object.entries(node.patternProperties).map(([key, value]) => [key, projectOwnerInput(value, stripUnknown)]));
448
+ if (node.type === "string" && normalizers.length) {
449
+ delete projected.pattern;
450
+ delete projected.format;
451
+ delete projected.minLength;
452
+ delete projected.maxLength;
453
+ }
454
+ const strip = Boolean(stripUnknown && node[STRIP] && properties);
455
+ if (!((node[STEPS]?.length ?? 0) > 0 || strip)) return projected;
456
+ return ownerNode(projected, node, strip);
457
+ };
458
+ /**
459
+ * An input schema as callers send it, for the documents that publish it: a field with a default is optional,
460
+ * since decoding fills it in. A schema `inputSchema()` compiled is its wire form already.
461
+ */
462
+ function wireInput(schema) {
463
+ return IsCodec(schema) ? schema : projectOwnerInput(schema, false);
464
+ }
465
+ /**
466
+ * Whether a schema carries owner codecs that only `inputSchema()` compiles: a normalizer, transform,
467
+ * inspector or refinement, a `pipeSchema` source, or a `stripObject`. A plain decode ignores their
468
+ * markers, so such a schema used directly as an operation input would admit raw, unnormalized and
469
+ * unrefined values without a word. A compiled subtree (a TypeBox codec) is already honest.
470
+ */
471
+ function hasUncompiledCodecs(schema) {
472
+ const seen = /* @__PURE__ */ new Set();
473
+ /**
474
+ * Whether this schema, or any schema below it that no transform already compiled, carries a codec marker.
475
+ */
476
+ const visit = (node) => {
477
+ if (!node || typeof node !== "object" || seen.has(node) || IsCodec(node)) return false;
478
+ seen.add(node);
479
+ const owner = node;
480
+ if ((owner[STEPS]?.length ?? 0) > 0 || owner[SOURCE] || owner[STRIP] === true) return true;
481
+ return [
482
+ ...Object.values(owner.properties ?? {}),
483
+ ...Object.values(owner.patternProperties ?? {}),
484
+ ...[owner.items].flat(),
485
+ ...owner.anyOf ?? [],
486
+ ...owner.allOf ?? [],
487
+ ...owner.oneOf ?? []
488
+ ].some(visit);
489
+ };
490
+ return visit(schema);
491
+ }
492
+ function inputSchema(schema, source) {
493
+ const options = source && Object.keys(source).every((key) => key === "stripUnknown") ? source : void 0;
494
+ const wire = source && !options ? source : void 0;
495
+ if (wire) requireSecretsOnWire(wire, schema);
496
+ const stripUnknown = options?.stripUnknown === true;
497
+ const projected = projectOwnerInput(schema, stripUnknown);
498
+ return Type.Codec(Type.Unsafe(wire ? projectOwnerInput(wire, false) : projected)).Decode((input) => {
499
+ if (!wire) return input;
500
+ const value = Value.Default(projected, input);
501
+ Value.Assert(projected, value);
502
+ return DecodeUnsafe({}, projected, value);
503
+ }).Encode((value) => value);
504
+ }
505
+
506
+ // src/schema-reader.ts
507
+ /**
508
+ * Reads untrusted data — a stored record, a provider or model answer — through its schema's owner
509
+ * semantics: defaults applied, normalizers run before their checks, unknown keys of a strip object
510
+ * dropped. A refusal carries every issue with its path; nothing is coerced. An owner codec that fails
511
+ * throws what it threw.
512
+ */
513
+ function checkSchema(schema, input) {
514
+ try {
515
+ return {
516
+ success: true,
517
+ data: decodeSchema(inputSchema(schema, { stripUnknown: true }), input)
518
+ };
519
+ } catch (error) {
520
+ const issues = decodeIssues(error);
521
+ if (!issues) throw error;
522
+ return {
523
+ success: false,
524
+ error: new SchemaValidationError(issues)
525
+ };
526
+ }
527
+ }
528
+ /** `checkSchema`, throwing its SchemaValidationError on refusal. */
529
+ function readSchema(schema, input) {
530
+ const checked = checkSchema(schema, input);
531
+ if (!checked.success) throw checked.error;
532
+ return checked.data;
533
+ }
534
+
535
+ // src/attachment-schema.ts
536
+ /**
537
+ * The file an HTTP operation answers with and its output schema, with nothing that needs a runtime. An
538
+ * attachment is never a JSON or RPC value.
539
+ */
540
+ /** The output of an operation that answers with a file (`http.response: 'attachment'`). */
541
+ const AttachmentOutputSchema = Type.Unsafe(Memory.Update({
542
+ type: "string",
543
+ format: "binary",
544
+ description: "Authenticated attachment bytes with validated media type, filename and exact length."
545
+ }, { "~kind": "HttpAttachment" }, {}));
546
+
547
+ // src/pagination.ts
548
+ /**
549
+ * The one list contract: bidirectional keyset pagination. A list takes the query fields `cursor`,
550
+ * `direction` and `limit` and answers `{ object: 'list', data, pageInfo }`. The cursor is opaque to
551
+ * callers; there is no page number, page size, offset or implicit total. `cutPage` cuts such a page from a
552
+ * list a service holds whole.
553
+ *
554
+ * `PageInfo` and each `Page` are named schemas, so an OpenAPI document carries them once as
555
+ * `#/components/schemas/<name>` and every SDK generated from it shares their types.
556
+ */
557
+ /** A public schema name: an SDK type in every language generated from the document. */
558
+ const PAGE_ID = /^[A-Z][A-Za-z0-9]{0,127}$/;
559
+ /**
560
+ * How to reach a list's neighboring pages: whether they exist and their opaque cursors, named `PageInfo`.
561
+ */
562
+ const PageInfoSchema = Type.Object({
563
+ hasNextPage: Type.Boolean({ description: "Whether a later page exists in the current ordering." }),
564
+ hasPreviousPage: Type.Boolean({ description: "Whether an earlier page exists in the current ordering." }),
565
+ nextCursor: Type.Union([Type.String(), Type.Null()], { description: "Opaque cursor for the next page, or null when there is none." }),
566
+ previousCursor: Type.Union([Type.String(), Type.Null()], { description: "Opaque cursor for the previous page, or null when there is none." })
567
+ }, {
568
+ $id: "PageInfo",
569
+ additionalProperties: false
570
+ });
571
+ /**
572
+ * A list's `limit`: an integer from 1 to `maximum` (100), `default` (25, or the maximum when it is lower)
573
+ * when the caller sends none. A list whose items are costly lowers the maximum:
574
+ * `{ ...PageQueryFields, limit: pageLimit({ maximum: 20 }) }`. A default outside 1 to the maximum, or a
575
+ * value that is not an integer, throws a TypeError.
576
+ */
577
+ function pageLimit(options = {}) {
578
+ const { maximum = 100, default: fallback = Math.min(25, maximum) } = options;
579
+ if (!(Number.isInteger(maximum) && Number.isInteger(fallback) && fallback >= 1 && fallback <= maximum)) throw new TypeError("A page limit has an integer default from 1 to its integer maximum.");
580
+ return defaultSchema(Type.Integer({
581
+ minimum: 1,
582
+ maximum,
583
+ description: `Maximum items returned in one page. Defaults to ${fallback}; larger reads require another cursor.`
584
+ }), fallback);
585
+ }
586
+ /**
587
+ * The query fields of a list, spread into its input beside its own filters: an optional opaque `cursor`, a
588
+ * `direction` (`forward` by default, or `backward`) and a `limit` (`pageLimit()`).
589
+ */
590
+ const PageQueryFields = {
591
+ cursor: Type.Optional(Type.String({ description: "Opaque cursor returned by pageInfo; omit it to request the first page." })),
592
+ direction: defaultSchema(Type.Union([Type.Literal("forward"), Type.Literal("backward")], { description: "Direction to traverse the stable keyset ordering from the supplied cursor." }), "forward"),
593
+ limit: pageLimit()
594
+ };
595
+ /**
596
+ * The output of a list of `item`, named by `$id` (`AppointmentPage`), a PascalCase name of up to 128
597
+ * characters; any other throws a TypeError. Give each list its own name and use it for that list only: two
598
+ * different shapes under one `$id` become two components, the second one suffixed `_2`.
599
+ */
600
+ function Page(item, options) {
601
+ if (!PAGE_ID.test(options.$id)) throw new TypeError(`Page "${options.$id}" needs a PascalCase schema name, such as AppointmentPage.`);
602
+ return Type.Object({
603
+ data: Type.Array(item, { description: "Items admitted by this resource contract within the verified organization." }),
604
+ object: Type.Literal("list", { description: "Discriminator for a resource list response." }),
605
+ pageInfo: Type.With(PageInfoSchema, { description: "Opaque navigation cursors for this page’s stable keyset order." })
606
+ }, {
607
+ $id: options.$id,
608
+ additionalProperties: false
609
+ });
610
+ }
611
+ /** The longest cursor `cutPage` reads: keys are short identifiers, dates and names. */
612
+ const MAX_CURSOR_LENGTH = 4096;
613
+ /** A cursor's text: unpadded base64url. */
614
+ const CURSOR_TEXT = /^[A-Za-z0-9_-]+$/;
615
+ /** Two keys, part by part, in code unit order: the same in every runtime, whatever its locale. */
616
+ function compareKeys(left, right) {
617
+ for (const [index, part] of left.entries()) {
618
+ const other = right[index] ?? "";
619
+ if (part !== other) return part < other ? -1 : 1;
620
+ }
621
+ return 0;
622
+ }
623
+ /** A position as a cursor: `[side, ...key]` as JSON, in unpadded base64url. */
624
+ function encodeCursor(position) {
625
+ let binary = "";
626
+ for (const byte of new TextEncoder().encode(JSON.stringify([position.side, ...position.key]))) binary += String.fromCodePoint(byte);
627
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/[=]+$/, "");
628
+ }
629
+ /** The position a cursor names, or undefined for text `encodeCursor` did not write. */
630
+ function decodeCursor(cursor) {
631
+ if (cursor.length > MAX_CURSOR_LENGTH || !CURSOR_TEXT.test(cursor)) return;
632
+ try {
633
+ const base64 = cursor.replaceAll("-", "+").replaceAll("_", "/");
634
+ const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
635
+ const bytes = Uint8Array.from(binary, (character) => character.codePointAt(0) ?? 0);
636
+ const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
637
+ if (Array.isArray(parsed) && parsed.length > 1 && (parsed[0] === "after" || parsed[0] === "before") && parsed.every((part) => typeof part === "string")) return {
638
+ side: parsed[0],
639
+ key: parsed.slice(1)
640
+ };
641
+ } catch {}
642
+ }
643
+ /**
644
+ * The key of the item a cursor of `cutPage` sits beside, or undefined for text that is not such a cursor: a
645
+ * service checks with it that a cursor belongs to the list it is asked for before it reads that list.
646
+ */
647
+ function cursorKey(cursor) {
648
+ return decodeCursor(cursor)?.key;
649
+ }
650
+ /**
651
+ * One page of a list a service holds whole, such as one a provider answers complete. A cursor is a
652
+ * place between two items, right after one page's last item (`nextCursor`) or right before its first
653
+ * (`previousCursor`), never an offset: it keeps its meaning while items come and go, the one it names
654
+ * included. `forward` takes the items after the place and `backward` the ones before it, and both answer in
655
+ * the list's `ordering`; without a cursor, `forward` starts at the first item and `backward` at the last. A cursor
656
+ * is null exactly when there is no such page. Undefined when the query's cursor is not one this list made,
657
+ * including a key of another length, for the service to refuse as it does.
658
+ */
659
+ function cutPage(items, ordering, query) {
660
+ const sign = ordering.order === "desc" ? -1 : 1;
661
+ const sorted = items.map((item) => ({
662
+ item,
663
+ key: ordering.key(item)
664
+ })).toSorted((left, right) => sign * compareKeys(left.key, right.key));
665
+ const forward = query.direction === "forward";
666
+ let at = forward ? 0 : sorted.length;
667
+ if (query.cursor !== void 0) {
668
+ const position = decodeCursor(query.cursor);
669
+ const listedKey = sorted[0]?.key;
670
+ if (!position || listedKey !== void 0 && listedKey.length !== position.key.length) return;
671
+ const after = sorted.findIndex(({ key }) => {
672
+ const comparison = sign * compareKeys(key, position.key);
673
+ return position.side === "after" ? comparison > 0 : comparison >= 0;
674
+ });
675
+ at = after === -1 ? sorted.length : after;
676
+ }
677
+ const start = forward ? at : Math.max(0, at - query.limit);
678
+ const end = forward ? Math.min(sorted.length, at + query.limit) : at;
679
+ const page = sorted.slice(start, end);
680
+ /**
681
+ * The cursor beside an edge item; for an empty page, the cursor it was asked from, which still divides the
682
+ * items before it from the items after it.
683
+ */
684
+ const cursorBeside = (entry, side) => entry ? encodeCursor({
685
+ side,
686
+ key: entry.key
687
+ }) : query.cursor ?? null;
688
+ const hasNextPage = end < sorted.length;
689
+ const hasPreviousPage = start > 0;
690
+ return {
691
+ object: "list",
692
+ data: page.map(({ item }) => item),
693
+ pageInfo: {
694
+ hasNextPage,
695
+ hasPreviousPage,
696
+ nextCursor: hasNextPage ? cursorBeside(page.at(-1), "after") : null,
697
+ previousCursor: hasPreviousPage ? cursorBeside(page.at(0), "before") : null
698
+ }
699
+ };
700
+ }
701
+
702
+ // src/common-schemas.ts
703
+ /**
704
+ * Values and objects that services publish alike, each named by its `$id`: an OpenAPI document carries
705
+ * it once as `#/components/schemas/<name>`, and every SDK generated from those documents has one type
706
+ * for it. A name is public, so it names exactly one shape. Domain records (people, patients,
707
+ * identity documents) stay with the service that owns them.
708
+ */
709
+ /** An email address of at most 254 characters, named `EmailAddress`. */
710
+ const EmailAddressSchema = Type.String({
711
+ $id: "EmailAddress",
712
+ format: "email",
713
+ maxLength: 254,
714
+ description: "Email address."
715
+ });
716
+ /** A phone number in E.164 format, named `PhoneNumber`. */
717
+ const PhoneNumberSchema = Type.String({
718
+ $id: "PhoneNumber",
719
+ pattern: "^\\+[1-9][0-9]{1,14}$",
720
+ description: "Phone number in E.164 format."
721
+ });
722
+ /** An HTTPS URL of at most 2048 characters, named `HttpsUrl`. */
723
+ const HttpsUrlSchema = Type.String({
724
+ $id: "HttpsUrl",
725
+ format: "uri",
726
+ pattern: "^https://",
727
+ maxLength: 2048,
728
+ description: "An HTTPS URL."
729
+ });
730
+ /** A `#rrggbb` color, named `HexColor`. */
731
+ const HexColorSchema = Type.String({
732
+ $id: "HexColor",
733
+ pattern: "^#[0-9a-fA-F]{6}$",
734
+ description: "A color, as #rrggbb."
735
+ });
736
+ /** What a delete answers: the deleted resource's id and `deleted: true`, named `DeletedObject`. */
737
+ const DeletedObjectSchema = Type.Object({
738
+ id: Type.String({ description: "The id of the deleted resource." }),
739
+ deleted: Type.Literal(true)
740
+ }, {
741
+ $id: "DeletedObject",
742
+ additionalProperties: false
743
+ });
744
+ /** The URL of a `SignedUrl`, described as the credential it is. */
745
+ const SignedUrlFieldSchema = Type.With(HttpsUrlSchema, { description: "The signed URL. Anyone holding it has access until it expires." });
746
+ /**
747
+ * A link that grants access by itself until it expires, such as a file download: its HTTPS `url` and its
748
+ * `expiresAt` date-time, named `SignedUrl`.
749
+ */
750
+ const SignedUrlSchema = Type.Object({
751
+ url: SignedUrlFieldSchema,
752
+ expiresAt: Type.String({
753
+ format: "date-time",
754
+ description: "When the URL stops working."
755
+ })
756
+ }, {
757
+ $id: "SignedUrl",
758
+ additionalProperties: false
759
+ });
760
+ /** Another resource, by its id and the name people know it by, named `NamedReference`. */
761
+ const NamedReferenceSchema = Type.Object({
762
+ id: Type.String({ description: "The id of the referenced resource." }),
763
+ name: Type.String({ description: "Its name." })
764
+ }, {
765
+ $id: "NamedReference",
766
+ additionalProperties: false
767
+ });
768
+ /**
769
+ * A postal address, shaped as FHIR `Address` (its lines, city, state, postal code, ISO 3166-1 alpha-2 country
770
+ * code and use), every field optional, named `PostalAddress`.
771
+ */
772
+ const PostalAddressSchema = Type.Object({
773
+ city: Type.Optional(Type.String({ maxLength: 120 })),
774
+ countryCode: Type.Optional(Type.String({
775
+ description: "ISO 3166-1 alpha-2.",
776
+ pattern: "^[A-Z]{2}$"
777
+ })),
778
+ line: Type.Optional(Type.Array(Type.String({ maxLength: 200 }), { maxItems: 4 })),
779
+ postalCode: Type.Optional(Type.String({ maxLength: 20 })),
780
+ state: Type.Optional(Type.String({ maxLength: 120 })),
781
+ use: Type.Optional(Type.Union([Type.Literal("home"), Type.Literal("work")]))
782
+ }, {
783
+ $id: "PostalAddress",
784
+ additionalProperties: false
785
+ });
786
+
787
+ // src/schemas.ts
788
+ /**
789
+ * `@arbol-ai/maximus/schemas`: the browser-safe schema vocabulary: TypeBox (`t`), its types, the validators
790
+ * and the shared identifier schemas, with nothing that needs a Worker runtime. A contract module that
791
+ * browsers import (a Dashboard reading an API's limits, a widget's settings) imports from here rather than
792
+ * the package root.
793
+ */
794
+ /** The input of an operation that takes none: an empty strict object. */
795
+ const EmptyInputSchema = Type.Object({}, { additionalProperties: false });
796
+ /**
797
+ * An organization id as identity providers issue them (`org_…`, a UUID, a slug): 1 to 128 letters, digits,
798
+ * `_` and `-`, starting with a letter or digit, named `OrganizationId`. Nothing in it can change the meaning
799
+ * of a storage key, a path or a log line.
800
+ */
801
+ const OrganizationIdSchema = Type.String({
802
+ $id: "OrganizationId",
803
+ pattern: "^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$",
804
+ description: "Verified organization identifier."
805
+ });
806
+ /** A lowercase RFC 9562 UUID of version 1 to 8, named `Uuid`. */
807
+ const UuidSchema = Type.String({
808
+ $id: "Uuid",
809
+ format: "uuid",
810
+ pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
811
+ });
812
+
813
+ export { normalizeSchema as A, withoutSecrets as B, defaultSchema as C, inspectSchema as D, inputSchema as E, transformSchema as F, urlSchema as I, wireInput as L, refineSchema as M, strictObject as N, literalUnion as O, stripObject as P, holdsSecrets as R, readSchema as S, hasUncompiledCodecs as T, cursorKey as _, t as a, AttachmentOutputSchema as b, HexColorSchema as c, PhoneNumberSchema as d, PostalAddressSchema as f, PageQueryFields as g, PageInfoSchema as h, UuidSchema as i, pipeSchema as j, looseObject as k, HttpsUrlSchema as l, Page as m, OrganizationIdSchema as n, DeletedObjectSchema as o, SignedUrlSchema as p, Type$1 as r, EmailAddressSchema as s, EmptyInputSchema as t, NamedReferenceSchema as u, cutPage as v, extendObject as w, checkSchema as x, pageLimit as y, withoutSecretKeyword as z };