@schema-engine/registry 0.5.2 → 0.7.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 (84) hide show
  1. package/README.md +94 -7
  2. package/dist/bind-registry.d.ts +6 -3
  3. package/dist/bind-registry.js +1 -1
  4. package/dist/bind-registry.js.map +4 -4
  5. package/dist/chunk-24SNVXNP.js +2 -0
  6. package/dist/chunk-24SNVXNP.js.map +7 -0
  7. package/dist/chunk-55J6XMHW.js +0 -0
  8. package/dist/chunk-55J6XMHW.js.map +7 -0
  9. package/dist/chunk-BY4BKVNV.js +1 -0
  10. package/dist/chunk-BY4BKVNV.js.map +7 -0
  11. package/dist/chunk-DDOMNXV7.js +1 -0
  12. package/dist/chunk-DDOMNXV7.js.map +7 -0
  13. package/dist/chunk-DE7GQKZP.js +3 -0
  14. package/dist/chunk-DE7GQKZP.js.map +7 -0
  15. package/dist/chunk-FRJ453UJ.js +1 -0
  16. package/dist/chunk-FRJ453UJ.js.map +7 -0
  17. package/dist/chunk-GX6PAJLU.js +1 -0
  18. package/dist/chunk-GX6PAJLU.js.map +7 -0
  19. package/dist/chunk-HBQNBR6L.js +1 -0
  20. package/dist/chunk-HBQNBR6L.js.map +7 -0
  21. package/dist/chunk-L3ZXHX7S.js +1 -0
  22. package/dist/chunk-L3ZXHX7S.js.map +7 -0
  23. package/dist/chunk-M3SYVKZK.js +1 -0
  24. package/dist/chunk-M3SYVKZK.js.map +7 -0
  25. package/dist/chunk-MWH2GNPD.js +1 -0
  26. package/dist/chunk-MWH2GNPD.js.map +7 -0
  27. package/dist/chunk-O5CRFISG.js +1 -0
  28. package/dist/chunk-O5CRFISG.js.map +7 -0
  29. package/dist/chunk-P3DDHPDA.js +1 -0
  30. package/dist/chunk-P3DDHPDA.js.map +7 -0
  31. package/dist/chunk-UH3CEF45.js +1 -0
  32. package/dist/chunk-UH3CEF45.js.map +7 -0
  33. package/dist/create-registry.d.ts +70 -10
  34. package/dist/create-registry.js +1 -1
  35. package/dist/create-registry.js.map +4 -4
  36. package/dist/export-tree-schema.d.ts +112 -0
  37. package/dist/export-tree-schema.js +1 -0
  38. package/dist/export-tree-schema.js.map +7 -0
  39. package/dist/format-issue-path.js +1 -1
  40. package/dist/format-issue-path.js.map +4 -4
  41. package/dist/index.d.ts +4 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +4 -4
  44. package/dist/json-schema/embedder.d.ts +119 -0
  45. package/dist/json-schema/embedder.js +1 -0
  46. package/dist/json-schema/embedder.js.map +7 -0
  47. package/dist/json-schema/index.d.ts +5 -0
  48. package/dist/json-schema/index.js +1 -0
  49. package/dist/json-schema/index.js.map +7 -0
  50. package/dist/json-schema/slot.d.ts +46 -0
  51. package/dist/json-schema/slot.js +1 -0
  52. package/dist/json-schema/slot.js.map +7 -0
  53. package/dist/json-schema/standard.d.ts +44 -0
  54. package/dist/json-schema/standard.js +1 -0
  55. package/dist/json-schema/standard.js.map +7 -0
  56. package/dist/parse-node.d.ts +69 -10
  57. package/dist/parse-node.js +1 -1
  58. package/dist/parse-node.js.map +4 -4
  59. package/dist/parse-tree.d.ts +111 -35
  60. package/dist/parse-tree.js +1 -1
  61. package/dist/parse-tree.js.map +4 -4
  62. package/dist/registry-error.d.ts +82 -0
  63. package/dist/registry-error.js +1 -0
  64. package/dist/registry-error.js.map +7 -0
  65. package/dist/standard-schema.d.ts +9 -0
  66. package/dist/standard-schema.js +1 -1
  67. package/dist/standard-schema.js.map +4 -4
  68. package/dist/tree-types.d.ts +152 -0
  69. package/dist/tree-types.js +0 -0
  70. package/dist/tree-types.js.map +7 -0
  71. package/dist/types.d.ts +37 -7
  72. package/dist/types.js +1 -0
  73. package/dist/yaml/index.js +1 -4
  74. package/dist/yaml/index.js.map +4 -4
  75. package/dist/yaml/parse.js +1 -2
  76. package/dist/yaml/parse.js.map +4 -4
  77. package/dist/yaml/stringify.js +1 -3
  78. package/dist/yaml/stringify.js.map +4 -4
  79. package/package.json +13 -9
  80. package/skill/SKILL.md +9 -9
  81. package/skill/reference/registry.md +57 -18
  82. package/dist/base-registry.d.ts +0 -73
  83. package/dist/base-registry.js +0 -1
  84. package/dist/base-registry.js.map +0 -7
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @schema-engine/registry
2
2
 
3
- The registration contract and the read-only registries that hold registrations by `$type`. It is the base of Schema Engine's common language: a document names registrations by `$type`, a registry resolves each one, and the registration's schema validates its configuration. It has no UI and no schema-library dependency.
3
+ The registration contract and the registries that hold registrations by `$type`, read-only from a list or mutable for registrations that arrive at runtime. It is the base of Schema Engine's common language: a document names registrations by `$type`, a registry resolves each one, and the registration's schema validates its configuration. It has no UI and no schema-library dependency.
4
4
 
5
5
  ## Install
6
6
 
@@ -41,18 +41,105 @@ export function resolve(node: unknown): string {
41
41
  }
