@lunora/server 1.0.0-alpha.202 → 1.0.0-alpha.204

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/in-process.mjs +1 -1
  2. package/dist/index.d.mts +21 -0
  3. package/dist/index.d.ts +21 -0
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-mmP-6BcT.mjs +1 -0
  6. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BBf5JG4Z.mjs +1 -0
  7. package/dist/packem_shared/{assertShapesDeclareReadPolicies-BRj8MjCw.mjs → assertShapesDeclareReadPolicies-uqHVUw8L.mjs} +1 -1
  8. package/dist/packem_shared/beginDeferredSchedules-C7QLYr6C.mjs +1 -0
  9. package/dist/packem_shared/bindOrm-Kf5dmpGw.mjs +1 -0
  10. package/dist/packem_shared/{defineShape-gJ3o7MC2.mjs → defineShape-B6tFBTkW.mjs} +1 -1
  11. package/dist/packem_shared/httpAction-8vJ8HTqX.mjs +5 -0
  12. package/dist/packem_shared/{mask-B8XBFMhN.mjs → mask-CYXknf5m.mjs} +1 -1
  13. package/dist/packem_shared/middleware-oEEmcgVa.mjs +1 -0
  14. package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
  15. package/dist/packem_shared/rls-DRFzG7LZ.mjs +1 -0
  16. package/dist/packem_shared/{serveStorageObject-DNN3r8x3.mjs → serveStorageObject-uoExuirp.mjs} +1 -1
  17. package/dist/packem_shared/{storageRules-BOVDr5cr.mjs → storageRules-Cd2r-H_T.mjs} +1 -1
  18. package/dist/rls/testing.mjs +1 -1
  19. package/package.json +5 -4
  20. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs +0 -1
  21. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs +0 -1
  22. package/dist/packem_shared/beginDeferredSchedules-n_pHHjPE.mjs +0 -1
  23. package/dist/packem_shared/bindOrm-BHq_oUP2.mjs +0 -1
  24. package/dist/packem_shared/httpAction-CsKNC6op.mjs +0 -5
  25. package/dist/packem_shared/middleware-BN0Q7fMj.mjs +0 -1
  26. package/dist/packem_shared/onQueryChange-CatdYnH5.mjs +0 -1
  27. package/dist/packem_shared/rls-DRyDdfoA.mjs +0 -1
  28. package/dist/packem_shared/stable-key-B_BlboiY.mjs +0 -1
  29. package/dist/packem_shared/wire-codec-CZ4obM6q.mjs +0 -1
