@arbol-ai/maximus 8.0.1 → 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 (70) hide show
  1. package/dist/analytics/analytics.d.ts +16 -16
  2. package/dist/analytics/analytics.js +4 -4
  3. package/dist/body.d.ts +2 -2
  4. package/dist/body.js +2 -2
  5. package/dist/capture/index.d.ts +37 -0
  6. package/dist/capture/index.js +181 -0
  7. package/dist/chunks/{define-app-x7uY70_1.js → define-app-CQpWqqqE.js} +44 -14
  8. package/dist/chunks/delay-BsKQP_lF.js +12 -0
  9. package/dist/chunks/{json-B14evE6-.js → destination-DIkn8W6K.js} +65 -1
  10. package/dist/chunks/digest-C51F1bhA.js +12 -0
  11. package/dist/chunks/{errors-C5w9WY1l.js → errors-BoutSmiy.js} +2 -3
  12. package/dist/chunks/execution-Bpq6s4nA.js +265 -0
  13. package/dist/chunks/{generate-C-9FKW0o.js → generate-Dg88LzLU.js} +1 -1
  14. package/dist/chunks/{handler-iebR-urt.js → handler-DSpyrWc-.js} +6 -2
  15. package/dist/chunks/{http-layout-DS8DnPyu.js → http-layout-BcYH4I2w.js} +1 -1
  16. package/dist/chunks/{http-paths-DMBxwpp6.js → http-paths-D043DkJv.js} +50 -81
  17. package/dist/chunks/http-routes-B6tCsnxB.js +29 -0
  18. package/dist/chunks/{openapi-CeolxIqa.js → openapi-D2rds7vy.js} +32 -130
  19. package/dist/chunks/{openapi-file-Bz9FRaE6.js → openapi-file-BK8zET5U.js} +24 -6
  20. package/dist/chunks/{pages-iZTvFs5a.js → pages-B7ysoFAM.js} +1 -1
  21. package/dist/chunks/result-CF4OzG9O.js +29 -0
  22. package/dist/chunks/{runtime-D94vx21X.js → runtime-CGtS2rOb.js} +165 -11
  23. package/dist/chunks/schemas-_UJcx_uY.js +813 -0
  24. package/dist/chunks/{server-Bzf1Q1_4.js → server-CVhTLNj2.js} +38 -101
  25. package/dist/chunks/{src-CPrJpbOM.js → src-D67OfW9B.js} +94 -27
  26. package/dist/chunks/tasks-C873C3le.js +100 -0
  27. package/dist/chunks/tasks-DYdY-dBI.js +267 -0
  28. package/dist/chunks/{telemetry-C3LfZcOB.js → telemetry-BtxJh69Q.js} +4 -4
  29. package/dist/chunks/{types-DTIuIEJ-.d.ts → types-BfGa2aJT.d.ts} +537 -124
  30. package/dist/chunks/validation-CpzAxj2_.js +201 -0
  31. package/dist/chunks/{workers-types-BRk_Xa_5.d.ts → workers-types-Cxf-5cH7.d.ts} +6 -1
  32. package/dist/diagnostics.d.ts +1 -1
  33. package/dist/diagnostics.js +1 -1
  34. package/dist/errors.d.ts +1 -1
  35. package/dist/errors.js +1 -1
  36. package/dist/http-paths.d.ts +1 -1
  37. package/dist/http-paths.js +1 -1
  38. package/dist/index.d.ts +2 -2
  39. package/dist/index.js +12 -11
  40. package/dist/internals.d.ts +2 -2
  41. package/dist/internals.js +6 -6
  42. package/dist/mcp/index.d.ts +1 -1
  43. package/dist/mcp/index.js +1 -1
  44. package/dist/mcp/tasks.d.ts +33 -0
  45. package/dist/mcp/tasks.js +3 -0
  46. package/dist/project/config.d.ts +2 -2
  47. package/dist/project/config.js +3 -2
  48. package/dist/project/index.d.ts +2 -2
  49. package/dist/project/index.js +3 -3
  50. package/dist/schemas.d.ts +2 -2
  51. package/dist/schemas.js +3 -3
  52. package/dist/standard-failures.d.ts +1 -1
  53. package/dist/tooling/cli.js +2 -2
  54. package/dist/vite/index.d.ts +2 -2
  55. package/dist/vite/index.js +15 -9
  56. package/dist/webhooks.d.ts +13 -2
  57. package/dist/webhooks.js +38 -1
  58. package/dist/workers/runtime.d.ts +1 -1
  59. package/dist/workers/runtime.js +1 -1
  60. package/package.json +15 -3
  61. package/skills/maximus/SKILL.md +14 -4
  62. package/skills/maximus/references/project.md +4 -0
  63. package/skills/maximus/references/routes-and-tools.md +11 -1
  64. package/templates/project/CLAUDE.md.template +3 -3
  65. package/templates/project/README.md.template +1 -0
  66. package/templates/project/tsconfig.json.template +1 -0
  67. package/dist/chunks/execution-rOiLo8VG.js +0 -84
  68. package/dist/chunks/result-CKgZHrnj.js +0 -56
  69. package/dist/chunks/schemas-p_aRcMC1.js +0 -227
  70. package/dist/chunks/validation-fTohBT6R.js +0 -420
