@abloatai/humans 0.59.1 → 0.60.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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/dist/Ablo.d.ts +2 -10
  3. package/dist/Ablo.js +0 -1
  4. package/dist/client.d.ts +1 -48
  5. package/dist/local/BaseSyncedStore.d.ts +6 -8
  6. package/dist/local/BaseSyncedStore.js +4 -9
  7. package/dist/local/Model.js +2 -2
  8. package/dist/local/SyncClient.d.ts +3 -3
  9. package/dist/local/SyncClient.js +45 -11
  10. package/dist/local/client/createModelOperations.d.ts +3 -27
  11. package/dist/local/client/createModelOperations.js +14 -17
  12. package/dist/local/client/options.d.ts +14 -39
  13. package/dist/local/client/reactiveEngine.d.ts +3 -9
  14. package/dist/local/client/reactiveEngine.js +6 -151
  15. package/dist/local/client/storeLifecycle.js +5 -1
  16. package/dist/local/storeContract.d.ts +5 -5
  17. package/dist/local/sync/credentialLifecycle.d.ts +4 -5
  18. package/dist/local/sync/credentialLifecycle.js +4 -5
  19. package/dist/local/sync/deltaPipeline.d.ts +11 -3
  20. package/dist/local/sync/deltaPipeline.js +27 -80
  21. package/dist/local/sync/scopeGroups.d.ts +11 -0
  22. package/dist/local/sync/scopeGroups.js +75 -0
  23. package/dist/local/sync/wsFrameHandlers.d.ts +1 -1
  24. package/dist/local/transactions/mutations/failureHandling.js +9 -81
  25. package/dist/local/transactions/mutations/failureReporting.d.ts +10 -0
  26. package/dist/local/transactions/mutations/failureReporting.js +67 -0
  27. package/dist/react/AbloProvider.d.ts +11 -86
  28. package/dist/react/AbloProvider.js +10 -162
  29. package/dist/react.d.ts +1 -1
  30. package/dist/react.js +1 -1
  31. package/dist/surface.d.ts +2 -2
  32. package/dist/surface.js +1 -4
  33. package/package.json +3 -2
  34. package/src/Ablo.ts +5 -17
  35. package/src/client.ts +0 -51
  36. package/src/local/BaseSyncedStore.ts +11 -17
  37. package/src/local/Model.ts +2 -2
  38. package/src/local/SyncClient.ts +63 -15
  39. package/src/local/client/createModelOperations.ts +23 -60
  40. package/src/local/client/options.ts +20 -43
  41. package/src/local/client/reactiveEngine.ts +7 -179
  42. package/src/local/client/storeLifecycle.ts +6 -1
  43. package/src/local/storeContract.ts +5 -5
  44. package/src/local/sync/SyncWebSocket.ts +1 -1
  45. package/src/local/sync/credentialLifecycle.ts +4 -5
  46. package/src/local/sync/deltaPipeline.ts +26 -82
  47. package/src/local/sync/scopeGroups.ts +91 -0
  48. package/src/local/sync/wsFrameHandlers.ts +0 -1
  49. package/src/local/transactions/mutations/failureHandling.ts +73 -132
  50. package/src/local/transactions/mutations/failureReporting.ts +93 -0
  51. package/src/react/AbloProvider.tsx +17 -249
  52. package/src/react.ts +1 -5
  53. package/src/surface.ts +1 -4
  54. package/dist/local/sync/participants.d.ts +0 -132
  55. package/dist/local/sync/participants.js +0 -342
  56. package/src/local/sync/participants.ts +0 -564
package/src/surface.ts CHANGED
@@ -41,7 +41,6 @@ export const PUBLIC_MODEL_VERBS = [
41
41
  'update',
42
42
  'delete',
43
43
  'claim',
44
- 'join',
45
44
  'onChange',
46
45
  ] as const;
