@crud-api/core 0.1.1 → 0.3.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.
@@ -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
@@ -3,7 +3,7 @@ import { and } from "@unquery/core";
3
3
  import { DEPTH_LIMIT, exceedsDepth, RESOURCE_MAX_DEPTH } from "./depth.js";
4
4
  import { CrudError } from "./errors.js";
5
5
  import { parseFieldList } from "./field-list.js";
6
- import { isSlug, idOf, setKey, stripKey } from "./ids.js";
6
+ import { assertValidId, isSlug, idOf, setKey, stripKey } from "./ids.js";
7
7
  import { negotiateQueryFormat, negotiateRepresentation, negotiateSpecs } from "./negotiation.js";
8
8
  import { normalizePagination } from "./pagination.js";
9
9
  import { isPlainObject, validateJsonPatch, validateMergePatch } from "./patch.js";
@@ -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;
@@ -69,7 +73,8 @@ function parseParams(server, ctx, params) {
69
73
  let sort = sortKeys(null, ctx.key);
70
74
  let page = null;
71
75
  if (ctx.operation === "list") {
72
- const items = has("sort") ? parseFieldList(input.sort, { target: "sort" }) : null;
76
+ // FIELD_LIST_NO_INDEX: the Sorting Parameter is the field list that may have indexes (SORTING_ARRAY_PATH).
77
+ const items = has("sort") ? parseFieldList(input.sort, { target: "sort", indexes: true }) : null;
73
78
  // SORTING_NULLS (design 6.5): a provider that cannot order null and missing lowest cannot sort at all.
74
79
  if (items !== null && items.length > 0 && (!ctx.caps.sort.fields || !ctx.caps.sort.nullsLowest)) {
75
80
  throw new CrudError("UNSUPPORTED", "this Collection cannot be sorted by Fields", { rule: "SORTING_NULLS" });
@@ -95,7 +100,15 @@ function parseParams(server, ctx, params) {
95
100
  throw new CrudError("INVALID_INPUT", "`denyUpsert` must be a boolean", { rule: "PARAM_DENY_UPSERT" });
96
101
  denyUpsert = input.denyUpsert;
97
102
  }
98
- 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 };
99
112
  }
100
113
  /** SUB_JSON_PATCH, SUB_MERGE_PATCH: the patch is well formed, checked before anything is read. */
101
114
  function checkPatch(patch, required) {
@@ -166,7 +179,7 @@ function checkSubject(ctx) {
166
179
  for (const resource of resources) {
167
180
  if (key.kind === "id") {
168
181
  if (keyPresent(resource, key))
169
- assertClientId(resource._id, info, ctx.caps); // SUB_WITH_IDS, RES_NO_IDS
182
+ assertClientId(resource._id, info, ctx.caps); // ID_INVALID, SUB_WITH_IDS, RES_NO_IDS
170
183
  }
171
184
  else if (idOf(resource, key, opts) === undefined) {
172
185
  throw new CrudError("INVALID_INPUT", "every Field of the composite key must have a value", { rule: "ID_COMP_KEY" });
@@ -190,9 +203,8 @@ function checkSubject(ctx) {
190
203
  case "replaceById": {
191
204
  let resource = checkResource(ctx, request.resource, "SUB_RESOURCE_REPLACE");
192
205
  // SUB_ID_REPLACE: the Resource ID inside the replacement or separately; both present and different fail.
193
- if (key.kind === "id" && keyPresent(resource, key) && typeof resource._id !== "string") {
194
- throw new CrudError("INVALID_INPUT", "`_id` must be a Resource ID", { rule: "ID_SLUG" });
195
- }
206
+ if (key.kind === "id" && keyPresent(resource, key))
207
+ assertValidId(resource._id, key); // ID_INVALID
196
208
  const inside = idOf(resource, key, opts);
197
209
  if (inside === undefined && keyPresent(resource, key)) {
198
210
  throw new CrudError("INVALID_INPUT", "the replacement has only part of the composite key", { rule: "SUB_ID_REPLACE" });
@@ -215,8 +227,11 @@ function checkSubject(ctx) {
215
227
  case "replaceByQuery": {
216
228
  let resource = checkResource(ctx, request.resource, "SUB_RESOURCE_REPLACE");
217
229
  if (keyPresent(resource, key)) {
230
+ // ID_INVALID: even an ignored Resource ID must be valid, as any Resource ID an operation receives (D113).
231
+ if (key.kind === "id")
232
+ assertValidId(resource._id, key);
218
233
  // SUB_NO_ID: the Resource ID of the replacement is ignored, with ID_IGNORED (reported once, D61).
219
- const id = idOf(resource, key, opts) ?? (key.kind === "id" ? String(resource._id) : "");
234
+ const id = idOf(resource, key, opts) ?? "";
220
235
  resource = stripKey(resource, key);
221
236
  ctx.sink.warn({ code: "ID_IGNORED", message: "the Resource ID of the replacement was ignored: each matched Resource keeps its own", id });
222
237
  }
@@ -377,6 +392,9 @@ export async function executeOperation(server, defaults, request) {
377
392
  default:
378
393
  resources = operation === "list" ? await list(ctx) : await deleteByQuery(ctx);
379
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]);
380
398
  Object.assign(meta, counters);
381
399
  meta.warnings = [...sink.list];
382
400
  if (WRITES_BY_ID.has(operation))
@@ -396,6 +414,7 @@ export async function executeOperation(server, defaults, request) {
396
414
  catch (error) {
397
415
  const failure = toCrudError(server, error);
398
416
  Object.assign(meta, counters);
417
+ delete meta.reserved; // D116: mirrors describe a Resource the operation returned
399
418
  if (isWrite)
400
419
  meta.modifiedCount = counters.modifiedCount ?? 0; // META_MODIFIED_COUNT, WRITE_MODIFIED_COUNT
401
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/patch.d.ts CHANGED
@@ -19,6 +19,19 @@ export declare function applyJsonPatch(doc: Resource, ops: unknown): Resource;
19
19
  * without applying it, so that the engine can fail with `INVALID_PATCH` before reading anything.
20
20
  */
21
21
  export declare function validateJsonPatch(ops: unknown): void;
22
+ /**
23
+ * A patch read as ECSON (MCP_ARGS_ECSON, HTTP_PATCH_ECSON): the whole Merge Patch document, and the `value` member of
24
+ * each JSON Patch operation that has one, go through `decode` (the Server's codec, with the adapter's own errors);
25
+ * other members stay as they are. The shape is left to SUB_JSON_PATCH and SUB_MERGE_PATCH, so a patch of the wrong
26
+ * shape is returned as it is and fails there (D115).
27
+ */
28
+ export declare function decodePatch<P extends {
29
+ type: "json-patch";
30
+ ops: unknown;
31
+ } | {
32
+ type: "merge-patch";
33
+ doc: unknown;
34
+ }>(patch: P, decode: (tree: unknown, what: string) => unknown): P;
22
35
  /** SUB_MERGE_PATCH: a Merge Patch for a Resource must be an object (S03); `INVALID_PATCH` otherwise. */
23
36
  export declare function validateMergePatch(patch: unknown): void;
24
37
  /**
@@ -30,8 +43,9 @@ export declare function validateMergePatch(patch: unknown): void;
30
43
  export declare function applyMergePatch(doc: Resource, patch: unknown): Resource;
31
44
  /**
32
45
  * PATCH_NO_ID, ID_COMP_KEY_FIELDS: a patch must not change the Resource ID: `_id`, or every Field
33
- * of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH`.
34
- * Not called by `clone` (SUB_CLONE: the patch may set the Resource ID).
46
+ * of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH`;
47
+ * setting `_id` to an invalid Resource ID fails `INVALID_INPUT` first (ID_INVALID covers a Resource ID
48
+ * in a patch, D113). Not called by `clone` (SUB_CLONE: the patch may set the Resource ID).
35
49
  */
36
50
  export declare function assertKeyUnchanged(before: Resource, after: Resource, key: KeySpec): void;
37
51
  export {};
package/dist/patch.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // bytes, UnknownTag, Temporal, ...) is a leaf value: a pointer cannot go inside it.
4
4
  import { formatPath, valuesEqual } from "@unquery/core";
5
5
  import { CrudError } from "./errors.js";
6
+ import { assertValidId } from "./ids.js";
6
7
  /** True for plain objects (prototype `Object.prototype` or `null`): the only objects a pointer can enter. */
7
8
  export function isPlainObject(value) {
8
9
  if (typeof value !== "object" || value === null || Array.isArray(value))
@@ -230,6 +231,29 @@ export function applyJsonPatch(doc, ops) {
230
231
  export function validateJsonPatch(ops) {
231
232
  validate(ops);
232
233
  }
234
+ // ---- Patches read as ECSON ----
235
+ /**
236
+ * A patch read as ECSON (MCP_ARGS_ECSON, HTTP_PATCH_ECSON): the whole Merge Patch document, and the `value` member of
237
+ * each JSON Patch operation that has one, go through `decode` (the Server's codec, with the adapter's own errors);
238
+ * other members stay as they are. The shape is left to SUB_JSON_PATCH and SUB_MERGE_PATCH, so a patch of the wrong
239
+ * shape is returned as it is and fails there (D115).
240
+ */
241
+ export function decodePatch(patch, decode) {
242
+ if (patch.type === "merge-patch")
243
+ return { ...patch, doc: decode(patch.doc, "the patch") };
244
+ if (!Array.isArray(patch.ops))
245
+ return patch;
246
+ const ops = patch.ops.map((op) => {
247
+ if (!isPlainObject(op) || !Object.hasOwn(op, "value"))
248
+ return op;
249
+ const copy = {};
250
+ for (const [key, value] of Object.entries(op))
251
+ define(copy, key, value);
252
+ copy.value = decode(op.value, "the value of a patch operation");
253
+ return copy;
254
+ });
255
+ return { ...patch, ops };
256
+ }
233
257
  // ---- JSON Merge Patch (RFC 7396) ----
234
258
  /** SUB_MERGE_PATCH: a Merge Patch for a Resource must be an object (S03); `INVALID_PATCH` otherwise. */
235
259
  export function validateMergePatch(patch) {
@@ -281,8 +305,9 @@ function valueAt(resource, path) {
281
305
  }
282
306
  /**
283
307
  * PATCH_NO_ID, ID_COMP_KEY_FIELDS: a patch must not change the Resource ID: `_id`, or every Field
284
- * of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH`.
285
- * Not called by `clone` (SUB_CLONE: the patch may set the Resource ID).
308
+ * of a composite key (paths may go inside `_id`). Removing or changing one fails `INVALID_PATCH`;
309
+ * setting `_id` to an invalid Resource ID fails `INVALID_INPUT` first (ID_INVALID covers a Resource ID
310
+ * in a patch, D113). Not called by `clone` (SUB_CLONE: the patch may set the Resource ID).
286
311
  */
287
312
  export function assertKeyUnchanged(before, after, key) {
288
313
  const paths = key.kind === "id" ? [["_id"]] : key.paths;
@@ -292,6 +317,8 @@ export function assertKeyUnchanged(before, after, key) {
292
317
  // Both missing counts as unchanged (nothing to protect); present on one side only is a change.
293
318
  if (a === MISSING && b === MISSING)
294
319
  continue;
320
+ if (key.kind === "id" && b !== MISSING && !valuesEqual(a, b))
321
+ assertValidId(b, key); // ID_INVALID
295
322
  if (a === MISSING || b === MISSING || !valuesEqual(a, b)) {
296
323
  throw new CrudError("INVALID_PATCH", `the patch changes the Resource ID (${formatPath(path)})`, { rule: "PATCH_NO_ID" });
297
324
  }
@@ -1,9 +1,9 @@
1
1
  import type { FieldListItem } from "./field-list.ts";
2
- import type { KeySpec, Path, Projection, Resource } from "./types.ts";
2
+ import type { KeySpec, Path, Projection, Resource, SortPath } from "./types.ts";
3
3
  /** The field paths that hold the Resource ID: `_id` (ID_KEY) or the composite key paths in key order (ID_COMP_KEY_FIELDS). */
4
4
  export declare function keyPaths(key: KeySpec): readonly Path[];
5
- /** Two field paths are the same when every segment is the same. */
6
- export declare function samePath(a: Path, b: Path): boolean;
5
+ /** Two field paths are the same when every segment (or index, in a `SortPath`) is the same. */
6
+ export declare function samePath(a: SortPath, b: SortPath): boolean;
7
7
  /**
8
8
  * Normalizes a Projection Parameter (PROJECTION_FIELD_LIST: the `-` modifier omits): `include` is the listed
9
9
  * paths, or null when none is listed (PROJECTION_EXCLUDE); `exclude` is the omitted paths, removed after the
@@ -5,7 +5,7 @@ const ID_PATH = Object.freeze(["_id"]);
5
5
  export function keyPaths(key) {
6
6
  return key.kind === "id" ? [ID_PATH] : key.paths;
7
7
  }
8
- /** Two field paths are the same when every segment is the same. */
8
+ /** Two field paths are the same when every segment (or index, in a `SortPath`) is the same. */
9
9
  export function samePath(a, b) {
10
10
  return a.length === b.length && a.every((segment, i) => segment === b[i]);
11
11
  }
@@ -81,6 +81,12 @@ export type PrimitiveRequest = {
81
81
  readonly format: string;
82
82
  readonly text: string;
83
83
  };
84
+ /**
85
+ * The sort keys, whose paths may have indexes. SORTING_ARRAY_PATH (D112): `getPath` and `compareResources`
86
+ * read them as the rule says; the provider reports `SORT_ARRAY_PATH` in `execute` for each key path that crosses
87
+ * an array in a matched Resource (`sortArrayPathWarnings` over every matched Resource, not only the page), or
88
+ * fails in `prepare` (UNSUPPORTED) when it cannot sort so.
89
+ */
84
90
  readonly sort: readonly SortKey[];
85
91
  readonly projection: Projection | null;
86
92
  readonly page: Page;
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/dist/sorting.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type Codec } from "@ecson/core";
2
- import type { FieldListItem } from "./field-list.ts";
3
- import type { KeySpec, Path, Resource, SortKey } from "./types.ts";
2
+ import { type FieldListItem } from "./field-list.ts";
3
+ import type { KeySpec, Resource, SortKey, SortPath } from "./types.ts";
4
+ import type { Warning } from "./warnings.ts";
4
5
  /**
5
6
  * Options of the comparators. `codec` is the ECSON codec of the Server, built with `createCodec` from the type sets of
6
7
  * the enabled extensions (design 6.4), so extension host values (`Rel` of the References type set, `ObjectId` of
@@ -14,9 +15,9 @@ export interface SortOptions {
14
15
  * Sort keys of a `list` operation (SORTING_FIELD_LIST: the `-` modifier means descending). SORTING_DEFAULT: the
15
16
  * Resource ID is added as the last key, ascending: `_id`, or each composite key path in key order
16
17
  * (ID_COMP_KEY_FIELDS), unless the path is already a key. Without a Sorting Parameter (null or empty), the
17
- * keys are the Resource ID alone.
18
+ * keys are the Resource ID alone. Paths may have indexes (SORTING_ARRAY_PATH: `parseFieldList` with `{ indexes: true }`).
18
19
  */
19
- export declare function sortKeys(items: readonly FieldListItem[] | null, key: KeySpec): SortKey[];
20
+ export declare function sortKeys(items: readonly FieldListItem<SortPath>[] | null, key: KeySpec): SortKey[];
20
21
  /**
21
22
  * The total order of sorted values (SORTING_NULLS, SORTING_TYPES, SORTING_SAME_TYPE): -1, 0 or 1. `null`, missing
22
23
  * (`MISSING`) and `undefined` are the lowest and equal among themselves; then numbers, strings, objects, arrays,
@@ -25,14 +26,24 @@ export declare function sortKeys(items: readonly FieldListItem[] | null, key: Ke
25
26
  */
26
27
  export declare function compareSortValues(a: unknown, b: unknown, options?: SortOptions): number;
27
28
  /**
28
- * The value at a field path of a Resource, or `MISSING`. Decision: the path is followed through plain objects
29
- * only; an array (or any other value) in the middle of the path gives `MISSING` (Base does not define sorting by
30
- * a path through arrays).
29
+ * The value at a field path of a Resource, or `MISSING`, as sorting reads it (SORTING_ARRAY_PATH, D112): names follow
30
+ * own properties of plain objects, indexes select array elements (`MISSING` on a non-array or out of range), and a
31
+ * path that crosses an array without an index gives `MISSING`, never an element of the array.
31
32
  */
32
- export declare function getPath(resource: Resource, path: Path): unknown;
33
+ export declare function getPath(resource: Resource, path: SortPath): unknown;
34
+ /** True when the path crosses an array of the Resource without an index, so it sorts as missing (SORTING_ARRAY_PATH). */
35
+ export declare function crossesArray(resource: Resource, path: SortPath): boolean;
36
+ /** The `SORT_ARRAY_PATH` Warning for a sort path, written as a field list item in `field` (SORTING_ARRAY_PATH). */
37
+ export declare function sortArrayPathWarning(path: SortPath): Warning;
38
+ /**
39
+ * The `SORT_ARRAY_PATH` Warnings of a sort (SORTING_ARRAY_PATH, D112): one for each distinct key path that crosses an
40
+ * array in at least one of the Resources, in key order. A provider that sorts passes every matched Resource, not
41
+ * only the page, and reports these once per operation.
42
+ */
43
+ export declare function sortArrayPathWarnings(resources: Iterable<Resource>, keys: readonly SortKey[]): Warning[];
33
44
  /**
34
45
  * A comparator for `Array.prototype.sort` (SORTING_FIELD_LIST): each key in order, descending keys reversed, so
35
- * that `null` and missing values come first in ascending order and last in descending order (SORTING_NULLS).
36
- * `options.codec` as in `compareSortValues`.
46
+ * that `null` and missing values come first in ascending order and last in descending order (SORTING_NULLS). Values
47
+ * are read with `getPath` (SORTING_ARRAY_PATH). `options.codec` as in `compareSortValues`.
37
48
  */
38
49
  export declare function compareResources(keys: readonly SortKey[], options?: SortOptions): (a: Resource, b: Resource) => number;