@crud-api/schema 0.0.0-stage → 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,202 @@
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 reasonable and customary use in describing the
141
+ origin of the Work and 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 [yyyy] [name of copyright owner]
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.
202
+
package/README.md CHANGED
@@ -1,3 +1,141 @@
1
- # Temporary Holding Version
1
+ # @crud-api/schema
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [Schema extension](https://lingodata.3gr.am/crud/schema/schema/) (`schema 0.1.0`) of the CRUD API reference implementation: a JSON Schema 2020-12 per Collection, kept as the Resources of the reserved Collection `@schema` and managed with the Base operations, the validation and conversion of every Resource written to a Collection with a registered schema, the CRUD Schema vocabulary (`refCollection`, `dbType`) and the [ESType](https://github.com/lingodata/estype) vocabulary (`estype`), and the provider hooks of Data sources that enforce a schema of their own.
4
+
5
+ ESM only, requires Node 24 or later (also runs on Bun and Deno). Apache-2.0.
6
+
7
+ ## Usage
8
+
9
+ ```ts
10
+ import { createCrudServer } from "@crud-api/core";
11
+ import { createMemoryProvider } from "@crud-api/memory";
12
+ import { metadata } from "@crud-api/metadata";
13
+ import { schema } from "@crud-api/schema";
14
+
15
+ const provider = createMemoryProvider({ collections: { customers: {} } });
16
+ const server = createCrudServer({ provider, extensions: [schema(), metadata()] });
17
+
18
+ await server.execute({
19
+ operation: "create",
20
+ collection: "@schema",
21
+ resources: {
22
+ _id: "customers",
23
+ validation: "strict",
24
+ schema: {
25
+ type: "object",
26
+ properties: {
27
+ _id: { type: "string" },
28
+ name: { type: "string" },
29
+ since: { type: "string", estype: "date" },
30
+ },
31
+ required: ["name"],
32
+ },
33
+ },
34
+ });
35
+
36
+ // A plain JSON body: "since" is validated as received, then stored as a Date.
37
+ await server.execute({
38
+ operation: "create",
39
+ collection: "customers",
40
+ resources: { _id: "c1", name: "Ana", since: "2026-12-04T12:00:00Z" },
41
+ meta: { input: "json" },
42
+ });
43
+
44
+ // Fails with INVALID_INPUT, rule SCHEMA_STRICT, writing nothing:
45
+ // error.data = { errors: [{ instanceLocation: "", keywordLocation: "/required", error: "must have required property 'name'" }], id: "c2" }
46
+ await server.execute({ operation: "create", collection: "customers", resources: { _id: "c2", age: 3 } });
47
+
48
+ // Every Collection of the API, with or without a schema (SCHEMA_LIST_ALL).
49
+ await server.execute({ operation: "list", collection: "@schema", params: { fields: "_id" } });
50
+ ```
51
+
52
+ The Schema extension requires Metadata (`_meta.version` is the version of a schema, SCHEMA_VERSION), a system storage (design 6.10: by default the data provider, when it declares `systemCollections`; otherwise `createCrudServer({ system })`) and a data provider with `listCollections`; `createCrudServer` refuses to start without them. `schema()` must come before `relationships()` and `metadata()` in `extensions`: it converts values (references among them) before Relationships drops their `data`, and Metadata hashes the converted stored form; the other order fails when the server is built (`Extension.before`).
53
+
54
+ Over HTTP, `@crud-api/http` maps `/@schema`, the alias `/:collection/@schema`, `@derive`, `Accept: application/schema+json` (the compiled schema alone), the `describedby` link and the 422 of a strict schema (HTTP section 7, D151). Over MCP, `@crud-api/mcp` adds the `derive` argument, the `crud.schema.*` tools, Collection tools typed with the compiled schema, `_meta["dev.lingodata/crud.schema"]` and the MCP resources `lingodata-crud://schema/{collection}` (MCP section 6, D152). Both turn these on when `schema` is among the Server's specifications.
55
+
56
+ ## API
57
+
58
+ - `schema(options?)`: the extension, for `createCrudServer({ extensions })`. One instance serves one Server. Its `validator` member is the `SchemaValidator` in use.
59
+ - `validator` (default `ajvValidator()`): the JSON Schema validator (D143).
60
+ - `forceStrict` (default `false`): every schema is stored with `validation: strict`, with the Warning `VALIDATION_FORCED` when the Client sent `lenient` (SCHEMA_FORCED_STRICT).
61
+ - Other members or types are a `TypeError`.
62
+ - `ajvValidator(options?)`: the default validator, [Ajv](https://ajv.js.org/) 2020 with [`@estype/ajv`](https://github.com/lingodata/estype) and the keywords of the CRUD Schema vocabulary; properties are checked as own properties, so `required: ["__proto__"]` holds.
63
+ - `regExp` (default `defaultRegExp`, ECMAScript's `RegExp`): the regular expression engine, `(pattern, flags) => { test(text) }`, given to Ajv as `code.regExp`; see [Regular expressions](#regular-expressions).
64
+ - `vocabularyMetaSchema`: the meta-schema of the CRUD Schema vocabulary (`refCollection` a Collection Slug, `dbType` a non-empty string); `VOCABULARY_URI` (`https://lingodata.dev/crud/schema/vocab/0.1`) and `META_SCHEMA_URI` (`https://lingodata.dev/crud/schema/meta/0.1`), both provisional as the specification says; `SUPPORTED_DIALECTS`: JSON Schema 2020-12 and the ESType dialect.
65
+ - `SCHEMA_VERSION`: `"0.1.0"`; `conformance`: see below.
66
+
67
+ It declares the reserved Collection `@schema`, the error code `SCHEMA_INCOMPATIBLE`, the Warning codes `SCHEMA_VIOLATION` and `VALIDATION_FORCED`, and two Parameters that apply to `@schema` only: `derive` (`create`, `replaceById`, `replaceByQuery`; a boolean) and `compiled` (`get`, `list`; `true`, set by the Protocols to get the compiled schemas as the annotation `compiled`). It uses the hook points of `@crud-api/core` 0.5.0 (D138): a reserved provider for `@schema`, `attach`, placeholders, owned values, Parameters scoped to a Collection, result annotations and `meta.input`.
68
+
69
+ ### The validator interface
70
+
71
+ ```ts
72
+ interface OutputUnit {
73
+ readonly instanceLocation: string;
74
+ readonly keywordLocation: string;
75
+ readonly error: string;
76
+ }
77
+
78
+ interface SchemaValidator {
79
+ /** SCHEMA_META_SCHEMA: the units of a written schema against the dialect and both vocabularies; [] when valid. */
80
+ checkSchema(schema: unknown): OutputUnit[];
81
+ /** A validation function for a schema already compiled by ESType; units of the `basic` output format, [] when valid. Throws for a schema it cannot compile. */
82
+ compile(compiled: unknown): (instance: unknown) => OutputUnit[];
83
+ /** The regular expression engine, also used by the extension for `patternProperties`; default `defaultRegExp`. */
84
+ readonly regExp?: (pattern: string, flags: string) => { test(text: string): boolean };
85
+ }
86
+ ```
87
+
88
+ Any JSON Schema 2020-12 validator that reports `basic` output units can be plugged in (design 7.4, D5). `checkSchema` must apply JSON Schema 2020-12, the ESType vocabulary meta-schema and `vocabularyMetaSchema` to every subschema; `compile` receives the schema compiled by `@estype/core`, where `refCollection` must check that a plain collection object (or each one of an array) names that Collection. `compile` throws for a schema it cannot compile; a written schema is compiled when it is written, so such a schema is refused then (`INVALID_INPUT`, SCHEMA_META_SCHEMA, `data.reason`), and a registered one that still cannot be compiled (stored by an older version, seeded) fails each write on its Collection with `INTERNAL`, rule SCHEMA_VALIDATE_WRITES. `ajvValidator()` does both, removes duplicate units and keeps 64 compiled functions, the oldest removed first.
89
+
90
+ ### Regular expressions
91
+
92
+ The keywords `pattern` and `patternProperties` come from the schemas Clients write, and run against every written Resource. ECMAScript's `RegExp` backtracks: a pattern such as `^(a+)+$` takes seconds on a value of 30 characters, and blocks the Server meanwhile. A Server that lets untrusted Clients write schemas should plug a linear engine, for example [`re2`](https://www.npmjs.com/package/re2) on Node (this package depends on none):
93
+
94
+ ```ts
95
+ import RE2 from "re2";
96
+ import { metadata } from "@crud-api/metadata";
97
+ import { ajvValidator, schema } from "@crud-api/schema";
98
+
99
+ const extensions = [schema({ validator: ajvValidator({ regExp: (pattern, flags) => new RE2(pattern, flags) }) }), metadata()];
100
+ ```
101
+
102
+ The engine receives the flag `u`; a pattern it refuses makes the schema fail when it is written. The extension matches `patternProperties` (owned values, conversion) with the `regExp` of the validator, each pattern compiled once per operation; a custom validator without `regExp` gets ECMAScript's.
103
+
104
+ ## Behaviour
105
+
106
+ Decisions D138 to D154 of `docs/decisions.md` record each reading, and S59 to S71 of `docs/spec-issues.md` the gaps of the specification; in short:
107
+
108
+ - **`@schema`** (SCHEMA_COLLECTION, SCHEMA_LIST_ALL, SCHEMA_NULL): one Resource per Collection of the data provider (each Slug of `listCollections`), plus every stored schema. A Collection without a registered schema reads as `{ "_id": "<slug>", "schema": null }` and nothing is stored for it. Every Base operation applies: filters (UnQuery), sorting, offset pages and counts; no cursor pages and no native query formats. `@schema` never lists itself, and a stored schema whose Collection was dropped outside the API is still listed.
109
+ - **Schema Resources** (SCHEMA_RESOURCE_FIELDS, SCHEMA_VALIDATION_DEFAULT, SCHEMA_CREATE_ID, SCHEMA_CLONE_ID): `_id` (the Slug, always sent by the Client, also as `newId` of a `clone`), `validation` (`strict` or `lenient`, `lenient` by default), `schema` (an object; `null` is never written, delete the schema instead) and `_meta`. The schema is stored and returned exactly as sent, `$schema`, `$id`, `$ref` and `$defs` included, whether it came as plain JSON or as ECSON (S70).
110
+ - **Written schemas** (SCHEMA_DIALECT, SCHEMA_META_SCHEMA, SCHEMA_ID_FIELD, SCHEMA_NO_META_FIELD, SCHEMA_REF_COLLECTION): every `$schema` must be JSON Schema 2020-12 or the ESType dialect (otherwise `NEGOTIATION`, with `data.supported`); the schema must conform to the meta-schemas (`INVALID_INPUT` with `data.errors`) and compile with ESType (`data.estypeCode`, `data.path`) and then with the validator (`data.reason`: an unresolvable `$ref`, an invalid `pattern`, a `$ref` cycle, an `$id` clash); `refCollection` only with `estype: "rel"`; the top-level `properties._id` must have `type` (so a boolean schema is refused, S59, S60); `_meta` must not be described.
111
+ - **Writes on `@schema`** (SCHEMA_CREATE_NULL, SCHEMA_COLLECTION_MISSING, SCHEMA_COLLECTION_CREATE, SCHEMA_DELETE, SCHEMA_VERSION, SCHEMA_NO_REVALIDATION): `create` over a Collection without a schema is accepted, over a registered one it is `CONFLICT`; `replace` and `patch` of a Collection without a schema write its first version. A schema for a Collection that does not exist is `NOT_FOUND`, target `collection`, unless the data provider creates Collections implicitly, in which case the Collection is created with the schema. Deleting a schema never touches the Collection or its Resources. Changing a schema validates and changes no existing Resource.
112
+ - **Derivation** (SCHEMA_DERIVE): `derive: true` on `create` or `replace` asks the data provider for the schema (`provider.schema.deriveSchema`); the request must not carry `schema`; a provider that cannot derive is `UNSUPPORTED`. Without `derive` the schema is stored as sent.
113
+ - **Validation of Resources** (SCHEMA_VALIDATE_WRITES, SCHEMA_ESTYPE_VALIDATE, SCHEMA_STRICT, SCHEMA_LENIENT, SCHEMA_VIOLATION_DETAILS): every Resource that `create`, `clone`, `patch` and `replace` produce on a Collection with a registered schema is validated without `_meta`, as received (its plain JSON form for a plain JSON body, its ECSON form otherwise), against the schema compiled by ESType. Violations are `basic` output units whose `keywordLocation` refers to the compiled schema. `strict`: `INVALID_INPUT`, rule SCHEMA_STRICT, `data: { errors, id }`, nothing written, for the whole operation. `lenient`: written, with one `SCHEMA_VIOLATION` Warning per unit (`instance`, `keyword`, `id`; S67), which the strict preference of the Client turns into `STRICT_WARNINGS`. Reads never validate.
114
+ - **Conversion** (SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE, SCHEMA_REF_COLLECTION): a value under `estype` is converted to its host value from either form (`"2026-12-04T12:00:00Z"` or `{ "$date": ... }` to a `Date`, a collection object to a `Rel`), so a plain JSON body may carry ECSON forms in those Fields only; a value under `dbType` alone is converted by the data provider (`provider.schema.convertValue`). A value that cannot be converted is a violation at `.../estype` or `.../dbType` (S66); a lenient write stores it as received (S64). The conversion is one pass over the Resource, whatever the number of values that fail. Every reference is checked against `refCollection` in its plain form, whatever form it was sent in (S65). Without either keyword, nothing is converted.
115
+ - **Annotations**: `get` and `list` of a Collection with a registered schema annotate `meta.annotations.schema = { collection, version }`, which HTTP turns into a `describedby` link and MCP into `_meta`.
116
+
117
+ ## System storage and atomicity
118
+
119
+ Registered schemas are Resources of the Collection `@schema` of the system storage (design 6.10). The data provider is the system storage by default; `createCrudServer({ provider, system })` puts it on another provider.
120
+
121
+ - **Same provider with transactions** (the normal case): a write on `@schema` runs in one transaction of that provider: the creation of a missing Collection, the change of a Data source with its own schema (`applySchema`) and the schema itself happen together or not at all.
122
+ - **Another provider, or no transactions**: there is no transaction across the two, and a compensating write would not be atomic either. A schema write for a Collection whose Data source has its own schema fails with `UNSUPPORTED` (SCHEMA_SOURCE_APPLY) before anything changes. Collections without their own schema are not affected, but a schema write that fails after creating a missing Collection leaves that Collection empty.
123
+ - The registered schema of a Collection is read from the system storage once per operation, outside the transaction of the write it validates: a schema changed while a write runs may or may not apply to it.
124
+
125
+ ## Data sources with their own schema
126
+
127
+ A provider whose Data source enforces a schema (tables, typed properties) implements `Provider.schema` (`ProviderSchemaHooks` of `@crud-api/core`) and the `applySchema` primitive; `@crud-api/memory` simulates one with its `schema` option (D149).
128
+
129
+ - `ownSchema(collection, ctx)`: whether the Collection has its own schema. For those, `validation` is always stored `strict` (`VALIDATION_FORCED` when the Client sent `lenient`, SCHEMA_FORCED_STRICT), top-level properties without `dbType` get the one `inferDbType(field)` gives (SCHEMA_DB_TYPE_INFER, stored and returned), the write runs `applySchema` in the transaction of the system write, and deleting the schema is `UNSUPPORTED` (SCHEMA_SOURCE_DELETE).
130
+ - `acceptsDbType(dbType, field)`: every `dbType` of a written schema must be accepted, otherwise `SCHEMA_INCOMPATIBLE` (SCHEMA_DB_TYPE_CLIENT). A provider without hooks accepts none.
131
+ - `convertValue(dbType, value)`: converts a value of a Field with `dbType` and no `estype`, or throws `INVALID_INPUT`.
132
+ - `deriveSchema(collection, ctx)` (optional): the schema built from the Data source, or `null`.
133
+ - `applySchema`: `prepare` is the dry run, `execute` checks the stored data and changes the Data source's schema, or throws `SCHEMA_INCOMPATIBLE` changing nothing (SCHEMA_SOURCE_INCOMPATIBLE).
134
+
135
+ ## Conformance
136
+
137
+ `conformance` declares the Schema extension specification `0.1.0` (vector spec id `@crud-api/schema`) over the CRUD Base specification `0.2.0`. The engine vectors (`conformance/vectors/schema/`) run in the provider conformance kit of `@crud-api/conformance`, which enables `schema()` per case; cases that need a separate system storage call the provider factory twice, and cases of Data sources with their own schema run only against providers with `schema` hooks (D153). SCHEMA_LIST_CACHE (a MAY) is not used: the Collections of the Data source are never cached (D150).
138
+
139
+ ```ts
140
+ import { conformance } from "@crud-api/schema";
141
+ ```
@@ -0,0 +1,20 @@
1
+ import { type Provider, type Resource } from "@crud-api/core";
2
+ import type { Codec } from "@ecson/core";
3
+ /** SCHEMA_COLLECTION: the reserved Collection of schemas. */
4
+ export declare const SCHEMA_COLLECTION = "@schema";
5
+ /** What the virtual provider and the hooks work with: the providers `attach` received (D139). */
6
+ export interface SchemaEnv {
7
+ /** The data provider: which Collections exist, their own schema (design 7.4). */
8
+ readonly provider: Provider;
9
+ /** The system storage of design 6.10, whose Collection `@schema` keeps the registered schemas. */
10
+ readonly system: Provider;
11
+ readonly codec: Codec;
12
+ /** SCHEMA_FORCED_STRICT for every Collection (`SchemaOptions.forceStrict`, D148). */
13
+ readonly forceStrict: boolean;
14
+ }
15
+ /** SCHEMA_NULL: the schema Resource of a Collection without a registered schema; never stored. */
16
+ export declare const placeholder: (id: string) => Resource;
17
+ /** SCHEMA_NULL: a placeholder has `schema: null` and no `_meta` (a stored schema always has both a schema and `_meta`). */
18
+ export declare const isPlaceholder: (resource: Resource) => boolean;
19
+ /** Creates the virtual provider of `@schema` (D140). */
20
+ export declare function schemaProvider(env: SchemaEnv): Provider;
@@ -0,0 +1,234 @@
1
+ // D140: the `@schema` virtual provider (SCHEMA_COLLECTION, SCHEMA_LIST_ALL, SCHEMA_NULL). It serves the reserved
2
+ // Collection `@schema` over the data provider (which Collections exist) and the system storage (the registered
3
+ // schemas, stored in its Collection `@schema`), so that every Base operation applies to schemas (D138).
4
+ import { compareResources, CrudError, ID_KEY, isSlug, mapUnQueryError, sortArrayPathWarnings, sortKeys, } from "@crud-api/core";
5
+ import { createMatcher, evaluatorOperators, UnQueryError } from "@unquery/core";
6
+ /** SCHEMA_COLLECTION: the reserved Collection of schemas. */
7
+ export const SCHEMA_COLLECTION = "@schema";
8
+ /** SCHEMA_NULL: the schema Resource of a Collection without a registered schema; never stored. */
9
+ export const placeholder = (id) => ({ _id: id, schema: null });
10
+ /** SCHEMA_NULL: a placeholder has `schema: null` and no `_meta` (a stored schema always has both a schema and `_meta`). */
11
+ export const isPlaceholder = (resource) => resource.schema === null && !Object.hasOwn(resource, "_meta");
12
+ /** D140: the Collection `@schema` as the core sees it; placeholders are not conflicts for `create` and `clone` (D138). */
13
+ const INFO = Object.freeze({ slug: SCHEMA_COLLECTION, key: ID_KEY, idKinds: Object.freeze(["slug", "string"]), isPlaceholder });
14
+ const BRAND = Symbol("@crud-api/schema prepared");
15
+ /** Warnings of a primitive prepared again (inside a transaction, or as an `insert`) were already reported. */
16
+ const silent = (ctx) => ({ warn: () => { }, ...(ctx.codec !== undefined ? { codec: ctx.codec } : {}) });
17
+ function expectKind(result, kind) {
18
+ if (result.kind !== kind)
19
+ throw new Error(`the system storage answered a ${kind} primitive with a ${result.kind} result`);
20
+ return result;
21
+ }
22
+ /** Creates the virtual provider of `@schema` (D140). */
23
+ export function schemaProvider(env) {
24
+ const { provider, system } = env;
25
+ const systemCaps = system.capabilities();
26
+ const capabilities = Object.freeze({
27
+ operators: evaluatorOperators,
28
+ queryFormats: Object.freeze([]),
29
+ pagination: Object.freeze({ offset: true, cursor: false }),
30
+ sort: Object.freeze({ fields: true, nullsLowest: true }),
31
+ projection: false,
32
+ count: true,
33
+ transactions: systemCaps.transactions && system.transaction !== undefined,
34
+ conditionalWrite: false,
35
+ // SCHEMA_CREATE_ID: the core never generates the ID of a schema (generator `provider`), and this provider never does either.
36
+ ids: Object.freeze({ clientIds: true, generator: "provider", kinds: Object.freeze(["slug", "string"]) }),
37
+ nativeTypes: systemCaps.nativeTypes,
38
+ implicitCollections: false,
39
+ systemCollections: false,
40
+ });
41
+ const codecOf = (ctx) => ctx.codec ?? env.codec;
42
+ function prepareWith(io, request, ctx) {
43
+ if (request.collection !== SCHEMA_COLLECTION)
44
+ throw new TypeError(`the schema provider serves only ${SCHEMA_COLLECTION}, not ${request.collection}`);
45
+ switch (request.kind) {
46
+ case "find": {
47
+ if (request.native !== undefined)
48
+ throw new CrudError("UNSUPPORTED", `the Search Query format ${request.native.format} is not supported`, { rule: "SEARCH_QUERY_FORMATS" });
49
+ if (request.page.kind !== "offset")
50
+ throw new CrudError("UNSUPPORTED", "cursor pages are not supported", { rule: "PAGINATION_CURSOR" });
51
+ const filter = request.filter;
52
+ let matcher = null;
53
+ if (filter !== null) {
54
+ try {
55
+ matcher = createMatcher(filter, { ecson: codecOf(ctx) });
56
+ }
57
+ catch (error) {
58
+ throw error instanceof UnQueryError ? mapUnQueryError(error) : error;
59
+ }
60
+ }
61
+ return Object.freeze({ [BRAND]: true, request, matcher });
62
+ }
63
+ case "findByIds":
64
+ return Object.freeze({ [BRAND]: true, request });
65
+ case "insert":
66
+ case "replace":
67
+ case "remove":
68
+ // D140: the system storage prepares the write, so that its downgrade Warnings are the ones reported.
69
+ return Object.freeze({ [BRAND]: true, request, inner: io.prepare(request, ctx) });
70
+ default:
71
+ throw new TypeError(`the schema provider does not run ${request.kind} primitives`);
72
+ }
73
+ }
74
+ /** The stored schemas with the given IDs, by ID. */
75
+ async function storedByIds(scope, ids, ctx) {
76
+ const found = new Map();
77
+ if (ids.length === 0)
78
+ return found;
79
+ const request = { kind: "findByIds", collection: SCHEMA_COLLECTION, key: ID_KEY, ids, projection: null };
80
+ const result = expectKind(await scope.system.execute(scope.system.prepare(request, silent(ctx)), ctx), "findByIds");
81
+ for (const resource of result.resources)
82
+ found.set(resource._id, resource);
83
+ return found;
84
+ }
85
+ /** Every stored schema, page after page as the system storage serves them, sorted by Resource ID. */
86
+ async function storedAll(scope, ctx) {
87
+ const { offset: canOffset, cursor: canCursor, maxLimit } = systemCaps.pagination;
88
+ const limit = maxLimit ?? null;
89
+ const base = { kind: "find", collection: SCHEMA_COLLECTION, key: ID_KEY, filter: null, sort: sortKeys(null, ID_KEY), projection: null, count: false };
90
+ const all = [];
91
+ if (canOffset || !canCursor) {
92
+ for (let offset = 0;;) {
93
+ const request = { ...base, page: { kind: "offset", offset, limit } };
94
+ const result = expectKind(await scope.system.execute(scope.system.prepare(request, silent(ctx)), ctx), "find");
95
+ all.push(...result.resources);
96
+ if (limit === null || result.resources.length < limit)
97
+ return all;
98
+ offset += result.resources.length;
99
+ }
100
+ }
101
+ const seen = new Set();
102
+ for (let cursor = null;;) {
103
+ const request = { ...base, page: { kind: "cursor", cursor, limit } };
104
+ const result = expectKind(await scope.system.execute(scope.system.prepare(request, silent(ctx)), ctx), "find");
105
+ all.push(...result.resources);
106
+ const next = result.nextCursor ?? null;
107
+ if (next === null || seen.has(next) || result.resources.length === 0)
108
+ return all;
109
+ seen.add(next);
110
+ cursor = next;
111
+ }
112
+ }
113
+ /** A Collection of the API: a Slug the data provider has (system Collections are not Slugs, D150). */
114
+ async function exists(id) {
115
+ return typeof id === "string" && isSlug(id) && (await provider.collection(id, {})) !== null;
116
+ }
117
+ /**
118
+ * SCHEMA_LIST_ALL, SCHEMA_NULL: every Collection of the data provider (its Slugs only: `@schema` and the other system
119
+ * Collections are not Collections of the API, D150) united with the stored schemas (S62: also those of Collections
120
+ * that no longer exist); a Collection without a stored schema is its placeholder.
121
+ */
122
+ async function everySchema(scope, ctx) {
123
+ const stored = new Map();
124
+ for (const resource of await storedAll(scope, ctx))
125
+ stored.set(resource._id, resource);
126
+ const names = (await provider.listCollections({})).filter(isSlug);
127
+ const all = [...stored.values()];
128
+ for (const name of new Set(names))
129
+ if (!stored.has(name))
130
+ all.push(placeholder(name));
131
+ return all;
132
+ }
133
+ /**
134
+ * Before the system write of a schema (D140): the described Collection is created when it does not exist
135
+ * (SCHEMA_COLLECTION_CREATE; `beforeWrite` already checked that it can be, D145), and a Collection whose Data source
136
+ * has its own schema gets it applied, with the data provider's I/O of the same transaction (SCHEMA_SOURCE_APPLY, D148).
137
+ */
138
+ async function prepareCollection(scope, resource, ctx) {
139
+ const id = resource._id;
140
+ let info = await provider.collection(id, {});
141
+ if (info === null) {
142
+ // Inside the transaction when its primitives can create Collections, else with the data provider itself.
143
+ const creator = scope.data.createCollection !== undefined ? scope.data : provider;
144
+ if (creator.createCollection === undefined)
145
+ throw new Error(`the data provider cannot create the Collection ${id}`);
146
+ info = await creator.createCollection(id, {});
147
+ }
148
+ if (provider.schema !== undefined && (await provider.schema.ownSchema(id, {}))) {
149
+ const request = { kind: "applySchema", collection: id, key: info.key, schema: resource.schema };
150
+ expectKind(await scope.data.execute(scope.data.prepare(request, ctx), ctx), "applySchema");
151
+ }
152
+ }
153
+ async function executeWith(scope, prepared, ctx) {
154
+ if (prepared[BRAND] !== true)
155
+ throw new TypeError("execute: the prepared request does not come from the schema provider");
156
+ ctx.signal?.throwIfAborted();
157
+ const request = prepared.request;
158
+ switch (request.kind) {
159
+ case "find": {
160
+ const matcher = prepared.matcher ?? null;
161
+ let resources = await everySchema(scope, ctx);
162
+ if (matcher !== null)
163
+ resources = resources.filter(matcher);
164
+ resources.sort(compareResources(request.sort, { codec: codecOf(ctx) }));
165
+ for (const warning of sortArrayPathWarnings(resources, request.sort))
166
+ ctx.warn(warning); // SORTING_ARRAY_PATH
167
+ const total = resources.length;
168
+ const page = request.page;
169
+ const end = page.limit === null ? total : Math.min(total, page.offset + page.limit);
170
+ const result = { kind: "find", resources: resources.slice(page.offset, end) };
171
+ if (request.count)
172
+ result.matchedCount = total; // META_MATCHED_COUNT
173
+ return result;
174
+ }
175
+ case "findByIds": {
176
+ const ids = [...new Set(request.ids)];
177
+ const stored = await storedByIds(scope, ids, ctx);
178
+ const resources = [];
179
+ for (const id of ids) {
180
+ const found = stored.get(id) ?? ((await exists(id)) ? placeholder(id) : undefined);
181
+ if (found !== undefined)
182
+ resources.push(found);
183
+ }
184
+ return { kind: "findByIds", resources };
185
+ }
186
+ case "insert": {
187
+ for (const resource of request.resources)
188
+ await prepareCollection(scope, resource, ctx);
189
+ return scope.system.execute(prepared.inner, ctx); // over a placeholder: an insert into the system storage
190
+ }
191
+ case "replace": {
192
+ await prepareCollection(scope, request.resource, ctx);
193
+ if ((await storedByIds(scope, [request.id], ctx)).size > 0)
194
+ return scope.system.execute(prepared.inner, ctx);
195
+ // D140: a replace whose target is not stored (a placeholder) is the first version, an insert.
196
+ const insert = { kind: "insert", collection: SCHEMA_COLLECTION, key: ID_KEY, resources: [request.resource] };
197
+ const written = expectKind(await scope.system.execute(scope.system.prepare(insert, silent(ctx)), ctx), "insert");
198
+ return { kind: "replace", resource: written.resources[0] };
199
+ }
200
+ case "remove": {
201
+ // SCHEMA_DELETE, D145: stored schemas are removed; a placeholder counts as removed with nothing stored. The
202
+ // Collection and its Resources are never touched.
203
+ const ids = [...new Set(request.ids)];
204
+ const stored = await storedByIds(scope, ids, ctx);
205
+ let removed = 0;
206
+ if (stored.size > 0)
207
+ removed += expectKind(await scope.system.execute(prepared.inner, ctx), "remove").removed;
208
+ for (const id of ids)
209
+ if (!stored.has(id) && (await exists(id)))
210
+ removed++;
211
+ return { kind: "remove", removed };
212
+ }
213
+ default:
214
+ throw new TypeError(`the schema provider does not run ${request.kind} primitives`);
215
+ }
216
+ }
217
+ const outside = { system, data: provider };
218
+ const virtual = {
219
+ name: "schema",
220
+ capabilities: () => capabilities,
221
+ collection: async (slug) => (slug === SCHEMA_COLLECTION ? INFO : null),
222
+ prepare: (request, ctx) => prepareWith(system, request, ctx),
223
+ execute: (prepared, ctx) => executeWith(outside, prepared, ctx),
224
+ };
225
+ const transactional = system;
226
+ if (capabilities.transactions) {
227
+ virtual.transaction = (fn, ctx) => transactional.transaction((stx) => {
228
+ // D140: the data provider writes through the same transaction when it is the system storage.
229
+ const scope = { system: stx, data: provider === system ? stx : provider };
230
+ return fn({ prepare: (request, prepareCtx) => prepareWith(stx, request, prepareCtx), execute: (prepared, execCtx) => executeWith(scope, prepared, execCtx) });
231
+ }, ctx);
232
+ }
233
+ return virtual;
234
+ }
@@ -0,0 +1,7 @@
1
+ /** Conformance declaration of the Schema extension: its specification (vector spec id `@crud-api/schema`) and the Base it extends. */
2
+ export declare const conformance: Readonly<{
3
+ spec: "@crud-api/schema";
4
+ version: "0.1.0";
5
+ base: "0.2.0";
6
+ extension: "schema";
7
+ }>;
@@ -0,0 +1,7 @@
1
+ /** Conformance declaration of the Schema extension: its specification (vector spec id `@crud-api/schema`) and the Base it extends. */
2
+ export const conformance = Object.freeze({
3
+ spec: "@crud-api/schema",
4
+ version: "0.1.0",
5
+ base: "0.2.0",
6
+ extension: "schema",
7
+ });