@crud-api/schema 0.1.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 CHANGED
@@ -62,9 +62,11 @@ Over HTTP, `@crud-api/http` maps `/@schema`, the alias `/:collection/@schema`, `
62
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
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
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.
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.
66
68
 
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`.
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`.
68
70
 
69
71
  ### The validator interface
70
72
 
@@ -112,7 +114,7 @@ Decisions D138 to D154 of `docs/decisions.md` record each reading, and S59 to S7
112
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.
113
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.
114
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.
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`.
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).
116
118
 
117
119
  ## System storage and atomicity
118
120
 
package/dist/index.d.ts CHANGED
@@ -3,4 +3,6 @@ export type { SchemaOptions } from "./schema.ts";
3
3
  export { ajvValidator, defaultRegExp } from "./validator.ts";
4
4
  export type { AjvValidatorOptions, OutputUnit, RegExpEngine, RegExpLike, SchemaValidator } from "./validator.ts";
5
5
  export { META_SCHEMA_URI, SUPPORTED_DIALECTS, VOCABULARY_URI, vocabularyMetaSchema } from "./vocabulary.ts";
6
+ export { checkSchemaDefinition } from "./writes.ts";
7
+ export { checkValue } from "./validate.ts";
6
8
  export { conformance } from "./conformance.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { schema, SCHEMA_VERSION } from "./schema.js";
2
2
  export { ajvValidator, defaultRegExp } from "./validator.js";
3
3
  export { META_SCHEMA_URI, SUPPORTED_DIALECTS, VOCABULARY_URI, vocabularyMetaSchema } from "./vocabulary.js";
4
+ export { checkSchemaDefinition } from "./writes.js";
5
+ export { checkValue } from "./validate.js";
4
6
  export { conformance } from "./conformance.js";
