@schema-engine/registry 0.5.1 → 0.6.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.
- package/README.md +98 -14
- package/dist/bind-registry.d.ts +68 -0
- package/dist/bind-registry.js +1 -0
- package/dist/bind-registry.js.map +7 -0
- package/dist/chunk-24SNVXNP.js +2 -0
- package/dist/chunk-24SNVXNP.js.map +7 -0
- package/dist/chunk-55J6XMHW.js +0 -0
- package/dist/chunk-55J6XMHW.js.map +7 -0
- package/dist/chunk-DE7GQKZP.js +3 -0
- package/dist/chunk-DE7GQKZP.js.map +7 -0
- package/dist/chunk-FMWSZRDV.js +1 -0
- package/dist/chunk-FMWSZRDV.js.map +7 -0
- package/dist/chunk-GX6PAJLU.js +1 -0
- package/dist/chunk-GX6PAJLU.js.map +7 -0
- package/dist/chunk-IYIWS4LW.js +1 -0
- package/dist/chunk-IYIWS4LW.js.map +7 -0
- package/dist/chunk-LG33VSKX.js +1 -0
- package/dist/chunk-LG33VSKX.js.map +7 -0
- package/dist/chunk-NSLF54GM.js +1 -0
- package/dist/chunk-NSLF54GM.js.map +7 -0
- package/dist/chunk-O5CRFISG.js +1 -0
- package/dist/chunk-O5CRFISG.js.map +7 -0
- package/dist/chunk-P3DDHPDA.js +1 -0
- package/dist/chunk-P3DDHPDA.js.map +7 -0
- package/dist/chunk-QHVQ4S4D.js +1 -0
- package/dist/chunk-QHVQ4S4D.js.map +7 -0
- package/dist/chunk-RVS7JY2Y.js +1 -0
- package/dist/chunk-RVS7JY2Y.js.map +7 -0
- package/dist/chunk-UH3CEF45.js +1 -0
- package/dist/chunk-UH3CEF45.js.map +7 -0
- package/dist/chunk-XG4EZ5VP.js +1 -0
- package/dist/chunk-XG4EZ5VP.js.map +7 -0
- package/dist/create-registry.d.ts +83 -7
- package/dist/create-registry.js +1 -1
- package/dist/create-registry.js.map +4 -4
- package/dist/export-tree-schema.d.ts +100 -0
- package/dist/export-tree-schema.js +1 -0
- package/dist/export-tree-schema.js.map +7 -0
- package/dist/format-issue-path.d.ts +12 -0
- package/dist/format-issue-path.js +1 -0
- package/dist/format-issue-path.js.map +7 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/json-schema/embedder.d.ts +119 -0
- package/dist/json-schema/embedder.js +1 -0
- package/dist/json-schema/embedder.js.map +7 -0
- package/dist/json-schema/index.d.ts +5 -0
- package/dist/json-schema/index.js +1 -0
- package/dist/json-schema/index.js.map +7 -0
- package/dist/json-schema/slot.d.ts +46 -0
- package/dist/json-schema/slot.js +1 -0
- package/dist/json-schema/slot.js.map +7 -0
- package/dist/json-schema/standard.d.ts +44 -0
- package/dist/json-schema/standard.js +1 -0
- package/dist/json-schema/standard.js.map +7 -0
- package/dist/parse-node.d.ts +131 -0
- package/dist/parse-node.js +1 -0
- package/dist/parse-node.js.map +7 -0
- package/dist/parse-tree.d.ts +131 -0
- package/dist/parse-tree.js +1 -0
- package/dist/parse-tree.js.map +7 -0
- package/dist/registry-error.d.ts +80 -0
- package/dist/registry-error.js +1 -0
- package/dist/registry-error.js.map +7 -0
- package/dist/standard-schema.d.ts +19 -0
- package/dist/standard-schema.js +1 -1
- package/dist/standard-schema.js.map +4 -4
- package/dist/tree-types.d.ts +152 -0
- package/dist/tree-types.js +0 -0
- package/dist/tree-types.js.map +7 -0
- package/dist/types.d.ts +41 -0
- package/dist/types.js +1 -0
- package/dist/yaml/index.js +1 -4
- package/dist/yaml/index.js.map +4 -4
- package/dist/yaml/parse.js +1 -2
- package/dist/yaml/parse.js.map +4 -4
- package/dist/yaml/stringify.js +1 -3
- package/dist/yaml/stringify.js.map +4 -4
- package/package.json +13 -9
- package/skill/SKILL.md +34 -33
- package/skill/reference/registry.md +120 -7
- package/dist/base-registry.d.ts +0 -73
- package/dist/base-registry.js +0 -1
- package/dist/base-registry.js.map +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/parse-node.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseStandardSchema, type StandardSchemaIssue } from './standard-schema.js';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * What {@link safeParseNode} needs of a registry: the registration of a `$type`, of which it reads the schema.\n * Both registry kinds fit.\n */\nexport interface NodeLookup<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> {\n\tget(key: string): TRegistration | undefined;\n\t/**\n\t * The registry's label, for example `Widget`, as it is used in errors.\n\t *\n\t * @remarks\n\t * {@link safeParseTree} names it in the `RegistryError` it throws when a schema contradicts its registration, and\n\t * leaves it out for a lookup that has none, such as a function that tries several registries.\n\t */\n\treadonly kind?: string;\n\t/**\n\t * A sentence that follows the message of a `$type` `get` does not answer, such as where to register it.\n\t *\n\t * @remarks\n\t * The message is `No registration for $type 'x'.`, a space and the hint. A registry built with the `hint` option\n\t * has it.\n\t */\n\thint?: string;\n}\n\n/**\n * What {@link safeParseNode} returns: the registration with the node's validated configuration, or every issue found.\n *\n * @remarks\n * The success branch has one member per registration of a typed registry, so checking `$type` (the node's, repeated at\n * the top of the result because TypeScript narrows a union only by a property of the union itself) narrows\n * `registration` and `data` together. A registration that does not declare its `$type`, such as a lookup typed by\n * `{ schema }` alone, leaves it a `string`. A registry typed as plain `BaseRegistration` has no concrete schema to\n * read, so its `data` is `unknown`.\n */\nexport type SafeParseNodeResult<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> =\n\t| (TRegistration extends unknown\n\t\t\t? {\n\t\t\t\t\tsuccess: true;\n\t\t\t\t\t$type: TRegistration extends { $type: infer TType extends string } ? TType : string;\n\t\t\t\t\tregistration: TRegistration;\n\t\t\t\t\tdata: StandardSchemaV1.InferOutput<TRegistration['schema']>;\n\t\t\t\t}\n\t\t\t: never)\n\t| { success: false; issues: RegistryIssue[] };\n\n/**\n * The message for a `$type` no registration answers, as {@link safeParseNode} reports it.\n *\n * @param type - The `$type` that found nothing\n * @param hint - A sentence that follows the message, as {@link NodeLookup.hint} gives it\n *\n * @remarks\n * Exported so a caller that has to throw for the same case, instead of returning an issue, says the same thing.\n */\nexport function unregisteredTypeMessage(type: string, hint?: string): string {\n\tconst message = `No registration for $type '${type}'.`;\n\treturn hint ? `${message} ${hint}` : message;\n}\n\n/**\n * An issue of a node or a document, as {@link safeParseNode} and {@link safeParseTree} report it.\n *\n * @remarks\n * The issues the engine creates itself carry a namespaced `code`, so a consumer can branch on it and a schema library's\n * own `code`, which an issue from a schema keeps untouched, cannot be mistaken for one:\n *\n * - `'registry/not-an-object'`: the node is not an object.\n * - `'registry/missing-type'`: the node has no string `$type`.\n * - `'registry/unregistered-type'`: no registration answers the `$type` (`received`).\n * - `'registry/not-accepted'`: the `$type` (`received`) is not in the `accepts` list (`expected`) of its position.\n * - `'registry/not-a-node'`: a value at a child path is neither an object nor a list.\n * - `'registry/not-a-list'`: a value at a child path that sets `list` is not an array.\n * - `'registry/contains-itself'`: a node is reached again through its own ancestors.\n *\n * The messages are written for a person and may be reworded; the codes stay.\n */\nexport interface RegistryIssue extends StandardSchemaIssue {\n\t/** The namespaced code of an issue the engine created, or whatever the schema library put on its own issue. */\n\treadonly code?: string;\n\t/**\n\t * What would have fitted, for `'registry/not-accepted'`: the `accepts` list.\n\t *\n\t * @remarks\n\t * Set only on an issue the engine created. An issue from a schema keeps its library's own fields untouched, and some\n\t * libraries have an `expected` or `received` of their own, so check `code` first.\n\t */\n\treadonly expected?: readonly string[];\n\t/** What was there, for `'registry/not-accepted'` and `'registry/unregistered-type'`: the `$type`. */\n\treadonly received?: string;\n}\n\n/**\n * What a call of {@link safeParseNode} or {@link safeParseTree} may be told besides the node.\n *\n * @remarks\n * For {@link safeParseTree}, `TType` is the `$type`s of the lookup, so a name it lacks is a type error and a literal\n * `accepts` narrows the root.\n */\nexport interface ParseOptions<TType extends string = string> {\n\t/** Where the node sits in its document. Every issue's `path` starts with it. */\n\treadonly path?: NonNullable<StandardSchemaIssue['path']>;\n\t/**\n\t * The `$type`s the node may have, as a position of a document accepts them. Not empty when present, or the call\n\t * throws: an empty list is a caller bug, like an asynchronous schema.\n\t */\n\treadonly accepts?: readonly TType[];\n}\n\nfunction notAcceptedMessage(type: string, accepts: readonly string[]): string {\n\tconst names = accepts.map((name) => `'${name}'`);\n\tconst expected = names.length === 1 ? names[0] : `one of ${names.join(', ')}`;\n\treturn `$type '${type}' is not accepted here. Expected ${expected}.`;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Check one node against the registration its `$type` names, without throwing.\n *\n * @param registry - Where the node's `$type` finds its registration\n * @param node - The node as it arrived, for example one entry of a parsed JSON document\n * @param options - Where the node sits (`path`) and which `$type`s it may have (`accepts`), see {@link ParseOptions}\n *\n * @remarks\n * An issue points at the value that is wrong, as a schema reports it, so an editor can mark that value and a YAML\n * mapper finds its line: a node that is not an object is an issue at `path`; an object without a string `$type`, a\n * `$type` outside `accepts` and a `$type` no registration answers are issues at `[...path, '$type']`, where a schema\n * reports a missing required key. `accepts` is checked before the lookup, so a `$type` outside the list is not\n * accepted whether or not it is registered, and the issue names what would fit. The lookup's `hint` adds to the message\n * of an unregistered `$type` only.\n * Otherwise the issues are those of the registration's schema, with `path` in front of the path the schema reported.\n *\n * `data` is what the schema returned, so its defaults and transforms apply. Its type is the schema output of the\n * registration that `registration.$type` names, for a registry typed by registrations with literal `$type`s, and\n * `unknown` for one typed as `BaseRegistration`. TypeScript cannot follow the runtime lookup from the node's string\n * `$type` to a registration, so the function returns `data` through one cast to that type: it is the value the matched\n * registration's own schema returned. The node is checked on its own, whatever its `childPaths` say, and its schema\n * may omit `$type`: {@link safeParseTree} walks a tree with it and holds the schema to the registration's contract.\n *\n * @throws {Error} When the registration's schema validates asynchronously, as {@link safeParseStandardSchema} does,\n * and when `accepts` is an empty list.\n */\nexport function safeParseNode<TRegistration extends Pick<BaseRegistration, 'schema'>>(\n\tregistry: NodeLookup<TRegistration>,\n\tnode: unknown,\n\toptions: ParseOptions = {},\n): SafeParseNodeResult<TRegistration> {\n\tconst { path = [], accepts } = options;\n\tif (accepts?.length === 0) throw new Error('accepts must name at least one $type.');\n\tif (!isRecord(node)) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: [{ code: 'registry/not-an-object', message: 'Expected an object with a string $type.', path }],\n\t\t};\n\t}\n\tconst type = node.$type;\n\tif (typeof type !== 'string') {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: [{ code: 'registry/missing-type', message: 'Expected a string $type.', path: [...path, '$type'] }],\n\t\t};\n\t}\n\tif (accepts && !accepts.includes(type)) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: [\n\t\t\t\t{\n\t\t\t\t\tcode: 'registry/not-accepted',\n\t\t\t\t\tmessage: notAcceptedMessage(type, accepts),\n\t\t\t\t\tpath: [...path, '$type'],\n\t\t\t\t\texpected: accepts,\n\t\t\t\t\treceived: type,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst registration = registry.get(type);\n\tif (!registration) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: [\n\t\t\t\t{\n\t\t\t\t\tcode: 'registry/unregistered-type',\n\t\t\t\t\tmessage: unregisteredTypeMessage(type, registry.hint),\n\t\t\t\t\tpath: [...path, '$type'],\n\t\t\t\t\treceived: type,\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\tconst parsed = safeParseStandardSchema(registration.schema, node);\n\tif (parsed.success) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\t$type: type,\n\t\t\tregistration,\n\t\t\tdata: parsed.data,\n\t\t} as SafeParseNodeResult<TRegistration>;\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\tissues: parsed.error.issues.map((issue) => ({ ...issue, path: [...path, ...(issue.path ?? [])] })),\n\t};\n}\n"],
|
|
5
|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O,CACN,QAAS,GACT,OAAQ,CACP,CACC,KAAM,6BACN,QAAShB,EAAwBC,EAAMW,EAAS,IAAI,EACpD,KAAM,CAAC,GAAGG,EAAM,OAAO,EACvB,SAAUd,CACX,CACD,CACD,EAED,IAAMgB,EAASC,EAAwBF,EAAa,OAAQH,CAAI,EAChE,OAAII,EAAO,QACH,CACN,QAAS,GACT,MAAOhB,EACP,aAAAe,EACA,KAAMC,EAAO,IACd,EAEM,CACN,QAAS,GACT,OAAQA,EAAO,MAAM,OAAO,IAAKE,IAAW,CAAE,GAAGA,EAAO,KAAM,CAAC,GAAGJ,EAAM,GAAII,EAAM,MAAQ,CAAC,CAAE,CAAE,EAAE,CAClG,CACD",
|
|
6
|
+
"names": ["unregisteredTypeMessage", "type", "hint", "message", "notAcceptedMessage", "accepts", "names", "name", "expected", "isRecord", "value", "safeParseNode", "registry", "node", "options", "path", "registration", "parsed", "safeParseStandardSchema", "issue"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r(t){return typeof(t!==null&&(typeof t=="object"||typeof t=="function")?t["~standard"]:void 0)?.validate=="function"}function s(t,n){let a=t["~standard"].validate(n);if(a&&typeof a.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(a===null||typeof a!="object")throw new Error("Standard Schema validation returned an invalid result");let e=a;return e.issues!==void 0?{success:!1,error:{issues:[...e.issues]}}:{success:!0,data:e.value}}function u(t){return{"~standard":{version:1,vendor:"schema-engine",validate:t}}}export{r as a,s as b,u as c};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/standard-schema.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type StandardSchemaIssue = StandardSchemaV1.Issue;\n\nexport type StandardSchemaSafeParseResult<T> =\n\t{ success: true; data: T } | { success: false; error: { issues: StandardSchemaIssue[] } };\n\n/**\n * Whether `schema` is a Standard Schema: an object or function with a `~standard.validate` function.\n *\n * @remarks\n * It looks at the shape only and never runs the schema. {@link assertStandardSchema} throws where this returns `false`, and\n * {@link createRegistry} reports a registration for which it is `false` as `'invalid-schema'`. A domain package that checks\n * schemas of its own, such as the slot schemas of a recipe, uses it to throw a {@link RegistryError} with its own details.\n */\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n\tconst standard =\n\t\tschema !== null && (typeof schema === 'object' || typeof schema === 'function')\n\t\t\t? (schema as Partial<StandardSchemaV1>)['~standard']\n\t\t\t: undefined;\n\treturn typeof standard?.validate === 'function';\n}\n\n/**\n * Validate `value` with a Standard Schema without throwing.\n *\n * @param schema - Standard Schema to run\n * @param value - Input to validate\n * @throws {Error} When the schema validates asynchronously or returns a malformed result\n *\n * @remarks\n * Only synchronous validation is supported, because the callers (registry lookups, form validation,\n * action parsing) need an immediate result.\n */\nexport function safeParseStandardSchema<TInput, TOutput>(\n\tschema: StandardSchemaV1<TInput, TOutput>,\n\tvalue: TInput,\n): StandardSchemaSafeParseResult<TOutput> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\n\tconst syncResult = result as StandardSchemaV1.Result<TOutput>;\n\n\tif (syncResult.issues !== undefined) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tissues: [...syncResult.issues],\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { success: true, data: syncResult.value };\n}\n\n/**\n * A Standard Schema that validates with a function, for a check that is not a schema library's.\n *\n * @param validate - Returns `{ value }` for an input that passes, or `{ issues }` for one that does not\n *\n * @remarks\n * The schema reports `schema-engine` as its vendor and is synchronous, as {@link safeParseStandardSchema} requires.\n * `TInput` only types what the schema accepts, so an authoring type can be inferred from it; `validate` still receives `unknown`.\n */\nexport function standardSchema<TOutput, TInput = unknown>(\n\tvalidate: (value: unknown) => StandardSchemaV1.Result<TOutput>,\n): StandardSchemaV1<TInput, TOutput> {\n\treturn { '~standard': { version: 1, vendor: 'schema-engine', validate } };\n}\n"],
|
|
5
|
+
"mappings": "AAeO,SAASA,EAAiBC,EAA6C,CAK7E,OAAO,OAHNA,IAAW,OAAS,OAAOA,GAAW,UAAY,OAAOA,GAAW,YAChEA,EAAqC,WAAW,EACjD,SACoB,UAAa,UACtC,CAaO,SAASC,EACfD,EACAE,EACyC,CACzC,IAAMC,EAASH,EAAO,WAAW,EAAE,SAASE,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD,CAWO,SAASC,EACfC,EACoC,CACpC,MAAO,CAAE,YAAa,CAAE,QAAS,EAAG,OAAQ,gBAAiB,SAAAA,CAAS,CAAE,CACzE",
|
|
6
|
+
"names": ["isStandardSchema", "schema", "safeParseStandardSchema", "value", "result", "syncResult", "standardSchema", "validate"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as E}from"./chunk-O5CRFISG.js";import{a as j}from"./chunk-XG4EZ5VP.js";function B(t,o){let a=s=>({$type:s.$type,registration:s.registration,output:o.get(s)??s.data,path:s.path,children:[]}),n=a(t),e=[[t,n]];for(let s=e.pop();s;s=e.pop()){let[l,h]=s;for(let{keys:r,nodes:m}of l.children){let f=[];h.children.push({keys:r,nodes:f});for(let y of m){let i=a(y);f.push(i),e.push([y,i])}}}return n}function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function D(t){if(!b(t))return!1;let o=Object.getPrototypeOf(t);return o===Object.prototype||o===null}function M(t,o,a){let n=t;for(let e of o){if(!a(n)||!Object.hasOwn(n,e))return;n=n[e]}return n}function V(t,o,a){Object.defineProperty(t,o,{value:a,enumerable:!0,writable:!0,configurable:!0})}function F(t,o){let a={...t},n=new Set([a]);for(let{keys:e,value:s}of o){let l=a;for(let h of e.slice(0,-1)){let r=l[h];n.has(r)||(r={...r},n.add(r),V(l,h,r)),l=r}V(l,e[e.length-1],s)}return a}function J(t,o,a){let n=t,e=[],s=new Map,l=n.kind===void 0?"":`${n.kind} `,h=n.kind===void 0?{}:{kind:n.kind};function r(i,T){return new j("schema-breaks-child-path",`${l}'${i}' schema output does not keep the child path '${T.join(".")}' as the document has it.`,{...h,$type:i,childPath:T})}function m(i,T,S,K){if(S.includes(i)){e.push({code:"registry/contains-itself",message:"A node cannot contain itself.",path:T});return}let A=E(n,i,{path:T,accepts:K});if(!A.success){e.push(...A.issues);return}let{$type:u,registration:I}=A,p=A.data;if(!D(p)||!Object.hasOwn(p,"$type")||p.$type!==u)throw new j("schema-changes-type",`${l}'${u}' schema output must keep its $type '${u}'.`,{...h,$type:u});let q=i,v=[...S,i],W=[],N=[],k=!0;for(let{keys:d,accepts:L,list:z}of I.childPaths??[]){let w=[];W.push({keys:d,nodes:w});let c=M(q,d,b),P=M(p,d,D),O=[...T,...d];if(c===void 0){if(P!==void 0&&!(Array.isArray(P)&&P.length===0))throw r(u,d)}else if(z===!0&&!Array.isArray(c))e.push({code:"registry/not-a-list",message:"Expected a list of nodes.",path:O}),k=!1;else if(Array.isArray(c)){if(!Array.isArray(P)||P.length!==c.length)throw r(u,d);let g=0;for(let R=0;R<c.length;R+=1){let $=m(c[R],[...O,R],v,L);$&&(w.push($),$.data!==void 0&&(g+=1))}g===c.length?N.push({keys:d,value:w.map(R=>R.data)}):k=!1}else if(b(c)){if(!b(P))throw r(u,d);let g=m(c,O,v,L);g?(w.push(g),g.data!==void 0?N.push({keys:d,value:g.data}):k=!1):k=!1}else e.push({code:"registry/not-a-node",message:"Expected a node or a list of nodes.",path:O}),k=!1}let x;k&&(x=N.length===0?p:F(p,N));let C={$type:u,registration:I,data:x,path:T,children:W};return x!==p&&s.set(C,p),C}let f=m(o,a?.path??[],[],a?.accepts),y;return f?.data!==void 0&&e.length===0?y={success:!0,tree:f}:f?y={success:!1,issues:e,tree:B(f,s)}:y={success:!1,issues:e},y}export{J as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/parse-tree.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseNode, type NodeLookup, type ParseOptions, type RegistryIssue } from './parse-node.js';\nimport { RegistryError } from './registry-error.js';\nimport type { Accepted, AcceptedOf, CheckLookup, NodeData, TreeRegistration } from './tree-types.js';\nimport type { StandardSchemaIssue } from './standard-schema.js';\nimport type { ChildPath } from './types.js';\n\n/**\n * One node of a validated document: its registration, its data, where it sits and its children.\n *\n * @remarks\n * `$type` is the node's own, repeated at the top for the same reason as on {@link SafeParseNodeResult}: checking it\n * narrows `registration` and `data` together. `data` is the node's composed data: the schema output with each child\n * path replaced by the data of the children found there, so it is the same object the parent's data holds at that\n * position, and `tree.data` is the whole parsed document. `children` has one entry per child path the registration\n * declares, in declaration order, each `{ keys, nodes }` with `nodes` empty when the node holds none there, in document\n * order. Find an entry by its `keys`, compared key by key and never by index or by a joined string (`['a.b']` and\n * `['a', 'b']` are two paths), or read `data`, which is typed per path. `TAll` is the whole union of registrations, so a child is typed by what its\n * path accepts, or by the whole union without `accepts`.\n */\nexport type ParsedNode<\n\tTAll extends TreeRegistration,\n\tTRegistration extends TreeRegistration = TAll,\n> = TRegistration extends unknown\n\t? {\n\t\t\t$type: TRegistration['$type'];\n\t\t\tregistration: TRegistration;\n\t\t\tdata: NodeData<TAll, TRegistration>;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: ParsedChildren<TAll, TRegistration['childPaths']>;\n\t\t}\n\t: never;\n\n/** The `children` of a node: a tuple over the declared child paths, each `nodes` typed by its `accepts`. */\ntype ParsedChildren<TAll extends TreeRegistration, TPaths> = TPaths extends readonly ChildPath[]\n\t? {\n\t\t\treadonly [I in keyof TPaths]: TPaths[I] extends ChildPath\n\t\t\t\t? { keys: TPaths[I]['keys']; nodes: readonly ParsedNode<TAll, Accepted<TAll, TPaths[I]>>[] }\n\t\t\t\t: never;\n\t\t}\n\t: readonly [];\n\n/**\n * One node of a document that has issues: its registration, its own schema output, where it sits and the children that\n * parsed.\n *\n * @remarks\n * `output` is exactly what {@link safeParseNode} returned for the node. No child data is written into it, so a child\n * slot holds whatever the parent's schema returned there (the authored items, for an opaque slot), including children\n * that failed or were pruned. Read the children from `children`, never from a slot of `output`. There is no `data`:\n * the composed document exists only when there are no issues, as `data` of a {@link ParsedNode}. `children` has one\n * `{ keys, nodes }` entry per child path the registration declares, in declaration order, with `nodes` holding the\n * children that parsed in document order, each with its own `path`. A child that failed is missing, so the issues, not\n * the position in `nodes`, say where it was. A child is any `PartialNode<TAll>`, narrowed by its `$type`, not by\n * `accepts`.\n */\nexport type PartialNode<\n\tTAll extends TreeRegistration,\n\tTRegistration extends TreeRegistration = TAll,\n> = TRegistration extends unknown\n\t? {\n\t\t\t$type: TRegistration['$type'];\n\t\t\tregistration: TRegistration;\n\t\t\toutput: StandardSchemaV1.InferOutput<TRegistration['schema']>;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: readonly { keys: readonly string[]; nodes: readonly PartialNode<TAll>[] }[];\n\t\t}\n\t: never;\n\n/**\n * What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found and the nodes that\n * parsed.\n *\n * @remarks\n * `tree` on the failure branch is present exactly when the root's own schema passed, and is absent when the root\n * failed, was not accepted or has no registration.\n */\nexport type SafeParseTreeResult<TAll extends TreeRegistration, TRoot extends TreeRegistration = TAll> =\n\t| { success: true; tree: ParsedNode<TAll, TRoot> }\n\t| { success: false; issues: RegistryIssue[]; tree?: PartialNode<TAll, TRoot> };\n\n/**\n * The registrations a root may be: those `accepts` names, but only when the options type has `accepts`, not when it\n * only may.\n */\ntype RootOf<TAll extends TreeRegistration, TOptions> = TOptions extends {\n\treadonly accepts: readonly (infer TName)[];\n}\n\t? AcceptedOf<TAll, TName>\n\t: TAll;\n\n/**\n * A node the walk kept, in the shape of a {@link ParsedNode}, which the success path returns as it is.\n *\n * @remarks\n * `data` is the composed data, and is `undefined` exactly when something below the node failed, was pruned or was no\n * node: a complete node's data is always an object, so `data !== undefined` is the completeness test and the node\n * carries no flag. The schema output of a node whose `data` is not that same object is kept apart, in the walk's\n * `outputs`, so a node costs no field the caller would see.\n */\ninterface WalkedNode {\n\t$type: string;\n\tregistration: TreeRegistration;\n\tdata: unknown;\n\tpath: NonNullable<StandardSchemaIssue['path']>;\n\tchildren: { keys: readonly string[]; nodes: WalkedNode[] }[];\n}\n\ninterface PartialRuntimeNode {\n\t$type: string;\n\tregistration: TreeRegistration;\n\toutput: unknown;\n\tpath: NonNullable<StandardSchemaIssue['path']>;\n\tchildren: { keys: readonly string[]; nodes: PartialRuntimeNode[] }[];\n}\n\n/**\n * The {@link PartialNode} shape of a walked tree, built without recursion so that a document as deep as the walk can\n * handle converts too.\n *\n * @remarks\n * A node's `output` is its entry in `outputs`, or its `data` when it has none: a node with no child to write has the\n * schema output itself as `data`.\n */\nfunction toPartial(root: WalkedNode, outputs: ReadonlyMap<WalkedNode, unknown>): PartialRuntimeNode {\n\tconst partialOf = (node: WalkedNode): PartialRuntimeNode => ({\n\t\t$type: node.$type,\n\t\tregistration: node.registration,\n\t\toutput: outputs.get(node) ?? node.data,\n\t\tpath: node.path,\n\t\tchildren: [],\n\t});\n\tconst top = partialOf(root);\n\tconst pending: [WalkedNode, PartialRuntimeNode][] = [[root, top]];\n\tfor (let next = pending.pop(); next; next = pending.pop()) {\n\t\tconst [source, target] = next;\n\t\tfor (const { keys, nodes } of source.children) {\n\t\t\tconst kept: PartialRuntimeNode[] = [];\n\t\t\ttarget.children.push({ keys, nodes: kept });\n\t\t\tfor (const child of nodes) {\n\t\t\t\tconst converted = partialOf(child);\n\t\t\t\tkept.push(converted);\n\t\t\t\tpending.push([child, converted]);\n\t\t\t}\n\t\t}\n\t}\n\treturn top;\n}\n\ntype PlainObject = Record<PropertyKey, unknown>;\n\nfunction isRecord(value: unknown): value is PlainObject {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n\tif (!isRecord(value)) return false;\n\tconst prototype: unknown = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/**\n * The value an object holds at keys, through own entries only, or `undefined` when an intermediate is absent or not an\n * object that `isObject` accepts.\n *\n * @remarks\n * Only own keys count: a key a plain object inherits, such as `constructor`, is no child.\n */\nfunction valueAt(\n\troot: PlainObject,\n\tkeys: readonly string[],\n\tisObject: (value: unknown) => value is PlainObject,\n): unknown {\n\tlet current: unknown = root;\n\tfor (const key of keys) {\n\t\tif (!isObject(current) || !Object.hasOwn(current, key)) return undefined;\n\t\tcurrent = current[key];\n\t}\n\treturn current;\n}\n\n/**\n * Set an own, enumerable entry.\n *\n * @remarks\n * A plain assignment under the key `__proto__` would replace the object's prototype instead of adding an entry.\n */\nfunction setOwn(target: PlainObject, key: string, value: unknown): void {\n\tObject.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/**\n * A copy of a node's schema output with each child slot replaced, without touching the output.\n *\n * @remarks\n * The output shares references with the authored document (a loose object returns the authored array), so it is\n * never written to. The root and each object on a path are shallow-copied once, and two paths with a shared prefix\n * share that copy.\n */\nfunction withChildData(\n\toutput: PlainObject,\n\twrites: readonly { keys: readonly string[]; value: unknown }[],\n): PlainObject {\n\tconst root: PlainObject = { ...output };\n\tconst copies = new Set<object>([root]);\n\tfor (const { keys, value } of writes) {\n\t\tlet current = root;\n\t\tfor (const key of keys.slice(0, -1)) {\n\t\t\tlet next = current[key] as PlainObject;\n\t\t\tif (!copies.has(next)) {\n\t\t\t\tnext = { ...next };\n\t\t\t\tcopies.add(next);\n\t\t\t\tsetOwn(current, key, next);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t}\n\t\tsetOwn(current, keys[keys.length - 1]!, value);\n\t}\n\treturn root;\n}\n\n/**\n * Check a whole document, node by node, without throwing for a bad document.\n *\n * @param registry - Where each node's `$type` finds its registration\n * @param root - The document's root node, as it arrived\n * @param options - Where the root sits in a larger document (`path`, which starts every issue's `path`) and which\n * `$type`s the root may have (`accepts`), see {@link ParseOptions}\n *\n * @remarks\n * Each node goes through {@link safeParseNode} with its full path, and `accepts` of the position it sits in (the\n * option for the root, the child path's own below), so the issues are those of one node, at the position the document\n * has them. A registration says where its children are with `childPaths`, each path read from the node as authored:\n *\n * | Value at the child path | Result |\n * | --- | --- |\n * | key absent, or an intermediate absent or not an object | no children; `data` keeps the schema output there |\n * | `undefined` | no children, as absent |\n * | `null` or another primitive | issue `registry/not-a-node` at the path |\n * | an object | one child |\n * | an array | each item is a child, at `[...path, index]`; an item that is not an object is an issue |\n * | an empty array | no children; `data` holds `[]` |\n * | anything but an array or a missing value, on a path that sets `list` | issue `registry/not-a-list` at the path |\n *\n * A node that contains itself is `registry/contains-itself`. A node whose own schema fails is not walked further, but\n * its siblings still are, so one call reports every issue of the document. When there are none, `tree.data` is the\n * parsed document, each node's schema output with the children's data at its child paths, in document order. When\n * there are issues, `tree` is a {@link PartialNode} of the nodes that parsed, present exactly when the root's own\n * schema passed: every node whose own schema passed and whose parent was kept, with `output` and `children`, and\n * without `data`. A failed node, a child the slot does not accept and the edge of a cycle are left out. Each child is\n * parsed once, from the authored value, and the authored document and the schema outputs are never written to.\n *\n * The parent schema owns, at a child path, whether the value may be missing, list or single, and list bounds; it does\n * not own the children, whose data replaces whatever the schema returned there. For each node it parses, `safeParseTree`\n * holds the schema to that contract and throws a {@link RegistryError} when it breaks it, since that is a bug of the\n * registration and no issue of the document: `'schema-changes-type'` when the output is not a plain object whose own\n * `$type` equals the node's, and `'schema-breaks-child-path'` when, where the document fills a child path, the output\n * lacks the keys down to it as plain objects or the same cardinality (an array of the same length for an array, an\n * object for an object), or when, where the document leaves a path empty, the output holds anything but nothing,\n * `undefined` or `[]`: a default that holds nodes. A transform of the parent at a filled slot (a reorder, say) is\n * discarded, not detected, so slots stay opaque to the parent's schema.\n *\n * The result is typed from the registrations: with a literal `accepts` the root narrows, and `tree.data` types each\n * child path by what it accepts. The walk itself reads registrations through one widened view of the lookup, and\n * the function returns the tree through one cast to that type: every node in it was built from a registration of the\n * lookup by its own `$type`, which TypeScript cannot follow at runtime.\n *\n * @throws {RegistryError} Code `'schema-changes-type'` or `'schema-breaks-child-path'`, as above\n * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does, and when\n * `accepts` is an empty list\n */\nexport function safeParseTree<\n\tTAll extends TreeRegistration,\n\tconst TOptions extends ParseOptions<TAll['$type']> = ParseOptions<TAll['$type']>,\n>(\n\tregistry: NodeLookup<TAll> & CheckLookup<TAll>,\n\troot: unknown,\n\toptions?: TOptions,\n): SafeParseTreeResult<TAll, RootOf<TAll, TOptions>> {\n\tconst lookup: NodeLookup<TreeRegistration> = registry;\n\tconst issues: RegistryIssue[] = [];\n\tconst outputs = new Map<WalkedNode, unknown>();\n\tconst label = lookup.kind === undefined ? '' : `${lookup.kind} `;\n\n\tconst kind = lookup.kind === undefined ? {} : { kind: lookup.kind };\n\n\tfunction brokenSlot(type: string, keys: readonly string[]): RegistryError {\n\t\treturn new RegistryError(\n\t\t\t'schema-breaks-child-path',\n\t\t\t`${label}'${type}' schema output does not keep the child path '${keys.join('.')}' as the document has it.`,\n\t\t\t{ ...kind, $type: type, childPath: keys },\n\t\t);\n\t}\n\n\tfunction walk(\n\t\tnode: unknown,\n\t\tnodePath: NonNullable<StandardSchemaIssue['path']>,\n\t\tancestors: readonly unknown[],\n\t\taccepts: readonly string[] | undefined,\n\t): WalkedNode | undefined {\n\t\tif (ancestors.includes(node)) {\n\t\t\tissues.push({ code: 'registry/contains-itself', message: 'A node cannot contain itself.', path: nodePath });\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parsed = safeParseNode(lookup, node, { path: nodePath, accepts });\n\t\tif (!parsed.success) {\n\t\t\tissues.push(...parsed.issues);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst { $type: type, registration } = parsed;\n\t\tconst output: unknown = parsed.data;\n\t\tif (!isPlainObject(output) || !Object.hasOwn(output, '$type') || output.$type !== type) {\n\t\t\tthrow new RegistryError(\n\t\t\t\t'schema-changes-type',\n\t\t\t\t`${label}'${type}' schema output must keep its $type '${type}'.`,\n\t\t\t\t{ ...kind, $type: type },\n\t\t\t);\n\t\t}\n\n\t\tconst authored = node as PlainObject;\n\t\tconst trail = [...ancestors, node];\n\t\tconst groups: WalkedNode['children'] = [];\n\t\tconst writes: { keys: readonly string[]; value: unknown }[] = [];\n\t\tlet complete = true;\n\t\tfor (const { keys, accepts: childAccepts, list } of registration.childPaths ?? []) {\n\t\t\tconst nodes: WalkedNode[] = [];\n\t\t\tgroups.push({ keys, nodes });\n\t\t\tconst slot = valueAt(authored, keys, isRecord);\n\t\t\tconst held = valueAt(output, keys, isPlainObject);\n\t\t\tconst childPath = [...nodePath, ...keys];\n\t\t\tif (slot === undefined) {\n\t\t\t\tif (held !== undefined && !(Array.isArray(held) && held.length === 0)) {\n\t\t\t\t\tthrow brokenSlot(type, keys);\n\t\t\t\t}\n\t\t\t} else if (list === true && !Array.isArray(slot)) {\n\t\t\t\tissues.push({ code: 'registry/not-a-list', message: 'Expected a list of nodes.', path: childPath });\n\t\t\t\tcomplete = false;\n\t\t\t} else if (Array.isArray(slot)) {\n\t\t\t\tif (!Array.isArray(held) || held.length !== slot.length) throw brokenSlot(type, keys);\n\t\t\t\tlet kept = 0;\n\t\t\t\tfor (let index = 0; index < slot.length; index += 1) {\n\t\t\t\t\tconst child = walk(slot[index], [...childPath, index], trail, childAccepts);\n\t\t\t\t\tif (child) {\n\t\t\t\t\t\tnodes.push(child);\n\t\t\t\t\t\tif (child.data !== undefined) kept += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (kept === slot.length) {\n\t\t\t\t\twrites.push({ keys, value: nodes.map((item) => item.data) });\n\t\t\t\t} else {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t}\n\t\t\t} else if (isRecord(slot)) {\n\t\t\t\tif (!isRecord(held)) throw brokenSlot(type, keys);\n\t\t\t\tconst child = walk(slot, childPath, trail, childAccepts);\n\t\t\t\tif (child) {\n\t\t\t\t\tnodes.push(child);\n\t\t\t\t\tif (child.data !== undefined) writes.push({ keys, value: child.data });\n\t\t\t\t\telse complete = false;\n\t\t\t\t} else {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'registry/not-a-node',\n\t\t\t\t\tmessage: 'Expected a node or a list of nodes.',\n\t\t\t\t\tpath: childPath,\n\t\t\t\t});\n\t\t\t\tcomplete = false;\n\t\t\t}\n\t\t}\n\t\tlet data: unknown;\n\t\tif (complete) data = writes.length === 0 ? output : withChildData(output, writes);\n\t\tconst kept: WalkedNode = { $type: type, registration, data, path: nodePath, children: groups };\n\t\tif (data !== output) outputs.set(kept, output);\n\t\treturn kept;\n\t}\n\n\tconst walked = walk(root, options?.path ?? [], [], options?.accepts);\n\tlet result: unknown;\n\tif (walked?.data !== undefined && issues.length === 0) result = { success: true, tree: walked };\n\telse if (walked) result = { success: false, issues, tree: toPartial(walked, outputs) };\n\telse result = { success: false, issues };\n\treturn result as SafeParseTreeResult<TAll, RootOf<TAll, TOptions>>;\n}\n"],
|
|
5
|
+
"mappings": "gFA4HA,SAASA,EAAUC,EAAkBC,EAA+D,CACnG,IAAMC,EAAaC,IAA0C,CAC5D,MAAOA,EA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AO,CAAE,EAChFwD,EAAS,CAAE,QAAS,GAAO,OAAA1B,CAAO,EAChC0B,CACR",
|
|
6
|
+
"names": ["toPartial", "root", "outputs", "partialOf", "node", "top", "pending", "next", "source", "target", "keys", "nodes", "kept", "child", "converted", "isRecord", "value", "isPlainObject", "prototype", "valueAt", "isObject", "current", "key", "setOwn", "withChildData", "output", "writes", "copies", "safeParseTree", "registry", "options", "lookup", "issues", "label", "kind", "brokenSlot", "type", "RegistryError", "walk", "nodePath", "ancestors", "accepts", "parsed", "safeParseNode", "registration", "authored", "trail", "groups", "complete", "childAccepts", "list", "slot", "held", "childPath", "index", "item", "data", "walked", "result"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as f}from"./chunk-P3DDHPDA.js";import{a as g}from"./chunk-XG4EZ5VP.js";var u=e=>`${e} must implement Standard Schema (~standard.validate).`;function O(e,t="Registration schema"){if(!f(e))throw new Error(u(t));return e}function b(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}function p(e){return typeof e=="string"&&e!==""}function k(e,t,n){if(e===void 0)return;let s=i=>new g("invalid-child-paths",`${t} ${i}`,n);if(!Array.isArray(e))throw s("childPaths must be a list of child paths.");let a=[];for(let[i,o]of e.entries()){let r=`childPaths[${i}]`;if(typeof o!="object"||o===null||Array.isArray(o))throw s(`${r} must be an object { keys, accepts?, list? }.`);let d=Object.keys(o).find(y=>y!=="keys"&&y!=="accepts"&&y!=="list");if(d!==void 0)throw s(`${r} has the property '${d}', which a child path does not have.`);let{keys:c,accepts:h,list:l}=o;if(!Array.isArray(c)||c.length===0||!c.every(p))throw s(`${r}.keys must be a non-empty list of non-empty strings.`);if(h!==void 0){if(!Array.isArray(h)||h.length===0||!h.every(p))throw s(`${r}.accepts must be a non-empty list of non-empty $types when present.`);let y=h.find((w,$)=>h.indexOf(w)!==$);if(y!==void 0)throw s(`${r}.accepts names '${y}' twice.`)}if(l!==void 0&&l!==!0)throw s(`${r}.list must be true when present.`);a.push(c)}for(let[i,o]of a.entries()){let r=o.join(".");if(a.findIndex(c=>b(c,o))!==i)throw new g("duplicate-child-path",`${t} declares the child path '${r}' twice.`,{...n,childPath:[...o]});let d=a.find(c=>c.length<o.length&&c.every((h,l)=>h===o[l]));if(d)throw new g("nested-child-path",`${t} child path '${r}' runs through the child path '${d.join(".")}'.`,{...n,childPath:[...o],outerChildPath:[...d]})}}function R(e,t){let n={kind:e,$type:t.$type};if(!f(t.schema))throw new g("invalid-schema",u(`${e} '${t.$type}' schema`),n);k(t.childPaths,`${e} '${t.$type}'`,n)}function m(e,t){return new g("duplicate-type",`${e} '${t}' is registered twice.`,{kind:e,$type:t})}function j(e,t,n={}){let s=new Map;for(let r of t){if(n.duplicates==="error"&&s.has(r.$type))throw m(e,r.$type);s.set(r.$type,r)}let a=new Map;for(let[r,d]of s)R(e,d),a.set(r,Object.freeze({...d}));let i=Object.freeze([...a.values()]),o=Object.freeze([...a.keys()]);return Object.freeze({kind:e,...n.hint===void 0?{}:{hint:n.hint},size:a.size,get:r=>a.get(r),has:r=>a.has(r),all:()=>i,keys:()=>o})}function x(e,t={}){let n=new Map,s,a;return Object.freeze({kind:e,...t.hint===void 0?{}:{hint:t.hint},get size(){return n.size},get:i=>n.get(i),has:i=>n.has(i),all:()=>s??=Object.freeze([...n.values()]),keys:()=>a??=Object.freeze([...n.keys()]),register:i=>{if(t.duplicates==="error"&&n.has(i.$type))throw m(e,i.$type);R(e,i),n.set(i.$type,Object.freeze({...i})),s=a=void 0},clear:()=>{n.clear(),s=a=void 0}})}export{O as a,j as b,x as c};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/create-registry.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { RegistryError, type RegistryErrorDetails } from './registry-error.js';\nimport { isStandardSchema } from './standard-schema.js';\nimport type { CheckChildPaths } from './tree-types.js';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * The read side of every registry: what {@link createRegistry} returns, and what a {@link MutableRegistry} also has.\n * It has no `register` or `clear`; to change the contents of one built by {@link createRegistry}, build another\n * registry from a new list.\n */\nexport interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {\n\t/** Label used in errors, for example `Element`. */\n\treadonly kind: string;\n\t/**\n\t * A sentence that follows the message of a `$type` the registry does not answer, such as where to register it.\n\t * Set by the `hint` option; absent without it.\n\t *\n\t * @remarks\n\t * It is the `hint` of {@link NodeLookup}, so a registry is a lookup with its hint, and `safeParseNode`,\n\t * `safeParseTree` and every function that takes a lookup report it.\n\t */\n\treadonly hint?: string;\n\t/** Number of distinct `$type` keys. */\n\treadonly size: number;\n\tget(key: string): TRegistration | undefined;\n\thas(key: string): boolean;\n\t/** Registrations in first-registration order. The array is frozen. */\n\tall(): readonly TRegistration[];\n\t/** `$type` keys in first-registration order. The array is frozen. */\n\tkeys(): readonly string[];\n}\n\nconst standardSchemaMessage = (context: string) => `${context} must implement Standard Schema (~standard.validate).`;\n\n/**\n * Require a registration schema to implement Standard Schema.\n *\n * @param schema - Value to check\n * @param context - Subject of the error message, for example `Element 'text' schema`\n * @throws {Error} When `schema` has no `~standard.validate` function\n *\n * @remarks\n * A plain `Error`, not a {@link RegistryError}: the caller is not building a registry, so there is no `kind` or\n * `$type` to report, only the free-form `context`. {@link createRegistry} runs the same check and throws a\n * `RegistryError` with code `'invalid-schema'`.\n */\nexport function assertStandardSchema(schema: unknown, context = 'Registration schema'): StandardSchemaV1 {\n\tif (!isStandardSchema(schema)) throw new Error(standardSchemaMessage(context));\n\treturn schema;\n}\n\nfunction sameKeys(left: readonly string[], right: readonly string[]): boolean {\n\treturn left.length === right.length && left.every((key, position) => key === right[position]);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n\treturn typeof value === 'string' && value !== '';\n}\n\n/**\n * Check the `childPaths` of a registration.\n *\n * @remarks\n * Paths are compared key by key, so `['a.b']` and `['a', 'b']` are two different paths. Two equal paths are one path\n * declared twice. A path that runs through another one would reach inside a child node, whose own registration says\n * where its children are, so the walk would visit the same node from two parents. The shape of an entry is checked\n * here as well as by the types, because a registration may arrive as parsed data.\n */\nfunction assertChildPaths(childPaths: unknown, context: string, details: RegistryErrorDetails): void {\n\tif (childPaths === undefined) return;\n\tconst invalid = (message: string) => new RegistryError('invalid-child-paths', `${context} ${message}`, details);\n\tif (!Array.isArray(childPaths)) throw invalid('childPaths must be a list of child paths.');\n\tconst paths: string[][] = [];\n\tfor (const [index, entry] of (childPaths as unknown[]).entries()) {\n\t\tconst name = `childPaths[${index}]`;\n\t\tif (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {\n\t\t\tthrow invalid(`${name} must be an object { keys, accepts?, list? }.`);\n\t\t}\n\t\tconst extra = Object.keys(entry).find(\n\t\t\t(property) => property !== 'keys' && property !== 'accepts' && property !== 'list',\n\t\t);\n\t\tif (extra !== undefined)\n\t\t\tthrow invalid(`${name} has the property '${extra}', which a child path does not have.`);\n\t\tconst { keys, accepts, list } = entry as { keys?: unknown; accepts?: unknown; list?: unknown };\n\t\tif (!Array.isArray(keys) || keys.length === 0 || !keys.every(isNonEmptyString)) {\n\t\t\tthrow invalid(`${name}.keys must be a non-empty list of non-empty strings.`);\n\t\t}\n\t\tif (accepts !== undefined) {\n\t\t\tif (!Array.isArray(accepts) || accepts.length === 0 || !accepts.every(isNonEmptyString)) {\n\t\t\t\tthrow invalid(`${name}.accepts must be a non-empty list of non-empty $types when present.`);\n\t\t\t}\n\t\t\tconst repeated = (accepts as string[]).find((type, position) => accepts.indexOf(type) !== position);\n\t\t\tif (repeated !== undefined) throw invalid(`${name}.accepts names '${repeated}' twice.`);\n\t\t}\n\t\tif (list !== undefined && list !== true) throw invalid(`${name}.list must be true when present.`);\n\t\tpaths.push(keys as string[]);\n\t}\n\tfor (const [index, keys] of paths.entries()) {\n\t\tconst name = keys.join('.');\n\t\tif (paths.findIndex((other) => sameKeys(other, keys)) !== index) {\n\t\t\tthrow new RegistryError('duplicate-child-path', `${context} declares the child path '${name}' twice.`, {\n\t\t\t\t...details,\n\t\t\t\tchildPath: [...keys],\n\t\t\t});\n\t\t}\n\t\tconst outer = paths.find(\n\t\t\t(other) => other.length < keys.length && other.every((key, position) => key === keys[position]),\n\t\t);\n\t\tif (outer) {\n\t\t\tthrow new RegistryError(\n\t\t\t\t'nested-child-path',\n\t\t\t\t`${context} child path '${name}' runs through the child path '${outer.join('.')}'.`,\n\t\t\t\t{ ...details, childPath: [...keys], outerChildPath: [...outer] },\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * Check one registration the way both registry factories do, so their errors cannot drift.\n *\n * @throws {RegistryError} Code `'invalid-schema'`, or one of the child path codes of {@link createRegistry}\n */\nfunction assertRegistration(kind: string, registration: BaseRegistration): void {\n\tconst details = { kind, $type: registration.$type };\n\tif (!isStandardSchema(registration.schema)) {\n\t\tthrow new RegistryError(\n\t\t\t'invalid-schema',\n\t\t\tstandardSchemaMessage(`${kind} '${registration.$type}' schema`),\n\t\t\tdetails,\n\t\t);\n\t}\n\tassertChildPaths(registration.childPaths, `${kind} '${registration.$type}'`, details);\n}\n\nfunction duplicateTypeError(kind: string, type: string): RegistryError {\n\treturn new RegistryError('duplicate-type', `${kind} '${type}' is registered twice.`, { kind, $type: type });\n}\n\n/** Options of {@link createRegistry} and {@link createMutableRegistry}. */\nexport interface CreateRegistryOptions {\n\t/** The `hint` of the registry, see {@link ReadOnlyRegistry.hint}. */\n\treadonly hint?: string;\n\t/**\n\t * What a second registration of one `$type` does: replace the first (`'override'`, the default) or fail the build\n\t * (`'error'`).\n\t *\n\t * @remarks\n\t * `'override'` is how `[...defaults, custom]` replaces a built-in. Use `'error'` for a catalog where a repeated\n\t * key is always a mistake, such as component keys.\n\t */\n\treadonly duplicates?: 'override' | 'error';\n}\n\n/**\n * Build a frozen, read-only registry from a list of registrations.\n *\n * @param kind - Label for errors, for example `Element`\n * @param registrations - Registrations to store, keyed by `$type`\n * @param options - How to treat a repeated `$type`, see {@link CreateRegistryOptions}\n * @throws {RegistryError} Code `'duplicate-type'`, `Widget 'card' is registered twice.`, when `duplicates` is `'error'`\n * and a `$type` repeats, before any schema is checked\n * @throws {RegistryError} Code `'invalid-schema'`, naming the `$type`, when a winning registration's schema is not a\n * Standard Schema\n * @throws {RegistryError} Naming the `$type`, with code `'invalid-child-paths'` when a winning registration's\n * `childPaths` is not a list of `{ keys, accepts?, list? }` objects (a property other than those three, empty or\n * non-string keys, an empty or repeating `accepts`, a `list` that is not `true`), `'duplicate-child-path'` when it repeats a path (`childPath`), or\n * `'nested-child-path'` when a path (`childPath`) runs through another (`outerChildPath`). Paths are compared key by\n * key.\n *\n * @remarks\n * The types check that the schema output declares every key of every child path (`childPathNotInSchema`), where the\n * output type can be read, and that a child path written inline has no property other than `keys`, `accepts` and `list`\n * (`childPathUnknownProperty`).\n *\n * By default a later registration with the same `$type` replaces the earlier one without a\n * warning, so `[...defaults, custom]` is the way to override. A replaced key\n * keeps its first position. Only the winning registration of each key is\n * checked. The registry stores a frozen shallow copy of each winner, taken at\n * build, and leaves the objects you passed untouched. Later assignments to or\n * spies on those objects do not reach the registry, so patch before building or\n * build a new registry. The copy shares nested values such as `schema` with the\n * original.\n *\n * Use {@link createMutableRegistry} instead when registrations arrive at runtime.\n */\nexport function createRegistry<const TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly TRegistration[] & CheckChildPaths<TRegistration>,\n\toptions: CreateRegistryOptions = {},\n): ReadOnlyRegistry<TRegistration> {\n\tconst winners = new Map<string, TRegistration>();\n\tfor (const registration of registrations) {\n\t\tif (options.duplicates === 'error' && winners.has(registration.$type)) {\n\t\t\tthrow duplicateTypeError(kind, registration.$type);\n\t\t}\n\t\twinners.set(registration.$type, registration);\n\t}\n\tconst entries = new Map<string, Readonly<TRegistration>>();\n\tfor (const [key, registration] of winners) {\n\t\tassertRegistration(kind, registration);\n\t\tentries.set(key, Object.freeze({ ...registration }));\n\t}\n\tconst all = Object.freeze([...entries.values()]);\n\tconst keys = Object.freeze([...entries.keys()]);\n\n\treturn Object.freeze({\n\t\tkind,\n\t\t...(options.hint === undefined ? {} : { hint: options.hint }),\n\t\tsize: entries.size,\n\t\tget: (key: string) => entries.get(key),\n\t\thas: (key: string) => entries.has(key),\n\t\tall: () => all,\n\t\tkeys: () => keys,\n\t});\n}\n\n/**\n * A registry that takes registrations after it exists: the read side of a {@link createRegistry} result, plus\n * `register` and `clear`.\n */\nexport interface MutableRegistry<\n\tTRegistration extends BaseRegistration = BaseRegistration,\n> extends ReadOnlyRegistry<TRegistration> {\n\t/**\n\t * Add a registration, keyed by its `$type`.\n\t *\n\t * @throws {RegistryError} The codes {@link createRegistry} gives for a registration: `'invalid-schema'`,\n\t * `'invalid-child-paths'`, `'duplicate-child-path'`, `'nested-child-path'`, and `'duplicate-type'` when the registry\n\t * was built with `{ duplicates: 'error' }`\n\t *\n\t * @remarks\n\t * The registry is unchanged when `register` throws. A repeated `$type` replaces the earlier registration and keeps\n\t * its first position. The registry stores a frozen shallow copy. `accepts` may name a `$type` that is not registered\n\t * yet: `safeParseTree` reports a node it cannot find as an issue.\n\t */\n\tregister<const T extends TRegistration>(registration: T & CheckChildPaths<T>): void;\n\t/** Remove every registration. */\n\tclear(): void;\n}\n\n/**\n * Build an empty registry that takes registrations at runtime, such as a plugin system's.\n *\n * @param kind - Label for errors, for example `Plugin`\n * @param options - How to treat a repeated `$type`, see {@link CreateRegistryOptions}\n *\n * @remarks\n * Its read side matches a {@link createRegistry} result, so it goes wherever a registry is read. `all()` and `keys()`\n * return the same frozen array until the next `register` or `clear`. `register` checks each registration as\n * {@link createRegistry} does. The registry logs nothing: call `has` before `register` to warn about an override.\n */\nexport function createMutableRegistry<TRegistration extends BaseRegistration = BaseRegistration>(\n\tkind: string,\n\toptions: CreateRegistryOptions = {},\n): MutableRegistry<TRegistration> {\n\tconst entries = new Map<string, Readonly<TRegistration>>();\n\tlet all: readonly TRegistration[] | undefined;\n\tlet keys: readonly string[] | undefined;\n\n\treturn Object.freeze({\n\t\tkind,\n\t\t...(options.hint === undefined ? {} : { hint: options.hint }),\n\t\tget size() {\n\t\t\treturn entries.size;\n\t\t},\n\t\tget: (key: string) => entries.get(key),\n\t\thas: (key: string) => entries.has(key),\n\t\tall: () => (all ??= Object.freeze([...entries.values()])),\n\t\tkeys: () => (keys ??= Object.freeze([...entries.keys()])),\n\t\tregister: (registration: TRegistration) => {\n\t\t\tif (options.duplicates === 'error' && entries.has(registration.$type)) {\n\t\t\t\tthrow duplicateTypeError(kind, registration.$type);\n\t\t\t}\n\t\t\tassertRegistration(kind, registration);\n\t\t\tentries.set(registration.$type, Object.freeze({ ...registration }));\n\t\t\tall = keys = undefined;\n\t\t},\n\t\tclear: () => {\n\t\t\tentries.clear();\n\t\t\tall = keys = undefined;\n\t\t},\n\t});\n}\n"],
|
|
5
|
+
"mappings": "gFAiCA,IAAMA,EAAyBC,GAAoB,GAAGA,CAAO,wDActD,SAASC,EAAqBC,EAAiBF,EAAU,sBAAyC,CACxG,GAAI,CAACG,EAAiBD,CAAM,EAAG,MAAM,IAAI,MAAMH,EAAsBC,CAAO,CAAC,EAC7E,OAAOE,CACR,CAEA,SAASE,EAASC,EAAyBC,EAAmC,CAC7E,OAAOD,EAAK,SAAWC,EAAM,QAAUD,EAAK,MAAM,CAACE,EAAKC,IAAaD,IAAQD,EAAME,CAAQ,CAAC,CAC7F,CAEA,SAASC,EAAiBC,EAAiC,CAC1D,OAAO,OAAOA,GAAU,UAAYA,IAAU,EAC/C,CAWA,SAASC,EAAiBC,EAAqBZ,EAAiBa,EAAqC,CACpG,GAAID,IAAe,OAAW,OAC9B,IAAME,EAAWC,GAAoB,IAAIC,EAAc,sBAAuB,GAAGhB,CAAO,IAAIe,CAAO,GAAIF,CAAO,EAC9G,GAAI,CAAC,MAAM,QAAQD,CAAU,EAAG,MAAME,EAAQ,2CAA2C,EACzF,IAAMG,EAAoB,CAAC,EAC3B,OAAW,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Ze,EAAQ,MAAM,EACdC,EAAMhB,EAAO,MACd,CACD,CAAC,CACF",
|
|
6
|
+
"names": ["standardSchemaMessage", "context", "assertStandardSchema", "schema", "isStandardSchema", "sameKeys", "left", "right", "key", "position", "isNonEmptyString", "value", "assertChildPaths", "childPaths", "details", "invalid", "message", "RegistryError", "paths", "index", "entry", "name", "extra", "property", "keys", "accepts", "list", "repeated", "type", "other", "outer", "assertRegistration", "kind", "registration", "duplicateTypeError", "createRegistry", "registrations", "options", "winners", "entries", "all", "createMutableRegistry"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function u(e,o){return typeof e=="object"&&e!==null?Reflect.get(e,o):void 0}function a(e,o){let r=o,n="";for(let s of e??[]){let t=typeof s=="object"?s.key:s;if(r=u(r,t),typeof t=="number"){let f=u(r,"id");n+=typeof f=="string"&&f?`[${t}] (${f})`:`[${t}]`}else n+=n?`.${String(t)}`:String(t)}return n}export{a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/format-issue-path.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaIssue } from './standard-schema.js';\n\nfunction childOf(node: unknown, key: PropertyKey): unknown {\n\treturn typeof node === 'object' && node !== null ? Reflect.get(node, key) : undefined;\n}\n\n/**\n * A Standard Schema issue path as it reads in an error message: object keys joined by dots, array\n * indexes in brackets, for example `steps[0].elements[2].grid.width`. A missing or empty path is the\n * empty string.\n *\n * @param path The `path` of a Standard Schema issue. A segment is a key or an object `{ key }`.\n * @param source The document the path points into. With it, an array item that has a string `id` is\n * followed by the id in parentheses, `steps[0] (main).elements[2] (email).grid.width`, so a log of a\n * document with many nodes names the one it means.\n */\nexport function formatIssuePath(path: StandardSchemaIssue['path'], source?: unknown): string {\n\tlet node = source;\n\tlet text = '';\n\tfor (const segment of path ?? []) {\n\t\tconst key = typeof segment === 'object' ? segment.key : segment;\n\t\tnode = childOf(node, key);\n\t\tif (typeof key === 'number') {\n\t\t\tconst id = childOf(node, 'id');\n\t\t\ttext += typeof id === 'string' && id ? `[${key}] (${id})` : `[${key}]`;\n\t\t} else {\n\t\t\ttext += text ? `.${String(key)}` : String(key);\n\t\t}\n\t}\n\treturn text;\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAASA,EAAQC,EAAeC,EAA2B,CAC1D,OAAO,OAAOD,GAAS,UAAYA,IAAS,KAAO,QAAQ,IAAIA,EAAMC,CAAG,EAAI,MAC7E,CAYO,SAASC,EAAgBC,EAAmCC,EAA0B,CAC5F,IAAIJ,EAAOI,EACPC,EAAO,GACX,QAAWC,KAAWH,GAAQ,CAAC,EAAG,CACjC,IAAMF,EAAM,OAAOK,GAAY,SAAWA,EAAQ,IAAMA,EAExD,GADAN,EAAOD,EAAQC,EAAMC,CAAG,EACpB,OAAOA,GAAQ,SAAU,CAC5B,IAAMM,EAAKR,EAAQC,EAAM,IAAI,EAC7BK,GAAQ,OAAOE,GAAO,UAAYA,EAAK,IAAIN,CAAG,MAAMM,CAAE,IAAM,IAAIN,CAAG,GACpE,MACCI,GAAQA,EAAO,IAAI,OAAOJ,CAAG,CAAC,GAAK,OAAOA,CAAG,CAE/C,CACA,OAAOI,CACR",
|
|
6
|
+
"names": ["childOf", "node", "key", "formatIssuePath", "path", "source", "text", "segment", "id"]
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var r=class extends Error{code;kind;$type;key;childPath;outerChildPath;constructor(i,n,e){super(n),this.name="RegistryError",this.code=i,e.kind!==void 0&&(this.kind=e.kind),this.$type=e.$type,e.key!==void 0&&(this.key=e.key),e.childPath!==void 0&&(this.childPath=e.childPath),e.outerChildPath!==void 0&&(this.outerChildPath=e.outerChildPath)}};export{r as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/registry-error.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Why building or binding a registry, or parsing a tree, failed. Each code names one mistake in the registrations or\n * bindings.\n *\n * @remarks\n * The codes are the contract: depend on a code, not on the wording of `message`, which may change. A code is only\n * added, never renamed or reused for another mistake.\n *\n * - `'invalid-schema'`: a registration's `schema` has no `~standard.validate` function.\n * - `'invalid-child-paths'`: a registration's `childPaths` is not a list, or holds an entry that is not an object\n * `{ keys, accepts?, list? }` with a non-empty list of non-empty string `keys`, no other property, an `accepts` that\n * is absent or a non-empty list of non-empty strings without repeats, and a `list` that is absent or `true`.\n * `replaceChildSlot` throws it too for a path with no keys. A domain package throws it too for a `childPaths` its own\n * rules refuse.\n * - `'duplicate-child-path'`: a registration declares the same child path (`childPath`) twice, key by key.\n * - `'nested-child-path'`: a child path (`childPath`) runs through another child path (`outerChildPath`) of the same\n * registration.\n * - `'duplicate-type'`: a `$type` is registered twice while `duplicates` is `'error'`.\n * - `'unknown-binding'`: {@link bindRegistry} got a binding whose key (`$type`) is no contract's `$type`.\n * - `'missing-binding'`: {@link bindRegistry} got no binding for a contract.\n * - `'binding-overrides-contract'`: a binding sets a key (`key`) its contract already defines.\n * - `'schema-changes-type'`: {@link safeParseTree} parsed a node whose schema returned an output with another `$type`\n * than the node's, or none.\n * - `'schema-breaks-child-path'`: {@link safeParseTree} parsed a node whose schema returned an output that does not\n * keep a child path (`childPath`) the document fills, or fills one the document leaves empty.\n * - `'unreachable-child-path'`: {@link exportTreeSchema} found no slot for a child path (`childPath`) in the JSON\n * Schema of a registration, because the schema does not declare its keys, or it sits behind `allOf`, a `$ref` or a\n * union, or inside a schema with an `$id` of its own, or because the slot is nullable.\n * - `'unknown-accepted-type'`: {@link exportTreeSchema} was given a lookup that lacks a `$type` a child path\n * (`childPath`) accepts (`key`).\n * - `'definition-name-clash'`: {@link exportTreeSchema}, or the JSON Schema embedder it writes through, found that a\n * definition a schema brought along (`key`, brought by `$type`) takes the name of a `$type` or of another definition.\n * - `'invalid-declaration'`: a domain package refuses a declaration of a registration other than its child paths.\n */\nexport type RegistryErrorCode =\n\t| 'invalid-schema'\n\t| 'invalid-child-paths'\n\t| 'duplicate-child-path'\n\t| 'nested-child-path'\n\t| 'duplicate-type'\n\t| 'unknown-binding'\n\t| 'missing-binding'\n\t| 'binding-overrides-contract'\n\t| 'schema-changes-type'\n\t| 'schema-breaks-child-path'\n\t| 'unreachable-child-path'\n\t| 'unknown-accepted-type'\n\t| 'definition-name-clash'\n\t| 'invalid-declaration';\n\n/** Where a {@link RegistryError} happened, and what its code needs to be described without the message. */\nexport interface RegistryErrorDetails {\n\t/**\n\t * The registry's label, for example `Widget`.\n\t *\n\t * @remarks\n\t * Absent when a parse failed through a lookup that is not a registry, a function say, which has no label.\n\t */\n\treadonly kind?: string;\n\t/** The `$type` of the registration at fault, or the key of a binding that names no registration. */\n\treadonly $type: string;\n\t/**\n\t * The key a binding sets that its contract defines, for `'binding-overrides-contract'`, the `$type` a child path\n\t * accepts that the lookup lacks, for `'unknown-accepted-type'`, and the name of the definition that clashes, for\n\t * `'definition-name-clash'`.\n\t */\n\treadonly key?: string;\n\t/**\n\t * The keys of the child path at fault, for `'duplicate-child-path'`, `'nested-child-path'` and\n\t * `'schema-breaks-child-path'`, `'unreachable-child-path'` and `'unknown-accepted-type'`.\n\t */\n\treadonly childPath?: readonly string[];\n\t/** The keys of the child path that `childPath` runs through, for `'nested-child-path'`. */\n\treadonly outerChildPath?: readonly string[];\n}\n\n/**\n * Thrown while a registry is built ({@link createRegistry}) or bound ({@link bindRegistry}) from registrations that\n * break a rule, and while a tree is parsed ({@link safeParseTree}) when a schema contradicts its registration.\n *\n * @remarks\n * Branch on `code`, not on `message`: the message is written for a person and may be reworded, while the codes of\n * {@link RegistryErrorCode} stay. `code` with the details is enough to write the message again, in another language\n * say, without parsing it. A parse throws a `RegistryError` only when a schema contradicts its registration, which is\n * a bug of the registration and no issue of the document. Other errors raised while parsing a node or a document (an\n * asynchronous Standard Schema, say), and by {@link assertStandardSchema} on its own, are not `RegistryError`s.\n */\nexport class RegistryError extends Error implements RegistryErrorDetails {\n\treadonly code: RegistryErrorCode;\n\treadonly kind?: string;\n\treadonly $type: string;\n\treadonly key?: string;\n\treadonly childPath?: readonly string[];\n\treadonly outerChildPath?: readonly string[];\n\n\tconstructor(code: RegistryErrorCode, message: string, details: RegistryErrorDetails) {\n\t\tsuper(message);\n\t\tthis.name = 'RegistryError';\n\t\tthis.code = code;\n\t\tif (details.kind !== undefined) this.kind = details.kind;\n\t\tthis.$type = details.$type;\n\t\tif (details.key !== undefined) this.key = details.key;\n\t\tif (details.childPath !== undefined) this.childPath = details.childPath;\n\t\tif (details.outerChildPath !== undefined) this.outerChildPath = details.outerChildPath;\n\t}\n}\n"],
|
|
5
|
+
"mappings": "AAuFO,IAAMA,EAAN,cAA4B,KAAsC,CAC/D,KACA,KACA,MACA,IACA,UACA,eAET,YAAYC,EAAyBC,EAAiBC,EAA+B,CACpF,MAAMD,CAAO,EACb,KAAK,KAAO,gBACZ,KAAK,KAAOD,EACRE,EAAQ,OAAS,SAAW,KAAK,KAAOA,EAAQ,MACpD,KAAK,MAAQA,EAAQ,MACjBA,EAAQ,MAAQ,SAAW,KAAK,IAAMA,EAAQ,KAC9CA,EAAQ,YAAc,SAAW,KAAK,UAAYA,EAAQ,WAC1DA,EAAQ,iBAAmB,SAAW,KAAK,eAAiBA,EAAQ,eACzE,CACD",
|
|
6
|
+
"names": ["RegistryError", "code", "message", "details"]
|
|
7
|
+
}
|
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import type { CheckChildPaths } from './tree-types.js';
|
|
2
3
|
import type { BaseRegistration } from './types.js';
|
|
3
4
|
/**
|
|
4
|
-
*
|
|
5
|
-
* `clear`; to change
|
|
5
|
+
* The read side of every registry: what {@link createRegistry} returns, and what a {@link MutableRegistry} also has.
|
|
6
|
+
* It has no `register` or `clear`; to change the contents of one built by {@link createRegistry}, build another
|
|
7
|
+
* registry from a new list.
|
|
6
8
|
*/
|
|
7
9
|
export interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {
|
|
8
|
-
/** Label used in
|
|
10
|
+
/** Label used in errors, for example `Element`. */
|
|
9
11
|
readonly kind: string;
|
|
12
|
+
/**
|
|
13
|
+
* A sentence that follows the message of a `$type` the registry does not answer, such as where to register it.
|
|
14
|
+
* Set by the `hint` option; absent without it.
|
|
15
|
+
*
|
|
16
|
+
* @remarks
|
|
17
|
+
* It is the `hint` of {@link NodeLookup}, so a registry is a lookup with its hint, and `safeParseNode`,
|
|
18
|
+
* `safeParseTree` and every function that takes a lookup report it.
|
|
19
|
+
*/
|
|
20
|
+
readonly hint?: string;
|
|
10
21
|
/** Number of distinct `$type` keys. */
|
|
11
22
|
readonly size: number;
|
|
12
23
|
get(key: string): TRegistration | undefined;
|
|
@@ -22,17 +33,49 @@ export interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseR
|
|
|
22
33
|
* @param schema - Value to check
|
|
23
34
|
* @param context - Subject of the error message, for example `Element 'text' schema`
|
|
24
35
|
* @throws {Error} When `schema` has no `~standard.validate` function
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* A plain `Error`, not a {@link RegistryError}: the caller is not building a registry, so there is no `kind` or
|
|
39
|
+
* `$type` to report, only the free-form `context`. {@link createRegistry} runs the same check and throws a
|
|
40
|
+
* `RegistryError` with code `'invalid-schema'`.
|
|
25
41
|
*/
|
|
26
42
|
export declare function assertStandardSchema(schema: unknown, context?: string): StandardSchemaV1;
|
|
43
|
+
/** Options of {@link createRegistry} and {@link createMutableRegistry}. */
|
|
44
|
+
export interface CreateRegistryOptions {
|
|
45
|
+
/** The `hint` of the registry, see {@link ReadOnlyRegistry.hint}. */
|
|
46
|
+
readonly hint?: string;
|
|
47
|
+
/**
|
|
48
|
+
* What a second registration of one `$type` does: replace the first (`'override'`, the default) or fail the build
|
|
49
|
+
* (`'error'`).
|
|
50
|
+
*
|
|
51
|
+
* @remarks
|
|
52
|
+
* `'override'` is how `[...defaults, custom]` replaces a built-in. Use `'error'` for a catalog where a repeated
|
|
53
|
+
* key is always a mistake, such as component keys.
|
|
54
|
+
*/
|
|
55
|
+
readonly duplicates?: 'override' | 'error';
|
|
56
|
+
}
|
|
27
57
|
/**
|
|
28
58
|
* Build a frozen, read-only registry from a list of registrations.
|
|
29
59
|
*
|
|
30
60
|
* @param kind - Label for errors, for example `Element`
|
|
31
61
|
* @param registrations - Registrations to store, keyed by `$type`
|
|
32
|
-
* @
|
|
62
|
+
* @param options - How to treat a repeated `$type`, see {@link CreateRegistryOptions}
|
|
63
|
+
* @throws {RegistryError} Code `'duplicate-type'`, `Widget 'card' is registered twice.`, when `duplicates` is `'error'`
|
|
64
|
+
* and a `$type` repeats, before any schema is checked
|
|
65
|
+
* @throws {RegistryError} Code `'invalid-schema'`, naming the `$type`, when a winning registration's schema is not a
|
|
66
|
+
* Standard Schema
|
|
67
|
+
* @throws {RegistryError} Naming the `$type`, with code `'invalid-child-paths'` when a winning registration's
|
|
68
|
+
* `childPaths` is not a list of `{ keys, accepts?, list? }` objects (a property other than those three, empty or
|
|
69
|
+
* non-string keys, an empty or repeating `accepts`, a `list` that is not `true`), `'duplicate-child-path'` when it repeats a path (`childPath`), or
|
|
70
|
+
* `'nested-child-path'` when a path (`childPath`) runs through another (`outerChildPath`). Paths are compared key by
|
|
71
|
+
* key.
|
|
33
72
|
*
|
|
34
73
|
* @remarks
|
|
35
|
-
*
|
|
74
|
+
* The types check that the schema output declares every key of every child path (`childPathNotInSchema`), where the
|
|
75
|
+
* output type can be read, and that a child path written inline has no property other than `keys`, `accepts` and `list`
|
|
76
|
+
* (`childPathUnknownProperty`).
|
|
77
|
+
*
|
|
78
|
+
* By default a later registration with the same `$type` replaces the earlier one without a
|
|
36
79
|
* warning, so `[...defaults, custom]` is the way to override. A replaced key
|
|
37
80
|
* keeps its first position. Only the winning registration of each key is
|
|
38
81
|
* checked. The registry stores a frozen shallow copy of each winner, taken at
|
|
@@ -41,6 +84,39 @@ export declare function assertStandardSchema(schema: unknown, context?: string):
|
|
|
41
84
|
* build a new registry. The copy shares nested values such as `schema` with the
|
|
42
85
|
* original.
|
|
43
86
|
*
|
|
44
|
-
* Use {@link
|
|
87
|
+
* Use {@link createMutableRegistry} instead when registrations arrive at runtime.
|
|
88
|
+
*/
|
|
89
|
+
export declare function createRegistry<const TRegistration extends BaseRegistration>(kind: string, registrations: readonly TRegistration[] & CheckChildPaths<TRegistration>, options?: CreateRegistryOptions): ReadOnlyRegistry<TRegistration>;
|
|
90
|
+
/**
|
|
91
|
+
* A registry that takes registrations after it exists: the read side of a {@link createRegistry} result, plus
|
|
92
|
+
* `register` and `clear`.
|
|
93
|
+
*/
|
|
94
|
+
export interface MutableRegistry<TRegistration extends BaseRegistration = BaseRegistration> extends ReadOnlyRegistry<TRegistration> {
|
|
95
|
+
/**
|
|
96
|
+
* Add a registration, keyed by its `$type`.
|
|
97
|
+
*
|
|
98
|
+
* @throws {RegistryError} The codes {@link createRegistry} gives for a registration: `'invalid-schema'`,
|
|
99
|
+
* `'invalid-child-paths'`, `'duplicate-child-path'`, `'nested-child-path'`, and `'duplicate-type'` when the registry
|
|
100
|
+
* was built with `{ duplicates: 'error' }`
|
|
101
|
+
*
|
|
102
|
+
* @remarks
|
|
103
|
+
* The registry is unchanged when `register` throws. A repeated `$type` replaces the earlier registration and keeps
|
|
104
|
+
* its first position. The registry stores a frozen shallow copy. `accepts` may name a `$type` that is not registered
|
|
105
|
+
* yet: `safeParseTree` reports a node it cannot find as an issue.
|
|
106
|
+
*/
|
|
107
|
+
register<const T extends TRegistration>(registration: T & CheckChildPaths<T>): void;
|
|
108
|
+
/** Remove every registration. */
|
|
109
|
+
clear(): void;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Build an empty registry that takes registrations at runtime, such as a plugin system's.
|
|
113
|
+
*
|
|
114
|
+
* @param kind - Label for errors, for example `Plugin`
|
|
115
|
+
* @param options - How to treat a repeated `$type`, see {@link CreateRegistryOptions}
|
|
116
|
+
*
|
|
117
|
+
* @remarks
|
|
118
|
+
* Its read side matches a {@link createRegistry} result, so it goes wherever a registry is read. `all()` and `keys()`
|
|
119
|
+
* return the same frozen array until the next `register` or `clear`. `register` checks each registration as
|
|
120
|
+
* {@link createRegistry} does. The registry logs nothing: call `has` before `register` to warn about an override.
|
|
45
121
|
*/
|
|
46
|
-
export declare function
|
|
122
|
+
export declare function createMutableRegistry<TRegistration extends BaseRegistration = BaseRegistration>(kind: string, options?: CreateRegistryOptions): MutableRegistry<TRegistration>;
|
package/dist/create-registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{a,b,c}from"./chunk-RVS7JY2Y.js";import"./chunk-P3DDHPDA.js";import"./chunk-XG4EZ5VP.js";export{a as assertStandardSchema,c as createMutableRegistry,b as createRegistry};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": [],
|
|
4
|
+
"sourcesContent": [],
|
|
5
|
+
"mappings": "",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import { type JSONSchemaObject, type JSONSchemaTarget } from './json-schema/standard.js';
|
|
3
|
+
import type { TreeRegistration } from './tree-types.js';
|
|
4
|
+
/**
|
|
5
|
+
* What {@link exportTreeSchema} needs of a registry: the registrations it lists.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Both registry kinds ({@link createRegistry}, {@link createMutableRegistry}) provide it. A vocabulary spread over several
|
|
9
|
+
* registries is passed as a list of them.
|
|
10
|
+
*/
|
|
11
|
+
export interface ExportLookup {
|
|
12
|
+
all(): readonly TreeRegistration[];
|
|
13
|
+
}
|
|
14
|
+
/** The two dialects {@link exportTreeSchema} knows the `$schema` and the definitions keyword of. */
|
|
15
|
+
type TreeSchemaTarget = Extract<JSONSchemaTarget, 'draft-2020-12' | 'draft-07'>;
|
|
16
|
+
/** What a `resolve` function is told about the export it takes part in. */
|
|
17
|
+
export interface ExportSchemaContext {
|
|
18
|
+
/** `'input'` is the authored shape, `'output'` the parsed one. */
|
|
19
|
+
readonly io: 'input' | 'output';
|
|
20
|
+
/** The target the document is written for. */
|
|
21
|
+
readonly target: TreeSchemaTarget;
|
|
22
|
+
}
|
|
23
|
+
/** Options of {@link exportTreeSchema}. */
|
|
24
|
+
export interface ExportTreeSchemaOptions {
|
|
25
|
+
/**
|
|
26
|
+
* The `$type`s the document's root may have. Absent: every `$type` of the lookup.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* Each name must be registered in the lookup, and the list must not be empty.
|
|
30
|
+
*/
|
|
31
|
+
readonly accepts?: readonly string[];
|
|
32
|
+
/** Which shape of each schema to write. Default `'input'`, the shape an author writes. */
|
|
33
|
+
readonly io?: 'input' | 'output';
|
|
34
|
+
/**
|
|
35
|
+
* The JSON Schema dialect to write. Default `'draft-2020-12'`.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* Any other value throws before a schema is read, since a document without `$schema`, or with the wrong keyword for
|
|
39
|
+
* its definitions, would be written silently.
|
|
40
|
+
*/
|
|
41
|
+
readonly target?: TreeSchemaTarget;
|
|
42
|
+
/**
|
|
43
|
+
* Writes the JSON Schema of one registration's schema, or returns `undefined` for a schema it cannot write.
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* The default reads `~standard.jsonSchema`, so any schema library that implements Standard JSON Schema exports
|
|
47
|
+
* without a function here. Pass one for a library that does not, or to prefer another converter, Zod's own say:
|
|
48
|
+
* `(schema, { io, target }) => z.toJSONSchema(schema, { io, target })`. The registry takes no validator dependency.
|
|
49
|
+
* A schema that resolves to `undefined` is listed by an open object, as {@link exportTreeSchema} explains. The
|
|
50
|
+
* result is not changed.
|
|
51
|
+
*/
|
|
52
|
+
readonly resolve?: (schema: StandardSchemaV1, context: ExportSchemaContext) => JSONSchemaObject | undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Write the JSON Schema of a whole tree of registrations, composed at the JSON Schema level.
|
|
56
|
+
*
|
|
57
|
+
* @param lookup - The registrations to export: a registry, or a list of registries that make up one vocabulary. When
|
|
58
|
+
* two list a `$type`, the first wins, as it does for a lookup that tries them in turn
|
|
59
|
+
* @param options - The root's `accepts`, the `io` and `target` of the schemas, and a `resolve` function, see
|
|
60
|
+
* {@link ExportTreeSchemaOptions}
|
|
61
|
+
* @returns One document, `{ $schema, $defs, anyOf }`: a definition per `$type` under `$defs` (`definitions` for a
|
|
62
|
+
* draft-07 target), and the root as the union of the root's accepted `$type`s
|
|
63
|
+
* @throws {RegistryError} Code `'unreachable-child-path'` when a slot cannot be found where a registration's JSON
|
|
64
|
+
* Schema declares it, `'unknown-accepted-type'` when a child path accepts a `$type` the lookup lacks, and
|
|
65
|
+
* `'definition-name-clash'` when a definition a schema brought along takes the name of a `$type` or of another definition
|
|
66
|
+
* @throws {Error} When `target` is not `'draft-2020-12'` or `'draft-07'`, before any schema is read, when the lookup
|
|
67
|
+
* holds no registration, when `accepts` is empty, and when it names a `$type` the lookup lacks
|
|
68
|
+
*
|
|
69
|
+
* @remarks
|
|
70
|
+
* Each registration's schema is written by `options.resolve`, by default the schema's own `~standard.jsonSchema`, so
|
|
71
|
+
* Zod, Valibot, ArkType and a hand-written schema export the same way and the registry depends on none of them. A
|
|
72
|
+
* schema it cannot write (`resolve` returns `undefined`) is listed by an open object that holds its `$type` and its child
|
|
73
|
+
* paths, so the document still shows where children go.
|
|
74
|
+
*
|
|
75
|
+
* Each child path is then replaced in the definition, and only the slot: `required`, `minItems` and `maxItems`, and the
|
|
76
|
+
* sibling keys stay as the registration's schema wrote them. The slot takes the union of the path's `accepts` as
|
|
77
|
+
* `$ref`s to the definitions, or of every `$type` of the lookup without `accepts`:
|
|
78
|
+
*
|
|
79
|
+
* | Slot in the registration's JSON Schema | Becomes |
|
|
80
|
+
* | --- | --- |
|
|
81
|
+
* | an array (`type: 'array'`, `items` or `prefixItems`) | the same array, `items: U`, and `U` at each tuple position |
|
|
82
|
+
* | an object | `U` |
|
|
83
|
+
* | open (`{}`) | `{ anyOf: [U, { type: 'array', items: U }] }`, a child or a list of children |
|
|
84
|
+
*
|
|
85
|
+
* `U` is `{ anyOf: [{ $ref }, ...] }`. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside
|
|
86
|
+
* a schema with an `$id` of its own) throws, since guessing would write a document that disagrees with the registration.
|
|
87
|
+
*
|
|
88
|
+
* A schema that was written as a document of its own is moved into the document by
|
|
89
|
+
* {@link createJSONSchemaEmbedder}, and every local pointer follows. Its `$defs` are lifted to the top as
|
|
90
|
+
* `<owner>.<name>` (`page.address` for the `address` definition of `page`), and each anchor is renamed
|
|
91
|
+
* `<owner part>.<name>`. Both write the owner so that two owners never write the same name: in a lifted name each `.`
|
|
92
|
+
* and `_` of the `$type` is `_2e_` and `_5f_` (`a.b` with `c` is `a_2e_b.c`, `a` with `b.c` is `a.b.c`), and in an anchor
|
|
93
|
+
* the owner part is `o` and the `$type` with every character outside `[A-Za-z0-9-]` written as `_<hex>_`
|
|
94
|
+
* (`ui/button` with `x` is `oui_2f_button.x`, `my-card` with `x` is `omy-card.x`). The anchors it renames are `$anchor`,
|
|
95
|
+
* `$dynamicAnchor`, a draft-07 `$id: '#name'` and a draft-04 `id: '#name'`. A name that is still taken, by a `$type` say, is an error, since the two
|
|
96
|
+
* definitions could not both stay. A name in a `$ref` is a JSON Pointer token (`~` as `~0`, `/` as `~1`) and
|
|
97
|
+
* percent-encoded for the URI fragment.
|
|
98
|
+
*/
|
|
99
|
+
export declare function exportTreeSchema(lookup: ExportLookup | readonly ExportLookup[], options?: ExportTreeSchemaOptions): JSONSchemaObject;
|
|
100
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-IYIWS4LW.js";import"./chunk-FMWSZRDV.js";import"./chunk-NSLF54GM.js";import"./chunk-GX6PAJLU.js";import"./chunk-XG4EZ5VP.js";export{a as exportTreeSchema};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { StandardSchemaIssue } from './standard-schema.js';
|
|
2
|
+
/**
|
|
3
|
+
* A Standard Schema issue path as it reads in an error message: object keys joined by dots, array
|
|
4
|
+
* indexes in brackets, for example `steps[0].elements[2].grid.width`. A missing or empty path is the
|
|
5
|
+
* empty string.
|
|
6
|
+
*
|
|
7
|
+
* @param path The `path` of a Standard Schema issue. A segment is a key or an object `{ key }`.
|
|
8
|
+
* @param source The document the path points into. With it, an array item that has a string `id` is
|
|
9
|
+
* followed by the id in parentheses, `steps[0] (main).elements[2] (email).grid.width`, so a log of a
|
|
10
|
+
* document with many nodes names the one it means.
|
|
11
|
+
*/
|
|
12
|
+
export declare function formatIssuePath(path: StandardSchemaIssue['path'], source?: unknown): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-UH3CEF45.js";export{a as formatIssuePath};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
|
-
export * from './
|
|
2
|
+
export * from './registry-error.js';
|
|
3
3
|
export * from './create-registry.js';
|
|
4
|
+
export * from './bind-registry.js';
|
|
4
5
|
export * from './standard-schema.js';
|
|
6
|
+
export * from './parse-node.js';
|
|
7
|
+
export * from './parse-tree.js';
|
|
8
|
+
export * from './format-issue-path.js';
|
|
9
|
+
export * from './export-tree-schema.js';
|
|
10
|
+
export type { JSONSchemaObject, JSONSchemaTarget } from './json-schema/standard.js';
|
|
11
|
+
export type { CheckChildPaths, NodeData, TreeRegistration } from './tree-types.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import"./chunk-55J6XMHW.js";import{a as x}from"./chunk-LG33VSKX.js";import{a as m,b as p,c as f}from"./chunk-RVS7JY2Y.js";import{a}from"./chunk-IYIWS4LW.js";import"./chunk-FMWSZRDV.js";import"./chunk-NSLF54GM.js";import"./chunk-GX6PAJLU.js";import{a as s}from"./chunk-UH3CEF45.js";import{a as d}from"./chunk-QHVQ4S4D.js";import{a as h,b as c}from"./chunk-O5CRFISG.js";import{a as e,b as o,c as t}from"./chunk-P3DDHPDA.js";import{a as r}from"./chunk-XG4EZ5VP.js";export{r as RegistryError,m as assertStandardSchema,x as bindRegistry,f as createMutableRegistry,p as createRegistry,a as exportTreeSchema,s as formatIssuePath,e as isStandardSchema,c as safeParseNode,o as safeParseStandardSchema,d as safeParseTree,t as standardSchema,h as unregisteredTypeMessage};
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": [
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": [],
|
|
4
|
+
"sourcesContent": [],
|
|
5
|
+
"mappings": "",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|