@myfield/sdk 0.9.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.
@@ -0,0 +1,253 @@
1
+ import { bytesToB64url } from "../internal/encoding.ts";
2
+
3
+ export type BinaryInput = Blob | ArrayBuffer | Uint8Array;
4
+
5
+ export type BinaryOptions = {
6
+ mimeType?: string;
7
+ name?: string;
8
+ lastModified?: number;
9
+ };
10
+
11
+ export type BucketBinaryValue = {
12
+ readonly kind: "binary";
13
+ readonly size: number;
14
+ readonly mimeType?: string;
15
+ readonly name?: string;
16
+ readonly lastModified?: number;
17
+ blob(): Promise<Blob>;
18
+ arrayBuffer(): Promise<ArrayBuffer>;
19
+ };
20
+
21
+ export type StoredBinaryValue = {
22
+ __myfieldSdkType: "binary-v1";
23
+ size: number;
24
+ bytes: Uint8Array;
25
+ mimeType?: string;
26
+ name?: string;
27
+ lastModified?: number;
28
+ };
29
+
30
+ const BINARY_HANDLE_MARKER = Symbol("myfield.sdk.binary");
31
+ const STORED_BINARY_TYPE = "binary-v1";
32
+
33
+ type RuntimeBinaryHandle = BucketBinaryValue & {
34
+ readonly [BINARY_HANDLE_MARKER]: true;
35
+ };
36
+
37
+ export function createBucketBinaryValue(input: BinaryInput | BucketBinaryValue, options: BinaryOptions = {}): BucketBinaryValue {
38
+ if (isBucketBinaryValue(input)) {
39
+ return makeBinaryHandle(
40
+ {
41
+ size: input.size,
42
+ ...(input.mimeType ? { mimeType: input.mimeType } : {}),
43
+ ...(input.name ? { name: input.name } : {}),
44
+ ...(typeof input.lastModified === "number" ? { lastModified: input.lastModified } : {}),
45
+ ...normalizeBinaryOptions(options),
46
+ },
47
+ () => input.arrayBuffer()
48
+ );
49
+ }
50
+
51
+ if (isBlobLike(input)) {
52
+ const blob = input;
53
+ const fileMeta = blob as Blob & { name?: unknown; lastModified?: unknown };
54
+ return makeBinaryHandle(
55
+ {
56
+ size: blob.size,
57
+ ...(blob.type ? { mimeType: blob.type } : {}),
58
+ ...(typeof fileMeta.name === "string" && fileMeta.name ? { name: fileMeta.name } : {}),
59
+ ...(typeof fileMeta.lastModified === "number" ? { lastModified: fileMeta.lastModified } : {}),
60
+ ...normalizeBinaryOptions(options),
61
+ },
62
+ () => blob.arrayBuffer()
63
+ );
64
+ }
65
+
66
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
67
+ return makeBinaryHandle(
68
+ {
69
+ size: bytes.byteLength,
70
+ ...normalizeBinaryOptions(options),
71
+ },
72
+ async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer
73
+ );
74
+ }
75
+
76
+ export function isBucketBinaryValue(value: unknown): value is BucketBinaryValue {
77
+ return !!value && typeof value === "object" && (value as Partial<RuntimeBinaryHandle>)[BINARY_HANDLE_MARKER] === true;
78
+ }
79
+
80
+ export function isStoredBinaryValue(value: unknown): value is StoredBinaryValue {
81
+ const row = value as Partial<StoredBinaryValue> | null;
82
+ return (
83
+ !!row &&
84
+ row.__myfieldSdkType === STORED_BINARY_TYPE &&
85
+ typeof row.size === "number" &&
86
+ Number.isSafeInteger(row.size) &&
87
+ row.size >= 0 &&
88
+ row.bytes instanceof Uint8Array &&
89
+ row.bytes.byteLength === row.size &&
90
+ optionalString(row.mimeType) &&
91
+ optionalString(row.name) &&
92
+ optionalNumber(row.lastModified)
93
+ );
94
+ }
95
+
96
+ export async function toStoredBinaryValue(value: BucketBinaryValue | StoredBinaryValue): Promise<StoredBinaryValue> {
97
+ if (isStoredBinaryValue(value)) return cloneStoredBinaryValue(value);
98
+ if (!isBucketBinaryValue(value)) throw new Error("binary value must be created with bucket.binary()");
99
+ const bytes = new Uint8Array(await value.arrayBuffer());
100
+ if (bytes.byteLength !== value.size) throw new Error("binary value size changed while reading");
101
+ return {
102
+ __myfieldSdkType: STORED_BINARY_TYPE,
103
+ size: bytes.byteLength,
104
+ bytes,
105
+ ...(value.mimeType ? { mimeType: value.mimeType } : {}),
106
+ ...(value.name ? { name: value.name } : {}),
107
+ ...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
108
+ };
109
+ }
110
+
111
+ export function hydrateBinaryValue(value: StoredBinaryValue): BucketBinaryValue {
112
+ const stored = cloneStoredBinaryValue(value);
113
+ return makeBinaryHandle(
114
+ {
115
+ size: stored.size,
116
+ ...(stored.mimeType ? { mimeType: stored.mimeType } : {}),
117
+ ...(stored.name ? { name: stored.name } : {}),
118
+ ...(typeof stored.lastModified === "number" ? { lastModified: stored.lastModified } : {}),
119
+ },
120
+ async () => stored.bytes.buffer.slice(stored.bytes.byteOffset, stored.bytes.byteOffset + stored.bytes.byteLength) as ArrayBuffer
121
+ );
122
+ }
123
+
124
+ export function binaryValueToCanonicalJson(value: StoredBinaryValue): Record<string, unknown> {
125
+ return {
126
+ __myfieldSdkType: STORED_BINARY_TYPE,
127
+ size: value.size,
128
+ data: bytesToB64url(value.bytes),
129
+ ...(value.mimeType ? { mimeType: value.mimeType } : {}),
130
+ ...(value.name ? { name: value.name } : {}),
131
+ ...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
132
+ };
133
+ }
134
+
135
+ export function fieldValueToCanonicalJson(value: unknown): unknown {
136
+ if (isStoredBinaryValue(value)) return binaryValueToCanonicalJson(value);
137
+ if (Array.isArray(value)) return value.map(fieldValueToCanonicalJson);
138
+ if (value && typeof value === "object") {
139
+ return Object.fromEntries(
140
+ Object.entries(value as Record<string, unknown>)
141
+ .sort(([a], [b]) => a.localeCompare(b))
142
+ .map(([key, item]) => [key, fieldValueToCanonicalJson(item)])
143
+ );
144
+ }
145
+ return value;
146
+ }
147
+
148
+ export async function canonicalizeFieldValue(value: unknown, seen = new WeakSet<object>()): Promise<unknown> {
149
+ if (value === undefined) return undefined;
150
+ if (value === null) return null;
151
+ if (typeof value === "string" || typeof value === "boolean") return value;
152
+ if (typeof value === "number") {
153
+ if (!Number.isFinite(value)) throw new Error("number field values must be finite");
154
+ return value;
155
+ }
156
+ if (isBucketBinaryValue(value) || isStoredBinaryValue(value)) return toStoredBinaryValue(value);
157
+ if (isRawBinaryInput(value)) throw new Error("binary field values must be created with bucket.binary()");
158
+ if (Array.isArray(value)) {
159
+ if (seen.has(value)) throw new Error("cyclic field values are not supported");
160
+ seen.add(value);
161
+ const out = [];
162
+ for (const item of value) out.push(await canonicalizeFieldValue(item, seen));
163
+ seen.delete(value);
164
+ return out;
165
+ }
166
+ if (typeof value === "object") {
167
+ if (!isPlainObject(value)) throw new Error("field values must be JSON-compatible or created with bucket.binary()");
168
+ if (seen.has(value)) throw new Error("cyclic field values are not supported");
169
+ seen.add(value);
170
+ const out: Record<string, unknown> = {};
171
+ for (const [key, item] of Object.entries(value)) out[key] = await canonicalizeFieldValue(item, seen);
172
+ seen.delete(value);
173
+ return out;
174
+ }
175
+ throw new Error("field values must be JSON-compatible or created with bucket.binary()");
176
+ }
177
+
178
+ export async function canonicalizeFieldMap(fields: Record<string, unknown>): Promise<Record<string, unknown>> {
179
+ const out: Record<string, unknown> = {};
180
+ for (const [name, value] of Object.entries(fields)) out[name] = await canonicalizeFieldValue(value);
181
+ return out;
182
+ }
183
+
184
+ export function hydrateFieldValue(value: unknown): unknown {
185
+ if (isStoredBinaryValue(value)) return hydrateBinaryValue(value);
186
+ if (Array.isArray(value)) return value.map(hydrateFieldValue);
187
+ if (value && typeof value === "object") {
188
+ return Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, hydrateFieldValue(item)]));
189
+ }
190
+ return value;
191
+ }
192
+
193
+ export function cloneStoredBinaryValue(value: StoredBinaryValue): StoredBinaryValue {
194
+ return {
195
+ __myfieldSdkType: STORED_BINARY_TYPE,
196
+ size: value.size,
197
+ bytes: new Uint8Array(value.bytes),
198
+ ...(value.mimeType ? { mimeType: value.mimeType } : {}),
199
+ ...(value.name ? { name: value.name } : {}),
200
+ ...(typeof value.lastModified === "number" ? { lastModified: value.lastModified } : {}),
201
+ };
202
+ }
203
+
204
+ function makeBinaryHandle(
205
+ meta: { size: number; mimeType?: string; name?: string; lastModified?: number },
206
+ load: () => Promise<ArrayBuffer>
207
+ ): BucketBinaryValue {
208
+ const handle: BucketBinaryValue = {
209
+ kind: "binary",
210
+ size: meta.size,
211
+ ...(meta.mimeType ? { mimeType: meta.mimeType } : {}),
212
+ ...(meta.name ? { name: meta.name } : {}),
213
+ ...(typeof meta.lastModified === "number" ? { lastModified: meta.lastModified } : {}),
214
+ async blob() {
215
+ return new Blob([await load()], { type: meta.mimeType || "" });
216
+ },
217
+ async arrayBuffer() {
218
+ const buffer = await load();
219
+ return buffer.slice(0);
220
+ },
221
+ };
222
+ Object.defineProperty(handle, BINARY_HANDLE_MARKER, { value: true });
223
+ return handle;
224
+ }
225
+
226
+ function normalizeBinaryOptions(options: BinaryOptions): BinaryOptions {
227
+ return {
228
+ ...(typeof options.mimeType === "string" && options.mimeType ? { mimeType: options.mimeType } : {}),
229
+ ...(typeof options.name === "string" && options.name ? { name: options.name } : {}),
230
+ ...(typeof options.lastModified === "number" && Number.isFinite(options.lastModified) ? { lastModified: options.lastModified } : {}),
231
+ };
232
+ }
233
+
234
+ function isBlobLike(value: unknown): value is Blob {
235
+ return typeof Blob !== "undefined" && value instanceof Blob;
236
+ }
237
+
238
+ function isRawBinaryInput(value: unknown): value is BinaryInput {
239
+ return isBlobLike(value) || value instanceof ArrayBuffer || value instanceof Uint8Array;
240
+ }
241
+
242
+ function isPlainObject(value: object): value is Record<string, unknown> {
243
+ const proto = Object.getPrototypeOf(value);
244
+ return proto === Object.prototype || proto === null;
245
+ }
246
+
247
+ function optionalString(value: unknown): boolean {
248
+ return value === undefined || typeof value === "string";
249
+ }
250
+
251
+ function optionalNumber(value: unknown): boolean {
252
+ return value === undefined || (typeof value === "number" && Number.isFinite(value));
253
+ }
@@ -0,0 +1,383 @@
1
+ // Local-first bucket client. Reads and writes hit the local store first;
2
+ // sync reconciles with the relay through the CAS retry loop
3
+ // (push conflict → pull current → merge → re-push), which converges because
4
+ // every merge strategy is required to be state-based convergent.
5
+ //
6
+ // The relay may have evicted any object. A remote miss with a surviving
7
+ // local record is healed by re-pushing the local state (CAS create).
8
+
9
+ import {
10
+ applyLwwMapUpdates,
11
+ decodePayloadDoc,
12
+ emptyLwwMapDoc,
13
+ encodePayloadDoc,
14
+ lwwMapDocsEqual,
15
+ lwwMapValues,
16
+ LwwClock,
17
+ mergeLwwMapDocs,
18
+ type LwwMapDoc,
19
+ type OpaqueDoc,
20
+ type PayloadDoc,
21
+ } from "./format.ts";
22
+ import { canonicalizeFieldMap } from "./binary.ts";
23
+ import type { StorageAdapter } from "./store.ts";
24
+ import { BucketTransportError, type TransportHeadResult, type TransportPayloadResult, type TransportPushResult } from "./transport.ts";
25
+
26
+ export type MergeStrategy = { kind: "lww-map" } | { kind: "opaque"; merge: (local: unknown, remote: unknown) => unknown };
27
+
28
+ export type BucketTransportLike = {
29
+ pullHead(wireObjectId: string): Promise<TransportHeadResult>;
30
+ pullPayload(wireObjectId: string, versionId: string): Promise<TransportPayloadResult>;
31
+ push(wireObjectId: string, plaintext: Uint8Array, expectedHeadVersionId: string | null): Promise<TransportPushResult>;
32
+ };
33
+
34
+ export type BucketClientOptions = {
35
+ transport: BucketTransportLike;
36
+ storage: StorageAdapter;
37
+ actorId: string;
38
+ wireObjectId?: (appObjectId: string) => Promise<string>;
39
+ storagePrefix?: string;
40
+ mergeStrategyFor?: (appObjectId: string) => MergeStrategy;
41
+ maxCasAttempts?: number;
42
+ pushDebounceMs?: number;
43
+ onChange?: (appObjectId: string) => void;
44
+ onSyncError?: (appObjectId: string | null, error: unknown) => void;
45
+ };
46
+
47
+ type LocalObjectRecord = {
48
+ v: 1;
49
+ doc: PayloadDoc;
50
+ remoteVersionId: string | null;
51
+ dirty: boolean;
52
+ };
53
+
54
+ const DEFAULT_MAX_CAS_ATTEMPTS = 5;
55
+ const DEFAULT_PUSH_DEBOUNCE_MS = 800;
56
+ const DEFAULT_SYNC_INTERVAL_MS = 5 * 60 * 1000;
57
+ const DEFAULT_MAX_ENCODED_OBJECT_BYTES = 100 * 1024 * 1024;
58
+
59
+ export class BucketClient {
60
+ private readonly transport: BucketTransportLike;
61
+ private readonly storage: StorageAdapter;
62
+ private readonly actorId: string;
63
+ private readonly wireId: (appObjectId: string) => Promise<string>;
64
+ private readonly prefix: string;
65
+ private readonly mergeStrategyFor: (appObjectId: string) => MergeStrategy;
66
+ private readonly maxCasAttempts: number;
67
+ private readonly pushDebounceMs: number;
68
+ private readonly maxEncodedObjectBytes = DEFAULT_MAX_ENCODED_OBJECT_BYTES;
69
+ private readonly onChange?: (appObjectId: string) => void;
70
+ private readonly onSyncError?: (appObjectId: string | null, error: unknown) => void;
71
+ private readonly clock = new LwwClock();
72
+ private readonly inFlightSync = new Map<string, Promise<boolean>>();
73
+ private readonly objectLocks = new Map<string, Promise<void>>();
74
+ private readonly pendingPushTimers = new Map<string, ReturnType<typeof setTimeout>>();
75
+ private readonly watched = new Set<string>();
76
+ private triggerCleanup: (() => void) | null = null;
77
+ private disposed = false;
78
+
79
+ constructor(options: BucketClientOptions) {
80
+ this.transport = options.transport;
81
+ this.storage = options.storage;
82
+ this.actorId = options.actorId;
83
+ this.wireId = options.wireObjectId || (async (id) => id);
84
+ this.prefix = options.storagePrefix || "myfield-sdk";
85
+ this.mergeStrategyFor = options.mergeStrategyFor || (() => ({ kind: "lww-map" }));
86
+ this.maxCasAttempts = options.maxCasAttempts ?? DEFAULT_MAX_CAS_ATTEMPTS;
87
+ this.pushDebounceMs = options.pushDebounceMs ?? DEFAULT_PUSH_DEBOUNCE_MS;
88
+ this.onChange = options.onChange;
89
+ this.onSyncError = options.onSyncError;
90
+ }
91
+
92
+ // ---- local reads -------------------------------------------------------
93
+
94
+ async getFields(appObjectId: string): Promise<Record<string, unknown> | null> {
95
+ const record = await this.readRecord(appObjectId);
96
+ if (!record || record.doc.t !== "lww-map") return null;
97
+ return lwwMapValues(record.doc);
98
+ }
99
+
100
+ async getData(appObjectId: string): Promise<unknown> {
101
+ const record = await this.readRecord(appObjectId);
102
+ if (!record || record.doc.t !== "opaque") return null;
103
+ return record.doc.data;
104
+ }
105
+
106
+ async knownObjectIds(): Promise<string[]> {
107
+ const keys = await this.storage.keys(`${this.prefix}:obj:`);
108
+ return keys.map((key) => decodeURIComponent(key.slice(`${this.prefix}:obj:`.length)));
109
+ }
110
+
111
+ // ---- local writes ------------------------------------------------------
112
+
113
+ // Every read-modify-write of a local record runs through a per-object
114
+ // queue: interleaved async writers (concurrent setFields, or a sync merge
115
+ // racing a local write) would otherwise clobber each other's snapshot and
116
+ // silently lose fields.
117
+ private withObjectLock<T>(appObjectId: string, fn: () => Promise<T>): Promise<T> {
118
+ const previous = this.objectLocks.get(appObjectId) ?? Promise.resolve();
119
+ const run = previous.then(fn, fn);
120
+ this.objectLocks.set(
121
+ appObjectId,
122
+ run.then(
123
+ () => undefined,
124
+ () => undefined
125
+ )
126
+ );
127
+ return run;
128
+ }
129
+
130
+ // `undefined` field values delete the field (tombstone).
131
+ setFields(appObjectId: string, updates: Record<string, unknown>): Promise<Record<string, unknown>> {
132
+ return this.withObjectLock(appObjectId, async () => {
133
+ const record = await this.readRecord(appObjectId);
134
+ const baseDoc: LwwMapDoc = record && record.doc.t === "lww-map" ? record.doc : emptyLwwMapDoc();
135
+ this.clock.observeDoc(baseDoc);
136
+ const nextDoc = applyLwwMapUpdates(baseDoc, await canonicalizeFieldMap(updates), this.clock, this.actorId);
137
+ this.assertEncodedObjectSize(nextDoc);
138
+ await this.writeRecord(appObjectId, {
139
+ v: 1,
140
+ doc: nextDoc,
141
+ remoteVersionId: record?.remoteVersionId ?? null,
142
+ dirty: true,
143
+ });
144
+ this.schedulePush(appObjectId);
145
+ this.onChange?.(appObjectId);
146
+ return lwwMapValues(nextDoc);
147
+ });
148
+ }
149
+
150
+ setData(appObjectId: string, data: unknown): Promise<void> {
151
+ return this.withObjectLock(appObjectId, async () => {
152
+ const record = await this.readRecord(appObjectId);
153
+ const nextDoc: OpaqueDoc = { t: "opaque", data };
154
+ this.assertEncodedObjectSize(nextDoc);
155
+ await this.writeRecord(appObjectId, {
156
+ v: 1,
157
+ doc: nextDoc,
158
+ remoteVersionId: record?.remoteVersionId ?? null,
159
+ dirty: true,
160
+ });
161
+ this.schedulePush(appObjectId);
162
+ this.onChange?.(appObjectId);
163
+ });
164
+ }
165
+
166
+ // ---- sync --------------------------------------------------------------
167
+
168
+ // Reconciles one object with the relay. Returns true when the local view
169
+ // changed because of remote data.
170
+ syncObject(appObjectId: string): Promise<boolean> {
171
+ const inFlight = this.inFlightSync.get(appObjectId);
172
+ if (inFlight) return inFlight;
173
+ const promise = this.performSync(appObjectId).finally(() => {
174
+ if (this.inFlightSync.get(appObjectId) === promise) this.inFlightSync.delete(appObjectId);
175
+ });
176
+ this.inFlightSync.set(appObjectId, promise);
177
+ return promise;
178
+ }
179
+
180
+ async syncObjects(appObjectIds: Iterable<string>): Promise<void> {
181
+ await Promise.all(Array.from(appObjectIds, (id) => this.syncObject(id).catch((error) => this.onSyncError?.(id, error))));
182
+ }
183
+
184
+ async syncKnown(): Promise<void> {
185
+ const ids = new Set([...(await this.knownObjectIds()), ...this.watched]);
186
+ await this.syncObjects(ids);
187
+ }
188
+
189
+ async syncAuto(options?: { indexObjectId?: string }): Promise<void> {
190
+ const indexObjectId = options?.indexObjectId;
191
+ const dirtyIdsBefore = await this.dirtyObjectIds();
192
+ const changedIds = new Set<string>();
193
+ if (indexObjectId) {
194
+ const before = await this.indexFields(indexObjectId);
195
+ const beforeRecord = await this.readRecord(indexObjectId);
196
+ const changed = await this.syncObject(indexObjectId);
197
+ const after = await this.indexFields(indexObjectId);
198
+ const afterRecord = await this.readRecord(indexObjectId);
199
+ if (changed) {
200
+ for (const id of diffIndexObjectIds(before, after)) changedIds.add(id);
201
+ }
202
+ if (!changed && beforeRecord && beforeRecord.remoteVersionId !== afterRecord?.remoteVersionId) {
203
+ for (const id of Object.keys(after)) changedIds.add(id);
204
+ }
205
+ }
206
+ const ids = new Set([...this.watched, ...dirtyIdsBefore, ...changedIds]);
207
+ if (indexObjectId) ids.delete(indexObjectId);
208
+ await this.syncObjects(ids);
209
+ }
210
+
211
+ watch(appObjectIds: Iterable<string>): void {
212
+ for (const id of appObjectIds) this.watched.add(id);
213
+ }
214
+
215
+ // Sync-trigger model: launch (start itself) and a timer fallback.
216
+ // Browser/app lifecycle triggers are owned by the app; post-write pushes
217
+ // are scheduled by setFields/setData.
218
+ start(options?: { intervalMs?: number; indexObjectId?: string }): void {
219
+ if (this.triggerCleanup || this.disposed) return;
220
+ const kick = () => void this.syncAuto(options).catch((error) => this.onSyncError?.(null, error));
221
+ const intervalMs = options?.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS;
222
+ const timer = intervalMs > 0 ? setInterval(kick, intervalMs) : null;
223
+ this.triggerCleanup = () => {
224
+ if (timer) clearInterval(timer);
225
+ };
226
+ kick();
227
+ }
228
+
229
+ stop(): void {
230
+ this.triggerCleanup?.();
231
+ this.triggerCleanup = null;
232
+ for (const timer of this.pendingPushTimers.values()) clearTimeout(timer);
233
+ this.pendingPushTimers.clear();
234
+ }
235
+
236
+ dispose(): void {
237
+ this.disposed = true;
238
+ this.stop();
239
+ }
240
+
241
+ async flush(appObjectId?: string): Promise<void> {
242
+ const ids = appObjectId ? [appObjectId] : Array.from(this.pendingPushTimers.keys());
243
+ for (const id of ids) {
244
+ const timer = this.pendingPushTimers.get(id);
245
+ if (timer) {
246
+ clearTimeout(timer);
247
+ this.pendingPushTimers.delete(id);
248
+ }
249
+ }
250
+ await this.syncObjects(ids);
251
+ }
252
+
253
+ // ---- internals ---------------------------------------------------------
254
+
255
+ private schedulePush(appObjectId: string): void {
256
+ if (this.disposed) return;
257
+ const existing = this.pendingPushTimers.get(appObjectId);
258
+ if (existing) clearTimeout(existing);
259
+ this.pendingPushTimers.set(
260
+ appObjectId,
261
+ setTimeout(() => {
262
+ this.pendingPushTimers.delete(appObjectId);
263
+ void this.syncObject(appObjectId).catch((error) => this.onSyncError?.(appObjectId, error));
264
+ }, this.pushDebounceMs)
265
+ );
266
+ }
267
+
268
+ private async performSync(appObjectId: string): Promise<boolean> {
269
+ const wireObjectId = await this.wireId(appObjectId);
270
+ let remoteChangedLocal = false;
271
+ for (let attempt = 0; attempt < this.maxCasAttempts; attempt += 1) {
272
+ // Each attempt holds the object lock across read → merge → write so a
273
+ // concurrent local setFields cannot land between the snapshot and the
274
+ // record write and get clobbered. Between attempts the lock is
275
+ // released, so local writes slip in and the next attempt re-reads them.
276
+ const outcome = await this.withObjectLock(appObjectId, async (): Promise<"retry" | boolean> => {
277
+ const record = await this.readRecord(appObjectId);
278
+ const head = await this.transport.pullHead(wireObjectId);
279
+
280
+ if (!head.found) {
281
+ if (!record) return false;
282
+ // Relay miss with surviving local state: re-create (self-healing).
283
+ const result = await this.transport.push(wireObjectId, encodePayloadDoc(record.doc), null);
284
+ if (result.ok) {
285
+ await this.writeRecord(appObjectId, { ...record, remoteVersionId: result.versionId, dirty: false });
286
+ return remoteChangedLocal;
287
+ }
288
+ return "retry";
289
+ }
290
+
291
+ if (record && !record.dirty && record.remoteVersionId === head.versionId) return remoteChangedLocal;
292
+
293
+ const payload = await this.transport.pullPayload(wireObjectId, head.versionId);
294
+ if (!payload.found) return "retry";
295
+ const remoteDoc = decodePayloadDoc(payload.plaintext);
296
+ const merged = record ? this.merge(appObjectId, record.doc, remoteDoc) : remoteDoc;
297
+ const localViewChanged = !record || !docsEqual(merged, record.doc);
298
+ const remoteNeedsUpdate = !docsEqual(merged, remoteDoc);
299
+
300
+ if (merged.t === "lww-map") this.clock.observeDoc(merged);
301
+
302
+ if (!remoteNeedsUpdate) {
303
+ await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: head.versionId, dirty: false });
304
+ if (localViewChanged) {
305
+ remoteChangedLocal = true;
306
+ this.onChange?.(appObjectId);
307
+ }
308
+ return remoteChangedLocal;
309
+ }
310
+
311
+ const result = await this.transport.push(wireObjectId, encodePayloadDoc(merged), head.versionId);
312
+ if (result.ok) {
313
+ await this.writeRecord(appObjectId, { v: 1, doc: merged, remoteVersionId: result.versionId, dirty: false });
314
+ if (localViewChanged) {
315
+ remoteChangedLocal = true;
316
+ this.onChange?.(appObjectId);
317
+ }
318
+ return remoteChangedLocal;
319
+ }
320
+ // CAS conflict: retry pulls the newer head and merges again.
321
+ return "retry";
322
+ });
323
+ if (outcome !== "retry") return outcome;
324
+ }
325
+ throw new BucketTransportError("sync did not converge within CAS attempt limit", 409);
326
+ }
327
+
328
+ private merge(appObjectId: string, local: PayloadDoc, remote: PayloadDoc): PayloadDoc {
329
+ const strategy = this.mergeStrategyFor(appObjectId);
330
+ if (strategy.kind === "lww-map") {
331
+ if (local.t !== "lww-map" || remote.t !== "lww-map") throw new Error(`object ${appObjectId} is not an lww-map payload`);
332
+ return mergeLwwMapDocs(local, remote);
333
+ }
334
+ if (local.t !== "opaque" || remote.t !== "opaque") throw new Error(`object ${appObjectId} is not an opaque payload`);
335
+ return { t: "opaque", data: strategy.merge(local.data, remote.data) };
336
+ }
337
+
338
+ private recordKey(appObjectId: string): string {
339
+ return `${this.prefix}:obj:${encodeURIComponent(appObjectId)}`;
340
+ }
341
+
342
+ async dirtyObjectIds(): Promise<string[]> {
343
+ const ids: string[] = [];
344
+ for (const id of await this.knownObjectIds()) {
345
+ const record = await this.readRecord(id);
346
+ if (record?.dirty) ids.push(id);
347
+ }
348
+ return ids;
349
+ }
350
+
351
+ private async indexFields(indexObjectId: string): Promise<Record<string, unknown>> {
352
+ const record = await this.readRecord(indexObjectId);
353
+ return record?.doc.t === "lww-map" ? lwwMapValues(record.doc) : {};
354
+ }
355
+
356
+ private async readRecord(appObjectId: string): Promise<LocalObjectRecord | null> {
357
+ const record = await this.storage.get<LocalObjectRecord>(this.recordKey(appObjectId));
358
+ if (!record || record.v !== 1 || !record.doc) return null;
359
+ return record;
360
+ }
361
+
362
+ private writeRecord(appObjectId: string, record: LocalObjectRecord): Promise<void> {
363
+ return this.storage.set(this.recordKey(appObjectId), record);
364
+ }
365
+
366
+ private assertEncodedObjectSize(doc: PayloadDoc): void {
367
+ const size = encodePayloadDoc(doc).byteLength;
368
+ if (size > this.maxEncodedObjectBytes) {
369
+ throw new Error(`encoded object payload exceeds ${this.maxEncodedObjectBytes} bytes`);
370
+ }
371
+ }
372
+ }
373
+
374
+ function docsEqual(a: PayloadDoc, b: PayloadDoc): boolean {
375
+ if (a.t === "lww-map" && b.t === "lww-map") return lwwMapDocsEqual(a, b);
376
+ if (a.t === "opaque" && b.t === "opaque") return JSON.stringify(a.data) === JSON.stringify(b.data);
377
+ return false;
378
+ }
379
+
380
+ function diffIndexObjectIds(before: Record<string, unknown>, after: Record<string, unknown>): string[] {
381
+ const ids = new Set([...Object.keys(before), ...Object.keys(after)]);
382
+ return [...ids].filter((id) => JSON.stringify(before[id]) !== JSON.stringify(after[id]));
383
+ }
@@ -0,0 +1,58 @@
1
+ // AES-GCM envelope, wire compatible with the established myfield bucket sync
2
+ // envelope shape. The worker only validates envelope shape (zero-knowledge
3
+ // storage); it never decrypts payloads. AAD binds bucketId and the blinded
4
+ // wire object id.
5
+
6
+ import { b64urlToBytes, bytesToB64url, utf8Decode, utf8Encode } from "../internal/encoding.ts";
7
+ import type { BucketKeys } from "./keys.ts";
8
+
9
+ export type EncryptedEnvelopeFields = {
10
+ ciphertext: string;
11
+ cipherMeta: { alg: "AES-GCM"; iv: string; keyId: string; bucketId: string; aad: string };
12
+ wrappedDEK: string;
13
+ wrappedDEKMeta: { alg: "direct-bucket-key"; keyId: string; bucketId: string };
14
+ };
15
+
16
+ export async function encryptEnvelopeFields(keys: BucketKeys, wireObjectId: string, plaintext: Uint8Array): Promise<EncryptedEnvelopeFields> {
17
+ const iv = crypto.getRandomValues(new Uint8Array(12));
18
+ const aad = buildAad(keys.bucketId, wireObjectId);
19
+ const plaintextBuffer = plaintext.buffer.slice(plaintext.byteOffset, plaintext.byteOffset + plaintext.byteLength) as ArrayBuffer;
20
+ const ciphertext = new Uint8Array(
21
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: utf8Encode(aad) }, keys.payloadKey, plaintextBuffer)
22
+ );
23
+ return {
24
+ ciphertext: bytesToB64url(ciphertext),
25
+ cipherMeta: { alg: "AES-GCM", iv: bytesToB64url(iv), keyId: keys.keyId, bucketId: keys.bucketId, aad },
26
+ wrappedDEK: keys.keyId,
27
+ wrappedDEKMeta: { alg: "direct-bucket-key", keyId: keys.keyId, bucketId: keys.bucketId },
28
+ };
29
+ }
30
+
31
+ export async function decryptEnvelope(keys: BucketKeys, wireObjectId: string, envelope: Uint8Array): Promise<Uint8Array> {
32
+ const parsed = JSON.parse(utf8Decode(envelope)) as {
33
+ cipherMeta?: { alg?: unknown; iv?: unknown; keyId?: unknown; bucketId?: unknown; aad?: unknown };
34
+ ciphertext?: unknown;
35
+ };
36
+ if (
37
+ typeof parsed.ciphertext !== "string" ||
38
+ parsed.cipherMeta?.alg !== "AES-GCM" ||
39
+ parsed.cipherMeta.keyId !== keys.keyId ||
40
+ parsed.cipherMeta.bucketId !== keys.bucketId ||
41
+ typeof parsed.cipherMeta.iv !== "string" ||
42
+ typeof parsed.cipherMeta.aad !== "string"
43
+ ) {
44
+ throw new Error("corrupted sync envelope");
45
+ }
46
+ if (parsed.cipherMeta.aad !== buildAad(keys.bucketId, wireObjectId)) throw new Error("sync envelope aad mismatch");
47
+ return new Uint8Array(
48
+ await crypto.subtle.decrypt(
49
+ { name: "AES-GCM", iv: b64urlToBytes(parsed.cipherMeta.iv) as BufferSource, additionalData: utf8Encode(parsed.cipherMeta.aad) },
50
+ keys.payloadKey,
51
+ b64urlToBytes(parsed.ciphertext) as BufferSource
52
+ )
53
+ );
54
+ }
55
+
56
+ function buildAad(bucketId: string, wireObjectId: string): string {
57
+ return `myfield.bucket.sync.v1|${bucketId}|${wireObjectId}`;
58
+ }