@@ -1,227 +0,0 @@
1
- import { a as codecFault, c as defaultSchema, d as inputSchema, n as decodeSchema, o as decodeIssues, s as SchemaValidationError } from "./validation-fTohBT6R.js";
2
- import { Kind, Type, Type as Type$1, Type as t } from "@sinclair/typebox";
3
-
4
- // src/schema-reader.ts
5
- /**
6
- * Reads untrusted data — a stored record, a provider or model answer — through its schema's owner
7
- * semantics: defaults applied, normalizers run before their checks, unknown keys of a strip object
8
- * dropped. A refusal carries every issue with its path; nothing is coerced. An owner codec that fails
9
- * throws what it threw.
10
- */
11
- function checkSchema(schema, input) {
12
- try {
13
- return {
14
- success: true,
15
- data: decodeSchema(inputSchema(schema, { stripUnknown: true }), input)
16
- };
17
- } catch (error) {
18
- const issues = decodeIssues(error);
19
- if (!issues) throw codecFault(error);
20
- return {
21
- success: false,
22
- error: new SchemaValidationError(issues)
23
- };
24
- }
25
- }
26
- /** `checkSchema`, throwing its SchemaValidationError on refusal. */
27
- function readSchema(schema, input) {
28
- const checked = checkSchema(schema, input);
29
- if (!checked.success) throw checked.error;
30
- return checked.data;
31
- }
32
-
33
- // src/attachment-schema.ts
34
- /**
35
- * The file an HTTP operation answers with and its output schema, with nothing that needs a runtime. An
36
- * attachment is never a JSON or RPC value.
37
- */
38
- /** The output of an operation that answers with a file (`http.response: 'attachment'`). */
39
- const AttachmentOutputSchema = Type.Unsafe({
40
- [Kind]: "HttpAttachment",
41
- type: "string",
42
- format: "binary",
43
- description: "Authenticated attachment bytes with validated media type, filename and exact length."
44
- });
45
-
46
- // src/pagination.ts
47
- /**
48
- * The one list contract: bidirectional keyset pagination. A list takes the query fields `cursor`,
49
- * `direction` and `limit` and answers `{ object: 'list', data, pageInfo }`. The cursor is opaque to
50
- * callers; there is no page number, page size, offset or implicit total.
51
- *
52
- * `PageInfo` and each `Page` are named schemas, so an OpenAPI document carries them once as
53
- * `#/components/schemas/<name>` and every SDK generated from it shares their types.
54
- */
55
- /** A public schema name: an SDK type in every language generated from the document. */
56
- const PAGE_ID = /^[A-Z][A-Za-z0-9]{0,127}$/;
57
- /**
58
- * How to reach a list's neighboring pages: whether they exist and their opaque cursors, named `PageInfo`.
59
- */
60
- const PageInfoSchema = Type.Object({
61
- hasNextPage: Type.Boolean({ description: "Whether a later page exists in the current ordering." }),
62
- hasPreviousPage: Type.Boolean({ description: "Whether an earlier page exists in the current ordering." }),
63
- nextCursor: Type.Union([Type.String(), Type.Null()], { description: "Opaque cursor for the next page, or null when there is none." }),
64
- previousCursor: Type.Union([Type.String(), Type.Null()], { description: "Opaque cursor for the previous page, or null when there is none." })
65
- }, {
66
- $id: "PageInfo",
67
- additionalProperties: false
68
- });
69
- /**
70
- * A list's `limit`: an integer from 1 to `maximum` (100), `default` (25, or the maximum when it is lower)
71
- * when the caller sends none. A list whose items are costly lowers the maximum:
72
- * `{ ...PageQueryFields, limit: pageLimit({ maximum: 20 }) }`. A default outside 1 to the maximum, or a
73
- * value that is not an integer, throws a TypeError.
74
- */
75
- function pageLimit(options = {}) {
76
- const { maximum = 100, default: fallback = Math.min(25, maximum) } = options;
77
- 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.");
78
- return defaultSchema(Type.Integer({
79
- minimum: 1,
80
- maximum,
81
- description: `Maximum items returned in one page. Defaults to ${fallback}; larger reads require another cursor.`
82
- }), fallback);
83
- }
84
- /**
85
- * The query fields of a list, spread into its input beside its own filters: an optional opaque `cursor`, a
86
- * `direction` (`forward` by default, or `backward`) and a `limit` (`pageLimit()`).
87
- */
88
- const PageQueryFields = {
89
- cursor: Type.Optional(Type.String({ description: "Opaque cursor returned by pageInfo; omit it to request the first page." })),
90
- direction: defaultSchema(Type.Union([Type.Literal("forward"), Type.Literal("backward")], { description: "Direction to traverse the stable keyset ordering from the supplied cursor." }), "forward"),
91
- limit: pageLimit()
92
- };
93
- /**
94
- * The output of a list of `item`, named by `$id` (`AppointmentPage`), a PascalCase name of up to 128
95
- * characters; any other throws a TypeError. Give each list its own name and use it for that list only: two
96
- * different shapes under one `$id` become two components, the second one suffixed `_2`.
97
- */
98
- function Page(item, options) {
99
- if (!PAGE_ID.test(options.$id)) throw new TypeError(`Page "${options.$id}" needs a PascalCase schema name, such as AppointmentPage.`);
100
- return Type.Object({
101
- data: Type.Array(item, { description: "Items admitted by this resource contract within the verified organization." }),
102
- object: Type.Literal("list", { description: "Discriminator for a resource list response." }),
103
- pageInfo: {
104
- ...PageInfoSchema,
105
- description: "Opaque navigation cursors for this page’s stable keyset order."
106
- }
107
- }, {
108
- $id: options.$id,
109
- additionalProperties: false
110
- });
111
- }
112
-
113
- // src/common-schemas.ts
114
- /**
115
- * Values and objects that services publish alike, each named by its `$id`: an OpenAPI document carries
116
- * it once as `#/components/schemas/<name>`, and every SDK generated from those documents has one type
117
- * for it. A name is public, so it names exactly one shape. Domain records (people, patients,
118
- * identity documents) stay with the service that owns them.
119
- */
120
- /** An email address of at most 254 characters, named `EmailAddress`. */
121
- const EmailAddressSchema = Type.String({
122
- $id: "EmailAddress",
123
- format: "email",
124
- maxLength: 254,
125
- description: "Email address."
126
- });
127
- /** A phone number in E.164 format, named `PhoneNumber`. */
128
- const PhoneNumberSchema = Type.String({
129
- $id: "PhoneNumber",
130
- pattern: "^\\+[1-9][0-9]{1,14}$",
131
- description: "Phone number in E.164 format."
132
- });
133
- /** An HTTPS URL of at most 2048 characters, named `HttpsUrl`. */
134
- const HttpsUrlSchema = Type.String({
135
- $id: "HttpsUrl",
136
- format: "uri",
137
- pattern: "^https://",
138
- maxLength: 2048,
139
- description: "An HTTPS URL."
140
- });
141
- /** A `#rrggbb` color, named `HexColor`. */
142
- const HexColorSchema = Type.String({
143
- $id: "HexColor",
144
- pattern: "^#[0-9a-fA-F]{6}$",
145
- description: "A color, as #rrggbb."
146
- });
147
- /** What a delete answers: the deleted resource's id and `deleted: true`, named `DeletedObject`. */
148
- const DeletedObjectSchema = Type.Object({
149
- id: Type.String({ description: "The id of the deleted resource." }),
150
- deleted: Type.Literal(true)
151
- }, {
152
- $id: "DeletedObject",
153
- additionalProperties: false
154
- });
155
- /** The URL of a `SignedUrl`, described as the credential it is. */
156
- const SignedUrlFieldSchema = {
157
- ...HttpsUrlSchema,
158
- description: "The signed URL. Anyone holding it has access until it expires."
159
- };
160
- /**
161
- * A link that grants access by itself until it expires, such as a file download: its HTTPS `url` and its
162
- * `expiresAt` date-time, named `SignedUrl`.
163
- */
164
- const SignedUrlSchema = Type.Object({
165
- url: SignedUrlFieldSchema,
166
- expiresAt: Type.String({
167
- format: "date-time",
168
- description: "When the URL stops working."
169
- })
170
- }, {
171
- $id: "SignedUrl",
172
- additionalProperties: false
173
- });
174
- /** Another resource, by its id and the name people know it by, named `NamedReference`. */
175
- const NamedReferenceSchema = Type.Object({
176
- id: Type.String({ description: "The id of the referenced resource." }),
177
- name: Type.String({ description: "Its name." })
178
- }, {
179
- $id: "NamedReference",
180
- additionalProperties: false
181
- });
182
- /**
183
- * A postal address, shaped as FHIR `Address` (its lines, city, state, postal code, ISO 3166-1 alpha-2 country
184
- * code and use), every field optional, named `PostalAddress`.
185
- */
186
- const PostalAddressSchema = Type.Object({
187
- city: Type.Optional(Type.String({ maxLength: 120 })),
188
- countryCode: Type.Optional(Type.String({
189
- description: "ISO 3166-1 alpha-2.",
190
- pattern: "^[A-Z]{2}$"
191
- })),
192
- line: Type.Optional(Type.Array(Type.String({ maxLength: 200 }), { maxItems: 4 })),
193
- postalCode: Type.Optional(Type.String({ maxLength: 20 })),
194
- state: Type.Optional(Type.String({ maxLength: 120 })),
195
- use: Type.Optional(Type.Union([Type.Literal("home"), Type.Literal("work")]))
196
- }, {
197
- $id: "PostalAddress",
198
- additionalProperties: false
199
- });
200
-
201
- // src/schemas.ts
202
- /**
203
- * `@arbol-ai/maximus/schemas`: the browser-safe schema vocabulary: TypeBox (`t`), its types, the validators
204
- * and the shared identifier schemas, with nothing that needs a Worker runtime. A contract module that
205
- * browsers import (a Dashboard reading an API's limits, a widget's settings) imports from here rather than
206
- * the package root.
207
- */
208
- /** The input of an operation that takes none: an empty strict object. */
209
- const EmptyInputSchema = Type.Object({}, { additionalProperties: false });
210
- /**
211
- * An organization id as identity providers issue them (`org_…`, a UUID, a slug): 1 to 128 letters, digits,
212
- * `_` and `-`, starting with a letter or digit, named `OrganizationId`. Nothing in it can change the meaning
213
- * of a storage key, a path or a log line.
214
- */
215
- const OrganizationIdSchema = Type.String({
216
- $id: "OrganizationId",
217
- pattern: "^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$",
218
- description: "Verified organization identifier."
219
- });
220
- /** A lowercase RFC 9562 UUID of version 1 to 8, named `Uuid`. */
221
- const UuidSchema = Type.String({
222
- $id: "Uuid",
223
- format: "uuid",
224
- pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
225
- });
226
-
227
- export { pageLimit as _, t as a, readSchema as b, HexColorSchema as c, PhoneNumberSchema as d, PostalAddressSchema as f, PageQueryFields as g, PageInfoSchema as h, UuidSchema as i, 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, AttachmentOutputSchema as v, checkSchema as y };
@@ -1,420 +0,0 @@
1
- import { FormatRegistry, Kind, TransformKind, Type } from "@sinclair/typebox";
2
- import { AssertError, HasTransform, TransformDecode, TransformDecodeError, Value } from "@sinclair/typebox/value";
3
- import { fullFormats } from "ajv-formats/dist/formats.js";
4
-
5
- // src/input-schemas.ts
6
- /**
7
- * Owner codecs on TypeBox schemas: defaults, normalizers, transforms, inspections, refinements, pipes and
8
- * unknown-key stripping. `inputSchema()` compiles them into one input schema, so the wire is checked as
9
- * declared and the handler receives the decoded value.
10
- */
11
- /** Every issue of a refused value, as `readSchema` throws it and `checkSchema` returns it. */
12
- var SchemaValidationError = class extends TypeError {
13
- /** Every issue of the refused value; the error's message is the first one's. */
14
- issues;
15
- constructor(issues) {
16
- super(issues[0]?.message ?? "The input does not match its schema.");
17
- this.name = "SchemaValidationError";
18
- this.issues = issues;
19
- }
20
- };
21
- /** The ordered codec steps a schema runs inside `inputSchema()`. */
22
- const STEPS = Symbol("maximus.schema.steps");
23
- /** The transforms a schema applies after its source value is valid. */
24
- const TRANSFORMERS = Symbol("maximus.schema.transformers");
25
- /** The normalizers a schema applies before its own checks. */
26
- const NORMALIZERS = Symbol("maximus.schema.normalizers");
27
- /** The inspections and refinements a schema runs on a valid value. */
28
- const INSPECTORS = Symbol("maximus.schema.inspectors");
29
- /** The source schema of a `pipeSchema`, which the wire value is first read as. */
30
- const SOURCE = Symbol("maximus.schema.source");
31
- /** Whether an object drops unknown keys when read with `stripUnknown`. */
32
- const STRIP = Symbol("maximus.schema.strip");
33
- /** A union of literals: `literalUnion(['open', 'done'])`. */
34
- const literalUnion = (values) => Type.Union(values.map((value) => Type.Literal(value)));
35
- /**
36
- * The schema with a default that decoding applies when the field is absent, so the field is optional on the
37
- * wire.
38
- */
39
- const defaultSchema = (schema, value) => ({
40
- ...schema,
41
- default: value
42
- });
43
- /**
44
- * A strict object that, read with `stripUnknown` (as `readSchema` does), drops unknown keys instead of
45
- * refusing them. Wrap an input that uses it in `inputSchema()`.
46
- */
47
- const stripObject = (properties) => ({
48
- ...Type.Object(properties, { additionalProperties: false }),
49
- [STRIP]: true
50
- });
51
- /** The object, refusing unknown keys even where a read strips them. */
52
- const strictObject = (schema) => ({
53
- ...schema,
54
- additionalProperties: false,
55
- [STRIP]: false
56
- });
57
- /** The object, admitting and keeping unknown keys. */
58
- const looseObject = (schema) => ({
59
- ...schema,
60
- additionalProperties: true,
61
- [STRIP]: false
62
- });
63
- /** The object with more properties, keeping how it treats unknown keys. */
64
- const extendObject = (schema, properties) => ({
65
- ...Type.Object({
66
- ...schema.properties,
67
- ...properties
68
- }, { additionalProperties: schema.additionalProperties }),
69
- [STRIP]: schema[STRIP]
70
- });
71
- /**
72
- * Reads a field through `normalize`. For a string, or a string that may be null, the pattern, format and
73
- * lengths apply to the normalized value, so the wire may send a raw spelling (another case, surrounding
74
- * spaces); any other schema checks the raw value first. The wire type stays the schema's own. Runs inside
75
- * `inputSchema()`.
76
- */
77
- const normalizeSchema = (schema, normalize) => Type.Unsafe({
78
- ...schema,
79
- [NORMALIZERS]: [...schema[NORMALIZERS] ?? [], normalize],
80
- [STEPS]: [...schema[STEPS] ?? [], {
81
- kind: "normalize",
82
- apply: normalize
83
- }]
84
- });
85
- /**
86
- * Decodes a field with `transform` once its value passes `schema`: the wire sends what `schema` checks, and
87
- * the handler receives what `transform` returns. Runs inside `inputSchema()`.
88
- */
89
- const transformSchema = (schema, transform) => Type.Unsafe({
90
- ...schema,
91
- [TRANSFORMERS]: [...schema[TRANSFORMERS] ?? [], transform],
92
- [STEPS]: [...schema[STEPS] ?? [], {
93
- kind: "transform",
94
- apply: transform
95
- }]
96
- });
97
- /**
98
- * Admits a value as `source`, then checks and decodes the result as `target`: a wire shape read into its
99
- * canonical one. Runs inside `inputSchema()`.
100
- */
101
- const pipeSchema = (source, target) => ({
102
- ...target,
103
- [SOURCE]: source
104
- });
105
- /**
106
- * Runs `inspect` on a value the schema admits; every `addIssue` refuses the value with that issue. Runs
107
- * inside `inputSchema()`.
108
- */
109
- const inspectSchema = (schema, inspect) => ({
110
- ...schema,
111
- [INSPECTORS]: [...schema[INSPECTORS] ?? [], inspect],
112
- [STEPS]: [...schema[STEPS] ?? [], {
113
- kind: "inspect",
114
- apply: inspect
115
- }]
116
- });
117
- /**
118
- * Refuses a value the schema admits when `predicate` rejects it, with a `custom` issue whose message and path
119
- * `detail` gives (`Invalid value` at the field by default). Runs inside `inputSchema()`.
120
- */
121
- const refineSchema = (schema, predicate, detail) => inspectSchema(schema, (value, context) => {
122
- if (!predicate(value)) context.addIssue({
123
- code: "custom",
124
- message: typeof detail === "string" ? detail : detail?.message ?? detail?.error ?? "Invalid value",
125
- path: typeof detail === "object" ? detail.path ?? [] : []
126
- });
127
- });
128
- /**
129
- * A URL, of at most `maxLength` characters when given, whose protocol (without its colon, such as `https`)
130
- * and, optionally, hostname match the given patterns. Runs inside `inputSchema()`.
131
- */
132
- const urlSchema = (options) => refineSchema(Type.String({
133
- format: "uri",
134
- ...options.maxLength ? { maxLength: options.maxLength } : {}
135
- }), (value) => {
136
- try {
137
- const url = new URL(value);
138
- return options.protocol.test(url.protocol.slice(0, -1)) && (!options.hostname || options.hostname.test(url.hostname));
139
- } catch {
140
- return false;
141
- }
142
- });
143
- /** Compile owner semantics into real native TypeBox source codecs. Canonical output schemas stay strict. */
144
- const projectOwnerInput = (schema, stripUnknown) => {
145
- if (schema[SOURCE]) {
146
- const source = projectOwnerInput(schema[SOURCE], stripUnknown);
147
- const targetSchema = {
148
- ...schema,
149
- [SOURCE]: void 0
150
- };
151
- const target = projectOwnerInput(targetSchema, stripUnknown);
152
- return Type.Transform(source).Decode((value) => {
153
- const targetInput = Value.Default(target, value);
154
- Value.Assert(target, targetInput);
155
- return TransformDecode(target, [], targetInput);
156
- }).Encode((value) => value);
157
- }
158
- const projected = { ...schema };
159
- if (schema.properties) {
160
- projected.properties = Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => [key, projectOwnerInput(value, stripUnknown)]));
161
- projected.required = schema.required?.filter((key) => !("default" in schema.properties[key]));
162
- if (stripUnknown && schema[STRIP]) projected.additionalProperties = true;
163
- }
164
- if (schema.items) projected.items = Array.isArray(schema.items) ? schema.items.map((value) => projectOwnerInput(value, stripUnknown)) : projectOwnerInput(schema.items, stripUnknown);
165
- if (schema.anyOf) projected.anyOf = schema.anyOf.map((value) => {
166
- if ((schema[NORMALIZERS]?.length ?? 0) > 0 && value.type === "string") {
167
- const source = { ...value };
168
- delete source.pattern;
169
- delete source.format;
170
- delete source.minLength;
171
- delete source.maxLength;
172
- return projectOwnerInput(source, stripUnknown);
173
- }
174
- return projectOwnerInput(value, stripUnknown);
175
- });
176
- if (schema.patternProperties) projected.patternProperties = Object.fromEntries(Object.entries(schema.patternProperties).map(([key, value]) => [key, projectOwnerInput(value, stripUnknown)]));
177
- const normalizers = schema[NORMALIZERS] ?? [];
178
- if (schema.type === "string" && normalizers.length) {
179
- delete projected.pattern;
180
- delete projected.format;
181
- delete projected.minLength;
182
- delete projected.maxLength;
183
- }
184
- const transforms = schema[TRANSFORMERS] ?? [];
185
- const inspectors = schema[INSPECTORS] ?? [];
186
- const strip = stripUnknown && schema[STRIP] && schema.properties;
187
- if (!(normalizers.length || transforms.length || inspectors.length || strip)) return projected;
188
- return Type.Transform(projected).Decode((input) => {
189
- let value = input;
190
- if (strip && value !== null && typeof value === "object" && !Array.isArray(value)) value = Object.fromEntries(Object.entries(value).filter(([key]) => key in schema.properties));
191
- const issues = [];
192
- const steps = schema[STEPS] ?? [];
193
- for (const [index, step] of steps.entries()) if (step.kind === "inspect") {
194
- step.apply(value, { addIssue: (issue) => issues.push(issue) });
195
- if (issues.length) throw new SchemaValidationError(issues);
196
- } else {
197
- value = step.apply(value);
198
- if (step.kind === "normalize" && steps[index + 1]?.kind !== "normalize" && (schema.type === "string" || schema.anyOf?.every((branch) => branch.type === "string" || branch.type === "null")) && !Value.Check(schema, value)) throw new SchemaValidationError([{
199
- code: "invalid_input",
200
- message: "The normalized value does not match its schema.",
201
- path: []
202
- }]);
203
- }
204
- return value;
205
- }).Encode((value) => value);
206
- };
207
- /**
208
- * An input schema as callers send it, for the documents that publish it: a field with a default is optional,
209
- * since decoding fills it in. A schema `inputSchema()` compiled is its wire form already.
210
- */
211
- function wireInput(schema) {
212
- return TransformKind in schema ? schema : projectOwnerInput(schema, false);
213
- }
214
- /**
215
- * Whether a schema carries owner codecs that only `inputSchema()` compiles: a normalizer, transform,
216
- * inspector or refinement, a `pipeSchema` source, or a `stripObject`. A plain decode ignores their
217
- * markers, so such a schema used directly as an operation input would admit raw, unnormalized and
218
- * unrefined values without a word. A compiled subtree (a TypeBox transform) is already honest.
219
- */
220
- function hasUncompiledCodecs(schema) {
221
- const seen = /* @__PURE__ */ new Set();
222
- /**
223
- * Whether this schema, or any schema below it that no transform already compiled, carries a codec marker.
224
- */
225
- const visit = (node) => {
226
- if (!node || typeof node !== "object" || seen.has(node) || TransformKind in node) return false;
227
- seen.add(node);
228
- const owner = node;
229
- if ((owner[STEPS]?.length ?? 0) > 0 || owner[SOURCE] || owner[STRIP] === true) return true;
230
- return [
231
- ...Object.values(owner.properties ?? {}),
232
- ...Object.values(owner.patternProperties ?? {}),
233
- ...[owner.items].flat(),
234
- ...owner.anyOf ?? [],
235
- ...owner.allOf ?? [],
236
- ...owner.oneOf ?? []
237
- ].some(visit);
238
- };
239
- return visit(schema);
240
- }
241
- function inputSchema(schema, source) {
242
- const wire = source && Kind in source ? source : void 0;
243
- const stripUnknown = !wire && source && "stripUnknown" in source && source.stripUnknown === true;
244
- const projected = projectOwnerInput(schema, Boolean(stripUnknown));
245
- return Type.Transform(Type.Unsafe(wire ? projectOwnerInput(wire, false) : projected)).Decode((input) => {
246
- if (!wire) return input;
247
- const value = Value.Default(projected, input);
248
- Value.Assert(projected, value);
249
- return TransformDecode(projected, [], value);
250
- }).Encode((value) => value);
251
- }
252
-
253
- // src/internal/decode-issues.ts
254
- /**
255
- * Turns a failed TypeBox decode into field issues whose paths start at the input's root, as the
256
- * INVALID_INPUT failure carries them.
257
- */
258
- /** The segments of a JSON Pointer, unescaped. */
259
- function segments(path) {
260
- return path.split("/").slice(1).filter(Boolean).map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
261
- }
262
- /**
263
- * The issues of a refused decode, at most `limit`, each with its path from the input's root, or null when
264
- * nothing refused the input: an owner codec threw something other than a `SchemaValidationError`, which is
265
- * the codec's fault for the caller to report. A codec nested in another reports its issues below the path
266
- * the outer one decodes. TypeBox finds issues one at a time, so an input with millions of them costs no
267
- * more than `limit`.
268
- */
269
- function decodeIssues(error, limit = Number.POSITIVE_INFINITY) {
270
- let cause = error;
271
- const path = [];
272
- while (cause instanceof TransformDecodeError) {
273
- path.push(...segments(cause.path));
274
- cause = cause.error;
275
- }
276
- if (cause instanceof SchemaValidationError) return cause.issues.slice(0, limit).map((issue) => ({
277
- ...issue,
278
- path: [...path, ...issue.path]
279
- }));
280
- if (cause instanceof AssertError) {
281
- const issues = [];
282
- for (const issue of cause.Errors()) {
283
- issues.push({
284
- code: "invalid_input",
285
- message: issue.message,
286
- path: [...path, ...segments(issue.path)]
287
- });
288
- if (issues.length >= limit) break;
289
- }
290
- return issues;
291
- }
292
- return null;
293
- }
294
- /**
295
- * What an owner codec threw, without the TypeBox error that wraps it: that wrapper carries the value being
296
- * decoded, which a fault must never take with it to a log.
297
- */
298
- function codecFault(error) {
299
- let cause = error;
300
- while (cause instanceof TransformDecodeError) cause = cause.error;
301
- return cause;
302
- }
303
- /** RFC 6901 JSON Pointer of an issue path; the empty string names the whole input. */
304
- function jsonPointer(path) {
305
- return path.map((part) => `/${String(part).replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
306
- }
307
-
308
- // src/validation.ts
309
- /**
310
- * Schema validation: the check-only and the decoding validators, the guard that admits only bounded plain
311
- * JSON, and the RFC format validators registered once with TypeBox.
312
- */
313
- for (const name of [
314
- "date",
315
- "time",
316
- "date-time",
317
- "email",
318
- "uuid",
319
- "uri"
320
- ]) {
321
- const format = fullFormats[name];
322
- const validator = typeof format === "object" && !(format instanceof RegExp) ? format.validate : format;
323
- FormatRegistry.Set(name, (value) => {
324
- if (value.length > 8192) return false;
325
- if (validator instanceof RegExp) return validator.test(value);
326
- return typeof validator === "function" && validator(value) === true;
327
- });
328
- }
329
- /**
330
- * Checks a value against a schema without decoding it: the value when it matches, else an `INVALID_INPUT`
331
- * failure without issues. Use `decodeInput` for input with defaults and codecs.
332
- */
333
- function parseInput(schema, input) {
334
- if (Value.Check(schema, input)) return {
335
- ok: true,
336
- value: input
337
- };
338
- return {
339
- ok: false,
340
- error: {
341
- code: "INVALID_INPUT",
342
- message: "The input does not match its schema.",
343
- retryable: false,
344
- data: {}
345
- }
346
- };
347
- }
348
- /** Checks a value against a schema and returns it typed, or throws a TypeError that names no value. */
349
- function parseSchema(schema, input) {
350
- if (!Value.Check(schema, input)) throw new TypeError("Value does not match its schema");
351
- return input;
352
- }
353
- /**
354
- * Whether a value is a bounded plain JSON tree, which TypeBox's traversals expect and every transport admits:
355
- * no cycles, class instances, functions, non-finite numbers, nesting beyond 100 levels or own `__proto__` key.
356
- */
357
- function boundedInput(value, depth = 0, parents = /* @__PURE__ */ new Set()) {
358
- if (depth > 100) return false;
359
- if (value === void 0 || value === null || typeof value === "string" || typeof value === "boolean") return true;
360
- if (typeof value === "number") return Number.isFinite(value);
361
- if (typeof value !== "object" || parents.has(value)) return false;
362
- if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
363
- if (Object.hasOwn(value, "__proto__")) return false;
364
- parents.add(value);
365
- const valid = Object.values(value).every((child) => boundedInput(child, depth + 1, parents));
366
- parents.delete(value);
367
- return valid;
368
- }
369
- /**
370
- * Decodes input against its schema: admits only a bounded plain JSON tree, applies the declared defaults to a
371
- * copy, checks it and runs its codecs. Throws a `SchemaValidationError` (or TypeBox's assertion error) when the
372
- * input is refused, and whatever an owner codec throws otherwise. Output is checked, never decoded: what a
373
- * handler returns must already be canonical.
374
- */
375
- function decodeSchema(schema, input) {
376
- if (!boundedInput(input)) throw new SchemaValidationError([{
377
- code: "invalid_input",
378
- message: "Input must be a bounded plain JSON tree.",
379
- path: []
380
- }]);
381
- const value = Value.Default(schema, Value.Clone(input));
382
- Value.Assert(schema, value);
383
- return HasTransform(schema, []) ? TransformDecode(schema, [], value) : value;
384
- }
385
- /** The most field issues one refusal carries. */
386
- const MAX_ISSUES = 10;
387
- /** The longest path or message one issue carries. */
388
- const MAX_ISSUE_TEXT = 256;
389
- /**
390
- * Decodes input as `decodeSchema` does and answers a refusal as the `INVALID_INPUT` failure, with its first
391
- * field issues: where the input failed and what was expected, never a value. A fault of an owner codec, an
392
- * error that refuses nothing, is thrown for the caller to report: it is the server's failure, not the input's.
393
- */
394
- function decodeInput(schema, input) {
395
- let value;
396
- try {
397
- value = decodeSchema(schema, input);
398
- } catch (error) {
399
- const refused = decodeIssues(error, MAX_ISSUES);
400
- if (!refused) throw codecFault(error);
401
- return {
402
- ok: false,
403
- error: {
404
- code: "INVALID_INPUT",
405
- message: "The input does not match its schema.",
406
- retryable: false,
407
- data: { issues: refused.map((issue) => ({
408
- path: jsonPointer(issue.path).slice(0, MAX_ISSUE_TEXT),
409
- message: issue.message.slice(0, MAX_ISSUE_TEXT)
410
- })) }
411
- }
412
- };
413
- }
414
- return {
415
- ok: true,
416
- value
417
- };
418
- }
419
-
420
- export { wireInput as S, refineSchema as _, codecFault as a, transformSchema as b, defaultSchema as c, inputSchema as d, inspectSchema as f, pipeSchema as g, normalizeSchema as h, parseSchema as i, extendObject as l, looseObject as m, decodeSchema as n, decodeIssues as o, literalUnion as p, parseInput as r, SchemaValidationError as s, decodeInput as t, hasUncompiledCodecs as u, strictObject as v, urlSchema as x, stripObject as y };