@lunora/server 1.0.0-alpha.1 → 1.0.0-alpha.100

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 (83) hide show
  1. package/LICENSE.md +219 -0
  2. package/README.md +51 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/data-model.d.mts +324 -140
  5. package/dist/data-model.d.ts +324 -140
  6. package/dist/data-model.mjs +0 -1
  7. package/dist/drizzle.mjs +1 -1
  8. package/dist/index.d.mts +2917 -1356
  9. package/dist/index.d.ts +2917 -1356
  10. package/dist/index.mjs +1 -24
  11. package/dist/otel.d.mts +543 -0
  12. package/dist/otel.d.ts +543 -0
  13. package/dist/otel.mjs +1 -0
  14. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-JWV1BkYm.mjs +1 -0
  15. package/dist/packem_shared/DEFAULT_LIMIT-DC-M6faS.mjs +1 -0
  16. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-Lxhp5uwN.mjs +1 -0
  17. package/dist/packem_shared/LunoraEnvError-BurH8oOM.mjs +3 -0
  18. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs +1 -0
  19. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  20. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  21. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  22. package/dist/packem_shared/beginDeferredSchedules-gJlbW6h9.mjs +1 -0
  23. package/dist/packem_shared/bindOrm-ChQydkdL.mjs +1 -0
  24. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  25. package/dist/packem_shared/buildRlsReadRegistry-De9fP25P.mjs +1 -0
  26. package/dist/packem_shared/compose-middleware-3i5Qk3sb.mjs +1 -0
  27. package/dist/packem_shared/composePluginMiddleware-pe7Ncehp.mjs +1 -0
  28. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  29. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  30. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  31. package/dist/packem_shared/defineAggregateIndex-DFVCeuX1.mjs +1 -0
  32. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  33. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  34. package/dist/packem_shared/defineMutator-DKy8UtbB.mjs +1 -0
  35. package/dist/packem_shared/defineShape-BWgwFuMT.mjs +1 -0
  36. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  37. package/dist/packem_shared/flushDeferredDeletes-DEJXlhop.mjs +1 -0
  38. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  39. package/dist/packem_shared/functions-B2-H4PQT.mjs +1 -0
  40. package/dist/packem_shared/httpAction-CF2zTm9X.mjs +5 -0
  41. package/dist/packem_shared/initLunora-D5TSiy5j.mjs +1 -0
  42. package/dist/packem_shared/mask-D6hJ86fP.mjs +1 -0
  43. package/dist/packem_shared/middleware-BXIVIudl.mjs +1 -0
  44. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  45. package/dist/packem_shared/onQueryChange-CatdYnH5.mjs +1 -0
  46. package/dist/packem_shared/plugin-yKCbHnlj.mjs +1 -0
  47. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  48. package/dist/packem_shared/protectPublic-Csf6ObbJ.mjs +1 -0
  49. package/dist/packem_shared/rls-BVJokL_k.mjs +1 -0
  50. package/dist/packem_shared/run-middleware-CuM-Chm3.mjs +1 -0
  51. package/dist/packem_shared/serveStorageObject-Cof46mpm.mjs +1 -0
  52. package/dist/packem_shared/stable-key-B_BlboiY.mjs +1 -0
  53. package/dist/packem_shared/storageRules-BYT8_Re0.mjs +1 -0
  54. package/dist/packem_shared/types.d-B7FLdYUD.d.mts +148 -0
  55. package/dist/packem_shared/types.d-BCtjbIzl.d.ts +148 -0
  56. package/dist/packem_shared/wire-codec-BfIZrTJe.mjs +1 -0
  57. package/dist/rls/testing.d.mts +42 -34
  58. package/dist/rls/testing.d.ts +42 -34
  59. package/dist/rls/testing.mjs +1 -49
  60. package/dist/types.d.mts +1798 -439
  61. package/dist/types.d.ts +1798 -439
  62. package/dist/types.mjs +1 -31
  63. package/package.json +18 -5
  64. package/dist/packem_shared/LunoraError-DhggBJZF.mjs +0 -51
  65. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  66. package/dist/packem_shared/bindTableFacade-DCuyr46L.mjs +0 -71
  67. package/dist/packem_shared/defineAggregateIndex-DzqxtAyV.mjs +0 -236
  68. package/dist/packem_shared/defineEnv-DjFkpkSP.mjs +0 -187
  69. package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
  70. package/dist/packem_shared/definePolicy-De67zPDS.mjs +0 -29
  71. package/dist/packem_shared/definePresence-D5LtwGl0.mjs +0 -114
  72. package/dist/packem_shared/defineSchemaExtension-Ck5_TUO8.mjs +0 -100
  73. package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
  74. package/dist/packem_shared/httpAction-B7FYUEgr.mjs +0 -340
  75. package/dist/packem_shared/initLunora-CATvPsVt.mjs +0 -86
  76. package/dist/packem_shared/mask-CkZJHHMM.mjs +0 -211
  77. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  78. package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
  79. package/dist/packem_shared/rls-Zhf5wEeJ.mjs +0 -551
  80. package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
  81. package/dist/packem_shared/storageRules-4a30FSpI.mjs +0 -88
  82. package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
  83. package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