47
46
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -76,11 +75,9 @@ type _ListOptionKeysExact = Expect<
76
75
  export const PUBLIC_ABLO_OPTION_KEYS = [
77
76
  'schema',
78
77
  'apiKey',
78
+ 'session',
79
79
  'projectId',
80
80
  'branchId',
81
- 'authEndpoint',
82
- 'authTimeoutMs',
83
- 'allowCrossOriginAuthEndpoint',
84
81
  'persistence',
85
82
  'durableWrites',
86
83
  'commitOutbox',
@@ -1,132 +0,0 @@
1
- import type { JoinOptions } from '@abloatai/transaction/client/resources/modelOperations';
2
- import type { SyncWebSocket } from './SyncWebSocket.js';
3
- import type { Schema } from '@abloatai/transaction/schema/schema';
4
- import type { Claim, Activity, ClaimTarget, ClaimStream, Peer, PresenceStream, PresenceTarget } from '@abloatai/transaction/types/streams';
5
- import type { AttachableClaimStream } from './createClaimStream.js';
6
- /**
7
- * The scope a participant can be joined to. The usual form is an entity target
8
- * (`{ type, id }`); raw sync-group strings are an advanced escape hatch for
9
- * addressing a transport scope directly.
10
- */
11
- export type ParticipantScope = ClaimTarget | readonly ClaimTarget[] | string | readonly string[] | {
12
- readonly syncGroup: string;
13
- } | {
14
- readonly syncGroups: readonly string[];
15
- } | Record<string, string | readonly string[] | undefined>;
16
- export type ParticipantStatus = 'idle' | 'connecting' | 'connected' | 'error' | 'disconnected';
17
- export interface EngineParticipant {
18
- readonly presence: PresenceStream;
19
- readonly claims: ClaimStream;
20
- }
21
- /**
22
- * The options for a participant join. It extends the public per-model
23
- * {@link JoinOptions} rather than restating its members, so the lease dial is
24
- * declared once, in the core, and this surface adds only what a lower-level
25
- * join can additionally say.
26
- */
27
- export interface ParticipantJoinOptions extends JoinOptions {
28
- /**
29
- * The initial focus target, named in your schema's vocabulary and optionally
30
- * narrowed to a field. When `scope` is omitted, this target also becomes the
31
- * routing scope.
32
- */
33
- readonly target?: PresenceTarget;
34
- /** Alias for `target` when the participant is joined to a broader scope. */
35
- readonly focus?: PresenceTarget;
36
- /**
37
- * The routing scope: one entity, many entities, or a raw sync-group escape
38
- * hatch. Use it for "joined to the folder, focused on one file" shapes,
39
- * where the participant listens more broadly than its focus target.
40
- */
41
- readonly scope?: ParticipantScope;
42
- /** Present a narrower capability for this logical participant. */
43
- readonly capabilityToken?: string;
44
- /**
45
- * @deprecated Use `ttl`. Removed in 0.37.0.
46
- *
47
- * One lease, spelled two ways, and the seconds spelling was the one that
48
- * misled: it accepted a duration string, so `ablo.<model>.join(ids, { ttl:
49
- * '5m' })` reached this surface as `ttlSeconds: '5m'` — a field whose name
50
- * asserts a unit its value did not carry. `ttl` takes the same values and is
51
- * the spelling every other lease in the SDK already uses (`claim`'s `ttl`,
52
- * `ClaimLeaseOptions.ttl`). The wire is unchanged: it has always carried
53
- * seconds, and still does.
54
- */
55
- readonly ttlSeconds?: number | string | null;
56
- /**
57
- * The activity to announce as soon as the claim is acknowledged. Defaults to
58
- * `reading` when a `target` is present. Pass `false` to join without
59
- * announcing anything.
60
- */
61
- readonly activity?: 'reading' | 'viewing' | 'editing' | false;
62
- readonly detail?: string;
63
- }
64
- export interface ScopedPresence {
65
- readonly self: Peer;
66
- readonly focus: ClaimTarget | null;
67
- readonly others: readonly Peer[];
68
- update(activity: Activity): void;
69
- reading(detail?: string): void;
70
- reading(target: PresenceTarget, detail?: string): void;
71
- viewing(detail?: string): void;
72
- viewing(target: PresenceTarget, detail?: string): void;
73
- editing(detail?: string): void;
74
- editing(target: PresenceTarget, detail?: string): void;
75
- idle(): void;
76
- onChange(listener: () => void): () => void;
77
- }
78
- export interface ScopedClaimOptions {
79
- /** Override the participant's focus target for this one claim. */
80
- readonly target?: PresenceTarget;
81
- /** Peer-visible description of the work. Defaults to `'editing'`. */
82
- readonly description?: string;
83
- /** How long the claim lives; the server expires it automatically after this. */
84
- readonly ttl?: import('@abloatai/transaction/types/streams').Duration;
85
- }
86
- export interface ScopedClaims {
87
- readonly focus: ClaimTarget | null;
88
- readonly others: readonly Claim[];
89
- /**
90
- * Takes an exclusive claim on the participant's focus target, or on an
91
- * explicit target passed via `opts.target`. While the claim is held, other
92
- * participants that request an overlapping target are rejected.
93
- */
94
- claim(opts?: ScopedClaimOptions): Claim;
95
- onRejected(listener: Parameters<ClaimStream['onRejected']>[0]): () => void;
96
- onChange(listener: () => void): () => void;
97
- }
98
- export interface ParticipantFocusOptions {
99
- readonly activity?: 'reading' | 'viewing' | 'editing' | false;
100
- readonly detail?: string;
101
- }
102
- export interface JoinedParticipant {
103
- /** The exact entity this participant is currently reading or editing. */
104
- readonly target: ClaimTarget | null;
105
- readonly focusTarget: ClaimTarget | null;
106
- /** The transport scopes this participant is joined to, which govern what it sees and receives. */
107
- readonly syncGroups: readonly string[];
108
- readonly presence: ScopedPresence;
109
- readonly claims: ScopedClaims;
110
- readonly peers: readonly Peer[];
111
- readonly activeClaims: readonly Claim[];
112
- focus(target: PresenceTarget, options?: ParticipantFocusOptions): JoinedParticipant;
113
- leave(): void;
114
- [Symbol.asyncDispose](): Promise<void>;
115
- }
116
- export interface ParticipantManager {
117
- join(target: PresenceTarget, options?: Omit<ParticipantJoinOptions, 'target'>): Promise<JoinedParticipant>;
118
- join(options: ParticipantJoinOptions): Promise<JoinedParticipant>;
119
- }
120
- export interface ParticipantManagerConfig {
121
- readonly ready: () => Promise<void>;
122
- /** The connection, host-built and stable for the client's lifetime. */
123
- readonly transport: SyncWebSocket;
124
- readonly presence: PresenceStream;
125
- readonly claims: AttachableClaimStream;
126
- readonly schema?: Schema;
127
- }
128
- export declare function createParticipantManager(config: ParticipantManagerConfig): ParticipantManager;
129
- export declare function resolveParticipantSyncGroups(scope: ParticipantScope | undefined, schema?: Schema): string[];
130
- export declare function syncGroupFromEntityRef(ref: ClaimTarget, schema?: Schema): string;
131
- export declare function parseParticipantTtlSeconds(value: number | string | null | undefined): number | undefined;
132
- export declare function createParticipantClaimId(): string;
@@ -1,342 +0,0 @@
1
- import { scopeKindOf } from '@abloatai/transaction/schema/model';
2
- import { AbloValidationError } from '@abloatai/transaction/errors';
3
- import { subTarget, streamTarget, wireTarget, } from '@abloatai/transaction/coordination';
4
- export function createParticipantManager(config) {
5
- return {
6
- async join(input, overrides) {
7
- const options = normalizeJoinOptions(input, overrides);
8
- const target = options.focus ?? options.target
9
- ? targetToEntityRef((options.focus ?? options.target))
10
- : null;
11
- const syncGroups = unique(resolveParticipantSyncGroups(options.scope ?? target ?? undefined, config.schema));
12
- await config.ready();
13
- // Not-connected joins surface through `sendClaim`'s diagnosed
14
- // rejection below; a scopeless join needs no wire send at all.
15
- const transport = config.transport;
16
- const claimId = createParticipantClaimId();
17
- if (syncGroups.length > 0) {
18
- await transport.sendClaim(claimId, syncGroups, {
19
- capabilityToken: options.capabilityToken,
20
- // `ttl` is the spelling; `ttlSeconds` is the deprecated one, read
21
- // second so a caller passing both gets the current name honored.
22
- // eslint-disable-next-line @typescript-eslint/no-deprecated -- reading the deprecated alias IS the back-compat this line provides
23
- ttlSeconds: parseParticipantTtlSeconds(options.ttl ?? options.ttlSeconds),
24
- });
25
- }
26
- const participant = createJoinedParticipant({
27
- target,
28
- syncGroups,
29
- claimId,
30
- transport,
31
- presence: config.presence,
32
- claims: config.claims,
33
- });
34
- if (target && options.activity !== false) {
35
- const activity = options.activity ?? 'reading';
36
- if (activity === 'editing') {
37
- participant.presence.editing(options.detail);
38
- }
39
- else if (activity === 'viewing') {
40
- participant.presence.viewing(options.detail);
41
- }
42
- else {
43
- participant.presence.reading(options.detail);
44
- }
45
- }
46
- return participant;
47
- },
48
- };
49
- }
50
- export function resolveParticipantSyncGroups(scope, schema) {
51
- if (!scope)
52
- return [];
53
- if (typeof scope === 'string')
54
- return [scope];
55
- if (Array.isArray(scope)) {
56
- return scope.flatMap((entry) => typeof entry === 'string' ? [entry] : [syncGroupFromEntityRef(entry, schema)]);
57
- }
58
- const direct = scope;
59
- if (isEntityScope(scope))
60
- return [syncGroupFromEntityRef(scope, schema)];
61
- if (typeof direct.syncGroup === 'string')
62
- return [direct.syncGroup];
63
- if (Array.isArray(direct.syncGroups)) {
64
- return direct.syncGroups.filter((g) => typeof g === 'string');
65
- }
66
- const out = [];
67
- for (const [key, value] of Object.entries(scope)) {
68
- if (value === undefined)
69
- continue;
70
- if (Array.isArray(value)) {
71
- for (const id of value)
72
- out.push(syncGroupFromSchemaKey(key, id, schema));
73
- }
74
- else {
75
- out.push(syncGroupFromSchemaKey(key, value, schema));
76
- }
77
- }
78
- return out;
79
- }
80
- /**
81
- * The group kind for a model, in the wire dialect every plane shares: a
82
- * declared scope root wins; otherwise the lowercased typename — the same
83
- * token the commit plane and claim targets use (`wireModel`). Never the
84
- * camelCase schema key: the server validates inbound subscription groups
85
- * against a lowercase-only grammar, so a key like `reportBlocks` would be
86
- * rejected as malformed on subscribe — and even a lowercase key would put
87
- * this client in a different group than a peer who resolved the same row
88
- * through an entity ref, so the two would never see each other's claims.
89
- */
90
- function groupKindForModel(def, key) {
91
- return scopeKindOf(def, key) ?? (def.typename ?? key).toLowerCase();
92
- }
93
- export function syncGroupFromEntityRef(ref, schema) {
94
- const match = findModelForEntityRef(ref, schema);
95
- const kind = match
96
- ? groupKindForModel(match.def, match.key)
97
- : ref.type.toLowerCase();
98
- return `${kind}:${ref.id}`;
99
- }
100
- function syncGroupFromSchemaKey(schemaKey, id, schema) {
101
- const def = schema?.models?.[schemaKey];
102
- const kind = def ? groupKindForModel(def, schemaKey) : schemaKey.toLowerCase();
103
- return `${kind}:${id}`;
104
- }
105
- function findModelForEntityRef(ref, schema) {
106
- if (!schema?.models)
107
- return null;
108
- const wanted = ref.type.toLowerCase();
109
- for (const [key, def] of Object.entries(schema.models)) {
110
- const typename = def.typename ?? key;
111
- if (typename.toLowerCase() === wanted || key.toLowerCase() === wanted) {
112
- return { key, def };
113
- }
114
- }
115
- return null;
116
- }
117
- export function parseParticipantTtlSeconds(value) {
118
- if (typeof value === 'number' && Number.isFinite(value))
119
- return value;
120
- if (!value)
121
- return undefined;
122
- if (typeof value !== 'string')
123
- return undefined;
124
- const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(value.trim());
125
- if (!match)
126
- return undefined;
127
- const amount = Number(match[1]);
128
- const unit = match[2] ?? 's';
129
- if (unit === 'ms')
130
- return Math.max(1, Math.ceil(amount / 1000));
131
- if (unit === 'm')
132
- return Math.ceil(amount * 60);
133
- if (unit === 'h')
134
- return Math.ceil(amount * 3600);
135
- return Math.ceil(amount);
136
- }
137
- export function createParticipantClaimId() {
138
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
139
- return `participant:${crypto.randomUUID()}`;
140
- }
141
- return `participant:${Date.now()}:${Math.random().toString(36).slice(2)}`;
142
- }
143
- function normalizeJoinOptions(input, overrides) {
144
- if (isTupleTarget(input) || isEntityScope(input)) {
145
- return { ...overrides, target: input };
146
- }
147
- return { ...input, ...overrides };
148
- }
149
- function isTupleTarget(value) {
150
- return (Array.isArray(value) &&
151
- typeof value[0] === 'string' &&
152
- typeof value[1] === 'string');
153
- }
154
- function isEntityScope(scope) {
155
- return (typeof scope === 'object' &&
156
- scope !== null &&
157
- !Array.isArray(scope) &&
158
- typeof scope.type === 'string' &&
159
- typeof scope.id === 'string');
160
- }
161
- function targetToEntityRef(target) {
162
- if (isTupleTarget(target))
163
- return { type: target[0], id: target[1] };
164
- return target;
165
- }
166
- function unique(values) {
167
- return [...new Set(values)];
168
- }
169
- function createJoinedParticipant(args) {
170
- const ownHandles = new Set();
171
- let currentTarget = args.target;
172
- let left = false;
173
- const requireTarget = (target) => {
174
- const resolved = target ? targetToEntityRef(target) : currentTarget;
175
- if (!resolved) {
176
- throw new AbloValidationError('Participant action requires a structured target', {
177
- code: 'invalid_request',
178
- });
179
- }
180
- return resolved;
181
- };
182
- const setFocus = (target, options) => {
183
- currentTarget = targetToEntityRef(target);
184
- if (options?.activity === 'editing') {
185
- scopedPresence.editing(options.detail);
186
- }
187
- else if (options?.activity === 'viewing') {
188
- scopedPresence.viewing(options.detail);
189
- }
190
- else if (options?.activity === 'reading') {
191
- scopedPresence.reading(options.detail);
192
- }
193
- return joined;
194
- };
195
- const resolvePresenceAction = (targetOrDetail, detail) => {
196
- if (typeof targetOrDetail === 'string' || targetOrDetail === undefined) {
197
- return { target: requireTarget(), detail: targetOrDetail ?? detail };
198
- }
199
- return { target: requireTarget(targetOrDetail), detail };
200
- };
201
- const scopedPresence = {
202
- get self() {
203
- return args.presence.self;
204
- },
205
- get focus() {
206
- return currentTarget;
207
- },
208
- get others() {
209
- return args.presence.others.filter((entry) => presenceMatchesParticipant(entry, currentTarget, args.syncGroups));
210
- },
211
- update(activity) {
212
- args.presence.update(activity);
213
- },
214
- reading(targetOrDetail, detail) {
215
- const action = resolvePresenceAction(targetOrDetail, detail);
216
- args.presence.update({
217
- ...activityFromTarget(action.target),
218
- action: 'reading',
219
- detail: action.detail,
220
- });
221
- },
222
- viewing(targetOrDetail, detail) {
223
- const action = resolvePresenceAction(targetOrDetail, detail);
224
- args.presence.viewing(action.target, action.detail);
225
- },
226
- editing(targetOrDetail, detail) {
227
- const action = resolvePresenceAction(targetOrDetail, detail);
228
- args.presence.editing(action.target, action.detail);
229
- },
230
- idle() {
231
- args.presence.idle();
232
- },
233
- onChange(listener) {
234
- return args.presence.onChange(listener);
235
- },
236
- };
237
- const track = (handle) => {
238
- ownHandles.add(handle);
239
- return {
240
- object: 'claim',
241
- id: handle.id,
242
- description: handle.description,
243
- target: handle.target,
244
- async release() {
245
- ownHandles.delete(handle);
246
- await handle.release?.();
247
- },
248
- revoke() {
249
- ownHandles.delete(handle);
250
- handle.revoke?.();
251
- },
252
- [Symbol.asyncDispose]: async () => {
253
- ownHandles.delete(handle);
254
- await handle[Symbol.asyncDispose]?.();
255
- },
256
- };
257
- };
258
- const scopedClaims = {
259
- get focus() {
260
- return currentTarget;
261
- },
262
- get others() {
263
- return args.claims.others.filter((claim) => currentTarget ? targetsOverlap(claim.target, currentTarget) : true);
264
- },
265
- claim(opts) {
266
- return track(args.claims.claim(requireTarget(opts?.target), {
267
- description: opts?.description,
268
- ttl: opts?.ttl,
269
- }));
270
- },
271
- onRejected(listener) {
272
- return args.claims.onRejected(listener);
273
- },
274
- onChange(listener) {
275
- return args.claims.onChange(listener);
276
- },
277
- };
278
- const leave = () => {
279
- if (left)
280
- return;
281
- left = true;
282
- for (const handle of Array.from(ownHandles)) {
283
- handle.revoke?.();
284
- ownHandles.delete(handle);
285
- }
286
- args.presence.idle();
287
- if (args.syncGroups.length > 0) {
288
- args.transport.sendRelease(args.claimId);
289
- }
290
- };
291
- const joined = {
292
- get target() {
293
- return currentTarget;
294
- },
295
- get focusTarget() {
296
- return currentTarget;
297
- },
298
- syncGroups: [...args.syncGroups],
299
- presence: scopedPresence,
300
- claims: scopedClaims,
301
- get peers() {
302
- return scopedPresence.others;
303
- },
304
- get activeClaims() {
305
- return scopedClaims.others;
306
- },
307
- focus: setFocus,
308
- leave,
309
- [Symbol.asyncDispose]: async () => {
310
- leave();
311
- },
312
- };
313
- return joined;
314
- }
315
- function activityFromTarget(target) {
316
- return {
317
- ...wireTarget(target),
318
- ...subTarget(target),
319
- };
320
- }
321
- function presenceMatchesParticipant(entry, target, syncGroups) {
322
- if (syncGroups.some((g) => entry.syncGroups.includes(g)))
323
- return true;
324
- if (!target)
325
- return true;
326
- return targetsOverlap({
327
- ...streamTarget(entry.activity),
328
- ...subTarget(entry.activity),
329
- }, target);
330
- }
331
- function targetsOverlap(a, b) {
332
- if (a.type !== b.type || a.id !== b.id)
333
- return false;
334
- if (!hasSubtarget(a) || !hasSubtarget(b))
335
- return true;
336
- // Field is the floor: same field overlaps, different fields do not. Sub-field
337
- // targeting returns when same-field concurrency (OT) is solved.
338
- return !a.field || !b.field || a.field === b.field;
339
- }
340
- function hasSubtarget(target) {
341
- return Boolean(target.field);
342
- }