@hydranium/protocol 1.0.0-next.117 → 1.0.0-next.123

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.
Files changed (60) hide show
  1. package/lib/client/data-connection.d.ts +28 -66
  2. package/lib/client/data-connection.d.ts.map +1 -1
  3. package/lib/client/data-connection.js +41 -112
  4. package/lib/client/data-connection.js.map +1 -1
  5. package/lib/client/data-session.d.ts +168 -93
  6. package/lib/client/data-session.d.ts.map +1 -1
  7. package/lib/client/data-session.js +291 -147
  8. package/lib/client/data-session.js.map +1 -1
  9. package/lib/data/data-protocol-methods.d.ts +2 -2
  10. package/lib/data/data-protocol-methods.d.ts.map +1 -1
  11. package/lib/data/data-protocol-methods.js +4 -0
  12. package/lib/data/data-protocol-methods.js.map +1 -1
  13. package/lib/data/data-server-protocol.d.ts +66 -30
  14. package/lib/data/data-server-protocol.d.ts.map +1 -1
  15. package/lib/data/requests.d.ts +67 -11
  16. package/lib/data/requests.d.ts.map +1 -1
  17. package/lib/errors.d.ts +66 -4
  18. package/lib/errors.d.ts.map +1 -1
  19. package/lib/errors.js +96 -5
  20. package/lib/errors.js.map +1 -1
  21. package/lib/messages/index.d.ts +1 -0
  22. package/lib/messages/index.d.ts.map +1 -1
  23. package/lib/messages/index.js +4 -1
  24. package/lib/messages/index.js.map +1 -1
  25. package/lib/model-server.d.ts +13 -1
  26. package/lib/model-server.d.ts.map +1 -1
  27. package/lib/model-server.js.map +1 -1
  28. package/lib/model-service/based-on.d.ts +2 -0
  29. package/lib/model-service/based-on.d.ts.map +1 -1
  30. package/lib/model-service/based-on.js +3 -0
  31. package/lib/model-service/based-on.js.map +1 -1
  32. package/lib/model-service/index.d.ts +0 -1
  33. package/lib/model-service/index.d.ts.map +1 -1
  34. package/lib/model-service/index.js +3 -5
  35. package/lib/model-service/index.js.map +1 -1
  36. package/lib/patch-merge.d.ts +28 -27
  37. package/lib/patch-merge.d.ts.map +1 -1
  38. package/lib/patch-merge.js +66 -22
  39. package/lib/patch-merge.js.map +1 -1
  40. package/lib/transfer-document.d.ts +2 -3
  41. package/lib/transfer-document.d.ts.map +1 -1
  42. package/lib/transfer-document.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/client/data-connection.ts +69 -119
  45. package/src/client/data-session.ts +348 -177
  46. package/src/data/data-protocol-methods.ts +4 -0
  47. package/src/data/data-server-protocol.ts +74 -30
  48. package/src/data/requests.ts +71 -11
  49. package/src/errors.ts +101 -4
  50. package/src/messages/index.ts +1 -0
  51. package/src/model-server.ts +13 -5
  52. package/src/model-service/based-on.ts +3 -0
  53. package/src/model-service/index.ts +3 -5
  54. package/src/patch-merge.ts +90 -37
  55. package/src/transfer-document.ts +2 -3
  56. package/lib/model-service/args.d.ts +0 -65
  57. package/lib/model-service/args.d.ts.map +0 -1
  58. package/lib/model-service/args.js +0 -11
  59. package/lib/model-service/args.js.map +0 -1
  60. package/src/model-service/args.ts +0 -69
@@ -7,34 +7,43 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { applyPatch, compare, deepClone, getValueByPointer, type Operation as JsonPatchOperation } from 'fast-json-patch';
10
+ import {
11
+ _areEquals,
12
+ applyPatch,
13
+ compare,
14
+ deepClone,
15
+ getValueByPointer,
16
+ type Operation as JsonPatchOperation,
17
+ unescapePathComponent
18
+ } from 'fast-json-patch';
11
19
 
