@crud-api/core 0.2.0 → 0.3.1

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.
@@ -0,0 +1,19 @@
1
+ import type { Resource } from "./types.ts";
2
+ import { type Codec } from "@ecson/core";
3
+ /**
4
+ * The ECSON tag of a value, or `undefined` for JSON values (and for values outside the ECSON model). `codec` is the
5
+ * Server's (design 6.4), so the types of enabled extensions (`$rel`) have their tag; default the default codec of `@ecson/core`.
6
+ */
7
+ export declare function tagOf(value: unknown, codec?: Codec): string | undefined;
8
+ /** A Resource prepared for storage: the converted copy and the Fields whose values were downgraded, formatted. */
9
+ export interface Downgraded {
10
+ readonly resource: Resource;
11
+ readonly fields: readonly string[];
12
+ }
13
+ /**
14
+ * REPR_DOWNGRADE: a copy of `resource` where every value whose tag is not in `native` is replaced by its plain JSON
15
+ * form (`toPlain`). Plain objects and arrays are JSON containers and are traversed; the elements of a native `$set`
16
+ * or `$map` are traversed too, and reported with the path of the Field holding them (field paths have no indexes).
17
+ * Pure: never mutates `resource`.
18
+ */
19
+ export declare function downgrade(resource: Resource, native: ReadonlySet<string> | "all", codec?: Codec): Downgraded;
@@ -0,0 +1,70 @@
1
+ // REPR_NATIVE_STORAGE, REPR_DOWNGRADE (design 6.6): values are stored as host values; a value whose ECSON tag is not
2
+ // among the provider's declared native types is stored in its plain JSON form, and the Field is reported with
3
+ // TYPE_DOWNGRADED. Moved from `@crud-api/memory` so that providers and extensions share one definition of the stored
4
+ // form (D128): the Metadata hash describes the Resource as stored.
5
+ import { cloneValue, isPlainObject } from "./patch.js";
6
+ import { createCodec, isTypedValue, UnknownTag } from "@ecson/core";
7
+ import { formatPath } from "@unquery/core";
8
+ const DEFAULT_CODEC = createCodec();
9
+ /**
10
+ * The ECSON tag of a value, or `undefined` for JSON values (and for values outside the ECSON model). `codec` is the
11
+ * Server's (design 6.4), so the types of enabled extensions (`$rel`) have their tag; default the default codec of `@ecson/core`.
12
+ */
13
+ export function tagOf(value, codec = DEFAULT_CODEC) {
14
+ if (value === null || typeof value === "string" || typeof value === "boolean")
15
+ return undefined;
16
+ // A finite number other than -0 is a JSON number; NaN, the infinities and -0 are `$number` (ECSON).
17
+ if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0))
18
+ return undefined;
19
+ if (value instanceof UnknownTag)
20
+ return value.tag;
21
+ try {
22
+ const tree = codec.encode(value);
23
+ return isTypedValue(tree) ? Object.keys(tree)[0] : undefined;
24
+ }
25
+ catch {
26
+ // Decision: a value the ECSON codec cannot write (a function, a class instance) has no tag; it is copied as it is.
27
+ return undefined;
28
+ }
29
+ }
30
+ /**
31
+ * REPR_DOWNGRADE: a copy of `resource` where every value whose tag is not in `native` is replaced by its plain JSON
32
+ * form (`toPlain`). Plain objects and arrays are JSON containers and are traversed; the elements of a native `$set`
33
+ * or `$map` are traversed too, and reported with the path of the Field holding them (field paths have no indexes).
34
+ * Pure: never mutates `resource`.
35
+ */
36
+ export function downgrade(resource, native, codec = DEFAULT_CODEC) {
37
+ if (native === "all")
38
+ return { resource: cloneValue(resource), fields: [] };
39
+ const fields = [];
40
+ const report = (path) => {
41
+ const field = formatPath(path);
42
+ if (!fields.includes(field))
43
+ fields.push(field);
44
+ };
45
+ const walk = (value, path) => {
46
+ if (isPlainObject(value)) {
47
+ const copy = {};
48
+ for (const name of Object.keys(value)) {
49
+ // Own data property, so that a `__proto__` Field never reaches the prototype setter.
50
+ Object.defineProperty(copy, name, { value: walk(value[name], [...path, name]), writable: true, enumerable: true, configurable: true });
51
+ }
52
+ return copy;
53
+ }
54
+ if (Array.isArray(value))
55
+ return value.map((element) => walk(element, path));
56
+ const tag = tagOf(value, codec);
57
+ if (tag === undefined)
58
+ return cloneValue(value);
59
+ if (!native.has(tag)) {
60
+ report(path);
61
+ return codec.toPlain(value);
62
+ }
63
+ if (value instanceof Set)
64
+ return new Set([...value].map((element) => walk(element, path)));
65
+ if (value instanceof Map)
66
+ return new Map([...value].map(([k, v]) => [walk(k, path), walk(v, path)]));
67
+ return cloneValue(value);
68
+ };
69
+ return { resource: walk(resource, []), fields };
70
+ }
@@ -1,13 +1,45 @@
1
- import type { OperationName, Resource } from "./types.ts";
1
+ import type { Codec } from "@ecson/core";
2
+ import type { OperationName, Resource, ResourceId } from "./types.ts";
2
3
  import { CodeRegistry, type Warning } from "./warnings.ts";
