@vielzeug/tandem 26.11.16 → 26.11.17
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 +5 -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 +29 -29
- package/dist/tandem.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/tandem.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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,
|
|
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=n.autoStart??!0,s=n.ambient??!0,c=new AbortController,l=new Set,emit=e=>{if(l.size!==0)for(let t of l)try{t(e)}catch{}},warn=e=>{l.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},u=baseline(),d=(0,e.timer)(()=>void enqueue(pushJob(!1))),f=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(u.revs[envelopeKey(e)]??-1),save=()=>r.saveState(cloneState(u)),pull=async()=>{if(c.signal.aborted)return;let{cursor:e,deletions:t,records:n}=await i.pull(u.cursor),a=new Map((await r.records()).map(e=>[envelopeKey(e),e.record.rev])),o=new Set((await r.pendingDeletions()).map(e=>key(e.entity,e.id))),s=new Set(t.map(e=>key(e.entity,e.id))),l=n.filter(e=>!o.has(envelopeKey(e))&&!s.has(envelopeKey(e))&&(a.get(envelopeKey(e))??-1)<e.record.rev),d=await r.applyRecords(l);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)<=(u.revs[t]??-1)});await r.applyDeletions(f);for(let e of n)u.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete u.revs[key(e.entity,e.id)];u.cursor=e,await save(),emit({records:l.length,type:`pull`})},push=async e=>{if(c.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)u.revs[envelopeKey(e)]=e.record.rev;await r.clearDeletions(n);for(let e of n)delete u.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=f.then(e);return f=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{d.arm(a)},p=globalThis.document,onVisibility=()=>{p.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));s&&(p?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide)),enqueue(async()=>{c.signal.aborted||(u=cloneState(await r.loadState()??baseline()),o&&await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(c.signal.aborted)throw disposedError();flushSoon()},disposalSignal:c.signal,dispose(){c.signal.aborted||(emit({type:`dispose`}),c.abort(),d.cancel(),p?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),l.clear())},get disposed(){return c.signal.aborted},flush:()=>c.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(c.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{l.delete(e)};return l.add(e),c.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":["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();\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I,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"}
|
|
1
|
+
{"version":3,"file":"tandem.cjs","names":["timer","_vielzeug_arsenal","message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","autoStart","ambient","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. `ambient: false` drops\n * the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to the\n * first {@link SyncHandle.flush}: together they turn the scheduler into a\n * pull-when-told engine for short-lived connections that cannot survive an\n * ambient flush.\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 const autoStart = options.autoStart ?? true;\n const ambient = options.ambient ?? true;\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 if (ambient) {\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n }\n\n // Boot: load the persisted baseline, then (unless `autoStart` is off) run one full\n // cycle: pull remote changes, push anything created or changed while offline.\n // Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n if (autoStart) 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,GAmBrG,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAASC,EACpBC,EAAYD,EAAQ,aAAeF,EACnCI,EAAYF,EAAQ,WAAa,GACjCG,EAAUH,EAAQ,SAAW,GAE7BI,EAAa,IAAI,gBACjBC,EAAU,IAAI,IACd,KAAQ,GAA6B,CACzC,GAAIA,EAAQ,OAAS,EACrB,IAAK,IAAMC,KAAUD,EACnB,GAAI,CACFC,EAAOC,CAAK,CAC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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
CHANGED
|
@@ -7,7 +7,11 @@ import type { SyncHandle, SyncOptions, SyncRecordBase } from './types';
|
|
|
7
7
|
* comparison is the engine's: the gateway upserts what it is given and tombstones
|
|
8
8
|
* what it deletes. Flushes serialize (one push in flight), fire immediately when
|
|
9
9
|
* the tab hides or closes, and the tab runs a full cycle on return to the
|
|
10
|
-
* foreground. A rejected push triggers a pull to reconcile.
|
|
10
|
+
* foreground. A rejected push triggers a pull to reconcile. `ambient: false` drops
|
|
11
|
+
* the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to the
|
|
12
|
+
* first {@link SyncHandle.flush}: together they turn the scheduler into a
|
|
13
|
+
* pull-when-told engine for short-lived connections that cannot survive an
|
|
14
|
+
* ambient flush.
|
|
11
15
|
*
|
|
12
16
|
* Runs in the browser (the visibility/pagehide hooks are no-ops without a document)
|
|
13
17
|
* and in any storage-backed runtime the gateway can reach.
|
package/dist/tandem.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CAAC,OAAO,SAAS,cAAc,GAAG,cAAc,EAAE,OAAO,EAAE,WAAW,CAAC,OAAO,CAAC,GAAG,UAAU,CAoKrH"}
|
package/dist/tandem.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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,
|
|
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=e.autoStart??!0,s=e.ambient??!0,c=new AbortController,l=new Set,emit=e=>{if(l.size!==0)for(let t of l)try{t(e)}catch{}},warn=e=>{l.size!==0&&emit({error:e,message:e instanceof Error?e.message:String(e),type:`warning`})},u=baseline(),d=(0,t.timer)(()=>void enqueue(pushJob(!1))),f=Promise.resolve(),key=(e,t)=>`${e}:${t}`,envelopeKey=e=>key(e.entity,e.record.id),isDirty=e=>e.record.rev>(u.revs[envelopeKey(e)]??-1),save=()=>r.saveState(cloneState(u)),pull=async()=>{if(c.signal.aborted)return;let{cursor:e,deletions:t,records:n}=await i.pull(u.cursor),a=new Map((await r.records()).map(e=>[envelopeKey(e),e.record.rev])),o=new Set((await r.pendingDeletions()).map(e=>key(e.entity,e.id))),s=new Set(t.map(e=>key(e.entity,e.id))),l=n.filter(e=>!o.has(envelopeKey(e))&&!s.has(envelopeKey(e))&&(a.get(envelopeKey(e))??-1)<e.record.rev),d=await r.applyRecords(l);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)<=(u.revs[t]??-1)});await r.applyDeletions(f);for(let e of n)u.revs[envelopeKey(e)]=e.record.rev;for(let e of f)delete u.revs[key(e.entity,e.id)];u.cursor=e,await save(),emit({records:l.length,type:`pull`})},push=async e=>{if(c.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)u.revs[envelopeKey(e)]=e.record.rev;await r.clearDeletions(n);for(let e of n)delete u.revs[key(e.entity,e.id)];await save(),emit({records:t.length,type:`push`})}},enqueue=e=>{let t=f.then(e);return f=t.catch(warn),t},pushJob=e=>()=>push(e).catch(async e=>{throw await pull().catch(()=>{}),e}),cycle=async()=>{await pull(),await pushJob(!1)()},flushSoon=()=>{d.arm(a)},p=globalThis.document,onVisibility=()=>{p.visibilityState===`hidden`?enqueue(pushJob(!0)):enqueue(cycle)},onPageHide=()=>void enqueue(pushJob(!0));s&&(p?.addEventListener(`visibilitychange`,onVisibility),globalThis.addEventListener?.(`pagehide`,onPageHide)),enqueue(async()=>{c.signal.aborted||(u=cloneState(await r.loadState()??baseline()),o&&await cycle())});let disposedError=()=>new TandemDisposedError(`This sync handle has been disposed.`);return{changed(){if(c.signal.aborted)throw disposedError();flushSoon()},disposalSignal:c.signal,dispose(){c.signal.aborted||(emit({type:`dispose`}),c.abort(),d.cancel(),p?.removeEventListener(`visibilitychange`,onVisibility),globalThis.removeEventListener?.(`pagehide`,onPageHide),l.clear())},get disposed(){return c.signal.aborted},flush:()=>c.signal.aborted?Promise.reject(disposedError()):enqueue(cycle),tap(e,t){if(c.signal.aborted||t?.signal?.aborted)return()=>{};let detach=()=>{l.delete(e)};return l.add(e),c.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":["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"],"mappings":"A,uFAIA,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,I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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"}
|
|
1
|
+
{"version":3,"file":"tandem.iife.js","names":["timer","exports","message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","autoStart","ambient","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. `ambient: false` drops\n * the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to the\n * first {@link SyncHandle.flush}: together they turn the scheduler into a\n * pull-when-told engine for short-lived connections that cannot survive an\n * ambient flush.\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 const autoStart = options.autoStart ?? true;\n const ambient = options.ambient ?? true;\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 if (ambient) {\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n }\n\n // Boot: load the persisted baseline, then (unless `autoStart` is off) run one full\n // cycle: pull remote changes, push anything created or changed while offline.\n // Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n if (autoStart) 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,uFAIA,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,GAmBrG,SAAgB,WAA4D,EAA2C,CACrH,GAAM,CAAE,UAAS,QAASC,EACpBC,EAAYD,EAAQ,aAAeF,EACnCI,EAAYF,EAAQ,WAAa,GACjCG,EAAUH,EAAQ,SAAW,GAE7BI,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,EAEIT,EAAmB,SAAS,EAC1BU,GAAA,EAAaf,EAAAA,MAAAA,KAA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UAAiB,CACvB,KAAK,QAAQ,CACf,CACF,CACF,C"}
|
package/dist/tandem.js
CHANGED
|
@@ -12,19 +12,19 @@ var TandemError = class extends Error {
|
|
|
12
12
|
revs: { ...e.revs }
|
|
13
13
|
});
|
|
14
14
|
function createSync(n) {
|
|
15
|
-
let { gateway: r, port: i } = n, a = n.idleDelayMs ?? t, o = new AbortController(),
|
|
16
|
-
if (
|
|
15
|
+
let { gateway: r, port: i } = n, a = n.idleDelayMs ?? t, o = n.autoStart ?? !0, s = n.ambient ?? !0, c = new AbortController(), l = /* @__PURE__ */ new Set(), emit = (e) => {
|
|
16
|
+
if (l.size !== 0) for (let t of l) try {
|
|
17
17
|
t(e);
|
|
18
18
|
} catch {}
|
|
19
19
|
}, warn = (e) => {
|
|
20
|
-
|
|
20
|
+
l.size !== 0 && emit({
|
|
21
21
|
error: e,
|
|
22
22
|
message: e instanceof Error ? e.message : String(e),
|
|
23
23
|
type: "warning"
|
|
24
24
|
});
|
|
25
|
-
},
|
|
26
|
-
if (
|
|
27
|
-
let { cursor: e, deletions: t, records: n } = await i.pull(
|
|
25
|
+
}, u = baseline(), d = e(() => void enqueue(pushJob(!1))), f = Promise.resolve(), key = (e, t) => `${e}:${t}`, envelopeKey = (e) => key(e.entity, e.record.id), isDirty = (e) => e.record.rev > (u.revs[envelopeKey(e)] ?? -1), save = () => r.saveState(cloneState(u)), pull = async () => {
|
|
26
|
+
if (c.signal.aborted) return;
|
|
27
|
+
let { cursor: e, deletions: t, records: n } = await i.pull(u.cursor), a = new Map((await r.records()).map((e) => [envelopeKey(e), e.record.rev])), o = new Set((await r.pendingDeletions()).map((e) => key(e.entity, e.id))), s = new Set(t.map((e) => key(e.entity, e.id))), l = n.filter((e) => !o.has(envelopeKey(e)) && !s.has(envelopeKey(e)) && (a.get(envelopeKey(e)) ?? -1) < e.record.rev), d = await r.applyRecords(l);
|
|
28
28
|
d.length && emit({
|
|
29
29
|
message: `Skipped invalid remote records: ${d.join(", ")}.`,
|
|
30
30
|
skipped: d,
|
|
@@ -32,63 +32,63 @@ function createSync(n) {
|
|
|
32
32
|
});
|
|
33
33
|
let f = t.filter((e) => {
|
|
34
34
|
let t = key(e.entity, e.id);
|
|
35
|
-
return (a.get(t) ?? -1) <= (
|
|
35
|
+
return (a.get(t) ?? -1) <= (u.revs[t] ?? -1);
|
|
36
36
|
});
|
|
37
37
|
await r.applyDeletions(f);
|
|
38
|
-
for (let e of n)
|
|
39
|
-
for (let e of f) delete
|
|
40
|
-
|
|
41
|
-
records:
|
|
38
|
+
for (let e of n) u.revs[envelopeKey(e)] = e.record.rev;
|
|
39
|
+
for (let e of f) delete u.revs[key(e.entity, e.id)];
|
|
40
|
+
u.cursor = e, await save(), emit({
|
|
41
|
+
records: l.length,
|
|
42
42
|
type: "pull"
|
|
43
43
|
});
|
|
44
44
|
}, push = async (e) => {
|
|
45
|
-
if (
|
|
45
|
+
if (c.signal.aborted) return;
|
|
46
46
|
let t = (await r.records()).filter(isDirty), n = await r.pendingDeletions();
|
|
47
47
|
if (t.length || n.length) {
|
|
48
48
|
await i.push(t, n, e ? { keepalive: !0 } : void 0);
|
|
49
|
-
for (let e of t)
|
|
49
|
+
for (let e of t) u.revs[envelopeKey(e)] = e.record.rev;
|
|
50
50
|
await r.clearDeletions(n);
|
|
51
|
-
for (let e of n) delete
|
|
51
|
+
for (let e of n) delete u.revs[key(e.entity, e.id)];
|
|
52
52
|
await save(), emit({
|
|
53
53
|
records: t.length,
|
|
54
54
|
type: "push"
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
57
|
}, enqueue = (e) => {
|
|
58
|
-
let t =
|
|
59
|
-
return
|
|
58
|
+
let t = f.then(e);
|
|
59
|
+
return f = t.catch(warn), t;
|
|
60
60
|
}, pushJob = (e) => () => push(e).catch(async (e) => {
|
|
61
61
|
throw await pull().catch(() => {}), e;
|
|
62
62
|
}), cycle = async () => {
|
|
63
63
|
await pull(), await pushJob(!1)();
|
|
64
64
|
}, flushSoon = () => {
|
|
65
|
-
|
|
66
|
-
},
|
|
67
|
-
|
|
65
|
+
d.arm(a);
|
|
66
|
+
}, p = globalThis.document, onVisibility = () => {
|
|
67
|
+
p.visibilityState === "hidden" ? enqueue(pushJob(!0)) : enqueue(cycle);
|
|
68
68
|
}, onPageHide = () => void enqueue(pushJob(!0));
|
|
69
|
-
|
|
70
|
-
|
|
69
|
+
s && (p?.addEventListener("visibilitychange", onVisibility), globalThis.addEventListener?.("pagehide", onPageHide)), enqueue(async () => {
|
|
70
|
+
c.signal.aborted || (u = cloneState(await r.loadState() ?? baseline()), o && await cycle());
|
|
71
71
|
});
|
|
72
72
|
let disposedError = () => new TandemDisposedError("This sync handle has been disposed.");
|
|
73
73
|
return {
|
|
74
74
|
changed() {
|
|
75
|
-
if (
|
|
75
|
+
if (c.signal.aborted) throw disposedError();
|
|
76
76
|
flushSoon();
|
|
77
77
|
},
|
|
78
|
-
disposalSignal:
|
|
78
|
+
disposalSignal: c.signal,
|
|
79
79
|
dispose() {
|
|
80
|
-
|
|
80
|
+
c.signal.aborted || (emit({ type: "dispose" }), c.abort(), d.cancel(), p?.removeEventListener("visibilitychange", onVisibility), globalThis.removeEventListener?.("pagehide", onPageHide), l.clear());
|
|
81
81
|
},
|
|
82
82
|
get disposed() {
|
|
83
|
-
return
|
|
83
|
+
return c.signal.aborted;
|
|
84
84
|
},
|
|
85
|
-
flush: () =>
|
|
85
|
+
flush: () => c.signal.aborted ? Promise.reject(disposedError()) : enqueue(cycle),
|
|
86
86
|
tap(e, t) {
|
|
87
|
-
if (
|
|
87
|
+
if (c.signal.aborted || t?.signal?.aborted) return () => {};
|
|
88
88
|
let detach = () => {
|
|
89
|
-
|
|
89
|
+
l.delete(e);
|
|
90
90
|
};
|
|
91
|
-
return
|
|
91
|
+
return l.add(e), c.signal.addEventListener("abort", detach, { once: !0 }), t?.signal?.addEventListener("abort", detach, { once: !0 }), detach;
|
|
92
92
|
},
|
|
93
93
|
[Symbol.dispose]() {
|
|
94
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","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,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAOa,sBAAb,cAAyC,YAAY,CAAC,GCbhDC,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,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,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"}
|
|
1
|
+
{"version":3,"file":"tandem.js","names":["message","opts","DEFAULT_IDLE_DELAY_MS","state","options","idleDelay","autoStart","ambient","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. `ambient: false` drops\n * the tab-lifecycle hooks, and `autoStart: false` defers the opening cycle to the\n * first {@link SyncHandle.flush}: together they turn the scheduler into a\n * pull-when-told engine for short-lived connections that cannot survive an\n * ambient flush.\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 const autoStart = options.autoStart ?? true;\n const ambient = options.ambient ?? true;\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 if (ambient) {\n doc?.addEventListener('visibilitychange', onVisibility);\n globalThis.addEventListener?.('pagehide', onPageHide);\n }\n\n // Boot: load the persisted baseline, then (unless `autoStart` is off) run one full\n // cycle: pull remote changes, push anything created or changed while offline.\n // Later flushes chain onto it.\n void enqueue(async () => {\n if (controller.signal.aborted) return;\n state = cloneState((await gateway.loadState()) ?? baseline());\n if (autoStart) 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,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAOa,sBAAb,cAAyC,YAAY,CAAC,GCbhDC,IAAwB,KAExB,YAAY,IAAwB,UAAqB;CAAE;CAAQ,MAAM,CAAC;AAAE,IAG5E,cAAc,OAAiC;CAAE,QAAQC,EAAM;CAAQ,MAAM,EAAE,GAAGA,EAAM,KAAK;AAAE;AAmBrG,SAAgB,WAA4D,GAA2C;CACrH,IAAM,EAAE,YAAS,YAASC,GACpBC,IAAYD,EAAQ,eAAeF,GACnCI,IAAYF,EAAQ,aAAa,IACjCG,IAAUH,EAAQ,WAAW,IAE7BI,IAAa,IAAI,gBAAgB,GACjCC,oBAAU,IAAI,IAAkC,GAChD,QAAQ,MAA6B;EACzC,IAAIA,EAAQ,SAAS,GACrB,KAAK,IAAMC,KAAUD,GACnB,IAAI;GACF,EAAOE,CAAK;EACd,QAAQ,CAER;CAEJ,GACM,QAAQ,MAAyB;EACrC,AAAIF,EAAQ,SAAS,KACrB,KAAK;GAAE;GAAO,SAASG,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;GAAG,MAAM;EAAU,CAAC;CAClG,GAEIT,IAAmB,SAAS,GAC1BU,IAAaC,QAAY,KAAK,QAAQ,QAAQ,EAAK,CAAC,CAAC,GACvDC,IAAuB,QAAQ,QAAQ,GAErC,OAAO,GAAgB,MAAuB,GAAGC,EAAO,GAAGC,KAC3D,eAAe,MAA4C,IAAIC,EAAS,QAAQA,EAAS,OAAO,EAAE,GAClG,WAAW,MACfA,EAAS,OAA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|
export interface SyncOptions<TRecord extends SyncRecordBase = SyncRecordBase> {
|
|
106
|
+
/** Keep the tab's lifecycle wired to sync (default `true`): a keepalive push
|
|
107
|
+
* when the tab hides or closes, and a full cycle when it returns to the
|
|
108
|
+
* foreground. Set it to `false` for syncs over a connection that dies with
|
|
109
|
+
* the tab — an ephemeral peer-to-peer link, say — where those ambient flushes
|
|
110
|
+
* would fire into a dead or already-closed port. */
|
|
111
|
+
ambient?: boolean;
|
|
112
|
+
/** Run a full sync cycle when the handle is created (default `true`). Set it to
|
|
113
|
+
* `false` for short-lived syncs whose data flow must start on the app's cue:
|
|
114
|
+
* the boot job still loads the persisted baseline, and {@link SyncHandle.flush}
|
|
115
|
+
* runs the first cycle. */
|
|
116
|
+
autoStart?: boolean;
|
|
106
117
|
/** The device's storage. */
|
|
107
118
|
gateway: SyncGateway<TRecord>;
|
|
108
119
|
/** Quiet period after the last change before a flush, in ms (default 3000). */
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,wFAAwF;AACxF,MAAM,WAAW,cAAc;IAC7B,iDAAiD;IACjD,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,+FAA+F;IAC/F,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED,qEAAqE;AACrE,MAAM,WAAW,YAAY,CAAC,OAAO,SAAS,cAAc,GAAG,cAAc;IAC3E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAED,2FAA2F;AAC3F,MAAM,WAAW,YAAY;IAC3B;;oEAEgE;IAChE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,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AE,MAAM,CAAC;IACrB,kBAAkB;IAClB,IAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;CACzB;AAED,iEAAiE;AACjE,MAAM,WAAW,UAAU;IACzB;;;2DAGuD;IACvD,OAAO,IAAI,IAAI,CAAC;IAChB,2CAA2C;IAC3C,QAAQ,CAAC,cAAc,EAAE,WAAW,CAAC;IACrC;oFACgF;IAChF,OAAO,IAAI,IAAI,CAAC;IAChB,yCAAyC;IACzC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B;;;iCAG6B;IAC7B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB;gFAC4E;IAC5E,GAAG,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,EAAE,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,MAAM,IAAI,CAAC;IACpG,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC;CAC1B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/tandem",
|
|
3
|
-
"version": "26.11.
|
|
3
|
+
"version": "26.11.17",
|
|
4
4
|
"description": "Offline-first sync engine with rev baselines, tombstoned deletions, and idle-batched pushes",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"test": "vitest"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@vielzeug/arsenal": "26.11.
|
|
43
|
+
"@vielzeug/arsenal": "26.11.17"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@types/node": "^26.6.6",
|