12
20
  /**
13
- * Augment a user-intent JSON patch (computed `baseline → attempted`) with
21
+ * Augment a user-intent JSON patch (computed `base → ours`) with
14
22
  * `test` ops so a strict `applyPatch` against freshly-fetched server state
15
23
  * fails loudly when a foreign writer changed a path the user also changed.
16
24
  *
17
25
  * `fast-json-patch`'s `validateOperation: true` validates op structure and
18
26
  * path resolvability but NOT the pre-existing value — a plain `replace` /
19
27
  * `remove` silently overwrites whatever the foreign writer put there. For each
20
- * `replace` / `remove` op we prepend a `test` op carrying the baseline value at
28
+ * `replace` / `remove` op we prepend a `test` op carrying the base value at
21
29
  * that path, so a same-path divergence becomes a `TEST_OPERATION_FAILED` throw.
22
30
  * The caller treats that as a real field-level conflict (drop + refetch) rather
23
31
  * than silently clobbering the foreign edit.
24
32
  *
25
- * `add` ops are left unguarded: the path is new, so there is no baseline value
26
- * to test against, and add-vs-add overlaps are out of scope for this floor.
33
+ * `add` ops get no `test` op: the path is new, so there is no base value
34
+ * to test. {@link reconcileByPatchReplay} checks them against theirs
35
+ * instead; a caller applying this patch itself does not get that check.
27
36
  *
28
37
  * Used behind the framework's `ConflictError` contract by every reconcile
29
38
  * path — the GLSP recording command's undo/redo and forward-write, via
30
39
  * {@link ReconcilingConflictResolver}, and an adopter's form-widget save — so
31
40
  * they share one collision-detection rule.
32
41
  */
