@lunora/db 1.0.0-alpha.103 → 1.0.0-alpha.104
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/collections/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/mutators/index.mjs +1 -1
- package/dist/packem_shared/{CHECKPOINT_FALLBACK_MS-DVkxHO2j.mjs → CHECKPOINT_FALLBACK_MS-CNmrMAfD.mjs} +1 -1
- package/dist/packem_shared/{DIRECT_TRANSACTION_METADATA_KEY-O-hmqO42.mjs → DIRECT_TRANSACTION_METADATA_KEY-CGcOFtuo.mjs} +1 -1
- package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-DryDzA3q.mjs +1 -0
- package/dist/packem_shared/defineCollections-DHz2gn68.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-BfFCughR.mjs +0 -1
- package/dist/packem_shared/defineCollections-Cz4-m1Mp.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createCheckpointRegistry as t,lunoraCollectionOptions as r}from"../packem_shared/CHECKPOINT_FALLBACK_MS-
|
|
1
|
+
import{createCheckpointRegistry as t,lunoraCollectionOptions as r}from"../packem_shared/CHECKPOINT_FALLBACK_MS-CNmrMAfD.mjs";import{defineCollections as n}from"../packem_shared/defineCollections-DHz2gn68.mjs";export{t as createCheckpointRegistry,n as defineCollections,r as lunoraCollectionOptions};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyPlanToCollections as r,applyPlanToDb as i}from"./packem_shared/applyPlanToCollections-C_eyqNF9.mjs";import{CHECKPOINT_FALLBACK_MS as a,createCheckpointRegistry as p,getShardCheckpoints as c,lunoraCollectionOptions as l,releaseShardCheckpoints as s}from"./packem_shared/CHECKPOINT_FALLBACK_MS-
|
|
1
|
+
import{applyPlanToCollections as r,applyPlanToDb as i}from"./packem_shared/applyPlanToCollections-C_eyqNF9.mjs";import{CHECKPOINT_FALLBACK_MS as a,createCheckpointRegistry as p,getShardCheckpoints as c,lunoraCollectionOptions as l,releaseShardCheckpoints as s}from"./packem_shared/CHECKPOINT_FALLBACK_MS-CNmrMAfD.mjs";import{defineCollections as O}from"./packem_shared/defineCollections-DHz2gn68.mjs";import{DIRECT_TRANSACTION_METADATA_KEY as f,bindMutators as u,defineMutator as x,initMutators as A}from"./packem_shared/DIRECT_TRANSACTION_METADATA_KEY-CGcOFtuo.mjs";import{OUTBOX_MUTATION_FN_NAME as m,createExecutorOutboxSink as E,createOptimisticOnlineDetector as _,makeDiffEmit as N,runOutboxMutation as S,toMap as d}from"./packem_shared/OUTBOX_MUTATION_FN_NAME-DryDzA3q.mjs";const t="0.0.0";export{a as CHECKPOINT_FALLBACK_MS,f as DIRECT_TRANSACTION_METADATA_KEY,m as OUTBOX_MUTATION_FN_NAME,t as VERSION,r as applyPlanToCollections,i as applyPlanToDb,u as bindMutators,p as createCheckpointRegistry,E as createExecutorOutboxSink,_ as createOptimisticOnlineDetector,O as defineCollections,x as defineMutator,c as getShardCheckpoints,A as initMutators,l as lunoraCollectionOptions,N as makeDiffEmit,s as releaseShardCheckpoints,S as runOutboxMutation,d as toMap};
|
package/dist/mutators/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{bindMutators as r,defineMutator as i,initMutators as a}from"../packem_shared/DIRECT_TRANSACTION_METADATA_KEY-
|
|
1
|
+
import{bindMutators as r,defineMutator as i,initMutators as a}from"../packem_shared/DIRECT_TRANSACTION_METADATA_KEY-CGcOFtuo.mjs";export{r as bindMutators,i as defineMutator,a as initMutators};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as M}from"@lunora/errors";import{BTreeIndex as T}from"@tanstack/db";import{toMap as E,makeDiffEmit as S}from"./OUTBOX_MUTATION_FN_NAME-
|
|
1
|
+
import{LunoraError as M}from"@lunora/errors";import{BTreeIndex as T}from"@tanstack/db";import{toMap as E,makeDiffEmit as S}from"./OUTBOX_MUTATION_FN_NAME-DryDzA3q.mjs";const I=()=>{let e=Number.NEGATIVE_INFINITY;const a=[];return{advance:r=>{if(!(r<=e)){e=r;for(let n=a.length-1;n>=0;n-=1){const c=a[n];c&&c.threshold<=e&&(c.resolve(),a.splice(n,1))}}},await:r=>r<=e?Promise.resolve():new Promise(n=>{a.push({resolve:n,threshold:r})}),passed:r=>r<=e,reset:()=>{for(const r of a.splice(0))r.resolve();e=Number.NEGATIVE_INFINITY},waiting:()=>a.length}};let w=!1;const F=e=>{w||(w=!0,console.warn(`[@lunora/db] released an optimistic overlay via the ${String(e.waitedMs)}ms checkpoint fallback: the server confirmed ${e.kind} ${String(e.watermark)} but no sync frame ever echoed it. A dropped shape poke or \`settled\` frame is the usual cause — inspect the subscription rather than raising \`fallbackMs\`. (Reported once per process.)`))},y=new WeakMap,b=new WeakMap,C=new WeakSet,N=new WeakMap,K=3e3,R=(e={})=>{const a=e.fallbackMs??K,r=e.onFallback??F,n=I(),c=I();let d=0;const o=new Set,h=(t,i)=>{for(const l of o)l.kind===t&&l.threshold<=i&&(clearTimeout(l.handle),o.delete(l))},p=(t,i)=>{if(a<=0)return;const l=t==="checkpoint"?n:c;if(l.passed(i))return;for(const m of o)if(m.kind===t&&m.threshold>=i)return;const s={handle:setTimeout(()=>{if(o.delete(s),!l.passed(i)){d+=1,l.advance(i);try{r({kind:t,waitedMs:a,watermark:i})}catch{}}},a),kind:t,threshold:i};o.add(s)},u={acknowledge:({checkpoint:t,mutationId:i})=>{t!==void 0&&p("checkpoint",t),i!==void 0&&p("mutationId",i)},awaitCheckpoint:t=>n.await(t),awaitMutationId:t=>c.await(t),dispose:()=>{for(const t of o)clearTimeout(t.handle);o.clear()},resolve:({checkpoint:t,mutationId:i})=>{t!==void 0&&(n.advance(t),h("checkpoint",t)),i!==void 0&&(c.advance(i),h("mutationId",i))},stats:()=>({fallbacks:d,pendingCheckpointWaiters:n.waiting(),pendingMutationWaiters:c.waiting()})};return N.set(u,()=>{u.dispose(),n.reset(),c.reset()}),u},G=e=>{const a=y.get(e);if(a){for(const r of a.values())r.resolve({checkpoint:Number.POSITIVE_INFINITY,mutationId:Number.POSITIVE_INFINITY}),r.dispose();y.delete(e)}},A=e=>{const a=e.currentIdentity();if(y.has(e)&&b.get(e)!==a)for(const r of y.get(e)?.values()??[])N.get(r)?.();b.set(e,a)},_=(e,a,r)=>{A(e);let n=y.get(e);n||(n=new Map,y.set(e,n));const c=a??"",d=n.get(c);if(d)return d;const o=R(r);return n.set(c,o),o},W=e=>{C.add(e)},P=e=>C.has(e),L=e=>{if(e.list===void 0==(e.shape===void 0))throw new M("INTERNAL","lunoraCollectionOptions: pass exactly one of `list` or `shape`");const a=e.getKey??(s=>s._id),r=()=>{const s=e.checkpoints??_(e.client,e.shape?.shardKey??e.shardKey);return W(s),s},n=r(),c=new Map;let d,o,h,p,u;const t=(s,m)=>{const k=f=>{d?.(E(f,a)),m?.(),e.shape===void 0&&(r().resolve({mutationId:u??e.client.confirmedMutationWatermark(e.shardKey)}),u=void 0)},v=f=>h?.(f),g=f=>{f.rowsFollow===!0&&f.mutationId!==void 0&&(u=f.mutationId),r().resolve(f)};return e.shape!==void 0?e.client.subscribeShape({args:s,name:e.shape.name},k,{onCheckpoint:g,onError:v,shardKey:e.shape.shardKey}):e.client.subscribe(e.list,s,k,{onCheckpoint:g,onError:v,shardKey:e.shardKey})},i={autoIndex:"eager",defaultIndexType:T,getKey:a,id:e.id??e.list?.__lunoraRef??`shape:${e.shape?.name??""}`,...e.load==="eager"?{startSync:!0}:{},sync:{sync:s=>(d=S(c,s),h=k=>{s.markReady(),e.onError?.(k)},e.scopeBy===void 0?o=t(e.shape?.args??{},()=>{s.markReady()}):(s.markReady(),p!==void 0&&(o=t(p,void 0))),()=>{d=void 0,h=void 0,o?.(),o=void 0,c.clear()})}};return{checkpoints:n,config:i,scope:s=>{e.scopeBy!==void 0&&(p=s,o?.(),o=void 0,d?.(new Map),s!==void 0&&d!==void 0&&(o=t(s,void 0)))}}};export{K as CHECKPOINT_FALLBACK_MS,R as createCheckpointRegistry,_ as getShardCheckpoints,P as hasCheckpointsAttached,L as lunoraCollectionOptions,W as markCheckpointsAttached,G as releaseShardCheckpoints,A as syncShardCheckpointIdentity};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{createTransaction as k}from"@tanstack/db";import{getShardCheckpoints as v,hasCheckpointsAttached as w,syncShardCheckpointIdentity as C}from"./CHECKPOINT_FALLBACK_MS-
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{createTransaction as k}from"@tanstack/db";import{getShardCheckpoints as v,hasCheckpointsAttached as w,syncShardCheckpointIdentity as C}from"./CHECKPOINT_FALLBACK_MS-CNmrMAfD.mjs";import{runOutboxMutation as I}from"./OUTBOX_MUTATION_FN_NAME-DryDzA3q.mjs";const E="__tanstack_db_direct",T="defineMutator: `serverRef` must be a generated mutator reference (api.mutators.*) or a 'namespace:fn' string",A=t=>{const e=typeof t=="string"?t:t?.__lunoraRef;if(typeof e!="string"||e.length===0)throw new f("INTERNAL",T);return e},S=t=>({__lunoraClientMutator:!0,apply:t.apply,serverRef:A(t.serverRef)}),g=(t,e,l)=>{let c=0,u=t.currentIdentity();const d=()=>{C(t);const r=t.currentIdentity();r!==u&&(c=0,u=r)},y=()=>(d(),c=Math.max(c,t.confirmedMutationWatermark(e.shardKey))+1,c);let m=Promise.resolve();const R=(r,a)=>{const s=m.then(async()=>{for(let i=0;;i+=1){const n=y();try{const{applied:o}=await t.callMutator(r,a,{clientSeq:n,shardKey:e.shardKey});if(o)return n}catch(o){throw d(),c=t.confirmedMutationWatermark(e.shardKey),o}if(i>=32)throw new f("INTERNAL",`lunora: custom mutator "${r}" could not claim a fresh client sequence after ${String(32)} attempts`)}});return m=s.then(()=>{},()=>{}),s},M=()=>{if(e.checkpoints===!1)return;if(e.checkpoints)return e.checkpoints;const r=v(t,e.shardKey);return w(r)?r:void 0},_=(r,a,s,i)=>{const{onWriteRejected:n}=e;n&&r.isPersisted.promise.catch(o=>{const h=o instanceof Error?o:new Error(String(o));try{n({args:i,code:h.code,error:h,mutator:a,serverRef:s})}catch{}})},p={};for(const[r,a]of Object.entries(l))p[r]=s=>{const i=k({autoCommit:!0,metadata:{[E]:!0,serverRef:a.serverRef},mutationFn:async()=>{let n=0;await I(async()=>{n=await R(a.serverRef,s)});const o=M();o&&(o.acknowledge({mutationId:n}),await o.awaitMutationId(n))}});return i.mutate(()=>{a.apply({collections:e.collections},s)}),_(i,r,a.serverRef,s),i};return p},q=()=>({bindMutators:g,defineMutator:S});export{E as DIRECT_TRANSACTION_METADATA_KEY,g as bindMutators,S as defineMutator,q as initMutators};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createCollection as m,safeRandomUUID as y}from"@tanstack/db";import{NonRetriableError as O}from"@tanstack/offline-transactions";const p=1e3,f="__lunora_outbox__",u=new WeakMap,h=()=>m({getKey:e=>e._id,id:`${f}:${y()}`,startSync:!0,sync:{sync:e=>(e.markReady(),()=>{})}}),_=(e,t)=>{u.set(e,t)};let d=!1;const s=new Map,b=e=>{e.onRejected&&s.set(e.idempotencyKey,e.onRejected)},I=e=>{const t=s.get(e);return s.delete(e),t},E=(e,t={})=>{const n=t.maxItems??1e3,c=t.mutationFnName??f;return{enqueue(o){if(e.getPendingCount()>=n){const l=new Error("offline outbox is full");return l.code="OFFLINE_QUEUE_OVERFLOW",Promise.reject(l)}b(o);const r={args:o.args,clientId:o.clientId,functionPath:o.functionPath,idempotencyKey:o.idempotencyKey,identity:o.identity,mutationId:o.mutationId,shardKey:o.shardKey},i=u.get(e);!i&&!d&&(d=!0,console.warn("[@lunora/db] createExecutorOutboxSink: no outbox carrier is registered for this executor. On a TanStack OfflineExecutor a zero-mutation transaction is silently dropped, so offline writes may be lost — wire the sink to the executor returned by defineCollections()."));const a=e.createOfflineTransaction({autoCommit:!1,idempotencyKey:o.idempotencyKey,metadata:r,mutationFnName:c});return a.mutate(()=>{i?.insert({_id:o.idempotencyKey})}),a.commit?.().catch(()=>{}),Promise.resolve()}}},R=(e,t)=>new Map(e.map(n=>[t(n),n])),k=(e,t)=>n=>{t.begin();const c=new Map;for(const[o,r]of n){const i=JSON.stringify(r);c.set(o,i),e.has(o)?e.get(o)!==i&&t.write({type:"update",value:r}):t.write({type:"insert",value:r})}for(const o of e.keys())n.has(o)||t.write({key:o,type:"delete"});t.commit(),e.clear();for(const[o,r]of c)e.set(o,r)},w=async e=>{try{await e()}catch(t){if(typeof t.code=="string"){const n=new O(t instanceof Error?t.message:String(t));throw n.code=t.code,n}throw t}},N=()=>{const e=new Set;return{dispose:()=>{for(const t of e)clearInterval(t);e.clear()},isOnline:()=>!0,notifyOnline:()=>{},subscribe:t=>{const n=setInterval(t,p);return e.add(n),()=>{clearInterval(n),e.delete(n)}}}};export{f as OUTBOX_MUTATION_FN_NAME,E as createExecutorOutboxSink,N as createOptimisticOnlineDetector,h as createOutboxCarrier,k as makeDiffEmit,_ as registerOutboxCarrier,w as runOutboxMutation,I as takeOutboxRejection,R as toMap};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{lunoraCollectionOptions as M}from"./CHECKPOINT_FALLBACK_MS-CNmrMAfD.mjs";import{createCollection as U,safeRandomUUID as _}from"@tanstack/db";import{startOfflineExecutor as B,NonRetriableError as g}from"@tanstack/offline-transactions";import{createOutboxCarrier as R,createOptimisticOnlineDetector as j,OUTBOX_MUTATION_FN_NAME as K,registerOutboxCarrier as k,runOutboxMutation as I,takeOutboxRejection as N}from"./OUTBOX_MUTATION_FN_NAME-DryDzA3q.mjs";const v=new WeakMap,A=(n,r)=>{let t=v.get(n);t===void 0&&(t=new Map,v.set(n,t));const a=t.get(r)??0;t.set(r,a+1),a===1&&console.warn(`[@lunora/db] table "${r}" is bound by more than one defineCollections call on this client. Each call creates its own live collection and outbox for the table, so the two can drift and derived indexes built from one can silently read stale rows. Bind every table in a single defineCollections call (see the "One source of truth per table" docs section).`)},p=(n,r)=>{try{n.onWriteRejected?.(r)}catch{}},F=(n,r)=>{const t=n.replayIdentityVerdict(r?.identity);if(t==="mismatch")throw new g("outbox write dropped: identity changed since it was queued");if(t==="unknown")throw new Error("outbox write deferred: no identity established yet")},L=(n,r,t={})=>{const a={},w={},m={},b=Object.entries(r);for(const[o,e]of b){const i=e.insert;A(n,o);const{config:d,scope:y}=M({client:n,getKey:e.getKey,id:o,list:e.list,...e.load===void 0?{}:{load:e.load},onError:e.onError,scopeBy:e.scopeBy,shardKey:e.shardKey});a[o]=U(d),e.scopeBy!==void 0&&(w[o]=y),i&&(m[o]=async({idempotencyKey:l,transaction:u})=>{const c=u.metadata;for(const[h,E]of u.mutations.entries()){const C=E.modified,T=`${l}:${String(h)}`;try{F(n,c),await I(()=>n.mutation(i.mutation,i.toArgs(C),{mutationId:T,shardKey:c.shardKey}))}catch(f){throw f instanceof g&&p(t,{code:f.code,collection:o,error:f,row:C}),f}}})}m[K]=async({transaction:o})=>{const e=o.metadata;if(e)try{F(n,e),await I(()=>n.mutation({__lunoraRef:e.functionPath},e.args,{mutationId:e.idempotencyKey,shardKey:e.shardKey})),N(e.idempotencyKey)}catch(i){throw i instanceof g&&(N(e.idempotencyKey)?.(),p(t,{code:i.code,collection:e.functionPath,error:i})),i}};const O=R(),s=B({collections:{...a,[K]:O},mutationFns:m,onlineDetector:j(),...t.onLeadershipChange?{onLeadershipChange:t.onLeadershipChange}:{},...t.onStorageFailure?{onStorageFailure:t.onStorageFailure}:{},onUnknownMutationFn:(o,e)=>{p(t,{code:"UNKNOWN_MUTATION_FN",collection:o,error:new Error(`offline write dropped: mutation "${o}" no longer exists (removed or renamed in a deploy?)`),row:e.mutations[0]?.modified})}});k(s,O);const x={};for(const[o,e]of b){const i=e.insert,d=a[o];!i||!d||(x[o]=y=>{const l=_(),u={identity:n.currentIdentity(),shardKey:e.shardKey},c=s.createOfflineTransaction({autoCommit:!1,metadata:u,mutationFnName:o}),h=c.mutate(()=>{d.insert(i.optimistic(y,l))});return c.commit().catch(()=>{}),{id:l,transaction:h}})}return{actions:x,collections:a,executor:s,pendingCount:()=>s.getPendingCount(),scope:w}};export{L as defineCollections};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/db",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.104",
|
|
4
4
|
"description": "TanStack DB binding: typed, live-synced collections and a durable offline outbox over the Lunora client",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"access": "public"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@lunora/client": "1.0.0-alpha.
|
|
58
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
57
|
+
"@lunora/client": "1.0.0-alpha.101",
|
|
58
|
+
"@lunora/errors": "1.0.0-alpha.36"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"@tanstack/db": "^0.6.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createCollection as d,safeRandomUUID as m}from"@tanstack/db";import{NonRetriableError as y}from"@tanstack/offline-transactions";const p=1e3,f="__lunora_outbox__",u=new WeakMap,g=()=>d({getKey:e=>e._id,id:`${f}:${m()}`,startSync:!0,sync:{sync:e=>(e.markReady(),()=>{})}}),h=(e,t)=>{u.set(e,t)};let l=!1;const x=(e,t={})=>{const n=t.maxItems??1e3,a=t.mutationFnName??f;return{enqueue(r){if(e.getPendingCount()>=n){const c=new Error("offline outbox is full");return c.code="OFFLINE_QUEUE_OVERFLOW",Promise.reject(c)}const o={args:r.args,clientId:r.clientId,functionPath:r.functionPath,idempotencyKey:r.idempotencyKey,identity:r.identity,mutationId:r.mutationId,shardKey:r.shardKey},i=u.get(e);!i&&!l&&(l=!0,console.warn("[@lunora/db] createExecutorOutboxSink: no outbox carrier is registered for this executor. On a TanStack OfflineExecutor a zero-mutation transaction is silently dropped, so offline writes may be lost — wire the sink to the executor returned by defineCollections()."));const s=e.createOfflineTransaction({autoCommit:!1,idempotencyKey:r.idempotencyKey,metadata:o,mutationFnName:a});return s.mutate(()=>{i?.insert({_id:r.idempotencyKey})}),s.commit?.().catch(()=>{}),Promise.resolve()}}},_=(e,t)=>new Map(e.map(n=>[t(n),n])),I=(e,t)=>n=>{t.begin();const a=new Map;for(const[r,o]of n){const i=JSON.stringify(o);a.set(r,i),e.has(r)?e.get(r)!==i&&t.write({type:"update",value:o}):t.write({type:"insert",value:o})}for(const r of e.keys())n.has(r)||t.write({key:r,type:"delete"});t.commit(),e.clear();for(const[r,o]of a)e.set(r,o)},E=async e=>{try{await e()}catch(t){if(typeof t.code=="string"){const n=new y(t instanceof Error?t.message:String(t));throw n.code=t.code,n}throw t}},k=()=>{const e=new Set;return{dispose:()=>{for(const t of e)clearInterval(t);e.clear()},isOnline:()=>!0,notifyOnline:()=>{},subscribe:t=>{const n=setInterval(t,p);return e.add(n),()=>{clearInterval(n),e.delete(n)}}}};export{f as OUTBOX_MUTATION_FN_NAME,x as createExecutorOutboxSink,k as createOptimisticOnlineDetector,g as createOutboxCarrier,I as makeDiffEmit,h as registerOutboxCarrier,E as runOutboxMutation,_ as toMap};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{lunoraCollectionOptions as T}from"./CHECKPOINT_FALLBACK_MS-DVkxHO2j.mjs";import{createCollection as M,safeRandomUUID as U}from"@tanstack/db";import{startOfflineExecutor as _,NonRetriableError as g}from"@tanstack/offline-transactions";import{createOutboxCarrier as B,createOptimisticOnlineDetector as R,OUTBOX_MUTATION_FN_NAME as K,registerOutboxCarrier as A,runOutboxMutation as I}from"./OUTBOX_MUTATION_FN_NAME-BfFCughR.mjs";const N=new WeakMap,D=(n,r)=>{let e=N.get(n);e===void 0&&(e=new Map,N.set(n,e));const a=e.get(r)??0;e.set(r,a+1),a===1&&console.warn(`[@lunora/db] table "${r}" is bound by more than one defineCollections call on this client. Each call creates its own live collection and outbox for the table, so the two can drift and derived indexes built from one can silently read stale rows. Bind every table in a single defineCollections call (see the "One source of truth per table" docs section).`)},p=(n,r)=>{try{n.onWriteRejected?.(r)}catch{}},v=(n,r)=>{const e=n.replayIdentityVerdict(r?.identity);if(e==="mismatch")throw new g("outbox write dropped: identity changed since it was queued");if(e==="unknown")throw new Error("outbox write deferred: no identity established yet")},k=(n,r,e={})=>{const a={},w={},m={},b=Object.entries(r);for(const[o,t]of b){const i=t.insert;D(n,o);const{config:d,scope:h}=T({client:n,getKey:t.getKey,id:o,list:t.list,...t.load===void 0?{}:{load:t.load},onError:t.onError,scopeBy:t.scopeBy,shardKey:t.shardKey});a[o]=M(d),t.scopeBy!==void 0&&(w[o]=h),i&&(m[o]=async({idempotencyKey:l,transaction:u})=>{const c=u.metadata;for(const[y,F]of u.mutations.entries()){const x=F.modified,E=`${l}:${String(y)}`;try{v(n,c),await I(()=>n.mutation(i.mutation,i.toArgs(x),{mutationId:E,shardKey:c.shardKey}))}catch(f){throw f instanceof g&&p(e,{code:f.code,collection:o,error:f,row:x}),f}}})}m[K]=async({transaction:o})=>{const t=o.metadata;if(t)try{v(n,t),await I(()=>n.mutation({__lunoraRef:t.functionPath},t.args,{mutationId:t.idempotencyKey,shardKey:t.shardKey}))}catch(i){throw i instanceof g&&p(e,{code:i.code,collection:t.functionPath,error:i}),i}};const O=B(),s=_({collections:{...a,[K]:O},mutationFns:m,onlineDetector:R(),...e.onLeadershipChange?{onLeadershipChange:e.onLeadershipChange}:{},...e.onStorageFailure?{onStorageFailure:e.onStorageFailure}:{},onUnknownMutationFn:(o,t)=>{p(e,{code:"UNKNOWN_MUTATION_FN",collection:o,error:new Error(`offline write dropped: mutation "${o}" no longer exists (removed or renamed in a deploy?)`),row:t.mutations[0]?.modified})}});A(s,O);const C={};for(const[o,t]of b){const i=t.insert,d=a[o];!i||!d||(C[o]=h=>{const l=U(),u={identity:n.currentIdentity(),shardKey:t.shardKey},c=s.createOfflineTransaction({autoCommit:!1,metadata:u,mutationFnName:o}),y=c.mutate(()=>{d.insert(i.optimistic(h,l))});return c.commit().catch(()=>{}),{id:l,transaction:y}})}return{actions:C,collections:a,executor:s,pendingCount:()=>s.getPendingCount(),scope:w}};export{k as defineCollections};
|