42
42
  ```
43
43
 
44
+ ## A whole document
45
+
46
+ A document is a tree of nodes. A registration says where its children are with `childPaths`, `{ keys, accepts?, list? }` each, and which `$type`s each place accepts (and `list: true` when it holds only a list). `safeParseTree` checks the whole document in one call, collecting every issue with its path, and gives the parsed document as `tree.data`, typed per place:
47
+
48
+ ```typescript
49
+ import * as z from 'zod/mini';
50
+ import { createRegistry, safeParseTree } from '@schema-engine/registry';
51
+
52
+ const nodes = createRegistry('Node', [
53
+ {
54
+ $type: 'page',
55
+ schema: z.object({ $type: z.literal('page'), sections: z.array(z.unknown()) }),
56
+ metadata: { name: 'Page' },
57
+ childPaths: [{ keys: ['sections'], accepts: ['section'] }],
58
+ },
59
+ {
60
+ $type: 'section',
61
+ schema: z.object({ $type: z.literal('section'), title: z._default(z.string(), 'Untitled') }),
62
+ metadata: { name: 'Section' },
63
+ },
64
+ ]);
65
+
66
+ export function titles(document: unknown): string[] {
67
+ const parsed = safeParseTree(nodes, document, { accepts: ['page'] });
68
+ if (!parsed.success) throw new Error(parsed.issues.map((issue) => issue.message).join('\n'));
69
+ return parsed.tree.data.sections.map((section) => section.title);
70
+ }
71
+ ```
72
+
73
+ When the document has issues, the failure also carries `tree`, a `PartialNode`, when the root's own schema passed: every node whose own schema passed, typed like a parsed node, with `output` (its own schema output), `data` (its composed data, `undefined` where something below the node failed) and `children` (the children that parsed, in document order, typed by their `accepts`). One function over `children` reads the success tree and this one alike. Use it to run your own checks on what parsed. The parent's schema keeps the slot opaque (`z.array(z.unknown())`) and declares every child key; `accepts` is the only way to restrict it. The parent's schema keeps `$type` and the slot's shape in its output, or `safeParseTree` throws a `RegistryError`. The issues the engine creates carry a namespaced `code` (`registry/not-accepted`, `registry/unregistered-type`, `registry/missing-type`, `registry/not-an-object`, `registry/not-a-node`, `registry/not-a-list`, `registry/contains-itself`); an issue from a schema keeps whatever its library wrote.
74
+
75
+ ## JSON Schema of a whole document
76
+
77
+ `exportTreeSchema` writes the JSON Schema of the same tree, composed from each registration's own JSON Schema, and the registry depends on no validator. Each registration's schema is read from `~standard.jsonSchema`, which classic `zod`, ArkType and a hand-written schema that sets it provide. `zod/mini` and Valibot do not, so the default throws a `RegistryError` (`'schema-without-json-schema'`) that names the `$type`, and a classic Zod schema that embeds a `zod/mini` one (every schema of `@schema-engine/layout` is one) throws in that converter, which Zod keeps partial so an app bundles only the flavour it uses. `z.toJSONSchema`, Zod's complete converter, writes all three, so for Zod pass a `resolve` that calls it; `instanceof` narrows the Standard Schema `resolve` receives, and `undefined` lists a schema that is not Zod as an open node. The second argument also carries the `$type` of the registration being written, for a `resolve` that throws and names it:
78
+
79
+ ```typescript
80
+ import * as z from 'zod/mini';
81
+ import { createRegistry, exportTreeSchema } from '@schema-engine/registry';
82
+
83
+ const nodes = createRegistry('Node', [
84
+ {
85
+ $type: 'page',
86
+ schema: z.object({ $type: z.literal('page'), sections: z.array(z.unknown()) }),
87
+ metadata: { name: 'Page' },
88
+ childPaths: [{ keys: ['sections'], accepts: ['section'] }],
89
+ },
90
+ {
91
+ $type: 'section',
92
+ schema: z.object({ $type: z.literal('section'), title: z.string() }),
93
+ metadata: { name: 'Section' },
94
+ },
95
+ ]);
96
+
97
+ export const documentSchema = exportTreeSchema(nodes, {
98
+ accepts: ['page'],
99
+ resolve: (schema, { io, target }) =>
100
+ schema instanceof z.core.$ZodType ? z.toJSONSchema(schema, { io, target }) : undefined,
101
+ });
102
+ ```
103
+
104
+ The result is `{ $schema, $defs, anyOf }`: one definition per `$type`, and the root as the union of `accepts` (every `$type` without it). Only the slot of each child path is replaced, by the union of what it accepts, so `required`, `minItems` and `maxItems` stay. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside a schema with an `$id` (`id` for draft-04) of its own) throws a `RegistryError`. Zod writes a union of primitives as a `type` list (`type: ['string', 'number']`), which is valid JSON Schema, but strict Ajv refuses it unless it is created with `allowUnionTypes: true`.
105
+
106
+ ## Errors
107
+
108
+ Building or binding a registry from registrations that break a rule throws a `RegistryError`, and so does `safeParseTree` when a schema contradicts its registration, and `exportTreeSchema` when it cannot write a registration's slot. Branch on its `code`, not on the message: the message is for people and may be reworded, the codes stay. Every `RegistryError` carries `$type`, the registration at fault, and `kind`, the registry's label (`Widget`), which a parse leaves out when its lookup is no registry; a code that needs more to describe the mistake sets it too, so a message can be written again, in another language say, from the error's fields alone.
109
+
110
+ | Code | Thrown when | Details besides `kind` and `$type` |
111
+ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------- |
112
+ | `'invalid-schema'` | A registration's `schema` has no `~standard.validate` function | |
113
+ | `'invalid-child-paths'` | `childPaths` is not a list, or an entry is not `{ keys, accepts?, list? }` with non-empty `keys`, when present a non-empty `accepts` of non-empty names without repeats, and a `list` that is `true` | |
114
+ | `'duplicate-child-path'` | A registration declares the same child path (the same keys) twice | `childPath` |
115
+ | `'nested-child-path'` | A child path runs through another child path of the same registration | `childPath`, and `outerChildPath` |
116
+ | `'duplicate-type'` | A `$type` is registered twice with `duplicates: 'error'` | |
117
+ | `'unknown-binding'` | `bindRegistry` got a binding whose key is no contract's `$type` | None; `$type` is the binding key |
118
+ | `'missing-binding'` | `bindRegistry` got no binding for a contract | |
119
+ | `'binding-overrides-contract'` | A binding sets a key its contract already defines | `key`, the key the binding sets |
120
+ | `'schema-changes-type'` | `safeParseTree` parsed a node whose schema returned an output without the node's own `$type` | |
121
+ | `'schema-breaks-child-path'` | `safeParseTree` parsed a node whose schema returned an output that does not keep a child path as the document has it | `childPath` |
122
+ | `'unreachable-child-path'` | `exportTreeSchema` found no slot for a child path in a registration's JSON Schema: not declared, behind `allOf`, a `$ref` or a union, inside an `$id` (`id` for draft-04) of its own, or not an object, an array or open | `childPath` |
123
+ | `'schema-without-json-schema'` | `exportTreeSchema`, with its default `resolve`, met a schema that sets no `~standard.jsonSchema` | |
124
+ | `'unknown-accepted-type'` | `exportTreeSchema` got a lookup that lacks a `$type` a child path accepts | `childPath`, and `key`, the `$type` |
125
+ | `'definition-name-clash'` | A definition a schema brought along takes the name of a `$type` or of another definition | `key`, the name; `$type`, the owner |
126
+ | `'invalid-declaration'` | A domain package refuses a declaration of a registration other than its child paths | None; `$type` is the registration |
127
+
128
+ `assertStandardSchema` on its own throws a plain `Error`: its caller is not building a registry. Other errors raised while parsing a node or a document, such as a Standard Schema that validates asynchronously, are plain `Error`s too, and `parseYaml` still throws `YamlDocumentError`.
129
+
44
130
  ## Entry points
45
131
 
46
- | Import | Holds |
47
- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
48
- | `@schema-engine/registry` | `createRegistry`, `bindRegistry`, `BaseRegistry`, the registration types, `safeParseNode`, `safeParseTree`, `safeParseStandardSchema`, `assertStandardSchema`, `standardSchema` and `formatIssuePath` |
49
- | `@schema-engine/registry/yaml` | `parseYaml`, `safeParseYaml` and `stringifyYaml`, which report errors by line and column. Needs the optional peer dependency `yaml` |
132
+ | Import | Holds |
133
+ | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
134
+ | `@schema-engine/registry` | `createRegistry`, `createMutableRegistry`, `bindRegistry`, `RegistryError`, `RegistryErrorCode`, the registration types (`ChildPath` among them), `safeParseNode`, `safeParseTree`, `exportTreeSchema`, `safeParseStandardSchema`, `isStandardSchema`, `assertStandardSchema`, `standardSchema` and `formatIssuePath` |
135
+ | `@schema-engine/registry/json-schema` | `readStandardJSONSchema`, `createJSONSchemaEmbedder`, `assertJSONSchemaTarget`, `replaceChildSlot`, `definitionRef`, `definitionsKeyword`, `idKeyword` and `startsResource`, for code that writes JSON Schema itself: a `resolve` that falls back to Standard JSON Schema, or a domain package's own export |
136
+ | `@schema-engine/registry/yaml` | `parseYaml`, `safeParseYaml` and `stringifyYaml`, which report errors by line and column. Needs the optional peer dependency `yaml` |
50
137
 
51
138
  ## Documentation
52
139
 
53
140
  - [Registry](https://schema-engine.com/docs/registry/overview): install, build a registry and resolve a JSON node.
54
- - [Read-only and mutable registries](https://schema-engine.com/docs/registry/registries): `createRegistry` and `BaseRegistry`.
55
- - [Resolve a document](https://schema-engine.com/docs/registry/resolve-a-document): validate a whole tree of nodes with `safeParseTree` and render it.
141
+ - [Read-only and mutable registries](https://schema-engine.com/docs/registry/registries): `createRegistry` and `createMutableRegistry`.
142
+ - [Resolve a document](https://schema-engine.com/docs/registry/resolve-a-document): validate a whole tree of nodes with `safeParseTree`, render it and write its JSON Schema with `exportTreeSchema`.
56
143
  - [API reference](https://schema-engine.com/docs/registry/api-reference): every export.
57
144
  - [For AI agents](https://schema-engine.com/docs/schema-engine/agent-skill): the package ships its part of the agent skill.
58
145
 
@@ -48,9 +48,12 @@ export interface BoundRegistry<TContract extends BaseRegistration, TBindings> ex
48
48
  *
49
49
  * @param contracts - Registrations without the renderer's part: the `$type`, schema and metadata, plus what the domain fixes
50
50
  * @param bindings - What this renderer adds to each contract, keyed by `$type`, such as `render` or a tag name
51
- * @throws {Error} `Widget 'card' has no binding.` when a contract has no binding
52
- * @throws {Error} `Widget binding 'crad' names no registration.` when a binding's key is no contract's `$type`
53
- * @throws {Error} `Widget 'card' binding sets 'schema', which the contract defines.` when a binding sets a contract key
51
+ * @throws {RegistryError} Code `'missing-binding'`, `Widget 'card' has no binding.`, when a contract has no binding
52
+ * @throws {RegistryError} Code `'unknown-binding'`, `Widget binding 'crad' names no registration.`, when a binding's
53
+ * key, set as `$type`, is no contract's `$type`
54
+ * @throws {RegistryError} Code `'binding-overrides-contract'`, `Widget 'card' binding sets 'schema', which the contract
55
+ * defines.`, when a binding sets a contract key, named by `key`
56
+ * @throws {RegistryError} The errors of {@link createRegistry}, when a merged registration breaks one of its rules
54
57
  *
55
58
  * @remarks
56
59
  * The result is a frozen registry built with {@link createRegistry}, so it keeps the contracts' order and checks every
@@ -1 +1 @@
1
- function p(t,i="Registration schema"){if(typeof(t!==null&&(typeof t=="object"||typeof t=="function")?t["~standard"]:void 0)?.validate!="function")throw new Error(`${i} must implement Standard Schema (~standard.validate).`);return t}function f(t,i){if(t===void 0)return;if(!Array.isArray(t))throw new Error(`${i} childPaths must be a list of key paths.`);let s=[];for(let e of t){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||r===""))throw new Error(`${i} childPaths must hold non-empty lists of non-empty keys.`);s.push(e)}let a=s.map(e=>e.join("."));for(let[e,r]of s.entries()){let o=r.join(".");if(a.indexOf(o)!==e)throw new Error(`${i} declares the child path '${o}' twice.`);let n=s.find(d=>d.length<r.length&&d.every((g,c)=>g===r[c]));if(n)throw new Error(`${i} child path '${o}' runs through the child path '${n.join(".")}'.`)}}function y(t,i,s={}){let a=new Map;for(let n of i){if(s.duplicates==="error"&&a.has(n.$type))throw new Error(`${t} '${n.$type}' is registered twice.`);a.set(n.$type,n)}let e=new Map;for(let[n,d]of a)p(d.schema,`${t} '${n}' schema`),f(d.childPaths,`${t} '${n}'`),e.set(n,Object.freeze({...d}));let r=Object.freeze([...e.values()]),o=Object.freeze([...e.keys()]);return Object.freeze({kind:t,size:e.size,get:n=>e.get(n),has:n=>e.has(n),all:()=>r,keys:()=>o})}function T(t,i){let{kind:s}=t;for(let e of Object.keys(i))if(!t.has(e))throw new Error(`${s} binding '${e}' names no registration.`);let a=t.all().map(e=>{let r=Object.hasOwn(i,e.$type)?i[e.$type]:void 0;if(typeof r!="object"||r===null)throw new Error(`${s} '${e.$type}' has no binding.`);for(let o of Object.keys(r))if(Object.hasOwn(e,o))throw new Error(`${s} '${e.$type}' binding sets '${o}', which the contract defines.`);return{...e,...r}});return y(s,a)}export{T as bindRegistry};
1
+ import{a}from"./chunk-HBQNBR6L.js";import"./chunk-M3SYVKZK.js";import"./chunk-P3DDHPDA.js";import"./chunk-BY4BKVNV.js";export{a as bindRegistry};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/create-registry.ts", "../src/bind-registry.ts"],
4
- "sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * A registry built once from a list of registrations. It has no `register` or\n * `clear`; to change its contents, build another registry from a new list.\n */\nexport interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {\n\t/** Label used in build errors, for example `Element`. */\n\treadonly kind: 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\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 */\nexport function assertStandardSchema(schema: unknown, context = 'Registration schema'): 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\tif (typeof standard?.validate !== 'function') {\n\t\tthrow new Error(`${context} must implement Standard Schema (~standard.validate).`);\n\t}\n\treturn schema as StandardSchemaV1;\n}\n\n/**\n * Check the `childPaths` of a registration.\n *\n * @remarks\n * Two paths that read the same once joined with dots would share one key of `ParsedNode.children`, so they count as\n * one path declared twice. A path that runs through another one would reach inside a child node, whose own\n * registration says where its children are, so the walk would visit the same node from two parents.\n */\nfunction assertChildPaths(childPaths: unknown, context: string): void {\n\tif (childPaths === undefined) return;\n\tif (!Array.isArray(childPaths)) throw new Error(`${context} childPaths must be a list of key paths.`);\n\tconst paths: string[][] = [];\n\tfor (const keys of childPaths as unknown[]) {\n\t\tif (!Array.isArray(keys) || keys.length === 0 || keys.some((key) => typeof key !== 'string' || key === '')) {\n\t\t\tthrow new Error(`${context} childPaths must hold non-empty lists of non-empty keys.`);\n\t\t}\n\t\tpaths.push(keys as string[]);\n\t}\n\tconst joined = paths.map((keys) => keys.join('.'));\n\tfor (const [index, keys] of paths.entries()) {\n\t\tconst name = keys.join('.');\n\t\tif (joined.indexOf(name) !== index) throw new Error(`${context} declares the child path '${name}' twice.`);\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 Error(`${context} child path '${name}' runs through the child path '${outer.join('.')}'.`);\n\t\t}\n\t}\n}\n\n/** Options of {@link createRegistry}. */\nexport interface CreateRegistryOptions {\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 {Error} `Widget 'card' is registered twice.` when `duplicates` is `'error'` and a `$type` repeats, before any\n * schema is checked\n * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema\n * @throws {Error} Naming the `$type` when a winning registration's `childPaths` is not a list of non-empty key lists, repeats a path, or has a path that runs through another\n *\n * @remarks\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 BaseRegistry} instead when registrations arrive at runtime.\n */\nexport function createRegistry<const TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly 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 new Error(`${kind} '${registration.$type}' is registered twice.`);\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\tassertStandardSchema(registration.schema, `${kind} '${key}' schema`);\n\t\tassertChildPaths(registration.childPaths, `${kind} '${key}'`);\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\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", "import { createRegistry, type ReadOnlyRegistry } from './create-registry.js';\nimport type { BaseRegistration } from './types.js';\n\n/** What a binding may not set: the keys its contract already defines. */\ntype ContractKeys<TContract> = { readonly [K in keyof TContract]?: never };\n\n/** The binding each `$type` of a contracts registry takes, which may not set a key of its own contract. */\ntype BindingsOf<TContract extends BaseRegistration> = {\n\treadonly [K in TContract['$type']]: Readonly<Record<string, unknown>> &\n\t\tContractKeys<Extract<TContract, { $type: K }>>;\n};\n\n/** The keys of `TBindings` that no contract answers; each is typed `never`, so naming one is a compile error. */\ntype ExtraBindings<TBindings, TContract extends BaseRegistration> = {\n\treadonly [K in Exclude<keyof TBindings, TContract['$type']>]: never;\n};\n\n/**\n * One binding per `$type` of a contracts registry, every binding of the same shape.\n *\n * @remarks\n * Use it with `satisfies` to fix what one renderer binds:\n * `{ card: { render: Card } } satisfies RegistryBindings<typeof contracts, ReactBinding>`.\n * A contracts registry whose `$type` is a plain `string` has no known keys to require, so only {@link bindRegistry}'s\n * build-time checks apply to it.\n */\nexport type RegistryBindings<TRegistry extends ReadOnlyRegistry, TBinding extends object = object> =\n\tTRegistry extends ReadOnlyRegistry<infer TContract> ? { readonly [K in TContract['$type']]: TBinding } : never;\n\n/** A contract merged with the binding its `$type` names, member by member. */\nexport type BoundRegistration<TContract extends BaseRegistration, TBindings> = TContract extends unknown\n\t? TContract & TBindings[TContract['$type'] & keyof TBindings]\n\t: never;\n\n/** The `$type`s of a contracts registry that are known literals; `never` when the contracts are typed only as `string`. */\ntype KnownTypes<TContract extends BaseRegistration> = string extends TContract['$type'] ? never : TContract['$type'];\n\n/**\n * What {@link bindRegistry} returns: a read-only registry whose `get` also answers a known `$type` without `undefined`.\n *\n * @remarks\n * `get` returns the registration of that exact `$type` when the contracts name their `$type`s as literals, because\n * `bindRegistry` guarantees every contract is bound. The `string` overload stays for a `$type` read from a document.\n */\nexport interface BoundRegistry<TContract extends BaseRegistration, TBindings> extends ReadOnlyRegistry<\n\tBoundRegistration<TContract, TBindings>\n> {\n\tget<K extends KnownTypes<TContract>>(key: K): Extract<BoundRegistration<TContract, TBindings>, { $type: K }>;\n\tget(key: string): BoundRegistration<TContract, TBindings> | undefined;\n}\n\n/**\n * Build a renderer's registry from a registry of contracts and one binding per `$type`.\n *\n * @param contracts - Registrations without the renderer's part: the `$type`, schema and metadata, plus what the domain fixes\n * @param bindings - What this renderer adds to each contract, keyed by `$type`, such as `render` or a tag name\n * @throws {Error} `Widget 'card' has no binding.` when a contract has no binding\n * @throws {Error} `Widget binding 'crad' names no registration.` when a binding's key is no contract's `$type`\n * @throws {Error} `Widget 'card' binding sets 'schema', which the contract defines.` when a binding sets a contract key\n *\n * @remarks\n * The result is a frozen registry built with {@link createRegistry}, so it keeps the contracts' order and checks every\n * schema again. Each registration is a shallow merge, so `schema`, `metadata` and every other value of a contract is\n * shared by identity between all the renderers that bind it. A binding is renderer-only data (a `render` function, a\n * tag name) and never carries schema or metadata.\n *\n * With contracts typed by literal `$type`, a missing binding, an extra one and a binding that sets a contract key are\n * also compile errors. With contracts typed only as `string` the three checks run when the registry is built.\n */\nexport function bindRegistry<TContract extends BaseRegistration, const TBindings extends BindingsOf<TContract>>(\n\tcontracts: ReadOnlyRegistry<TContract>,\n\tbindings: TBindings & ExtraBindings<TBindings, TContract>,\n): BoundRegistry<TContract, TBindings>;\nexport function bindRegistry(\n\tcontracts: ReadOnlyRegistry,\n\tbindings: Readonly<Record<string, object>>,\n): ReadOnlyRegistry<BaseRegistration> {\n\tconst { kind } = contracts;\n\tfor (const key of Object.keys(bindings)) {\n\t\tif (!contracts.has(key)) throw new Error(`${kind} binding '${key}' names no registration.`);\n\t}\n\tconst bound = contracts.all().map((contract) => {\n\t\tconst binding: unknown = Object.hasOwn(bindings, contract.$type) ? bindings[contract.$type] : undefined;\n\t\tif (typeof binding !== 'object' || binding === null) {\n\t\t\tthrow new Error(`${kind} '${contract.$type}' has no binding.`);\n\t\t}\n\t\tfor (const key of Object.keys(binding)) {\n\t\t\tif (Object.hasOwn(contract, key)) {\n\t\t\t\tthrow new Error(`${kind} '${contract.$type}' binding sets '${key}', which the contract defines.`);\n\t\t\t}\n\t\t}\n\t\treturn { ...contract, ...binding };\n\t});\n\treturn createRegistry(kind, bound);\n}\n"],
5
- "mappings": "AA2BO,SAASA,EAAqBC,EAAiBC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I,OAAO,OAAOD,EAAUF,CAAG,EAC9B,MAAM,IAAI,MAAM,GAAGD,CAAI,KAAKG,EAAS,KAAK,mBAAmBF,CAAG,gCAAgC,EAGlG,MAAO,CAAE,GAAGE,EAAU,GAAGC,CAAQ,CAClC,CAAC,EACD,OAAOC,EAAeL,EAAME,CAAK,CAClC",
6
- "names": ["assertStandardSchema", "schema", "context", "assertChildPaths", "childPaths", "paths", "keys", "key", "joined", "index", "name", "outer", "other", "position", "createRegistry", "kind", "registrations", "options", "winners", "registration", "entries", "all", "bindRegistry", "contracts", "bindings", "kind", "key", "bound", "contract", "binding", "createRegistry"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }
@@ -0,0 +1,2 @@
1
+ import{LineCounter as h,isNode as P,parseDocument as I}from"yaml";var m=class extends Error{issues;constructor(n){super(n.length>0?n.map(T).join(`
2
+ `):"Invalid YAML document"),this.name="YamlDocumentError",this.issues=n}};function Y(e){let n="";for(let t of e)typeof t=="number"?n+=`[${t}]`:n+=n?`.${String(t)}`:String(t);return n}function T(e){let n=e.filename?`${e.filename}:${e.line}:${e.column}`:`line ${e.line}, column ${e.column}`,t=Y(e.path);return t?`${n} ${t}: ${e.message}`:`${n} ${e.message}`}function L(e){return typeof e=="object"?e.key:e}function A(e,n){for(let t=n.length;t>0;t--){let s=e.getIn(n.slice(0,t),!0);if(P(s)&&s.range)return s}return e.contents?.range?e.contents:null}var p=100;function M(e){return e.replace(/ at line \d+, column \d+:?[\s\S]*$/,"")}function E(e,n){return e!==void 0&&n!==void 0&&e.line===n.line&&e.col===n.col}function $(e){let n="tag:yaml.org,2002:";return e.startsWith(n)?`!!${e.slice(n.length)}`:e}function K(e){switch(e.code){case"MULTIPLE_DOCS":return"A file holds one document; remove the extra `---`.";case"MULTILINE_IMPLICIT_KEY":return"Bad indentation or a missing colon: line this up with the keys above it, or put the whole key on one line.";case"TAG_RESOLVE_FAILED":{let n=/Unresolved tag: (\S+)/.exec(e.message)?.[1];return`Tags are not supported: remove ${n?`${$(n)} `:""}and write the value plainly. Quote a string that looks like another type.`}default:return M(e.message)}}function x(e){let[n,t]=e.linePos??[];return(e.code==="MULTILINE_IMPLICIT_KEY"?t:n)??n??{line:1,col:1}}function _(e){let n=e.errors.filter(t=>t.code==="MULTILINE_IMPLICIT_KEY");return[...e.errors,...e.warnings].filter(t=>t.code!=="BLOCK_AS_IMPLICIT_KEY"||!n.some(s=>E(s.linePos?.[0],t.linePos?.[0]))).map(t=>({message:K(t),position:x(t)}))}function w(e){return e instanceof Error&&/alias count/i.test(e.message)?`The document has more than ${p} alias expansions (*name) in all. Write the repeated value out, or use fewer or smaller anchors.`:e instanceof Error?e.message:"The document could not be read"}function v(e,n,t){let s=new h,y=e.charCodeAt(0)===65279?e.slice(1):e,l=I(y,{lineCounter:s,version:"1.2",schema:"core",resolveKnownTags:!1,merge:!0,stringKeys:!0}),u=(r,o,a,i)=>{let d={message:r,path:o,line:a,column:i};return t?.filename!==void 0&&(d.filename=t.filename),d},f=_(l);if(f.length>0)return{success:!1,issues:f.map(({message:r,position:o})=>u(r,[],o.line,o.col))};let g;try{g=l.toJS({maxAliasCount:p})}catch(r){return{success:!1,issues:[u(w(r),[],1,1)]}}let c=n(g);return c.success?{success:!0,data:c.data}:{success:!1,issues:c.issues.map(r=>{let o=(r.path??[]).map(L),a=A(l,o),i=a?.range?s.linePos(a.range[0]):{line:1,col:1};return u(r.message,o,i.line,i.col)})}}function C(e,n,t){let s=v(e,n,t);if(!s.success)throw new m(s.issues);return s.data}export{m as a,v as b,C as c};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/yaml/parse.ts"],
4
+ "sourcesContent": ["import { LineCounter, isNode, parseDocument } from 'yaml';\nimport type { Document, Node, YAMLError, YAMLWarning } from 'yaml';\n\n/** One segment of a Standard Schema issue path: a key, or `{ key }` as Standard Schema allows. */\ntype PathSegment = PropertyKey | { readonly key: PropertyKey };\n\n/**\n * A validator for the parsed value, in the shape of Standard Schema issues. It must be synchronous.\n *\n * @remarks\n * `engine.safeValidateForm` from `@schema-engine/forms` fits as it is. For a Standard Schema\n * (`zod`, `valibot`, ...), wrap its `~standard.validate` and return `{ success: true, data }` or\n * `{ success: false, issues }`.\n */\nexport type YamlValidate<T> = (\n\tvalue: unknown,\n) =>\n\t| { success: true; data: T }\n\t| { success: false; issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PathSegment> }> };\n\n/**\n * A problem found in a YAML document, placed in its source text.\n *\n * @remarks\n * `line` and `column` count from 1. For a validation issue they point at the start of the value the\n * `path` names; when the path names a key the document does not have, they point at the nearest\n * ancestor that exists. A syntax error has an empty `path` and the position the parser reports.\n */\nexport type YamlIssue = {\n\tmessage: string;\n\tpath: PropertyKey[];\n\tline: number;\n\tcolumn: number;\n\tfilename?: string;\n};\n\n/** What {@link safeParseYaml} returns: the validated data, or every issue found. */\nexport type YamlParseResult<T> = { success: true; data: T } | { success: false; issues: YamlIssue[] };\n\nexport type YamlParseOptions = {\n\t/** Name of the file the text came from; it prefixes error messages and is set on each issue. */\n\tfilename?: string;\n};\n\n/**\n * Thrown by {@link parseYaml} when the text is not valid YAML or its value does not validate.\n *\n * @remarks\n * `message` lists the issues one per line as `<file>:<line>:<column> <path>: <message>`, so a log\n * reads without parsing `issues`.\n */\nexport class YamlDocumentError extends Error {\n\treadonly issues: YamlIssue[];\n\n\tconstructor(issues: YamlIssue[]) {\n\t\tsuper(issues.length > 0 ? issues.map(formatIssue).join('\\n') : 'Invalid YAML document');\n\t\tthis.name = 'YamlDocumentError';\n\t\tthis.issues = issues;\n\t}\n}\n\n/** A path as it reads in an error message: `steps[0].elements[2].grid.width`. */\nfunction formatPath(path: PropertyKey[]): string {\n\tlet text = '';\n\tfor (const key of path) {\n\t\tif (typeof key === 'number') {\n\t\t\ttext += `[${key}]`;\n\t\t} else {\n\t\t\ttext += text ? `.${String(key)}` : String(key);\n\t\t}\n\t}\n\treturn text;\n}\n\nfunction formatIssue(issue: YamlIssue): string {\n\tconst location = issue.filename\n\t\t? `${issue.filename}:${issue.line}:${issue.column}`\n\t\t: `line ${issue.line}, column ${issue.column}`;\n\tconst path = formatPath(issue.path);\n\treturn path ? `${location} ${path}: ${issue.message}` : `${location} ${issue.message}`;\n}\n\nfunction toKey(segment: PathSegment): PropertyKey {\n\treturn typeof segment === 'object' ? segment.key : segment;\n}\n\n/**\n * The source node a path names, or the nearest ancestor that exists when the document lacks the\n * last keys of the path.\n */\nfunction nodeForPath(doc: Document.Parsed, path: PropertyKey[]): Node | null {\n\tfor (let length = path.length; length > 0; length--) {\n\t\tconst node = doc.getIn(path.slice(0, length), true);\n\t\tif (isNode(node) && node.range) {\n\t\t\treturn node;\n\t\t}\n\t}\n\treturn doc.contents?.range ? doc.contents : null;\n}\n\n/** The most alias expansions `toJS` allows before it gives up, which guards against alias bombs. */\nconst MAX_ALIAS_COUNT = 100;\n\n/** The parser's message without the ` at line N, column N:` suffix and the code frame it appends. */\nfunction syntaxMessage(message: string): string {\n\treturn message.replace(/ at line \\d+, column \\d+:?[\\s\\S]*$/, '');\n}\n\ntype Position = { line: number; col: number };\n\nfunction samePosition(a: Position | undefined, b: Position | undefined): boolean {\n\treturn a !== undefined && b !== undefined && a.line === b.line && a.col === b.col;\n}\n\n/** `tag:yaml.org,2002:float` as it is written in a document, `!!float`. */\nfunction shortTag(tag: string): string {\n\tconst prefix = 'tag:yaml.org,2002:';\n\treturn tag.startsWith(prefix) ? `!!${tag.slice(prefix.length)}` : tag;\n}\n\n/**\n * The message an author can act on. The parser's own text often advises changing a `yaml` API call,\n * which the author of a document cannot do.\n */\nfunction friendlyMessage(problem: YAMLError | YAMLWarning): string {\n\tswitch (problem.code) {\n\t\tcase 'MULTIPLE_DOCS':\n\t\t\treturn 'A file holds one document; remove the extra `---`.';\n\t\tcase 'MULTILINE_IMPLICIT_KEY':\n\t\t\treturn 'Bad indentation or a missing colon: line this up with the keys above it, or put the whole key on one line.';\n\t\tcase 'TAG_RESOLVE_FAILED': {\n\t\t\tconst tag = /Unresolved tag: (\\S+)/.exec(problem.message)?.[1];\n\t\t\tconst name = tag ? `${shortTag(tag)} ` : '';\n\t\t\treturn `Tags are not supported: remove ${name}and write the value plainly. Quote a string that looks like another type.`;\n\t\t}\n\t\tdefault:\n\t\t\treturn syntaxMessage(problem.message);\n\t}\n}\n\n/**\n * Where a parser problem is reported. A `MULTILINE_IMPLICIT_KEY` starts on the line above the\n * over-indented line that ends it, so it is reported at its end.\n */\nfunction positionOf(problem: YAMLError | YAMLWarning): Position {\n\tconst [start, end] = problem.linePos ?? [];\n\treturn (problem.code === 'MULTILINE_IMPLICIT_KEY' ? end : start) ?? start ?? { line: 1, col: 1 };\n}\n\n/**\n * Every parser error and warning. An over-indented line makes the parser report two errors from the\n * same place; the `BLOCK_AS_IMPLICIT_KEY` one is dropped.\n */\nfunction parserProblems(doc: Document.Parsed): Array<{ message: string; position: Position }> {\n\tconst multiline = doc.errors.filter((error) => error.code === 'MULTILINE_IMPLICIT_KEY');\n\treturn [...doc.errors, ...doc.warnings]\n\t\t.filter(\n\t\t\t(problem) =>\n\t\t\t\tproblem.code !== 'BLOCK_AS_IMPLICIT_KEY' ||\n\t\t\t\t!multiline.some((other) => samePosition(other.linePos?.[0], problem.linePos?.[0])),\n\t\t)\n\t\t.map((problem) => ({ message: friendlyMessage(problem), position: positionOf(problem) }));\n}\n\n/** The text of an error `toJS` throws, with the alias limit said in terms an author can use. */\nfunction conversionMessage(error: unknown): string {\n\tif (error instanceof Error && /alias count/i.test(error.message)) {\n\t\treturn `The document has more than ${MAX_ALIAS_COUNT} alias expansions (*name) in all. Write the repeated value out, or use fewer or smaller anchors.`;\n\t}\n\treturn error instanceof Error ? error.message : 'The document could not be read';\n}\n\n/**\n * Parse YAML text and validate the value, returning the issues instead of throwing.\n *\n * @param text A single YAML document, read as YAML 1.2 with the core schema: only `true`, `false`,\n * `null` and numbers are special, so `no`, `on` and `yes` stay strings. A leading byte order mark is\n * ignored.\n * @param validate Called with the parsed value, only when the text is valid YAML.\n * @returns `{ success: true, data }` with what `validate` returned, or `{ success: false, issues }`\n * with each syntax error or validation issue and its line and column.\n *\n * @remarks\n * An unquoted `1.10` is the number `1.1` in every YAML version; quote it (`\"1.10\"`) to keep a string.\n * Multiple documents in one text are a syntax error. Tags (`!!binary`, `!!set`, `!custom`) are\n * reported as issues, so what `validate` receives is always JSON-shaped. Mapping keys are read as\n * strings: `1: a` is `{ '1': 'a' }`.\n *\n * Anchors, aliases and merge keys (`<<: *defaults`) work within the text. A text with more than 100\n * alias expansions is reported as an issue at line 1, not thrown. An issue inside a merged value\n * points at the map that merges it, because the merged keys have no place of their own. A merge\n * source that is not a map (`<<: 5`) is reported at line 1, column 1.\n */\nexport function safeParseYaml<T>(\n\ttext: string,\n\tvalidate: YamlValidate<T>,\n\toptions?: YamlParseOptions,\n): YamlParseResult<T> {\n\tconst lineCounter = new LineCounter();\n\tconst source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;\n\tconst doc = parseDocument(source, {\n\t\tlineCounter,\n\t\tversion: '1.2',\n\t\tschema: 'core',\n\t\tresolveKnownTags: false,\n\t\tmerge: true,\n\t\tstringKeys: true,\n\t});\n\n\tconst issue = (message: string, path: PropertyKey[], line: number, column: number): YamlIssue => {\n\t\tconst found: YamlIssue = { message, path, line, column };\n\t\tif (options?.filename !== undefined) {\n\t\t\tfound.filename = options.filename;\n\t\t}\n\t\treturn found;\n\t};\n\n\tconst problems = parserProblems(doc);\n\tif (problems.length > 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: problems.map(({ message, position }) => issue(message, [], position.line, position.col)),\n\t\t};\n\t}\n\n\tlet value: unknown;\n\ttry {\n\t\tvalue = doc.toJS({ maxAliasCount: MAX_ALIAS_COUNT });\n\t} catch (error) {\n\t\treturn { success: false, issues: [issue(conversionMessage(error), [], 1, 1)] };\n\t}\n\n\tconst result = validate(value);\n\tif (result.success) {\n\t\treturn { success: true, data: result.data };\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\tissues: result.issues.map((found) => {\n\t\t\tconst path = (found.path ?? []).map(toKey);\n\t\t\tconst node = nodeForPath(doc, path);\n\t\t\tconst start = node?.range ? lineCounter.linePos(node.range[0]) : { line: 1, col: 1 };\n\t\t\treturn issue(found.message, path, start.line, start.col);\n\t\t}),\n\t};\n}\n\n/**\n * Parse YAML text and validate the value, throwing when either fails.\n *\n * @throws {YamlDocumentError} With each syntax error or validation issue and its line and column.\n * {@link safeParseYaml} returns them instead.\n */\nexport function parseYaml<T>(text: string, validate: YamlValidate<T>, options?: YamlParseOptions): T {\n\tconst result = safeParseYaml(text, validate, options);\n\tif (!result.success) {\n\t\tthrow new YamlDocumentError(result.issues);\n\t}\n\treturn result.data;\n}\n"],
5
+ "mappings": "AAAA,OAAS,eAAAA,EAAa,UAAAC,EAAQ,iBAAAC,MAAqB,OAmD5C,IAAMC,EAAN,cAAgC,KAAM,CACnC,OAET,YAAYC,EAAqB,CAChC,MAAMA,EAAO,OAAS,EAAIA,EAAO,IAAIC,CAAW,EAAE,KAAK;AAAA,CAAI,EAAI,uBAAuB,EACtF,KAAK,KAAO,oBACZ,KAAK,OAASD,CACf,CACD,EAGA,SAASE,EAAWC,EAA6B,CAChD,IAAIC,EAAO,GACX,QAAWC,KAAOF,EACb,OAAOE,GAAQ,SAClBD,GAAQ,IAAIC,CAAG,IAEfD,GAAQA,EAAO,IAAI,OAAOC,CAAG,CAAC,GAAK,OAAOA,CAAG,EAG/C,OAAOD,CACR,CAEA,SAASH,EAAYK,EAA0B,CAC9C,IAAMC,EAAWD,EAAM,SACpB,GAAGA,EAAM,QAAQ,IAAIA,EAAM,IAAI,IAAIA,EAAM,MAAM,GAC/C,QAAQA,EAAM,IAAI,YAAYA,EAAM,MAAM,GACvCH,EAAOD,EAAWI,EAAM,IAAI,EAClC,OAAOH,EAAO,GAAGI,CAAQ,IAAIJ,CAAI,KAAKG,EAAM,OAAO,GAAK,GAAGC,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AAK,CAAE,cAAeG,CAAgB,CAAC,CACpD,OAASgB,EAAO,CACf,MAAO,CAAE,QAAS,GAAO,OAAQ,CAACxB,EAAM0B,EAAkBF,CAAK,EAAG,CAAC,EAAG,EAAG,CAAC,CAAC,CAAE,CAC9E,CAEA,IAAMc,EAASV,EAASS,CAAK,EAC7B,OAAIC,EAAO,QACH,CAAE,QAAS,GAAM,KAAMA,EAAO,IAAK,EAEpC,CACN,QAAS,GACT,OAAQA,EAAO,OAAO,IAAKJ,GAAU,CACpC,IAAMrC,GAAQqC,EAAM,MAAQ,CAAC,GAAG,IAAIhC,CAAK,EACnCK,EAAOH,EAAYC,EAAKR,CAAI,EAC5BuB,EAAQb,GAAM,MAAQuB,EAAY,QAAQvB,EAAK,MAAM,CAAC,CAAC,EAAI,CAAE,KAAM,EAAG,IAAK,CAAE,EACnF,OAAOP,EAAMkC,EAAM,QAASrC,EAAMuB,EAAM,KAAMA,EAAM,GAAG,CACxD,CAAC,CACF,CACD,CAQO,SAASmB,EAAazC,EAAc8B,EAA2BC,EAA+B,CACpG,IAAMS,EAASX,EAAc7B,EAAM8B,EAAUC,CAAO,EACpD,GAAI,CAACS,EAAO,QACX,MAAM,IAAI7C,EAAkB6C,EAAO,MAAM,EAE1C,OAAOA,EAAO,IACf",
6
+ "names": ["LineCounter", "isNode", "parseDocument", "YamlDocumentError", "issues", "formatIssue", "formatPath", "path", "text", "key", "issue", "location", "toKey", "segment", "nodeForPath", "doc", "length", "node", "MAX_ALIAS_COUNT", "syntaxMessage", "message", "samePosition", "a", "b", "shortTag", "tag", "prefix", "friendlyMessage", "problem", "positionOf", "start", "end", "parserProblems", "multiline", "error", "other", "conversionMessage", "safeParseYaml", "validate", "options", "lineCounter", "source", "line", "column", "found", "problems", "position", "value", "result", "parseYaml"]
7
+ }
File without changes
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1 @@
1
+ var i=class extends Error{code;kind;$type;key;childPath;outerChildPath;constructor(r,n,e){super(n),this.name="RegistryError",this.code=r,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{i 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 * - `'schema-without-json-schema'`: {@link exportTreeSchema} met a registration (`$type`) whose schema sets no\n * `~standard.jsonSchema`, while its `resolve` was the default.\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| 'schema-without-json-schema'\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": "AA0FO,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
+ }
@@ -0,0 +1 @@
1
+ import{a as $,c as u}from"./chunk-GX6PAJLU.js";import{a as N}from"./chunk-BY4BKVNV.js";var x=new Set(["const","enum","default","examples"]),E=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),y=e=>e==="#"||e.startsWith("#/"),l=e=>e==="draft-04"?"id":"$id",b=(e,n)=>{let t=e[l(n)];return typeof t=="string"&&!t.startsWith("#")};function m(e,n,t,s=!0){if(Array.isArray(e))return e.map(o=>m(o,n,t,!1));if(!u(e))return e;if(!s&&b(e,n))return structuredClone(e);let i={};for(let[o,c]of Object.entries(e))typeof c=="string"?i[o]=t(o,c):x.has(o)?i[o]=structuredClone(c):E.has(o)&&u(c)?i[o]=Object.fromEntries(Object.entries(c).map(([r,a])=>[r,m(a,n,t,!1)])):i[o]=m(c,n,t,!1);return i}function R(e,n){let t=new Set,s=l(n);return m(e,n,(i,o)=>(i==="$anchor"||i==="$dynamicAnchor"?t.add(o):i===s&&o.startsWith("#")&&t.add(o.slice(1)),o)),t}function A(e,n,t){let s=l(n),i=t.anchor?R(e,n):new Set,o=c=>t.anchor&&i.has(c)?t.anchor(c):c;return m(e,n,(c,r)=>c==="$anchor"||c==="$dynamicAnchor"?o(r):c===s&&r.startsWith("#")?`#${o(r.slice(1))}`:c!=="$ref"&&c!=="$dynamicRef"?r:y(r)?t.pointer?t.pointer(r):r:r.startsWith("#")?`#${o(r.slice(1))}`:r)}function g(e){let{$schema:n,...t}=e;return structuredClone(t)}function D(e,n){let t=!1;return m(e,n,(s,i)=>(s==="$ref"&&y(i)&&(t=!0),i)),t}function J(e,n){let t=l(n),s=e[t];if(typeof s!="string"||!s.startsWith("#"))return e;let{[t]:i,...o}=m(e,n,(c,r)=>(c==="$ref"||c==="$dynamicRef")&&r===s?"#":r);return o}var T=e=>e==="draft-2020-12"?"$defs":"definitions";function M(e,n){$(e);let t=T(e),s=l(e),i={},o=new Map,c=0;return{embed(r){let a=g(r);if(b(a,e))return a;let d=D(a,e);if(!d&&R(a,e).size===0)return a;c+=1;let h=`embedded-${c}`;if(d&&n.kind==="collection"){let O=n.uri(h);return i[h]={...r.$schema===void 0?{}:{$schema:r.$schema},...J(a,e),[s]:O},{$ref:O}}let f=w(e,h),S=A(a,e,{pointer:d?O=>`${f}${O.slice(1)}`:void 0,anchor:O=>`${h}-${O}`});return d?(i[h]=S,{$ref:f}):S},embedDefinition(r,a){if(n.kind==="collection"){let f=J(g(r),e);return b(f,e)?{allOf:[{$ref:f[s]}],[t]:{[a]:f}}:f}let{definition:d,nested:h}=K(r,a,e);for(let[f,S]of Object.entries(h)){if(Object.hasOwn(i,f))throw p(a,f);i[f]=S,o.set(f,a)}return d},finish(r){if(Object.keys(i).length===0)return r;let a=n.kind==="collection"?"schemas":t,d=u(r[a])?r[a]:{};for(let h of Object.keys(i)){if(!Object.hasOwn(d,h))continue;let f=o.get(h);throw f===void 0?new Error(`The embedder reserves '${h}'; the document already defines it.`):p(f,h)}return r[a]={...d,...i},r}}}function p(e,n){return new N("definition-name-clash",`The definition '${n}' that '${e}' brought along takes the name of another definition of the export.`,{$type:e,key:n})}function k(e,n){let t="";for(let s of e)t+=n.test(s)?s:`_${s.codePointAt(0).toString(16)}_`;return t}var C=e=>`o${k(e,/[A-Za-z0-9-]/)}`,P=(e,n)=>`${k(e,/[^._]/)}.${n}`;function W(e){return encodeURIComponent(e.replaceAll("~","~0").replaceAll("/","~1")).replaceAll(/%(?:24|26|2B|2C|3A|3B|3D|40)/g,decodeURIComponent)}function w(e,n){return`#/${T(e)}/${W(n)}`}var _=e=>e==="$defs"||e==="definitions";function j(e){return decodeURIComponent(e).replaceAll("~1","/").replaceAll("~0","~")}function K(e,n,t){let s=g(e);if(b(s,t))return{definition:s,nested:{}};let i=d=>P(n,d),o=d=>w(t,d),c=C(n),r=A(s,t,{pointer(d){if(d==="#")return o(n);let h=d.slice(2).split("/"),[f,S,...O]=h;return f!==void 0&&_(j(f))&&S!==void 0?[o(i(j(S))),...O].join("/"):`${o(n)}/${h.join("/")}`},anchor:d=>`${c}.${d}`}),a={};for(let d of["$defs","definitions"]){let h=r[d];if(u(h)){for(let[f,S]of Object.entries(h)){if(Object.hasOwn(a,i(f)))throw p(n,i(f));a[i(f)]=S}delete r[d]}}return{definition:r,nested:a}}export{l as a,b,T as c,M as d,W as e,w as f};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/json-schema/embedder.ts"],
4
+ "sourcesContent": ["import { RegistryError } from '../registry-error.js';\nimport { assertJSONSchemaTarget, isPlainObject, type JSONSchemaObject, type JSONSchemaTarget } from './standard.js';\n\n/** Where the JSON Schema being written keeps its definitions. */\nexport type JSONSchemaPlacement =\n\t| { readonly kind: 'document' }\n\t| {\n\t\t\treadonly kind: 'collection';\n\t\t\t/** The URI the collection refers to an entry by. */\n\t\t\treadonly uri: (id: string) => string;\n\t };\n\n/** Keywords whose value is data rather than a schema, so a `$ref` key inside it is not a reference. */\nconst DATA_KEYWORDS = new Set(['const', 'enum', 'default', 'examples']);\n\n/** Keywords whose value maps names to schemas, so a key there is a name rather than a keyword. */\nconst NAMED_SCHEMA_KEYWORDS = new Set([\n\t'properties',\n\t'patternProperties',\n\t'$defs',\n\t'definitions',\n\t'dependentSchemas',\n\t'dependencies',\n]);\n\nconst isLocalPointer = (ref: string): boolean => ref === '#' || ref.startsWith('#/');\n\n/** The keyword a target writes a schema's identifier under: `id` for draft-04, `$id` for every other target. */\nexport const idKeyword = (target: JSONSchemaTarget): 'id' | '$id' => (target === 'draft-04' ? 'id' : '$id');\n\n/**\n * Whether a schema is the root of a resource of its own, which resolves its references against itself: it sets the\n * identifier of its target ({@link idKeyword}) to something other than a fragment. An identifier that is only a\n * fragment (`#node`) names an anchor instead.\n */\nexport const startsResource = (schema: Record<string, unknown>, target: JSONSchemaTarget): boolean => {\n\tconst id = schema[idKeyword(target)];\n\treturn typeof id === 'string' && !id.startsWith('#');\n};\n\n/**\n * A copy of a schema's root resource with `rewrite` applied to each string keyword of every schema in it. A keyword\n * is replaced where `rewrite` returns another value.\n *\n * @remarks\n * A subschema with its own identifier (`$id`, or `id` for draft-04) is another resource: its references and anchors are\n * relative to it, not to the schema being embedded, so it is copied as it is. The root is walked whatever its\n * identifier; the embedder embeds a root that starts a resource as it is.\n */\nfunction mapResource(\n\tnode: unknown,\n\ttarget: JSONSchemaTarget,\n\trewrite: (keyword: string, value: string) => string,\n\tisRoot = true,\n): unknown {\n\tif (Array.isArray(node)) return node.map((item) => mapResource(item, target, rewrite, false));\n\tif (!isPlainObject(node)) return node;\n\tif (!isRoot && startsResource(node, target)) return structuredClone(node);\n\tconst copy: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(node)) {\n\t\tif (typeof value === 'string') copy[key] = rewrite(key, value);\n\t\telse if (DATA_KEYWORDS.has(key)) copy[key] = structuredClone(value);\n\t\telse if (NAMED_SCHEMA_KEYWORDS.has(key) && isPlainObject(value)) {\n\t\t\tcopy[key] = Object.fromEntries(\n\t\t\t\tObject.entries(value).map(([name, schema]) => [name, mapResource(schema, target, rewrite, false)]),\n\t\t\t);\n\t\t} else copy[key] = mapResource(value, target, rewrite, false);\n\t}\n\treturn copy;\n}\n\n/**\n * The anchor names a schema's root resource declares: `$anchor`, `$dynamicAnchor` and the fragment identifier the\n * target writes ({@link idKeyword}).\n */\nfunction declaredAnchors(schema: JSONSchemaObject, target: JSONSchemaTarget): Set<string> {\n\tconst names = new Set<string>();\n\tconst fragment = idKeyword(target);\n\tmapResource(schema, target, (keyword, value) => {\n\t\tif (keyword === '$anchor' || keyword === '$dynamicAnchor') names.add(value);\n\t\telse if (keyword === fragment && value.startsWith('#')) names.add(value.slice(1));\n\t\treturn value;\n\t});\n\treturn names;\n}\n\n/**\n * A copy of a schema's root resource with its local JSON Pointer references passed through `pointer`, and each\n * anchor it declares, with the `#name` references to it, renamed by `anchor`.\n */\nfunction rewriteResource(\n\tschema: JSONSchemaObject,\n\ttarget: JSONSchemaTarget,\n\trewrite: { readonly pointer?: (pointer: string) => string; readonly anchor?: (name: string) => string },\n): JSONSchemaObject {\n\tconst fragment = idKeyword(target);\n\tconst anchors = rewrite.anchor ? declaredAnchors(schema, target) : new Set<string>();\n\tconst renamed = (name: string) => (rewrite.anchor && anchors.has(name) ? rewrite.anchor(name) : name);\n\treturn mapResource(schema, target, (keyword, value) => {\n\t\tif (keyword === '$anchor' || keyword === '$dynamicAnchor') return renamed(value);\n\t\tif (keyword === fragment && value.startsWith('#')) return `#${renamed(value.slice(1))}`;\n\t\tif (keyword !== '$ref' && keyword !== '$dynamicRef') return value;\n\t\tif (isLocalPointer(value)) return rewrite.pointer ? rewrite.pointer(value) : value;\n\t\treturn value.startsWith('#') ? `#${renamed(value.slice(1))}` : value;\n\t}) as JSONSchemaObject;\n}\n\nfunction withoutSchemaKeyword(schema: JSONSchemaObject): JSONSchemaObject {\n\tconst { $schema: _dropped, ...rest } = schema;\n\treturn structuredClone(rest);\n}\n\nfunction hasLocalRef(schema: JSONSchemaObject, target: JSONSchemaTarget): boolean {\n\tlet found = false;\n\tmapResource(schema, target, (keyword, value) => {\n\t\tif (keyword === '$ref' && isLocalPointer(value)) found = true;\n\t\treturn value;\n\t});\n\treturn found;\n}\n\n/**\n * A copy of a schema without its root's fragment identifier (`$id: '#node'`, `id: '#node'` for draft-04), with the\n * `#node` references to it pointing at the root as `#`. A schema without one is returned as it is.\n *\n * @remarks\n * A fragment identifier is an anchor, and a root has only one identifier, which an entry of a collection needs for its\n * URI. The anchor can only name the root, so `#` says the same within the entry, which is a resource of its own by\n * that URI. Anchors below the root are kept, and the root's other keywords are untouched.\n */\nfunction withoutRootAnchor(schema: JSONSchemaObject, target: JSONSchemaTarget): JSONSchemaObject {\n\tconst keyword = idKeyword(target);\n\tconst root = schema[keyword];\n\tif (typeof root !== 'string' || !root.startsWith('#')) return schema;\n\tconst { [keyword]: _anchor, ...rest } = mapResource(schema, target, (name, value) =>\n\t\t(name === '$ref' || name === '$dynamicRef') && value === root ? '#' : value,\n\t) as JSONSchemaObject;\n\treturn rest;\n}\n\n/** The keyword a document keeps its definitions under, as Zod writes it for the target. */\nexport const definitionsKeyword = (target: JSONSchemaTarget): '$defs' | 'definitions' =>\n\ttarget === 'draft-2020-12' ? '$defs' : 'definitions';\n\n/**\n * Embeds JSON Schemas that were written as documents of their own (by a Standard JSON Schema converter or a separate\n * Zod conversion) into one JSON Schema being written.\n */\nexport interface JSONSchemaEmbedder {\n\t/** The schema to write in place of `own`, which is not changed. */\n\tembed(own: JSONSchemaObject): JSONSchemaObject;\n\t/**\n\t * The schema to write as the definition named `name` of a document, or as the entry of that name of a collection,\n\t * where `own` is not changed.\n\t *\n\t * @remarks\n\t * The schema stays at its own place, so a container found by its name is the schema itself and not a reference to\n\t * another definition. In a document, `#` points at the definition, a pointer into the schema's own definitions at the\n\t * definition lifted to the document as `<name>.<its name>` and anchors are renamed under `name`, as\n\t * {@link createJSONSchemaEmbedder} explains. In a collection the entry is its own resource, so the schema is kept as it is, with\n\t * its own definitions, without `$schema`, and a root fragment identifier (`$id: '#node'`, `id: '#node'` for draft-04) is\n\t * dropped with its references turned into `#`, since the entry is addressed by the identifier the collection gives\n\t * it. A schema with an identifier of its own (`$id`, or `id` for draft-04) is a\n\t * resource that keeps its base: in a document it is kept as it is, and in a collection the entry is an `allOf` of a\n\t * reference to it, with the schema beside it under the name (a `$ref` beside other keywords is ignored before 2019-09), so the entry keeps the collection's URI and the schema keeps its\n\t * identifier.\n\t */\n\tembedDefinition(own: JSONSchemaObject, name: string): JSONSchemaObject;\n\t/**\n\t * Adds the definitions `embed` and `embedDefinition` moved to the finished document or collection, in place.\n\t *\n\t * @throws {RegistryError} Code `'definition-name-clash'` when a definition `embedDefinition` lifted takes a name\n\t * `written` already defines\n\t * @throws {Error} When `written` already defines an `embedded-<n>` key `embed` hoisted: the embedder reserves them\n\t */\n\tfinish(written: JSONSchemaObject): JSONSchemaObject;\n}\n\n/**\n * Create the embedder for one JSON Schema being written.\n *\n * @param target - The target the schema is written for\n * @throws {Error} When `target` is not one of the four {@link JSONSchemaTarget}s, before anything is embedded\n * @param placement - Whether it is one document or a collection of entries\n *\n * @remarks\n * `$schema` is dropped, since the document being written declares the dialect. A schema whose `$ref` points into\n * itself from its root (`#`, `#/$defs/node`, as ArkType writes a recursive type) would point at the wrong root once\n * embedded, so it is hoisted: in a document, into its definitions under a key of its own (`embedded-1`), with each of\n * its local pointers prefixed by that place; in a collection, as an entry of its own, referred to by its URI. The\n * references stay `#/...` pointers and `#name` anchors, which is what AI tool APIs resolve, rather than `$id` URIs (`id` for draft-04).\n *\n * A plain-name anchor (`$anchor`, `$dynamicAnchor`, a draft-07 `$id: '#node'`, a draft-04 `id: '#node'`) resolves anywhere in the document, so\n * two schemas that each declare `node` would declare it twice. Each embedded schema's anchors, and the `#node`\n * references to them, are renamed to carry its key (`embedded-1-node`), whether it is hoisted into a document or\n * embedded where it stands. A schema hoisted into a collection is a resource of its own by its `$id` (`id` for draft-04), which scopes\n * its anchors, so they keep their names. Only a root fragment identifier (`$id: '#node'`, `id: '#node'` for draft-04) cannot stay: the entry's identifier is its\n * assigned URI, so the root's anchor is dropped and its `#node` references become `#`, as\n * {@link withoutRootAnchor} explains.\n *\n * Only the schema's root resource is rewritten. A schema with its own `$id` (`id` for draft-04), and any subschema that sets one, resolves\n * its pointers and anchors against that and is left as it is.\n *\n * A definition written into a document by `embedDefinition(own, owner)` is named, and its anchors renamed, by the\n * owner, so that no two owners share a name:\n *\n * - A definition `name` of the schema's own `$defs` (`definitions` for a draft-07 target) is lifted to\n * `<owner>.<name>`, with the owner written so that it holds no `.`: each `.` and `_` in it is replaced by `_` and its\n * code point in hex and `_` again (`_2e_`, `_5f_`), any other character stays. Owner `element:a.b` with a definition\n * `c` is lifted as `element:a_2e_b.c` and owner `element:a` with `b.c` as `element:a.b.c`, so the first `.` of a\n * lifted name always ends the owner.\n * - An anchor `name` is renamed `<owner part>.<name>`, where the owner part is `o` followed by the owner with every\n * character outside `[A-Za-z0-9-]` (`.` and `_` included) replaced by `_`, its code point in hex and `_` (`ui/button`\n * becomes `oui_2f_button`, `a.b` becomes `oa_2e_b`, `my-card` stays `omy-card`). The part starts with a letter, holds\n * only characters every dialect allows in an anchor, and no `.`, so the first `.` ends it, and the keys of `embed`\n * (`embedded-1`) never start with `o`.\n *\n * In both, the owner part never holds a `.`, and a `_` in the owner is always escaped, so the first `.` ends the owner\n * and its `_<hex>_` tokens decode one way. Both are one-to-one, so two owners never write the same name. A name that is still taken, by another definition\n * lifted into the document or one `finish` finds in the document it completes, is a `RegistryError` with the code\n * `'definition-name-clash'`; nothing is overwritten.\n */\nexport function createJSONSchemaEmbedder(target: JSONSchemaTarget, placement: JSONSchemaPlacement): JSONSchemaEmbedder {\n\tassertJSONSchemaTarget(target);\n\tconst keyword = definitionsKeyword(target);\n\tconst id = idKeyword(target);\n\tconst hoisted: Record<string, JSONSchemaObject> = {};\n\tconst ownerOf = new Map<string, string>();\n\tlet count = 0;\n\treturn {\n\t\tembed(own) {\n\t\t\tconst body = withoutSchemaKeyword(own);\n\t\t\tif (startsResource(body, target)) return body;\n\t\t\tconst pointsIntoItself = hasLocalRef(body, target);\n\t\t\tif (!pointsIntoItself && declaredAnchors(body, target).size === 0) return body;\n\t\t\tcount += 1;\n\t\t\tconst key = `embedded-${count}`;\n\t\t\tif (pointsIntoItself && placement.kind === 'collection') {\n\t\t\t\tconst ref = placement.uri(key);\n\t\t\t\thoisted[key] = {\n\t\t\t\t\t...(own.$schema === undefined ? {} : { $schema: own.$schema }),\n\t\t\t\t\t...withoutRootAnchor(body, target),\n\t\t\t\t\t[id]: ref,\n\t\t\t\t};\n\t\t\t\treturn { $ref: ref };\n\t\t\t}\n\t\t\tconst ref = definitionRef(target, key);\n\t\t\tconst rewritten = rewriteResource(body, target, {\n\t\t\t\tpointer: pointsIntoItself ? (pointer) => `${ref}${pointer.slice(1)}` : undefined,\n\t\t\t\tanchor: (name) => `${key}-${name}`,\n\t\t\t});\n\t\t\tif (!pointsIntoItself) return rewritten;\n\t\t\thoisted[key] = rewritten;\n\t\t\treturn { $ref: ref };\n\t\t},\n\t\tembedDefinition(own, name) {\n\t\t\tif (placement.kind === 'collection') {\n\t\t\t\tconst entry = withoutRootAnchor(withoutSchemaKeyword(own), target);\n\t\t\t\tif (!startsResource(entry, target)) return entry;\n\t\t\t\treturn { allOf: [{ $ref: entry[id] }], [keyword]: { [name]: entry } };\n\t\t\t}\n\t\t\tconst { definition, nested } = hoistDefinitions(own, name, target);\n\t\t\tfor (const [lifted, schema] of Object.entries(nested)) {\n\t\t\t\tif (Object.hasOwn(hoisted, lifted)) throw definitionNameClash(name, lifted);\n\t\t\t\thoisted[lifted] = schema;\n\t\t\t\townerOf.set(lifted, name);\n\t\t\t}\n\t\t\treturn definition;\n\t\t},\n\t\tfinish(written) {\n\t\t\tif (Object.keys(hoisted).length === 0) return written;\n\t\t\tconst field = placement.kind === 'collection' ? 'schemas' : keyword;\n\t\t\tconst existing: JSONSchemaObject = isPlainObject(written[field]) ? written[field] : {};\n\t\t\tfor (const key of Object.keys(hoisted)) {\n\t\t\t\tif (!Object.hasOwn(existing, key)) continue;\n\t\t\t\tconst owner = ownerOf.get(key);\n\t\t\t\tif (owner === undefined)\n\t\t\t\t\tthrow new Error(`The embedder reserves '${key}'; the document already defines it.`);\n\t\t\t\tthrow definitionNameClash(owner, key);\n\t\t\t}\n\t\t\twritten[field] = { ...existing, ...hoisted };\n\t\t\treturn written;\n\t\t},\n\t};\n}\n\n/** The error for a definition `key` that `owner` brought along and that takes a name another definition holds. */\nfunction definitionNameClash(owner: string, key: string): RegistryError {\n\treturn new RegistryError(\n\t\t'definition-name-clash',\n\t\t`The definition '${key}' that '${owner}' brought along takes the name of another definition of the export.`,\n\t\t{ $type: owner, key },\n\t);\n}\n\n/** `text` with each character that `keep` does not match written as `_`, its code point in hex and `_`. */\nfunction escapeCharacters(text: string, keep: RegExp): string {\n\tlet written = '';\n\tfor (const char of text) written += keep.test(char) ? char : `_${char.codePointAt(0)!.toString(16)}_`;\n\treturn written;\n}\n\n/**\n * The owner part of an anchor name: `o` and the owner with every character outside `[A-Za-z0-9-]` written as `_`, its\n * code point in hex and `_` (`ui/button` becomes `oui_2f_button`, `my-card` stays `omy-card`).\n *\n * @remarks\n * The part holds no `.`, so the first `.` of `<owner part>.<name>` ends it, and it escapes `_` as well, so a literal `_`\n * is never read as the start of an escape: two owners never share a part. It starts with a letter and holds only\n * `[A-Za-z0-9_-]`, which every dialect allows in an anchor name (`^[A-Za-z][-A-Za-z0-9._]*$`), whatever the owner is\n * called. No owner is kept as it is, since an owner that was kept could be mistaken for a written one.\n */\nconst anchorOwnerPart = (owner: string): string => `o${escapeCharacters(owner, /[A-Za-z0-9-]/)}`;\n\n/**\n * The name a definition of an owner takes in a document of definitions: `<owner part>.<name>`, with the owner part\n * written without a `.` (`.` and `_` become `_2e_` and `_5f_`, other characters stay).\n *\n * @remarks\n * The owner part holds no `.`, so the first `.` ends it and two (owner, name) pairs never write the same name, while an\n * owner like `element:tab` reads as written.\n */\nconst liftedName = (owner: string, name: string): string => `${escapeCharacters(owner, /[^._]/)}.${name}`;\n\n/**\n * A JSON Pointer reference token, written for a URI fragment: `~` and `/` escaped, then percent-encoded for what a\n * fragment does not allow.\n *\n * @remarks\n * RFC 3986 lets a fragment hold the `pchar` characters raw, so `:`, `@` and the sub-delimiters (`$&+,;=` and `!'()*`)\n * stay as they are and a name like `element:tab` reads as written.\n */\nexport function pointerToken(name: string): string {\n\treturn encodeURIComponent(name.replaceAll('~', '~0').replaceAll('/', '~1')).replaceAll(\n\t\t/%(?:24|26|2B|2C|3A|3B|3D|40)/g,\n\t\tdecodeURIComponent,\n\t);\n}\n\n/**\n * The `$ref` to the definition of a name in a document written for a target: `#/$defs/<name>` for `'draft-2020-12'`,\n * `#/definitions/<name>` for every other target, with the name written as a JSON Pointer token.\n *\n * @param target - The target the document is written for, which decides the keyword of its definitions\n * @param name - The key of the definition, for example `'ui/button'`\n *\n * @remarks\n * A name holds any character. `~` and `/` are escaped as the pointer syntax requires, and what a URI fragment does not\n * allow (a space, `%`, `#`, `?`) is percent-encoded, so a tool that resolves the reference finds the key whatever the\n * name is.\n */\nexport function definitionRef(target: JSONSchemaTarget, name: string): string {\n\treturn `#/${definitionsKeyword(target)}/${pointerToken(name)}`;\n}\n\nconst isDefinitionsKeyword = (keyword: string): boolean => keyword === '$defs' || keyword === 'definitions';\n\n/**\n * A pointer reference token as the document it points into names it: percent-decoded, since a URI fragment is\n * percent-decoded before it is read as a JSON Pointer (RFC 6901, section 6), then with `~1` and `~0` unescaped.\n */\nfunction unescapedToken(token: string): string {\n\treturn decodeURIComponent(token).replaceAll('~1', '/').replaceAll('~0', '~');\n}\n\n/**\n * A JSON Schema that was written as a document of its own, split into the definition it becomes and the definitions it\n * brought along.\n */\ninterface HoistedDefinitions {\n\t/** The schema to keep under the owner's name in the document's definitions. */\n\treadonly definition: JSONSchemaObject;\n\t/** The definitions of `own`, by the name each takes in the document, as {@link liftedName} writes it. */\n\treadonly nested: Readonly<Record<string, JSONSchemaObject>>;\n}\n\n/**\n * Move a schema written as a document of its own to where it resolves in a document of definitions, under the name of\n * its owner.\n *\n * @param own - The schema, which is not changed\n * @param owner - The name its definition takes in the document, for example a `$type`\n * @param target - The target the document is written for, which decides the definitions keyword\n * @throws {RegistryError} Code `'definition-name-clash'` when `$defs` and `definitions` both define one name\n *\n * @remarks\n * The schema's own definitions (`$defs`, or `definitions` for a draft-07 target) are lifted out and named under their\n * owner as {@link liftedName} does, so the document's definitions stay one flat list. Every local pointer follows: `#`\n * points at the owner's definition, `#/$defs/name` at the lifted one, and any other `#/...` pointer into the owner's\n * definition. Anchors and `$schema` are handled as {@link createJSONSchemaEmbedder} does, each anchor named\n * `<owner part>.<name>` as {@link anchorOwnerPart} writes the owner part. The caller checks the names it gets back\n * against the ones it already holds. A schema with an `$id` (`id` for draft-04) of its own is a resource that resolves itself, so it is\n * kept as it is.\n */\nfunction hoistDefinitions(own: JSONSchemaObject, owner: string, target: JSONSchemaTarget): HoistedDefinitions {\n\tconst body = withoutSchemaKeyword(own);\n\tif (startsResource(body, target)) return { definition: body, nested: {} };\n\tconst nameOf = (name: string) => liftedName(owner, name);\n\tconst place = (name: string) => definitionRef(target, name);\n\tconst ownerPart = anchorOwnerPart(owner);\n\tconst rewritten = rewriteResource(body, target, {\n\t\tpointer(pointer) {\n\t\t\tif (pointer === '#') return place(owner);\n\t\t\tconst tokens = pointer.slice(2).split('/');\n\t\t\tconst [head, name, ...rest] = tokens;\n\t\t\tif (head !== undefined && isDefinitionsKeyword(unescapedToken(head)) && name !== undefined) {\n\t\t\t\treturn [place(nameOf(unescapedToken(name))), ...rest].join('/');\n\t\t\t}\n\t\t\treturn `${place(owner)}/${tokens.join('/')}`;\n\t\t},\n\t\tanchor: (name) => `${ownerPart}.${name}`,\n\t});\n\tconst nested: Record<string, JSONSchemaObject> = {};\n\tfor (const field of ['$defs', 'definitions']) {\n\t\tconst lifted = rewritten[field];\n\t\tif (!isPlainObject(lifted)) continue;\n\t\tfor (const [name, schema] of Object.entries(lifted)) {\n\t\t\tif (Object.hasOwn(nested, nameOf(name))) throw definitionNameClash(owner, nameOf(name));\n\t\t\tnested[nameOf(name)] = schema as JSONSchemaObject;\n\t\t}\n\t\tdelete rewritten[field];\n\t}\n\treturn { definition: rewritten, nested };\n}\n"],
5
+ "mappings": "uFAaA,IAAMA,EAAgB,IAAI,IAAI,CAAC,QAAS,OAAQ,UAAW,UAAU,CAAC,EAGhEC,EAAwB,IAAI,IAAI,CACrC,aACA,oBACA,QACA,cACA,mBACA,cACD,CAAC,EAEKC,EAAkBC,GAAyBA,IAAQ,KAAOA,EAAI,WAAW,IAAI,EAGtEC,EAAaC,GAA4CA,IAAW,WAAa,KAAO,MAOxFC,EAAiB,CAACC,EAAiCF,IAAsC,CACrG,IAAMG,EAAKD,EAAOH,EAAUC,CAAM,CAAC,EACnC,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AqBC,EAAeM,CAAI,CAAC,GAAKtD,IAAS,OACzE,CAACmD,EAAMD,EAAOF,EAAehD,CAAI,CAAC,CAAC,EAAG,GAAGU,CAAI,EAAE,KAAK,GAAG,EAExD,GAAGyC,EAAMb,CAAK,CAAC,IAAIe,EAAO,KAAK,GAAG,CAAC,EAC3C,EACA,OAASrD,GAAS,GAAGoD,CAAS,IAAIpD,CAAI,EACvC,CAAC,EACK+B,EAA2C,CAAC,EAClD,QAAWK,IAAS,CAAC,QAAS,aAAa,EAAG,CAC7C,IAAMH,EAASN,EAAUS,CAAK,EAC9B,GAAKxC,EAAcqC,CAAM,EACzB,QAAW,CAACjC,EAAMX,CAAM,IAAK,OAAO,QAAQ4C,CAAM,EAAG,CACpD,GAAI,OAAO,OAAOF,EAAQmB,EAAOlD,CAAI,CAAC,EAAG,MAAMkC,EAAoBI,EAAOY,EAAOlD,CAAI,CAAC,EACtF+B,EAAOmB,EAAOlD,CAAI,CAAC,EAAIX,CACxB,CACA,OAAOsC,EAAUS,CAAK,EACvB,CACA,MAAO,CAAE,WAAYT,EAAW,OAAAI,CAAO,CACxC",
6
+ "names": ["DATA_KEYWORDS", "NAMED_SCHEMA_KEYWORDS", "isLocalPointer", "ref", "idKeyword", "target", "startsResource", "schema", "id", "mapResource", "node", "rewrite", "isRoot", "item", "isPlainObject", "copy", "key", "value", "name", "declaredAnchors", "names", "fragment", "keyword", "rewriteResource", "anchors", "renamed", "withoutSchemaKeyword", "_dropped", "rest", "hasLocalRef", "found", "withoutRootAnchor", "root", "_anchor", "definitionsKeyword", "createJSONSchemaEmbedder", "placement", "assertJSONSchemaTarget", "hoisted", "ownerOf", "count", "own", "body", "pointsIntoItself", "definitionRef", "rewritten", "pointer", "entry", "definition", "nested", "hoistDefinitions", "lifted", "definitionNameClash", "written", "field", "existing", "owner", "RegistryError", "escapeCharacters", "text", "keep", "char", "anchorOwnerPart", "liftedName", "pointerToken", "isDefinitionsKeyword", "unescapedToken", "token", "nameOf", "place", "ownerPart", "tokens", "head"]
7
+ }
@@ -0,0 +1,3 @@
1
+ import{Document as f,isPair as u,isScalar as s,visit as c}from"yaml";var g=3,m=48;function y(n){if(n.items.length===0||n.items.length>g)return!1;let r=0;for(let e of n.items){if(!s(e.key)||!s(e.value))return!1;let i=String(e.value.value);if(i.includes(`
2
+ `))return!1;r+=String(e.key.value).length+i.length+4}return r<=m}function p(n,r){let e=r?.schemaUrl;if(e!==void 0&&/[\r\n]/.test(e))throw new TypeError("schemaUrl must be a single line");let i=new f(n,{version:"1.2",aliasDuplicateObjects:!1});c(i,{Pair(a,t){s(t.key)&&t.key.value==="<<"&&(t.key.type="QUOTE_DOUBLE")},Map(a,t,o){u(o.at(-1))&&y(t)&&(t.flow=!0)}});let l=i.toString({lineWidth:0});return e===void 0?l:`# yaml-language-server: $schema=${e}
3
+ ${l}`}export{p as a};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/yaml/stringify.ts"],
4
+ "sourcesContent": ["import { Document, isPair, isScalar, visit } from 'yaml';\nimport type { YAMLMap } from 'yaml';\n\n/**\n * Limits for a map written in flow style: scalar entries only, at most this many, and about this\n * many characters.\n *\n * @remarks\n * `grid: { width: half }` reads better inline; an element with many keys does not.\n */\nconst MAX_FLOW_ENTRIES = 3;\nconst MAX_FLOW_LENGTH = 48;\n\nexport type StringifyYamlOptions = {\n\t/** Adds a `# yaml-language-server: $schema=<url>` header, which editors read to offer completion. */\n\tschemaUrl?: string;\n};\n\nfunction isShortLeafMap(map: YAMLMap): boolean {\n\tif (map.items.length === 0 || map.items.length > MAX_FLOW_ENTRIES) {\n\t\treturn false;\n\t}\n\tlet length = 0;\n\tfor (const pair of map.items) {\n\t\tif (!isScalar(pair.key) || !isScalar(pair.value)) {\n\t\t\treturn false;\n\t\t}\n\t\tconst value = String(pair.value.value);\n\t\tif (value.includes('\\n')) {\n\t\t\treturn false;\n\t\t}\n\t\tlength += String(pair.key.value).length + value.length + 4;\n\t}\n\treturn length <= MAX_FLOW_LENGTH;\n}\n\n/**\n * Write a value as YAML text.\n *\n * @remarks\n * An object that appears twice is written out twice, not as an anchor and an alias. A short map of\n * scalars under a key is written in flow style (`grid: { width: half }`); every other collection,\n * including a sequence item, is written in block style. Lines are not folded.\n * Strings that would read as another type are quoted, so `\"1.10\"` stays a string when parsed back,\n * and so is a key named `<<`, which `parseYaml` would otherwise read as a merge key.\n * `no` and `on` are not quoted, because YAML 1.2 reads them as strings; a YAML 1.1 reader would not.\n */\nexport function stringifyYaml(value: unknown, options?: StringifyYamlOptions): string {\n\tconst schemaUrl = options?.schemaUrl;\n\tif (schemaUrl !== undefined && /[\\r\\n]/.test(schemaUrl)) {\n\t\tthrow new TypeError('schemaUrl must be a single line');\n\t}\n\tconst doc = new Document(value, { version: '1.2', aliasDuplicateObjects: false });\n\tvisit(doc, {\n\t\tPair(_key, pair) {\n\t\t\tif (isScalar(pair.key) && pair.key.value === '<<') {\n\t\t\t\tpair.key.type = 'QUOTE_DOUBLE';\n\t\t\t}\n\t\t},\n\t\tMap(_key, map, path) {\n\t\t\tif (isPair(path.at(-1)) && isShortLeafMap(map)) {\n\t\t\t\tmap.flow = true;\n\t\t\t}\n\t\t},\n\t});\n\tconst text = doc.toString({ lineWidth: 0 });\n\treturn schemaUrl === undefined ? text : `# yaml-language-server: $schema=${schemaUrl}\\n${text}`;\n}\n"],
5
+ "mappings": "AAAA,OAAS,YAAAA,EAAU,UAAAC,EAAQ,YAAAC,EAAU,SAAAC,MAAa,OAUlD,IAAMC,EAAmB,EACnBC,EAAkB,GAOxB,SAASC,EAAeC,EAAuB,CAC9C,GAAIA,EAAI,MAAM,SAAW,GAAKA,EAAI,MAAM,OAASH,EAChD,MAAO,GAER,IAAII,EAAS,EACb,QAAWC,KAAQF,EAAI,MAAO,CAC7B,GAAI,CAACL,EAASO,EAAK,GAAG,GAAK,CAACP,EAASO,EAAK,KAAK,EAC9C,MAAO,GAER,IAAMC,EAAQ,OAAOD,EAAK,MAAM,KAAK,EACrC,GAAIC,EAAM,SAAS;AAAA,CAAI,EACtB,MAAO,GAERF,GAAU,OAAOC,EAAK,IAAI,KAAK,EAAE,OAASC,EAAM,OAAS,CAC1D,CACA,OAAOF,GAAUH,CAClB,CAaO,SAASM,EAAcD,EAAgBE,EAAwC,CACrF,IAAMC,EAAYD,GAAS,UAC3B,GAAIC,IAAc,QAAa,SAAS,KAAKA,CAAS,EACrD,MAAM,IAAI,UAAU,iCAAiC,EAEtD,IAAMC,EAAM,IAAId,EAASU,EAAO,CAAE,QAAS,MAAO,sBAAuB,EAAM,CAAC,EAChFP,EAAMW,EAAK,CACV,KAAKC,EAAMN,EAAM,CACZP,EAASO,EAAK,GAAG,GAAKA,EAAK,IAAI,QAAU,OAC5CA,EAAK,IAAI,KAAO,eAElB,EACA,IAAIM,EAAMR,EAAKS,EAAM,CAChBf,EAAOe,EAAK,GAAG,EAAE,CAAC,GAAKV,EAAeC,CAAG,IAC5CA,EAAI,KAAO,GAEb,CACD,CAAC,EACD,IAAMU,EAAOH,EAAI,SAAS,CAAE,UAAW,CAAE,CAAC,EAC1C,OAAOD,IAAc,OAAYI,EAAO,mCAAmCJ,CAAS;AAAA,EAAKI,CAAI,EAC9F",
6
+ "names": ["Document", "isPair", "isScalar", "visit", "MAX_FLOW_ENTRIES", "MAX_FLOW_LENGTH", "isShortLeafMap", "map", "length", "pair", "value", "stringifyYaml", "options", "schemaUrl", "doc", "_key", "path", "text"]
7
+ }
@@ -0,0 +1 @@
1
+ import{a as k}from"./chunk-L3ZXHX7S.js";import{b as E,c as j,d as b,f as N}from"./chunk-DDOMNXV7.js";import{b as $,c as S,d as u,e as T}from"./chunk-GX6PAJLU.js";import{a as f}from"./chunk-BY4BKVNV.js";var v={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"};function P(r,{$type:o,io:a,target:c}){let t=$(r);if(t===void 0)throw new f("schema-without-json-schema",`The schema of '${o}' sets no ~standard.jsonSchema, so the export cannot write it. Pass a resolve that converts it, or resolve: () => undefined to list '${o}' as an open node.`,{$type:o});return t[a]({target:c})}function C(r){return!("all"in r)}function V(r){let o={type:"object",properties:{$type:{const:r.$type}},required:["$type"]};for(let{keys:a}of r.childPaths??[]){let c=o;a.forEach((t,m)=>{let n=c.properties,p=m===a.length-1,h=u(n,t),s=S(h)?h:p?{}:{type:"object",properties:{}};T(n,t,s),!p&&!S(u(s,"properties"))&&(s.properties={}),c=s})}return o}function A(r,o){return new f("unreachable-child-path",`The JSON Schema of '${r}' sets an $id of its own, so the export cannot reach the child path '${o.join(".")}': a $ref written there resolves against that $id, not against the document.`,{$type:r,childPath:o})}function I(r,o={}){let{accepts:a,io:c="input",target:t="draft-2020-12",resolve:m}=o;if(!Object.hasOwn(v,t))throw new Error(`exportTreeSchema writes 'draft-2020-12' or 'draft-07', not '${t}'.`);let n=new Map;for(let e of C(r)?r:[r])for(let i of e.all())n.has(i.$type)||n.set(i.$type,i);if(n.size===0)throw new Error("exportTreeSchema needs at least one registration.");if(a?.length===0)throw new Error("accepts must list at least one $type.");for(let e of a??[])if(!n.has(e))throw new Error(`accepts names '${e}', which is not registered.`);let p=j(t),h=e=>({$ref:N(t,e)}),s=[...n.keys()],g=e=>({anyOf:e.map(h)}),O=b(t,{kind:"document"}),w=new Map;for(let e of n.values()){let i={$type:e.$type,io:c,target:t},J=(m??P)(e.schema,i),l=O.embedDefinition(J??V(e),e.$type);for(let{keys:d,accepts:x,list:R}of e.childPaths??[]){if(E(l,t))throw A(e.$type,d);let y=x?.find(L=>!n.has(L));if(y!==void 0)throw new f("unknown-accepted-type",`The child path '${d.join(".")}' of '${e.$type}' accepts '${y}', which the lookup does not list. Pass every registry of the vocabulary.`,{$type:e.$type,childPath:d,key:y});k(l,{$type:e.$type,keys:d,list:R},g(x??s),{target:t})}w.set(e.$type,l)}return O.finish({$schema:v[t],[p]:Object.fromEntries(w),...g(a??s)})}export{I as a};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/export-tree-schema.ts"],
4
+ "sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { createJSONSchemaEmbedder, definitionRef, definitionsKeyword, startsResource } from './json-schema/embedder.js';\nimport { replaceChildSlot } from './json-schema/slot.js';\nimport {\n\tgetOwn,\n\tisPlainObject,\n\treadStandardJSONSchema,\n\tsetOwn,\n\ttype JSONSchemaObject,\n\ttype JSONSchemaTarget,\n} from './json-schema/standard.js';\nimport { RegistryError } from './registry-error.js';\nimport type { TreeRegistration } from './tree-types.js';\n\n/**\n * What {@link exportTreeSchema} needs of a registry: the registrations it lists.\n *\n * @remarks\n * Both registry kinds ({@link createRegistry}, {@link createMutableRegistry}) provide it. A vocabulary spread over several\n * registries is passed as a list of them.\n */\nexport interface ExportLookup {\n\tall(): readonly TreeRegistration[];\n}\n\n/** The two dialects {@link exportTreeSchema} knows the `$schema` and the definitions keyword of. */\ntype TreeSchemaTarget = Extract<JSONSchemaTarget, 'draft-2020-12' | 'draft-07'>;\n\n/** What a `resolve` function is told about the export it takes part in. */\nexport interface ExportSchemaContext {\n\t/** The `$type` of the registration whose schema is being written, to name in an error. */\n\treadonly $type: string;\n\t/** `'input'` is the authored shape, `'output'` the parsed one. */\n\treadonly io: 'input' | 'output';\n\t/** The target the document is written for. */\n\treadonly target: TreeSchemaTarget;\n}\n\n/** Options of {@link exportTreeSchema}. */\nexport interface ExportTreeSchemaOptions {\n\t/**\n\t * The `$type`s the document's root may have. Absent: every `$type` of the lookup.\n\t *\n\t * @remarks\n\t * Each name must be registered in the lookup, and the list must not be empty.\n\t */\n\treadonly accepts?: readonly string[];\n\t/** Which shape of each schema to write. Default `'input'`, the shape an author writes. */\n\treadonly io?: 'input' | 'output';\n\t/**\n\t * The JSON Schema dialect to write. Default `'draft-2020-12'`.\n\t *\n\t * @remarks\n\t * Any other value throws before a schema is read, since a document without `$schema`, or with the wrong keyword for\n\t * its definitions, would be written silently.\n\t */\n\treadonly target?: TreeSchemaTarget;\n\t/**\n\t * Writes the JSON Schema of one registration's schema, or returns `undefined` to list it as an open node.\n\t *\n\t * @remarks\n\t * The default reads `~standard.jsonSchema`, so any schema library that implements Standard JSON Schema exports\n\t * without a function here, and a schema that has none makes the export throw, naming its `$type`, instead of\n\t * writing a document that accepts anything there. Pass a `resolve` for a library that does not provide it, or to\n\t * prefer another converter, and name `context.$type` in an error it throws, as the default does. The registry takes no\n\t * validator dependency.\n\t *\n\t * Classic Zod provides `~standard.jsonSchema`, `zod/mini` does not, and a classic schema that embeds a `zod/mini`\n\t * one (every schema of `@schema-engine/layout`) throws in that converter, which Zod keeps partial so an app bundles\n\t * only the flavour it uses. `z.toJSONSchema`, Zod's complete converter, reads all three:\n\t * `(schema, { io, target }) => (schema instanceof z.core.$ZodType ? z.toJSONSchema(schema, { io, target }) : undefined)`.\n\t *\n\t * A schema that resolves to `undefined` is listed by an open object, as {@link exportTreeSchema} explains:\n\t * `resolve: () => undefined` lists every node open, on purpose. The result is not changed.\n\t */\n\treadonly resolve?: (schema: StandardSchemaV1, context: ExportSchemaContext) => JSONSchemaObject | undefined;\n}\n\nconst DIALECTS: Readonly<Record<TreeSchemaTarget, string>> = {\n\t'draft-2020-12': 'https://json-schema.org/draft/2020-12/schema',\n\t'draft-07': 'http://json-schema.org/draft-07/schema#',\n};\n\n/**\n * Writes a registration's schema through its own `~standard.jsonSchema`.\n *\n * @throws {RegistryError} Code `'schema-without-json-schema'` when the schema sets none, since the document would\n * otherwise accept anything under the `$type` without a sign\n */\nfunction defaultResolve(schema: StandardSchemaV1, { $type, io, target }: ExportSchemaContext): JSONSchemaObject {\n\tconst converter = readStandardJSONSchema(schema);\n\tif (converter === undefined) {\n\t\tthrow new RegistryError(\n\t\t\t'schema-without-json-schema',\n\t\t\t`The schema of '${$type}' sets no ~standard.jsonSchema, so the export cannot write it. Pass a resolve that converts it, or resolve: () => undefined to list '${$type}' as an open node.`,\n\t\t\t{ $type },\n\t\t);\n\t}\n\treturn converter[io]({ target });\n}\n\nfunction isLookupList(lookup: ExportLookup | readonly ExportLookup[]): lookup is readonly ExportLookup[] {\n\treturn !('all' in lookup);\n}\n\n/**\n * The object a schema is listed by when it cannot be read: a node of its `$type` with its child paths in place, each\n * slot left open for {@link exportTreeSchema} to fill.\n */\nfunction openNode(registration: TreeRegistration): JSONSchemaObject {\n\tconst root: JSONSchemaObject = {\n\t\ttype: 'object',\n\t\tproperties: { $type: { const: registration.$type } },\n\t\trequired: ['$type'],\n\t};\n\tfor (const { keys } of registration.childPaths ?? []) {\n\t\tlet current = root;\n\t\tkeys.forEach((key, index) => {\n\t\t\tconst properties = current.properties as Record<string, unknown>;\n\t\t\tconst isLast = index === keys.length - 1;\n\t\t\tconst existing = getOwn(properties, key);\n\t\t\tconst next = isPlainObject(existing) ? existing : isLast ? {} : { type: 'object', properties: {} };\n\t\t\tsetOwn(properties, key, next);\n\t\t\tif (!isLast && !isPlainObject(getOwn(next, 'properties'))) next.properties = {};\n\t\t\tcurrent = next;\n\t\t});\n\t}\n\treturn root;\n}\n\n/**\n * The error for a registration whose own JSON Schema is a resource of its own (it sets an `$id`), so the references\n * written into it would resolve against that `$id` and not against the document.\n */\nfunction unreachableSlot($type: string, keys: readonly string[]): RegistryError {\n\treturn new RegistryError(\n\t\t'unreachable-child-path',\n\t\t`The JSON Schema of '${$type}' sets an $id of its own, so the export cannot reach the child path '${keys.join('.')}': a $ref written there resolves against that $id, not against the document.`,\n\t\t{ $type, childPath: keys },\n\t);\n}\n\n/**\n * Write the JSON Schema of a whole tree of registrations, composed at the JSON Schema level.\n *\n * @param lookup - The registrations to export: a registry, or a list of registries that make up one vocabulary. When\n * two list a `$type`, the first wins, as it does for a lookup that tries them in turn\n * @param options - The root's `accepts`, the `io` and `target` of the schemas, and a `resolve` function, see\n * {@link ExportTreeSchemaOptions}\n * @returns One document, `{ $schema, $defs, anyOf }`: a definition per `$type` under `$defs` (`definitions` for a\n * draft-07 target), and the root as the union of the root's accepted `$type`s\n * @throws {RegistryError} Code `'schema-without-json-schema'` when the default `resolve` meets a schema that sets no\n * `~standard.jsonSchema`, `'unreachable-child-path'` when a slot cannot be found where a registration's JSON\n * Schema declares it, `'unknown-accepted-type'` when a child path accepts a `$type` the lookup lacks, and\n * `'definition-name-clash'` when a definition a schema brought along takes the name of a `$type` or of another definition\n * @throws {Error} When `target` is not `'draft-2020-12'` or `'draft-07'`, before any schema is read, when the lookup\n * holds no registration, when `accepts` is empty, and when it names a `$type` the lookup lacks\n *\n * @remarks\n * Each registration's schema is written by `options.resolve`, by default the schema's own `~standard.jsonSchema`, so\n * any schema library that provides it exports the same way and the registry depends on none of them. A schema that\n * sets none makes the default throw, since the document would accept anything under its `$type`. A `resolve` that\n * returns `undefined` lists the schema by an open object that holds its `$type` and its child paths, so the document\n * still shows where children go: pass `resolve: () => undefined` for that on purpose.\n *\n * Each child path is then replaced in the definition, and only the slot: `required`, `minItems` and `maxItems`, and the\n * sibling keys stay as the registration's schema wrote them. The slot takes the union of the path's `accepts` as\n * `$ref`s to the definitions, or of every `$type` of the lookup without `accepts`:\n *\n * | Slot in the registration's JSON Schema | Becomes |\n * | --- | --- |\n * | an array (`type: 'array'`, `items` or `prefixItems`) | the same array, `items: U`, and `U` at each tuple position |\n * | an object | `U` |\n * | open (`{}`) | `{ anyOf: [U, { type: 'array', items: U }] }`, a child or a list of children |\n *\n * `U` is `{ anyOf: [{ $ref }, ...] }`. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside\n * a schema with an `$id` of its own) throws, since guessing would write a document that disagrees with the registration.\n *\n * A schema that was written as a document of its own is moved into the document by\n * {@link createJSONSchemaEmbedder}, and every local pointer follows. Its `$defs` are lifted to the top as\n * `<owner>.<name>` (`page.address` for the `address` definition of `page`), and each anchor is renamed\n * `<owner part>.<name>`. Both write the owner so that two owners never write the same name: in a lifted name each `.`\n * 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\n * the owner part is `o` and the `$type` with every character outside `[A-Za-z0-9-]` written as `_<hex>_`\n * (`ui/button` with `x` is `oui_2f_button.x`, `my-card` with `x` is `omy-card.x`). The anchors it renames are `$anchor`,\n * `$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\n * definitions could not both stay. A name in a `$ref` is a JSON Pointer token (`~` as `~0`, `/` as `~1`) and\n * percent-encoded for the URI fragment.\n */\nexport function exportTreeSchema(\n\tlookup: ExportLookup | readonly ExportLookup[],\n\toptions: ExportTreeSchemaOptions = {},\n): JSONSchemaObject {\n\tconst { accepts, io = 'input', target = 'draft-2020-12', resolve } = options;\n\tif (!Object.hasOwn(DIALECTS, target)) {\n\t\tthrow new Error(`exportTreeSchema writes 'draft-2020-12' or 'draft-07', not '${target}'.`);\n\t}\n\tconst registrations = new Map<string, TreeRegistration>();\n\tfor (const source of isLookupList(lookup) ? lookup : [lookup]) {\n\t\tfor (const registration of source.all()) {\n\t\t\tif (!registrations.has(registration.$type)) registrations.set(registration.$type, registration);\n\t\t}\n\t}\n\tif (registrations.size === 0) throw new Error('exportTreeSchema needs at least one registration.');\n\tif (accepts?.length === 0) throw new Error('accepts must list at least one $type.');\n\tfor (const name of accepts ?? []) {\n\t\tif (!registrations.has(name)) throw new Error(`accepts names '${name}', which is not registered.`);\n\t}\n\n\tconst keyword = definitionsKeyword(target);\n\tconst reference = (name: string) => ({ $ref: definitionRef(target, name) });\n\tconst everyType = [...registrations.keys()];\n\tconst unionOf = (names: readonly string[]): JSONSchemaObject => ({ anyOf: names.map(reference) });\n\n\tconst embedder = createJSONSchemaEmbedder(target, { kind: 'document' });\n\tconst definitions = new Map<string, JSONSchemaObject>();\n\tfor (const registration of registrations.values()) {\n\t\tconst context: ExportSchemaContext = { $type: registration.$type, io, target };\n\t\tconst resolved = (resolve ?? defaultResolve)(registration.schema, context);\n\t\tconst definition = embedder.embedDefinition(resolved ?? openNode(registration), registration.$type);\n\t\tfor (const { keys, accepts: slotAccepts, list } of registration.childPaths ?? []) {\n\t\t\tif (startsResource(definition, target)) throw unreachableSlot(registration.$type, keys);\n\t\t\tconst missing = slotAccepts?.find((name) => !registrations.has(name));\n\t\t\tif (missing !== undefined) {\n\t\t\t\tthrow new RegistryError(\n\t\t\t\t\t'unknown-accepted-type',\n\t\t\t\t\t`The child path '${keys.join('.')}' of '${registration.$type}' accepts '${missing}', which the lookup does not list. Pass every registry of the vocabulary.`,\n\t\t\t\t\t{ $type: registration.$type, childPath: keys, key: missing },\n\t\t\t\t);\n\t\t\t}\n\t\t\treplaceChildSlot(definition, { $type: registration.$type, keys, list }, unionOf(slotAccepts ?? everyType), {\n\t\t\t\ttarget,\n\t\t\t});\n\t\t}\n\t\tdefinitions.set(registration.$type, definition);\n\t}\n\n\treturn embedder.finish({\n\t\t$schema: DIALECTS[target],\n\t\t[keyword]: Object.fromEntries(definitions),\n\t\t...unionOf(accepts ?? everyType),\n\t});\n}\n"],
5
+ "mappings": "0MA8EA,IAAMA,EAAuD,CAC5D,gBAAiB,+CACjB,WAAY,yCACb,EAQA,SAASC,EAAeC,EAA0B,CAAE,MAAAC,EAAO,GAAAC,EAAI,OAAAC,CAAO,EAA0C,CAC/G,IAAMC,EAAYC,EAAuBL,CAAM,EAC/C,GAAII,IAAc,OACjB,MAAM,IAAIE,EACT,6BACA,kBAAkBL,CAAK,wIAAwIA,CAAK,qBACpK,CAAE,MAAAA,CAAM,CACT,EAED,OAAOG,EAAUF,CAAE,EAAE,CAAE,OAAAC,CAAO,CAAC,CAChC,CAEA,SAASI,EAAaC,EAAmF,CACxG,MAAO,EAAE,QAASA,EACnB,CAMA,SAASC,EAASC,EAAkD,CACnE,IAAMC,EAAyB,CAC9B,KAAM,SACN,WAAY,CAAE,MAAO,CAAE,MAAOD,EAAa,KAAM,CAAE,EACnD,SAAU,CAAC,OAAO,CACnB,EACA,OAAW,CAAE,KAAAE,CAAK,IAAKF,EAAa,YAAc,CAAC,EAAG,C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C4B,CAAO,EAAG,OAAO,YAAYS,CAAW,EACzC,GAAGJ,EAAQV,GAAWS,CAAS,CAChC,CAAC,CACF",
6
+ "names": ["DIALECTS", "defaultResolve", "schema", "$type", "io", "target", "converter", "readStandardJSONSchema", "RegistryError", "isLookupList", "lookup", "openNode", "registration", "root", "keys", "current", "key", "index", "properties", "isLast", "existing", "getOwn", "next", "isPlainObject", "setOwn", "unreachableSlot", "exportTreeSchema", "options", "accepts", "resolve", "registrations", "source", "name", "keyword", "definitionsKeyword", "reference", "definitionRef", "everyType", "unionOf", "names", "embedder", "createJSONSchemaEmbedder", "definitions", "context", "resolved", "definition", "slotAccepts", "list", "startsResource", "missing", "replaceChildSlot"]
7
+ }
@@ -0,0 +1 @@
1
+ var r=["draft-2020-12","draft-07","draft-04","openapi-3.0"];function o(n){if(!r.includes(n))throw new Error(`The JSON Schema target '${n}' is not supported. Use 'draft-2020-12', 'draft-07', 'draft-04' or 'openapi-3.0'.`)}function u(n){if(typeof n!="object"&&typeof n!="function"||n===null||!("~standard"in n))return;let t=n["~standard"];if(typeof t!="object"||t===null||!("jsonSchema"in t))return;let e=t.jsonSchema;if(!(typeof e!="object"||e===null)&&!(!("input"in e)||typeof e.input!="function")&&!(!("output"in e)||typeof e.output!="function"))return e}function i(n){if(typeof n!="object"||n===null)return!1;let t=Object.getPrototypeOf(n);return t===Object.prototype||t===null}function a(n,t){return Object.hasOwn(n,t)?n[t]:void 0}function d(n,t,e){Object.defineProperty(n,t,{value:e,enumerable:!0,writable:!0,configurable:!0})}export{o as a,u as b,i as c,a as d,d as e};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/json-schema/standard.ts"],
4
+ "sourcesContent": ["import type { StandardJSONSchemaV1 } from '@standard-schema/spec';\n\n/**\n * A JSON Schema as a plain object.\n *\n * @remarks\n * The export reads and writes schemas of any dialect, so the type names no keyword: callers narrow what they inspect.\n */\nexport type JSONSchemaObject = Record<string, unknown>;\n\nconst JSON_SCHEMA_TARGETS = ['draft-2020-12', 'draft-07', 'draft-04', 'openapi-3.0'] as const;\n\n/**\n * The JSON Schema dialects a schema can be written for, by their Standard JSON Schema names.\n *\n * @remarks\n * The set is closed, though the Standard JSON Schema type is open, so that each API names the targets it supports and\n * refuses the others. A target added later widens the union, which is additive.\n */\nexport type JSONSchemaTarget = (typeof JSON_SCHEMA_TARGETS)[number];\n\n/**\n * Throw unless `target` is a {@link JSONSchemaTarget}, and narrow it to one.\n *\n * @param target - A target as a caller wrote it, for example the `target` of a Standard JSON Schema converter's options,\n * which the Standard JSON Schema type leaves open\n * @throws {Error} When `target` is any other string, naming it and the four that are supported\n */\nexport function assertJSONSchemaTarget(target: string): asserts target is JSONSchemaTarget {\n\tif ((JSON_SCHEMA_TARGETS as readonly string[]).includes(target)) return;\n\tthrow new Error(\n\t\t`The JSON Schema target '${target}' is not supported. Use 'draft-2020-12', 'draft-07', 'draft-04' or 'openapi-3.0'.`,\n\t);\n}\n\n/**\n * The Standard JSON Schema converter of a schema (`~standard.jsonSchema`), when it provides one.\n *\n * @remarks\n * {@link exportTreeSchema} reads each registration's schema through it unless the caller passes its own `resolve`.\n */\nexport function readStandardJSONSchema(schema: unknown): StandardJSONSchemaV1.Converter | undefined {\n\tif (typeof schema !== 'object' && typeof schema !== 'function') return undefined;\n\tif (schema === null || !('~standard' in schema)) return undefined;\n\tconst standard = schema['~standard'];\n\tif (typeof standard !== 'object' || standard === null || !('jsonSchema' in standard)) return undefined;\n\tconst converter = standard.jsonSchema;\n\tif (typeof converter !== 'object' || converter === null) return undefined;\n\tif (!('input' in converter) || typeof converter.input !== 'function') return undefined;\n\tif (!('output' in converter) || typeof converter.output !== 'function') return undefined;\n\treturn converter as StandardJSONSchemaV1.Converter;\n}\n\n/** Only ordinary records and null-prototype value maps are walked as schemas. */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (typeof value !== 'object' || value === null) return false;\n\tconst prototype: unknown = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/**\n * The own entry of `record` under `key`, or `undefined`.\n *\n * @remarks\n * A child path key is data, and `__proto__` is a valid key. Reading and writing keys through these two functions keeps\n * every one on the document's own properties, so none reaches the prototype chain, whatever its name.\n */\nexport function getOwn(record: Record<string, unknown>, key: string): unknown {\n\treturn Object.hasOwn(record, key) ? record[key] : undefined;\n}\n\nexport function setOwn(record: Record<string, unknown>, key: string, value: unknown): void {\n\tObject.defineProperty(record, key, { value, enumerable: true, writable: true, configurable: true });\n}\n"],
5
+ "mappings": "AAUA,IAAMA,EAAsB,CAAC,gBAAiB,WAAY,WAAY,aAAa,EAkB5E,SAASC,EAAuBC,EAAoD,CAC1F,GAAK,CAAAF,EAA0C,SAASE,CAAM,EAC9D,MAAM,IAAI,MACT,2BAA2BA,CAAM,mFAClC,CACD,CAQO,SAASC,EAAuBC,EAA6D,CAEnG,GADI,OAAOA,GAAW,UAAY,OAAOA,GAAW,YAChDA,IAAW,MAAQ,EAAE,cAAeA,GAAS,OACjD,IAAMC,EAAWD,EAAO,WAAW,EACnC,GAAI,OAAOC,GAAa,UAAYA,IAAa,MAAQ,EAAE,eAAgBA,GAAW,OACtF,IAAMC,EAAYD,EAAS,WAC3B,GAAI,SAAOC,GAAc,UAAYA,IAAc,OAC/C,IAAE,UAAWA,IAAc,OAAOA,EAAU,OAAU,aACtD,IAAE,WAAYA,IAAc,OAAOA,EAAU,QAAW,YAC5D,OAAOA,CACR,CAGO,SAASC,EAAcC,EAAkD,CAC/E,GAAI,OAAOA,GAAU,UAAYA,IAAU,KAAM,MAAO,GACxD,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACxD,CASO,SAASC,EAAOC,EAAiCC,EAAsB,CAC7E,OAAO,OAAO,OAAOD,EAAQC,CAAG,EAAID,EAAOC,CAAG,EAAI,MACnD,CAEO,SAASC,EAAOF,EAAiCC,EAAaJ,EAAsB,CAC1F,OAAO,eAAeG,EAAQC,EAAK,CAAE,MAAAJ,EAAO,WAAY,GAAM,SAAU,GAAM,aAAc,EAAK,CAAC,CACnG",
6
+ "names": ["JSON_SCHEMA_TARGETS", "assertJSONSchemaTarget", "target", "readStandardJSONSchema", "schema", "standard", "converter", "isPlainObject", "value", "prototype", "getOwn", "record", "key", "setOwn"]
7
+ }
@@ -0,0 +1 @@
1
+ import{b as d}from"./chunk-M3SYVKZK.js";import{a as i}from"./chunk-BY4BKVNV.js";function T(r,s){let{kind:t}=r;for(let n of Object.keys(s))if(!r.has(n))throw new i("unknown-binding",`${t} binding '${n}' names no registration.`,{kind:t,$type:n});let a=r.all().map(n=>{let e=Object.hasOwn(s,n.$type)?s[n.$type]:void 0;if(typeof e!="object"||e===null)throw new i("missing-binding",`${t} '${n.$type}' has no binding.`,{kind:t,$type:n.$type});for(let o of Object.keys(e))if(Object.hasOwn(n,o))throw new i("binding-overrides-contract",`${t} '${n.$type}' binding sets '${o}', which the contract defines.`,{kind:t,$type:n.$type,key:o});return{...n,...e}});return d(t,a)}export{T as a};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/bind-registry.ts"],
4
+ "sourcesContent": ["import { createRegistry, type ReadOnlyRegistry } from './create-registry.js';\nimport { RegistryError } from './registry-error.js';\nimport type { BaseRegistration } from './types.js';\n\n/** What a binding may not set: the keys its contract already defines. */\ntype ContractKeys<TContract> = { readonly [K in keyof TContract]?: never };\n\n/** The binding each `$type` of a contracts registry takes, which may not set a key of its own contract. */\ntype BindingsOf<TContract extends BaseRegistration> = {\n\treadonly [K in TContract['$type']]: Readonly<Record<string, unknown>> &\n\t\tContractKeys<Extract<TContract, { $type: K }>>;\n};\n\n/** The keys of `TBindings` that no contract answers; each is typed `never`, so naming one is a compile error. */\ntype ExtraBindings<TBindings, TContract extends BaseRegistration> = {\n\treadonly [K in Exclude<keyof TBindings, TContract['$type']>]: never;\n};\n\n/**\n * One binding per `$type` of a contracts registry, every binding of the same shape.\n *\n * @remarks\n * Use it with `satisfies` to fix what one renderer binds:\n * `{ card: { render: Card } } satisfies RegistryBindings<typeof contracts, ReactBinding>`.\n * A contracts registry whose `$type` is a plain `string` has no known keys to require, so only {@link bindRegistry}'s\n * build-time checks apply to it.\n */\nexport type RegistryBindings<TRegistry extends ReadOnlyRegistry, TBinding extends object = object> =\n\tTRegistry extends ReadOnlyRegistry<infer TContract> ? { readonly [K in TContract['$type']]: TBinding } : never;\n\n/** A contract merged with the binding its `$type` names, member by member. */\nexport type BoundRegistration<TContract extends BaseRegistration, TBindings> = TContract extends unknown\n\t? TContract & TBindings[TContract['$type'] & keyof TBindings]\n\t: never;\n\n/** The `$type`s of a contracts registry that are known literals; `never` when the contracts are typed only as `string`. */\ntype KnownTypes<TContract extends BaseRegistration> = string extends TContract['$type'] ? never : TContract['$type'];\n\n/**\n * What {@link bindRegistry} returns: a read-only registry whose `get` also answers a known `$type` without `undefined`.\n *\n * @remarks\n * `get` returns the registration of that exact `$type` when the contracts name their `$type`s as literals, because\n * `bindRegistry` guarantees every contract is bound. The `string` overload stays for a `$type` read from a document.\n */\nexport interface BoundRegistry<TContract extends BaseRegistration, TBindings> extends ReadOnlyRegistry<\n\tBoundRegistration<TContract, TBindings>\n> {\n\tget<K extends KnownTypes<TContract>>(key: K): Extract<BoundRegistration<TContract, TBindings>, { $type: K }>;\n\tget(key: string): BoundRegistration<TContract, TBindings> | undefined;\n}\n\n/**\n * Build a renderer's registry from a registry of contracts and one binding per `$type`.\n *\n * @param contracts - Registrations without the renderer's part: the `$type`, schema and metadata, plus what the domain fixes\n * @param bindings - What this renderer adds to each contract, keyed by `$type`, such as `render` or a tag name\n * @throws {RegistryError} Code `'missing-binding'`, `Widget 'card' has no binding.`, when a contract has no binding\n * @throws {RegistryError} Code `'unknown-binding'`, `Widget binding 'crad' names no registration.`, when a binding's\n * key, set as `$type`, is no contract's `$type`\n * @throws {RegistryError} Code `'binding-overrides-contract'`, `Widget 'card' binding sets 'schema', which the contract\n * defines.`, when a binding sets a contract key, named by `key`\n * @throws {RegistryError} The errors of {@link createRegistry}, when a merged registration breaks one of its rules\n *\n * @remarks\n * The result is a frozen registry built with {@link createRegistry}, so it keeps the contracts' order and checks every\n * schema again. Each registration is a shallow merge, so `schema`, `metadata` and every other value of a contract is\n * shared by identity between all the renderers that bind it. A binding is renderer-only data (a `render` function, a\n * tag name) and never carries schema or metadata.\n *\n * With contracts typed by literal `$type`, a missing binding, an extra one and a binding that sets a contract key are\n * also compile errors. With contracts typed only as `string` the three checks run when the registry is built.\n */\nexport function bindRegistry<TContract extends BaseRegistration, const TBindings extends BindingsOf<TContract>>(\n\tcontracts: ReadOnlyRegistry<TContract>,\n\tbindings: TBindings & ExtraBindings<TBindings, TContract>,\n): BoundRegistry<TContract, TBindings>;\nexport function bindRegistry(\n\tcontracts: ReadOnlyRegistry,\n\tbindings: Readonly<Record<string, object>>,\n): ReadOnlyRegistry<BaseRegistration> {\n\tconst { kind } = contracts;\n\tfor (const key of Object.keys(bindings)) {\n\t\tif (!contracts.has(key)) {\n\t\t\tthrow new RegistryError('unknown-binding', `${kind} binding '${key}' names no registration.`, {\n\t\t\t\tkind,\n\t\t\t\t$type: key,\n\t\t\t});\n\t\t}\n\t}\n\tconst bound = contracts.all().map((contract) => {\n\t\tconst binding: unknown = Object.hasOwn(bindings, contract.$type) ? bindings[contract.$type] : undefined;\n\t\tif (typeof binding !== 'object' || binding === null) {\n\t\t\tthrow new RegistryError('missing-binding', `${kind} '${contract.$type}' has no binding.`, {\n\t\t\t\tkind,\n\t\t\t\t$type: contract.$type,\n\t\t\t});\n\t\t}\n\t\tfor (const key of Object.keys(binding)) {\n\t\t\tif (Object.hasOwn(contract, key)) {\n\t\t\t\tthrow new RegistryError(\n\t\t\t\t\t'binding-overrides-contract',\n\t\t\t\t\t`${kind} '${contract.$type}' binding sets '${key}', which the contract defines.`,\n\t\t\t\t\t{ kind, $type: contract.$type, key },\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn { ...contract, ...binding };\n\t});\n\treturn createRegistry(kind, bound);\n}\n"],
5
+ "mappings": "gFA6EO,SAASA,EACfC,EACAC,EACqC,CACrC,GAAM,CAAE,KAAAC,CAAK,EAAIF,EACjB,QAAWG,KAAO,OAAO,KAAKF,CAAQ,EACrC,GAAI,CAACD,EAAU,IAAIG,CAAG,EACrB,MAAM,IAAIC,EAAc,kBAAmB,GAAGF,CAAI,aAAaC,CAAG,2BAA4B,CAC7F,KAAAD,EACA,MAAOC,CACR,CAAC,EAGH,IAAME,EAAQL,EAAU,IAAI,EAAE,IAAKM,GAAa,CAC/C,IAAMC,EAAmB,OAAO,OAAON,EAAUK,EAAS,KAAK,EAAIL,EAASK,EAAS,KAAK,EAAI,OAC9F,GAAI,OAAOC,GAAY,UAAYA,IAAY,KAC9C,MAAM,IAAIH,EAAc,kBAAmB,GAAGF,CAAI,KAAKI,EAAS,KAAK,oBAAqB,CACzF,KAAAJ,EACA,MAAOI,EAAS,KACjB,CAAC,EAEF,QAAWH,KAAO,OAAO,KAAKI,CAAO,EACpC,GAAI,OAAO,OAAOD,EAAUH,CAAG,EAC9B,MAAM,IAAIC,EACT,6BACA,GAAGF,CAAI,KAAKI,EAAS,KAAK,mBAAmBH,CAAG,iCAChD,CAAE,KAAAD,EAAM,MAAOI,EAAS,MAAO,IAAAH,CAAI,CACpC,EAGF,MAAO,CAAE,GAAGG,EAAU,GAAGC,CAAQ,CAClC,CAAC,EACD,OAAOC,EAAeN,EAAMG,CAAK,CAClC",
6
+ "names": ["bindRegistry", "contracts", "bindings", "kind", "key", "RegistryError", "bound", "contract", "binding", "createRegistry"]
7
+ }
@@ -0,0 +1 @@
1
+ import{b as O}from"./chunk-DDOMNXV7.js";import{c as s,d,e as m}from"./chunk-GX6PAJLU.js";import{a as y}from"./chunk-BY4BKVNV.js";var g=["$ref","$dynamicRef","allOf","anyOf","oneOf","not","if","then","else"],N=["title","description","default","examples","deprecated","$comment"];function x(w,b,j,A){let{target:u}=A,{$type:c,keys:r,list:h}=b;if(r.length===0)throw new y("invalid-child-paths",`The child path of '${c}' has no keys, so there is no slot to replace.`,{$type:c,childPath:r});let n=()=>structuredClone(j),o=()=>new y("unreachable-child-path",`The JSON Schema of '${c}' has no slot the export can reach for the child path '${r.join(".")}'. The slot must be a declared property, not behind a reference, allOf or a union, nor inside a schema with an $id (id for draft-04) of its own, and an object, an array or open.`,{$type:c,childPath:r}),l=w;for(let t of r.slice(0,-1)){let i=s(l.properties)?d(l.properties,t):void 0;if(!s(i)||O(i,u))throw o();l=i}let p=r[r.length-1],a=l.properties;if(!s(a)||!Object.hasOwn(a,p))throw o();let S=d(a,p),e=S===!0?{}:S;if(!s(e)||g.some(t=>t in e)||Array.isArray(e.type)||e.nullable===!0||O(e,u))throw o();let f=Object.fromEntries(N.filter(t=>t in e).map(t=>[t,e[t]]));if(e.type==="array"||"items"in e||"prefixItems"in e){if(h===!0){if(e.type!==void 0&&e.type!=="array")throw o();e.type="array"}let t=Array.isArray(e.items),i=t?"additionalItems":"items";Array.isArray(e.prefixItems)&&(e.prefixItems=e.prefixItems.map(n)),t&&(e.items=e.items.map(n)),e[i]!==!1&&(e[i]=n())}else if(e.type==="object"||"properties"in e){if(h===!0)throw o();m(a,p,{...f,...n()})}else if(e.type===void 0&&Object.keys(e).every(t=>t in f)){let t={type:"array",items:n()};m(a,p,h===!0?{...f,...t}:{...f,anyOf:[n(),t]})}else throw o()}export{x as a};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/json-schema/slot.ts"],
4
+ "sourcesContent": ["import { RegistryError } from '../registry-error.js';\nimport { startsResource } from './embedder.js';\nimport { getOwn, isPlainObject, setOwn, type JSONSchemaObject, type JSONSchemaTarget } from './standard.js';\n\nconst SCHEMA_APPLICATORS = ['$ref', '$dynamicRef', 'allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else'];\n\nconst SLOT_ANNOTATIONS = ['title', 'description', 'default', 'examples', 'deprecated', '$comment'];\n\n/**\n * Replace the slot a child path names in a registration's JSON Schema, and nothing around it. The definition is\n * changed in place.\n *\n * @param definition - The registration's JSON Schema, as the definition of its `$type`\n * @param path - The registration's `$type`, for the error, and the `keys` and `list` of the child path whose slot to\n * replace\n * @param union - The schema every child must match, already resolved: each `$ref` is written as the document it goes in\n * refers to a definition. Each place the slot takes it gets its own copy\n * @param options - The `target` the schema is written for, which decides the identifier (`$id`, or `id` for draft-04)\n * that makes a schema a resource of its own\n * @throws {RegistryError} Code `'unreachable-child-path'` when the slot is not where the definition declares it, is\n * nullable, is not an object, an array or open, or is an object where the path sets `list`, and `'invalid-child-paths'` when `path.keys` is empty\n *\n * @remarks\n * `required`, list bounds and every sibling keyword of the slot's parent stay, since the registration's schema owns\n * them. The slot is read by what it is: an array (`type: 'array'`, `items` or `prefixItems`) gets its items replaced, an\n * object (`type: 'object'` or `properties`) becomes the union, and an open slot (no keyword but annotations) becomes the\n * union or a list of it, matching a child or a list of children. A path that sets `list` holds a list and never one\n * node, so its open slot becomes an array of the union, and an object slot is unreachable, since the schema would refuse\n * the list the document holds. An array slot of such a path that declares only array keywords (`items`) gets\n * `type: 'array'`, so an object is refused as the walk refuses it, and one whose `type` is another is unreachable.\n * Annotations of the slot are kept. A slot inside a\n * schema with an `$id` (`id` for draft-04) of its own cannot be reached: a `$ref` there resolves against that `$id`, not against the\n * document. That holds for each schema between the definition and the slot. The definition's own root is the caller's\n * to check, since only the caller knows whether the references it writes resolve against that root: a collection entry\n * has an `$id` that is its address, and its references are written for that collection. A nullable slot (`type: ['array', 'null']` or an `anyOf` with `null`, or `nullable: true` as OpenAPI 3.0\n * writes it) cannot be reached either, since `safeParseTree` refuses `null` at a slot and keeping the keyword would\n * leave the slot accepting it.\n *\n * A tuple is an array whose every item is a child, as `safeParseTree` reads it, so each position takes the union:\n * every `prefixItems` entry (2020-12), every array-form `items` entry and `additionalItems` (draft-07), and the\n * `items` that follows `prefixItems`. A rest that the schema closes with `false` stays closed, since the tuple's arity\n * is the registration's to decide. Throwing instead would refuse a fixed-arity pair of children that is valid, while\n * replacing only `items` would leave the prefix positions accepting any `$type`.\n *\n * The check that the union's names are registered belongs to the caller, as it does in `exportTreeSchema`.\n */\nexport function replaceChildSlot(\n\tdefinition: JSONSchemaObject,\n\tpath: { readonly $type: string; readonly keys: readonly string[]; readonly list?: true },\n\tunion: JSONSchemaObject,\n\toptions: { readonly target: JSONSchemaTarget },\n): void {\n\tconst { target } = options;\n\tconst { $type, keys, list } = path;\n\tif (keys.length === 0) {\n\t\tthrow new RegistryError(\n\t\t\t'invalid-child-paths',\n\t\t\t`The child path of '${$type}' has no keys, so there is no slot to replace.`,\n\t\t\t{ $type, childPath: keys },\n\t\t);\n\t}\n\tconst copy = () => structuredClone(union);\n\tconst unreachable = () =>\n\t\tnew RegistryError(\n\t\t\t'unreachable-child-path',\n\t\t\t`The JSON Schema of '${$type}' has no slot the export can reach for the child path '${keys.join('.')}'. The slot must be a declared property, not behind a reference, allOf or a union, nor inside a schema with an $id (id for draft-04) of its own, and an object, an array or open.`,\n\t\t\t{ $type, childPath: keys },\n\t\t);\n\tlet parent: JSONSchemaObject = definition;\n\tfor (const key of keys.slice(0, -1)) {\n\t\tconst step = isPlainObject(parent.properties) ? getOwn(parent.properties, key) : undefined;\n\t\tif (!isPlainObject(step) || startsResource(step, target)) throw unreachable();\n\t\tparent = step;\n\t}\n\tconst last = keys[keys.length - 1]!;\n\tconst properties = parent.properties;\n\tif (!isPlainObject(properties) || !Object.hasOwn(properties, last)) {\n\t\tthrow unreachable();\n\t}\n\tconst found = getOwn(properties, last);\n\tconst slot = found === true ? {} : found;\n\tif (!isPlainObject(slot)) throw unreachable();\n\tif (\n\t\tSCHEMA_APPLICATORS.some((keyword) => keyword in slot) ||\n\t\tArray.isArray(slot.type) ||\n\t\tslot.nullable === true ||\n\t\tstartsResource(slot, target)\n\t) {\n\t\tthrow unreachable();\n\t}\n\tconst annotations = Object.fromEntries(\n\t\tSLOT_ANNOTATIONS.filter((key) => key in slot).map((key) => [key, slot[key]]),\n\t);\n\tif (slot.type === 'array' || 'items' in slot || 'prefixItems' in slot) {\n\t\tif (list === true) {\n\t\t\tif (slot.type !== undefined && slot.type !== 'array') throw unreachable();\n\t\t\tslot.type = 'array';\n\t\t}\n\t\tconst tupleItems = Array.isArray(slot.items);\n\t\tconst rest = tupleItems ? 'additionalItems' : 'items';\n\t\tif (Array.isArray(slot.prefixItems)) slot.prefixItems = slot.prefixItems.map(copy);\n\t\tif (tupleItems) slot.items = (slot.items as unknown[]).map(copy);\n\t\tif (slot[rest] !== false) slot[rest] = copy();\n\t} else if (slot.type === 'object' || 'properties' in slot) {\n\t\tif (list === true) throw unreachable();\n\t\tsetOwn(properties, last, { ...annotations, ...copy() });\n\t} else if (slot.type === undefined && Object.keys(slot).every((key) => key in annotations)) {\n\t\tconst items = { type: 'array', items: copy() };\n\t\tsetOwn(\n\t\t\tproperties,\n\t\t\tlast,\n\t\t\tlist === true ? { ...annotations, ...items } : { ...annotations, anyOf: [copy(), items] },\n\t\t);\n\t} else {\n\t\tthrow unreachable();\n\t}\n}\n"],
5
+ "mappings": "iIAIA,IAAMA,EAAqB,CAAC,OAAQ,cAAe,QAAS,QAAS,QAAS,MAAO,KAAM,OAAQ,MAAM,EAEnGC,EAAmB,CAAC,QAAS,cAAe,UAAW,WAAY,aAAc,UAAU,EAwC1F,SAASC,EACfC,EACAC,EACAC,EACAC,EACO,CACP,GAAM,CAAE,OAAAC,CAAO,EAAID,EACb,CAAE,MAAAE,EAAO,KAAAC,EAAM,KAAAC,CAAK,EAAIN,EAC9B,GAAIK,EAAK,SAAW,EACnB,MAAM,IAAIE,EACT,sBACA,sBAAsBH,CAAK,iDAC3B,CAAE,MAAAA,EAAO,UAAWC,CAAK,CAC1B,EAED,IAAMG,EAAO,IAAM,gBAAgBP,CAAK,EAClCQ,EAAc,IACnB,IAAIF,EACH,yBACA,uBAAuBH,CAAK,0DAA0DC,EAAK,KAAK,GAAG,CAAC,oLACpG,CAAE,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AI,IAAM,KAAOJ,EAAKI,CAAI,EAAIf,EAAK,EAC7C,SAAWW,EAAK,OAAS,UAAY,eAAgBA,EAAM,CAC1D,GAAIb,IAAS,GAAM,MAAMG,EAAY,EACrCe,EAAOP,EAAYD,EAAM,CAAE,GAAGK,EAAa,GAAGb,EAAK,CAAE,CAAC,CACvD,SAAWW,EAAK,OAAS,QAAa,OAAO,KAAKA,CAAI,EAAE,MAAOR,GAAQA,KAAOU,CAAW,EAAG,CAC3F,IAAMI,EAAQ,CAAE,KAAM,QAAS,MAAOjB,EAAK,CAAE,EAC7CgB,EACCP,EACAD,EACAV,IAAS,GAAO,CAAE,GAAGe,EAAa,GAAGI,CAAM,EAAI,CAAE,GAAGJ,EAAa,MAAO,CAACb,EAAK,EAAGiB,CAAK,CAAE,CACzF,CACD,KACC,OAAMhB,EAAY,CAEpB",
6
+ "names": ["SCHEMA_APPLICATORS", "SLOT_ANNOTATIONS", "replaceChildSlot", "definition", "path", "union", "options", "target", "$type", "keys", "list", "RegistryError", "copy", "unreachable", "parent", "key", "step", "isPlainObject", "getOwn", "startsResource", "last", "properties", "found", "slot", "keyword", "annotations", "tupleItems", "rest", "setOwn", "items"]
7
+ }
@@ -0,0 +1 @@
1
+ import{a as f}from"./chunk-P3DDHPDA.js";import{a as g}from"./chunk-BY4BKVNV.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};