@kindgi/schema 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kindgi Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # @kindgi/schema
1
+ # `@kindgi/schema`
2
2
 
3
- A placeholder. Releases come from https://github.com/kindgi/kindgi-sdk.
3
+ JSON Schema utilities for Kindgi. Loads specs, provides Ajv-based validation, extracts schema versions, converts Zod v4 schemas to JSON Schema, and serializes JSON canonically for signing. Consumers use this to validate incoming data against the wire contracts in [`@kindgi/specs`](../specs/).
4
+
5
+ ## Purpose
6
+
7
+ Turn the JSON Schemas that live in `@kindgi/specs/*.schema.json` into runtime-usable validators, with cross-schema `$ref` resolution handled correctly (two-pass registration), typed `Result` errors, and version extraction that respects our `$id` + `$comment` convention.
8
+
9
+ ## Exports
10
+
11
+ - **`createSpecRegistry(schemas)`** — build a registry from already-parsed schema documents (synchronous, no filesystem access).
12
+ - **`loadSpecRegistry(dir)`** — build a registry by reading every `*.schema.json` from a directory (async).
13
+ - **`SpecRegistry`** — the resulting interface:
14
+ - `validate<T>(id, data)` — validate data against a schema by `$id`, returning `Result<T, SchemaError>`.
15
+ - `getSchema(id)` — retrieve the raw parsed schema JSON.
16
+ - `ids()` — list every registered `$id`.
17
+ - **`compileInlineSchema(schema)`** — compile one anonymous JSON Schema (no `$id`, no cross-schema `$ref`) into a `CompiledInlineSchema` whose `validate<T>(data)` returns `Result<T, ValidationErrorLike>`.
18
+ - **`versionOf(schema)`** — extract `{ major, semver }` from a schema's `$id` and `$comment`.
19
+ - **Zod authoring helpers** — `AnySchema` (a JSON Schema object or a Zod v4 schema), `isZodSchema`, `isJsonSchemaObject`, `schemaKindOf`, and `toJSONSchema` / `toJSONSchemaSync` (with `loadZodConverter` / `loadZodConverterSync`), which convert Zod to JSON Schema through Zod's native `z.toJSONSchema()`. `zod` is an optional peer dependency: it is imported only when a Zod schema is passed, and a missing or failed conversion is an `invalid-zod-conversion` error, not a throw.
20
+ - **`canonicalize(value)`** — deterministic JSON serialization (sorted keys, `undefined` omitted, no whitespace), a subset of RFC 8785 used for signing.
21
+ - **`SchemaError`** — typed discriminated union covering load / parse / compile / not-found / validation / Zod-conversion errors.
22
+
23
+ ## Example
24
+
25
+ ```ts
26
+ import { loadSpecRegistry, versionOf } from '@kindgi/schema';
27
+ import type { Flow } from '@kindgi/flow';
28
+
29
+ const registry = await loadSpecRegistry('./specs');
30
+ if (registry.kind === 'err') {
31
+ console.error(registry.error);
32
+ process.exit(1);
33
+ }
34
+
35
+ const incoming = JSON.parse(await readFile('user-flow.json', 'utf-8'));
36
+ const validated = registry.value.validate<Flow>(
37
+ 'https://kindgi.com/schemas/v1/flow.schema.json',
38
+ incoming,
39
+ );
40
+
41
+ if (validated.kind === 'ok') {
42
+ runGraph(validated.value);
43
+ } else {
44
+ console.error(validated.error.code, validated.error.message);
45
+ }
46
+ ```
47
+
48
+ ## Non-goals
49
+
50
+ - **No Zod on the wire, and no JSON Schema → Zod conversion.** Zod is an authoring convenience: schemas are converted one way, Zod → JSON Schema, and every schema that is registered or exchanged is JSON Schema.
51
+ - **No schema migration helpers.** Every schema is at its first major version, so there is nothing to migrate between.
52
+ - **No TypeScript type generation.** Callers define TypeScript types that match schema shapes by hand, or author with Zod and derive them with `z.infer`.
53
+ - **No custom Ajv extensions.** Uses stock Ajv Draft 2020-12 + `ajv-formats`, with no custom keywords.
package/SPEC.md ADDED
@@ -0,0 +1,120 @@
1
+ # `@kindgi/schema` — Specification
2
+
3
+ *Deep spec for humans. Complements the JSON Schemas in `@kindgi/specs` (the wire contracts) and `packages/types/SPEC.md` (the foundational types).*
4
+
5
+ ## Purpose in the OS
6
+
7
+ Every artifact in Kindgi has its shape defined by a JSON Schema in `@kindgi/specs/*.schema.json`. Those schemas are authoritative — they cross the boundary to Python runtimes, third-party MCP tools, community adapters. But TypeScript code inside the OS needs to *use* those schemas at runtime: validate incoming data, look up schemas by `$id`, parse schema versions.
8
+
9
+ `@kindgi/schema` is the layer that turns the JSON files into runtime-usable objects. It sits below every kernel/memory/tools/agents package.
10
+
11
+ ## Design principles
12
+
13
+ 1. **Ajv is the validation engine.** Not a leaky abstraction; downstream packages don't need to know about Ajv. But when they need to inspect a validation failure in detail, the raw Ajv error is available via `SchemaError.errors[]`.
14
+ 2. **Two-pass registration.** All schemas registered first, then validators compiled. This is the only way cross-schema `$ref`s (e.g. `pack.schema.json` → `tool.schema.json`) resolve correctly.
15
+ 3. **Typed `Result` errors, never thrown.** Every fallible operation returns `Result<T, SchemaError>`. Consumers explicitly handle both branches.
16
+ 4. **Sync when possible, async only when doing I/O.** `createSpecRegistry(schemas)` is sync; `loadSpecRegistry(dir)` is async. Not everything has to be a Promise.
17
+ 5. **Fail-fast at construction.** A broken schema during registration returns immediately — downstream validators would be meaningless.
18
+
19
+ ## The Registry
20
+
21
+ ```
22
+ ┌───────────────────────────────────────────────────────────────┐
23
+ │ SpecRegistry │
24
+ │ │
25
+ │ schemas: Map<$id, unknown> ← raw parsed JSON │
26
+ │ validators: Map<$id, ValidateFn> ← compiled Ajv validators │
27
+ │ │
28
+ │ validate<T>(id, data) → Result<T, SchemaError> │
29
+ │ getSchema(id) → Result<unknown, SchemaError> │
30
+ │ ids() → readonly string[] │
31
+ └───────────────────────────────────────────────────────────────┘
32
+ ```
33
+
34
+ ### Construction paths
35
+
36
+ Two entry points, one internal builder:
37
+
38
+ - `createSpecRegistry(schemas)` — synchronous. Every schema is already parsed. Suitable for tests and in-memory use.
39
+ - `loadSpecRegistry(dir)` — asynchronous. Reads every `*.schema.json` from `dir`, parses JSON, delegates.
40
+
41
+ Both return `Result<SpecRegistry, SchemaError>`. Failure at any point (bad `$id`, non-parseable JSON, Ajv rejection) surfaces as `err`.
42
+
43
+ ### Validate semantics
44
+
45
+ `validate<T>(id, data)` returns:
46
+ - `{ kind: 'ok', value: data as T }` on success. The `T` type parameter is caller-asserted — Ajv validated the shape matches the JSON Schema, but the caller declares what TypeScript type that corresponds to. Callers keep the pairing correct until we add TS codegen from schemas.
47
+ - `{ kind: 'err', error }` on failure. The error is a discriminated union: `schema-not-found` (id not registered), `validation-error` (Ajv rejected the data, raw `errors[]` available).
48
+
49
+ Validators are pre-compiled at construction time — `validate` is a hot-path operation with no per-call compilation cost.
50
+
51
+ ## Version extraction
52
+
53
+ `versionOf(schema)` parses two things:
54
+ - **Major version** from `$id` — the `v<N>` segment in `https://kindgi.com/schemas/v<N>/<name>.schema.json`. Returned as `SchemaMajor` (branded number).
55
+ - **Full semver** from `$comment: "schema-version: X.Y.Z"`. Returned as `Semver` (branded string).
56
+
57
+ The regex patterns are strict:
58
+ ```
59
+ $id: ^https://kindgi\.com/schemas/v(\d+)/([a-z][a-z0-9-]*)\.schema\.json$
60
+ $comment: ^schema-version: (\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)$
61
+ ```
62
+
63
+ Semver prereleases (`1.0.0-rc.3`) are supported. Non-conforming `$id` or `$comment` returns `err`.
64
+
65
+ **Not checked here:** consistency between the `$id` major (`v1`) and the `$comment` major (`1.x.y`). That's a lint concern — if `$id: v2` but `$comment: schema-version: 1.5.0`, this function still returns ok with major=2 and semver=1.5.0. A separate consistency check (in `@kindgi/specs`' `scripts/validate.mjs`, run by `pnpm run spec:validate`) catches drift.
66
+
67
+ ## Error shapes
68
+
69
+ `SchemaError` is a discriminated union. Consumers switch on `code`:
70
+
71
+ | Code | Fields | When |
72
+ |---|---|---|
73
+ | `schema-load-error` | `path`, `cause` | Filesystem I/O failed |
74
+ | `schema-parse-error` | `path`, `cause` | JSON.parse threw |
75
+ | `schema-compile-error` | `id`, `cause` | Schema structurally invalid or Ajv rejected during registration |
76
+ | `schema-not-found` | `id` | Validate/get for an unregistered `$id` |
77
+ | `validation-error` | `id`, `errors[]` | Ajv found data invalid; `errors[]` is the raw Ajv report |
78
+
79
+ Every error has `code` and `message`. Consumers should match on `code`; `message` is documentation-grade but not part of the contract.
80
+
81
+ ## Testing strategy
82
+
83
+ **Unit** (`src/*.test.ts`):
84
+ - `version.test.ts` — valid and invalid `$id` / `$comment` combinations, prereleases, higher majors.
85
+ - `registry.test.ts` — empty registry, populated registry, cross-`$ref` resolution, missing `$id`, non-object schemas, validate positive/negative, `getSchema`, `schema-not-found`.
86
+
87
+ **Integration** (`tests/*.test.ts`):
88
+ - `specs-integration.test.ts` — loads the real `@kindgi/specs` directory, exercises every registered schema, validates a real flow document, confirms error paths.
89
+
90
+ ## Zod as optional authoring surface
91
+
92
+ JSON Schema stays the **authoritative wire form**. Every artifact registered in `SpecRegistry`, every manifest exchanged over MCP / HTTP / cross-runtime discovery, every schema published in `@kindgi/specs/*.schema.json` remains a Draft 2020-12 JSON Schema document. Nothing changes for non-TS consumers.
93
+
94
+ With Zod v4 as the workspace-wide version, `@kindgi/schema` exposes three helpers that let downstream packages (`@kindgi/tools`, `@kindgi/guardrails`, and consumers below) accept **either** JSON Schema **or** Zod v4 schemas at authoring time:
95
+
96
+ - `isZodSchema(value): value is ZodLikeSchema` — structural check for the `_zod` + `~standard` shape Zod v4 stamps on every schema. No runtime import of `zod`; safe when the peer dep is absent.
97
+ - `schemaKindOf(value): 'zod' | 'json-schema'` — sugar over `isZodSchema`.
98
+ - `toJSONSchema(schema): Result<JSONSchemaObject, InvalidZodConversionError>` — async, dynamic-imports `zod` on first use. Companion `toJSONSchemaSync` accepts a pre-loaded converter for sync authoring paths; the corresponding `loadZodConverterSync()` uses Node's `createRequire` so `defineTool` / `defineCheck` stay synchronous.
99
+
100
+ **`zod` is a peer dependency** on every package that accepts Zod authoring. Workspaces that never write Zod never install it and never pay any resolution cost. Callers who pass a Zod schema without `zod` on their `node_modules` get a typed `invalid-zod-conversion` error surfaced through the returned `Result` — never a module-resolution crash.
101
+
102
+ **Fidelity + limitations** — `z.toJSONSchema()` covers Zod primitives, objects, arrays, unions, discriminated unions, literals, enums, records, tuples, optional/nullable/nonoptional wrappers, defaults, catches, coerced primitives, refinements, and pipes. Unrepresentable constructs (`z.function()`, `z.symbol()`, `.transform()` chains whose output has no JSON Schema equivalent) throw at conversion — we surface those as `invalid-zod-conversion` at the boundary so authors see the failure immediately, not at wire time.
103
+
104
+ **Not supported** — `z.fromJSONSchema()` (the reverse direction) and other TS validation libraries (Effect Schema, Valibot, …).
105
+
106
+ ## Non-goals
107
+
108
+ - **No wire-level Zod.** Every artifact on the wire is a JSON Schema. Language-agnostic MCP + OpenAPI + Python/Go/Rust consumers must never see Zod.
109
+ - **No TS type generation from JSON Schemas.** Callers maintain matching TS types by hand, or author with Zod and derive them via `z.infer<...>`.
110
+ - **No custom Ajv keywords or extensions.** Stock Ajv Draft 2020-12 + `ajv-formats` only.
111
+ - **No schema migration between majors.** Not needed until any schema has a v2.
112
+ - **No caching of loaded registries across calls.** Callers manage their own registry lifecycle.
113
+
114
+ ## Change discipline
115
+
116
+ `SpecRegistry` is a stable interface — additions are non-breaking, removals or signature changes are semver-major.
117
+
118
+ `SchemaError` union is stable — adding a new variant is non-breaking as long as consumers exhaustively switch on `code` with a default case (or accept unknown codes gracefully).
119
+
120
+ `versionOf` output shape (`{ major, semver }`) is stable. Adding fields (e.g. `prerelease`) is non-breaking.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Canonical JSON serialization — deterministic, reproducible byte-shape
3
+ * suitable for signing.
4
+ *
5
+ * A simplified RFC 8785 (JSON Canonicalization Scheme, JCS) implementation
6
+ * covering the subset of JSON the framework emits: primitives, arrays, and
7
+ * objects with sorted string keys.
8
+ *
9
+ * Rules:
10
+ * - Object keys are sorted lexicographically.
11
+ * - `undefined` values are omitted entirely (they're never signed).
12
+ * - `null` is preserved.
13
+ * - Numbers are serialized via `JSON.stringify` — sufficient for the
14
+ * integer + normal-float range the framework emits; if callers ever
15
+ * emit denormalized doubles or high-precision values, revisit.
16
+ * - Strings use JSON escaping (again via `JSON.stringify`).
17
+ * - No whitespace between tokens.
18
+ *
19
+ * This lives in the public `@kindgi/schema` package because:
20
+ * - Signature verifiers on the SDK side must reproduce the exact
21
+ * same bytes to check signatures — moving this to closed code
22
+ * would break client-side verify.
23
+ * - The algorithm is a public commitment: existing signatures become
24
+ * unverifiable if this changes.
25
+ */
26
+ export declare function canonicalize(value: unknown): string;
27
+ //# sourceMappingURL=canonical.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical.d.ts","sourceRoot":"","sources":["../src/canonical.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAuBnD"}
@@ -0,0 +1,55 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ /**
4
+ * Canonical JSON serialization — deterministic, reproducible byte-shape
5
+ * suitable for signing.
6
+ *
7
+ * A simplified RFC 8785 (JSON Canonicalization Scheme, JCS) implementation
8
+ * covering the subset of JSON the framework emits: primitives, arrays, and
9
+ * objects with sorted string keys.
10
+ *
11
+ * Rules:
12
+ * - Object keys are sorted lexicographically.
13
+ * - `undefined` values are omitted entirely (they're never signed).
14
+ * - `null` is preserved.
15
+ * - Numbers are serialized via `JSON.stringify` — sufficient for the
16
+ * integer + normal-float range the framework emits; if callers ever
17
+ * emit denormalized doubles or high-precision values, revisit.
18
+ * - Strings use JSON escaping (again via `JSON.stringify`).
19
+ * - No whitespace between tokens.
20
+ *
21
+ * This lives in the public `@kindgi/schema` package because:
22
+ * - Signature verifiers on the SDK side must reproduce the exact
23
+ * same bytes to check signatures — moving this to closed code
24
+ * would break client-side verify.
25
+ * - The algorithm is a public commitment: existing signatures become
26
+ * unverifiable if this changes.
27
+ */
28
+ export function canonicalize(value) {
29
+ if (value === null)
30
+ return 'null';
31
+ if (typeof value === 'boolean')
32
+ return value ? 'true' : 'false';
33
+ if (typeof value === 'number') {
34
+ if (!Number.isFinite(value)) {
35
+ throw new Error(`Cannot canonicalize non-finite number: ${String(value)}`);
36
+ }
37
+ return JSON.stringify(value);
38
+ }
39
+ if (typeof value === 'string')
40
+ return JSON.stringify(value);
41
+ if (Array.isArray(value)) {
42
+ const parts = value.map((item) => canonicalize(item));
43
+ return `[${parts.join(',')}]`;
44
+ }
45
+ if (typeof value === 'object') {
46
+ const obj = value;
47
+ const keys = Object.keys(obj)
48
+ .filter((k) => obj[k] !== undefined)
49
+ .sort();
50
+ const parts = keys.map((k) => `${JSON.stringify(k)}:${canonicalize(obj[k])}`);
51
+ return `{${parts.join(',')}}`;
52
+ }
53
+ throw new Error(`Cannot canonicalize value of type ${typeof value}`);
54
+ }
55
+ //# sourceMappingURL=canonical.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canonical.js","sourceRoot":"","sources":["../src/canonical.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAClC,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IAChE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,KAAK,CAAC,0CAA0C,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC5D,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QACtD,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAChC,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,MAAM,GAAG,GAAG,KAA0C,CAAC;QACvD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;aAC1B,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC;aACnC,IAAI,EAAE,CAAC;QACV,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC9E,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC;IAChC,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,qCAAqC,OAAO,KAAK,EAAE,CAAC,CAAC;AACvE,CAAC"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Typed errors emitted by @kindgi/schema.
3
+ *
4
+ * Every error carries:
5
+ * - `code` — machine-readable discriminator for `if (err.code === ...)` matching.
6
+ * - `message` — human-readable summary.
7
+ * - Case-specific fields (path, id, cause, errors[]).
8
+ *
9
+ * Consumers should switch on `code`, not on `message`. Message strings are
10
+ * documentation-grade but not part of the API contract.
11
+ */
12
+ export type SchemaError = SchemaLoadError | SchemaParseError | SchemaCompileError | SchemaNotFoundError | ValidationError | InvalidZodConversionError;
13
+ /** Filesystem error while reading a schema file or specs directory. */
14
+ export interface SchemaLoadError {
15
+ readonly code: 'schema-load-error';
16
+ readonly message: string;
17
+ readonly path: string;
18
+ readonly cause: unknown;
19
+ }
20
+ /** JSON parse error while reading a schema file. */
21
+ export interface SchemaParseError {
22
+ readonly code: 'schema-parse-error';
23
+ readonly message: string;
24
+ readonly path: string;
25
+ readonly cause: unknown;
26
+ }
27
+ /**
28
+ * Ajv rejected the schema during registration/compilation.
29
+ * Also used when a schema is structurally invalid (missing `$id`, etc).
30
+ */
31
+ export interface SchemaCompileError {
32
+ readonly code: 'schema-compile-error';
33
+ readonly message: string;
34
+ readonly id: string;
35
+ readonly cause: unknown;
36
+ }
37
+ /** Requested a schema by `$id` that isn't registered. */
38
+ export interface SchemaNotFoundError {
39
+ readonly code: 'schema-not-found';
40
+ readonly message: string;
41
+ readonly id: string;
42
+ }
43
+ /**
44
+ * Data did not validate against the schema. `errors` holds Ajv's error report,
45
+ * intentionally typed as `unknown[]` — consumers must cast to `AjvError[]` if
46
+ * they want to inspect fields, so this package doesn't leak the Ajv API shape.
47
+ */
48
+ export interface ValidationError {
49
+ readonly code: 'validation-error';
50
+ readonly message: string;
51
+ readonly id: string;
52
+ readonly errors: readonly unknown[];
53
+ }
54
+ /**
55
+ * A Zod schema was passed at an authoring boundary and either
56
+ * - the `zod` peer dependency is not installed, or
57
+ * - `z.toJSONSchema(schema)` threw (unrepresentable Zod construct —
58
+ * e.g. `.transform()` targeting a runtime side-effect, function
59
+ * schemas, uncontained cycles).
60
+ *
61
+ * `cause` is the underlying Error, preserved for surfacing to the author.
62
+ */
63
+ export interface InvalidZodConversionError {
64
+ readonly code: 'invalid-zod-conversion';
65
+ readonly message: string;
66
+ readonly cause: unknown;
67
+ }
68
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;GAUG;AACH,MAAM,MAAM,WAAW,GACnB,eAAe,GACf,gBAAgB,GAChB,kBAAkB,GAClB,mBAAmB,GACnB,eAAe,GACf,yBAAyB,CAAC;AAE9B,uEAAuE;AACvE,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED,oDAAoD;AACpD,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,oBAAoB,CAAC;IACpC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,IAAI,EAAE,sBAAsB,CAAC;IACtC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB;AAED,yDAAyD;AACzD,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;CACrC;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,yBAAyB;IACxC,QAAQ,CAAC,IAAI,EAAE,wBAAwB,CAAC;IACxC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;CACzB"}
package/dist/errors.js ADDED
@@ -0,0 +1,4 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export {};
4
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC"}
@@ -0,0 +1,9 @@
1
+ export { canonicalize } from './canonical.js';
2
+ export type { InvalidZodConversionError, SchemaCompileError, SchemaError, SchemaLoadError, SchemaNotFoundError, SchemaParseError, ValidationError, } from './errors.js';
3
+ export { compileInlineSchema, createSpecRegistry, loadSpecRegistry } from './registry.js';
4
+ export type { CompiledInlineSchema, SpecRegistry, ValidationErrorLike } from './registry.js';
5
+ export { versionOf } from './version.js';
6
+ export type { SchemaVersion } from './version.js';
7
+ export { isJsonSchemaObject, isZodSchema, loadZodConverter, loadZodConverterSync, parseWithSchema, schemaKindOf, toJSONSchema, toJSONSchemaSync, } from './zod.js';
8
+ export type { AnySchema, JSONSchemaObject, SchemaIo, SchemaIssue, SchemaKind, ZodConverter, ZodLikeSchema, } from './zod.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,YAAY,EACV,yBAAyB,EACzB,kBAAkB,EAClB,WAAW,EACX,eAAe,EACf,mBAAmB,EACnB,gBAAgB,EAChB,eAAe,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAC1F,YAAY,EAAE,oBAAoB,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC7F,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,oBAAoB,EACpB,eAAe,EACf,YAAY,EACZ,YAAY,EACZ,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,WAAW,EACX,UAAU,EACV,YAAY,EACZ,aAAa,GACd,MAAM,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ export { canonicalize } from './canonical.js';
4
+ export { compileInlineSchema, createSpecRegistry, loadSpecRegistry } from './registry.js';
5
+ export { versionOf } from './version.js';
6
+ export { isJsonSchemaObject, isZodSchema, loadZodConverter, loadZodConverterSync, parseWithSchema, schemaKindOf, toJSONSchema, toJSONSchemaSync, } from './zod.js';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AAEjC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAU9C,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAE1F,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,gBAAgB,EAChB,oBAAoB,EACpB,eAAe,EACf,YAAY,EACZ,YAAY,EACZ,gBAAgB,GACjB,MAAM,UAAU,CAAC"}