3
- /** The context of an extension hook: Warnings go to the sink of the operation (WARN_EXTENSION_CODES). */
4
+ /**
5
+ * The context of an extension hook: Warnings go to the sink of the operation (WARN_EXTENSION_CODES); the clock and the
6
+ * codec are the Server's, and `principal` is the Client's identity as the Protocol adapter or host gave it (D116).
7
+ */
4
8
  export interface HookCtx {
5
9
  warn(warning: Warning): void;
10
+ /**
11
+ * Reports the Warning unless one with the same code and members (the message aside) was already reported in the
12
+ * operation, so that a hook called once per matched Resource reports what the Client sent once (D116).
13
+ */
14
+ warnOnce(warning: Warning): void;
15
+ /** Unix time in milliseconds, from the Server's injected clock. */
16
+ clock(): number;
17
+ /** `request.meta.principal`, undefined when none was given. */
18
+ readonly principal: unknown;
19
+ /** The ECSON codec of the Server (design 6.4). */
20
+ readonly codec: Codec;
21
+ /**
22
+ * The form the data provider stores the Resource in (REPR_DOWNGRADE): values whose ECSON tag is not among its
23
+ * declared `nativeTypes` in their plain JSON form (D128). Pure; the Resource given is not changed.
24
+ */
25
+ stored(resource: Resource): Resource;
26
+ }
27
+ /**
28
+ * A Parameter an extension adds (design 7, "extra Parameters"; D116): recognized by the listed operations, so that it
29
+ * is not reported as PARAM_IGNORED there (PARAM_CUSTOM_UNKNOWN), and passed to the extension's hooks in `params`.
30
+ */
31
+ export interface ExtensionParameter {
32
+ readonly name: string;
33
+ readonly operations: readonly OperationName[];
34
+ /** Checks the value in step 6 of design 6.3, before anything is read; throws a CrudError when it is invalid. */
35
+ check?(value: unknown): void;
6
36
  }
37
+ /** The Parameters of one extension that the request sent, by name (D116). */
38
+ export type ExtensionParams = Readonly<Record<string, unknown>>;
7
39
  /**
8
40
  * An extension of the Base Specification (design 7): a factory result passed to `createCrudServer`. Phase 2 offers
9
- * the minimum hooks (`beforeWrite`, `afterRead`); later phases add reserved Collection handlers, extra operations and
10
- * the execution mode.
41
+ * `beforeWrite` and `afterRead`, phase 7 (Metadata) Parameters and `precondition` (D116); later phases add reserved
42
+ * Collection handlers, extra operations and the execution mode.
11
43
  */