@@ -1 +1 @@
1
- import{LunoraError as I}from"@lunora/errors";import{runShardMigrations as R,TransactionHeadroomTracker as h,createShardCtxDb as T,RLS_UNWRAP_SYMBOL as g}from"@lunora/shard-engine";import{beginDeferredSchedules as p}from"./packem_shared/beginDeferredSchedules-n_pHHjPE.mjs";import{bindTableFacade as y}from"./packem_shared/bindOrm-BHq_oUP2.mjs";const k=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...s}=e;return{claims:Object.keys(s).length>0?s:null,userId:r}};class S extends h{current=new h;reset(){this.current=new h}headroom(){return this.current.headroom()}recordRead(r){this.current.recordRead(r)}recordWrite(r){this.current.recordWrite(r)}}const x=(e,r)=>{const{scheduler:s,sql:a}=r,i=e;R(a,i);const c=new S,m=t=>{const n=t;for(const o of Object.keys(i.tables))n[o]=y(t,o);return t};let u=!1;const w=t=>{const n=T({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),o=n[g]??n;return{database:m(n),rawDatabase:m(o)}},l=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:w,resetHeadroom:()=>{c.reset()},runInTransaction:t=>{const n=async()=>{const b=p({scheduler:s});c.reset(),l("BEGIN"),u=!0;try{const d=await t();return l("COMMIT"),u=!1,await b(!0),d}catch(d){u=!1;try{l("ROLLBACK")}catch{}throw await b(!1),d}},o=f.then(n);return f=o.then(()=>{},()=>{}),o}}},v=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},A=(e,r,s,a,i)=>{const c=v(r);if(c!==e)throw new I("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new I("INTERNAL",`This ${e} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${e.charAt(0).toUpperCase()}${e.slice(1)} from another function instead.`);return Promise.resolve(r.handler(s,a??{}))};export{x as createInProcessRuntime,v as registeredFunctionKind,k as resolveInProcessIdentity,A as runRegisteredFunction};
1
+ import{LunoraError as I}from"@lunora/errors";import{runShardMigrations as R,TransactionHeadroomTracker as h,createShardCtxDb as T,RLS_UNWRAP_SYMBOL as g}from"@lunora/shard-engine";import{beginDeferredSchedules as p}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{bindTableFacade as y}from"./packem_shared/bindOrm-Kf5dmpGw.mjs";const k=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...s}=e;return{claims:Object.keys(s).length>0?s:null,userId:r}};class S extends h{current=new h;reset(){this.current=new h}headroom(){return this.current.headroom()}recordRead(r){this.current.recordRead(r)}recordWrite(r){this.current.recordWrite(r)}}const x=(e,r)=>{const{scheduler:s,sql:a}=r,i=e;R(a,i);const c=new S,m=t=>{const n=t;for(const o of Object.keys(i.tables))n[o]=y(t,o);return t};let u=!1;const w=t=>{const n=T({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),o=n[g]??n;return{database:m(n),rawDatabase:m(o)}},l=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:w,resetHeadroom:()=>{c.reset()},runInTransaction:t=>{const n=async()=>{const b=p({scheduler:s});c.reset(),l("BEGIN"),u=!0;try{const d=await t();return l("COMMIT"),u=!1,await b(!0),d}catch(d){u=!1;try{l("ROLLBACK")}catch{}throw await b(!1),d}},o=f.then(n);return f=o.then(()=>{},()=>{}),o}}},v=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},A=(e,r,s,a,i)=>{const c=v(r);if(c!==e)throw new I("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new I("INTERNAL",`This ${e} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${e.charAt(0).toUpperCase()}${e.slice(1)} from another function instead.`);return Promise.resolve(r.handler(s,a??{}))};export{x as createInProcessRuntime,v as registeredFunctionKind,k as resolveInProcessIdentity,A as runRegisteredFunction};
package/dist/index.d.mts CHANGED
@@ -2473,6 +2473,13 @@ interface PatchWriteOptions {
2473
2473
  interface QueryArgs$1 {
2474
2474
  baseWhere?: WhereInput;
2475
2475
  cursor?: null | string;
2476
+ /**
2477
+ * Opt a list read back into a `.softDelete()` table's tombstoned rows. Set by
2478
+ * the chunked erase's re-location for a `{ hard: true }` delete, which must find
2479
+ * a row an earlier delete of the page soft-deleted and physically remove it; the
2480
+ * read `baseWhere` still applies (see `@lunora/do`'s `QueryArgs`).
2481
+ */
2482
+ includeDeleted?: boolean;
2476
2483
  limit?: number;
2477
2484
  orderBy?: ReadonlyArray<unknown>;
2478
2485
  /**
@@ -2670,6 +2677,13 @@ interface DatabaseWriterLike {
2670
2677
  allowExplicitId?: boolean;
2671
2678
  limit?: number;
2672
2679
  }) => Promise<string[]>;
2680
+ /**
2681
+ * Does the store currently hold an atomic write boundary open? Published by the writer (see
2682
+ * `@lunora/shard-engine`'s `DatabaseWriterLike`). A chunked erase trusts the page image only while a
2683
+ * mutation's serialized transaction is open; an action runs outside one, so every row is re-located.
2684
+ * Absent ⇒ treated as "not in a transaction" (the conservative default).
2685
+ */
2686
+ inTransaction?: () => boolean;
2673
2687
  /**
2674
2688
  * Optional table-aware lookup. The underlying writer (e.g. `@lunora/do`)
2675
2689
  * already knows the owning table of an id internally, so it can return
@@ -2759,6 +2773,13 @@ interface DatabaseWriterLike {
2759
2773
  relationEdges?: ReadonlyArray<RelationEdgeLike>;
2760
2774
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2761
2775
  restore?: (id: string, expectedTable?: string) => Promise<void>;
2776
+ /**
2777
+ * Soft-delete marker column per table, for tables declared `.softDelete()`. Published by the writer
2778
+ * (see `@lunora/shard-engine`'s `DatabaseWriterLike`). A re-located row whose marker is already set is
2779
+ * gone — the writer's delete is a no-op for it — so the chunked erase skips it instead of deleting and
2780
+ * counting it.
2781
+ */
2782
+ softDeleteFields?: ReadonlyMap<string, string>;
2762
2783
  /**
2763
2784
  * Whole-shard erase. The RLS wrapper deliberately **fails this closed** rather
2764
2785
  * than wrapping it — see the wrapper's `wipeShard`.
package/dist/index.d.ts CHANGED
@@ -2473,6 +2473,13 @@ interface PatchWriteOptions {
2473
2473
  interface QueryArgs$1 {
2474
2474
  baseWhere?: WhereInput;
2475
2475
  cursor?: null | string;
2476
+ /**
2477
+ * Opt a list read back into a `.softDelete()` table's tombstoned rows. Set by
2478
+ * the chunked erase's re-location for a `{ hard: true }` delete, which must find
2479
+ * a row an earlier delete of the page soft-deleted and physically remove it; the
2480
+ * read `baseWhere` still applies (see `@lunora/do`'s `QueryArgs`).
2481
+ */
2482
+ includeDeleted?: boolean;
2476
2483
  limit?: number;
2477
2484
  orderBy?: ReadonlyArray<unknown>;
2478
2485
  /**
@@ -2670,6 +2677,13 @@ interface DatabaseWriterLike {
2670
2677
  allowExplicitId?: boolean;
2671
2678
  limit?: number;
2672
2679
  }) => Promise<string[]>;
2680
+ /**
2681
+ * Does the store currently hold an atomic write boundary open? Published by the writer (see
2682
+ * `@lunora/shard-engine`'s `DatabaseWriterLike`). A chunked erase trusts the page image only while a
2683
+ * mutation's serialized transaction is open; an action runs outside one, so every row is re-located.
2684
+ * Absent ⇒ treated as "not in a transaction" (the conservative default).
2685
+ */
2686
+ inTransaction?: () => boolean;
2673
2687
  /**
2674
2688
  * Optional table-aware lookup. The underlying writer (e.g. `@lunora/do`)
2675
2689
  * already knows the owning table of an id internally, so it can return
@@ -2759,6 +2773,13 @@ interface DatabaseWriterLike {
2759
2773
  relationEdges?: ReadonlyArray<RelationEdgeLike>;
2760
2774
  replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
2761
2775
  restore?: (id: string, expectedTable?: string) => Promise<void>;
2776
+ /**
2777
+ * Soft-delete marker column per table, for tables declared `.softDelete()`. Published by the writer
2778
+ * (see `@lunora/shard-engine`'s `DatabaseWriterLike`). A re-located row whose marker is already set is
2779
+ * gone — the writer's delete is a no-op for it — so the chunked erase skips it instead of deleting and
2780
+ * counting it.
2781
+ */
2782
+ softDeleteFields?: ReadonlyMap<string, string>;
2762
2783
  /**
2763
2784
  * Whole-shard erase. The RLS wrapper deliberately **fails this closed** rather
2764
2785
  * than wrapping it — see the wrapper's `wipeShard`.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as h,withDeferredDeletes as S}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-n_pHHjPE.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as I,documentHistoryExtension as L}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-BHq_oUP2.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-CsKNC6op.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-DNN3r8x3.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as Y}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as z,clampLimit as Z,defineListArgs as $}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as re}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as te}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as ne}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as fe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as de,d as me,a as pe,b as xe,e as ce,f as le,g as Ee,h as ue,i as he,j as Se,k as De,m as Te}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ae,PRESENCE_TABLE as Re,definePresence as _e,presenceExtension as Ie}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs";import{protectPublic as Ce}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Pe}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{createServices as ye}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Oe}from"./packem_shared/defineShape-gJ3o7MC2.mjs";import{onWhisper as Ne}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ue}from"@lunora/errors";import{cronJobs as ve}from"@lunora/scheduler";import{ValidationError as Ve,v as We}from"@lunora/values";import{allowAll as Ye,deny as Ge,isDeny as Je,toWhereInput as Ke}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Xe}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ze,buildRlsReadRegistry as Ze,composeShapeReadWhere as $e}from"./packem_shared/assertShapesDeclareReadPolicies-BRj8MjCw.mjs";import{buildMaskRegistry as rr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as tr,definePermission as ir,definePolicies as nr,definePolicy as ar,defineRole as fr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as dr,defineStorageRules as mr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as xr}from"./packem_shared/mask-B8XBFMhN.mjs";import{r as lr}from"./packem_shared/middleware-BN0Q7fMj.mjs";import{storageRules as ur}from"./packem_shared/storageRules-BOVDr5cr.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,z as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ue as LunoraError,Ae as PRESENCE_DEFAULT_TTL_MS,Re as PRESENCE_TABLE,e as VERSION,Ve as ValidationError,n as actionCacheExtension,Ye as allowAll,Xe as asBucketStorage,ze as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,rr as buildMaskRegistry,Ze as buildRlsReadRegistry,a as cacheKeyFor,Z as clampLimit,de as composePluginMiddleware,$e as composeShapeReadWhere,tr as createPolicyDsl,l as createSecrets,ye as createServices,ve as cronJobs,f as defineActionCache,me as defineAggregateIndex,pe as defineComponent,I as defineDocumentHistory,P as defineEnv,W as defineIdentity,Y as defineIdentityGuard,$ as defineListArgs,re as defineMigration,te as defineModule,ne as defineMutator,ir as definePermission,xe as definePlugin,nr as definePolicies,ar as definePolicy,_e as definePresence,ce as defineRankIndex,fr as defineRole,le as defineSchema,Ee as defineSchemaExtension,Oe as defineShape,dr as defineStorageRule,mr as defineStorageRules,ue as defineTable,he as defineVectorIndex,Ge as deny,L as documentHistoryExtension,h as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,Se as indexFieldsFromSchema,d as initLunora,De as installPlugins,Je as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,xr as mask,Te as mergeSchemaExtension,J as onConnect,K as onDisconnect,Pe as onQueryChange,Q as onShardInit,Ne as onWhisper,fe as platformAdmin,Ie as presenceExtension,Ce as protectPublic,b as redactSecrets,lr as rls,B as serveStorageObject,ur as storageRules,x as tagPerDispatchMiddleware,Ke as toWhereInput,We as v,S as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-mmP-6BcT.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as h,withDeferredDeletes as S}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as I,documentHistoryExtension as L}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BBf5JG4Z.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-Kf5dmpGw.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-8vJ8HTqX.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-uoExuirp.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as Y}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as z,clampLimit as Z,defineListArgs as $}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as re}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as te}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as ne}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{platformAdmin as fe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as de,d as me,a as pe,b as xe,e as ce,f as le,g as Ee,h as ue,i as he,j as Se,k as De,m as Te}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ae,PRESENCE_TABLE as Re,definePresence as _e,presenceExtension as Ie}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs";import{protectPublic as Ce}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Pe}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{createServices as ye}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Oe}from"./packem_shared/defineShape-B6tFBTkW.mjs";import{onWhisper as Ne}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ue}from"@lunora/errors";import{cronJobs as ve}from"@lunora/scheduler";import{ValidationError as Ve,v as We}from"@lunora/values";import{allowAll as Ye,deny as Ge,isDeny as Je,toWhereInput as Ke}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Xe}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as ze,buildRlsReadRegistry as Ze,composeShapeReadWhere as $e}from"./packem_shared/assertShapesDeclareReadPolicies-uqHVUw8L.mjs";import{buildMaskRegistry as rr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as tr,definePermission as ir,definePolicies as nr,definePolicy as ar,defineRole as fr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as dr,defineStorageRules as mr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as xr}from"./packem_shared/mask-CYXknf5m.mjs";import{r as lr}from"./packem_shared/middleware-oEEmcgVa.mjs";import{storageRules as ur}from"./packem_shared/storageRules-Cd2r-H_T.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,z as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ue as LunoraError,Ae as PRESENCE_DEFAULT_TTL_MS,Re as PRESENCE_TABLE,e as VERSION,Ve as ValidationError,n as actionCacheExtension,Ye as allowAll,Xe as asBucketStorage,ze as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,rr as buildMaskRegistry,Ze as buildRlsReadRegistry,a as cacheKeyFor,Z as clampLimit,de as composePluginMiddleware,$e as composeShapeReadWhere,tr as createPolicyDsl,l as createSecrets,ye as createServices,ve as cronJobs,f as defineActionCache,me as defineAggregateIndex,pe as defineComponent,I as defineDocumentHistory,P as defineEnv,W as defineIdentity,Y as defineIdentityGuard,$ as defineListArgs,re as defineMigration,te as defineModule,ne as defineMutator,ir as definePermission,xe as definePlugin,nr as definePolicies,ar as definePolicy,_e as definePresence,ce as defineRankIndex,fr as defineRole,le as defineSchema,Ee as defineSchemaExtension,Oe as defineShape,dr as defineStorageRule,mr as defineStorageRules,ue as defineTable,he as defineVectorIndex,Ge as deny,L as documentHistoryExtension,h as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,Se as indexFieldsFromSchema,d as initLunora,De as installPlugins,Je as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,xr as mask,Te as mergeSchemaExtension,J as onConnect,K as onDisconnect,Pe as onQueryChange,Q as onShardInit,Ne as onWhisper,fe as platformAdmin,Ie as presenceExtension,Ce as protectPublic,b as redactSecrets,lr as rls,B as serveStorageObject,ur as storageRules,x as tagPerDispatchMiddleware,Ke as toWhereInput,We as v,S as withDeferredDeletes,g as withDeferredSchedules};
@@ -0,0 +1 @@
1
+ import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{decodeWire as U,encodeWire as D,stableWireKey as S}from"@lunora/wire";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-Bm9wIpiI.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=r=>r===void 0?"":S(r),x=async(r,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${r}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:G}=F.dataModel().create(),Z=(r={})=>{const m=r.ttlMs!==void 0&&Number.isFinite(r.ttlMs)?Math.max(1,Math.floor(r.ttlMs)):P,A=r.maxValueBytes!==void 0&&Number.isFinite(r.maxValueBytes)?Math.max(1,Math.floor(r.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(s._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),o=await C(e,i);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,o,{expiresAt:g,key:i,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(c).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(c).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
@@ -0,0 +1 @@
1
+ import{v as r}from"@lunora/values";import{decodeWire as E,encodeWire as h}from"@lunora/wire";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-Bm9wIpiI.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-BN0Q7fMj.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
1
+ import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-oEEmcgVa.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
@@ -0,0 +1 @@
1
+ import{assertScheduleInstant as A,assertScheduleDelay as v,resolveScheduleId as y}from"@lunora/scheduler";import{encodeArgsOrThrow as S}from"@lunora/wire";const m=new WeakMap,w=c=>{if(typeof c=="string")return c;const r=c??{},e=r.__lunoraRef??r.binding;return typeof e=="string"?e:"<unknown>"},x=c=>{let r=c;for(;r!==void 0&&!r.open;)r=r.parent;return r},D=(c,r,e)=>c==="runAfter"?Math.max(r,e-Date.now()):Math.max(r,e),k=(c,r)=>{const e=c,t={decisions:new Map,innermost:void 0,outbox:r},a=(n,i,o,s,d)=>e[n].call(e,i,o,s,d),u=(n,i,o,s,d)=>{const l=w(o);t.decisions.has(l)||t.decisions.set(l,t.outbox?.admit(l));const g=t.decisions.get(l),h=g===void 0?i:D(n,i,g),b=t.innermost;if(b===void 0)return a(n,h,o,s,d);const p=y(d?.id);return t.outbox?.record(p,{args:S(`ctx.scheduler.${n}`,w(o),s),options:d,target:o,when:Math.ceil(n==="runAfter"?Date.now()+h:h)}),b.pending.push({id:p,run:async()=>a(n,h,o,s,{...d,id:p})}),Promise.resolve(p)},f={...e,runAfter:(n,i,o,s)=>(v(n,"ctx.scheduler.runAfter"),u("runAfter",n,i,o,s)),runAt:(n,i,o,s)=>(A(n,Date.now(),"ctx.scheduler.runAt"),u("runAt",n,i,o,s))};return Object.setPrototypeOf(f,Object.getPrototypeOf(e)),m.set(f,t),f},q=c=>{const{scheduler:r}=c,e=typeof r=="object"&&r!==null?m.get(r):void 0;if(!e)return async()=>{};const t={open:!0,parent:e.innermost,pending:[]};return e.innermost=t,async a=>{if(!t.open)return;t.open=!1,e.innermost===t&&(e.innermost=x(t.parent));const u=t.pending.splice(0);if(u.length===0)return;if(!a){for(const{id:s}of u)e.outbox?.forget(s);return}const f=x(t.parent);if(f!==void 0){f.pending.push(...u);return}const n=[];for(const{id:s,run:d}of u)try{await d(),e.outbox?.forget(s)}catch(l){n.push(l)}const[i,...o]=n;if(i!==void 0)throw e.outbox?.wake(),o.length===0?i:new AggregateError(n,`ctx.scheduler: ${String(n.length)} of ${String(u.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{q as beginDeferredSchedules,k as withDeferredSchedules};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{isPlainObject as M}from"@lunora/wire";const b=new Set(["connect","disconnect","set"]),y=500,I=(t,n,s)=>t!==void 0&&Object.hasOwn(t,n)&&M(s),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},O=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,s)=>{n.through===void 0&&E(t,n,s)},k=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:O(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=e===void 0?[]:O(e,`${t}.connect`),r=i===void 0?[]:O(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},j=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!b.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):k(n,s,i)},W=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},$=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},R=async(t,n,s,e,i)=>{const c=await t.get(i,e);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},_=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await R(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},F=async(t,{info:n,name:s},e,i)=>{(await R(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(e,{[n.field]:i},n.table)},U=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(String(s._id),{[n.field]:null},n.table)},V=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},w=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},C=async(t,n,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},P=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>R(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await w(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await w(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await w(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await C(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>R(t,i,"connect",e.table,h)));for(const h of d)await t.delete(String(h._id),a);for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>R(t,n.name,"disconnect",n.info.table,c)));else{const c=await V(t,n,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await U(t,n,c,s);for(const c of e)await F(t,n,c,s)},S=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await P(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},x=(t,n,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(s,n))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await _(t,c),r=await i(a);return r!==null&&await S(t,n,c,x(t,n,r,a)),r},m=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(e,c.columns,n);return}const a=await _(t,c);if(Object.keys(a).length>0)await t.patch(e,a,n);else{if(await t.get(e,n)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(e,n)}await S(t,n,c,x(t,n,e,a))},G=(t,n,s,e)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=s[a]}return c},X=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>m(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=G(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(o,n),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(o,d,n)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const h=o;return t.deleteWhere(n,h.where,{limit:h.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(o,n),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(o,n,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const h of o)$(n,e,h,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)$(n,e,l,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(o.map(l=>({id:l.id,patch:l.values})),d,n)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>($(n,e,d,"replace"),t.replace(o,d,n)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(o,n)},upsert:r,upsertMany:async({rows:o,target:d})=>{const h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},z=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{z as bindOrm,X as bindTableFacade};
@@ -1 +1 @@
1
- import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-BRj8MjCw.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
1
+ import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-uqHVUw8L.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{encodeWire as q}from"@lunora/wire";import{Hono as x}from"hono";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const U=e=>async r=>e(r.get("lunora"),r.req.raw),J=()=>{const e=new x;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},C=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=C(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},L=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(r===void 0?q(e):e);return`${r?`event: ${r}
2
+ `:""}data: ${o}
3
+
4
+ `},D=(e,r)=>(async o=>{const n=A(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},a=Object.keys(e.params).length>0?T(e.params,o):{}}catch(m){return j(m)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const f=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const y=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const p of y){if(s.signal.aborted)break;m.enqueue(h.encode(b(e.output?k(e.output,p):p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(y){const{body:p,redacted:P}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});P&&console.error("[lunora] unhandled stream handler error:",y),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,message:p.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>L(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>D(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),Q={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},W=e=>!(e.includes("\r")||e.includes(`
5
+ `)||e.includes("\0"));export{U as httpAction,Q as httpRoute,J as httpRouter,W as isSafeHeaderValue};
@@ -1 +1 @@
1
- import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as G,a as C,o as K,b as H,c as J,d as m}from"./middleware-BN0Q7fMj.mjs";import{bindTableFacade as Q,bindOrm as V}from"./bindOrm-BHq_oUP2.mjs";import{tagMaskMiddleware as X}from"./buildMaskRegistry-DpWMtalG.mjs";const Y=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},f=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=Y(g,s[y],{...c,column:y,row:s}));return w},F=(s,i,c)=>({...s,page:s.page.map(w=>f(w,i,c))}),I=(s,i)=>{const c=J(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>u=>(typeof u=="string"&&y.add(u),g())});s(g());for(const u of y)if(I(i,u))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${u}" is not supported`)},Z=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,u=(r,t)=>{const n=i.get(r);return n?t.map(o=>f(o,n,c)):t},l=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?u:(n,o)=>t(n,u(n,o))}},p=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,t,c)},collect:async()=>(await r.collect()).map(e=>f(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=f(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(f(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?f(o,t,c):null},order:o=>k(r.order(o),t,n),paginate:async o=>F(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>f(a,t,c)),unique:async()=>{const o=await r.unique();return o?f(o,t,c):null},withIndex:(o,e)=>(p(n,o,"withIndex","index"),L(e,t,n,"withIndex"),k(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(L(e,t,n,"withSearchIndex"),k(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(p(n,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),t,n))}),W=async(r,t)=>{if(s.lookupById){const d=await s.lookupById(r,t);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const n=await s.get(r,t);if(!n)return{row:null,tableName:void 0};const o=t!==void 0&&i.has(t)?[t]:[],e=t===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:n,tableName:a.find(d=>d!==void 0)}},S=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const t of Object.keys(r))O.add(t);const P=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,t,n,o)},q=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])P(a,n,o,e);return}if(r==="NOT"){P(t,n,o,e);return}if(!r.startsWith("__")){if(I(n,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(m(t))for(const a of Object.values(t))P(a,O,`${o}.${r}`,e)}},E=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{O.size===0||t===void 0||P(t,E(r),r,n)},U=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(I(n,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},v=(r,t,n)=>{if(!(O.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;P(a.where,O,d,n),U(d,a.orderBy,O,n),v(d,a.with,n)}},$=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),U(r,t?.orderBy,E(r),n),v(r,t?.with,n)},_=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=_(t);h(r,o?.where,n),h(r,o?.baseWhere,n),v(r,o?.with,n)},j=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,B={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,d]=e.kind==="one"?[t,e.table]:[e.table,t],R=e.through?j(e.through.table,e.through.from)??j(e.through.table,e.through.to):j(a,e.field)??j(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return S(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=_(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,l(t)),o=i.get(r);return n&&o?f(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,l(t)),o=i.get(r);return o?f(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,l(t)),o=i.get(r);return o?F(n,o,c):n},async get(r,t){const{row:n,tableName:o}=await W(r,t),e=o===void 0?void 0:i.get(o);return!n||!e?n:f(n,e,c)},related:s.related?async(r,t)=>await s.related(r,l(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?f(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return S(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?k(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),p(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),p(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?F(o,e,c):o},...K("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),p(t,n,"rankBefore","rank"),r(t,n,o))),...K("rankPageRows",g,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),p(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:f(d.doc,a,c)}))}:e})},z=B;if(O.size>0)for(const[r,t]of Object.entries(s))H(t)&&(z[r]=Q(B,r));return B},nr=(s,i={})=>{const c=new Map(Object.entries(s)),w=G(i.roles),y=async({ctx:u,next:l})=>{const p={auth:await C(u.auth??{},w),ctx:u};if(i.bypass?.(p)===!0)return l();const k=Z(u.db,c,p,i.indexFields),W={db:k},{orm:S}=u;return S!==null&&typeof S=="object"&&(W.orm=V(k)),l({ctx:W})},g=new Map;for(const[u,l]of c)g.set(u,new Set(Object.keys(l)));return X(y,{columns:g})};export{nr as mask};
1
+ import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as G,a as C,o as K,b as H,c as J,d as m}from"./middleware-oEEmcgVa.mjs";import{bindTableFacade as Q,bindOrm as V}from"./bindOrm-Kf5dmpGw.mjs";import{tagMaskMiddleware as X}from"./buildMaskRegistry-DpWMtalG.mjs";const Y=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},f=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=Y(g,s[y],{...c,column:y,row:s}));return w},F=(s,i,c)=>({...s,page:s.page.map(w=>f(w,i,c))}),I=(s,i)=>{const c=J(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>u=>(typeof u=="string"&&y.add(u),g())});s(g());for(const u of y)if(I(i,u))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${u}" is not supported`)},Z=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,u=(r,t)=>{const n=i.get(r);return n?t.map(o=>f(o,n,c)):t},l=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?u:(n,o)=>t(n,u(n,o))}},p=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,t,c)},collect:async()=>(await r.collect()).map(e=>f(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=f(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(f(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?f(o,t,c):null},order:o=>k(r.order(o),t,n),paginate:async o=>F(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>f(a,t,c)),unique:async()=>{const o=await r.unique();return o?f(o,t,c):null},withIndex:(o,e)=>(p(n,o,"withIndex","index"),L(e,t,n,"withIndex"),k(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(L(e,t,n,"withSearchIndex"),k(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(p(n,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),t,n))}),W=async(r,t)=>{if(s.lookupById){const d=await s.lookupById(r,t);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const n=await s.get(r,t);if(!n)return{row:null,tableName:void 0};const o=t!==void 0&&i.has(t)?[t]:[],e=t===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:n,tableName:a.find(d=>d!==void 0)}},S=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const t of Object.keys(r))O.add(t);const P=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,t,n,o)},q=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])P(a,n,o,e);return}if(r==="NOT"){P(t,n,o,e);return}if(!r.startsWith("__")){if(I(n,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(m(t))for(const a of Object.values(t))P(a,O,`${o}.${r}`,e)}},E=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{O.size===0||t===void 0||P(t,E(r),r,n)},U=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(I(n,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},v=(r,t,n)=>{if(!(O.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;P(a.where,O,d,n),U(d,a.orderBy,O,n),v(d,a.with,n)}},$=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),U(r,t?.orderBy,E(r),n),v(r,t?.with,n)},_=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=_(t);h(r,o?.where,n),h(r,o?.baseWhere,n),v(r,o?.with,n)},j=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,B={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,d]=e.kind==="one"?[t,e.table]:[e.table,t],R=e.through?j(e.through.table,e.through.from)??j(e.through.table,e.through.to):j(a,e.field)??j(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new A("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return S(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=_(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,l(t)),o=i.get(r);return n&&o?f(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,l(t)),o=i.get(r);return o?f(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,l(t)),o=i.get(r);return o?F(n,o,c):n},async get(r,t){const{row:n,tableName:o}=await W(r,t),e=o===void 0?void 0:i.get(o);return!n||!e?n:f(n,e,c)},related:s.related?async(r,t)=>await s.related(r,l(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?f(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return S(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?k(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),p(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),p(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?F(o,e,c):o},...K("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),p(t,n,"rankBefore","rank"),r(t,n,o))),...K("rankPageRows",g,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),p(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:f(d.doc,a,c)}))}:e})},z=B;if(O.size>0)for(const[r,t]of Object.entries(s))H(t)&&(z[r]=Q(B,r));return B},nr=(s,i={})=>{const c=new Map(Object.entries(s)),w=G(i.roles),y=async({ctx:u,next:l})=>{const p={auth:await C(u.auth??{},w),ctx:u};if(i.bypass?.(p)===!0)return l();const k=Z(u.db,c,p,i.indexFields),W={db:k},{orm:S}=u;return S!==null&&typeof S=="object"&&(W.orm=V(k)),l({ctx:W})},g=new Map;for(const[u,l]of c)g.set(u,new Set(Object.keys(l)));return X(y,{columns:g})};export{nr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as g,isLunoraError as pe}from"@lunora/errors";import{findRelated as we,whereFilter as ge}from"@lunora/shard-engine";import{isPlainObject as H}from"@lunora/wire";import{bindTableFacade as Oe,bindOrm as be}from"./bindOrm-Kf5dmpGw.mjs";import{t as ve}from"./policy-tag-V0lqFzgS.mjs";import{deny as Re}from"./allowAll-DkRAgItV.mjs";const K=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},J=4;class T extends Error{}const C=e=>e.includes("."),ht=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ne=e=>{const t=e.split(".");if(t.length>J||t.includes(""))throw new T(`field path "${e}" must have 1 to ${String(J)} non-empty segments`);return t},We=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of ne(t)){if(!K(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},re=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new T(`field path "${s}" is empty`);if(e!=null&&!K(e))throw new T(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const d=e??{};return{...d,[a]:l.length===0?r:re(d[a],l,r,s)}},Ee=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const l=r.find(d=>d!==a&&d.startsWith(`${a}.`));if(l!==void 0)throw new T(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))C(a)||(s[a]=l);for(const a of r){const[l="",...d]=ne(a);if(Object.hasOwn(e,l))throw new T(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=re(Object.hasOwn(s,l)?s[l]:t[l],d,e[a],a)}return s},Ae=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},Se=["every","is","isNot","none","some"],ke=new Set(Se),Be=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>ke.has(r))},Z=(e,t,r)=>t?{[e]:r(t)}:{},Q={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const oe=e=>{if(!K(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Q,r)))return{operand:e[r],operator:r}},Pe=e=>oe(e)!==void 0,_e=(e,t,r,s)=>{const a=Q[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},se=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&Pe(a)&&r.add(s);return r},Ie=(e,t,r)=>{let s;for(const a of se(e,r)){const{operand:l,operator:d}=oe(e[a]),b=r(a);if(Q[d].kind!==b)throw new R(`patch: "${d}" does not apply to the ${String(b)} column "${a}".`);s??={...e},s[a]=_e(a,d,l,t[a])}return s??e},Te=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of se(e,r))try{Object.assign(s,Ie({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return Ee(s,t)}catch(a){if(a instanceof T)return s;throw a}},$e=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],k=-1,B=0,W=1,$=e=>e?W:k,O=(e,t)=>e<t?e:t,me=(e,t)=>e>t?e:t,ie=e=>e===B?B:$(e===k),V=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},P=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new g("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},De={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Fe=(e,t,r)=>{let s=W;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const d=C(e);if(d?Ae(l)===void 0:!V(l))s=O(s,k);else if(P(t))s=O(s,B);else{const b=De[a],p=d?typeof t==typeof l:V(t);s=O(s,$(p&&b(t,l)))}}return s},ee=(e,t,r)=>{if(!Array.isArray(r))throw new g("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new g("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},te=(e,t)=>t.length===0?k:P(e)?B:t.includes(e)?W:t.some(r=>P(r))?B:k,Me=(e,t,r)=>{let s=W;if("in"in r&&(s=O(s,te(t,ee(e,"in",r.in)))),"notIn"in r&&(s=O(s,ie(te(t,ee(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=P(t)?O(s,B):O(s,$(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=O(s,$(r.isNull===!0===P(t)))),s},Y=(e,t,r)=>t===null?$(r===P(e)):P(e)?B:$(r===(e===t)),je=(e,t,r)=>{let s=W;return"eq"in r&&(D(e,"eq",r.eq),s=O(s,Y(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=O(s,Y(t,r.ne,!1))),s},Le=(e,t,r)=>O(je(e,t,r),O(Me(e,t,r),Fe(e,t,r))),Ce=(e,t,r,s)=>{if(t==="NOT")return ie(s(e,r??{}));if(!Array.isArray(r))return k;let a=t==="AND"?W:k;for(const l of r){const d=s(e,l);a=t==="AND"?O(a,d):me(a,d)}return a},ae=e=>e==="AND"||e==="OR"||e==="NOT",Ue=e=>H(e)&&Object.keys(e).every(t=>$e.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ae(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):Be(r)}),ce=(e,t)=>{let r=W;for(const s of Object.keys(t)){const a=t[s];if(ae(s)){r=O(r,Ce(e,s,a,ce));continue}const l=We(e,s);if(Ue(a)){r=O(r,Le(s,l,a));continue}D(s,"eq",a),r=O(r,Y(l,a,!0))}return r},q=(e,t)=>ce(e,t)===W,le=500,I=(e,t,r)=>{const s=t??le;if(e>s)throw new g("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},qe=Re(),Ne=Symbol.for("lunora.ctxdb.rls-unwrap"),fe=Symbol.for("lunora.rls.wrapped-chain"),Ye=e=>e[fe],xe=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},He=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?qe:r.length===1?r[0]:{OR:r}},Ke=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new g("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},Qe=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Ke(e,t,r);if(s===!1)return!1;if(U(s))throw new g("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},ze=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!Qe(l,r,s)))return!1;return a},Xe=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ge=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":H(t),Je=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Xe.has(r)&&Ge(r,e[r]))},Ze=e=>e===void 0?{}:H(e)&&Je(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,Ve=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,et=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},tt=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,d=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const u of r){const h=u.perTable.get(n);if(!h||h.length===0||!h.some(_=>_.on==="read"))continue;c=!0;const y=He(h,u.context);y!==void 0&&i.push(y)}const f={baseWhere:Ve(i),restricts:c};return l.set(n,f),f},b=(n,o,i,c)=>{for(const f of r){const u=f.perTable.get(n);if(u&&!ze(u,o,{...f.context,row:i},c))return!1}return!0},p=n=>d(n).restricts?t:e,w=n=>d(n).baseWhere,E=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const f=o??i,u=f===void 0?[...a.keys()]:[f].filter(y=>a.has(y)),h=await Promise.all(u.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:h.find(y=>y!==void 0)}},N=async(n,o,i)=>{const c=await E(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},A=async(n,o,i,c,f,u)=>{const h=await N(n,f,u);if(!h)return i(e);const y=c?c(h.row):void 0;if(!b(h.tableName,o,h.row,y))throw new g("FORBIDDEN",`${o} denied by policy`);return i(t,h.tableName)},F=(n,o,i)=>{if(i?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},M=async(n,o,i,c,f)=>{const u=i?t:e,h=await u.findFirst(o,{...i?{baseWhere:d(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:w,where:f===void 0?{_id:n}:v(f,{_id:n})});if(!h||F(o,h,c))return!1;if(i&&!b(o,"delete",h))throw new g("FORBIDDEN","delete denied by policy");return await u.delete(n,o,c),!0},m=async(n,o,i,c)=>{const f=a.has(n),u=f?t:e,h=i===void 0?void 0:{hard:i},y=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let _=0;for(const X of o){const G=String(X._id);if(y){await M(G,n,f,h,c)&&(_+=1);continue}if(f&&!b(n,"delete",X))throw new g("FORBIDDEN","delete denied by policy");await u.delete(G,n,h),_+=1}return _},j=(n,o,i,c)=>A(n,"update",(f,u)=>i(f,{verify:u===void 0?void 0:(h,y)=>b(u,"update",h,y)}),f=>({...f,...Te(o,f)}),c),L=(n,o)=>{const{baseWhere:i}=d(n);if(x(i))throw new g("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},ue=e.rankBefore,he=e.rankPageRows,{relationEdges:z}=e,S={...e,async count(n,o){const{baseWhere:i}=d(n),c=Ze(o);return p(n).count(n,{...c,baseWhere:v(c.baseWhere,i),relationBaseWhere:w,restrictsCounts:(c.restrictsCounts??!1)||x(i)})},delete:(n,o,i)=>A(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??le),{baseWhere:c}=d(n);let f=0;for(;;){const u=await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:w}),{page:h}=u;if(h.length===0||(f+=await m(n,h,o?.hard),h.length<i))break}return{deleted:f}},async deleteMany(n,o,i){I(n.length,o?.limit,"deleteMany");for(const c of n)await A(c,"delete",f=>f.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=d(n),f=await p(n).findMany(n,{baseWhere:v(o,c),relationBaseWhere:w}),u=f.page.map(h=>String(h._id));return I(u.length,i?.limit,"deleteWhere"),{deleted:await m(n,f.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=d(n);return p(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async findFirstOrThrow(n,o){const{baseWhere:i}=d(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async explain(n,o){const{baseWhere:i}=d(n);return p(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async findMany(n,o){const{baseWhere:i}=d(n);return p(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async get(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:f}=d(i.tableName);if(!f)return e.get(n,o);if(!c)return i.row;const u=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return u?._id===n?u:null},async lookupById(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0||!d(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=d(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const f=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return f?._id===n?{row:f,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!b(n,"insert",o))throw new g("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(I(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new g("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(I(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new g("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>j(n,o,(c,f)=>c.patch(n,o,i,f),i),assertPatchAllowed:(n,o)=>j(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await j(o,i.patch,async(u,h)=>{if(u.patchIf===void 0)throw new g("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return u.patchIf(n,o,{...i,verify:h.verify})},n);return c.doc===null||await S.get(o,n).then(u=>u!==null,u=>{if(pe(u)&&u.code==="RLS_REQUIRED")return!1;throw u})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){I(n.length,o?.limit,"patchMany");for(const c of n)await j(c.id,c.patch,(f,u)=>f.patch(c.id,c.patch,i,u),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=d(n),u=(await p(n).findMany(n,{baseWhere:v(o.where,c),relationBaseWhere:w})).page.map(h=>({id:String(h._id),patch:o.patch}));return I(u.length,i?.limit,"patchWhere"),S.patchMany(u,i)},query(n){const{baseWhere:o}=d(n),i=p(n).query(n);return o?i.filter(ge(o,c=>q(c,o))):i},related:z===void 0?void 0:async(n,o)=>we({findMany:async(i,c)=>S.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},z,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new g("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>A(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=d(n);return p(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:w})},groupBy(n,o){const{baseWhere:i}=d(n);return p(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:w})},rank(n,o,i){return L(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return L(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new g("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...Z("rankBefore",ue,n=>(o,i,c)=>(L(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...Z("rankPageRows",he,n=>(o,i,c)=>(L(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))},ye=S;if(a.size>0)for(const[n,o]of Object.entries(e))et(o)&&(ye[n]=Oe(S,n));return Object.defineProperty(S,fe,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),S},de=e=>typeof e=="string"?e:e.name,nt=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>de(s))));return t},rt=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(de(s))},ot=["roles","role"],st=e=>{for(const t of ot){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},it=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...st(r),...e.roles??[]])];return{can:rt(s,t),identity:r,roles:s,userId:e.userId??null}},yt=(e,t={})=>{const r=e,s=xe(r),a=nt(t.roles);return ve(async({ctx:d,next:b})=>{const p={auth:await it(d.auth??{},a),ctx:d},w=d.db,E=Ye(w),N=E?.base??w,A=E?.raw??w[Ne]??w,F=tt(N,A,[...E?.steps??[],{context:p,perTable:s}]),M={db:F},{orm:m}=d;return m!==null&&typeof m=="object"&&(M.orm=be(F)),b({ctx:M})},[{policies:r,roles:t.roles??[]}])};export{it as a,et as b,ht as c,Be as d,st as e,He as f,rt as g,ze as h,nt as i,q as m,Z as o,yt as r};
@@ -0,0 +1 @@
1
+ import{stableStringify as o}from"@lunora/wire";import{f as e,F as c,a as f}from"./fnv1a-D3ueNTWB.mjs";const l=r=>`${e(r,c)}${e(r,f)}`,m=(r,i)=>({args:{},handler:async(a,s)=>{const n=await r(a),t=l(o(n));return t===s?.previousDigest?{digest:t,ran:!1}:(await i(a,n),{digest:t,ran:!0})},kind:"mutation",lifecycle:"reactor",visibility:"internal"});export{m as onQueryChange};
@@ -0,0 +1 @@
1
+ import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-oEEmcgVa.mjs";import"./bindOrm-Kf5dmpGw.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
@@ -1 +1 @@
1
- import{isSafeHeaderValue as b}from"./httpAction-CsKNC6op.mjs";const N=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,R=/(?:W\/)?"[^"]*"/g,p=t=>t.startsWith("W/")?t.slice(2):t,S=(t,e)=>{if(t.trim()==="*")return!0;const n=p(g(e));return(t.match(R)??[]).some(s=>p(s)===n)},m=(t,e)=>{if(t===null)return{kind:"full"};const n=N.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let r,o;if(s===""){const u=Number(a);if(u===0)return{kind:"unsatisfiable"};r=Math.max(0,e-u),o=e-1}else r=Number(s),o=a===""?e-1:Math.min(Number(a),e-1);return r>o||r>=e?{kind:"unsatisfiable"}:{end:o,kind:"partial",start:r}},v=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),w=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&b(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return v.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},y=t=>m(t,0).kind==="full",h=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...w(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},T=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},W=async(t,e,n,s,a="no-store")=>{if(!await T(s,e,n))return new Response("Forbidden",{status:403});const r=n.headers.get("if-none-match");let o;if(r!==null){const d=await t.storage.head(e);if(!d)return new Response("Not Found",{status:404});if(S(r,d.etag))return new Response(void 0,{headers:{"cache-control":a,etag:g(d.etag)},status:304});o=d}const u=n.headers.get("range");if(y(u))return h(t,e,a);const c=o??await t.storage.head(e);if(!c)return new Response("Not Found",{status:404});const i=m(u,c.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(c.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(c.etag)},status:416});if(i.kind==="full")return h(t,e,a);const f=i.end-i.start+1,l=await t.storage.download(e,{range:{length:f,offset:i.start}});return l?new Response(l.body,{headers:{...w(c,a),"content-length":String(f),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(c.size)}`},status:206}):new Response("Not Found",{status:404})};export{W as serveStorageObject};
1
+ import{isSafeHeaderValue as b}from"./httpAction-8vJ8HTqX.mjs";const N=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,R=/(?:W\/)?"[^"]*"/g,p=t=>t.startsWith("W/")?t.slice(2):t,S=(t,e)=>{if(t.trim()==="*")return!0;const n=p(g(e));return(t.match(R)??[]).some(s=>p(s)===n)},m=(t,e)=>{if(t===null)return{kind:"full"};const n=N.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let r,o;if(s===""){const u=Number(a);if(u===0)return{kind:"unsatisfiable"};r=Math.max(0,e-u),o=e-1}else r=Number(s),o=a===""?e-1:Math.min(Number(a),e-1);return r>o||r>=e?{kind:"unsatisfiable"}:{end:o,kind:"partial",start:r}},v=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),w=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&b(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return v.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},y=t=>m(t,0).kind==="full",h=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...w(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},T=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},W=async(t,e,n,s,a="no-store")=>{if(!await T(s,e,n))return new Response("Forbidden",{status:403});const r=n.headers.get("if-none-match");let o;if(r!==null){const d=await t.storage.head(e);if(!d)return new Response("Not Found",{status:404});if(S(r,d.etag))return new Response(void 0,{headers:{"cache-control":a,etag:g(d.etag)},status:304});o=d}const u=n.headers.get("range");if(y(u))return h(t,e,a);const c=o??await t.storage.head(e);if(!c)return new Response("Not Found",{status:404});const i=m(u,c.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(c.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(c.etag)},status:416});if(i.kind==="full")return h(t,e,a);const f=i.end-i.start+1,l=await t.storage.download(e,{range:{length:f,offset:i.start}});return l?new Response(l.body,{headers:{...w(c,a),"content-length":String(f),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(c.size)}`},status:206}):new Response("Not Found",{status:404})};export{W as serveStorageObject};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-BN0Q7fMj.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-oEEmcgVa.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -1 +1 @@
1
- import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-BN0Q7fMj.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
1
+ import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-oEEmcgVa.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.202",
3
+ "version": "1.0.0-alpha.204",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -71,9 +71,10 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
74
- "@lunora/scheduler": "1.0.0-alpha.126",
75
- "@lunora/shard-engine": "1.0.0-alpha.129",
76
- "@lunora/values": "1.0.0-alpha.65",
74
+ "@lunora/scheduler": "1.0.0-alpha.128",
75
+ "@lunora/shard-engine": "1.0.0-alpha.131",
76
+ "@lunora/values": "1.0.0-alpha.66",
77
+ "@lunora/wire": "1.0.0-alpha.1",
77
78
  "drizzle-orm": "^0.45.3",
78
79
  "hono": "^4.13.13"
79
80
  },
@@ -1 +0,0 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CZ4obM6q.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-Bm9wIpiI.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
@@ -1 +0,0 @@
1
- import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CZ4obM6q.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-Bm9wIpiI.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +0,0 @@
1
- import{assertScheduleInstant as A,assertScheduleDelay as v,resolveScheduleId as y}from"@lunora/scheduler";import{a as S}from"./wire-codec-CZ4obM6q.mjs";const m=new WeakMap,w=c=>{if(typeof c=="string")return c;const r=c??{},e=r.__lunoraRef??r.binding;return typeof e=="string"?e:"<unknown>"},x=c=>{let r=c;for(;r!==void 0&&!r.open;)r=r.parent;return r},D=(c,r,e)=>c==="runAfter"?Math.max(r,e-Date.now()):Math.max(r,e),k=(c,r)=>{const e=c,t={decisions:new Map,innermost:void 0,outbox:r},l=(n,i,o,s,d)=>e[n].call(e,i,o,s,d),u=(n,i,o,s,d)=>{const a=w(o);t.decisions.has(a)||t.decisions.set(a,t.outbox?.admit(a));const g=t.decisions.get(a),h=g===void 0?i:D(n,i,g),b=t.innermost;if(b===void 0)return l(n,h,o,s,d);const p=y(d?.id);return t.outbox?.record(p,{args:S(`ctx.scheduler.${n}`,w(o),s),options:d,target:o,when:Math.ceil(n==="runAfter"?Date.now()+h:h)}),b.pending.push({id:p,run:async()=>l(n,h,o,s,{...d,id:p})}),Promise.resolve(p)},f={...e,runAfter:(n,i,o,s)=>(v(n,"ctx.scheduler.runAfter"),u("runAfter",n,i,o,s)),runAt:(n,i,o,s)=>(A(n,Date.now(),"ctx.scheduler.runAt"),u("runAt",n,i,o,s))};return Object.setPrototypeOf(f,Object.getPrototypeOf(e)),m.set(f,t),f},q=c=>{const{scheduler:r}=c,e=typeof r=="object"&&r!==null?m.get(r):void 0;if(!e)return async()=>{};const t={open:!0,parent:e.innermost,pending:[]};return e.innermost=t,async l=>{if(!t.open)return;t.open=!1,e.innermost===t&&(e.innermost=x(t.parent));const u=t.pending.splice(0);if(u.length===0)return;if(!l){for(const{id:s}of u)e.outbox?.forget(s);return}const f=x(t.parent);if(f!==void 0){f.pending.push(...u);return}const n=[];for(const{id:s,run:d}of u)try{await d(),e.outbox?.forget(s)}catch(a){n.push(a)}const[i,...o]=n;if(i!==void 0)throw e.outbox?.wake(),o.length===0?i:new AggregateError(n,`ctx.scheduler: ${String(n.length)} of ${String(u.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{q as beginDeferredSchedules,k as withDeferredSchedules};
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{i as M}from"./wire-codec-CZ4obM6q.mjs";const b=new Set(["connect","disconnect","set"]),y=500,I=(t,n,s)=>t!==void 0&&Object.hasOwn(t,n)&&M(s),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},O=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,s)=>{n.through===void 0&&E(t,n,s)},k=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:O(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=e===void 0?[]:O(e,`${t}.connect`),r=i===void 0?[]:O(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},j=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!b.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):k(n,s,i)},W=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},$=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},R=async(t,n,s,e,i)=>{const c=await t.get(i,e);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},_=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await R(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},F=async(t,{info:n,name:s},e,i)=>{(await R(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(e,{[n.field]:i},n.table)},U=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(String(s._id),{[n.field]:null},n.table)},V=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},w=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},C=async(t,n,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},P=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>R(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await w(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await w(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await w(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await C(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>R(t,i,"connect",e.table,h)));for(const h of d)await t.delete(String(h._id),a);for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>R(t,n.name,"disconnect",n.info.table,c)));else{const c=await V(t,n,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await U(t,n,c,s);for(const c of e)await F(t,n,c,s)},S=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await P(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},x=(t,n,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(s,n))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await _(t,c),r=await i(a);return r!==null&&await S(t,n,c,x(t,n,r,a)),r},m=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(e,c.columns,n);return}const a=await _(t,c);if(Object.keys(a).length>0)await t.patch(e,a,n);else{if(await t.get(e,n)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(e,n)}await S(t,n,c,x(t,n,e,a))},G=(t,n,s,e)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=s[a]}return c},X=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>m(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=G(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(o,n),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(o,d,n)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const h=o;return t.deleteWhere(n,h.where,{limit:h.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(o,n),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(o,n,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const h of o)$(n,e,h,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)$(n,e,l,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(o.map(l=>({id:l.id,patch:l.values})),d,n)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>($(n,e,d,"replace"),t.replace(o,d,n)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(o,n)},upsert:r,upsertMany:async({rows:o,target:d})=>{const h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},z=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{z as bindOrm,X as bindTableFacade};
@@ -1,5 +0,0 @@
1
- import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{e as x}from"./wire-codec-CZ4obM6q.mjs";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const U=e=>async r=>e(r.get("lunora"),r.req.raw),J=()=>{const e=new q;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},C=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=C(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},L=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(r===void 0?x(e):e);return`${r?`event: ${r}
2
- `:""}data: ${o}
3
-
4
- `},D=(e,r)=>(async o=>{const n=A(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},a=Object.keys(e.params).length>0?T(e.params,o):{}}catch(m){return j(m)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const f=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const y=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const p of y){if(s.signal.aborted)break;m.enqueue(h.encode(b(e.output?k(e.output,p):p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(y){const{body:p,redacted:P}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});P&&console.error("[lunora] unhandled stream handler error:",y),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,message:p.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>L(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>D(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),Q={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},W=e=>!(e.includes("\r")||e.includes(`
5
- `)||e.includes("\0"));export{U as httpAction,Q as httpRoute,J as httpRouter,W as isSafeHeaderValue};
@@ -1 +0,0 @@
1
- import{LunoraError as w,isLunoraError as ue}from"@lunora/errors";import{findRelated as he,whereFilter as ye}from"@lunora/shard-engine";import{i as $}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as pe,bindOrm as we}from"./bindOrm-BHq_oUP2.mjs";import{t as ge}from"./policy-tag-V0lqFzgS.mjs";import{deny as Oe}from"./allowAll-DkRAgItV.mjs";const z=4;class m extends Error{}const j=e=>e.includes("."),ft=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},V=e=>{const t=e.split(".");if(t.length>z||t.includes(""))throw new m(`field path "${e}" must have 1 to ${String(z)} non-empty segments`);return t},be=(e,t)=>{if(!j(t))return e[t];let r=e;for(const s of V(t)){if(!$(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ee=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new m(`field path "${s}" is empty`);if(e!=null&&!$(e))throw new m(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const f=e??{};return{...f,[a]:l.length===0?r:ee(f[a],l,r,s)}},ve=(e,t)=>{const r=Object.keys(e).filter(a=>j(a));if(r.length===0)return e;for(const a of r){const l=r.find(f=>f!==a&&f.startsWith(`${a}.`));if(l!==void 0)throw new m(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))j(a)||(s[a]=l);for(const a of r){const[l="",...f]=V(a);if(Object.hasOwn(e,l))throw new m(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=ee(Object.hasOwn(s,l)?s[l]:t[l],f,e[a],a)}return s},Re=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},We=["every","is","isNot","none","some"],Ee=new Set(We),Ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Ee.has(r))},X=(e,t,r)=>t?{[e]:r(t)}:{},H={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const te=e=>{if(!$(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(H,r)))return{operand:e[r],operator:r}},ke=e=>te(e)!==void 0,Se=(e,t,r,s)=>{const a=H[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},ne=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&ke(a)&&r.add(s);return r},Be=(e,t,r)=>{let s;for(const a of ne(e,r)){const{operand:l,operator:f}=te(e[a]),b=r(a);if(H[f].kind!==b)throw new R(`patch: "${f}" does not apply to the ${String(b)} column "${a}".`);s??={...e},s[a]=Se(a,f,l,t[a])}return s??e},Pe=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of ne(e,r))try{Object.assign(s,Be({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return ve(s,t)}catch(a){if(a instanceof m)return s;throw a}},Ie=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,P=0,W=1,T=e=>e?W:B,g=(e,t)=>e<t?e:t,_e=(e,t)=>e>t?e:t,re=e=>e===P?P:T(e===B),G=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},I=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new w("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},me={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Te=(e,t,r)=>{let s=W;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];F(e,a,l);const f=j(e);if(f?Re(l)===void 0:!G(l))s=g(s,B);else if(I(t))s=g(s,P);else{const b=me[a],p=f?typeof t==typeof l:G(t);s=g(s,T(p&&b(t,l)))}}return s},J=(e,t,r)=>{if(!Array.isArray(r))throw new w("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new w("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},Z=(e,t)=>t.length===0?B:I(e)?P:t.includes(e)?W:t.some(r=>I(r))?P:B,$e=(e,t,r)=>{let s=W;if("in"in r&&(s=g(s,Z(t,J(e,"in",r.in)))),"notIn"in r&&(s=g(s,re(Z(t,J(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),s=I(t)?g(s,P):g(s,T(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=g(s,T(r.isNull===!0===I(t)))),s},Y=(e,t,r)=>t===null?T(r===I(e)):I(e)?P:T(r===(e===t)),De=(e,t,r)=>{let s=W;return"eq"in r&&(F(e,"eq",r.eq),s=g(s,Y(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),s=g(s,Y(t,r.ne,!1))),s},Me=(e,t,r)=>g(De(e,t,r),g($e(e,t,r),Te(e,t,r))),Fe=(e,t,r,s)=>{if(t==="NOT")return re(s(e,r??{}));if(!Array.isArray(r))return B;let a=t==="AND"?W:B;for(const l of r){const f=s(e,l);a=t==="AND"?g(a,f):_e(a,f)}return a},oe=e=>e==="AND"||e==="OR"||e==="NOT",Le=e=>$(e)&&Object.keys(e).every(t=>Ie.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return oe(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(s=>q(s??{})):Ae(r)}),se=(e,t)=>{let r=W;for(const s of Object.keys(t)){const a=t[s];if(oe(s)){r=g(r,Fe(e,s,a,se));continue}const l=be(e,s);if(Le(a)){r=g(r,Me(s,l,a));continue}F(s,"eq",a),r=g(r,Y(l,a,!0))}return r},N=(e,t)=>se(e,t)===W,ie=500,_=(e,t,r)=>{const s=t??ie;if(e>s)throw new w("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},Ce=Oe(),Ue=Symbol.for("lunora.ctxdb.rls-unwrap"),ae=Symbol.for("lunora.rls.wrapped-chain"),je=e=>e[ae],qe=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Ne=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?Ce:r.length===1?r[0]:{OR:r}},Ye=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(q(s))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return N(r,s)},xe=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Ye(e,t,r);if(s===!1)return!1;if(q(s))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!N(t.row,s)?!1:r===void 0||N(r,s)},He=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!xe(l,r,s)))return!1;return a},Ke=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Qe=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":$(t),ze=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ke.has(r)&&Qe(r,e[r]))},Xe=e=>e===void 0?{}:$(e)&&ze(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,Ge=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,Je=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},Ze=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,f=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const u of r){const h=u.perTable.get(n);if(!h||h.length===0||!h.some(M=>M.on==="read"))continue;c=!0;const y=Ne(h,u.context);y!==void 0&&i.push(y)}const d={baseWhere:Ge(i),restricts:c};return l.set(n,d),d},b=(n,o,i,c)=>{for(const d of r){const u=d.perTable.get(n);if(u&&!He(u,o,{...d.context,row:i},c))return!1}return!0},p=n=>f(n).restricts?t:e,O=n=>f(n).baseWhere,E=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const d=o??i,u=d===void 0?[...a.keys()]:[d].filter(y=>a.has(y)),h=await Promise.all(u.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:h.find(y=>y!==void 0)}},L=async(n,o,i)=>{const c=await E(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},A=async(n,o,i,c,d,u)=>{const h=await L(n,d,u);if(!h)return i(e);const y=c?c(h.row):void 0;if(!b(h.tableName,o,h.row,y))throw new w("FORBIDDEN",`${o} denied by policy`);return i(t,h.tableName)},C=async(n,o,i)=>{const c=await L(n,o);if(!c)return!1;if(!b(o,"delete",c.row))throw new w("FORBIDDEN","delete denied by policy");return await t.delete(n,o,i),!0},D=async(n,o,i)=>{const c=a.has(n),d=c?t:e,u=i===void 0?void 0:{hard:i},h=c&&e.deleteRereadTables?.has(n)===!0;let y=0;for(const M of o){const Q=String(M._id);if(h){await C(Q,n,u)&&(y+=1);continue}if(c&&!b(n,"delete",M))throw new w("FORBIDDEN","delete denied by policy");await d.delete(Q,n,u),y+=1}return y},k=(n,o,i,c)=>A(n,"update",(d,u)=>i(d,{verify:u===void 0?void 0:(h,y)=>b(u,"update",h,y)}),d=>({...d,...Pe(o,d)}),c),U=(n,o)=>{const{baseWhere:i}=f(n);if(x(i))throw new w("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},le=e.rankBefore,fe=e.rankPageRows,{relationEdges:K}=e,S={...e,async count(n,o){const{baseWhere:i}=f(n),c=Xe(o);return p(n).count(n,{...c,baseWhere:v(c.baseWhere,i),relationBaseWhere:O,restrictsCounts:(c.restrictsCounts??!1)||x(i)})},delete:(n,o,i)=>A(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??ie),{baseWhere:c}=f(n);let d=0;for(;;){const u=await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:O}),{page:h}=u;if(h.length===0||(d+=await D(n,h,o?.hard),h.length<i))break}return{deleted:d}},async deleteMany(n,o,i){_(n.length,o?.limit,"deleteMany");for(const c of n)await A(c,"delete",d=>d.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=f(n),d=await p(n).findMany(n,{baseWhere:v(o,c),relationBaseWhere:O}),u=d.page.map(h=>String(h._id));return _(u.length,i?.limit,"deleteWhere"),{deleted:await D(n,d.page)}},async findFirst(n,o){const{baseWhere:i}=f(n);return p(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:O})},async findFirstOrThrow(n,o){const{baseWhere:i}=f(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:O})},async explain(n,o){const{baseWhere:i}=f(n);return p(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:O})},async findMany(n,o){const{baseWhere:i}=f(n);return p(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:O})},async get(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:d}=f(i.tableName);if(!d)return e.get(n,o);if(!c)return i.row;const u=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return u?._id===n?u:null},async lookupById(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0||!f(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=f(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const d=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!b(n,"insert",o))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(_(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(_(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>k(n,o,(c,d)=>c.patch(n,o,i,d),i),assertPatchAllowed:(n,o)=>k(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await k(o,i.patch,async(u,h)=>{if(u.patchIf===void 0)throw new w("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return u.patchIf(n,o,{...i,verify:h.verify})},n);return c.doc===null||await S.get(o,n).then(u=>u!==null,u=>{if(ue(u)&&u.code==="RLS_REQUIRED")return!1;throw u})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){_(n.length,o?.limit,"patchMany");for(const c of n)await k(c.id,c.patch,(d,u)=>d.patch(c.id,c.patch,i,u),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=f(n),u=(await p(n).findMany(n,{baseWhere:v(o.where,c),relationBaseWhere:O})).page.map(h=>({id:String(h._id),patch:o.patch}));return _(u.length,i?.limit,"patchWhere"),S.patchMany(u,i)},query(n){const{baseWhere:o}=f(n),i=p(n).query(n);return o?i.filter(ye(o,c=>N(c,o))):i},related:K===void 0?void 0:async(n,o)=>he({findMany:async(i,c)=>S.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},K,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new w("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>A(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=f(n);return p(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:O})},groupBy(n,o){const{baseWhere:i}=f(n);return p(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:O})},rank(n,o,i){return U(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return U(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new w("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...X("rankBefore",le,n=>(o,i,c)=>(U(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...X("rankPageRows",fe,n=>(o,i,c)=>(U(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))},de=S;if(a.size>0)for(const[n,o]of Object.entries(e))Je(o)&&(de[n]=pe(S,n));return Object.defineProperty(S,ae,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),S},ce=e=>typeof e=="string"?e:e.name,Ve=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>ce(s))));return t},et=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(ce(s))},tt=["roles","role"],nt=e=>{for(const t of tt){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},rt=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...nt(r),...e.roles??[]])];return{can:et(s,t),identity:r,roles:s,userId:e.userId??null}},dt=(e,t={})=>{const r=e,s=qe(r),a=Ve(t.roles);return ge(async({ctx:f,next:b})=>{const p={auth:await rt(f.auth??{},a),ctx:f},O=f.db,E=je(O),L=E?.base??O,A=E?.raw??O[Ue]??O,C=Ze(L,A,[...E?.steps??[],{context:p,perTable:s}]),D={db:C},{orm:k}=f;return k!==null&&typeof k=="object"&&(D.orm=we(C)),b({ctx:D})},[{policies:r,roles:t.roles??[]}])};export{rt as a,Je as b,ft as c,Ae as d,nt as e,Ne as f,et as g,He as h,Ve as i,N as m,X as o,dt as r};
@@ -1 +0,0 @@
1
- import{f as e,F as o,a as c}from"./fnv1a-D3ueNTWB.mjs";import{s as f}from"./stable-key-B_BlboiY.mjs";const l=r=>`${e(r,o)}${e(r,c)}`,m=(r,i)=>({args:{},handler:async(a,s)=>{const n=await r(a),t=l(f(n));return t===s?.previousDigest?{digest:t,ran:!1}:(await i(a,n),{digest:t,ran:!0})},kind:"mutation",lifecycle:"reactor",visibility:"internal"});export{m as onQueryChange};
@@ -1 +0,0 @@
1
- import{f as i,h as m,i as l,b as p,m as d,e as h,g as n,a as c,r as u}from"./middleware-BN0Q7fMj.mjs";import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-BHq_oUP2.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,p as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,c as resolvePolicyAuth,u as rls};
@@ -1 +0,0 @@
1
- const a=/["\\\u0000-\u001F\uD800-\uDFFF]/,f=t=>a.test(t)?JSON.stringify(t):`"${t}"`,y=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return f(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let r="[";for(let n=0;n<t.length;n++)n>0&&(r+=","),r+=y(t[n]);return r+"]"}const i=Object.getPrototypeOf(t);if(i!==null&&i!==Object.prototype){const r=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const o=t,c=Object.keys(o).sort();let e="{",s=!0;for(const r of c){const n=o[r];n!==void 0&&(s?s=!1:e+=",",e+=f(r),e+=":",e+=y(n))}return e+"}"};export{y as s};
@@ -1 +0,0 @@
1
- const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},A=e=>{const t=atob(e),c=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)c[o]=t.codePointAt(o)??0;return c},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const c=typeof e;if(c==="bigint"){const r=e.toString();if(r.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[i,"bigint",r]}if(c==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(c!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n=u(Object.fromEntries(Object.keys(r).map(a=>[a,r[a]])),t+1),s=[i,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(u(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(s)]:[i,"bytes",m(s),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=u(n,t+1);r===w?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(p,r)?p[r]:void 0)??Error,a=new s(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const b=y(e[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(b))d===w?Object.defineProperty(a,d,{configurable:!0,enumerable:!0,value:b[d],writable:!0}):a[d]=b[d];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=A(r);if(m(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const a=Object.hasOwn(g,s)?g[s]:void 0;return a?new a(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const c=e,o={};for(const f of Object.keys(c)){const r=y(c[f],t+1);f===w?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o},E=(e,t,c)=>{try{return u(c)}catch(o){throw new TypeError(`${e}: cannot encode args for '${t}' — ${o instanceof Error?o.message:String(o)}`,o instanceof Error?{cause:o}:void 0)}};export{E as a,y as d,u as e,l as i};