@@ -0,0 +1 @@
1
+ import{LunoraError as t}from"@lunora/errors";const n=r=>{if(r.id.trim()==="")throw new t("INTERNAL","defineMigration: `id` must be a non-empty string");return{__lunoraMigration:!0,...r}};export{n as defineMigration};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{c as u}from"./context-identity-B2XYGA0B.mjs";import{v as c}from"./functions-B2-H4PQT.mjs";const w=(r,s,t)=>{if(r.trim()==="")throw new a("INTERNAL",'defineMutator: `owner` must name the column carrying the row owner (e.g. `owner: "userId"`)');const e=u(s);if(e===void 0)throw new a("UNAUTHORIZED","defineMutator: an owner-scoped mutator requires a verified identity; none was resolved for this request");const o=t,n=o[r];if(n!==void 0&&n!==e)throw new a("FORBIDDEN",`defineMutator: \`${r}\` does not match the verified identity — a mutator may only write rows its caller owns`);return o[r]=e,t},h=r=>({__lunoraMutator:!0,...r,handler:async(t,e)=>{const o=c(r.args??{},e),n=r.owner===void 0?o:w(r.owner,t,o);return r.server(t,n)},kind:"mutation"});export{h as defineMutator};
@@ -0,0 +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 d,deny as m}from"./allowAll-DkRAgItV.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,n,s)=>{const w=u(e.args??{},n),o=e.where?d(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?s?.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 h=p(a);if(h===void 0)return m();const l={[t]:h};return o===void 0?l:{AND:[l,o]}}}};export{I as defineShape};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";const s=n=>({bucket:n.bucket,on:n.on,prefix:n.prefix,when:n.when}),f=n=>{const t=new Map;for(const e of n){const o=JSON.stringify([e.bucket,e.on,e.prefix]),r=t.get(o)??new Set;if(r.has(e.when))throw new i("INTERNAL",`defineStorageRules: duplicate rule for (bucket "${e.bucket}", on "${e.on}"${e.prefix===void 0?"":`, prefix "${e.prefix}"`}) — the same decision function is registered more than once. Multiple distinct rules per (bucket, on) are allowed (they OR); remove the duplicate.`);r.add(e.when),t.set(o,r)}return n};export{s as defineStorageRule,f as defineStorageRules};
@@ -0,0 +1 @@
1
+ const l=new WeakMap,i=f=>{const a=[],o=n=>{const e=n??{},s={...e,deleteAfterCommit:r=>{a.push({key:r,storage:e})}};return Object.setPrototypeOf(s,Object.getPrototypeOf(e)),typeof e.bucket=="function"&&(s.bucket=r=>o(e.bucket?.(r))),l.set(s,a),s};return o(f)},u=async f=>{const{log:a,storage:o}=f??{},n=typeof o=="object"&&o!==null?l.get(o):void 0;if(!n||n.length===0)return{attempted:0,failures:[]};const e=n.splice(0),r=(await Promise.allSettled(e.map(async({key:t,storage:c})=>{if(typeof c.delete!="function")throw new TypeError("ctx.storage: no storage configured, so the object was not deleted");await c.delete(t)}))).flatMap((t,c)=>t.status==="rejected"?[{error:t.reason,key:e[c]?.key??""}]:[]);for(const t of r)a?.warn("ctx.storage.deleteAfterCommit: delete failed, object leaked",{error:String(t.error),key:t.key});return{attempted:e.length,failures:r}};export{u as flushDeferredDeletes,i as withDeferredDeletes};
@@ -0,0 +1 @@
1
+ const S=2166136261,n=16777619,o=(F,e=2166136261)=>{let t=e;for(let a=0;a<F.length;a+=1)t^=F.charCodeAt(a),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")};export{S as F,n as a,o as f};
@@ -0,0 +1 @@
1
+ import{parseValidatorMap as o}from"@lunora/values";const t=(a,r)=>o(a,r,"args");export{t as v};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as E,toErrorBody as O,isLunoraError as P}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as N}from"@lunora/values";import{Hono as _}from"hono";import{a as q}from"./apply-output-C5wZ5EAL.mjs";const V=e=>async r=>e(r.get("lunora"),r.req.raw),$=()=>{const e=new _;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},k=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}},x=(e,r,o)=>{const n=k(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)},v=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return R(e,o,"searchParams")},S=(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(k(a).kind,d)}return R(e,n,"params")},C=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")},T=e=>{if(e instanceof N)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(P(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},j=(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})},H=(e,r)=>async o=>{const n=j(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?v(e.searchParams,o):{},d=Object.keys(e.params).length>0?S(e.params,o):{},i=Object.keys(e.body).length>0?await C(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?q(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 p=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:p?c:void 0,status:204}):Response.json(s,{headers:p?c:void 0})}catch(t){return T(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(e);return`${r?`event: ${r}
2
+ `:""}data: ${o}
3
+
4
+ `},L=(e,r)=>(async o=>{const n=j(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?v(e.searchParams,o):{},a=Object.keys(e.params).length>0?S(e.params,o):{}}catch(m){return T(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 p=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const y of f){if(s.signal.aborted)break;m.enqueue(h.encode(b(y)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(f){const{body:y,redacted:A}=O(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});A&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(b({code:y.code,message:y.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(p,{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=>H(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=>L(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),U={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},J=e=>!(e.includes("\r")||e.includes(`
5
+ `)||e.includes("\0"));export{V as httpAction,U as httpRoute,$ as httpRouter,J as isSafeHeaderValue};
@@ -0,0 +1 @@
1
+ import{a as j}from"./apply-output-C5wZ5EAL.mjs";import{v as i}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as C}from"./policy-tag-V0lqFzgS.mjs";import{r as b}from"./run-middleware-CuM-Chm3.mjs";const h=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),y=(e,r)=>b(e,r,o=>o),M=(e,r,o,n,t)=>async(s,c)=>{const d=i(e,c),m=await y(r,h(s,t,d,r.length)),l=await o({args:d,ctx:m});return n?j(n,l):l},O=(e,r,o,n)=>(t,s,c)=>{const d=i(e,s);return(async function*(){const l=await y(r,h(t,n,d,r.length)),f=o({args:d,ctx:l,signal:c})[Symbol.asyncIterator]();try{for(;;){if(c.aborted)return;const p=await f.next();if(p.done||c.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>C(o));return r.length>0?{tags:r}:void 0},x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},u=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)u(o,r),u(n,r);x(e)}else if(e instanceof Set){for(const o of e)u(o,r);x(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},z=e=>u(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const t=g(r.middlewares),s=w(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:M(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{rls:t}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:z({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,t)=>{const s=g(r.middlewares),c=w(r.middlewares),d=t?.durable===!0?{}:t?.durable;return{args:r.args,...d?{durable:d}:{},...r.expose?{expose:r.expose}:{},handler:O(r.args,r.middlewares,n,r.meta),kind:"stream",...c?{maskedTables:c}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),H={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{H as initLunora};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-BXIVIudl.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-ChQydkdL.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},u=(e,i,a)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...a,column:y,row:e}));return d},j=(e,i,a)=>({...e,page:e.page.map(d=>u(d,i,a))}),D=(e,i,a,d)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${d}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,a)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,a)},collect:async()=>(await r.collect()).map(s=>u(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,a):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>u(c,n,a)),unique:async()=>{const o=await r.unique();return o?u(o,n,a):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);return f?{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}:{row:null,tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:u(t,s,a)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:u(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k))return l();const p=X(w.db,a,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of a)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as W}from"@lunora/errors";import{i as P}from"./wire-codec-BfIZrTJe.mjs";import{bindTableFacade as U,bindOrm as T}from"./bindOrm-ChQydkdL.mjs";import{t as j}from"./policy-tag-V0lqFzgS.mjs";import{deny as $}from"./allowAll-DkRAgItV.mjs";const N=["every","is","isNot","none","some"],q=new Set(N),Y=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const t=Object.keys(r);return t.length>0&&t.every(i=>q.has(i))},M=(r,t,i)=>t?{[r]:i(t)}:{},D=500,A=(r,t,i)=>{const a=t??D;if(r>a)throw new W("BATCH_LIMIT_EXCEEDED",`${i}: batch of ${String(r)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},K=$(),z=Symbol.for("lunora.ctxdb.rls-unwrap"),H=r=>{const t=new Map;for(const i of r){const a=t.get(i.table)??[];a.push(i),t.set(i.table,a)}return t},G=(r,t)=>{const i=[];let a=!1;for(const l of r){if(l.on!=="read")continue;const f=l.when(t);if(f!==void 0){if(f===!0){a=!0;break}f!==!1&&i.push(f)}}if(!a)return i.length===0?K:i.length===1?i[0]:{OR:i}},Q=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],p=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},X=(r,t)=>!("lt"in t&&(!p(r)||!p(t.lt)||r>=t.lt)||"lte"in t&&(!p(r)||!p(t.lte)||r>t.lte)||"gt"in t&&(!p(r)||!p(t.gt)||r<=t.gt)||"gte"in t&&(!p(r)||!p(t.gte)||r<t.gte)),J=(r,t)=>{if("in"in t){const i=t.in;if(!Array.isArray(i)||!i.includes(r))return!1}if("notIn"in t){const i=t.notIn;if(Array.isArray(i)&&i.includes(r))return!1}if("contains"in t){const i=t.contains;if(typeof r!="string"||typeof i!="string"||!r.includes(i))return!1}return!("isNull"in t&&t.isNull===!0!==(r==null))},Z=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:J(r,t)&&X(r,t),x=(r,t,i,a)=>t==="AND"?Array.isArray(i)&&i.every(l=>a(r,l)):t==="OR"?Array.isArray(i)&&i.some(l=>a(r,l)):!a(r,i??{}),m=r=>r==="AND"||r==="OR"||r==="NOT",V=r=>P(r)&&Object.keys(r).every(t=>Q.includes(t)),v=r=>Object.keys(r).some(t=>{const i=r[t];return m(t)?t==="NOT"?v(i??{}):Array.isArray(i)&&i.some(a=>v(a??{})):Y(i)}),B=(r,t)=>{for(const i of Object.keys(t)){const a=t[i];if(m(i)){if(!x(r,i,a,B))return!1;continue}const l=r[i];if(V(a)){if(!Z(l,a))return!1;continue}if(l!==a)return!1}return!0},ee=(r,t,i)=>{const a=r.when({...t,row:i});if(a===void 0||a===!0)return!0;if(a===!1)return!1;if(v(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return B(i,a)},re=(r,t,i)=>{const a=r.when(t);if(a===void 0||a===!0)return i===void 0||ee(r,t,i);if(a===!1)return!1;if(v(a))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||!B(t.row,a)?!1:i===void 0||B(i,a)},_=(r,t,i,a)=>{let l=!1;for(const f of r)if(f.on===t&&(l=!0,!re(f,i,a)))return!1;return l},te=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ne=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":P(t),se=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(i=>te.has(i)&&ne(i,r[i]))},ie=r=>r===void 0?{}:P(r)&&se(r)?r:{where:r},w=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},oe=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ae=(r,t,i,a)=>{const l=new Map,f=e=>{const n=l.get(e);if(n)return n;const s=i.get(e);if(!s||s.length===0||!s.some(u=>u.on==="read")){const u={baseWhere:void 0,restricts:!1};return l.set(e,u),u}const c={baseWhere:G(s,a),restricts:!0};return l.set(e,c),c},d=e=>f(e).restricts?t:r,y=e=>f(e).baseWhere,O=async(e,n)=>{if(t.lookupById){const h=await t.lookupById(e,n);return h?{row:h.row,tableName:i.has(h.tableName)?h.tableName:void 0}:{row:null,tableName:void 0}}const s=await t.get(e,n);if(!s)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],c=n===void 0?[...i.keys()]:o,u=await Promise.all(c.map(async h=>(await t.findFirst(h,{limit:1,where:{_id:e}}))?._id===e?h:void 0));return{row:s,tableName:u.find(h=>h!==void 0)}},I=async(e,n)=>{const s=await O(e,n);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},g=async(e,n,s,o,c)=>{const u=await I(e,c);if(!u)return s(r);const h=i.get(u.tableName);if(h){const R=o?o(u.row):void 0;if(!_(h,n,{...a,row:u.row},R))throw new W("FORBIDDEN",`${n} denied by policy`)}return s(t)},b=(e,n)=>{const{baseWhere:s,restricts:o}=f(e);if(o)throw new W("COUNT_RLS_UNSUPPORTED",`${n}() is not supported on "${e}" inside an RLS-restricted context`);return s},E=r.rankBefore,F=r.rankPageRows,k={...r,async count(e,n){const{baseWhere:s,restricts:o}=f(e),c=ie(n);return d(e).count(e,{...c,baseWhere:w(c.baseWhere,s),relationBaseWhere:y,restrictsCounts:(c.restrictsCounts??!1)||o})},delete:(e,n,s)=>g(e,"delete",o=>o.delete(e,n,s),void 0,n),async deleteAll(e,n){const s=Math.max(1,n?.chunkSize??D),{baseWhere:o}=f(e);let c=0;for(;;){const h=(await d(e).findMany(e,{baseWhere:o,limit:s,relationBaseWhere:y})).page.map(R=>String(R._id));if(h.length===0)break;for(const R of h)await g(R,"delete",S=>S.delete(R,void 0,n?.hard===void 0?void 0:{hard:n.hard})),c+=1;if(h.length<s)break}return{deleted:c}},async deleteMany(e,n,s){A(e.length,n?.limit,"deleteMany");for(const o of e)await g(o,"delete",c=>c.delete(o,s),void 0,s);return{deleted:e.length}},async deleteWhere(e,n,s){const{baseWhere:o}=f(e),u=(await d(e).findMany(e,{baseWhere:w(n,o),relationBaseWhere:y})).page.map(h=>String(h._id));return A(u.length,s?.limit,"deleteWhere"),k.deleteMany(u,s)},async findFirst(e,n){const{baseWhere:s}=f(e);return d(e).findFirst(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findFirstOrThrow(e,n){const{baseWhere:s}=f(e);return d(e).findFirstOrThrow(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findMany(e,n){const{baseWhere:s}=f(e);return d(e).findMany(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async get(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0)return r.get(e,n);const{baseWhere:o,restricts:c}=f(s.tableName);if(!c)return r.get(e,n);if(!o)return s.row;const u=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return u?._id===e?u:null},async lookupById(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0||!f(s.tableName).restricts)return await r.lookupById?.(e,n)??null;const{baseWhere:o}=f(s.tableName);if(!o)return{row:s.row,tableName:s.tableName};const c=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return c?._id===e?{row:c,tableName:s.tableName}:null},async insert(e,n){const s=i.get(e);if(s){if(!_(s,"insert",{...a,row:n}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insert(e,n)}return r.insert(e,n)},async insertMany(e,n,s){A(n.length,s?.limit,"insertMany");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertMany(e,n,s)}return r.insertMany(e,n,s)},async insertManyUnsafe(e,n,s){A(n.length,s?.limit,"insertManyUnsafe");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertManyUnsafe(e,n,s)}return r.insertManyUnsafe(e,n,s)},patch:(e,n,s)=>g(e,"update",o=>o.patch(e,n,s),o=>({...o,...n}),s),async patchMany(e,n,s){A(e.length,n?.limit,"patchMany");for(const o of e)await g(o.id,"update",c=>c.patch(o.id,o.patch,s),c=>({...c,...o.patch}),s);return{patched:e.length}},async patchWhere(e,n,s){const{baseWhere:o}=f(e),u=(await d(e).findMany(e,{baseWhere:w(n.where,o),relationBaseWhere:y})).page.map(h=>({id:String(h._id),patch:n.patch}));return A(u.length,s?.limit,"patchWhere"),k.patchMany(u,s)},query(e){const{baseWhere:n}=f(e),s=d(e).query(e);return n?s.filter(o=>B(o,n)):s},restore:(e,n)=>g(e,"update",async s=>{const o=s.restore??t.restore;if(!o)throw new W("BAD_REQUEST","restore is not supported by this writer");await o(e,n)},void 0,n),replace:(e,n,s)=>g(e,"update",o=>o.replace(e,n,s),o=>({...n,_creationTime:n._creationTime??o._creationTime,_id:o._id}),s),aggregate(e,n){const{baseWhere:s}=f(e);return d(e).aggregate(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},groupBy(e,n){const{baseWhere:s}=f(e);return d(e).groupBy(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},rank(e,n,s){const o=b(e,"rank");return d(e).rank(e,n,{...s,baseWhere:w(s.baseWhere,o)})},rankPage(e,n,s){const o=b(e,"rankPage");return d(e).rankPage(e,n,{...s,baseWhere:w(s?.baseWhere,o)})},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})},...M("rankBefore",E,e=>(n,s,o)=>(b(n,"rankBefore"),(d(n).rankBefore??e)(n,s,o))),...M("rankPageRows",F,e=>(n,s,o)=>{const c=b(n,"rankPageRows");return(d(n).rankPageRows??e)(n,s,{...o,baseWhere:w(o?.baseWhere,c)})})},L=k;if(i.size>0)for(const[e,n]of Object.entries(r))oe(n)&&(L[e]=U(k,e));return k},C=r=>typeof r=="string"?r:r.name,ce=r=>{const t=new Map;for(const i of r??[])t.set(i.name,new Set((i.permissions??[]).map(a=>C(a))));return t},fe=(r,t)=>{const i=new Set;for(const a of r)for(const l of t.get(a)??[])i.add(l);return a=>i.has(C(a))},le=["roles","role"],ue=r=>{for(const t of le){const i=r?.[t];if(typeof i=="string"){const a=i.split(",").map(l=>l.trim()).filter(l=>l.length>0);if(a.length>0)return a}if(Array.isArray(i)){const a=i.filter(l=>typeof l=="string"&&l.length>0);if(a.length>0)return a}}return[]},he=async(r,t)=>{const i=await r.getIdentity?.()??null,a=[...new Set([...ue(i),...r.roles??[]])];return{can:fe(a,t),identity:i,roles:a,userId:r.userId??null}},pe=(r,t={})=>{const i=H(r),a=ce(t.roles);return j(async({ctx:f,next:d})=>{const y={auth:await he(f.auth??{},a),ctx:f},O=f.db,I=O[z]??O,g=ae(O,I,i,y),b={db:g},{orm:E}=f;return E!==null&&typeof E=="object"&&(b.orm=T(g)),d({ctx:b})},[{policies:r,roles:t.roles??[]}])};export{he as a,oe as b,Y as c,ue as d,G as e,fe as f,_ as g,ce as i,B as m,M as o,C as p,pe as r};
@@ -0,0 +1 @@
1
+ const t=(n,c)=>({args:{},handler:(i,o)=>c(i,o),kind:"mutation",lifecycle:n,visibility:"internal"}),e=n=>t("connect",n),r=n=>t("disconnect",n),s=n=>t("init",n);export{e as onConnect,r as onDisconnect,s as onShardInit};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as K}from"./compose-middleware-3i5Qk3sb.mjs";import{v as R}from"@lunora/values";const j=["de","en","es","fr","it","nl","none","pt"],_=["native","portable"],z=e=>_.includes(e),H=e=>j.includes(e),q=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?q(t):e.kind},B=16,Q={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),X=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),F=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},le=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},l=[],f={},m=X(),b=[];let y={kind:"root"},$=!1,N=!1,k=!1,T=!1,L,M,A,O;const c={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return $=!0,c},get commitOrderedMode(){return $},externallyManaged(){return N=!0,c},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),c},get geoIndexes(){return r},global(i){return y={backend:i?.backend??"d1",kind:"global"},c},get isExternallyManaged(){return N},get isPublic(){return T},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),c},get indexes(){return o},memory(){return k=!0,c},get memoryMode(){return k},ownedBy(i){return L=i,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:F(i,a.sortBy),where:a.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(Q)),c},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>B)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(B)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!H(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${j.join(", ")})`);const{strategy:v}=a;if(v!==void 0&&!z(v))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${v}" (supported: ${_.join(", ")})`);return l.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(i){return y={field:i,kind:"shardBy"},c},get shardMode(){return y},get softDeleteMode(){return M},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=i,N=!0,c},softDelete(i){const a=i?.field??"deletedAt";return M={field:a},a in t||(t[a]=R.optional(R.number().nullable())),c},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),c},ttl(i,a){return A={after:a?.after,field:i},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(i,a){return b.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,name:a.index}),c}};return c},ce=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),ue=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},fe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:F(e,t.sortBy),where:t.where}),x=e=>({...e,extend(t){return x(C(e,t))},jurisdiction(t){return x(e)},rls(t){return x({...e,rlsMode:t})}}),U=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},V=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},Y=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},G=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=Y(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},J=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);G(t,r)}}},W=["_commitSeq","_creationTime","_id"],D="_commitSeq",Z=new Set(W),w=(e,t,n,r)=>{if(!(Z.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},p=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},P=e=>{for(const[t,n]of Object.entries(e))p(t,"index",n.indexes,r=>{for(const o of r.fields)w(t,r.name,o,n)}),p(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)w(t,r.name,o.field,n);for(const o of r.partitionBy??[])w(t,r.name,o,n)}),p(t,"geo index",n.geoIndexes,r=>{w(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},ee=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,ee);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},te=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ne=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,o]of Object.entries(n.shape))if(q(o)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},re=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(D))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${D}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},he=(e,t={},n={},r={})=>(U(e),V(e,n,r),J(e),re(e),ne(e),te(e),P(e),x({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,S=(e,t,n)=>n.has(e)?I(t,e):e,ae=(e,t,n,r)=>{const o=I(t,r),d=m=>m===""?o:S(m,t,n),u={};for(const[m,b]of Object.entries(e.relationMap))u[m]={...b,table:S(b.table,t,n)};const l=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},ge=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},oe=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),be=(e,t)=>({...oe(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),C=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=I(n,u);if(Object.hasOwn(o,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);o[f]=ae(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=I(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:S(l.table,n,r)}}return P(o),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},we=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=C(n,r.extension));return n},xe=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return K(t)};export{be as a,oe as b,xe as c,ue as d,fe as e,he as f,ge as g,le as h,ce as i,me as j,we as k,C as m,P as v};
@@ -0,0 +1 @@
1
+ const t=Symbol.for("lunora.rls.middleware-policies"),o=(e,r)=>(Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:r}),e),n=e=>e===null||typeof e!="function"&&typeof e!="object"?[]:e[t]??[];export{n as r,o as t};
@@ -0,0 +1 @@
1
+ import{c as t}from"./compose-middleware-3i5Qk3sb.mjs";const i=c=>{const e=[c.rateLimit,c.captcha,...c.use??[]].filter(r=>r!==void 0);return t(e)};export{i as protectPublic};
@@ -0,0 +1 @@
1
+ import{e as t,g as m,i as p,b as l,m as d,p as n,d as c,f as h,a as u,r as v}from"./middleware-BXIVIudl.mjs";import"./wire-codec-BfIZrTJe.mjs";import"./bindOrm-ChQydkdL.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";const w=async(s,c,i)=>{let a=-1;const e=async(r,t)=>{if(r<=a)throw new d("INTERNAL","middleware next() called multiple times");a=r;const n=s[r];return n?await n({ctx:t,next:(l=>e(r+1,l?.ctx?{...t,...l.ctx}:t))}):i(t)};return e(0,c)};export{w as r};
@@ -0,0 +1 @@
1
+ import{isSafeHeaderValue as l}from"./httpAction-CF2zTm9X.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(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 m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{i as y,a as R}from"./middleware-BXIVIudl.mjs";const U=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},v=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},N=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",v],["getUrl","read"],["head","read"],["store","write"]],$=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},A=(e,t)=>{const o=e.bucketName??"default",{bucket:c}=e;for(const s of new Set(t))if(!(s===o||typeof c=="function"&&$(c,s)))throw new b("INTERNAL",`storageRules: rule for bucket "${s}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${s}" 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 })\`.`)},S=(e,t={})=>{const o=y(t.roles);return async({ctx:c,next:s})=>{const g=await R(c.auth??{},o),w=(n,a,i)=>{const d=e.filter(r=>r.on===n&&r.bucket===i);if(d.length===0)return;const u={auth:g,ctx:c,key:a};if(!d.some(r=>U(r.prefix,a)&&r.when(u)===!0))throw new b("FORBIDDEN",`storage ${n} on "${a}" in bucket "${i}" denied by access rule`)},p=n=>{const a=n.bucketName??"default",i={bucketName:a};for(const[u,l]of N){const r=n[u];typeof r=="function"&&(i[u]=(...f)=>{const k=typeof f[0]=="string"?f[0]:"",m=typeof l=="function"?l(f):l;return w(m,k,a),r(...f)})}const{bucket:d}=n;return typeof d=="function"&&(i.bucket=u=>p(d(u))),i},h=c.storage;return h===void 0?s():(A(h,e.map(n=>n.bucket)),s({ctx:{storage:p(h)}}))}};export{S as storageRules};
@@ -0,0 +1,148 @@
1
+ import { WhereOf } from "../data-model.mjs";
2
+ /** Structural mirror of `@lunora/do`'s `WhereInput`. */
3
+ interface WhereInput {
4
+ [field: string]: unknown;
5
+ AND?: WhereInput[];
6
+ NOT?: WhereInput;
7
+ OR?: WhereInput[];
8
+ }
9
+ /** Operations a policy can gate. `read` covers `get`/`findMany`/`query`/`count`. */
10
+ type PolicyOperation = "delete" | "insert" | "read" | "update";
11
+ /**
12
+ * A policy's `when` decision:
13
+ *
14
+ * - `WhereInput`: a row-shape predicate. On reads it is AND-merged into every
15
+ * query against the table — the row is invisible unless it matches. On writes
16
+ * it is evaluated against the candidate document (`insert`) or the pre-write
17
+ * row (`update`/`delete`); a mismatch denies the write with
18
+ * `LunoraError("FORBIDDEN")`. Same operator set as the SQL compiler
19
+ * (`eq`/`ne`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte`/`isNull`/`contains` +
20
+ * `AND`/`OR`/`NOT`).
21
+ * - `true`: unrestricted. On reads no predicate is merged; on writes the row is
22
+ * allowed.
23
+ * - `false`: deny. On reads the table is forced to match zero rows (a sentinel
24
+ * predicate); on writes the operation throws `LunoraError("FORBIDDEN")`.
25
+ *
26
+ * Returning `undefined` opts this specific policy out (rare; useful when
27
+ * branching on `ctx.auth.roles`).
28
+ */
29
+ type PolicyDecision = WhereInput | boolean | undefined;
30
+ /**
31
+ * Relation-aware twin of {@link PolicyDecision}, parameterized over the
32
+ * generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
33
+ * read policy may now return a Prisma-style relation predicate (the
34
+ * `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
35
+ * authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
36
+ * `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
37
+ * addition to the `boolean`/`undefined` decisions. Used by the project-bound
38
+ * `definePolicy` from `createPolicyDsl`.
39
+ */
40
+ type PolicyDecisionOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = WhereOf<DM, REL, T> | boolean | undefined;
41
+ /**
42
+ * Relation-aware input for a project-bound `definePolicy` (see
43
+ * `createPolicyDsl`). `table` is constrained to a real table name and
44
+ * `when`'s return type is the table-specific {@link PolicyDecisionOf} — so an
45
+ * unknown table, a stray column, or a relation predicate naming a relation the
46
+ * table does not declare is a compile error rather than a silent runtime deny.
47
+ */
48
+ interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T extends keyof DM, Context = unknown, Identity = Record<string, unknown>> {
49
+ on: PolicyOperation;
50
+ table: T;
51
+ when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
52
+ }
53
+ /**
54
+ * Context handed to a policy. `auth.roles` is the per-request role list, read
55
+ * from the `roles` CLAIM on the resolved identity — a `string[]` or a
56
+ * comma-separated string returned by `WorkerOptions.resolveIdentity` (and
57
+ * validated by `defineIdentity(...)` at the worker's trust boundary). A
58
+ * resolver that forwards no `roles` claim yields no roles, so every
59
+ * role-branched policy is evaluated against `[]`. `auth.can`
60
+ * answers whether any of those roles grants a permission (see
61
+ * {@link Permission} / {@link RlsOptions}). `row` is present only on write
62
+ * policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
63
+ * pre-write row; for `insert` it is the candidate document. `ctx` is the full
64
+ * procedure context the middleware closed over.
65
+ */
66
+ interface PolicyContext<Context = unknown, Identity = Record<string, unknown>> {
67
+ readonly auth: {
68
+ /**
69
+ * `true` when any of the request's `roles` grants `permission` (passed
70
+ * by {@link Permission} object or its `name`). Always `false` when no
71
+ * roles were handed to the middleware (`rls(policies, { roles })`), or
72
+ * when none of the request's roles lists the permission.
73
+ */
74
+ readonly can: (permission: Permission | string) => boolean;
75
+ /**
76
+ * The resolved identity, typed to the `Identity` type parameter bound on
77
+ * `createPolicyDsl` — e.g. the app's `defineIdentity(...)` claim type via
78
+ * the `InferIdentity` helper; otherwise the untyped claim bag.
79
+ * `undefined`/`null` when the request is anonymous.
80
+ */
81
+ readonly identity?: Identity | null;
82
+ readonly roles: ReadonlyArray<string>;
83
+ readonly userId: null | string;
84
+ };
85
+ readonly ctx: Context;
86
+ readonly row?: Record<string, unknown>;
87
+ }
88
+ /** A registered policy as stored in the policy table. */
89
+ interface Policy<Context = unknown> {
90
+ readonly on: PolicyOperation;
91
+ readonly table: string;
92
+ readonly when: (context: PolicyContext<Context>) => PolicyDecision;
93
+ }
94
+ /**
95
+ * Input accepted by `definePolicy`. The branded result is the same
96
+ * shape; we keep the input/output split so callers can read JSDoc on the
97
+ * constructor without the type re-exposing `Policy` internals.
98
+ */
99
+ interface DefinePolicyInput<Context = unknown> {
100
+ on: PolicyOperation;
101
+ /** Logical table name the policy applies to. */
102
+ table: string;
103
+ /**
104
+ * Decision function. Returning a `WhereInput` (read only) AND-merges the
105
+ * predicate; `true` allows; `false` denies; `undefined` skips this policy.
106
+ *
107
+ * NOTE: `count()` is **unsupported** on a policy-restricted table — the
108
+ * reader throws `LunoraError("COUNT_RLS_UNSUPPORTED")` (422). This mirrors
109
+ * kitcn's documented behavior.
110
+ */
111
+ when: (context: PolicyContext<Context>) => PolicyDecision;
112
+ }
113
+ /**
114
+ * A named, abstract capability a policy can check with `ctx.auth.can(...)`,
115
+ * instead of branching on raw role strings. Declare one with
116
+ * `definePermission`; grant it to a role via {@link Role.permissions};
117
+ * register the roles with the middleware via {@link RlsOptions.roles}.
118
+ */
119
+ interface Permission {
120
+ readonly description?: string;
121
+ readonly name: string;
122
+ }
123
+ /**
124
+ * A role declaration. Roles are string labels the request carries in the
125
+ * `roles` claim of its resolved identity — `WorkerOptions.resolveIdentity`
126
+ * forwards every non-`userId` key verbatim, so a resolver returning
127
+ * `{ userId, roles: ["admin"] }` (or the comma-joined `"user,admin"` that
128
+ * better-auth's `admin()` plugin stores) is what puts them there. `permissions`
129
+ * lists the capabilities the role grants — at request time the middleware
130
+ * unions the permissions of every role in `ctx.auth.roles` so a policy can ask
131
+ * `ctx.auth.can(permission)` rather than enumerate roles.
132
+ */
133
+ interface Role {
134
+ readonly description?: string;
135
+ readonly name: string;
136
+ /** Permissions this role grants — by {@link Permission} object or bare name. */
137
+ readonly permissions?: ReadonlyArray<Permission | string>;
138
+ }
139
+ /**
140
+ * Options for the `rls(policies, options)` middleware. `roles` registers the
141
+ * role→permission grants that back `ctx.auth.can(...)`; a role not listed here
142
+ * grants no permissions (so `can` is conservative — it fails closed for
143
+ * unknown roles).
144
+ */
145
+ interface RlsOptions {
146
+ readonly roles?: ReadonlyArray<Role>;
147
+ }
148
+ export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, RlsOptions as b, Permission as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
@@ -0,0 +1,148 @@
1
+ import { WhereOf } from "../data-model.js";
2
+ /** Structural mirror of `@lunora/do`'s `WhereInput`. */
3
+ interface WhereInput {
4
+ [field: string]: unknown;
5
+ AND?: WhereInput[];
6
+ NOT?: WhereInput;
7
+ OR?: WhereInput[];
8
+ }
9
+ /** Operations a policy can gate. `read` covers `get`/`findMany`/`query`/`count`. */
10
+ type PolicyOperation = "delete" | "insert" | "read" | "update";
11
+ /**
12
+ * A policy's `when` decision:
13
+ *
14
+ * - `WhereInput`: a row-shape predicate. On reads it is AND-merged into every
15
+ * query against the table — the row is invisible unless it matches. On writes
16
+ * it is evaluated against the candidate document (`insert`) or the pre-write
17
+ * row (`update`/`delete`); a mismatch denies the write with
18
+ * `LunoraError("FORBIDDEN")`. Same operator set as the SQL compiler
19
+ * (`eq`/`ne`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte`/`isNull`/`contains` +
20
+ * `AND`/`OR`/`NOT`).
21
+ * - `true`: unrestricted. On reads no predicate is merged; on writes the row is
22
+ * allowed.
23
+ * - `false`: deny. On reads the table is forced to match zero rows (a sentinel
24
+ * predicate); on writes the operation throws `LunoraError("FORBIDDEN")`.
25
+ *
26
+ * Returning `undefined` opts this specific policy out (rare; useful when
27
+ * branching on `ctx.auth.roles`).
28
+ */
29
+ type PolicyDecision = WhereInput | boolean | undefined;
30
+ /**
31
+ * Relation-aware twin of {@link PolicyDecision}, parameterized over the
32
+ * generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
33
+ * read policy may now return a Prisma-style relation predicate (the
34
+ * `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
35
+ * authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
36
+ * `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
37
+ * addition to the `boolean`/`undefined` decisions. Used by the project-bound
38
+ * `definePolicy` from `createPolicyDsl`.
39
+ */
40
+ type PolicyDecisionOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = WhereOf<DM, REL, T> | boolean | undefined;
41
+ /**
42
+ * Relation-aware input for a project-bound `definePolicy` (see
43
+ * `createPolicyDsl`). `table` is constrained to a real table name and
44
+ * `when`'s return type is the table-specific {@link PolicyDecisionOf} — so an
45
+ * unknown table, a stray column, or a relation predicate naming a relation the
46
+ * table does not declare is a compile error rather than a silent runtime deny.
47
+ */
48
+ interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T extends keyof DM, Context = unknown, Identity = Record<string, unknown>> {
49
+ on: PolicyOperation;
50
+ table: T;
51
+ when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
52
+ }
53
+ /**
54
+ * Context handed to a policy. `auth.roles` is the per-request role list, read
55
+ * from the `roles` CLAIM on the resolved identity — a `string[]` or a
56
+ * comma-separated string returned by `WorkerOptions.resolveIdentity` (and
57
+ * validated by `defineIdentity(...)` at the worker's trust boundary). A
58
+ * resolver that forwards no `roles` claim yields no roles, so every
59
+ * role-branched policy is evaluated against `[]`. `auth.can`
60
+ * answers whether any of those roles grants a permission (see
61
+ * {@link Permission} / {@link RlsOptions}). `row` is present only on write
62
+ * policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
63
+ * pre-write row; for `insert` it is the candidate document. `ctx` is the full
64
+ * procedure context the middleware closed over.
65
+ */
66
+ interface PolicyContext<Context = unknown, Identity = Record<string, unknown>> {
67
+ readonly auth: {
68
+ /**
69
+ * `true` when any of the request's `roles` grants `permission` (passed
70
+ * by {@link Permission} object or its `name`). Always `false` when no
71
+ * roles were handed to the middleware (`rls(policies, { roles })`), or
72
+ * when none of the request's roles lists the permission.
73
+ */
74
+ readonly can: (permission: Permission | string) => boolean;
75
+ /**
76
+ * The resolved identity, typed to the `Identity` type parameter bound on
77
+ * `createPolicyDsl` — e.g. the app's `defineIdentity(...)` claim type via
78
+ * the `InferIdentity` helper; otherwise the untyped claim bag.
79
+ * `undefined`/`null` when the request is anonymous.
80
+ */
81
+ readonly identity?: Identity | null;
82
+ readonly roles: ReadonlyArray<string>;
83
+ readonly userId: null | string;
84
+ };
85
+ readonly ctx: Context;
86
+ readonly row?: Record<string, unknown>;
87
+ }
88
+ /** A registered policy as stored in the policy table. */
89
+ interface Policy<Context = unknown> {
90
+ readonly on: PolicyOperation;
91
+ readonly table: string;
92
+ readonly when: (context: PolicyContext<Context>) => PolicyDecision;
93
+ }
94
+ /**
95
+ * Input accepted by `definePolicy`. The branded result is the same
96
+ * shape; we keep the input/output split so callers can read JSDoc on the
97
+ * constructor without the type re-exposing `Policy` internals.
98
+ */
99
+ interface DefinePolicyInput<Context = unknown> {
100
+ on: PolicyOperation;
101
+ /** Logical table name the policy applies to. */
102
+ table: string;
103
+ /**
104
+ * Decision function. Returning a `WhereInput` (read only) AND-merges the
105
+ * predicate; `true` allows; `false` denies; `undefined` skips this policy.
106
+ *
107
+ * NOTE: `count()` is **unsupported** on a policy-restricted table — the
108
+ * reader throws `LunoraError("COUNT_RLS_UNSUPPORTED")` (422). This mirrors
109
+ * kitcn's documented behavior.
110
+ */
111
+ when: (context: PolicyContext<Context>) => PolicyDecision;
112
+ }
113
+ /**
114
+ * A named, abstract capability a policy can check with `ctx.auth.can(...)`,
115
+ * instead of branching on raw role strings. Declare one with
116
+ * `definePermission`; grant it to a role via {@link Role.permissions};
117
+ * register the roles with the middleware via {@link RlsOptions.roles}.
118
+ */
119
+ interface Permission {
120
+ readonly description?: string;
121
+ readonly name: string;
122
+ }
123
+ /**
124
+ * A role declaration. Roles are string labels the request carries in the
125
+ * `roles` claim of its resolved identity — `WorkerOptions.resolveIdentity`
126
+ * forwards every non-`userId` key verbatim, so a resolver returning
127
+ * `{ userId, roles: ["admin"] }` (or the comma-joined `"user,admin"` that
128
+ * better-auth's `admin()` plugin stores) is what puts them there. `permissions`
129
+ * lists the capabilities the role grants — at request time the middleware
130
+ * unions the permissions of every role in `ctx.auth.roles` so a policy can ask
131
+ * `ctx.auth.can(permission)` rather than enumerate roles.
132
+ */
133
+ interface Role {
134
+ readonly description?: string;
135
+ readonly name: string;
136
+ /** Permissions this role grants — by {@link Permission} object or bare name. */
137
+ readonly permissions?: ReadonlyArray<Permission | string>;
138
+ }
139
+ /**
140
+ * Options for the `rls(policies, options)` middleware. `roles` registers the
141
+ * role→permission grants that back `ctx.auth.can(...)`; a role not listed here
142
+ * grants no permissions (so `can` is conservative — it fails closed for
143
+ * unknown roles).
144
+ */
145
+ interface RlsOptions {
146
+ readonly roles?: ReadonlyArray<Role>;
147
+ }
148
+ export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, RlsOptions as b, Permission as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
@@ -0,0 +1 @@
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)},p=e=>{const t=atob(e),a=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)a[o]=t.codePointAt(o)??0;return a},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},A={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 a=typeof e;if(a==="bigint")return[i,"bigint",e.toString()];if(a==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(a!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n={};for(const f of Object.keys(r))r[f]!==void 0&&(n[f]=u(r[f],t+1));const c=[i,"error",r.name,r.message,n];return r.cause!==void 0&&c.push(u(r.cause,t+1)),c}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,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(c)]:[i,"bytes",m(c),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,s={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const c=u(n,t+1);r===w?Object.defineProperty(s,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):s[r]=c}return s},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":{if(e.length<3)throw new TypeError("wire-codec: malformed date — missing payload");return new Date(y(e[2],t+1))}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":return new URL(e[2]);case"error":{const r=e[2],n=e[3],c=(Object.hasOwn(A,r)?A[r]:void 0)??Error,f=new c(n);f.name!==r&&Object.defineProperty(f,"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(f,d,{configurable:!0,enumerable:!0,value:b[d],writable:!0}):f[d]=b[d];return e.length>5&&Object.defineProperty(f,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),f}case"bytes":{const r=p(e[2]),n=e[3]??"Uint8Array";if(n==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const c=Object.hasOwn(g,n)?g[n]:void 0;return c?new c(r.slice().buffer):r}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(s=>y(s,t+1))}const a=e,o={};for(const s of Object.keys(a)){const r=y(a[s],t+1);s===w?Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[s]=r}return o};export{y as d,u as e,l as i};
@@ -1,48 +1,56 @@
1
- import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-DmvyEMD6.mjs";
1
+ import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-B7FLdYUD.mjs";
2
2
  import "../data-model.mjs";
3
3
  /**
4
- * The slice of a request identity a policy reads. Mirrors the
5
- * `PolicyContext.auth` shape the middleware builds at request time — every
6
- * field is optional and defaults the same way the middleware defaults it
7
- * (`userId`/`identity` → `null`, `roles` → `[]`).
8
- */
4
+ * The slice of a request identity a policy reads. Mirrors the
5
+ * `PolicyContext.auth` shape the middleware builds at request time — every
6
+ * field is optional and defaults the same way the middleware defaults it
7
+ * (`userId`/`identity` → `null`, `roles` → the `roles` claim on `identity`).
8
+ *
9
+ * There is deliberately NO separate `roles` field: `auth.roles` is derived from
10
+ * the identity claims by the same `readIdentityRoles` the middleware uses, so
11
+ * the harness cannot set up a world the runtime is unable to produce. Give a
12
+ * role-branched policy its roles the way production does —
13
+ * `.as({ identity: { roles: ["admin"] }, userId: "u1" })`.
14
+ */
9
15
  interface TestIdentity {
10
- /** Raw identity claims a policy may branch on (`auth.identity.email`, …). */
16
+ /**
17
+ * Raw identity claims a policy may branch on (`auth.identity.email`, …).
18
+ * The `roles` claim (a `string[]` or a comma-separated string) is what
19
+ * populates `auth.roles` and backs `auth.can(...)`.
20
+ */
11
21
  identity?: Record<string, unknown> | null;
12
- /** Role labels the request carries; resolved to permissions via the harness `roles` registry. */
13
- roles?: ReadonlyArray<string>;
14
22
  /** The caller id (`auth.userId`); `null`/omitted is the anonymous caller. */
15
23
  userId?: null | string;
16
24
  }
17
25
  /** Options for {@link expectPolicy}. */
18
26
  interface ExpectPolicyOptions<Context = unknown> {
19
27
  /**
20
- * The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
21
- * for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
22
- * different context. Defaults to an empty object.
23
- */
28
+ * The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
29
+ * for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
30
+ * different context. Defaults to an empty object.
31
+ */
24
32
  ctx?: Context;
25
33
  /**
26
- * Role→permission grants backing `auth.can(...)` — the same registry passed
27
- * to `rls(policies, { roles })`. A role not listed here grants nothing, so
28
- * `can(...)` fails closed exactly as it does in production.
29
- */
34
+ * Role→permission grants backing `auth.can(...)` — the same registry passed
35
+ * to `rls(policies, { roles })`. A role not listed here grants nothing, so
36
+ * `can(...)` fails closed exactly as it does in production.
37
+ */
30
38
  roles?: ReadonlyArray<Role>;
31
39
  }
32
40
  /** A harness bound to one identity; answers can/cannot for an `(op, table, row)`. */
33
41
  interface BoundPolicyAssertion {
34
42
  /**
35
- * Would this identity be **allowed** the operation on `row`?
36
- *
37
- * - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
38
- * - `insert` — is the candidate `row` allowed by the insert policies?
39
- * - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
40
- *
41
- * A table with **no** policy in the list is unguarded → always `true`
42
- * (mirrors the middleware passing such tables through unwrapped). A table
43
- * that participates but declares no policy for the write `op` denies
44
- * (default-DENY), exactly as the middleware does.
45
- */
43
+ * Would this identity be **allowed** the operation on `row`?
44
+ *
45
+ * - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
46
+ * - `insert` — is the candidate `row` allowed by the insert policies?
47
+ * - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
48
+ *
49
+ * A table with **no** policy in the list is unguarded → always `true`
50
+ * (mirrors the middleware passing such tables through unwrapped). A table
51
+ * that participates but declares no policy for the write `op` denies
52
+ * (default-DENY), exactly as the middleware does.
53
+ */
46
54
  can: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
47
55
  /** Negation of {@link BoundPolicyAssertion.can} — reads more naturally in a denial test. */
48
56
  cannot: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
@@ -53,11 +61,11 @@ interface PolicyAssertion {
53
61
  as: (identity?: TestIdentity | null) => BoundPolicyAssertion;
54
62
  }
55
63
  /**
56
- * Build an in-process assertion harness over a policy set. Reuses the `rls()`
57
- * middleware's own evaluation primitives, so an assertion is faithful to
58
- * request-time behaviour by construction.
59
- * @param policies the policy list, typically from `definePolicies([...])`.
60
- * @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
61
- */
64
+ * Build an in-process assertion harness over a policy set. Reuses the `rls()`
65
+ * middleware's own evaluation primitives, so an assertion is faithful to
66
+ * request-time behaviour by construction.
67
+ * @param policies the policy list, typically from `definePolicies([...])`.
68
+ * @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
69
+ */
62
70
  declare const expectPolicy: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>, options?: ExpectPolicyOptions<Context>) => PolicyAssertion;
63
71
  export { BoundPolicyAssertion, ExpectPolicyOptions, PolicyAssertion, TestIdentity, expectPolicy };