12
44
  export interface Extension {
13
45
  /** Unique name, such as `metadata`. */
@@ -31,19 +63,58 @@ export interface Extension {
31
63
  readonly errorCodes?: readonly string[];
32
64
  /** Warning codes of the extension (WARN_EXTENSION_CODES: never a Base code). */
33
65
  readonly warningCodes?: readonly string[];
34
- /** Called on each Resource about to be written, with its previous state (null on create, clone and upsert). */
35
- beforeWrite?(input: {
36
- readonly operation: OperationName;
37
- readonly collection: string;
38
- readonly previous: Resource | null;
39
- readonly next: Resource;
40
- }, ctx: HookCtx): Resource | Promise<Resource>;
66
+ /** Parameters of the extension (D116). */
67
+ readonly parameters?: readonly ExtensionParameter[];
68
+ /**
69
+ * Called on each Resource about to be written, with its previous state (null on create, clone and upsert), the
70
+ * extension's Parameters and, for `clone`, the source Resource as stored.
71
+ */
72
+ beforeWrite?(input: BeforeWriteInput, ctx: HookCtx): Resource | Promise<Resource>;
73
+ /**
74
+ * Called with the current state of each Resource a write by ID or by query targets, before anything changes (D116):
75
+ * `patchById`, `replaceById` and `deleteById` call it right after reading the Resource (`current` null when it does
76
+ * not exist, before NOT_FOUND, UPSERT_DENIED and the upsert), and the ByQuery writes with each matched Resource after
77
+ * PARAM_EXPECT_MATCH. Throwing a CrudError fails the operation without writing (Metadata META_DOC_CONDITIONAL).
78
+ */
79
+ precondition?(input: PreconditionInput, ctx: HookCtx): void | Promise<void>;
41
80
  /** Called on the Resources read by `get` and `list`, after the provider's projection push-down and before the core's own projection (D74). */
42
81
  afterRead?(input: {
43
82
  readonly collection: string;
44
83
  readonly resources: Resource[];
45
84
  }, ctx: HookCtx): Resource[] | Promise<Resource[]>;
46
85
  }
86
+ /** What `beforeWrite` receives (D116). */
87
+ export interface BeforeWriteInput {
88
+ readonly operation: OperationName;
89
+ readonly collection: string;
90
+ readonly previous: Resource | null;
91
+ readonly next: Resource;
92
+ /** The extension's own Parameters the request sent. */
93
+ readonly params: ExtensionParams;
94
+ /** `clone`: the source Resource as stored, with its canonical Resource ID. */
95
+ readonly source?: {
96
+ readonly collection: string;
97
+ readonly id: ResourceId;
98
+ readonly resource: Resource;
99
+ };
100
+ /** `patchById`, `patchByQuery` and `clone` with a patch: the Client's patch, so hooks know what it touched (D128). */
101
+ readonly patch?: {
102
+ readonly type: "json-patch";
103
+ readonly ops: unknown;
104
+ } | {
105
+ readonly type: "merge-patch";
106
+ readonly doc: unknown;
107
+ };
108
+ }
109
+ /** What `precondition` receives (D116). */
110
+ export interface PreconditionInput {
111
+ readonly operation: OperationName;
112
+ readonly collection: string;
113
+ /** The current state, null when the Resource does not exist. */
114
+ readonly current: Resource | null;
115
+ /** The extension's own Parameters the request sent. */
116
+ readonly params: ExtensionParams;
117
+ }
47
118
  /**
48
119
  * Reserved Fields defined by the specifications of the family, with the extension that defines each one
49
120
  * (FIELDS_RESERVED, FIELDS_RESERVED_UNSUPPORTED). Only Metadata defines one (`_meta`, Metadata META_FIELD).
@@ -59,13 +130,19 @@ export declare class ExtensionRegistry {
59
130
  get names(): string[];
60
131
  /** The extension that claims a reserved Collection name (design 6.3 step 4), if any. */
61
132
  claimant(collection: string): Extension | undefined;
62
- /** Runs every `beforeWrite` hook in the order of the extensions. */
63
- beforeWrite(input: {
64
- operation: OperationName;
65
- collection: string;
66
- previous: Resource | null;
67
- next: Resource;
133
+ /** The Parameters of the enabled extensions that `operation` recognizes (D116). */
134
+ parametersFor(operation: OperationName): ExtensionParameter[];
135
+ /**
136
+ * Runs every `beforeWrite` hook in the order of the extensions; `params` holds the Parameters of every extension, and
137
+ * each hook gets its own.
138
+ */
139
+ beforeWrite(input: Omit<BeforeWriteInput, "params"> & {
140
+ readonly params?: Readonly<Record<string, unknown>>;
68
141
  }, ctx: HookCtx): Promise<Resource>;
142
+ /** Runs every `precondition` hook in the order of the extensions (D116). */
143
+ precondition(input: Omit<PreconditionInput, "params"> & {
144
+ readonly params?: Readonly<Record<string, unknown>>;
145
+ }, ctx: HookCtx): Promise<void>;
69
146
  /** Runs every `afterRead` hook in the order of the extensions. */
70
147
  afterRead(collection: string, resources: Resource[], ctx: HookCtx): Promise<Resource[]>;
71
148
  }
@@ -1,6 +1,14 @@
1
- // Extensions plugged into the engine (design section 7): the interface and the registry built at server construction.
2
1
  import { isSlug } from "./ids.js";
3
2
  import { CodeRegistry } from "./warnings.js";
3
+ /** The Parameters of `extension` found in `params`, by name. */
4
+ function paramsOf(extension, params) {
5
+ const own = {};
6
+ for (const parameter of extension.parameters ?? []) {
7
+ if (Object.hasOwn(params, parameter.name) && params[parameter.name] !== undefined)
8
+ own[parameter.name] = params[parameter.name];
9
+ }
10
+ return own;
11
+ }
4
12
  /**
5
13
  * Reserved Fields defined by the specifications of the family, with the extension that defines each one
6
14
  * (FIELDS_RESERVED, FIELDS_RESERVED_UNSUPPORTED). Only Metadata defines one (`_meta`, Metadata META_FIELD).
@@ -28,7 +36,14 @@ export class ExtensionRegistry {
28
36
  throw new Error(`extension ${extension.name} is enabled twice`);
29
37
  names.add(extension.name);
30
38
  }
39
+ const parameters = new Map();
31
40
  for (const extension of extensions) {
41
+ for (const parameter of extension.parameters ?? []) {
42
+ const owner = parameters.get(parameter.name);
43
+ if (owner !== undefined)
44
+ throw new Error(`extensions ${owner} and ${extension.name} both define the Parameter ${parameter.name}`);
45
+ parameters.set(parameter.name, extension.name);
46
+ }
32
47
  for (const required of extension.requires ?? []) {
33
48
  if (!names.has(required))
34
49
  throw new Error(`extension ${extension.name} requires extension ${required}, which is not enabled`);
@@ -48,15 +63,31 @@ export class ExtensionRegistry {
48
63
  claimant(collection) {
49
64
  return this.list.find((e) => (e.reservedCollections ?? []).some((pattern) => matchesReserved(pattern, collection)));
50
65
  }
51
- /** Runs every `beforeWrite` hook in the order of the extensions. */
66
+ /** The Parameters of the enabled extensions that `operation` recognizes (D116). */
67
+ parametersFor(operation) {
68
+ return this.list.flatMap((e) => (e.parameters ?? []).filter((p) => p.operations.includes(operation)));
69
+ }
70
+ /**
71
+ * Runs every `beforeWrite` hook in the order of the extensions; `params` holds the Parameters of every extension, and
72
+ * each hook gets its own.
73
+ */
52
74
  async beforeWrite(input, ctx) {
75
+ const { params = {}, ...rest } = input;
53
76
  let next = input.next;
54
77
  for (const extension of this.list) {
55
78
  if (extension.beforeWrite !== undefined)
56
- next = await extension.beforeWrite({ ...input, next }, ctx);
79
+ next = await extension.beforeWrite({ ...rest, next, params: paramsOf(extension, params) }, ctx);
57
80
  }
58
81
  return next;
59
82
  }
83
+ /** Runs every `precondition` hook in the order of the extensions (D116). */
84
+ async precondition(input, ctx) {
85
+ const { params = {}, ...rest } = input;
86
+ for (const extension of this.list) {
87
+ if (extension.precondition !== undefined)
88
+ await extension.precondition({ ...rest, params: paramsOf(extension, params) }, ctx);
89
+ }
90
+ }
60
91
  /** Runs every `afterRead` hook in the order of the extensions. */
61
92
  async afterRead(collection, resources, ctx) {
62
93
  let current = resources;
package/dist/index.d.ts CHANGED
@@ -20,12 +20,14 @@ export { applyProjection, keyPaths, normalizeProjection, samePath } from "./proj
20
20
  export { compareResources, compareSortValues, crossesArray, getPath, sortArrayPathWarning, sortArrayPathWarnings, sortKeys } from "./sorting.ts";
21
21
  export type { SortOptions } from "./sorting.ts";
22
22
  export { assertWritableDepth, DEPTH_LIMIT, exceedsDepth, RESOURCE_MAX_DEPTH } from "./depth.ts";
23
+ export { downgrade, tagOf } from "./downgrade.ts";
24
+ export type { Downgraded } from "./downgrade.ts";
23
25
  export { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, decodePatch, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.ts";
24
26
  export { createCrudServer, BASE_SPEC } from "./server.ts";
25
27
  export type { CrudServer, CrudServerOptions, ProtocolRegistration, ServerDescription } from "./server.ts";
26
28
  export type { OperationRequest, OperationResult, ResultMeta } from "./operation.ts";
27
29
  export { ExtensionRegistry, KNOWN_RESERVED_FIELDS } from "./extensions.ts";
28
- export type { Extension, HookCtx } from "./extensions.ts";
30
+ export type { BeforeWriteInput, Extension, ExtensionParameter, ExtensionParams, HookCtx, PreconditionInput } from "./extensions.ts";
29
31
  export { atomicity, decideWriteMode } from "./write-policy.ts";
30
32
  export type { Atomicity, WriteMode, WritePolicyInput } from "./write-policy.ts";
31
33
  export { assertClientId, assertNoStrayId, assertResource, assertSubjectId, canonicalId, checkFieldNames, dropReservedChanges, dropReservedFields, keyIsTopLevel } from "./subject.ts";
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ export { formatFieldList, formatFieldPath, parseFieldList } from "./field-list.j
10
10
  export { applyProjection, keyPaths, normalizeProjection, samePath } from "./projection.js";
11
11
  export { compareResources, compareSortValues, crossesArray, getPath, sortArrayPathWarning, sortArrayPathWarnings, sortKeys } from "./sorting.js";
12
12
  export { assertWritableDepth, DEPTH_LIMIT, exceedsDepth, RESOURCE_MAX_DEPTH } from "./depth.js";
13
+ export { downgrade, tagOf } from "./downgrade.js";
13
14
  export { applyJsonPatch, applyMergePatch, assertKeyUnchanged, cloneValue, decodePatch, isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.js";
14
15
  export { createCrudServer, BASE_SPEC } from "./server.js";
15
16
  export { ExtensionRegistry, KNOWN_RESERVED_FIELDS } from "./extensions.js";
@@ -46,6 +46,8 @@ export interface OperationRequest {
46
46
  expectMatch?: number;
47
47
  denyUpsert?: boolean;
48
48
  custom?: Record<string, unknown>;
49
+ /** Parameters of enabled extensions (design 7, D116), such as `ifMatch` of Metadata; unknown names are PARAM_IGNORED. */
50
+ [parameter: string]: unknown;
49
51
  };
50
52
  meta?: {
51
53
  accept?: Accepted[];
@@ -84,6 +86,12 @@ export interface ResultMeta {
84
86
  * Subject order, also when no Resource is returned (HTTP_LOCATION, HTTP_CLONE with `return=minimal`; D86).
85
87
  */
86
88
  ids?: ResourceId[];
89
+ /**
90
+ * The reserved Fields handled by enabled extensions (such as `_meta`) of the one Resource of `get`, `clone`,
91
+ * `patchById`, `replaceById` and a `create` whose Subject is one object, as stored, before the Projection and
92
+ * `return=minimal`, so that Protocols can mirror them (Metadata META_PROTOCOL_MIRROR, D116). Absent otherwise.
93
+ */
94
+ reserved?: Record<string, unknown>;
87
95
  }
88
96
  /** The Output: the Resources (get: one Resource; list and writes: a list; null when none is returned) or an error. */
89
97
  export type OperationResult = {
package/dist/operation.js CHANGED
@@ -13,7 +13,7 @@ import { sortKeys } from "./sorting.js";
13
13
  import { assertClientId, assertNoStrayId, assertResource, assertSubjectId, canonicalId, checkFieldNames, dropReservedFields } from "./subject.js";
14
14
  import { ID_KEY, OPERATIONS } from "./types.js";
15
15
  import { LENIENT, WarningSink } from "./warnings.js";
16
- import { assertStrict, toCrudError, warnOf } from "./operations/context.js";
16
+ import { assertStrict, keepReserved, toCrudError, warnOf } from "./operations/context.js";
17
17
  import { get, list } from "./operations/read.js";
18
18
  import { clone, create } from "./operations/create.js";
19
19
  import { deleteById, patchById, replaceById } from "./operations/by-id.js";
@@ -21,6 +21,8 @@ import { deleteByQuery, patchByQuery, replaceByQuery } from "./operations/by-que
21
21
  const WRITES = new Set(["create", "clone", "patchById", "patchByQuery", "replaceById", "replaceByQuery", "deleteById", "deleteByQuery"]);
22
22
  const BY_QUERY = new Set(["patchByQuery", "replaceByQuery", "deleteByQuery"]);
23
23
  const DELETES = new Set(["deleteById", "deleteByQuery"]);
24
+ /** Writes on one Resource whose stored reserved Fields go to `meta.reserved` (D116); `create` of one object too. */
25
+ const SINGLE_WRITES = new Set(["clone", "patchById", "replaceById"]);
24
26
  /** Writes whose written Resource IDs go to `meta.ids` (D86). */
25
27
  const WRITES_BY_ID = new Set(["create", "clone", "patchById", "replaceById", "deleteById"]);
26
28
  /** The Search Query is an UnQuery model built by the adapter (D87). */
@@ -48,7 +50,9 @@ const ignored = (parameter) => ({ code: "PARAM_IGNORED", message: `the Parameter
48
50
  /** Step 6: Parameters (PARAM_CUSTOM_UNKNOWN, field lists, sorting, pagination). */
49
51
  function parseParams(server, ctx, params) {
50
52
  const input = params ?? {};
51
- const recognized = RECOGNIZED[ctx.operation];
53
+ // D116: the Parameters of enabled extensions are recognized by the operations they list.
54
+ const own = server.extensions.parametersFor(ctx.operation);
55
+ const recognized = [...RECOGNIZED[ctx.operation], ...own.map((p) => p.name)];
52
56
  for (const [name, value] of Object.entries(input)) {
53
57
  if (value === undefined)
54
58
  continue;
@@ -96,7 +100,15 @@ function parseParams(server, ctx, params) {
96
100
  throw new CrudError("INVALID_INPUT", "`denyUpsert` must be a boolean", { rule: "PARAM_DENY_UPSERT" });
97
101
  denyUpsert = input.denyUpsert;
98
102
  }
99
- return { projection, sort, page, expectMatch, denyUpsert };
103
+ const extension = {};
104
+ for (const parameter of own) {
105
+ const value = input[parameter.name];
106
+ if (value === undefined)
107
+ continue;
108
+ parameter.check?.(value);
109
+ extension[parameter.name] = value;
110
+ }
111
+ return { projection, sort, page, expectMatch, denyUpsert, extension };
100
112
  }
101
113
  /** SUB_JSON_PATCH, SUB_MERGE_PATCH: the patch is well formed, checked before anything is read. */
102
114
  function checkPatch(patch, required) {
@@ -380,6 +392,9 @@ export async function executeOperation(server, defaults, request) {
380
392
  default:
381
393
  resources = operation === "list" ? await list(ctx) : await deleteByQuery(ctx);
382
394
  }
395
+ // META_PROTOCOL_MIRROR (D116): the stored Resource of a single-Resource write, before Projection and `return=minimal`.
396
+ if (SINGLE_WRITES.has(operation) || (operation === "create" && !Array.isArray(request.resources)))
397
+ keepReserved(ctx, resources[0]);
383
398
  Object.assign(meta, counters);
384
399
  meta.warnings = [...sink.list];
385
400
  if (WRITES_BY_ID.has(operation))
@@ -399,6 +414,7 @@ export async function executeOperation(server, defaults, request) {
399
414
  catch (error) {
400
415
  const failure = toCrudError(server, error);
401
416
  Object.assign(meta, counters);
417
+ delete meta.reserved; // D116: mirrors describe a Resource the operation returned
402
418
  if (isWrite)
403
419
  meta.modifiedCount = counters.modifiedCount ?? 0; // META_MODIFIED_COUNT, WRITE_MODIFIED_COUNT
404
420
  delete meta.upserted; // META_UPSERTED describes a Resource that was written
@@ -4,7 +4,7 @@ import { idOf } from "../ids.js";
4
4
  import { assertKeyUnchanged } from "../patch.js";
5
5
  import { assertClientId, assertNoStrayId, checkFieldNames, dropReservedChanges } from "../subject.js";
6
6
  import { atomicity, decideWriteMode } from "../write-policy.js";
7
- import { applyPatch, checkStrict, executeWrites, inWriteScope, notFound, readOne, unit, warnOf, withCodec, } from "./context.js";
7
+ import { applyPatch, checkStrict, executeWrites, inWriteScope, notFound, readOne, unit, hookCtx, precondition, warnOf, withCodec, } from "./context.js";
8
8
  /** Runs one single-Resource write: policy, then (in a transaction when available) read, change, prepare, write. */
9
9
  async function single(ctx, body) {
10
10
  ctx.counters.modifiedCount = 0;
@@ -36,6 +36,7 @@ export async function patchById(ctx, id, patch) {
36
36
  const key = ctx.info.key;
37
37
  return single(ctx, async (mode) => {
38
38
  const current = await readOne(ctx, id);
39
+ await precondition(ctx, current); // D116: before NOT_FOUND (Metadata META_DOC_CONDITIONAL)
39
40
  if (current === null)
40
41
  throw notFound(id);
41
42
  let next = applyPatch(current, patch);
@@ -43,7 +44,7 @@ export async function patchById(ctx, id, patch) {
43
44
  checkFieldNames(next, "INVALID_PATCH");
44
45
  assertNoStrayId(next, key, "INVALID_PATCH"); // FIELDS_RESERVED: a patch cannot give `_id` a meaning either
45
46
  next = dropReservedChanges(current, next, ctx.server.extensions.handledFields, warnOf(ctx)); // FIELDS_RESERVED_UNSUPPORTED
46
- next = await ctx.server.extensions.beforeWrite({ operation: "patchById", collection: ctx.info.slug, previous: current, next }, { warn: warnOf(ctx) });
47
+ next = await ctx.server.extensions.beforeWrite({ params: ctx.params.extension, patch, operation: "patchById", collection: ctx.info.slug, previous: current, next }, hookCtx(ctx));
47
48
  const target = idOf(current, key, withCodec(ctx)) ?? id;
48
49
  const outcomes = await write(ctx, [unit(ctx, { kind: "replace", collection: ctx.info.slug, key, id: target, resource: next }, [target])], mode);
49
50
  return stored(outcomes[0]?.result); // RES_RESOURCES_WRITTEN
@@ -59,9 +60,10 @@ export async function replaceById(ctx, id, replacement) {
59
60
  ctx.counters.upserted = false; // META_UPSERTED: always present for replaceById (D57)
60
61
  return single(ctx, async (mode) => {
61
62
  const current = await readOne(ctx, id);
63
+ await precondition(ctx, current); // D116: before UPSERT_DENIED and the upsert
62
64
  let units;
63
65
  if (current !== null) {
64
- const next = await ctx.server.extensions.beforeWrite({ operation: "replaceById", collection: ctx.info.slug, previous: current, next: replacement }, { warn: warnOf(ctx) });
66
+ const next = await ctx.server.extensions.beforeWrite({ params: ctx.params.extension, operation: "replaceById", collection: ctx.info.slug, previous: current, next: replacement }, hookCtx(ctx));
65
67
  const target = idOf(current, key, withCodec(ctx)) ?? id;
66
68
  units = [unit(ctx, { kind: "replace", collection: ctx.info.slug, key, id: target, resource: next }, [target])];
67
69
  }
@@ -70,7 +72,7 @@ export async function replaceById(ctx, id, replacement) {
70
72
  throw new CrudError("UPSERT_DENIED", `Resource ${id} does not exist and the Client denied its creation`, { rule: "RES_UPSERT_PREVENTED" });
71
73
  }
72
74
  assertClientId(key.kind === "id" ? replacement._id : id, ctx.info, ctx.caps);
73
- const next = await ctx.server.extensions.beforeWrite({ operation: "replaceById", collection: ctx.info.slug, previous: null, next: replacement }, { warn: warnOf(ctx) });
75
+ const next = await ctx.server.extensions.beforeWrite({ params: ctx.params.extension, operation: "replaceById", collection: ctx.info.slug, previous: null, next: replacement }, hookCtx(ctx));
74
76
  units = [unit(ctx, { kind: "insert", collection: ctx.info.slug, key, resources: [next] }, [id])];
75
77
  }
76
78
  const outcomes = await write(ctx, units, mode);
@@ -84,6 +86,7 @@ export async function deleteById(ctx, id) {
84
86
  const key = ctx.info.key;
85
87
  return single(ctx, async (mode) => {
86
88
  const current = await readOne(ctx, id);
89
+ await precondition(ctx, current); // D116
87
90
  if (current === null)
88
91
  throw notFound(id);
89
92
  const target = idOf(current, key, withCodec(ctx)) ?? id;
@@ -6,7 +6,7 @@ import { idOf, setKey } from "../ids.js";
6
6
  import { assertKeyUnchanged, cloneValue } from "../patch.js";
7
7
  import { assertNoStrayId, checkFieldNames, dropReservedChanges } from "../subject.js";
8
8
  import { atomicity, decideWriteMode } from "../write-policy.js";
9
- import { applyPatch, checkStrict, executeWrites, findAll, inWriteScope, unit, warnOf, withCodec, } from "./context.js";
9
+ import { applyPatch, checkStrict, executeWrites, findAll, inWriteScope, unit, hookCtx, precondition, warnOf, withCodec, } from "./context.js";
10
10
  async function byQuery(ctx, change) {
11
11
  ctx.counters.modifiedCount = 0;
12
12
  const key = ctx.info.key;
@@ -24,6 +24,8 @@ async function byQuery(ctx, change) {
24
24
  data: { matchedCount: matched.length, expectMatch: expected },
25
25
  });
26
26
  }
27
+ for (const current of matched)
28
+ await precondition(ctx, current); // D116: e.g. Metadata META_DOC_CONDITIONAL
27
29
  const mode = decideWriteMode({ strict: ctx.strict, several: matched.length > 1, atomicity: atom, lateWarnings: ctx.caps.lateWarnings === true });
28
30
  if (matched.length === 0) {
29
31
  checkStrict(ctx);
@@ -53,7 +55,7 @@ async function byQuery(ctx, change) {
53
55
  else {
54
56
  resource = setKey(cloneValue(change.replacement), key, ids[i], withCodec(ctx)); // REPLACE_QUERY_EACH: keeps each ID
55
57
  }
56
- resource = await ctx.server.extensions.beforeWrite({ operation, collection: ctx.info.slug, previous: current, next: resource }, { warn: warnOf(ctx) });
58
+ resource = await ctx.server.extensions.beforeWrite({ params: ctx.params.extension, ...(change.kind === "patch" ? { patch: change.patch } : {}), operation, collection: ctx.info.slug, previous: current, next: resource }, hookCtx(ctx));
57
59
  next.push(resource);
58
60
  }
59
61
  units = next.map((resource, i) => unit(ctx, { kind: "replace", collection: ctx.info.slug, key, id: ids[i], resource }, [ids[i]]));
@@ -1,7 +1,7 @@
1
1
  import type { Codec } from "@ecson/core";
2
2
  import type { Filter, Limits } from "@unquery/core";
3
3
  import { CrudError } from "../errors.ts";
4
- import type { ExtensionRegistry } from "../extensions.ts";
4
+ import type { ExtensionRegistry, HookCtx } from "../extensions.ts";
5
5
  import type { OperationRequest } from "../operation.ts";
6
6
  import type { CollectionInfo, Ctx, ExecCtx, Prepared, PrepareCtx, PrimitiveRequest, PrimitiveResult, Provider, ProviderCapabilities } from "../provider.ts";
7
7
  import type { OperationName, Page, Projection, Representation, Resource, ResourceId, SortKey } from "../types.ts";
@@ -28,6 +28,8 @@ export interface ServerState {
28
28
  readonly onError: ((error: unknown) => void) | undefined;
29
29
  /** The ECSON codec of the Server (design 6.4, D75): sorting, composite keys, Search Queries, provider contexts. */
30
30
  readonly codec: Codec;
31
+ /** The injected clock, Unix time in milliseconds (extension hooks, D116). */
32
+ readonly clock: () => number;
31
33
  }
32
34
  /** The primitives the engine calls: the provider itself, or the `ProviderTx` of a transaction. */
33
35
  export interface Io {
@@ -45,6 +47,8 @@ export interface ParsedParams {
45
47
  readonly page: Page | null;
46
48
  readonly expectMatch: number | undefined;
47
49
  readonly denyUpsert: boolean;
50
+ /** Parameters of enabled extensions the operation recognizes, by name (D116). */
51
+ readonly extension: Readonly<Record<string, unknown>>;
48
52
  }
49
53
  /** The Search Query after step 8: an UnQuery model, or the text of a native format the provider declared. */
50
54
  export interface ParsedQuery {
@@ -62,6 +66,8 @@ export interface Counters {
62
66
  nextCursor?: string | null;
63
67
  hasNext?: boolean;
64
68
  limit?: number | null;
69
+ /** The reserved Fields handled by extensions of the one Resource of a single-Resource operation (D116). */
70
+ reserved?: Record<string, unknown>;
65
71
  }
66
72
  export interface OpContext {
67
73
  readonly server: ServerState;
@@ -81,6 +87,12 @@ export interface OpContext {
81
87
  io: Io;
82
88
  }
83
89
  export declare const warnOf: (ctx: OpContext) => (warning: Warning) => void;
90
+ /** The context of extension hooks (D116). */
91
+ export declare const hookCtx: (ctx: OpContext) => HookCtx;
92
+ /** Runs the `precondition` hooks on the current state of a Resource the write targets (D116). */
93
+ export declare function precondition(ctx: OpContext, current: Resource | null): Promise<void>;
94
+ /** META_PROTOCOL_MIRROR: keeps the handled reserved Fields of the Resource a single-Resource operation read or wrote (D116). */
95
+ export declare function keepReserved(ctx: OpContext, resource: Resource | undefined): void;
84
96
  /** The codec option of the ID and sorting functions (D75). */
85
97
  export declare const withCodec: (ctx: OpContext) => {
86
98
  readonly codec: Codec;
@@ -1,4 +1,5 @@
1
1
  import { assertWritableDepth } from "../depth.js";
2
+ import { downgrade } from "../downgrade.js";
2
3
  import { CrudError } from "../errors.js";
3
4
  import { idOf } from "../ids.js";
4
5
  import { applyJsonPatch, applyMergePatch } from "../patch.js";
@@ -6,6 +7,38 @@ import { sortKeys } from "../sorting.js";
6
7
  import { canonicalId } from "../subject.js";
7
8
  import { strictPolicy } from "../warnings.js";
8
9
  export const warnOf = (ctx) => (warning) => ctx.sink.warn(warning);
10
+ /** The context of extension hooks (D116). */
11
+ export const hookCtx = (ctx) => ({
12
+ warn: warnOf(ctx),
13
+ warnOnce: (warning) => {
14
+ const { message: _, ...members } = warning;
15
+ const same = (w) => {
16
+ const { message: __, ...other } = w;
17
+ return JSON.stringify(Object.entries(other).sort()) === JSON.stringify(Object.entries(members).sort());
18
+ };
19
+ if (!ctx.sink.list.some(same))
20
+ ctx.sink.warn(warning);
21
+ },
22
+ clock: ctx.server.clock,
23
+ principal: ctx.request.meta?.principal,
24
+ codec: ctx.server.codec,
25
+ stored: (resource) => downgrade(resource, ctx.caps.nativeTypes, ctx.server.codec).resource, // D128
26
+ });
27
+ /** Runs the `precondition` hooks on the current state of a Resource the write targets (D116). */
28
+ export async function precondition(ctx, current) {
29
+ await ctx.server.extensions.precondition({ operation: ctx.operation, collection: ctx.info.slug, current, params: ctx.params.extension }, hookCtx(ctx));
30
+ }
31
+ /** META_PROTOCOL_MIRROR: keeps the handled reserved Fields of the Resource a single-Resource operation read or wrote (D116). */
32
+ export function keepReserved(ctx, resource) {
33
+ if (resource === undefined)
34
+ return;
35
+ const reserved = {};
36
+ for (const field of ctx.server.extensions.handledFields)
37
+ if (Object.hasOwn(resource, field))
38
+ reserved[field] = resource[field];
39
+ if (Object.keys(reserved).length > 0)
40
+ ctx.counters.reserved = reserved;
41
+ }
9
42
  /** The codec option of the ID and sorting functions (D75). */
10
43
  export const withCodec = (ctx) => ({ codec: ctx.server.codec });
11
44
  /** The context of a provider primitive: the operation's Warning sink and the Server's codec. */
@@ -5,7 +5,7 @@ import { idOf, setKey, stripKey } from "../ids.js";
5
5
  import { cloneValue } from "../patch.js";
6
6
  import { assertClientId, assertNoStrayId, canonicalId, checkFieldNames, dropReservedChanges } from "../subject.js";
7
7
  import { atomicity, decideWriteMode } from "../write-policy.js";
8
- import { applyPatch, checkStrict, ensureCollection, executeWrites, inWriteScope, notFound, readByIds, readOne, undoImplicitCollection, unit, warnOf, withCodec, } from "./context.js";
8
+ import { applyPatch, checkStrict, ensureCollection, executeWrites, inWriteScope, notFound, readByIds, readOne, undoImplicitCollection, unit, hookCtx, warnOf, withCodec, } from "./context.js";
9
9
  function conflict(id) {
10
10
  return new CrudError("CONFLICT", `a Resource with the ID ${id} already exists`, { rule: "RES_CONFLICT" });
11
11
  }
@@ -67,7 +67,7 @@ export async function create(ctx, subject) {
67
67
  if (id !== undefined)
68
68
  clientIds.push(id);
69
69
  }
70
- resource = await ctx.server.extensions.beforeWrite({ operation: "create", collection: ctx.info.slug, previous: null, next: resource }, { warn: warnOf(ctx) });
70
+ resource = await ctx.server.extensions.beforeWrite({ params: ctx.params.extension, operation: "create", collection: ctx.info.slug, previous: null, next: resource }, hookCtx(ctx));
71
71
  resources.push(resource);
72
72
  }
73
73
  const ids = resources.map((r) => idOf(r, key, withCodec(ctx)));
@@ -155,7 +155,8 @@ export async function clone(ctx, sourceId, patch, newId) {
155
155
  // RES_CLONE: a new Resource ID, generated as in `create`.
156
156
  next = ctx.caps.ids.generator === "core" ? setKey(next, key, ctx.server.newId(), withCodec(ctx)) : stripKey(next, key);
157
157
  } // D55: a composite key cannot be generated; the copy keeps the source's key and fails with CONFLICT below.
158
- next = await ctx.server.extensions.beforeWrite({ operation: "clone", collection: ctx.info.slug, previous: null, next }, { warn: warnOf(ctx) });
158
+ const sourceInfo = { collection: ctx.info.slug, id: sourceCanonical, resource: source };
159
+ next = await ctx.server.extensions.beforeWrite({ params: ctx.params.extension, ...(patch === undefined ? {} : { patch }), operation: "clone", collection: ctx.info.slug, previous: null, next, source: sourceInfo }, hookCtx(ctx));
159
160
  const id = idOf(next, key, withCodec(ctx));
160
161
  if (id !== undefined && (await readOne(ctx, id)) !== null)
161
162
  throw conflict(id); // RES_CONFLICT
@@ -1,17 +1,32 @@
1
1
  // Read operations: `get` and `list` (Base 4.1, 4.2; design 6.7).
2
2
  import { applyProjection } from "../projection.js";
3
- import { checkStrict, execCtx, notFound, prepare, read, warnOf } from "./context.js";
3
+ import { checkStrict, execCtx, hookCtx, keepReserved, notFound, prepare, read } from "./context.js";
4
4
  function asFind(result) {
5
5
  if (result.kind !== "find" && result.kind !== "findByIds")
6
6
  throw new Error(`the provider answered a read with a ${result.kind} result`);
7
7
  return result;
8
8
  }
9
- /** Design 6.5: the projection is pushed down when the provider declares it, and always applied again here. */
9
+ /**
10
+ * Design 6.5: the projection is pushed down when the provider declares it, and always applied again here. The reserved
11
+ * Fields handled by enabled extensions are always read, so that hooks and Protocol mirrors see them (D116): an include
12
+ * list gets them, an exclude list loses them.
13
+ */
10
14
  function pushdown(ctx) {
11
- return ctx.caps.projection ? ctx.params.projection : null;
15
+ const projection = ctx.caps.projection ? ctx.params.projection : null;
16
+ const handled = [...ctx.server.extensions.handledFields];
17
+ if (projection === null || handled.length === 0)
18
+ return projection;
19
+ const isHandled = (path) => path.length > 0 && handled.includes(path[0]);
20
+ if (projection.include !== null) {
21
+ const include = [...projection.include.filter((path) => !isHandled(path)), ...handled.map((field) => [field])];
22
+ return { include, exclude: projection.exclude.filter((path) => !isHandled(path)) };
23
+ }
24
+ return { include: null, exclude: projection.exclude.filter((path) => !isHandled(path)) };
12
25
  }
13
26
  async function finish(ctx, resources) {
14
- const read = await ctx.server.extensions.afterRead(ctx.info.slug, resources, { warn: warnOf(ctx) });
27
+ const read = await ctx.server.extensions.afterRead(ctx.info.slug, resources, hookCtx(ctx));
28
+ if (ctx.operation === "get")
29
+ keepReserved(ctx, read[0]); // META_PROTOCOL_MIRROR (D116)
15
30
  const projection = ctx.params.projection;
16
31
  return projection === null ? read : read.map((resource) => applyProjection(resource, projection));
17
32
  }
package/dist/server.js CHANGED
@@ -61,6 +61,7 @@ export function createCrudServer(options) {
61
61
  authorize: options.authorize,
62
62
  onError: options.onError,
63
63
  codec,
64
+ clock,
64
65
  };
65
66
  const description = Object.freeze({
66
67
  specs: Object.freeze(Object.fromEntries(Object.entries(specs).map(([name, versions]) => [name, Object.freeze([...versions])]))),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crud-api/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "CRUD API reference implementation: data model, engine, provider contract, field lists, projection, sorting, pagination, patch engines, negotiation",
5
5
  "keywords": [
6
6
  "crud",