@crud-api/metadata 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,51 @@
1
- # Temporary Holding Version
1
+ # @crud-api/metadata
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [Metadata extension](https://lingodata.3gr.am/crud/metadata/metadata/) (`metadata 0.1.0`) of the CRUD API reference implementation: every Resource gets a reserved Field `_meta` with its version, a content hash, the events that happened to it (`created`, `updated`, status events), an optional status and its provenance (`ancestor`, `origin`), all managed by the Server; writes can be made conditional on the expected hash.
4
+
5
+ ESM only, requires Node 24 or later (also runs on Bun and Deno). Apache-2.0.
6
+
7
+ ## Usage
8
+
9
+ ```ts
10
+ import { createCrudServer } from "@crud-api/core";
11
+ import { createMemoryProvider } from "@crud-api/memory";
12
+ import { metadata } from "@crud-api/metadata";
13
+
14
+ const server = createCrudServer({ provider: createMemoryProvider({ collections: { customers: {} } }), extensions: [metadata()] });
15
+
16
+ const created = await server.execute({
17
+ operation: "create",
18
+ collection: "customers",
19
+ resources: { name: "Ana", total: 10, _meta: { status: "draft" } },
20
+ meta: { principal: "gustavo@example.com" },
21
+ });
22
+ // created.resources._meta:
23
+ // { version: 1, hash: "5fWJ6A", status: "draft",
24
+ // events: { created: { timestamp: Date, author: "gustavo@example.com" },
25
+ // draft: { timestamp: Date, author: "gustavo@example.com" } } }
26
+
27
+ // Fails with PRECONDITION_FAILED, writing nothing, when someone changed the Resource meanwhile.
28
+ await server.execute({ operation: "patchById", collection: "customers", id, patch, params: { ifMatch: "5fWJ6A" } });
29
+ ```
30
+
31
+ The HTTP adapter (`@crud-api/http`) mirrors `_meta` in `ETag` and `Last-Modified` and reads `If-Match` and `If-None-Match`; the MCP adapter (`@crud-api/mcp`) reads the `ifMatch` argument. Both turn these on when `metadata` is among the Server's specifications.
32
+
33
+ ## API
34
+
35
+ - `metadata(options?)`: the extension, for `createCrudServer({ extensions })`. `options.author(principal)` gives the `author` of the events a write records from `request.meta.principal`; by default the principal when it is a non-empty string, otherwise no `author` (META_EVENT_AUTHOR is a SHOULD).
36
+ - `metaHash(resource, codec?)`: the content hash of META_DOC_HASH. `contentOf` and `canonicalContent` give the content it is computed from; `crc32` and `base64url` are the two steps.
37
+ - `METADATA_VERSION`: `"0.1.0"`.
38
+
39
+ It reads the stored form of a Resource through the hook context (`stored`, D128) and the Client's patch through `beforeWrite`, both from `@crud-api/core` 0.3.0. The extension declares the error code `PRECONDITION_FAILED`, the Warning code `META_IGNORED` and the Parameter `ifMatch` (`patchById`, `patchByQuery`, `replaceById`, `replaceByQuery`, `deleteById`, `deleteByQuery`). Put it last in `extensions` when other extensions change Resources in `beforeWrite`, so the hash covers their changes.
40
+
41
+ ## Behaviour
42
+
43
+ Decisions D116 to D128 of `docs/decisions.md` record each reading; in short:
44
+
45
+ - **Version** (META_DOC_VERSION): `1` on creation (`create`, an upsert, `clone`), plus one on every write that changes the Resource: its content (every Field but `_id` and `_meta`, compared in canonical ECSON) or its status. A write that changes nothing keeps `_meta` as stored, while the Modified Count still counts it (D121). A Resource stored without `_meta` counts as version 0.
46
+ - **Hash** (META_DOC_HASH): CRC-32 (ISO-HDLC) of the ECSON canonical serialization of the content as the provider stores it (a value of a type the provider does not store natively hashes in its plain JSON form, as it is stored and read back), 4 bytes big-endian, base64url without padding. It never depends on the negotiated Representation. `{ "name": "Ana", "total": 10 }` gives `5fWJ6A`. CRC-32 detects changes; it does not protect against deliberate tampering.
47
+ - **Events** (META_EVENT_CREATED, META_EVENT_UPDATED, META_STATUS_EVENT): `timestamp` from the Server clock, `author` as above, and the `reason` and `comments` the Client sends in `_meta.events.<name>` for the events the write records: `created` on creation, `updated` on a change, the new status's event on a status change.
48
+ - **Status** (META_STATUS): set on creation, changed by `patch` or `replace`; a valid Field name other than `created` and `updated`, since it names an event (D123). Removing it records no event.
49
+ - **Provenance**: `clone` sets `ancestor` to a collection reference to the source (META_ANCESTOR); `create` and upserts accept `ancestor` (a collection reference) and `origin` (any `$rel`) from the Client (META_ORIGIN). A clone starts a new `_meta`: status, origin and the source's events are not copied (D122).
50
+ - **Ignored members** (META_SERVER_MANAGED): a member the Client sent that it may not write is ignored, the stored value kept, and reported once per operation with `META_IGNORED` and its field path (`_meta.version`, `_meta.events.created.timestamp`). In a Resource sent whole (`create`, `replace`) a value equal to the stored one is not "sent", so a Client may send a Resource back as it read it; a patch sends what it touches, equal or not (D118, D128).
51
+ - **Conditional writes** (META_DOC_CONDITIONAL): `ifMatch` is one expected hash or a list of them; the current hash is computed from the current Resource; a missing Resource fails too. With a write by query, every matched Resource must match, checked before any write (D120). The check and the write run in one transaction when the provider has transactions; without them a concurrent write between the read and the write is not detected (the cost of design 6.7).
@@ -0,0 +1,4 @@
1
+ /** CRC-32/ISO-HDLC of the bytes, as an unsigned 32-bit integer (`"123456789"` gives `0xCBF43926`). */
2
+ export declare function crc32(bytes: Uint8Array): number;
3
+ /** base64url of the bytes, without padding (RFC 4648 section 5). */
4
+ export declare function base64url(bytes: Uint8Array): string;
package/dist/crc32.js ADDED
@@ -0,0 +1,36 @@
1
+ // META_DOC_HASH: CRC-32 with the ISO-HDLC polynomial (the one of zlib and gzip: reflected 0xEDB88320, initial value
2
+ // and final XOR 0xFFFFFFFF), from a lookup table built once; and base64url without padding (RFC 4648 section 5).
3
+ const TABLE = (() => {
4
+ const table = new Uint32Array(256);
5
+ for (let n = 0; n < 256; n++) {
6
+ let c = n;
7
+ for (let k = 0; k < 8; k++)
8
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
9
+ table[n] = c >>> 0;
10
+ }
11
+ return table;
12
+ })();
13
+ /** CRC-32/ISO-HDLC of the bytes, as an unsigned 32-bit integer (`"123456789"` gives `0xCBF43926`). */
14
+ export function crc32(bytes) {
15
+ let crc = 0xffffffff;
16
+ for (const byte of bytes)
17
+ crc = TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
18
+ return (crc ^ 0xffffffff) >>> 0;
19
+ }
20
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
21
+ /** base64url of the bytes, without padding (RFC 4648 section 5). */
22
+ export function base64url(bytes) {
23
+ let text = "";
24
+ for (let i = 0; i < bytes.length; i += 3) {
25
+ const a = bytes[i];
26
+ const b = bytes[i + 1];
27
+ const c = bytes[i + 2];
28
+ text += ALPHABET[a >> 2];
29
+ text += ALPHABET[((a & 3) << 4) | ((b ?? 0) >> 4)];
30
+ if (b !== undefined)
31
+ text += ALPHABET[((b & 15) << 2) | ((c ?? 0) >> 6)];
32
+ if (c !== undefined)
33
+ text += ALPHABET[c & 63];
34
+ }
35
+ return text;
36
+ }
package/dist/hash.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { type Resource } from "@crud-api/core";
2
+ import { type Codec } from "@ecson/core";
3
+ /** The content of a Resource: every Field but `_id` and `_meta`. */
4
+ export declare function contentOf(resource: Resource): Resource;
5
+ /** ECSON canonical serialization of the content (ECSON CANONICAL_JCS), with the Server's codec. */
6
+ export declare function canonicalContent(resource: Resource, codec?: Codec): string;
7
+ /**
8
+ * META_DOC_HASH: CRC-32 (ISO-HDLC) of the UTF-8 bytes of the ECSON canonical serialization of the Resource without
9
+ * `_id` and `_meta`, its 4 bytes in big-endian order in base64url without padding. The same for any Representation:
10
+ * the canonical form is always ECSON. `{ "name": "Ana", "total": 10 }` gives `5fWJ6A`.
11
+ */
12
+ export declare function metaHash(resource: Resource, codec?: Codec): string;
13
+ /** The `_meta` of a stored Resource as an object (`{}` when it has none or it is not an object). */
14
+ export declare function storedMeta(resource: Resource | null | undefined): Record<string, unknown>;
package/dist/hash.js ADDED
@@ -0,0 +1,29 @@
1
+ // META_DOC_HASH (D119): the content hash of a Resource.
2
+ import { isPlainObject } from "@crud-api/core";
3
+ import { createCodec } from "@ecson/core";
4
+ import { base64url, crc32 } from "./crc32.js";
5
+ const defaultCodec = createCodec();
6
+ const utf8 = new TextEncoder();
7
+ /** The content of a Resource: every Field but `_id` and `_meta`. */
8
+ export function contentOf(resource) {
9
+ const { _id: _, _meta: __, ...content } = resource;
10
+ return content;
11
+ }
12
+ /** ECSON canonical serialization of the content (ECSON CANONICAL_JCS), with the Server's codec. */
13
+ export function canonicalContent(resource, codec = defaultCodec) {
14
+ return codec.stringify(contentOf(resource), { canonical: true });
15
+ }
16
+ /**
17
+ * META_DOC_HASH: CRC-32 (ISO-HDLC) of the UTF-8 bytes of the ECSON canonical serialization of the Resource without
18
+ * `_id` and `_meta`, its 4 bytes in big-endian order in base64url without padding. The same for any Representation:
19
+ * the canonical form is always ECSON. `{ "name": "Ana", "total": 10 }` gives `5fWJ6A`.
20
+ */
21
+ export function metaHash(resource, codec = defaultCodec) {
22
+ const crc = crc32(utf8.encode(canonicalContent(resource, codec)));
23
+ return base64url(new Uint8Array([crc >>> 24, (crc >>> 16) & 0xff, (crc >>> 8) & 0xff, crc & 0xff]));
24
+ }
25
+ /** The `_meta` of a stored Resource as an object (`{}` when it has none or it is not an object). */
26
+ export function storedMeta(resource) {
27
+ const meta = resource?._meta;
28
+ return isPlainObject(meta) ? meta : {};
29
+ }
@@ -0,0 +1,4 @@
1
+ export { metadata, METADATA_VERSION } from "./metadata.ts";
2
+ export type { MetadataOptions } from "./metadata.ts";
3
+ export { canonicalContent, contentOf, metaHash } from "./hash.ts";
4
+ export { base64url, crc32 } from "./crc32.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { metadata, METADATA_VERSION } from "./metadata.js";
2
+ export { canonicalContent, contentOf, metaHash } from "./hash.js";
3
+ export { base64url, crc32 } from "./crc32.js";
@@ -0,0 +1,12 @@
1
+ import { type Extension } from "@crud-api/core";
2
+ export interface MetadataOptions {
3
+ /**
4
+ * The `author` of the events a write records (META_EVENT_AUTHOR), from the Client's identity (`request.meta.principal`).
5
+ * Default: the principal when it is a non-empty string, otherwise no `author`.
6
+ */
7
+ author?(principal: unknown): string | undefined;
8
+ }
9
+ /** The specification version this package implements. */
10
+ export declare const METADATA_VERSION = "0.1.0";
11
+ /** The Metadata extension: pass it to `createCrudServer({ extensions: [metadata()] })`. */
12
+ export declare function metadata(options?: MetadataOptions): Extension;
@@ -0,0 +1,332 @@
1
+ // The Metadata extension (specs/metadata, design 7.1): the reserved Field `_meta` with version, content hash, events,
2
+ // status and provenance, managed by the Server, and conditional writes on the expected hash.
3
+ import { cloneValue, CrudError, formatFieldPath, isPlainObject } from "@crud-api/core";
4
+ import { Rel } from "@ecson/core";
5
+ import { canonicalContent, metaHash, storedMeta } from "./hash.js";
6
+ /** The writes the expected hash applies to (META_DOC_CONDITIONAL, HTTP_META_IF_MATCH, MCP_ARGS_PRECONDITIONS). */
7
+ const CONDITIONAL = ["patchById", "patchByQuery", "replaceById", "replaceByQuery", "deleteById", "deleteByQuery"];
8
+ const PATCHES = new Set(["patchById", "patchByQuery"]);
9
+ const EVENT_INPUT = ["reason", "comments"];
10
+ /** The specification version this package implements. */
11
+ export const METADATA_VERSION = "0.1.0";
12
+ const defaultAuthor = (principal) => (typeof principal === "string" && principal !== "" ? principal : undefined);
13
+ /** D120: `ifMatch` is one expected hash or a list of them (any listed one matches; an empty list never does). */
14
+ function checkIfMatch(value) {
15
+ if (typeof value === "string")
16
+ return;
17
+ if (Array.isArray(value) && value.every((v) => typeof v === "string"))
18
+ return;
19
+ throw new CrudError("INVALID_INPUT", "the expected hash (ifMatch) must be a string or a list of strings", { rule: "META_DOC_CONDITIONAL" });
20
+ }
21
+ /** The Metadata extension: pass it to `createCrudServer({ extensions: [metadata()] })`. */
22
+ export function metadata(options = {}) {
23
+ const author = options.author ?? defaultAuthor;
24
+ return {
25
+ name: "metadata",
26
+ spec: "metadata",
27
+ versions: [METADATA_VERSION],
28
+ reservedFields: ["_meta"], // META_FIELD
29
+ errorCodes: ["PRECONDITION_FAILED"],
30
+ warningCodes: ["META_IGNORED"],
31
+ parameters: [{ name: "ifMatch", operations: CONDITIONAL, check: checkIfMatch }],
32
+ precondition: (input, ctx) => precondition(input, ctx),
33
+ beforeWrite: (input, ctx) => new MetaWrite(input, ctx, author).run(),
34
+ };
35
+ }
36
+ /**
37
+ * META_DOC_CONDITIONAL (D120): the expected hash must match the current Resource, computed from its content (so it is
38
+ * exact also for a Resource this extension never wrote). A missing Resource never matches (HTTP_IF_MATCH_MISSING).
39
+ */
40
+ function precondition(input, ctx) {
41
+ const expected = input.params.ifMatch;
42
+ if (expected === undefined)
43
+ return;
44
+ const list = typeof expected === "string" ? [expected] : expected;
45
+ if (input.current === null) {
46
+ throw new CrudError("PRECONDITION_FAILED", "the Resource does not exist, so it cannot have the expected hash", { rule: "META_DOC_CONDITIONAL" });
47
+ }
48
+ const hash = metaHash(input.current, ctx.codec);
49
+ if (!list.includes(hash)) {
50
+ throw new CrudError("PRECONDITION_FAILED", `the Resource has the hash ${hash}, not the expected one`, { rule: "META_DOC_CONDITIONAL" });
51
+ }
52
+ }
53
+ /** An own property, never one inherited from the prototype (`__proto__`, `constructor`). */
54
+ const own = (o, key) => (Object.hasOwn(o, key) ? o[key] : undefined);
55
+ /** Sets an own enumerable member, also one named `__proto__`. */
56
+ function define(target, key, value) {
57
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
58
+ }
59
+ /** RFC 6901: the segments of a JSON Pointer, or null when it is not one. */
60
+ function pointer(text) {
61
+ if (typeof text !== "string" || (text !== "" && !text.startsWith("/")))
62
+ return null;
63
+ return text === "" ? [] : text.slice(1).split("/").map((s) => s.replaceAll("~1", "/").replaceAll("~0", "~"));
64
+ }
65
+ /**
66
+ * The paths a patch touches (D128): each JSON Patch operation's `path` (and the `from` of `move`, which removes it;
67
+ * `test` changes nothing), and each leaf of a Merge Patch document (a member whose value is not an object, `null`
68
+ * included, which removes it).
69
+ */
70
+ function touchedPaths(patch) {
71
+ const paths = [];
72
+ if (patch.type === "json-patch") {
73
+ for (const op of Array.isArray(patch.ops) ? patch.ops : []) {
74
+ if (!isPlainObject(op) || op.op === "test")
75
+ continue;
76
+ const path = pointer(op.path);
77
+ if (path !== null)
78
+ paths.push(path);
79
+ if (op.op === "move") {
80
+ const from = pointer(op.from);
81
+ if (from !== null)
82
+ paths.push(from);
83
+ }
84
+ }
85
+ }
86
+ else {
87
+ const walk = (value, at) => {
88
+ if (!isPlainObject(value)) {
89
+ paths.push(at);
90
+ return;
91
+ }
92
+ for (const key of Object.keys(value))
93
+ walk(value[key], [...at, key]);
94
+ };
95
+ if (isPlainObject(patch.doc))
96
+ walk(patch.doc, []);
97
+ else
98
+ paths.push([]);
99
+ }
100
+ return paths;
101
+ }
102
+ const isPrefix = (prefix, path) => prefix.length <= path.length && prefix.every((s, i) => s === path[i]);
103
+ /** One `beforeWrite` call: the `_meta` of the Resource about to be written. */
104
+ class MetaWrite {
105
+ #input;
106
+ #ctx;
107
+ #author;
108
+ #codec;
109
+ /** The write creates a Resource: `create`, an upsert or `clone`. */
110
+ #creates;
111
+ /** What the Client's `_meta` is compared with to know what it sent (D118). */
112
+ #baseline;
113
+ /**
114
+ * The paths the Client's patch touched (patches and clones; a clone without a patch touched nothing), or null for
115
+ * a Resource sent whole (`create`, `replace`, upserts), D128.
116
+ */
117
+ #touched;
118
+ /** Type errors come from a patch (INVALID_PATCH) or from a Resource (INVALID_INPUT). */
119
+ #code;
120
+ constructor(input, ctx, author) {
121
+ this.#input = input;
122
+ this.#ctx = ctx;
123
+ this.#author = author;
124
+ this.#codec = ctx.codec;
125
+ this.#creates = input.previous === null;
126
+ this.#baseline = input.operation === "clone" ? storedMeta(input.source?.resource) : storedMeta(input.previous);
127
+ const patched = PATCHES.has(input.operation) || input.operation === "clone";
128
+ this.#touched = patched ? (input.patch === undefined ? [] : touchedPaths(input.patch)) : null;
129
+ this.#code = patched ? "INVALID_PATCH" : "INVALID_INPUT";
130
+ }
131
+ #same(a, b) {
132
+ if (a === undefined || b === undefined)
133
+ return a === b;
134
+ return this.#codec.stringify(a, { canonical: true }) === this.#codec.stringify(b, { canonical: true });
135
+ }
136
+ /** META_SERVER_MANAGED: an ignored member, reported once per operation (META_IGNORED with its field path). */
137
+ #ignore(path) {
138
+ const field = formatFieldPath(["_meta", ...path]);
139
+ this.#ctx.warnOnce({ code: "META_IGNORED", message: `the Server manages ${field}: the value sent was ignored`, field });
140
+ }
141
+ /**
142
+ * Whether the Client sent the member at `path` (under `_meta`), whose value is `value` (absent when `present` is
143
+ * false) and whose baseline is `base` (D118, D128). A Resource sent whole sends what differs from the baseline; a
144
+ * missing member is left as it is. A patch sends what it touched at or below the member, even a value equal to the
145
+ * stored one; when it replaced a parent of the member, what differs from the baseline, removals included.
146
+ */
147
+ #sent(path, value, base, present) {
148
+ const touched = this.#touched;
149
+ if (touched === null)
150
+ return present && !this.#same(value, base);
151
+ const at = ["_meta", ...path];
152
+ if (touched.some((t) => isPrefix(at, t)))
153
+ return present || base !== undefined;
154
+ if (touched.some((t) => t.length < at.length && isPrefix(t, at)))
155
+ return present ? !this.#same(value, base) : base !== undefined;
156
+ return false;
157
+ }
158
+ /** The keys whose members may have been sent: the input's, plus the baseline's when a patch may have removed them. */
159
+ #keys(input, base) {
160
+ return new Set([...Object.keys(input), ...(this.#touched === null ? [] : Object.keys(base))]);
161
+ }
162
+ run() {
163
+ const { next, previous, operation } = this.#input;
164
+ const present = Object.hasOwn(next, "_meta");
165
+ let input = {};
166
+ let whole = true;
167
+ if (present && !isPlainObject(next._meta)) {
168
+ // A `_meta` that is not an object is ignored as a whole: nothing in it is read (D118).
169
+ if (this.#sent([], next._meta, this.#input.source?.resource._meta ?? previous?._meta, true))
170
+ this.#ignore([]);
171
+ whole = false;
172
+ }
173
+ else if (present)
174
+ input = next._meta;
175
+ const { _meta: _, ...rest } = next;
176
+ const resource = rest;
177
+ const old = storedMeta(previous);
178
+ // The members the Client sent, top level (D118).
179
+ const sent = new Set();
180
+ if (whole) {
181
+ for (const key of this.#keys(input, this.#baseline)) {
182
+ if (key === "events")
183
+ continue;
184
+ if (this.#sent([key], own(input, key), own(this.#baseline, key), Object.hasOwn(input, key)))
185
+ sent.add(key);
186
+ }
187
+ }
188
+ // META_STATUS, META_STATUS_EVENT (D123).
189
+ const oldStatus = this.#creates ? undefined : own(old, "status");
190
+ let status = oldStatus;
191
+ if (sent.has("status")) {
192
+ status = own(input, "status");
193
+ if (status !== undefined)
194
+ this.#checkStatus(status);
195
+ }
196
+ const statusChanged = status !== undefined && status !== oldStatus;
197
+ // META_DOC_VERSION, META_EVENT_UPDATED (D121): only a write that changes the Resource as stored (D128).
198
+ const stored = this.#ctx.stored(resource);
199
+ const changes = this.#creates || status !== oldStatus || canonicalContent(stored, this.#codec) !== canonicalContent(previous, this.#codec);
200
+ const recorded = new Set();
201
+ if (this.#creates)
202
+ recorded.add("created");
203
+ else if (changes)
204
+ recorded.add("updated");
205
+ if (statusChanged)
206
+ recorded.add(status);
207
+ // Provenance (META_ANCESTOR, META_ORIGIN): Client values only on `create` and upserts.
208
+ const provenanceWritable = this.#creates && operation !== "clone";
209
+ for (const key of sent) {
210
+ if (key === "status")
211
+ continue;
212
+ if ((key === "ancestor" || key === "origin") && provenanceWritable)
213
+ continue;
214
+ this.#ignore([key]);
215
+ }
216
+ const eventInput = whole ? this.#eventInput(input, recorded) : new Map();
217
+ if (!changes) {
218
+ // D121: an unchanged Resource keeps its `_meta` as stored (also none).
219
+ return previous !== null && Object.hasOwn(previous, "_meta") ? { ...resource, _meta: cloneValue(previous._meta) } : resource;
220
+ }
221
+ const meta = {};
222
+ const oldVersion = typeof old.version === "number" && Number.isSafeInteger(old.version) && old.version >= 1 ? old.version : 0;
223
+ meta.version = this.#creates ? 1 : oldVersion + 1;
224
+ meta.hash = metaHash(stored, this.#codec); // META_DOC_HASH: the content as the provider stores it (D128)
225
+ if (status !== undefined)
226
+ meta.status = status;
227
+ const oldEvents = own(old, "events");
228
+ const events = !this.#creates && isPlainObject(oldEvents) ? cloneValue(oldEvents) : {};
229
+ const timestamp = new Date(this.#ctx.clock());
230
+ const who = this.#author(this.#ctx.principal);
231
+ for (const name of recorded) {
232
+ const event = { timestamp };
233
+ if (who !== undefined)
234
+ event.author = who; // META_EVENT_AUTHOR
235
+ Object.assign(event, eventInput.get(name)); // META_EVENT_COMMENTS
236
+ define(events, name, event); // META_EVENT_CREATED, META_EVENT_UPDATED, META_STATUS_EVENT: replaces the previous one
237
+ }
238
+ meta.events = events;
239
+ if (operation === "clone") {
240
+ // META_ANCESTOR, D122: a collection reference to the source.
241
+ const source = this.#input.source;
242
+ if (source !== undefined)
243
+ meta.ancestor = new Rel({ collection: source.collection, id: source.id });
244
+ }
245
+ else if (provenanceWritable) {
246
+ if (sent.has("ancestor") && own(input, "ancestor") !== undefined)
247
+ meta.ancestor = this.#checkAncestor(own(input, "ancestor"));
248
+ if (sent.has("origin") && own(input, "origin") !== undefined)
249
+ meta.origin = this.#checkOrigin(own(input, "origin"));
250
+ }
251
+ else {
252
+ if (own(old, "ancestor") !== undefined)
253
+ meta.ancestor = cloneValue(own(old, "ancestor"));
254
+ if (own(old, "origin") !== undefined)
255
+ meta.origin = cloneValue(own(old, "origin"));
256
+ }
257
+ return { ...resource, _meta: meta };
258
+ }
259
+ /**
260
+ * The `reason` and `comments` the Client sent for the events this write records (META_EVENT_COMMENTS); everything
261
+ * else sent under `events` is ignored (META_SERVER_MANAGED, D118).
262
+ */
263
+ #eventInput(input, recorded) {
264
+ const result = new Map();
265
+ const given = own(input, "events");
266
+ const before = own(this.#baseline, "events");
267
+ if (Object.hasOwn(input, "events") && !isPlainObject(given)) {
268
+ if (this.#sent(["events"], given, before, true))
269
+ this.#ignore(["events"]);
270
+ return result;
271
+ }
272
+ const events = isPlainObject(given) ? given : {};
273
+ const base = isPlainObject(before) ? before : {};
274
+ for (const name of this.#keys(events, base)) {
275
+ const event = own(events, name);
276
+ const presentEvent = Object.hasOwn(events, name);
277
+ if (!this.#sent(["events", name], event, own(base, name), presentEvent))
278
+ continue;
279
+ if (!recorded.has(name) || (presentEvent && !isPlainObject(event))) {
280
+ // A removed event of a recorded name is rebuilt anyway; anything else is the Server's.
281
+ if (!(recorded.has(name) && !presentEvent))
282
+ this.#ignore(["events", name]);
283
+ continue;
284
+ }
285
+ const e = presentEvent ? event : {};
286
+ const b0 = own(base, name);
287
+ const b = isPlainObject(b0) ? b0 : {};
288
+ const members = {};
289
+ for (const member of this.#keys(e, b)) {
290
+ const has = Object.hasOwn(e, member);
291
+ if (!this.#sent(["events", name, member], own(e, member), own(b, member), has))
292
+ continue;
293
+ if (EVENT_INPUT.includes(member)) {
294
+ if (!has || e[member] === undefined)
295
+ continue; // removed: the new event has none
296
+ if (typeof e[member] !== "string") {
297
+ throw new CrudError(this.#code, `_meta.events.${name}.${member} must be a string`, { rule: "META_EVENT_COMMENTS" });
298
+ }
299
+ members[member] = e[member];
300
+ }
301
+ else {
302
+ this.#ignore(["events", name, member]);
303
+ }
304
+ }
305
+ result.set(name, members);
306
+ }
307
+ return result;
308
+ }
309
+ /** D123: a status names an event, so it is a valid Field name other than `created` and `updated`. */
310
+ #checkStatus(status) {
311
+ if (typeof status !== "string")
312
+ throw new CrudError(this.#code, "_meta.status must be a string", { rule: "META_STATUS" });
313
+ if (status === "" || status.startsWith("$") || status.startsWith("@")) {
314
+ throw new CrudError(this.#code, `_meta.status ${JSON.stringify(status)} must be a valid Field name, since it names an event`, { rule: "META_STATUS" });
315
+ }
316
+ if (status === "created" || status === "updated") {
317
+ throw new CrudError(this.#code, `_meta.status cannot be ${status}: its event would replace the ${status} event`, { rule: "META_STATUS" });
318
+ }
319
+ }
320
+ /** META_ANCESTOR: an ECSON collection reference. */
321
+ #checkAncestor(value) {
322
+ if (value instanceof Rel && value.kind === "collection")
323
+ return value;
324
+ throw new CrudError(this.#code, "_meta.ancestor must be an ECSON collection reference ($rel with collection and id)", { rule: "META_ANCESTOR" });
325
+ }
326
+ /** META_ORIGIN: an ECSON reference. */
327
+ #checkOrigin(value) {
328
+ if (value instanceof Rel)
329
+ return value;
330
+ throw new CrudError(this.#code, "_meta.origin must be an ECSON reference ($rel)", { rule: "META_ORIGIN" });
331
+ }
332
+ }
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@crud-api/metadata",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Metadata extension of the CRUD API reference implementation: _meta with version, content hash, events, status and provenance, and conditional writes",
5
+ "keywords": [
6
+ "crud",
7
+ "api",
8
+ "metadata",
9
+ "etag",
10
+ "versioning",
11
+ "lingodata"
12
+ ],
13
+ "homepage": "https://lingodata.3gr.am/crud/",
14
+ "bugs": {
15
+ "url": "https://github.com/lingodata/crud/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/lingodata/crud.git",
20
+ "directory": "packages/metadata"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "author": "Gustavo Gondim",
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "types": "./dist/index.d.ts",
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "engines": {
40
+ "node": ">=24"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@crud-api/core": "^0.2.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@ecson/core": "^0.2.0"
50
+ },
51
+ "devDependencies": {
52
+ "@crud-api/memory": "^0.2.0",
53
+ "@unquery/core": "^0.2.0"
54
+ }
55
+ }