33
- export function augmentWithTestOps(baseline: object, userPatch: ReadonlyArray<JsonPatchOperation>): JsonPatchOperation[] {
42
+ export function augmentWithTestOps(base: object, userPatch: ReadonlyArray<JsonPatchOperation>): JsonPatchOperation[] {
34
43
  const augmented: JsonPatchOperation[] = [];
35
44
  for (const op of userPatch) {
36
45
  if (op.op === 'replace' || op.op === 'remove') {
37
- augmented.push({ op: 'test', path: op.path, value: getValueByPointer(baseline, op.path) });
46
+ augmented.push({ op: 'test', path: op.path, value: getValueByPointer(base, op.path) });
38
47
  }
39
48
  augmented.push(op);
40
49
  }
@@ -42,39 +51,38 @@ export function augmentWithTestOps(baseline: object, userPatch: ReadonlyArray<Js
42
51
  }
43
52
 
44
53
  /**
45
- * Outcome of {@link reconcileByPatchReplay}. The caller persists / re-baselines
46
- * on `merged`, drops + surfaces the `fresh` root on `conflict`, and decides its
47
- * own fallback (e.g. force-retry) on `no-op` / `unavailable`.
54
+ * Outcome of {@link reconcileByPatchReplay}. The caller persists `merged` and
55
+ * takes it as the new base, drops + surfaces the `theirs` root on `conflict`, and
56
+ * decides its own fallback (e.g. force-retry) on `no-op` / `unavailable`.
48
57
  */
49
58
  export type ReconcileOutcome<T> =
50
59
  | {
51
60
  /** The replay succeeded: the foreign writer touched no path the user did. */
52
61
  status: 'merged';
53
62
  /**
54
- * A fresh root built on the refetched server state, carrying both
55
- * intents. It is NOT the caller's `attempted` root — re-baseline on
56
- * this value, or the next write diffs against state the server never
57
- * had.
63
+ * A new root built on theirs, carrying both intents. It is NOT the
64
+ * caller's `ours` root — take this value as the new base, or the next
65
+ * write diffs against state the server never had.
58
66
  */
59
67
  merged: T;
60
68
  }
61
69
  | {
62
70
  /**
63
- * The user's root already equalled the baseline, so the version gate
71
+ * The user's root already equalled the base, so the version gate
64
72
  * fired on drift that changed nothing. No refetch was performed and
65
73
  * there is nothing to persist — retrying the same write reproduces it.
66
74
  */
67
75
  status: 'no-op';
68
76
  }
69
77
  | {
70
- /** A guarded `test` op tripped: user and foreign writer touched one path. */
78
+ /** User and foreign writer changed one path, or both added the same element or key. */
71
79
  status: 'conflict';
72
80
  /**
73
81
  * The server's current root, refetched and unmodified — the user's
74
82
  * intent was NOT applied to it. Surface it and drop the write; treating
75
83
  * it as a merge result silently discards what the user typed.
76
84
  */
77
- fresh: T;
85
+ theirs: T;
78
86
  }
79
87
  | {
80
88
  /**
@@ -87,39 +95,84 @@ export type ReconcileOutcome<T> =
87
95
 
88
96
  /**
89
97
  * Shared three-way reconcile for a `ConflictError`: diff the user's intent
90
- * (`baseline → attempted`), refetch the server's current root, and replay the
98
+ * (`base → ours`), refetch the server's current root (theirs), and replay the
91
99
  * intent on top under strict, {@link augmentWithTestOps}-guarded `applyPatch`.
92
100
  *
93
- * - `no-op` — the user's root equals the baseline, so the gate fired on a
101
+ * - `no-op` — the user's root equals the base, so the gate fired on a
94
102
  * benign version drift; nothing to replay (refetch is skipped).
95
103
  * - `unavailable` — the refetch produced nothing; caller falls back.
96
104
  * - `merged` — the foreign writer touched only paths the user did not; the
97
105
  * merged root carries both intents.
98
- * - `conflict` — a same-path divergence tripped a `test` op; caller drops the
99
- * write and surfaces `fresh`.
106
+ * - `conflict` — a same-path divergence tripped a `test` op, or an `add`
107
+ * collides with one the foreign writer made; caller drops the write and
108
+ * surfaces `theirs`.
100
109
  *
101
110
  * I/O is the caller's: `refetch` supplies the current root, and applying the
102
- * `merged` result (update vs save, re-baseline, UI refresh) stays at the call
111
+ * `merged` result (update vs save, new base, UI refresh) stays at the call
103
112
  * site so form and GLSP paths keep their own persistence semantics.
104
113
  */
105
114
  export async function reconcileByPatchReplay<T extends object>(
106
- baseline: T,
107
- attempted: T,
115
+ base: T,
116
+ ours: T,
108
117
  refetch: () => Promise<T | undefined>
109
118
  ): Promise<ReconcileOutcome<T>> {
110
- const userPatch = compare(baseline, attempted);
119
+ const userPatch = compare(base, ours);
111
120
  if (userPatch.length === 0) {
112
121
  return { status: 'no-op' };
113
122
  }
114
- const fresh = await refetch();
115
- if (!fresh) {
123
+ const theirs = await refetch();
124
+ if (!theirs) {
116
125
  return { status: 'unavailable' };
117
126
  }
127
+ if (addsCollide(base, theirs, userPatch)) {
128
+ return { status: 'conflict', theirs };
129
+ }
118
130
  try {
119
- const merged = applyPatch(deepClone(fresh), augmentWithTestOps(baseline, userPatch), true).newDocument;
131
+ const merged = applyPatch(deepClone(theirs), augmentWithTestOps(base, userPatch), true).newDocument;
120
132
  return { status: 'merged', merged };
121
133
  } catch {
122
- return { status: 'conflict', fresh };
134
+ return { status: 'conflict', theirs };
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Whether an `add` of `userPatch` collides with one the foreign writer made:
140
+ * it inserts a value into an array that `theirs` holds more often than
141
+ * `base` did, or it adds an object key that `theirs` already holds.
142
+ *
143
+ * Replayed, the first inserts the value a second time and the second replaces
144
+ * the foreign value. Identical values conflict rather than being skipped:
145
+ * skipping drops one of two additions that merely happen to be equal.
146
+ */
147
+ function addsCollide(base: object, theirs: object, userPatch: readonly JsonPatchOperation[]): boolean {
148
+ // Through JSON, as `compare` clones the add values: an undefined-valued key
149
+ // in `theirs` would otherwise make an equal element count as another.
150
+ const comparable = JSON.parse(JSON.stringify(theirs)) as object;
151
+ return userPatch.some(op => {
152
+ if (op.op !== 'add') {
153
+ return false;
154
+ }
155
+ const cut = op.path.lastIndexOf('/');
156
+ const before = valueAt(base, op.path.slice(0, cut));
157
+ const now = valueAt(comparable, op.path.slice(0, cut));
158
+ if (Array.isArray(before)) {
159
+ return Array.isArray(now) && occurrences(now, op.value) > occurrences(before, op.value);
160
+ }
161
+ return typeof now === 'object' && now !== null && Object.hasOwn(now, unescapePathComponent(op.path.slice(cut + 1)));
162
+ });
163
+ }
164
+
165
+ /** How many elements of `array` deeply equal `value`, whatever their key order. */
166
+ function occurrences(array: readonly unknown[], value: unknown): number {
167
+ return array.filter(element => _areEquals(element, value)).length;
168
+ }
169
+
170
+ /** The value at `pointer`, or `undefined` when a step of it is missing. */
171
+ function valueAt(document: object, pointer: string): unknown {
172
+ try {
173
+ return getValueByPointer(document, pointer);
174
+ } catch {
175
+ return undefined;
123
176
  }
124
177
  }
125
178
 
@@ -132,12 +185,12 @@ export async function reconcileByPatchReplay<T extends object>(
132
185
  */
133
186
  export interface ConflictResolver {
134
187
  /**
135
- * Reconcile the user's `baseline → attempted` intent against the current
136
- * server state (`refetch`), returning a {@link ReconcileOutcome} the caller
188
+ * Reconcile the user's `base → ours` intent against the current
189
+ * server state (theirs, from `refetch`), returning a {@link ReconcileOutcome} the caller
137
190
  * acts on (persist `merged`, drop on `conflict`, fall back on `no-op` /
138
191
  * `unavailable`).
139
192
  */
140
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
193
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>>;
141
194
  }
142
195
 
143
196
  /**
@@ -147,19 +200,19 @@ export interface ConflictResolver {
147
200
  * clobbered.
148
201
  */
149
202
  export class ReconcilingConflictResolver implements ConflictResolver {
150
- resolve<T extends object>(baseline: T, attempted: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
151
- return reconcileByPatchReplay(baseline, attempted, refetch);
203
+ resolve<T extends object>(base: T, ours: T, refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
204
+ return reconcileByPatchReplay(base, ours, refetch);
152
205
  }
153
206
  }
154
207
 
155
208
  /**
156
- * Last-writer-wins {@link ConflictResolver}: always reports the `attempted`
209
+ * Last-writer-wins {@link ConflictResolver}: always reports the `ours`
157
210
  * state as merged, without refetching or guarding. Suitable for single-client
158
211
  * tools or always-regenerated artifacts where a concurrent foreign edit may be
159
212
  * overwritten. A foreign edit to any field is clobbered.
160
213
  */
161
214
  export class ForceConflictResolver implements ConflictResolver {
162
- async resolve<T extends object>(_baseline: T, attempted: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
163
- return { status: 'merged', merged: attempted };
215
+ async resolve<T extends object>(_base: T, ours: T, _refetch: () => Promise<T | undefined>): Promise<ReconcileOutcome<T>> {
216
+ return { status: 'merged', merged: ours };
164
217
  }
165
218
  }
@@ -29,9 +29,8 @@ export interface TransferDocument<TTransfer extends TransferElement, TDiagnostic
29
29
  /**
30
30
  * The document version this snapshot was taken at — sourced from the
31
31
  * server's text-document version counter. A caller that mutates the document
32
- * subsequently sends this straight back as `TransferUpdateArgs.basedOn` (or
33
- * `TransferSaveArgs.basedOn`), and the server rejects a stale-based update
34
- * with `ConflictError`.
32
+ * subsequently sends this straight back as `TransferUpdateDocumentArgs.basedOn`, and
33
+ * the server rejects a stale-based update with `ConflictError`.
35
34
  *
36
35
  * See `@hydranium/protocol#errors` for the conflict-detection contract.
37
36
  */
@@ -1,65 +0,0 @@
1
- /********************************************************************************
2
- * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
- *
4
- * This program and the accompanying materials are made available under the
5
- * terms of the MIT License which is available in the project root.
6
- *
7
- * SPDX-License-Identifier: MIT
8
- ********************************************************************************/
9
- /**
10
- * Argument shapes for the in-process `ModelService` facade — the
11
- * canonical home for the lifecycle operation signatures. Implementation
12
- * lives in `@hydranium/core/langium/model-service`; this protocol
13
- * package owns the types so wire-side projections (the data-server
14
- * protocol in `./data`) can structurally extend them rather than
15
- * mirroring them by hand.
16
- *
17
- * `./model-server.ts` re-exports them, so an import from either path
18
- * resolves.
19
- */
20
- import type { BasedOn } from './based-on';
21
- /** Identifies a client-document binding. Every facade operation carries these fields. */
22
- export interface TransferClientArgs {
23
- /** Document URI. */
24
- uri: string;
25
- /** Stable identifier for the client invoking the operation. */
26
- clientId: string;
27
- }
28
- /**
29
- * Update a document's content via the in-process facade. `model` may be
30
- * the structured (transfer-model or AST) root or its serialised textual
31
- * form — implementations decide which is faster on their transport.
32
- * Generic over `T` so adopters parameterise the structured shape against
33
- * their grammar's transfer-model overlay; passing a string is always
34
- * allowed.
35
- */
36
- export interface TransferUpdateArgs<T> extends TransferClientArgs {
37
- /** Structured model root or its serialised textual form. */
38
- model: T | string;
39
- /**
40
- * What this update was authored against. A `SnapshotVersion` is compared
41
- * against the server's current text-document version for `uri` and throws
42
- * `ConflictError` on mismatch; `'anything'` writes unconditionally.
43
- *
44
- * **Required so that an ungated write is a decision rather than an
45
- * omission.** An optional gate is indistinguishable from a forgotten one at
46
- * the call site, and a file of twenty writes hides the one that lost the
47
- * field. Nothing else here can see that, since the defect is an absence.
48
- */
49
- basedOn: BasedOn;
50
- }
51
- /**
52
- * Persist a document to disk via the in-process facade. Same `model`
53
- * shape as {@link TransferUpdateArgs}.
54
- */
55
- export interface TransferSaveArgs<T> extends TransferClientArgs {
56
- /** Structured model root or its serialised textual form. */
57
- model: T | string;
58
- /**
59
- * Same semantics and same requirement as {@link TransferUpdateArgs.basedOn}.
60
- * `save` delegates the gating check to its inner `update`, so this field
61
- * threads through to the same `ConflictError` site.
62
- */
63
- basedOn: BasedOn;
64
- }
65
- //# sourceMappingURL=args.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"args.d.ts","sourceRoot":"","sources":["../../src/model-service/args.ts"],"names":[],"mappings":"AAAA;;;;;;;kFAOkF;AAElF;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,yFAAyF;AACzF,MAAM,WAAW,kBAAkB;IAChC,oBAAoB;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,kBAAkB,CAAC,CAAC,CAAE,SAAQ,kBAAkB;IAC9D,4DAA4D;IAC5D,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC;IAClB;;;;;;;;;OASG;IACH,OAAO,EAAE,OAAO,CAAC;CACnB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB,CAAC,CAAC,CAAE,SAAQ,kBAAkB;IAC5D,4DAA4D;IAC5D,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC;IAClB;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;CACnB"}
@@ -1,11 +0,0 @@
1
- "use strict";
2
- /********************************************************************************
3
- * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
4
- *
5
- * This program and the accompanying materials are made available under the
6
- * terms of the MIT License which is available in the project root.
7
- *
8
- * SPDX-License-Identifier: MIT
9
- ********************************************************************************/
10
- Object.defineProperty(exports, "__esModule", { value: true });
11
- //# sourceMappingURL=args.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"args.js","sourceRoot":"","sources":["../../src/model-service/args.ts"],"names":[],"mappings":";AAAA;;;;;;;kFAOkF"}
@@ -1,69 +0,0 @@
1
- /********************************************************************************
2
- * Copyright (c) 2026 CrossBreeze, EclipseSource and others.
3
- *
4
- * This program and the accompanying materials are made available under the
5
- * terms of the MIT License which is available in the project root.
6
- *
7
- * SPDX-License-Identifier: MIT
8
- ********************************************************************************/
9
-
10
- /**
11
- * Argument shapes for the in-process `ModelService` facade — the
12
- * canonical home for the lifecycle operation signatures. Implementation
13
- * lives in `@hydranium/core/langium/model-service`; this protocol
14
- * package owns the types so wire-side projections (the data-server
15
- * protocol in `./data`) can structurally extend them rather than
16
- * mirroring them by hand.
17
- *
18
- * `./model-server.ts` re-exports them, so an import from either path
19
- * resolves.
20
- */
21
-
22
- import type { BasedOn } from './based-on';
23
-
24
- /** Identifies a client-document binding. Every facade operation carries these fields. */
25
- export interface TransferClientArgs {
26
- /** Document URI. */
27
- uri: string;
28
- /** Stable identifier for the client invoking the operation. */
29
- clientId: string;
30
- }
31
-
32
- /**
33
- * Update a document's content via the in-process facade. `model` may be
34
- * the structured (transfer-model or AST) root or its serialised textual
35
- * form — implementations decide which is faster on their transport.
36
- * Generic over `T` so adopters parameterise the structured shape against
37
- * their grammar's transfer-model overlay; passing a string is always
38
- * allowed.
39
- */
40
- export interface TransferUpdateArgs<T> extends TransferClientArgs {
41
- /** Structured model root or its serialised textual form. */
42
- model: T | string;
43
- /**
44
- * What this update was authored against. A `SnapshotVersion` is compared
45
- * against the server's current text-document version for `uri` and throws
46
- * `ConflictError` on mismatch; `'anything'` writes unconditionally.
47
- *
48
- * **Required so that an ungated write is a decision rather than an
49
- * omission.** An optional gate is indistinguishable from a forgotten one at
50
- * the call site, and a file of twenty writes hides the one that lost the
51
- * field. Nothing else here can see that, since the defect is an absence.
52
- */
53
- basedOn: BasedOn;
54
- }
55
-
56
- /**
57
- * Persist a document to disk via the in-process facade. Same `model`
58
- * shape as {@link TransferUpdateArgs}.
59
- */
60
- export interface TransferSaveArgs<T> extends TransferClientArgs {
61
- /** Structured model root or its serialised textual form. */
62
- model: T | string;
63
- /**
64
- * Same semantics and same requirement as {@link TransferUpdateArgs.basedOn}.
65
- * `save` delegates the gating check to its inner `update`, so this field
66
- * threads through to the same `ConflictError` site.
67
- */
68
- basedOn: BasedOn;
69
- }