@vielzeug/tandem 26.11.12 → 26.11.13
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/dist/tandem.cjs +1 -1
- package/dist/tandem.cjs.map +1 -1
- package/dist/tandem.d.ts.map +1 -1
- package/dist/tandem.iife.js +1 -1
- package/dist/tandem.iife.js.map +1 -1
- package/dist/tandem.js +36 -35
- package/dist/tandem.js.map +1 -1
- package/package.json +4 -1
package/dist/tandem.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/arsenal");var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},t=3e3,baseline=(e=null)=>({cursor:e,revs:{}}),cloneState=e=>({cursor:e.cursor,revs:{...e.revs}});function createSync(n){let{gateway:r,port:i}=n,a=n.idleDelayMs??t,o=new AbortController,s=new Set,emit=e=>{if(s.size!==0)for(let t of s)try{t(e)}catch{}},warn=e=>{s.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},c=baseline(),l=(0,e.timer)(()=>void enqueue(pushJob(!1))),u=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(c.revs[envelopeKey(e)]??-1),save=()=>r.saveState(cloneState(c)),pull=async()=>{if(o.signal.aborted)return;let{cursor:e,deletions:t,records:n}=await i.pull(c.cursor),a=new Map((await r.records()).map(e=>[envelopeKey(e),e.record.rev])),s=new Set((await r.pendingDeletions()).map(e=>key(e.entity,e.id))),l=new Set(t.map(e=>key(e.entity,e.id))),u=n.filter(e=>!s.has(envelopeKey(e))&&!l.has(envelopeKey(e))&&(a.get(envelopeKey(e))??-1)<e.record.rev),d=await r.applyRecords(u);d.length&&emit({message:`Skipped invalid remote records: ${d.join(`, `)}.`,skipped:d,type:`invalid`});let f=t.filter(e=>{let t=key(e.entity,e.id);return(a.get(t)??-1)<=(c.revs[t]??-1)});await r.applyDeletions(f);for(let e of n)c.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete c.revs[key(e.entity,e.id)];c.cursor=e,await save(),emit({records:u.length,type:`pull`})},push=async e=>{if(o.signal.aborted)return;let t=(await r.records()).filter(isDirty),n=await r.pendingDeletions();if(t.length||n.length){await i.push(t,n,e?{keepalive:!0}:void 0);for(let e of t)c.revs[envelopeKey(e)]=e.record.rev;await r.clearDeletions(n);for(let e of n)delete c.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=u.then(e);return u=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{l.arm(a)},d=globalThis.document,onVisibility=()=>{d.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));d?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide),enqueue(async()=>{o.signal.aborted||(c=cloneState(await r.loadState()??baseline()),await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(o.signal.aborted)throw disposedError();flushSoon()},disposalSignal:o.signal,dispose(){o.signal.aborted||(emit({type:`dispose`}),o.abort(),l.cancel(),d?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),s.clear())},get disposed(){return o.signal.aborted},flush:()=>o.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(o.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{s.delete(e)};return s.add(e),o.signal.addEventListener(`abort`,detach,{once:!0}),t?.signal?.addEventListener(`abort`,detach,{once:!0}),detach},[Symbol.dispose](){this.dispose()}}}exports.TandemDisposedError=TandemDisposedError,exports.TandemError=TandemError,exports.createSync=createSync;
|
|
2
2
|
//# sourceMappingURL=tandem.cjs.map
|
package/dist/tandem.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.cjs","names":["message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","controller","tappers","tapper","event","error","timer","queue","entity","id","envelope","gateway","port","localRevs","entombed","deletion","deleted","deletions","ahead","records","skipped","doomed","localKey","cursor","keepalive","attempt","job","doc","tapOptions","handler"],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"A,mEAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMA,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC,ECdhDC,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE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BAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvDzB,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAOD,EAAW,OAAO,OAC3B,EACA,UAAcA,EAAW,OAAO,QAAU,QAAQ,OAAO,cAAc,CAAC,EAAI,QAAQ,KAAK,EACzF,IAAI,EAAS,EAAwB,CACnC,GAAIA,EAAW,OAAO,SAAW2B,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB1B,EAAQ,OAAO2B,CAAO,CACxB,EAIA,OAHA3B,EAAQ,IAAI2B,CAAO,EACnB5B,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE2B,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"tandem.cjs","names":["timer","_vielzeug_arsenal","message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","controller","tappers","tapper","event","error","flushTimer","queue","entity","id","envelope","gateway","port","localRevs","entombed","deletion","deleted","deletions","ahead","records","skipped","doomed","localKey","cursor","keepalive","attempt","job","doc","tapOptions","handler"],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { timer } from '@vielzeug/arsenal';\nimport { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n const flushTimer = timer(() => void enqueue(pushJob(false)));\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n flushTimer.arm(idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n flushTimer.cancel();\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"A,sGAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAME,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC,ECbhDC,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAG5E,WAAc,IAAiC,CAAE,OAAQC,EAAM,OAAQ,KAAM,CAAE,GAAGA,EAAM,IAAK,CAAE,GAerG,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAASC,EACpBC,EAAYD,EAAQ,aAAeF,EAEnCI,EAAa,IAAI,gBACjBC,EAAU,IAAI,IACd,KAAQ,GAA6B,CACzC,GAAIA,EAAQ,OAAS,EACrB,IAAK,IAAMC,KAAUD,EACnB,GAAI,CACFC,EAAOC,CAAK,CACd,MAAQ,CAER,CAEJ,EACM,KAAQ,GAAyB,CACjCF,EAAQ,OAAS,GACrB,KAAK,CAAE,QAAO,QAASG,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EAAG,KAAM,SAAU,CAAC,CAClG,EAEIP,EAAmB,SAAS,EAC1BQ,GAAA,EAAab,EAAAA,MAAAA,KAAY,KAAK,QAAQ,QAAQ,EAAK,CAAC,CAAC,EACvDc,EAAuB,QAAQ,QAAQ,EAErC,KAAO,EAAgB,IAAuB,GAAGC,EAAO,GAAGC,IAC3D,YAAe,GAA4C,IAAIC,EAAS,OAAQA,EAAS,OAAO,EAAE,EAClG,QAAW,GACfA,EAAS,OAAO,KAAOZ,EAAM,KAAK,YAAYY,CAAQ,IAAM,IACxD,SAA4BC,EAAQ,UAAU,WAAWb,CAAK,CAAC,EAE/D,KAAO,S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Q,WAAY,MAAMU,EAAQ,UAAU,GAAM,SAAS,CAAC,EAC5D,MAAM,MAAM,EACd,CAAC,EAED,IAAM,kBAA2C,IAAI,oBAAoB,qCAAqC,EAE9G,MAAO,CACL,SAAgB,CACd,GAAIV,EAAW,OAAO,QAAS,MAAM,cAAc,EAEnD,UAAU,CACZ,EACA,eAAgBA,EAAW,OAC3B,SAAgB,CACVA,EAAW,OAAO,UACtB,KAAK,CAAE,KAAM,SAAU,CAAC,EACxBA,EAAW,MAAM,EACjBK,EAAW,OAAO,EAClBqB,GAAK,oBAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvDzB,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAOD,EAAW,OAAO,OAC3B,EACA,UAAcA,EAAW,OAAO,QAAU,QAAQ,OAAO,cAAc,CAAC,EAAI,QAAQ,KAAK,EACzF,IAAI,EAAS,EAAwB,CACnC,GAAIA,EAAW,OAAO,SAAW2B,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB1B,EAAQ,OAAO2B,CAAO,CACxB,EAIA,OAHA3B,EAAQ,IAAI2B,CAAO,EACnB5B,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE2B,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF,C"}
|
package/dist/tandem.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.d.ts","sourceRoot":"","sources":["../src/tandem.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"tandem.d.ts","sourceRoot":"","sources":["../src/tandem.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAgB,UAAU,EAAE,WAAW,EAAE,cAAc,EAA0B,MAAM,SAAS,CAAC;AAS7G;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,OAAO,SAAS,cAAc,GAAG,cAAc,EAAE,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,UAAU,CA+JrH"}
|
package/dist/tandem.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Tandem=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},
|
|
1
|
+
var Tandem=(function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var TandemError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},TandemDisposedError=class extends TandemError{},n=3e3,baseline=(e=null)=>({cursor:e,revs:{}}),cloneState=e=>({cursor:e.cursor,revs:{...e.revs}});function createSync(e){let{gateway:r,port:i}=e,a=e.idleDelayMs??n,o=new AbortController,s=new Set,emit=e=>{if(s.size!==0)for(let t of s)try{t(e)}catch{}},warn=e=>{s.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},c=baseline(),l=(0,t.timer)(()=>void enqueue(pushJob(!1))),u=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(c.revs[envelopeKey(e)]??-1),save=()=>r.saveState(cloneState(c)),pull=async()=>{if(o.signal.aborted)return;let{cursor:e,deletions:t,records:n}=await i.pull(c.cursor),a=new Map((await r.records()).map(e=>[envelopeKey(e),e.record.rev])),s=new Set((await r.pendingDeletions()).map(e=>key(e.entity,e.id))),l=new Set(t.map(e=>key(e.entity,e.id))),u=n.filter(e=>!s.has(envelopeKey(e))&&!l.has(envelopeKey(e))&&(a.get(envelopeKey(e))??-1)<e.record.rev),d=await r.applyRecords(u);d.length&&emit({message:`Skipped invalid remote records: ${d.join(`, `)}.`,skipped:d,type:`invalid`});let f=t.filter(e=>{let t=key(e.entity,e.id);return(a.get(t)??-1)<=(c.revs[t]??-1)});await r.applyDeletions(f);for(let e of n)c.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete c.revs[key(e.entity,e.id)];c.cursor=e,await save(),emit({records:u.length,type:`pull`})},push=async e=>{if(o.signal.aborted)return;let t=(await r.records()).filter(isDirty),n=await r.pendingDeletions();if(t.length||n.length){await i.push(t,n,e?{keepalive:!0}:void 0);for(let e of t)c.revs[envelopeKey(e)]=e.record.rev;await r.clearDeletions(n);for(let e of n)delete c.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=u.then(e);return u=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{l.arm(a)},d=globalThis.document,onVisibility=()=>{d.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));d?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide),enqueue(async()=>{o.signal.aborted||(c=cloneState(await r.loadState()??baseline()),await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(o.signal.aborted)throw disposedError();flushSoon()},disposalSignal:o.signal,dispose(){o.signal.aborted||(emit({type:`dispose`}),o.abort(),l.cancel(),d?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),s.clear())},get disposed(){return o.signal.aborted},flush:()=>o.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(o.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{s.delete(e)};return s.add(e),o.signal.addEventListener(`abort`,detach,{once:!0}),t?.signal?.addEventListener(`abort`,detach,{once:!0}),detach},[Symbol.dispose](){this.dispose()}}}return e.TandemDisposedError=TandemDisposedError,e.TandemError=TandemError,e.createSync=createSync,e})({},Arsenal);
|
|
2
2
|
//# sourceMappingURL=tandem.iife.js.map
|
package/dist/tandem.iife.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.iife.js","names":["exports","message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","controller","tappers","tapper","event","error","timer","queue","entity","id","envelope","gateway","port","localRevs","entombed","deletion","deleted","deletions","ahead","records","skipped","doomed","localKey","cursor","keepalive","attempt","job","doc","tapOptions","handler"],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":"A,qFAIA,IAAa,YAAb,cAAiC,KAAM,CACrC,YAAY,EAAiB,EAAqB,CAChD,MAAMC,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,oBAAb,cAAyC,WAAY,CAAC,ECdhDC,EAAwB,IAExB,UAAY,EAAwB,QAAqB,CAAE,SAAQ,KAAM,CAAC,CAAE,GAG5E,WAAc,IAAiC,CAAE,OAAQC,EAAM,OAAQ,KAAM,CAAE,GAAGA,EAAM,IAAK,CAAE,GAerG,SAAgB,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,OAC3B,EACA,UAAcA,EAAW,OAAO,QAAU,QAAQ,OAAO,cAAc,CAAC,EAAI,QAAQ,KAAK,EACzF,IAAI,EAAS,EAAwB,CACnC,GAAIA,EAAW,OAAO,SAAW2B,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB1B,EAAQ,OAAO2B,CAAO,CACxB,EAIA,OAHA3B,EAAQ,IAAI2B,CAAO,EACnB5B,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE2B,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF,C"}
|
|
1
|
+
{"version":3,"file":"tandem.iife.js","names":["timer","exports","message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","controller","tappers","tapper","event","error","flushTimer","_vielzeug_arsenal","queue","entity","id","envelope","gateway","port","localRevs","entombed","deletion","deleted","deletions","ahead","records","skipped","doomed","localKey","cursor","keepalive","attempt","job","doc","tapOptions","handler"],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { timer } from '@vielzeug/arsenal';\nimport { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n const flushTimer = timer(() => void enqueue(pushJob(false)));\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n flushTimer.arm(idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n flushTimer.cancel();\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mapp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C,EAE9G,MAAO,CACL,SAAgB,CACd,GAAIX,EAAW,OAAO,QAAS,MAAM,cAAc,EAEnD,UAAU,CACZ,EACA,eAAgBA,EAAW,OAC3B,SAAgB,CACVA,EAAW,OAAO,UACtB,KAAK,CAAE,KAAM,SAAU,CAAC,EACxBA,EAAW,MAAM,EACjBK,EAAW,OAAO,EAClBsB,GAAK,oBAAoB,mBAAoB,YAAY,EACzD,WAAW,sBAAsB,WAAY,UAAU,EACvD1B,EAAQ,MAAM,EAChB,EACA,IAAI,UAAoB,CACtB,OAAOD,EAAW,OAAO,OAC3B,EACA,UAAcA,EAAW,OAAO,QAAU,QAAQ,OAAO,cAAc,CAAC,EAAI,QAAQ,KAAK,EACzF,IAAI,EAAS,EAAwB,CACnC,GAAIA,EAAW,OAAO,SAAW4B,GAAY,QAAQ,QAAS,UAAa,CAAC,EAC5E,IAAM,WAAqB,CACzB3B,EAAQ,OAAO4B,CAAO,CACxB,EAIA,OAHA5B,EAAQ,IAAI4B,CAAO,EACnB7B,EAAW,OAAO,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAClE4B,GAAY,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,EAC7D,MACT,EACA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF,C"}
|
package/dist/tandem.js
CHANGED
|
@@ -1,29 +1,30 @@
|
|
|
1
|
+
import { timer as e } from "@vielzeug/arsenal";
|
|
1
2
|
// src/errors.ts
|
|
2
3
|
var TandemError = class extends Error {
|
|
3
4
|
constructor(e, t) {
|
|
4
5
|
super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
|
|
5
6
|
}
|
|
6
|
-
}, TandemDisposedError = class extends TandemError {},
|
|
7
|
+
}, TandemDisposedError = class extends TandemError {}, t = 3e3, baseline = (e = null) => ({
|
|
7
8
|
cursor: e,
|
|
8
9
|
revs: {}
|
|
9
10
|
}), cloneState = (e) => ({
|
|
10
11
|
cursor: e.cursor,
|
|
11
12
|
revs: { ...e.revs }
|
|
12
13
|
});
|
|
13
|
-
function createSync(
|
|
14
|
-
let { gateway:
|
|
15
|
-
if (
|
|
14
|
+
function createSync(n) {
|
|
15
|
+
let { gateway: r, port: i } = n, a = n.idleDelayMs ?? t, o = new AbortController(), s = /* @__PURE__ */ new Set(), emit = (e) => {
|
|
16
|
+
if (s.size !== 0) for (let t of s) try {
|
|
16
17
|
t(e);
|
|
17
18
|
} catch {}
|
|
18
19
|
}, warn = (e) => {
|
|
19
|
-
|
|
20
|
+
s.size !== 0 && emit({
|
|
20
21
|
error: e,
|
|
21
22
|
message: e instanceof Error ? e.message : String(e),
|
|
22
23
|
type: "warning"
|
|
23
24
|
});
|
|
24
|
-
},
|
|
25
|
-
if (
|
|
26
|
-
let { cursor: e, deletions: t, records:
|
|
25
|
+
}, c = baseline(), l = e(() => void enqueue(pushJob(!1))), u = Promise.resolve(), key = (e, t) => `${e}:${t}`, envelopeKey = (e) => key(e.entity, e.record.id), isDirty = (e) => e.record.rev > (c.revs[envelopeKey(e)] ?? -1), save = () => r.saveState(cloneState(c)), pull = async () => {
|
|
26
|
+
if (o.signal.aborted) return;
|
|
27
|
+
let { cursor: e, deletions: t, records: n } = await i.pull(c.cursor), a = new Map((await r.records()).map((e) => [envelopeKey(e), e.record.rev])), s = new Set((await r.pendingDeletions()).map((e) => key(e.entity, e.id))), l = new Set(t.map((e) => key(e.entity, e.id))), u = n.filter((e) => !s.has(envelopeKey(e)) && !l.has(envelopeKey(e)) && (a.get(envelopeKey(e)) ?? -1) < e.record.rev), d = await r.applyRecords(u);
|
|
27
28
|
d.length && emit({
|
|
28
29
|
message: `Skipped invalid remote records: ${d.join(", ")}.`,
|
|
29
30
|
skipped: d,
|
|
@@ -31,63 +32,63 @@ function createSync(t) {
|
|
|
31
32
|
});
|
|
32
33
|
let f = t.filter((e) => {
|
|
33
34
|
let t = key(e.entity, e.id);
|
|
34
|
-
return (
|
|
35
|
+
return (a.get(t) ?? -1) <= (c.revs[t] ?? -1);
|
|
35
36
|
});
|
|
36
|
-
await
|
|
37
|
-
for (let e of
|
|
38
|
-
for (let e of f) delete
|
|
39
|
-
|
|
37
|
+
await r.applyDeletions(f);
|
|
38
|
+
for (let e of n) c.revs[envelopeKey(e)] = e.record.rev;
|
|
39
|
+
for (let e of f) delete c.revs[key(e.entity, e.id)];
|
|
40
|
+
c.cursor = e, await save(), emit({
|
|
40
41
|
records: u.length,
|
|
41
42
|
type: "pull"
|
|
42
43
|
});
|
|
43
44
|
}, push = async (e) => {
|
|
44
|
-
if (
|
|
45
|
-
let t = (await
|
|
46
|
-
if (t.length ||
|
|
47
|
-
await
|
|
48
|
-
for (let e of t)
|
|
49
|
-
await
|
|
50
|
-
for (let e of
|
|
45
|
+
if (o.signal.aborted) return;
|
|
46
|
+
let t = (await r.records()).filter(isDirty), n = await r.pendingDeletions();
|
|
47
|
+
if (t.length || n.length) {
|
|
48
|
+
await i.push(t, n, e ? { keepalive: !0 } : void 0);
|
|
49
|
+
for (let e of t) c.revs[envelopeKey(e)] = e.record.rev;
|
|
50
|
+
await r.clearDeletions(n);
|
|
51
|
+
for (let e of n) delete c.revs[key(e.entity, e.id)];
|
|
51
52
|
await save(), emit({
|
|
52
53
|
records: t.length,
|
|
53
54
|
type: "push"
|
|
54
55
|
});
|
|
55
56
|
}
|
|
56
57
|
}, enqueue = (e) => {
|
|
57
|
-
let t =
|
|
58
|
-
return
|
|
58
|
+
let t = u.then(e);
|
|
59
|
+
return u = t.catch(warn), t;
|
|
59
60
|
}, pushJob = (e) => () => push(e).catch(async (e) => {
|
|
60
61
|
throw await pull().catch(() => {}), e;
|
|
61
62
|
}), cycle = async () => {
|
|
62
63
|
await pull(), await pushJob(!1)();
|
|
63
64
|
}, flushSoon = () => {
|
|
64
|
-
|
|
65
|
-
},
|
|
66
|
-
|
|
65
|
+
l.arm(a);
|
|
66
|
+
}, d = globalThis.document, onVisibility = () => {
|
|
67
|
+
d.visibilityState === "hidden" ? enqueue(pushJob(!0)) : enqueue(cycle);
|
|
67
68
|
}, onPageHide = () => void enqueue(pushJob(!0));
|
|
68
|
-
|
|
69
|
-
|
|
69
|
+
d?.addEventListener("visibilitychange", onVisibility), globalThis.addEventListener?.("pagehide", onPageHide), enqueue(async () => {
|
|
70
|
+
o.signal.aborted || (c = cloneState(await r.loadState() ?? baseline()), await cycle());
|
|
70
71
|
});
|
|
71
72
|
let disposedError = () => new TandemDisposedError("This sync handle has been disposed.");
|
|
72
73
|
return {
|
|
73
74
|
changed() {
|
|
74
|
-
if (
|
|
75
|
+
if (o.signal.aborted) throw disposedError();
|
|
75
76
|
flushSoon();
|
|
76
77
|
},
|
|
77
|
-
disposalSignal:
|
|
78
|
+
disposalSignal: o.signal,
|
|
78
79
|
dispose() {
|
|
79
|
-
|
|
80
|
+
o.signal.aborted || (emit({ type: "dispose" }), o.abort(), l.cancel(), d?.removeEventListener("visibilitychange", onVisibility), globalThis.removeEventListener?.("pagehide", onPageHide), s.clear());
|
|
80
81
|
},
|
|
81
82
|
get disposed() {
|
|
82
|
-
return
|
|
83
|
+
return o.signal.aborted;
|
|
83
84
|
},
|
|
84
|
-
flush: () =>
|
|
85
|
+
flush: () => o.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle),
|
|
85
86
|
tap(e, t) {
|
|
86
|
-
if (
|
|
87
|
+
if (o.signal.aborted || t?.signal?.aborted) return () => {};
|
|
87
88
|
let detach = () => {
|
|
88
|
-
|
|
89
|
+
s.delete(e);
|
|
89
90
|
};
|
|
90
|
-
return
|
|
91
|
+
return s.add(e), o.signal.addEventListener("abort", detach, { once: !0 }), t?.signal?.addEventListener("abort", detach, { once: !0 }), detach;
|
|
91
92
|
},
|
|
92
93
|
[Symbol.dispose]() {
|
|
93
94
|
this.dispose();
|
package/dist/tandem.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tandem.js","names":["message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","controller","tappers","tapper","event","error","timer","queue","entity","id","envelope","gateway","port","localRevs","entombed","deletion","deleted","deletions","ahead","records","skipped","doomed","localKey","cursor","keepalive","attempt","job","doc","tapOptions","handler"],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n let timer: ReturnType<typeof setTimeout> | null = null;\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void enqueue(pushJob(false)), idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n if (timer) clearTimeout(timer);\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":";AAIA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAOa,sBAAb,cAAyC,YAAY,CAAC,GCdhDC,IAAwB,KAExB,YAAY,IAAwB,UAAqB;CAAE;CAAQ,MAAM,CAAC;AAAE,IAG5E,cAAc,OAAiC;CAAE,QAAQC,EAAM;CAAQ,MAAM,EAAE,GAAGA,EAAM,KAAK;AAAE;AAerG,SAAgB,WAA4D,GAA2C;CACrH,IAAM,EAAE,YAAS,YAASC,GACpBC,IAAYD,EAAQ,eAAeF,GAEnCI,IAAa,IAAI,gBAAgB,GACjCC,oBAAU,IAAI,IAAkC,GAChD,QAAQ,MAA6B;EACzC,IAAIA,EAAQ,SAAS,GACrB,KAAK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;GACnC,IAAIA,EAAW,OAAO,WAAW2B,GAAY,QAAQ,SAAS,aAAa,CAAC;GAC5E,IAAM,eAAqB;IACzB,EAAQ,OAAOC,CAAO;GACxB;GAIA,OAHA3B,EAAQ,IAAI2B,CAAO,GACnB5B,EAAW,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,GAAK,CAAC,GAClE2B,GAAY,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,GAAK,CAAC,GAC7D;EACT;EACA,CAAC,OAAO,WAAiB;GACvB,KAAK,QAAQ;EACf;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"tandem.js","names":["message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","controller","tappers","tapper","event","error","flushTimer","timer","queue","entity","id","envelope","gateway","port","localRevs","entombed","deletion","deleted","deletions","ahead","records","skipped","doomed","localKey","cursor","keepalive","attempt","job","doc","tapOptions","handler"],"sources":["../src/errors.ts","../src/tandem.ts"],"sourcesContent":["/**\n * Base class for all tandem errors.\n * Use `instanceof TandemError` to catch any tandem-originated error in one branch.\n */\nexport class TandemError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a disposed sync handle is used again. A scheduler that stops\n * silently is a sync engine's worst failure: the device keeps editing while\n * nothing uploads, and the divergence looks like working software.\n */\nexport class TandemDisposedError extends TandemError {}\n","import { timer } from '@vielzeug/arsenal';\nimport { TandemDisposedError } from './errors';\nimport type { SyncEnvelope, SyncHandle, SyncOptions, SyncRecordBase, SyncState, TandemEvent } from './types';\n\nconst DEFAULT_IDLE_DELAY_MS = 3000;\n\nconst baseline = (cursor: string | null = null): SyncState => ({ cursor, revs: {} });\n\n/** Copies persisted state so the engine never aliases the object its gateway handed it. */\nconst cloneState = (state: SyncState): SyncState => ({ cursor: state.cursor, revs: { ...state.revs } });\n\n/**\n * Drives a {@link SyncPort} against a {@link SyncGateway}. The engine never sees\n * individual commands or record shapes: it reads the device's records, and after a\n * quiet period pushes every record whose `rev` is above the last-synced baseline: a\n * burst of edits becomes one batched upload instead of one per edit. Every rev\n * comparison is the engine's: the gateway upserts what it is given and tombstones\n * what it deletes. Flushes serialize (one push in flight), fire immediately when\n * the tab hides or closes, and the tab runs a full cycle on return to the\n * foreground. A rejected push triggers a pull to reconcile.\n *\n * Runs in the browser (the visibility/pagehide hooks are no-ops without a document)\n * and in any storage-backed runtime the gateway can reach.\n */\nexport function createSync<TRecord extends SyncRecordBase = SyncRecordBase>(options: SyncOptions<TRecord>): SyncHandle {\n const { gateway, port } = options;\n const idleDelay = options.idleDelayMs ?? DEFAULT_IDLE_DELAY_MS;\n\n const controller = new AbortController();\n const tappers = new Set<(event: TandemEvent) => void>();\n const emit = (event: TandemEvent): void => {\n if (tappers.size === 0) return;\n for (const tapper of tappers) {\n try {\n tapper(event);\n } catch {\n // Observability must not affect sync behavior.\n }\n }\n };\n const warn = (error: unknown): void => {\n if (tappers.size === 0) return;\n emit({ error, message: error instanceof Error ? error.message : String(error), type: 'warning' });\n };\n\n let state: SyncState = baseline();\n const flushTimer = timer(() => void enqueue(pushJob(false)));\n let queue: Promise<void> = Promise.resolve();\n\n const key = (entity: string, id: string): string => `${entity}:${id}`;\n const envelopeKey = (envelope: SyncEnvelope<TRecord>): string => key(envelope.entity, envelope.record.id);\n const isDirty = (envelope: SyncEnvelope<TRecord>): boolean =>\n envelope.record.rev > (state.revs[envelopeKey(envelope)] ?? -1);\n const save = (): Promise<void> => gateway.saveState(cloneState(state));\n\n const pull = async (): Promise<void> => {\n if (controller.signal.aborted) return;\n const { cursor, deletions, records } = await port.pull(state.cursor);\n // One read of the device's records answers every rev question this pull raises.\n const localRevs = new Map(\n (await gateway.records()).map((envelope) => [envelopeKey(envelope), envelope.record.rev] as const),\n );\n const entombed = new Set((await gateway.pendingDeletions()).map((deletion) => key(deletion.entity, deletion.id)));\n const deleted = new Set(deletions.map((deletion) => key(deletion.entity, deletion.id)));\n // Apply only records the server is ahead on: a locally tombstoned id or an id\n // deleted in this same pull never resurrects through the apply.\n const ahead = records.filter(\n (envelope) =>\n !entombed.has(envelopeKey(envelope)) &&\n !deleted.has(envelopeKey(envelope)) &&\n (localRevs.get(envelopeKey(envelope)) ?? -1) < envelope.record.rev,\n );\n const skipped = await gateway.applyRecords(ahead);\n if (skipped.length) {\n emit({ message: `Skipped invalid remote records: ${skipped.join(', ')}.`, skipped, type: 'invalid' });\n }\n // A deletion loses to local changes that have not made it to the server yet.\n const doomed = deletions.filter((deletion) => {\n const localKey = key(deletion.entity, deletion.id);\n\n return (localRevs.get(localKey) ?? -1) <= (state.revs[localKey] ?? -1);\n });\n await gateway.applyDeletions(doomed);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // A record this pull removed locally has no baseline left to keep: pruning\n // keeps `revs` bounded to records that still exist.\n for (const deletion of doomed) delete state.revs[key(deletion.entity, deletion.id)];\n state.cursor = cursor;\n await save();\n emit({ records: ahead.length, type: 'pull' });\n };\n\n const push = async (keepalive: boolean): Promise<void> => {\n if (controller.signal.aborted) return;\n const records = (await gateway.records()).filter(isDirty);\n const deletions = await gateway.pendingDeletions();\n if (!records.length && !deletions.length) return;\n await port.push(records, deletions, keepalive ? { keepalive: true } : undefined);\n for (const envelope of records) state.revs[envelopeKey(envelope)] = envelope.record.rev;\n // Only the tombstones this push carried: new ones may have landed mid-flight.\n await gateway.clearDeletions(deletions);\n for (const deletion of deletions) delete state.revs[key(deletion.entity, deletion.id)];\n await save();\n emit({ records: records.length, type: 'push' });\n };\n\n // Jobs serialize through one queue. A failure warns through tap and the queue\n // survives; enqueue returns the raw outcome so flush() can reject.\n const enqueue = (job: () => Promise<void>): Promise<void> => {\n const attempt = queue.then(job);\n queue = attempt.catch(warn);\n return attempt;\n };\n const pushJob = (keepalive: boolean) => (): Promise<void> =>\n push(keepalive).catch(async (error: unknown) => {\n // A rejected push usually means the server moved on: pull to reconcile,\n // then surface the failure to whoever is waiting on this job.\n await pull().catch(() => {});\n throw error;\n });\n // A full cycle: absorb remote changes first, then push the merged dirty set.\n const cycle = async (): Promise<void> => {\n await pull();\n await pushJob(false)();\n };\n\n const flushSoon = (): void => {\n flushTimer.arm(idleDelay);\n };\n\n const doc = globalThis.document;\n const onVisibility = (): void => {\n if (doc.visibilityState === 'hidden') void enqueue(pushJob(true));\n else void enqueue(cycle);\n };\n const onPageHide = (): void => void enqueue(pushJob(true));\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n\n // Boot: load the persisted baseline, run one full cycle: pull remote changes,\n // then push anything created or changed while offline. Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n await cycle();\n });\n\n const disposedError = (): TandemDisposedError => new TandemDisposedError('This sync handle has been disposed.');\n\n return {\n changed(): void {\n if (controller.signal.aborted) throw disposedError();\n\n flushSoon();\n },\n disposalSignal: controller.signal,\n dispose(): void {\n if (controller.signal.aborted) return;\n emit({ type: 'dispose' });\n controller.abort();\n flushTimer.cancel();\n doc?.removeEventListener('visibilitychange', onVisibility);\n globalThis.removeEventListener?.('pagehide', onPageHide);\n tappers.clear();\n },\n get disposed(): boolean {\n return controller.signal.aborted;\n },\n flush: () => (controller.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle)),\n tap(handler, tapOptions): () => void {\n if (controller.signal.aborted || tapOptions?.signal?.aborted) return () => {};\n const detach = (): void => {\n tappers.delete(handler);\n };\n tappers.add(handler);\n controller.signal.addEventListener('abort', detach, { once: true });\n tapOptions?.signal?.addEventListener('abort', detach, { once: true });\n return detach;\n },\n [Symbol.dispose](): void {\n this.dispose();\n },\n };\n}\n"],"mappings":";;AAIA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAA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EACZ;EACA,gBAAgBA,EAAW;EAC3B,UAAgB;GACd,AAAIA,EAAW,OAAO,YACtB,KAAK,EAAE,MAAM,UAAU,CAAC,GACxBA,EAAW,MAAM,GACjBK,EAAW,OAAO,GAClBsB,GAAK,oBAAoB,oBAAoB,YAAY,GACzD,WAAW,sBAAsB,YAAY,UAAU,GACvD1B,EAAQ,MAAM;EAChB;EACA,IAAI,WAAoB;GACtB,OAAOD,EAAW,OAAO;EAC3B;EACA,aAAcA,EAAW,OAAO,UAAU,QAAQ,OAAO,cAAc,CAAC,IAAI,QAAQ,KAAK;EACzF,IAAI,GAAS,GAAwB;GACnC,IAAIA,EAAW,OAAO,WAAW4B,GAAY,QAAQ,SAAS,aAAa,CAAC;GAC5E,IAAM,eAAqB;IACzB,EAAQ,OAAOC,CAAO;GACxB;GAIA,OAHA5B,EAAQ,IAAI4B,CAAO,GACnB7B,EAAW,OAAO,iBAAiB,SAAS,QAAQ,EAAE,MAAM,GAAK,CAAC,GAClE4B,GAAY,QAAQ,iBAAiB,SAAS,QAAQ,EAAE,MAAM,GAAK,CAAC,GAC7D;EACT;EACA,CAAC,OAAO,WAAiB;GACvB,KAAK,QAAQ;EACf;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/tandem",
|
|
3
|
-
"version": "26.11.
|
|
3
|
+
"version": "26.11.13",
|
|
4
4
|
"description": "Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -39,6 +39,9 @@
|
|
|
39
39
|
"prepublishOnly": "bun run --silent build",
|
|
40
40
|
"test": "vitest"
|
|
41
41
|
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"@vielzeug/arsenal": "26.11.13"
|
|
44
|
+
},
|
|
42
45
|
"devDependencies": {
|
|
43
46
|
"@types/node": "^26.6.6",
|
|
44
47
|
"typescript": "^6.0.3",
|