package/dist/reads.d.ts CHANGED
@@ -9,6 +9,6 @@ export declare function registeredSchema(env: SchemaEnv, collection: string, ctx
9
9
  * `afterRead` (D144). On `@schema` with `compiled: true`: the annotation `compiled`, the schema compiled by ESType of
10
10
  * every returned Resource with a schema; `get` of a placeholder fails with NOT_FOUND, target `schema`
11
11
  * (SCHEMA_NOT_FOUND_TARGET). On a data Collection with a registered schema: the annotation `schema`, its Collection and
12
- * version (`_meta.version`, null when absent).
12
+ * version (`_meta.version`, null when absent), for `get` and `list` only (D157.3).
13
13
  */
14
14
  export declare function readSchema(env: SchemaEnv, input: AfterReadInput, ctx: HookCtx): Promise<Resource[]>;
package/dist/reads.js CHANGED
@@ -33,7 +33,7 @@ function define(target, key, value) {
33
33
  * `afterRead` (D144). On `@schema` with `compiled: true`: the annotation `compiled`, the schema compiled by ESType of
34
34
  * every returned Resource with a schema; `get` of a placeholder fails with NOT_FOUND, target `schema`
35
35
  * (SCHEMA_NOT_FOUND_TARGET). On a data Collection with a registered schema: the annotation `schema`, its Collection and
36
- * version (`_meta.version`, null when absent).
36
+ * version (`_meta.version`, null when absent), for `get` and `list` only (D157.3).
37
37
  */
38
38
  export async function readSchema(env, input, ctx) {
39
39
  const { collection, resources } = input;
@@ -53,7 +53,9 @@ export async function readSchema(env, input, ctx) {
53
53
  ctx.annotate("compiled", compiled);
54
54
  return resources;
55
55
  }
56
- if (!isSlug(collection))
56
+ // D157.3: only `get` and `list` describe their Resources with the schema; `listByView` returns what a View makes of
57
+ // them (an aggregate, a projection), which the schema of the Collection does not describe (VIEW_SCHEMA).
58
+ if (!isSlug(collection) || (input.operation !== "get" && input.operation !== "list"))
57
59
  return resources;
58
60
  const registered = await registeredSchema(env, collection, ctx);
59
61
  if (registered !== null) {
@@ -1,8 +1,26 @@
1
- import { type BeforeWriteInput, type HookCtx, type OwnedValues, type Resource } from "@crud-api/core";
1
+ import { type BeforeWriteInput, type HookCtx, type OwnedValues, type Representation, type Resource } from "@crud-api/core";
2
+ import type { Codec } from "@ecson/core";
2
3
  import { type SchemaEnv } from "./collection.ts";
3
- import type { SchemaValidator } from "./validator.ts";
4
+ import type { OutputUnit, SchemaValidator } from "./validator.ts";
4
5
  /** D147.1: `ownedValues` on a data Collection: the values under a subschema with `estype` of its registered schema. */
5
6
  export declare function ownedByRegistered(env: SchemaEnv, validator: SchemaValidator, collection: string, ctx: HookCtx): Promise<OwnedValues | null>;
7
+ /**
8
+ * D157.2: the validation and the conversion of D147 (items 2 and 3) of `value` against any schema, without the strict or
9
+ * lenient policy: the validation tree (a JSON tree for `input: "json"`, the ECSON tree for `"ecson"`), the `refCollection`
10
+ * second pass, the ESType conversion and, with `convertDbType`, the `dbType` conversion of the values without `estype`.
11
+ * `units` is every violation; `value` is the converted copy when there is no unit, else `value` as received. Throws what
12
+ * ESType or the validator throw for a schema they refuse: check it first with `checkSchemaDefinition`. `validateWrite`
13
+ * runs the same steps on the registered schema, which it prepares once per operation.
14
+ */
15
+ export declare function checkValue(schema: unknown, value: Resource, options: {
16
+ validator: SchemaValidator;
17
+ codec: Codec;
18
+ input: Representation;
19
+ convertDbType?: (dbType: string, value: unknown) => unknown;
20
+ }): {
21
+ units: OutputUnit[];
22
+ value: Resource;
23
+ };
6
24
  /**
7
25
  * D147: `beforeWrite` on a data Collection with a registered schema. The Resource, without `_meta`
8
26
  * (SCHEMA_VALIDATE_WRITES), is validated as received (SCHEMA_ESTYPE_VALIDATE) against the schema compiled by ESType,
package/dist/validate.js CHANGED
@@ -1,11 +1,10 @@
1
1
  // D147: validation and conversion of the Resources written to a data Collection with a registered schema
2
2
  // (SCHEMA_VALIDATE_WRITES, SCHEMA_ESTYPE_VALIDATE, SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE, SCHEMA_STRICT,
3
3
  // SCHEMA_LENIENT, SCHEMA_REF_COLLECTION, SCHEMA_VIOLATION_DETAILS; S64 to S67).
4
- import { checkFieldNames, CrudError, isPlainObject, isSlug } from "@crud-api/core";
4
+ import { checkFieldNames, CrudError, isPlainObject, isSlug, jsonTree } from "@crud-api/core";
5
5
  import { compile, toPointer } from "@estype/core";
6
6
  import { SCHEMA_COLLECTION } from "./collection.js";
7
7
  import { createCollectingConverter } from "./convert.js";
8
- import { jsonTree } from "./json-tree.js";
9
8
  import { ownedValues, patternTest } from "./owned.js";
10
9
  import { registeredSchema } from "./reads.js";
11
10
  /** The key of `HookCtx.local` that caches what validating against a registered schema needs, by Collection (D138). */
@@ -18,6 +17,21 @@ function hasMember(value, name) {
18
17
  return false;
19
18
  return Object.hasOwn(value, name) || Object.values(value).some((member) => hasMember(member, name));
20
19
  }
20
+ /** A schema prepared for `check`: compiled by ESType and by the validator, with its converter (throws for a schema they refuse). */
21
+ function prepare(schema, validator, codec, validation) {
22
+ const matches = patternTest(validator.regExp);
23
+ const compiled = compile(schema);
24
+ return {
25
+ validation,
26
+ schema,
27
+ compiled,
28
+ validate: validator.compile(compiled),
29
+ convert: createCollectingConverter(schema, { codec, matches }),
30
+ matches,
31
+ owned: ownedValues(schema, matches),
32
+ refCollection: hasMember(schema, "refCollection"),
33
+ };
34
+ }
21
35
  /** The registered schema of a data Collection, prepared for validation, or null without one (SCHEMA_NULL). */
22
36
  async function registered(env, validator, collection, ctx) {
23
37
  if (collection === SCHEMA_COLLECTION || !isSlug(collection))
@@ -34,14 +48,8 @@ async function registered(env, validator, collection, ctx) {
34
48
  let prepared = null;
35
49
  if (resource !== null && (typeof resource.schema === "boolean" || isPlainObject(resource.schema))) {
36
50
  const schema = resource.schema;
37
- let compiled;
38
- let validate;
39
- let convert;
40
- const matches = patternTest(validator.regExp);
41
51
  try {
42
- compiled = compile(schema);
43
- validate = validator.compile(compiled);
44
- convert = createCollectingConverter(schema, { codec: env.codec, matches });
52
+ prepared = prepare(schema, validator, env.codec, resource.validation === "strict" ? "strict" : "lenient");
45
53
  }
46
54
  catch (error) {
47
55
  // D147 amended: a schema stored before D143 compiled it at write time, seeded, or that a custom validator refuses.
@@ -51,16 +59,6 @@ async function registered(env, validator, collection, ctx) {
51
59
  cause: error,
52
60
  });
53
61
  }
54
- prepared = {
55
- validation: resource.validation === "strict" ? "strict" : "lenient",
56
- schema,
57
- compiled,
58
- validate,
59
- convert,
60
- matches,
61
- owned: ownedValues(schema, matches),
62
- refCollection: hasMember(schema, "refCollection"),
63
- };
64
62
  }
65
63
  cache.set(collection, prepared);
66
64
  return prepared;
@@ -175,30 +173,20 @@ function convertEach(target, body, units) {
175
173
  return value;
176
174
  }
177
175
  /**
178
- * D147: `beforeWrite` on a data Collection with a registered schema. The Resource, without `_meta`
179
- * (SCHEMA_VALIDATE_WRITES), is validated as received (SCHEMA_ESTYPE_VALIDATE) against the schema compiled by ESType,
180
- * then converted (SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE). `strict`: any unit fails the write with
181
- * INVALID_INPUT (SCHEMA_STRICT); `lenient`: one SCHEMA_VIOLATION Warning per unit (SCHEMA_LENIENT, S67), and every
182
- * value is written converted, except those that cannot be, which are written as received (S64). Without a registered
183
- * schema: unchanged.
176
+ * D147.2 and D147.3 without the policy: the units of `body` against a prepared schema (validation as received, the
177
+ * second pass of `refCollection`, then the conversion failures), and `body` converted, every value that cannot be
178
+ * converted kept as received (S64).
184
179
  */
185
- export async function validateWrite(env, validator, input, ctx) {
186
- const { next } = input;
187
- const target = await registered(env, validator, input.collection, ctx);
188
- if (target === null)
189
- return next;
190
- const { codec } = ctx;
191
- const hasMeta = Object.hasOwn(next, "_meta");
192
- const { _meta: meta, ...body } = next;
193
- const id = typeof next._id === "string" ? next._id : undefined;
180
+ function check(target, body, options) {
181
+ const { codec } = options;
194
182
  // D147.2: the validation tree is the value as received: a JSON tree for a plain JSON Subject, else its ECSON tree.
195
- const units = target.validate(ctx.input === "json" ? jsonTree(body, codec) : codec.encode(body));
183
+ const units = target.validate(options.input === "json" ? jsonTree(body, codec) : codec.encode(body));
196
184
  // D147.3: conversion of the values with `estype`, then of those with `dbType` only (each failing one left as received).
197
185
  const conversion = [];
198
186
  let result = convertEach(target, body, conversion);
199
- const hooks = env.provider.schema;
200
- if (hooks !== undefined)
201
- result = convertDbTypes(target.schema, result, (dbType, value) => hooks.convertValue(dbType, value), [], conversion);
187
+ const { convertDbType } = options;
188
+ if (convertDbType !== undefined)
189
+ result = convertDbTypes(target.schema, result, convertDbType, [], conversion);
202
190
  if (target.refCollection) {
203
191
  // SCHEMA_REF_COLLECTION, S65: `refCollection` sits in the plain branch of the compiled schema, so every reference is
204
192
  // checked through the plain form of the converted value, whatever form it arrived in (a `{ "$rel": ... }` of a plain
@@ -212,6 +200,42 @@ export async function validateWrite(env, validator, input, ctx) {
212
200
  }
213
201
  }
214
202
  units.push(...conversion);
203
+ return { units, converted: result };
204
+ }
205
+ /**
206
+ * D157.2: the validation and the conversion of D147 (items 2 and 3) of `value` against any schema, without the strict or
207
+ * lenient policy: the validation tree (a JSON tree for `input: "json"`, the ECSON tree for `"ecson"`), the `refCollection`
208
+ * second pass, the ESType conversion and, with `convertDbType`, the `dbType` conversion of the values without `estype`.
209
+ * `units` is every violation; `value` is the converted copy when there is no unit, else `value` as received. Throws what
210
+ * ESType or the validator throw for a schema they refuse: check it first with `checkSchemaDefinition`. `validateWrite`
211
+ * runs the same steps on the registered schema, which it prepares once per operation.
212
+ */
213
+ export function checkValue(schema, value, options) {
214
+ const { units, converted } = check(prepare(schema, options.validator, options.codec, "strict"), value, options);
215
+ return { units, value: units.length === 0 ? converted : value };
216
+ }
217
+ /**
218
+ * D147: `beforeWrite` on a data Collection with a registered schema. The Resource, without `_meta`
219
+ * (SCHEMA_VALIDATE_WRITES), is validated as received (SCHEMA_ESTYPE_VALIDATE) against the schema compiled by ESType,
220
+ * then converted (SCHEMA_VALUE_CONVERSION, SCHEMA_VALUE_NO_ESTYPE). `strict`: any unit fails the write with
221
+ * INVALID_INPUT (SCHEMA_STRICT); `lenient`: one SCHEMA_VIOLATION Warning per unit (SCHEMA_LENIENT, S67), and every
222
+ * value is written converted, except those that cannot be, which are written as received (S64). Without a registered
223
+ * schema: unchanged.
224
+ */
225
+ export async function validateWrite(env, validator, input, ctx) {
226
+ const { next } = input;
227
+ const target = await registered(env, validator, input.collection, ctx);
228
+ if (target === null)
229
+ return next;
230
+ const hasMeta = Object.hasOwn(next, "_meta");
231
+ const { _meta: meta, ...body } = next;
232
+ const id = typeof next._id === "string" ? next._id : undefined;
233
+ const hooks = env.provider.schema;
234
+ const { units, converted: result } = check(target, body, {
235
+ codec: ctx.codec,
236
+ input: ctx.input,
237
+ ...(hooks !== undefined ? { convertDbType: (dbType, value) => hooks.convertValue(dbType, value) } : {}),
238
+ });
215
239
  if (units.length > 0) {
216
240
  if (target.validation === "strict") {
217
241
  throw new CrudError("INVALID_INPUT", `the Resource${id === undefined ? "" : ` ${id}`} does not conform to the schema of ${input.collection}: ${units[0]?.error ?? ""}`, {
package/dist/writes.d.ts CHANGED
@@ -3,6 +3,16 @@ import { type SchemaEnv } from "./collection.ts";
3
3
  import type { SchemaValidator } from "./validator.ts";
4
4
  /** D141: on `@schema` the extension reads `schema` itself, so `$schema`, `$ref`, `$defs` and `$id` are not FIELDS_NO_PREFIXES. */
5
5
  export declare const ownsSchema: OwnedValues;
6
+ /**
7
+ * D157.1, steps 1 to 4 and 6 of D142, in this order: the dialect of every `$schema` (SCHEMA_DIALECT, NEGOTIATION), the
8
+ * meta-schema of the dialect and both vocabularies (`rule`), the ESType compilation (`rule`), `refCollection` only with
9
+ * `estype: rel` (SCHEMA_REF_COLLECTION) and the compilation of the ESType result by the validator (`rule`, D143
10
+ * amended). The checks that name a Collection (`_id`, `_meta`) are not here: `checkWrittenSchema` adds them. These
11
+ * failures are INVALID_INPUT, as the rules name it, whatever produced the schema. `rule` is SCHEMA_META_SCHEMA for the
12
+ * Schema extension; another extension that holds schemas (Views, `params` and `schema`) gives its own rule, and the
13
+ * placement failure of `refCollection` then has that rule too.
14
+ */
15
+ export declare function checkSchemaDefinition(schema: unknown, validator: SchemaValidator, rule?: string): void;
6
16
  /**
7
17
  * `beforeWrite` on `@schema`: the Resource the write stores, `{ _id, validation, schema }` plus Metadata's `_meta`.
8
18
  * D141, in this order: `_id` given (SCHEMA_CREATE_ID, SCHEMA_CLONE_ID), a Slug (SCHEMA_COLLECTION), no other Field
package/dist/writes.js CHANGED
@@ -1,9 +1,8 @@
1
1
  // Writes on `@schema`: the checks of a schema Resource (D141), of the written schema (D142), derivation (D146), the
2
2
  // Collection it describes (D145) and the Data sources with their own schema (D148).
3
- import { CrudError, isPlainObject, isSlug } from "@crud-api/core";
3
+ import { CrudError, isPlainObject, isSlug, jsonTree } from "@crud-api/core";
4
4
  import { children, compile, EstypeError } from "@estype/core";
5
5
  import { SCHEMA_COLLECTION } from "./collection.js";
6
- import { jsonTree } from "./json-tree.js";
7
6
  import { SUPPORTED_DIALECTS } from "./vocabulary.js";
8
7
  /** SCHEMA_RESOURCE_FIELDS: the Fields of a schema Resource (`_meta` is Metadata's). */
9
8
  const FIELDS = new Set(["_id", "validation", "schema", "_meta"]);
@@ -23,13 +22,20 @@ function* subschemas(schema) {
23
22
  /** SCHEMA_DIALECT: a supported dialect URI, also with an empty fragment. */
24
23
  const supported = (dialect) => SUPPORTED_DIALECTS.includes(dialect.endsWith("#") ? dialect.slice(0, -1) : dialect);
25
24
  /**
26
- * D142, in this order: the dialect of every `$schema` (SCHEMA_DIALECT, NEGOTIATION), the meta-schema of the dialect and
27
- * both vocabularies (SCHEMA_META_SCHEMA, SCHEMA_VOCABULARY), the ESType compilation (SCHEMA_META_SCHEMA), `refCollection`
28
- * only with `estype: rel` (SCHEMA_REF_COLLECTION), an explicit type for `_id` (SCHEMA_ID_FIELD, S59, S60), no `_meta`
29
- * (SCHEMA_NO_META_FIELD) and last the compilation of the ESType result by the validator (SCHEMA_META_SCHEMA, D143
30
- * amended). These failures are INVALID_INPUT, as the rules name it, whatever produced the Resource.
25
+ * D157.1, steps 1 to 4 and 6 of D142, in this order: the dialect of every `$schema` (SCHEMA_DIALECT, NEGOTIATION), the
26
+ * meta-schema of the dialect and both vocabularies (`rule`), the ESType compilation (`rule`), `refCollection` only with
27
+ * `estype: rel` (SCHEMA_REF_COLLECTION) and the compilation of the ESType result by the validator (`rule`, D143
28
+ * amended). The checks that name a Collection (`_id`, `_meta`) are not here: `checkWrittenSchema` adds them. These
29
+ * failures are INVALID_INPUT, as the rules name it, whatever produced the schema. `rule` is SCHEMA_META_SCHEMA for the
30
+ * Schema extension; another extension that holds schemas (Views, `params` and `schema`) gives its own rule, and the
31
+ * placement failure of `refCollection` then has that rule too.
31
32
  */
32
- function checkWrittenSchema(schema, validator) {
33
+ export function checkSchemaDefinition(schema, validator, rule = "SCHEMA_META_SCHEMA") {
34
+ definition(schema, validator, rule, () => { });
35
+ }
36
+ /** `checkSchemaDefinition`, running `between` after the `refCollection` check and before the validator compiles (D142 order). */
37
+ function definition(schema, validator, rule, between) {
38
+ const placement = rule === "SCHEMA_META_SCHEMA" ? "SCHEMA_REF_COLLECTION" : rule;
33
39
  for (const node of subschemas(schema)) {
34
40
  const dialect = node.$schema;
35
41
  if (typeof dialect === "string" && !supported(dialect)) {
@@ -38,7 +44,7 @@ function checkWrittenSchema(schema, validator) {
38
44
  }
39
45
  const errors = validator.checkSchema(schema);
40
46
  if (errors.length > 0) {
41
- throw new CrudError("INVALID_INPUT", `the schema does not conform to its meta-schema: ${errors[0]?.error ?? ""}`, { rule: "SCHEMA_META_SCHEMA", data: { errors } });
47
+ throw new CrudError("INVALID_INPUT", `the schema does not conform to its meta-schema: ${errors[0]?.error ?? ""}`, { rule, data: { errors } });
42
48
  }
43
49
  let compiled;
44
50
  try {
@@ -48,24 +54,16 @@ function checkWrittenSchema(schema, validator) {
48
54
  if (!(error instanceof EstypeError))
49
55
  throw error;
50
56
  throw new CrudError("INVALID_INPUT", `the schema cannot be compiled by ESType: ${error.message}`, {
51
- rule: "SCHEMA_META_SCHEMA",
57
+ rule,
52
58
  data: { estypeCode: error.code, path: [...error.path] },
53
59
  });
54
60
  }
55
61
  for (const node of subschemas(schema)) {
56
62
  if (Object.hasOwn(node, "refCollection") && node.estype !== "rel") {
57
- throw new CrudError("INVALID_INPUT", "refCollection is only allowed with estype rel", { rule: "SCHEMA_REF_COLLECTION" });
63
+ throw new CrudError("INVALID_INPUT", "refCollection is only allowed with estype rel", { rule: placement });
58
64
  }
59
65
  }
60
- const properties = isPlainObject(schema) && isPlainObject(schema.properties) ? schema.properties : undefined;
61
- const id = properties !== undefined && Object.hasOwn(properties, "_id") ? properties._id : undefined;
62
- if (!isPlainObject(id) || !Object.hasOwn(id, "type")) {
63
- throw new CrudError("INVALID_INPUT", "the schema must describe the _id Field with an explicit type (properties._id.type)", { rule: "SCHEMA_ID_FIELD" });
64
- }
65
- const required = isPlainObject(schema) && Array.isArray(schema.required) ? schema.required : [];
66
- if (Object.hasOwn(properties, "_meta") || required.includes("_meta")) {
67
- throw new CrudError("INVALID_INPUT", "the schema must not describe the _meta Field", { rule: "SCHEMA_NO_META_FIELD" });
68
- }
66
+ between();
69
67
  // D143 amended: the validator compiles the schema now, so that a schema it cannot compile (an unresolvable `$ref`, an
70
68
  // invalid `pattern`, a `$ref` cycle, an `$id` clash) is refused here instead of making its Collection unwritable.
71
69
  try {
@@ -75,9 +73,27 @@ function checkWrittenSchema(schema, validator) {
75
73
  // Ajv's MissingRefError keeps the name Error: the class name tells it apart.
76
74
  const reason = error instanceof Error ? error.constructor.name || error.name : typeof error;
77
75
  const detail = error instanceof Error ? error.message : String(error);
78
- throw new CrudError("INVALID_INPUT", `the schema cannot be compiled by the validator: ${detail}`, { rule: "SCHEMA_META_SCHEMA", data: { reason } });
76
+ throw new CrudError("INVALID_INPUT", `the schema cannot be compiled by the validator: ${detail}`, { rule, data: { reason } });
79
77
  }
80
78
  }
79
+ /**
80
+ * D142, in this order: `checkSchemaDefinition` up to the ESType compilation and `refCollection` (SCHEMA_DIALECT,
81
+ * SCHEMA_META_SCHEMA, SCHEMA_VOCABULARY, SCHEMA_REF_COLLECTION), an explicit type for `_id` (SCHEMA_ID_FIELD, S59, S60),
82
+ * no `_meta` (SCHEMA_NO_META_FIELD) and last the compilation by the validator (SCHEMA_META_SCHEMA, D143 amended).
83
+ */
84
+ function checkWrittenSchema(schema, validator) {
85
+ definition(schema, validator, "SCHEMA_META_SCHEMA", () => {
86
+ const properties = isPlainObject(schema) && isPlainObject(schema.properties) ? schema.properties : undefined;
87
+ const id = properties !== undefined && Object.hasOwn(properties, "_id") ? properties._id : undefined;
88
+ if (!isPlainObject(id) || !Object.hasOwn(id, "type")) {
89
+ throw new CrudError("INVALID_INPUT", "the schema must describe the _id Field with an explicit type (properties._id.type)", { rule: "SCHEMA_ID_FIELD" });
90
+ }
91
+ const required = isPlainObject(schema) && Array.isArray(schema.required) ? schema.required : [];
92
+ if (Object.hasOwn(properties, "_meta") || required.includes("_meta")) {
93
+ throw new CrudError("INVALID_INPUT", "the schema must not describe the _meta Field", { rule: "SCHEMA_NO_META_FIELD" });
94
+ }
95
+ });
96
+ }
81
97
  /** SCHEMA_DB_TYPE_INFER: top-level properties without `dbType` get the one the Data source infers; a new tree. */
82
98
  function inferDbTypes(schema, infer) {
83
99
  if (!isPlainObject(schema.properties))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crud-api/schema",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Schema extension of the CRUD API reference implementation: a JSON Schema per Collection, validation of written Resources, the CRUD Schema vocabulary and the ESType vocabulary",
5
5
  "keywords": [
6
6
  "crud",
@@ -44,7 +44,7 @@
44
44
  "access": "public"
45
45
  },
46
46
  "dependencies": {
47
- "@crud-api/core": "^0.5.0",
47
+ "@crud-api/core": "^0.6.0",
48
48
  "@estype/ajv": "^0.2.0",
49
49
  "@estype/core": "^0.2.0",
50
50
  "@unquery/core": "^0.2.0",
@@ -54,8 +54,8 @@
54
54
  "@ecson/core": "^0.2.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@crud-api/memory": "^0.5.0",
58
- "@crud-api/metadata": "^0.1.3",
59
- "@crud-api/relationships": "^0.1.1"
57
+ "@crud-api/memory": "^0.6.0",
58
+ "@crud-api/metadata": "^0.1.4",
59
+ "@crud-api/relationships": "^0.1.2"
60
60
  }
61
61
  }
@@ -1,8 +0,0 @@
1
- import { type Codec } from "@ecson/core";
2
- /**
3
- * D141: normalizes a `schema` value to a JSON tree without escaping. A JSON Schema has keys that start with `$`
4
- * (`$ref`, `$defs`, `$schema`, `$id`) and ECSON encoding would escape them, so plain objects and arrays are walked and
5
- * keep their keys. A host value becomes its ECSON form with the Server's codec (`Date` becomes `{ "$date": ... }`), and
6
- * an `UnknownTag` its single member object: `{"$ref": "#/x"}` sent as ECSON decodes to one. Never mutates `value`.
7
- */
8
- export declare function jsonTree(value: unknown, codec: Codec): unknown;
package/dist/json-tree.js DELETED
@@ -1,31 +0,0 @@
1
- // D141: the `schema` of a Schema Resource is stored as a JSON tree, not as an ECSON tree.
2
- import { isPlainObject } from "@crud-api/core";
3
- import { UnknownTag } from "@ecson/core";
4
- /**
5
- * D141: normalizes a `schema` value to a JSON tree without escaping. A JSON Schema has keys that start with `$`
6
- * (`$ref`, `$defs`, `$schema`, `$id`) and ECSON encoding would escape them, so plain objects and arrays are walked and
7
- * keep their keys. A host value becomes its ECSON form with the Server's codec (`Date` becomes `{ "$date": ... }`), and
8
- * an `UnknownTag` its single member object: `{"$ref": "#/x"}` sent as ECSON decodes to one. Never mutates `value`.
9
- */
10
- export function jsonTree(value, codec) {
11
- if (value === null || typeof value === "string" || typeof value === "boolean")
12
- return value;
13
- if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0))
14
- return value;
15
- if (value instanceof UnknownTag)
16
- return Object.fromEntries([[value.tag, value.value]]);
17
- if (Array.isArray(value))
18
- return value.map((element) => jsonTree(element, codec));
19
- if (isPlainObject(value)) {
20
- const tree = {};
21
- for (const name of Object.keys(value)) {
22
- const member = value[name];
23
- if (member === undefined)
24
- continue; // like JSON: an undefined member is absent
25
- // Own data property, so that a `__proto__` key never reaches the prototype setter.
26
- Object.defineProperty(tree, name, { value: jsonTree(member, codec), writable: true, enumerable: true, configurable: true });
27
- }
28
- return tree;
29
- }
30
- return codec.encode(value);
31
- }