@crud-api/schema 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +142 -2
- package/dist/collection.d.ts +20 -0
- package/dist/collection.js +234 -0
- package/dist/conformance.d.ts +7 -0
- package/dist/conformance.js +7 -0
- package/dist/convert.d.ts +23 -0
- package/dist/convert.js +304 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +6 -0
- package/dist/owned.d.ts +18 -0
- package/dist/owned.js +142 -0
- package/dist/reads.d.ts +14 -0
- package/dist/reads.js +67 -0
- package/dist/schema.d.ts +19 -0
- package/dist/schema.js +98 -0
- package/dist/validate.d.ts +32 -0
- package/dist/validate.js +259 -0
- package/dist/validator.d.ts +52 -0
- package/dist/validator.js +138 -0
- package/dist/vocabulary.d.ts +23 -0
- package/dist/vocabulary.js +52 -0
- package/dist/writes.d.ts +24 -0
- package/dist/writes.js +196 -0
- package/package.json +56 -5
package/README.md
CHANGED
|
@@ -1,3 +1,143 @@
|
|
|
1
|
-
# @crud-api/schema
|
|
1
|
+
# @crud-api/schema
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
- `checkSchemaDefinition(schema, validator, rule?)` (D157): the checks of a written schema without the `_id` and `_meta` steps (dialect, meta-schema, ESType compile, `refCollection` placement, validator compile), for schemas held in other Fields; the `INVALID_INPUT` failures carry `rule` (default SCHEMA_META_SCHEMA, with SCHEMA_REF_COLLECTION for the placement), the dialect failure stays `NEGOTIATION`, rule SCHEMA_DIALECT. `@crud-api/views` checks the `params` and `schema` of a View with it (rule VIEW_DEFINITION_VALIDATE).
|
|
66
|
+
- `checkValue(schema, value, { validator, codec, input, convertDbType? })` (D157): validates and converts one value as a write would (validation units, `refCollection`, `estype` and `dbType` conversion) without the strict or lenient policy, and returns `{ units, value }`, `value` converted when there is no unit; check the schema with `checkSchemaDefinition` first, since a schema it cannot compile throws. `@crud-api/views` validates and converts View parameters with it.
|
|
67
|
+
- `SCHEMA_VERSION`: `"0.1.0"` (the version of the specification); `conformance`: see below.
|
|
68
|
+
|
|
69
|
+
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) and `jsonTree` of `@crud-api/core` 0.6.0: a reserved provider for `@schema`, `attach`, placeholders, owned values, Parameters scoped to a Collection, result annotations and `meta.input`.
|
|
70
|
+
|
|
71
|
+
### The validator interface
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
interface OutputUnit {
|
|
75
|
+
readonly instanceLocation: string;
|
|
76
|
+
readonly keywordLocation: string;
|
|
77
|
+
readonly error: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface SchemaValidator {
|
|
81
|
+
/** SCHEMA_META_SCHEMA: the units of a written schema against the dialect and both vocabularies; [] when valid. */
|
|
82
|
+
checkSchema(schema: unknown): OutputUnit[];
|
|
83
|
+
/** 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. */
|
|
84
|
+
compile(compiled: unknown): (instance: unknown) => OutputUnit[];
|
|
85
|
+
/** The regular expression engine, also used by the extension for `patternProperties`; default `defaultRegExp`. */
|
|
86
|
+
readonly regExp?: (pattern: string, flags: string) => { test(text: string): boolean };
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
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.
|
|
91
|
+
|
|
92
|
+
### Regular expressions
|
|
93
|
+
|
|
94
|
+
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):
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
import RE2 from "re2";
|
|
98
|
+
import { metadata } from "@crud-api/metadata";
|
|
99
|
+
import { ajvValidator, schema } from "@crud-api/schema";
|
|
100
|
+
|
|
101
|
+
const extensions = [schema({ validator: ajvValidator({ regExp: (pattern, flags) => new RE2(pattern, flags) }) }), metadata()];
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
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.
|
|
105
|
+
|
|
106
|
+
## Behaviour
|
|
107
|
+
|
|
108
|
+
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:
|
|
109
|
+
|
|
110
|
+
- **`@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.
|
|
111
|
+
- **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).
|
|
112
|
+
- **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.
|
|
113
|
+
- **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.
|
|
114
|
+
- **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.
|
|
115
|
+
- **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.
|
|
116
|
+
- **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.
|
|
117
|
+
- **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`; `listByView` does not, since the schema of a Collection does not describe the items of its Views (VIEW_SCHEMA).
|
|
118
|
+
|
|
119
|
+
## System storage and atomicity
|
|
120
|
+
|
|
121
|
+
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.
|
|
122
|
+
|
|
123
|
+
- **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.
|
|
124
|
+
- **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.
|
|
125
|
+
- 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.
|
|
126
|
+
|
|
127
|
+
## Data sources with their own schema
|
|
128
|
+
|
|
129
|
+
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).
|
|
130
|
+
|
|
131
|
+
- `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).
|
|
132
|
+
- `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.
|
|
133
|
+
- `convertValue(dbType, value)`: converts a value of a Field with `dbType` and no `estype`, or throws `INVALID_INPUT`.
|
|
134
|
+
- `deriveSchema(collection, ctx)` (optional): the schema built from the Data source, or `null`.
|
|
135
|
+
- `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).
|
|
136
|
+
|
|
137
|
+
## Conformance
|
|
138
|
+
|
|
139
|
+
`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).
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
import { conformance } from "@crud-api/schema";
|
|
143
|
+
```
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { EstypeError, type Path, type Schema } from "@estype/core";
|
|
2
|
+
import { EcsonError, type EcsonCodec } from "@estype/core/convert";
|
|
3
|
+
import type { PatternTest } from "./owned.ts";
|
|
4
|
+
/** A value that cannot be converted: its path and the error of the converter. */
|
|
5
|
+
export interface ConversionFailure {
|
|
6
|
+
readonly path: Path;
|
|
7
|
+
readonly error: EstypeError | EcsonError;
|
|
8
|
+
}
|
|
9
|
+
/** The converted copy of a value (the input is never changed) and the failures, in the order of the walk. */
|
|
10
|
+
export type CollectingConverter = (value: unknown) => {
|
|
11
|
+
readonly value: unknown;
|
|
12
|
+
readonly failures: readonly ConversionFailure[];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Builds a converter for a schema, like `createConverter`: the schema is checked first (`checkSchema`), so an invalid
|
|
16
|
+
* `estype` throws here, before any value. Each value that cannot be converted (`CONVERT_FAIL`, `CONVERT_UNSUPPORTED`,
|
|
17
|
+
* `REF_UNRESOLVED`, a malformed ECSON form) is one failure; the walk goes on, so the work is linear in the size of the
|
|
18
|
+
* value whatever the number of failures.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createCollectingConverter(schema: Schema, options: {
|
|
21
|
+
readonly codec?: EcsonCodec;
|
|
22
|
+
readonly matches: PatternTest;
|
|
23
|
+
}): CollectingConverter;
|