@lunora/server 1.0.0-alpha.61 → 1.0.0-alpha.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-model.d.mts +10 -10
- package/dist/data-model.d.ts +10 -10
- package/dist/index.d.mts +281 -293
- package/dist/index.d.ts +281 -293
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-DmnVChTY.mjs → PRESENCE_DEFAULT_TTL_MS-Dyb1szd2.mjs} +1 -1
- package/dist/packem_shared/buildRlsReadRegistry-CE5k6akj.mjs +1 -0
- package/dist/packem_shared/{composePluginMiddleware-B9NyOR1k.mjs → composePluginMiddleware-ByhCqIGt.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-C3CMy5jn.mjs → defineAggregateIndex-BoiwhUKL.mjs} +1 -1
- package/dist/packem_shared/httpAction-BpEJYwzV.mjs +5 -0
- package/dist/packem_shared/initLunora-BadfSfpJ.mjs +1 -0
- package/dist/packem_shared/mask-Chnz8Z0H.mjs +1 -0
- package/dist/packem_shared/middleware-D9_39C5C.mjs +1 -0
- package/dist/packem_shared/plugin-184MITA3.mjs +1 -0
- package/dist/packem_shared/rls-CI2149Ve.mjs +1 -0
- package/dist/packem_shared/storageRules-6_G8JpCv.mjs +1 -0
- package/dist/packem_shared/{types.d-C4CMJK8x.d.mts → types.d-B-pIn8rE.d.mts} +2 -2
- package/dist/packem_shared/{types.d-DdYF8E18.d.ts → types.d-CdPDEjhz.d.ts} +2 -2
- package/dist/rls/testing.d.mts +1 -1
- package/dist/rls/testing.d.ts +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +21 -21
- package/dist/types.d.ts +21 -21
- package/package.json +4 -4
- package/dist/packem_shared/buildRlsReadRegistry-CA-aUi7I.mjs +0 -1
- package/dist/packem_shared/httpAction-C14NuF3V.mjs +0 -4
- package/dist/packem_shared/initLunora-DXCOVntr.mjs +0 -1
- package/dist/packem_shared/mask-DF7mtxQe.mjs +0 -1
- package/dist/packem_shared/optional-writer-override-CXXO30sZ.mjs +0 -1
- package/dist/packem_shared/plugin-CDBMGCeQ.mjs +0 -1
- package/dist/packem_shared/rls-tRDkICWZ.mjs +0 -1
- package/dist/packem_shared/storageRules-BptPZbi8.mjs +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{initLunora as t}from"./packem_shared/initLunora-
|
|
1
|
+
import{initLunora as t}from"./packem_shared/initLunora-BadfSfpJ.mjs";import{createSecrets as i}from"./packem_shared/createSecrets-CgVPiW2C.mjs";import{LunoraEnvError as f,defineEnv as s,redactSecrets as m}from"./packem_shared/LunoraEnvError-CgpI2Mm_.mjs";import{LunoraError as p}from"./packem_shared/LunoraError-LVhdU0Lo.mjs";import{bindOrm as c,bindTableFacade as l}from"./packem_shared/bindOrm-Bp9hsM2q.mjs";import{httpAction as u,httpRoute as S,httpRouter as g,isSafeHeaderValue as R,serveStorageObject as L}from"./packem_shared/httpAction-BpEJYwzV.mjs";import{defineIdentity as P}from"./packem_shared/defineIdentity-B7gfAgxx.mjs";import{onConnect as A,onDisconnect as I}from"./packem_shared/onConnect-CEtRmUpJ.mjs";import{DEFAULT_LIMIT as y,DEFAULT_MAX_LIMIT as M,clampLimit as _,defineListArgs as D}from"./packem_shared/DEFAULT_LIMIT-yHJ5O96W.mjs";import{defineMigration as k}from"./packem_shared/defineMigration-Bfpwxv2f.mjs";import{defineMutator as C}from"./packem_shared/defineMutator-BgpQ-xUo.mjs";import{c as N,H as O,d as U,a as W,X as w,Z as B,b as H,q as X,K as j,W as q,i as J,m as K}from"./packem_shared/plugin-184MITA3.mjs";import{PRESENCE_DEFAULT_TTL_MS as z,PRESENCE_TABLE as G,definePresence as Q,presenceExtension as Y}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Dyb1szd2.mjs";import{protectPublic as ee}from"./packem_shared/protectPublic-BhKewPqm.mjs";import{defineShape as oe}from"./packem_shared/defineShape-Ds8uNqzX.mjs";import{anyApi as ne}from"./types.mjs";import{cronJobs as ae}from"@lunora/scheduler";import{ValidationError as se,v as me}from"@lunora/values";import{allowAll as pe,deny as xe,isDeny as ce,toWhereInput as le}from"./packem_shared/allowAll-BnyNbJZT.mjs";import{asBucketStorage as ue}from"./packem_shared/asBucketStorage-BthCnWop.mjs";import{buildMaskRegistry as ge}from"./packem_shared/buildMaskRegistry-BCIzKxdK.mjs";import{buildRlsReadRegistry as Le,composeShapeReadWhere as he}from"./packem_shared/buildRlsReadRegistry-CE5k6akj.mjs";import{createPolicyDsl as be,definePermission as Ae,definePolicies as Ie,definePolicy as Te,defineRole as ye}from"./packem_shared/createPolicyDsl-sV1swpkD.mjs";import{defineStorageRule as _e,defineStorageRules as De}from"./packem_shared/defineStorageRule-BDu01PUn.mjs";import{mask as ke}from"./packem_shared/mask-Chnz8Z0H.mjs";import{c as Ce}from"./packem_shared/middleware-D9_39C5C.mjs";import{storageRules as Ne}from"./packem_shared/storageRules-6_G8JpCv.mjs";const e="0.0.0";export{y as DEFAULT_LIMIT,M as DEFAULT_MAX_LIMIT,f as LunoraEnvError,p as LunoraError,z as PRESENCE_DEFAULT_TTL_MS,G as PRESENCE_TABLE,e as VERSION,se as ValidationError,pe as allowAll,ne as anyApi,ue as asBucketStorage,c as bindOrm,l as bindTableFacade,ge as buildMaskRegistry,Le as buildRlsReadRegistry,_ as clampLimit,N as composePluginMiddleware,he as composeShapeReadWhere,be as createPolicyDsl,i as createSecrets,ae as cronJobs,O as defineAggregateIndex,U as defineComponent,s as defineEnv,P as defineIdentity,D as defineListArgs,k as defineMigration,C as defineMutator,Ae as definePermission,W as definePlugin,Ie as definePolicies,Te as definePolicy,Q as definePresence,w as defineRankIndex,ye as defineRole,B as defineSchema,H as defineSchemaExtension,oe as defineShape,_e as defineStorageRule,De as defineStorageRules,X as defineTable,j as defineVectorIndex,xe as deny,u as httpAction,S as httpRoute,g as httpRouter,q as indexFieldsFromSchema,t as initLunora,J as installPlugins,ce as isDeny,R as isSafeHeaderValue,ke as mask,K as mergeSchemaExtension,A as onConnect,I as onDisconnect,Y as presenceExtension,ee as protectPublic,m as redactSecrets,Ce as rls,L as serveStorageObject,Ne as storageRules,le as toWhereInput,me as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as t}from"@lunora/values";import{initLunora as E}from"./initLunora-
|
|
1
|
+
import{v as t}from"@lunora/values";import{initLunora as E}from"./initLunora-BadfSfpJ.mjs";import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";import{onDisconnect as q}from"./onConnect-CEtRmUpJ.mjs";import{b as v,q as R,d as _}from"./plugin-184MITA3.mjs";const D=3e4,y=4096,u="presence",h="present",c=`${u}_${h}`,M=v(u,{tables:{[h]:R({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"])}}),{mutation:b,query:L}=E.dataModel().create(),B=(l={})=>{const m=l.ttlMs??D,f=Math.max(0,Math.min(l.disconnectGraceMs??0,m)),w=b.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),i=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>y)throw new p("BAD_REQUEST",`presence data exceeds the ${String(y)}-byte limit`);const e=await s.db.query(c).withIndex("byRoomSession",n=>n.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==i)throw new p("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...i===void 0?{}:{userId:i}};return await(e?s.db.patch(e._id,a):s.db.insert(c,a)),{lastSeen:r}}),S=L.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,i=(await s.db.query(c).withIndex("byRoom",n=>n.eq("roomId",o.roomId)).collect()).filter(n=>n.lastSeen>r).toSorted((n,d)=>d.lastSeen-n.lastSeen),e=new Set,a=[];for(const n of i){const d=n.userId;if(d!==void 0){if(e.has(d))continue;e.add(d)}const I={lastSeen:n.lastSeen,roomId:n.roomId};d!==void 0&&(I.userId=d),n.data!==void 0&&(I.data=n.data),a.push(I)}return a}),g={...b.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,i=await s.db.query(c).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(i.map(e=>s.db.delete(e._id))),{deleted:i.length}}),visibility:"internal"},x=q(async(o,s)=>{const r=s.context?.roomId,i=s.context?.sessionId;if(typeof r!="string"||typeof i!="string")return;const e=await o.db.query(c).withIndex("byRoomSession",d=>d.eq("roomId",r).eq("sessionId",i)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const n=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:n})});return _(u,{extension:M,functions:{disconnect:x,heartbeat:w,listPresent:S,sweep:g}})};export{D as PRESENCE_DEFAULT_TTL_MS,c as PRESENCE_TABLE,B as definePresence,M as presenceExtension};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{T as h,E as f,F as u}from"./middleware-D9_39C5C.mjs";import{l as d}from"./policy-tag-Dprt9JWo.mjs";import{deny as b}from"./allowAll-BnyNbJZT.mjs";const a=b(),p=t=>{const e=t?.rls?.tags;if(e)return e;const o=d(t);return o?[o]:[]},g=(t,e)=>{const o=h(e.roles),r=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const i=r.get(s.table)??new Set;if(i.has(s.when))continue;i.add(s.when),r.set(s.table,i);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,i]of n){const l=t.get(s)??[];l.push({policies:i,rolePermissions:o}),t.set(s,l)}},c=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},y=(t,e)=>!t||Object.keys(t).length===0?e:c(t)||Object.keys(e).length===0?t:{AND:[t,e]},m=(t,e)=>f(t.policies,{auth:{can:u(e.roles,t.rolePermissions),identity:e.identity,roles:e.roles,userId:e.userId},ctx:e.ctx}),w=(t,e)=>{const o=t.byTable.get(e.table);if(!o||o.length===0)return e.rlsRequired&&!e.tablePublic?a:void 0;const r=[];for(const n of o){const s=m(n,e);if(s===void 0)return;c(s)||r.push(s)}return r.length===0?a:r.length===1?r[0]:{OR:r}},j=t=>{const e=new Map,o=new Set;for(const r of t)for(const n of p(r))o.has(n)||(o.add(n),g(e,n));return{byTable:e}},k=(t,e)=>y(w(t,e),e.shapeWhere);export{j as buildRlsReadRegistry,k as composeShapeReadWhere};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import"./run-middleware-BeEEqmdE.mjs";import{c as s,d as o,a as m,b as t,i as d,m as l}from"./plugin-
|
|
1
|
+
import"@lunora/errors";import"./run-middleware-BeEEqmdE.mjs";import{c as s,d as o,a as m,b as t,i as d,m as l}from"./plugin-184MITA3.mjs";export{s as composePluginMiddleware,o as defineComponent,m as definePlugin,t as defineSchemaExtension,d as installPlugins,l as mergeSchemaExtension};
|
package/dist/packem_shared/{defineAggregateIndex-C3CMy5jn.mjs → defineAggregateIndex-BoiwhUKL.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import{
|
|
1
|
+
import"@lunora/errors";import{H as n,X as s,Z as r,q as f,K as m,W as o,O as t}from"./plugin-184MITA3.mjs";import"@lunora/values";export{n as defineAggregateIndex,s as defineRankIndex,r as defineSchema,f as defineTable,m as defineVectorIndex,o as indexFieldsFromSchema,t as validateIndexFields};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{toErrorBody as k}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as v}from"@lunora/values";import{Hono as _}from"hono";import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";const H=e=>async r=>e(r.get("lunora"),r.req.raw),z=()=>{const e=new _;return e.use("*",async(r,t)=>{const a=r.env.__lunoraCtx;if(!a)throw new p("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",a),await t()}),e},N=e=>e.kind==="optional"?e._meta?.inner??e:e,f=(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}},A=(e,r,t)=>{const a=N(e);if(a.kind==="array"){const o=r.req.queries(t);if(o===void 0)return;const n=a._meta?.inner;return o.map(c=>f(n?.kind??"string",c))}const s=r.req.query(t);return s===void 0?void 0:f(a.kind,s)},S=(e,r)=>{const t={};for(const a of Object.keys(e)){const s=e[a];s&&(t[a]=A(s,r,a))}return R(e,t,"searchParams")},O=(e,r)=>{const t=r.req.param(),a={};for(const s of Object.keys(e)){const o=e[s];if(!o)continue;const n=t[s];a[s]=n===void 0?void 0:f(N(o).kind,n)}return R(e,a,"params")},P=async(e,r)=>{let t;try{t=await r.req.json()}catch{throw new p("BAD_REQUEST","Invalid JSON body")}if(typeof t!="object"||t===null||Array.isArray(t))throw new p("BAD_REQUEST","Expected a JSON object body");return R(e,t,"body")},q=(e,r)=>{try{return e.parse(r)}catch(t){throw t instanceof v?new p("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${t.message}`):t}},T=e=>{if(e instanceof v)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof p){const{body:r,redacted:t,status:a}=k(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return t&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:a})}throw e},x=(e,r)=>async t=>{try{const a=t.get("lunora"),s=Object.keys(e.searchParams).length>0?S(e.searchParams,t):{},o=Object.keys(e.params).length>0?O(e.params,t):{},n=Object.keys(e.body).length>0?await P(e.body,t):{},c=await r({body:n,ctx:a,params:o,searchParams:s}),i=e.output?q(e.output,c):c,d={};e.cacheControl&&(d["cache-control"]=e.cacheControl),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const m=Object.keys(d).length>0;return i===void 0?new Response(null,{headers:m?d:void 0,status:204}):Response.json(i,{headers:m?d:void 0})}catch(a){return T(a)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},g=(e,r)=>{const t=JSON.stringify(e);return`${r?`event: ${r}
|
|
2
|
+
`:""}data: ${t}
|
|
3
|
+
|
|
4
|
+
`},C=(e,r)=>async t=>{let a,s;try{a=Object.keys(e.searchParams).length>0?S(e.searchParams,t):{},s=Object.keys(e.params).length>0?O(e.params,t):{}}catch(h){return T(h)}const o=t.get("lunora"),n=t.req.raw,c=new TextEncoder,i=new AbortController;if(n.signal.aborted)return i.abort(),new Response("",{headers:w});const d=()=>{i.abort()};n.signal.addEventListener("abort",d,{once:!0});const m=new ReadableStream({cancel(){n.signal.removeEventListener("abort",d),i.abort()},async start(h){try{const y=r({ctx:o,params:s,request:n,searchParams:a,signal:i.signal});for await(const b of y){if(i.signal.aborted)break;h.enqueue(c.encode(g(b)))}h.enqueue(c.encode(g({},"complete")))}catch(y){const{body:b,redacted:j}=k(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});j&&console.error("[lunora] unhandled stream handler error:",y),h.enqueue(c.encode(g({code:b.code,message:b.message},"error")))}finally{n.signal.removeEventListener("abort",d),h.close()}}});return new Response(m,{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=>x(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=>C(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")},$=/^bytes=(\d*)-(\d*)$/,E=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,I=e=>!(e.includes("\r")||e.includes(`
|
|
5
|
+
`)||e.includes("\0")),L=(e,r)=>{if(e===null)return{kind:"full"};const t=$.exec(e.trim());if(!t)return{kind:"full"};const a=t[1]??"",s=t[2]??"";if(a===""&&s==="")return{kind:"full"};let o,n;if(a===""){const c=Number(s);if(c===0)return{kind:"unsatisfiable"};o=Math.max(0,r-c),n=r-1}else o=Number(a),n=s===""?r-1:Math.min(Number(s),r-1);return o>n||o>=r?{kind:"unsatisfiable"}:{end:n,kind:"partial",start:o}},W=async(e,r,t)=>{const a=await e.storage.download(r);if(!a)return new Response("Not Found",{status:404});const s=a.httpMetadata?.contentType,o={"accept-ranges":"bytes","content-type":s!==void 0&&I(s)?s:"application/octet-stream",etag:E(a.etag)};a.sha256Base64!==void 0&&(o["repr-digest"]=`sha-256=:${a.sha256Base64}:`);const n=L(t.headers.get("range"),a.size);if(n.kind==="unsatisfiable")return a.body?.cancel().catch(()=>{}),new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(a.size)}`,"content-type":"text/plain; charset=utf-8",etag:E(a.etag)},status:416});if(n.kind==="full")return new Response(a.body,{headers:{...o,"content-length":String(a.size)},status:200});a.body?.cancel().catch(()=>{});const c=n.end-n.start+1,i=await e.storage.download(r,{range:{length:c,offset:n.start}});return i?new Response(i.body,{headers:{...o,"content-length":String(c),"content-range":`bytes ${String(n.start)}-${String(n.end)}/${String(a.size)}`},status:206}):new Response("Not Found",{status:404})};export{H as httpAction,U as httpRoute,z as httpRouter,I as isSafeHeaderValue,W as serveStorageObject};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as g}from"./functions-CDC08CWY.mjs";import{readMaskTag as w}from"./buildMaskRegistry-BCIzKxdK.mjs";import{l as x}from"./policy-tag-Dprt9JWo.mjs";import{l as f}from"./run-middleware-BeEEqmdE.mjs";const y=(t,e)=>e===void 0||typeof t!="object"||t===null?t:Object.assign(Object.create(Object.getPrototypeOf(t)),t,{meta:e}),p=(t,e)=>f(t,e,a=>a),b=(t,e,a,s,i)=>async(r,d)=>{const l=g(t,d),n=await p(e,y(r,i)),m=await a({args:l,ctx:n});return s?s.parse(m):m},v=(t,e,a)=>(s,i,r)=>{const d=g(t,i);return(async function*(){const l=await p(e,s),n=a({args:d,ctx:l,signal:r})[Symbol.asyncIterator]();try{for(;;){if(r.aborted)return;const m=await n.next();if(m.done||r.aborted)return;yield m.value}}finally{await n.return?.()}})()},u=t=>{const e=t.map(a=>x(a)).filter(a=>a!==void 0);return e.length>0?{tags:e}:void 0},c=t=>{const e=new Map;for(const a of t){const s=w(a);if(s)for(const[i,r]of s.columns){const d=e.get(i)??new Set;for(const l of r)d.add(l);e.set(i,d)}}return e.size>0?e:void 0},o=(t,e,a)=>({__lunoraProcedure:t,...a?{__lunoraVisibility:a}:{},input:s=>o(t,{...e,args:{...e.args,...s}},a),[t]:s=>{const i=u(e.middlewares),r=c(e.middlewares);return{args:e.args,...e.expose?{expose:e.expose}:{},handler:b(e.args,e.middlewares,s,e.output,e.meta),kind:t,...r?{maskedTables:r}:{},...e.meta?{meta:e.meta}:{},...i?{rls:i}:{},...a?{visibility:a}:{},...e.x402?{x402:e.x402}:{}}},meta:s=>o(t,{...e,meta:{...e.meta,...s}},a),output:s=>o(t,{...e,output:s},a),...t==="query"?{stream:s=>{const i=u(e.middlewares),r=c(e.middlewares);return{args:e.args,...e.expose?{expose:e.expose}:{},handler:v(e.args,e.middlewares,s),kind:"stream",...r?{maskedTables:r}:{},...i?{rls:i}:{},...a?{visibility:a}:{},...e.x402?{x402:e.x402}:{}}}}:{},use:s=>o(t,{...e,middlewares:[...e.middlewares,s]},a),...a?{}:{expose:s=>o(t,{...e,expose:s},a)},...a?{}:{x402:s=>o(t,{...e,x402:s},a)}}),O={dataModel:()=>({create:t=>({action:o("action",{args:{},middlewares:[]}),internalAction:o("action",{args:{},middlewares:[]},"internal"),internalMutation:o("mutation",{args:{},middlewares:[]},"internal"),internalQuery:o("query",{args:{},middlewares:[]},"internal"),mutation:o("mutation",{args:{},middlewares:[]}),query:o("query",{args:{},middlewares:[]})})})};export{O as initLunora};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"./LunoraError-LVhdU0Lo.mjs";import{bindOrm as $,bindTableFacade as T}from"./bindOrm-Bp9hsM2q.mjs";import{T as B,U as W,o as v,L as R}from"./middleware-D9_39C5C.mjs";import{tagMaskMiddleware as F}from"./buildMaskRegistry-BCIzKxdK.mjs";const U=n=>{let i=2166136261;for(let s=0;s<n.length;s+=1)i^=n.codePointAt(s)??0,i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},_=(n,i,s)=>{try{return n==="redact"?null:n==="hash"?i==null?i:U(typeof i=="string"?i:JSON.stringify(i)):n(i,s)}catch{return null}},f=(n,i,s)=>{const u={...n};for(const[y,g]of Object.entries(i))y in u&&(u[y]=_(g,n[y],{...s,column:y,row:n}));return u},N=(n,i,s)=>({...n,page:n.page.map(u=>f(u,i,s))}),A=(n,i,s,u)=>{if(typeof n!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>c=>(typeof c=="string"&&y.add(c),g())});n(g());for(const c of y)if(c in i)throw new m("MASK_UNSUPPORTED",`${u}() filtering "${s}" by masked column "${c}" is not supported`)},j=(n,i,s,u)=>{const y=n.rankBefore,g=n.rankPageRows,c=(t,r,e,o)=>{const a=i.get(t);if(!a)return;const w=u?.[t]?.[o]?.[r];if(!w)return;const l=w.find(O=>O in a);if(l!==void 0)throw new m("MASK_UNSUPPORTED",`${e}() reading "${t}" via index "${r}" would order rows by masked column "${l}" — use an index whose declared fields are all unmasked, or unmask the column`)},h=(t,r,e)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>t[Symbol.asyncIterator]()})yield f(o,r,s)},collect:async()=>(await t.collect()).map(o=>f(o,r,s)),collectWithScores:async()=>(await t.collectWithScores()).map(o=>{const a=f(o.document,r,s);return"distanceMeters"in o?{distanceMeters:null,document:a}:{document:a,score:o.score}}),filter:o=>h(t.filter(a=>o(f(a,r,s))),r,e),first:async()=>{const o=await t.first();return o?f(o,r,s):null},order:o=>h(t.order(o),r,e),paginate:async o=>N(await t.paginate(o),r,s),take:async o=>(await t.take(o)).map(a=>f(a,r,s)),unique:async()=>{const o=await t.unique();return o?f(o,r,s):null},withIndex:(o,a)=>(c(e,o,"withIndex","index"),A(a,r,e,"withIndex"),h(t.withIndex(o,a),r,e)),withSearchIndex:(o,a)=>(A(a,r,e,"withSearchIndex"),h(t.withSearchIndex(o,a),r,e)),withGeoIndex:(o,a)=>(c(e,o,"withGeoIndex","geo"),h(t.withGeoIndex(o,a),r,e))}),k=async(t,r)=>{if(n.lookupById){const l=await n.lookupById(t,r);return l?{row:l.row,tableName:i.has(l.tableName)?l.tableName:void 0}:{row:null,tableName:void 0}}const e=await n.get(t,r);if(!e)return{row:null,tableName:void 0};const o=r!==void 0&&i.has(r)?[r]:[],a=r===void 0?[...i.keys()]:o,w=await Promise.all(a.map(async l=>(await n.findFirst(l,{limit:1,where:{_id:t}}))?._id===t?l:void 0));return{row:e,tableName:w.find(l=>l!==void 0)}},b=(t,r,e)=>{const o=i.get(t);if(!o)return;const a=r.find(w=>typeof w=="string"&&w in o);if(a!==void 0)throw new m("MASK_UNSUPPORTED",`${e}() over masked column "${a}" on "${t}" is not supported`)},p=(t,r)=>{if(!(!t||typeof t!="object"||Array.isArray(t)))for(const[e,o]of Object.entries(t))if(e==="AND"||e==="OR"){if(Array.isArray(o))for(const a of o)p(a,r)}else e==="NOT"?p(o,r):e.startsWith("__")||r.add(e)},d=(t,r,e)=>{const o=i.get(t);if(!o||r===void 0)return;const a=new Set;p(r,a);for(const w of a)if(w in o)throw new m("MASK_UNSUPPORTED",`${e}() filtering "${t}" by masked column "${w}" is not supported`)},x=(t,r,e)=>{const o=i.get(t);if(!(!o||!Array.isArray(r))){for(const a of r)if(a&&typeof a=="object"&&!Array.isArray(a)){for(const w of Object.keys(a))if(w in o)throw new m("MASK_UNSUPPORTED",`${e}() ordering "${t}" by masked column "${w}" is not supported`)}}},P=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,S=(t,r,e)=>{const o=P(r);d(t,o?.where,e),d(t,o?.baseWhere,e)},M={...n,async deleteWhere(t,r,e){if(d(t,r,"deleteMany({ where })"),n.deleteWhere===void 0)throw new m("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return n.deleteWhere(t,r,e)},async patchWhere(t,r,e){if(d(t,r.where,"patchMany({ where })"),n.patchWhere===void 0)throw new m("INTERNAL",`ctx.db.${t}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return n.patchWhere(t,r,e)},aggregate(t,r){return b(t,[r.field],"aggregate"),d(t,r.where,"aggregate"),n.aggregate(t,r)},count(t,r){const e=P(r),o=e&&("where"in e||"baseWhere"in e||"restrictsCounts"in e)?e.where:r;return d(t,o,"count"),e&&d(t,e.baseWhere,"count"),n.count(t,r)},async findFirst(t,r){d(t,r?.where,"findFirst"),d(t,r?.baseWhere,"findFirst"),x(t,r?.orderBy,"findFirst");const e=await n.findFirst(t,r),o=i.get(t);return e&&o?f(e,o,s):e},async findFirstOrThrow(t,r){d(t,r?.where,"findFirstOrThrow"),d(t,r?.baseWhere,"findFirstOrThrow"),x(t,r?.orderBy,"findFirstOrThrow");const e=await n.findFirstOrThrow(t,r),o=i.get(t);return o?f(e,o,s):e},async findMany(t,r){d(t,r?.where,"findMany"),d(t,r?.baseWhere,"findMany"),x(t,r?.orderBy,"findMany");const e=await n.findMany(t,r),o=i.get(t);return o?N(e,o,s):e},async get(t,r){const{row:e,tableName:o}=await k(t,r),a=o===void 0?void 0:i.get(o);return!e||!a?e:f(e,a,s)},async lookupById(t,r){const e=await n.lookupById?.(t,r);if(!e)return null;const o=i.get(e.tableName);return{row:o?f(e.row,o,s):e.row,tableName:e.tableName}},groupBy(t,r){return b(t,[...r.by,r.agg?.field],"groupBy"),d(t,r.where,"groupBy"),n.groupBy(t,r)},query(t){const r=n.query(t),e=i.get(t);return e?h(r,e,t):r},async rank(t,r,e){return S(t,e,"rank"),c(t,r,"rank","rank"),n.rank(t,r,e)},async rankPage(t,r,e){S(t,e,"rankPage"),c(t,r,"rankPage","rank");const o=await n.rankPage(t,r,e),a=i.get(t);return a?N(o,a,s):o},...v("rankBefore",y,t=>(r,e,o)=>(S(r,o,"rankBefore"),c(r,e,"rankBefore","rank"),t(r,e,o))),...v("rankPageRows",g,t=>async(r,e,o)=>{S(r,o,"rankPageRows"),c(r,e,"rankPageRows","rank");const a=await t(r,e,o),w=i.get(r);return w?{...a,rows:a.rows.map(l=>({...l,doc:f(l.doc,w,s)}))}:a})},I=M;for(const t of i.keys())R(n[t])&&(I[t]=T(M,t));return M},L=(n,i={})=>{const s=new Map(Object.entries(n)),u=B(i.roles),y=async({ctx:c,next:h})=>{const k={auth:await W(c.auth??{},u),ctx:c};if(i.bypass?.(k))return h();const b=j(c.db,s,k,i.indexFields),p={db:b},{orm:d}=c;return d!==null&&typeof d=="object"&&(p.orm=$(b)),h({ctx:p})},g=new Map;for(const[c,h]of s)g.set(c,new Set(Object.keys(h)));return F(y,{columns:g})};export{L as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";import{bindOrm as x,bindTableFacade as F}from"./bindOrm-Bp9hsM2q.mjs";import{r as U}from"./policy-tag-Dprt9JWo.mjs";import{deny as j}from"./allowAll-BnyNbJZT.mjs";const _=(t,r,s)=>r?{[t]:s(r)}:{},I=500,W=(t,r,s)=>{const i=r??I;if(t>i)throw new p("BAD_REQUEST",`${s}: batch of ${String(t)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},C=j(),$=Symbol.for("lunora.ctxdb.rls-unwrap"),q=t=>{const r=new Map;for(const s of t){const i=r.get(s.table)??[];i.push(s),r.set(s.table,i)}return r},L=(t,r)=>{const s=[];let i=!1;for(const u of t){if(u.on!=="read")continue;const c=u.when(r);if(c!==void 0){if(c===!0){i=!0;break}c!==!1&&s.push(c)}}if(!i)return s.length===0?C:s.length===1?s[0]:{OR:s}},M=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),z=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],g=t=>{const r=typeof t;return r==="number"||r==="string"||r==="bigint"},Q=(t,r)=>!("lt"in r&&(!g(t)||!g(r.lt)||t>=r.lt)||"lte"in r&&(!g(t)||!g(r.lte)||t>r.lte)||"gt"in r&&(!g(t)||!g(r.gt)||t<=r.gt)||"gte"in r&&(!g(t)||!g(r.gte)||t<r.gte)),G=(t,r)=>{if("in"in r){const s=r.in;if(!Array.isArray(s)||!s.includes(t))return!1}if("notIn"in r){const s=r.notIn;if(Array.isArray(s)&&s.includes(t))return!1}if("contains"in r){const s=r.contains;if(typeof t!="string"||typeof s!="string"||!t.includes(s))return!1}return!("isNull"in r&&r.isNull===!0!=(t==null))},H=(t,r)=>"eq"in r&&t!==r.eq||"ne"in r&&t===r.ne?!1:G(t,r)&&Q(t,r),J=(t,r,s,i)=>r==="AND"?Array.isArray(s)&&s.every(u=>i(t,u)):r==="OR"?Array.isArray(s)&&s.some(u=>i(t,u)):!i(t,s??{}),D=t=>t==="AND"||t==="OR"||t==="NOT",V=t=>M(t)&&Object.keys(t).every(r=>z.includes(r)),X=["every","is","isNot","none","some"],Y=t=>M(t)&&Object.keys(t).length>0&&Object.keys(t).every(r=>X.includes(r)),A=t=>Object.keys(t).some(r=>{const s=t[r];return D(r)?r==="NOT"?A(s??{}):Array.isArray(s)&&s.some(i=>A(i??{})):Y(s)}),v=(t,r)=>{for(const s of Object.keys(r)){const i=r[s];if(D(s)){if(!J(t,s,i,v))return!1;continue}const u=t[s];if(V(i)){if(!H(u,i))return!1;continue}if(u!==i)return!1}return!0},Z=(t,r,s)=>{const i=t.when({...r,row:s});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(A(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return v(s,i)},K=(t,r,s)=>{const i=t.when(r);if(i===void 0||i===!0)return s===void 0||Z(t,r,s);if(i===!1)return!1;if(A(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!v(r.row,i)?!1:s===void 0||v(s,i)},O=(t,r,s,i)=>{let u=!1;for(const c of t)if(c.on===r&&(u=!0,!K(c,s,i)))return!1;return u},ee=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),te=(t,r)=>r===void 0?!0:t==="restrictsCounts"?typeof r=="boolean":t==="relationBaseWhere"?typeof r=="function":M(r),re=t=>{const r=Object.keys(t);return r.length===0?!1:r.every(s=>ee.has(s)&&te(s,t[s]))},ae=t=>t===void 0?{}:M(t)&&re(t)?t:{where:t},b=(t,r)=>!r||Object.keys(r).length===0?t:!t||Object.keys(t).length===0?r:{AND:[r,t]},ne=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},se=(t,r,s,i)=>{const u=new Map,c=e=>{const a=u.get(e);if(a)return a;const n=s.get(e);if(!n||n.length===0||!n.some(l=>l.on==="read")){const l={baseWhere:void 0,restricts:!1};return u.set(e,l),l}const o={baseWhere:L(n,i),restricts:!0};return u.set(e,o),o},h=e=>c(e).restricts?r:t,y=e=>c(e).baseWhere,N=async(e,a)=>{if(r.lookupById){const d=await r.lookupById(e,a);return d?{row:d.row,tableName:s.has(d.tableName)?d.tableName:void 0}:{row:null,tableName:void 0}}const n=await r.get(e,a);if(!n)return{row:null,tableName:void 0};const o=a!==void 0&&s.has(a)?[a]:[],l=a===void 0?[...s.keys()]:o,f=await Promise.all(l.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:e}}))?._id===e?d:void 0));return{row:n,tableName:f.find(d=>d!==void 0)}},B=async(e,a)=>{const n=await N(e,a);return n.row&&n.tableName!==void 0?{row:n.row,tableName:n.tableName}:void 0},w=async(e,a,n,o,l)=>{const f=await B(e,l);if(!f)return n(t);const d=s.get(f.tableName);if(d){const R=o?o(f.row):void 0;if(!O(d,a,{...i,row:f.row},R))throw new p("FORBIDDEN",`${a} denied by policy`)}return n(r)},m=(e,a)=>{const{baseWhere:n,restricts:o}=c(e);if(o)throw new p("COUNT_RLS_UNSUPPORTED",`${a}() is not supported on "${e}" inside an RLS-restricted context`);return n},S=t.rankBefore,T=t.rankPageRows,k={...t,async count(e,a){const{baseWhere:n,restricts:o}=c(e),l=ae(a);return h(e).count(e,{...l,baseWhere:b(l.baseWhere,n),relationBaseWhere:y,restrictsCounts:(l.restrictsCounts??!1)||o})},delete:(e,a,n)=>w(e,"delete",o=>o.delete(e,a,n),void 0,a),async deleteAll(e,a){const n=Math.max(1,a?.chunkSize??I),{baseWhere:o}=c(e);let l=0;for(;;){const f=(await h(e).findMany(e,{baseWhere:o,limit:n,relationBaseWhere:y})).page.map(d=>String(d._id));if(f.length===0)break;for(const d of f)await w(d,"delete",R=>R.delete(d,void 0,a?.hard===void 0?void 0:{hard:a.hard})),l+=1;if(f.length<n)break}return{deleted:l}},async deleteMany(e,a,n){W(e.length,a?.limit,"deleteMany");for(const o of e)await w(o,"delete",l=>l.delete(o,n),void 0,n);return{deleted:e.length}},async deleteWhere(e,a,n){const{baseWhere:o}=c(e),l=(await h(e).findMany(e,{baseWhere:b(a,o),relationBaseWhere:y})).page.map(f=>String(f._id));return W(l.length,n?.limit,"deleteWhere"),k.deleteMany(l,n)},async findFirst(e,a){const{baseWhere:n}=c(e);return h(e).findFirst(e,{...a,baseWhere:b(a?.baseWhere,n),relationBaseWhere:y})},async findFirstOrThrow(e,a){const{baseWhere:n}=c(e);return h(e).findFirstOrThrow(e,{...a,baseWhere:b(a?.baseWhere,n),relationBaseWhere:y})},async findMany(e,a){const{baseWhere:n}=c(e);return h(e).findMany(e,{...a,baseWhere:b(a?.baseWhere,n),relationBaseWhere:y})},async get(e,a){const n=await N(e,a);if(!n.row)return null;if(n.tableName===void 0)return t.get(e,a);const{baseWhere:o,restricts:l}=c(n.tableName);if(!l)return t.get(e,a);if(!o)return n.row;const f=await r.findFirst(n.tableName,{baseWhere:o,limit:1,where:{_id:e}});return f?._id===e?f:null},async lookupById(e,a){const n=await N(e,a);if(!n.row)return null;if(n.tableName===void 0||!c(n.tableName).restricts)return await t.lookupById?.(e,a)??null;const{baseWhere:o}=c(n.tableName);if(!o)return{row:n.row,tableName:n.tableName};const l=await r.findFirst(n.tableName,{baseWhere:o,limit:1,where:{_id:e}});return l?._id===e?{row:l,tableName:n.tableName}:null},async insert(e,a){const n=s.get(e);if(n){if(!O(n,"insert",{...i,row:a}))throw new p("FORBIDDEN",`insert on "${e}" denied by policy`);return r.insert(e,a)}return t.insert(e,a)},async insertMany(e,a,n){W(a.length,n?.limit,"insertMany");const o=s.get(e);if(o){for(const l of a)if(!O(o,"insert",{...i,row:l}))throw new p("FORBIDDEN",`insert on "${e}" denied by policy`);return r.insertMany(e,a,n)}return t.insertMany(e,a,n)},async insertManyUnsafe(e,a,n){W(a.length,n?.limit,"insertManyUnsafe");const o=s.get(e);if(o){for(const l of a)if(!O(o,"insert",{...i,row:l}))throw new p("FORBIDDEN",`insert on "${e}" denied by policy`);return r.insertManyUnsafe(e,a,n)}return t.insertManyUnsafe(e,a,n)},patch:(e,a,n)=>w(e,"update",o=>o.patch(e,a,n),o=>({...o,...a}),n),async patchMany(e,a,n){W(e.length,a?.limit,"patchMany");for(const o of e)await w(o.id,"update",l=>l.patch(o.id,o.patch,n),l=>({...l,...o.patch}),n);return{patched:e.length}},async patchWhere(e,a,n){const{baseWhere:o}=c(e),l=(await h(e).findMany(e,{baseWhere:b(a.where,o),relationBaseWhere:y})).page.map(f=>({id:String(f._id),patch:a.patch}));return W(l.length,n?.limit,"patchWhere"),k.patchMany(l,n)},query(e){const{baseWhere:a}=c(e),n=h(e).query(e);return a?n.filter(o=>v(o,a)):n},restore:(e,a)=>w(e,"update",async n=>{const o=n.restore??r.restore;if(!o)throw new p("BAD_REQUEST","restore is not supported by this writer");await o(e,a)},void 0,a),replace:(e,a,n)=>w(e,"update",o=>o.replace(e,a,n),o=>({...a,_creationTime:a._creationTime??o._creationTime,_id:o._id}),n),aggregate(e,a){const{baseWhere:n}=c(e);return h(e).aggregate(e,{...a,baseWhere:b(a.baseWhere,n),relationBaseWhere:y})},groupBy(e,a){const{baseWhere:n}=c(e);return h(e).groupBy(e,{...a,baseWhere:b(a.baseWhere,n),relationBaseWhere:y})},rank(e,a,n){const o=m(e,"rank");return h(e).rank(e,a,{...n,baseWhere:b(n.baseWhere,o)})},rankPage(e,a,n){const o=m(e,"rankPage");return h(e).rankPage(e,a,{...n,baseWhere:b(n?.baseWhere,o)})},wipeShard(){throw new p("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})},..._("rankBefore",S,e=>(a,n,o)=>(m(a,"rankBefore"),(h(a).rankBefore??e)(a,n,o))),..._("rankPageRows",T,e=>(a,n,o)=>{const l=m(a,"rankPageRows");return(h(a).rankPageRows??e)(a,n,{...o,baseWhere:b(o?.baseWhere,l)})})},P=k;for(const e of s.keys())ne(t[e])&&(P[e]=F(k,e));return k},E=t=>typeof t=="string"?t:t.name,oe=t=>{const r=new Map;for(const s of t??[])r.set(s.name,new Set((s.permissions??[]).map(i=>E(i))));return r},ie=(t,r)=>{const s=new Set;for(const i of t)for(const u of r.get(i)??[])s.add(u);return i=>s.has(E(i))},le=async(t,r)=>{const s=t.roles??[];return{can:ie(s,r),identity:await t.getIdentity?.()??null,roles:s,userId:t.userId??null}},he=(t,r={})=>{const s=q(t),i=oe(r.roles);return U(async({ctx:u,next:c})=>{const h={auth:await le(u.auth??{},i),ctx:u},y=u.db,N=y[$]??y,B=se(y,N,s,h),w={db:B},{orm:m}=u;return m!==null&&typeof m=="object"&&(w.orm=x(B)),c({ctx:w})},{policies:t,roles:r.roles??[]})};export{L as E,ie as F,O as I,ne as L,E as M,v as P,oe as T,le as U,he as c,_ as o};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{l as F}from"./run-middleware-BeEEqmdE.mjs";import{v as R}from"@lunora/values";const B=["de","en","es","fr","it","nl","none","pt"],O=["native","portable"],C=e=>O.includes(e),P=e=>B.includes(e),_="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",H="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",K="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",Q="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",U="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",J="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",W="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",G=/[\u0300-\u036F]/gu,X=e=>e.normalize("NFD").replaceAll(G,"").normalize("NFC").toLowerCase(),g=e=>new Set(X(e).split(" "));g(H),g(_),g(K),g(Q),g(U),g(J),g(W);const T=16,Y={many:(e,n)=>({field:n.field,kind:"many",references:n.references??"_id",table:e}),one:(e,n)=>({field:n.field,kind:"one",onDelete:n.onDelete,references:n.references??"_id",table:e})},b=(e,n,t)=>({handler:t,op:n,timing:e}),Z=()=>({afterDelete:e=>b("after","delete",e),afterInsert:e=>b("after","insert",e),afterUpdate:e=>b("after","update",e),beforeDelete:e=>b("before","delete",e),beforeInsert:e=>b("before","insert",e),beforeUpdate:e=>b("before","update",e)}),M=(e,n)=>{if(!n||n.length===0)throw new i("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return n.map(t=>({direction:t.direction??"asc",field:t.field}))},me=e=>{const n={...e},t=[],r=[],s=[],l=[],c={},d=[],m={},f=Z(),w=[];let I={kind:"root"},$=!1,j=!1,A,L,S,q;const u={aggregateIndex(a,o){const h=o?.op??"count";if(h!=="count"&&!o?.field)throw new i("INTERNAL",`aggregateIndex "${a}": op "${h}" requires a "field"`);return t.push({by:o?.by,field:o?.field,name:a,on:"",op:h,where:o?.where}),u},get aggregateIndexes(){return t},get externalSource(){return q},externallyManaged(){return $=!0,u},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),u},get geoIndexes(){return r},global(a){return I={backend:a?.backend??"d1",kind:"global"},u},get isExternallyManaged(){return $},get isPublic(){return j},index(a,o,h){return s.push({fields:o,name:a,unique:h?.unique??!1}),u},get indexes(){return s},ownedBy(a){return A=a,u},get ownerField(){return A},public(){return j=!0,u},rankIndex(a,o){return l.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:M(a,o.sortBy),where:o.where}),u},get rankIndexes(){return l},get relationMap(){return c},relations(a){return Object.assign(c,a(Y)),u},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>T)throw new i("INTERNAL",`searchIndex "${a}": at most ${String(T)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:h}=o;if(h!==void 0&&!P(h))throw new i("INTERNAL",`searchIndex "${a}": unknown language "${h}" (supported: ${B.join(", ")})`);const{strategy:N}=o;if(N!==void 0&&!C(N))throw new i("INTERNAL",`searchIndex "${a}": unknown strategy "${N}" (supported: ${O.join(", ")})`);return d.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return d},shape:n,shardBy(a){return I={field:a,kind:"shardBy"},u},get shardMode(){return I},get softDeleteMode(){return L},source(a){if(!a.binding)throw new i("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new i("INTERNAL","source: `query` is required (the tenant-membership SQL)");return q=a,$=!0,u},softDelete(a){const o=a?.field??"deletedAt";return L={field:o},o in n||(n[o]=R.optional(R.number().nullable())),u},get triggerMap(){return m},triggers(a){return Object.assign(m,a(f)),u},ttl(a,o){return S={after:o?.after,field:a},u},get ttlPolicy(){return S},get vectorIndexes(){return w},vectorize(a,o){return w.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),u}};return u},fe=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),he=(e,n)=>{const t=n.op??"count";if(t!=="count"&&!n.field)throw new i("INTERNAL",`aggregateIndex "${e}": op "${t}" requires a "field"`);return{by:n.by,field:n.field,name:e,on:n.on,op:t,where:n.where}},ge=(e,n)=>({name:e,on:n.table,partitionBy:n.partitionBy,sortBy:M(e,n.sortBy),where:n.where}),x=e=>({...e,extend(n){return x(z(e,n))},jurisdiction(n){return x(e)},rls(n){return x({...e,rlsMode:n})}}),V=e=>{for(const[n,t]of Object.entries(e))for(const r of[...t.aggregateIndexes,...t.rankIndexes])r.on===""&&(r.on=n)},ee=(e,n,t)=>{for(const r of Object.values(n)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);s.aggregateIndexes.push(r)}for(const r of Object.values(t)){const s=e[r.on];if(!s)throw new i("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);s.rankIndexes.push(r)}},ne=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},te=(e,n)=>{const t=n.mode==="incremental";if(n.mode!==void 0&&n.mode!=="full-pull"&&!t)throw new i("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(n.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!t){const r=ne(n);if(r)throw new i("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(!n.cursor?.column||!n.cursor.query)throw new i("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(n.reconcileEveryMs===void 0&&n.softDeleteColumn===void 0)throw new i("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).`)},re=e=>{for(const[n,t]of Object.entries(e)){const r=t.externalSource;if(r){if(t.shardMode.kind==="global")throw new i("INTERNAL",`defineSchema: table "${n}" 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(t.shardMode.kind==="shardBy"&&!r.tenantBy)throw new i("INTERNAL",`defineSchema: sourced + .shardBy() table "${n}" 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.`);te(n,r)}}},oe=["_creationTime","_id"],ae=new Set(oe),p=(e,n,t,r)=>{if(!(ae.has(t)||t in r.shape))throw new i("INTERNAL",`defineSchema: table "${e}" index "${n}" names column "${t}" which is not in the table's shape`)},v=(e,n,t,r)=>{const s=new Set;for(const l of t){if(s.has(l.name))throw new i("INTERNAL",`defineSchema: table "${e}" declares ${n} "${l.name}" more than once`);s.add(l.name),r(l)}},D=e=>{for(const[n,t]of Object.entries(e))v(n,"index",t.indexes,r=>{for(const s of r.fields)p(n,r.name,s,t)}),v(n,"rank index",t.rankIndexes,r=>{for(const s of r.sortBy)p(n,r.name,s.field,t);for(const s of r.partitionBy??[])p(n,r.name,s,t)}),v(n,"geo index",t.geoIndexes,r=>{p(n,r.name,r.field,t)})},k=(e,n,t)=>{if(e.length===0)return;const r={};for(const s of e)r[n(s)]=t(s);return r},se=e=>{const n=new Set(e.sortBy.map(t=>t.field));for(const t of e.partitionBy??[])n.add(t);return[...n]},be=e=>{const n={};for(const[t,r]of Object.entries(e.tables)){const s=k(r.geoIndexes,d=>d.name,d=>[d.field]),l=k(r.indexes,d=>d.name,d=>d.fields),c=k(r.rankIndexes,d=>d.name,se);(s||l||c)&&(n[t]={...s?{geo:s}:{},...l?{index:l}:{},...c?{rank:c}:{}})}return n},we=(e,n={},t={},r={})=>(V(e),ee(e,t,r),re(e),D(e),x({tables:e,vectorIndexes:n})),y=(e,n)=>`${e}_${n}`,E=(e,n,t)=>t.has(e)?y(n,e):e,ie=(e,n,t,r)=>{const s=y(n,r),l=f=>f===""?s:E(f,n,t),c={};for(const[f,w]of Object.entries(e.relationMap))c[f]={...w,table:E(w.table,n,t)};const d=e.aggregateIndexes.map(f=>({...f,on:l(f.on)})),m=e.rankIndexes.map(f=>({...f,on:l(f.on)}));return{...e,aggregateIndexes:d,rankIndexes:m,relationMap:c}},pe=(e,n)=>{if(!e)throw new i("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:n.tables,...n.vectorIndexes?{vectorIndexes:n.vectorIndexes}:{}}},de=((e,n)=>{if(!e)throw new i("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(n.extension&&n.extension.key!==e)throw new i("INTERNAL",`definePlugin("${e}"): extension key "${n.extension.key}" does not match plugin key`);return{key:e,...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}}),xe=(e,n)=>({...de(e,{...n.extension?{extension:n.extension}:{},...n.middleware?{middleware:n.middleware}:{}}),functions:n.functions??{}}),z=(e,n)=>{const{key:t}=n,r=new Set(Object.keys(n.tables)),s={...e.tables};for(const[c,d]of Object.entries(n.tables)){const m=y(t,c);if(Object.hasOwn(s,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): table "${m}" already exists in the base schema — another extension with the same key already contributed it`);s[m]=ie(d,t,r,c)}const l={...e.vectorIndexes};if(n.vectorIndexes)for(const[c,d]of Object.entries(n.vectorIndexes)){const m=y(t,c);if(Object.hasOwn(l,m))throw new i("INTERNAL",`defineSchema(...).extend("${t}"): vector index "${m}" already exists in the base schema — another extension with the same key already contributed it`);l[m]={...d,table:E(d.table,t,r)}}return D(s),{rlsMode:e.rlsMode,tables:s,vectorIndexes:l}},ye=(e,n)=>{let t=e;for(const r of n)r.extension&&(t=z(t,r.extension));return t},Ie=e=>{const n=e.map(t=>t.middleware).filter(t=>t!==void 0);return(async({ctx:t,next:r})=>F(n,t,s=>r({ctx:s})))};export{he as H,fe as K,D as O,be as W,ge as X,we as Z,de as a,pe as b,Ie as c,xe as d,ye as i,z as m,me as q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./LunoraError-LVhdU0Lo.mjs";import"./bindOrm-Bp9hsM2q.mjs";import{E as t,I as m,T as p,L as l,P as c,M as n,F as h,U as d,c as u}from"./middleware-D9_39C5C.mjs";import"./policy-tag-Dprt9JWo.mjs";import"./allowAll-BnyNbJZT.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,c as matchesWhere,n as permissionName,h as resolveCan,d as resolvePolicyAuth,u as rls};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"./LunoraError-LVhdU0Lo.mjs";import{T as k,U as x}from"./middleware-D9_39C5C.mjs";const U=(r,e)=>r===void 0||e.startsWith(r),v=r=>{const e=r[1],i=typeof e=="object"&&e!==null?e.method:void 0;return typeof i=="string"&&i.toUpperCase()==="PUT"?"write":"read"},N=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",v],["getUrl","read"],["store","write"]],D=(r,e={})=>{const i=k(e.roles);return async({ctx:f,next:d})=>{const y=await x(f.auth??{},i),m=(o,n,s)=>{const a=r.filter(t=>t.on===o&&t.bucket===s);if(a.length===0)return;const c={auth:y,ctx:f,key:n};if(!a.some(t=>U(t.prefix,n)&&t.when(c)===!0))throw new h("FORBIDDEN",`storage ${o} on "${n}" in bucket "${s}" denied by access rule`)},l=o=>{const n=o.bucketName??"default",s={bucketName:n};for(const[c,t]of N){const p=o[c];typeof p=="function"&&(s[c]=(...u)=>{const w=typeof u[0]=="string"?u[0]:"",b=typeof t=="function"?t(u):t;return m(b,w,n),p(...u)})}const{bucket:a}=o;return typeof a=="function"&&(s.bucket=c=>l(a(c))),s},g=f.storage;return g===void 0?d():d({ctx:{storage:l(g)}})}};export{D as storageRules};
|
|
@@ -32,7 +32,7 @@ type PolicyDecision = WhereInput | boolean | undefined;
|
|
|
32
32
|
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
|
|
33
33
|
* read policy may now return a Prisma-style relation predicate (the
|
|
34
34
|
* `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
|
|
35
|
-
* authoring surface accepts `WhereOf
|
|
35
|
+
* authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
|
|
36
36
|
* `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
|
|
37
37
|
* addition to the `boolean`/`undefined` decisions. Used by the project-bound
|
|
38
38
|
* `definePolicy` from `createPolicyDsl`.
|
|
@@ -138,4 +138,4 @@ interface Role {
|
|
|
138
138
|
interface RlsOptions {
|
|
139
139
|
readonly roles?: ReadonlyArray<Role>;
|
|
140
140
|
}
|
|
141
|
-
export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a,
|
|
141
|
+
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 };
|
|
@@ -32,7 +32,7 @@ type PolicyDecision = WhereInput | boolean | undefined;
|
|
|
32
32
|
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
|
|
33
33
|
* read policy may now return a Prisma-style relation predicate (the
|
|
34
34
|
* `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
|
|
35
|
-
* authoring surface accepts `WhereOf
|
|
35
|
+
* authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
|
|
36
36
|
* `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
|
|
37
37
|
* addition to the `boolean`/`undefined` decisions. Used by the project-bound
|
|
38
38
|
* `definePolicy` from `createPolicyDsl`.
|
|
@@ -138,4 +138,4 @@ interface Role {
|
|
|
138
138
|
interface RlsOptions {
|
|
139
139
|
readonly roles?: ReadonlyArray<Role>;
|
|
140
140
|
}
|
|
141
|
-
export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a,
|
|
141
|
+
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 };
|
package/dist/rls/testing.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-
|
|
1
|
+
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-B-pIn8rE.mjs";
|
|
2
2
|
import "../data-model.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* The slice of a request identity a policy reads. Mirrors the
|
package/dist/rls/testing.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-
|
|
1
|
+
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-CdPDEjhz.js";
|
|
2
2
|
import "../data-model.js";
|
|
3
3
|
/**
|
|
4
4
|
* The slice of a request identity a policy reads. Mirrors the
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{T as p,F as I,E as h,P,I as b}from"../packem_shared/middleware-D9_39C5C.mjs";const v=(d,s={})=>{const f=p(s.roles),x=s.ctx??{};return{as:y=>{const o=y??{},c=o.roles??[],i={auth:{can:I(c,f),identity:o.identity??null,roles:c,userId:o.userId??null},ctx:x},a=(t,u,r,l)=>{const e=d.filter(n=>n.table===u);if(e.length===0)return!0;if(t==="read"){if(!e.some(m=>m.on==="read"))return!0;const n=h(e,i);return n===void 0||P(r??{},n)}return b(e,t,{...i,row:r},l)};return{can:a,cannot:(t,u,r,l)=>!a(t,u,r,l)}}}};export{v as expectPolicy};
|
package/dist/types.d.mts
CHANGED
|
@@ -418,7 +418,7 @@ interface TableDefinition<Shape extends Record<string, Validator> = Record<strin
|
|
|
418
418
|
* data field doesn't collide with the fluent `.softDelete()` builder method —
|
|
419
419
|
* same convention as `shardBy()`/`shardMode`). When present, the table carries
|
|
420
420
|
* a nullable timestamp column (`field`, default `deletedAt`):
|
|
421
|
-
* `ctx.db
|
|
421
|
+
* `ctx.db.<table>.delete()` flips it instead of physically removing the row,
|
|
422
422
|
* and **list reads** (`findMany`/`findFirst`/`query()`/`count`/`aggregate`/
|
|
423
423
|
* relation loads) hide rows whose `field` is set unless
|
|
424
424
|
* `includeDeleted: true` is passed. By-id `get`/`patch`/`replace` and
|
|
@@ -524,7 +524,7 @@ type RestCacheConfig = RestCachePolicy;
|
|
|
524
524
|
/**
|
|
525
525
|
* Opt-in public-surface tag attached by the `.expose({ rest: true })` builder
|
|
526
526
|
* modifier (plan 167). Marks a procedure as deliberately published over the
|
|
527
|
-
* public REST surface: the runtime mints a `/_lunora/rest
|
|
527
|
+
* public REST surface: the runtime mints a `/_lunora/rest/<namespace>/<fn>` route
|
|
528
528
|
* that dispatches THROUGH the procedure (so `ctx.auth` / RLS / validators are
|
|
529
529
|
* enforced), and the generated OpenAPI describes it. Everything is default-closed
|
|
530
530
|
* — a procedure without this tag is unreachable over REST.
|
|
@@ -571,7 +571,7 @@ type RegisteredMutation<A extends ArgsValidator, R> = RegisteredFunction<A, R, "
|
|
|
571
571
|
type RegisteredAction<A extends ArgsValidator, R> = RegisteredFunction<A, R, "action">;
|
|
572
572
|
/**
|
|
573
573
|
* Structural mirror of `@lunora/client`'s `FunctionReference` — the handle the
|
|
574
|
-
* generated `api` / `internal` objects hand you, carrying
|
|
574
|
+
* generated `api` / `internal` objects hand you, carrying `<file>:<function>`
|
|
575
575
|
* in `__lunoraRef`. Redeclared here so `@lunora/server` needs no dependency on
|
|
576
576
|
* the client package, exactly as {@link Scheduler} avoids one on
|
|
577
577
|
* `@lunora/scheduler`. `RegisteredFunction` has no `__lunoraRef`, so the two
|
|
@@ -593,8 +593,8 @@ interface FunctionHandle<Kind extends "action" | "mutation" | "query" | "stream"
|
|
|
593
593
|
* contextually type a parameter against a multi-signature type, so a hand-built
|
|
594
594
|
* ctx object must annotate its `(reference, args)` explicitly — see
|
|
595
595
|
* `@lunora/testing`'s harness). It does not work: a concrete
|
|
596
|
-
* `RegisteredQuery
|
|
597
|
-
* `RegisteredFunction
|
|
596
|
+
* `RegisteredQuery<{…}, number>` is not assignable to a
|
|
597
|
+
* `RegisteredFunction<ArgsValidator, …>` constraint, because `handler`'s args
|
|
598
598
|
* are in a contravariant position. Two inference sites it is.
|
|
599
599
|
*/
|
|
600
600
|
interface RunQuery {
|
|
@@ -638,7 +638,7 @@ type RegisteredLifecycleHook = RegisteredFunction<Record<string, never>, void, "
|
|
|
638
638
|
};
|
|
639
639
|
/**
|
|
640
640
|
* A streaming query registration. Unlike {@link RegisteredFunction} the handler
|
|
641
|
-
* returns an `AsyncIterable
|
|
641
|
+
* returns an `AsyncIterable<R>` synchronously (it does NOT `Promise<R>`); the
|
|
642
642
|
* runtime drives it frame by frame and forwards each chunk to the caller. The
|
|
643
643
|
* third `signal` argument is wired to the caller's cancel signal so the handler
|
|
644
644
|
* can stop early — break out of the loop or check `signal.aborted` between
|
|
@@ -689,7 +689,7 @@ interface SystemQuery<T extends SystemTableName> {
|
|
|
689
689
|
* Read-only reader over Lunora's system tables (`_scheduled_functions`,
|
|
690
690
|
* `_storage`), exposed as `ctx.db.system`. Mirrors Convex's `ctx.db.system`.
|
|
691
691
|
*
|
|
692
|
-
* **Best-effort and eventually consistent.** Unlike `ctx.db
|
|
692
|
+
* **Best-effort and eventually consistent.** Unlike `ctx.db.<table>` — which
|
|
693
693
|
* reads the shard's transactional SQLite snapshot — the data behind these tables
|
|
694
694
|
* lives OUTSIDE the shard (scheduled functions in the `SchedulerDO`, storage
|
|
695
695
|
* objects in R2). Every `collect()` / `get()` reaches across to that source.
|
|
@@ -728,7 +728,7 @@ interface DatabaseReader {
|
|
|
728
728
|
*
|
|
729
729
|
* This is the **parse boundary** for an id that arrived as a plain `string`: a
|
|
730
730
|
* wire payload, a mutator's args, a change plan computed on the client. The
|
|
731
|
-
* alternative is `value as Id
|
|
731
|
+
* alternative is `value as Id<"table">` at every such call site — an assertion,
|
|
732
732
|
* not a check, and one that has to be repeated for every table a helper is
|
|
733
733
|
* generic over:
|
|
734
734
|
*
|
|
@@ -794,8 +794,8 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
794
794
|
}
|
|
795
795
|
/**
|
|
796
796
|
* The fluent `ctx.db.query(table)` reader. Generic over the document type
|
|
797
|
-
* `Row` so the generated `ctx.db` can bind it to `Doc
|
|
798
|
-
* every terminal then resolve typed rows — no `as unknown as Doc
|
|
797
|
+
* `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
|
|
798
|
+
* every terminal then resolve typed rows — no `as unknown as Doc<...>` casts),
|
|
799
799
|
* and over the table's declared index names so `.withIndex()` / `.withSearchIndex()`
|
|
800
800
|
* / `.withGeoIndex()` reject a name the table does not declare.
|
|
801
801
|
*
|
|
@@ -815,9 +815,9 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
815
815
|
* **Why `with*` are method signatures and everything else is a property.**
|
|
816
816
|
* Narrowing a parameter makes the enclosing type contravariant in it, so as
|
|
817
817
|
* function properties these would make a BOUND reader
|
|
818
|
-
* (`TableReader
|
|
819
|
-
* the unbound `TableReader
|
|
820
|
-
* `(reader: TableReader
|
|
818
|
+
* (`TableReader<Doc, "by_x">`, what `ctx.db.query(t)` returns) unassignable to
|
|
819
|
+
* the unbound `TableReader<Doc>` — quietly breaking every helper factored as
|
|
820
|
+
* `(reader: TableReader<Doc<"users">>) => …`, which is the obvious way to share
|
|
821
821
|
* query logic. A method signature is bivariant in its parameters, which keeps
|
|
822
822
|
* that direction working while the narrow parameter still rejects an undeclared
|
|
823
823
|
* name at the call site. Both directions are pinned in `types.test-d.ts`.
|
|
@@ -1122,8 +1122,8 @@ interface ScheduledJob {
|
|
|
1122
1122
|
shardKey?: string;
|
|
1123
1123
|
}
|
|
1124
1124
|
/**
|
|
1125
|
-
* A schedulable durable-workflow reference — the generated `workflows
|
|
1126
|
-
* `agents
|
|
1125
|
+
* A schedulable durable-workflow reference — the generated `workflows.<name>` /
|
|
1126
|
+
* `agents.<name>` object, which carries its `WORKFLOW_*`/`AGENT_*` binding and
|
|
1127
1127
|
* stable name. Structural mirror of `@lunora/scheduler`'s `WorkflowReference` so
|
|
1128
1128
|
* `ctx.scheduler` can target a workflow/agent without a dependency on
|
|
1129
1129
|
* `@lunora/scheduler` / `@lunora/workflow`. A scheduled workflow target starts a
|
|
@@ -1147,8 +1147,8 @@ interface Scheduler {
|
|
|
1147
1147
|
list: () => Promise<ScheduledJob[]>;
|
|
1148
1148
|
/**
|
|
1149
1149
|
* Schedule a one-shot run `delayMs` from now. `target` is a function path
|
|
1150
|
-
* (`"ns:fn"`) dispatched as a one-shot, or a generated `workflows
|
|
1151
|
-
* `agents
|
|
1150
|
+
* (`"ns:fn"`) dispatched as a one-shot, or a generated `workflows.<name>` /
|
|
1151
|
+
* `agents.<name>` reference which starts a fresh durable instance on fire
|
|
1152
1152
|
* (the args become its `params`).
|
|
1153
1153
|
*/
|
|
1154
1154
|
runAfter: (delayMs: number, target: SchedulableWorkflowReference | string, args?: Record<string, unknown>) => Promise<string>;
|
|
@@ -1370,12 +1370,12 @@ interface TriggerRankPageOptions {
|
|
|
1370
1370
|
/**
|
|
1371
1371
|
* Portable, table/id-addressed ORM writer handed to trigger handlers via
|
|
1372
1372
|
* `ctx.db`. Mirrors `@lunora/do`'s runtime `DatabaseWriterLike` surface — it is
|
|
1373
|
-
* **not** the generated per-table `ctx.db
|
|
1373
|
+
* **not** the generated per-table `ctx.db.<table>` facade (which can't be typed
|
|
1374
1374
|
* from inside `defineTable`, where the full schema isn't known).
|
|
1375
1375
|
*
|
|
1376
1376
|
* `aggregate`/`groupBy`/`count`/`rank`/`rankPage` route through the same
|
|
1377
1377
|
* trigger-maintained counter and rank tables the user-facing reader uses, so
|
|
1378
|
-
* a handler's `ctx.db
|
|
1378
|
+
* a handler's `ctx.db.<table>.aggregate(...)` observes the just-staged write
|
|
1379
1379
|
* within the same DO transaction (the counter step happens before the trigger
|
|
1380
1380
|
* fires).
|
|
1381
1381
|
*/
|
|
@@ -1562,7 +1562,7 @@ interface VectorSearch<IndexName extends string = string> extends VectorSearchRe
|
|
|
1562
1562
|
}
|
|
1563
1563
|
/**
|
|
1564
1564
|
* Structured, filterable key/value fields attached to a log line — the second
|
|
1565
|
-
* argument of a `ctx.log
|
|
1565
|
+
* argument of a `ctx.log.<level>(message, fields)` call, or the fields bound by
|
|
1566
1566
|
* `ctx.log.with(fields)`. They travel to an `ObservabilitySink`'s `onLog` and,
|
|
1567
1567
|
* for a network sink, become OTLP log-record attributes a log pipeline (or the
|
|
1568
1568
|
* Cloud log viewer) can filter and index on. Primitive values pass through;
|
|
@@ -1682,7 +1682,7 @@ interface SpanHandle {
|
|
|
1682
1682
|
addLink: (link: SpanLink) => void;
|
|
1683
1683
|
/**
|
|
1684
1684
|
* Attach an AI **evaluation** verdict to this (generation) span as the
|
|
1685
|
-
* `gen_ai.evaluation
|
|
1685
|
+
* `gen_ai.evaluation.<name>.score` / `.label` OpenTelemetry attributes, so a
|
|
1686
1686
|
* scorer's grade rides the same trace as the generation it graded. Convenience
|
|
1687
1687
|
* over {@link SpanHandle.setAttributes} that owns the key format; privacy-safe —
|
|
1688
1688
|
* only the name, score, and optional label are emitted. Throws on an empty name
|
package/dist/types.d.ts
CHANGED
|
@@ -418,7 +418,7 @@ interface TableDefinition<Shape extends Record<string, Validator> = Record<strin
|
|
|
418
418
|
* data field doesn't collide with the fluent `.softDelete()` builder method —
|
|
419
419
|
* same convention as `shardBy()`/`shardMode`). When present, the table carries
|
|
420
420
|
* a nullable timestamp column (`field`, default `deletedAt`):
|
|
421
|
-
* `ctx.db
|
|
421
|
+
* `ctx.db.<table>.delete()` flips it instead of physically removing the row,
|
|
422
422
|
* and **list reads** (`findMany`/`findFirst`/`query()`/`count`/`aggregate`/
|
|
423
423
|
* relation loads) hide rows whose `field` is set unless
|
|
424
424
|
* `includeDeleted: true` is passed. By-id `get`/`patch`/`replace` and
|
|
@@ -524,7 +524,7 @@ type RestCacheConfig = RestCachePolicy;
|
|
|
524
524
|
/**
|
|
525
525
|
* Opt-in public-surface tag attached by the `.expose({ rest: true })` builder
|
|
526
526
|
* modifier (plan 167). Marks a procedure as deliberately published over the
|
|
527
|
-
* public REST surface: the runtime mints a `/_lunora/rest
|
|
527
|
+
* public REST surface: the runtime mints a `/_lunora/rest/<namespace>/<fn>` route
|
|
528
528
|
* that dispatches THROUGH the procedure (so `ctx.auth` / RLS / validators are
|
|
529
529
|
* enforced), and the generated OpenAPI describes it. Everything is default-closed
|
|
530
530
|
* — a procedure without this tag is unreachable over REST.
|
|
@@ -571,7 +571,7 @@ type RegisteredMutation<A extends ArgsValidator, R> = RegisteredFunction<A, R, "
|
|
|
571
571
|
type RegisteredAction<A extends ArgsValidator, R> = RegisteredFunction<A, R, "action">;
|
|
572
572
|
/**
|
|
573
573
|
* Structural mirror of `@lunora/client`'s `FunctionReference` — the handle the
|
|
574
|
-
* generated `api` / `internal` objects hand you, carrying
|
|
574
|
+
* generated `api` / `internal` objects hand you, carrying `<file>:<function>`
|
|
575
575
|
* in `__lunoraRef`. Redeclared here so `@lunora/server` needs no dependency on
|
|
576
576
|
* the client package, exactly as {@link Scheduler} avoids one on
|
|
577
577
|
* `@lunora/scheduler`. `RegisteredFunction` has no `__lunoraRef`, so the two
|
|
@@ -593,8 +593,8 @@ interface FunctionHandle<Kind extends "action" | "mutation" | "query" | "stream"
|
|
|
593
593
|
* contextually type a parameter against a multi-signature type, so a hand-built
|
|
594
594
|
* ctx object must annotate its `(reference, args)` explicitly — see
|
|
595
595
|
* `@lunora/testing`'s harness). It does not work: a concrete
|
|
596
|
-
* `RegisteredQuery
|
|
597
|
-
* `RegisteredFunction
|
|
596
|
+
* `RegisteredQuery<{…}, number>` is not assignable to a
|
|
597
|
+
* `RegisteredFunction<ArgsValidator, …>` constraint, because `handler`'s args
|
|
598
598
|
* are in a contravariant position. Two inference sites it is.
|
|
599
599
|
*/
|
|
600
600
|
interface RunQuery {
|
|
@@ -638,7 +638,7 @@ type RegisteredLifecycleHook = RegisteredFunction<Record<string, never>, void, "
|
|
|
638
638
|
};
|
|
639
639
|
/**
|
|
640
640
|
* A streaming query registration. Unlike {@link RegisteredFunction} the handler
|
|
641
|
-
* returns an `AsyncIterable
|
|
641
|
+
* returns an `AsyncIterable<R>` synchronously (it does NOT `Promise<R>`); the
|
|
642
642
|
* runtime drives it frame by frame and forwards each chunk to the caller. The
|
|
643
643
|
* third `signal` argument is wired to the caller's cancel signal so the handler
|
|
644
644
|
* can stop early — break out of the loop or check `signal.aborted` between
|
|
@@ -689,7 +689,7 @@ interface SystemQuery<T extends SystemTableName> {
|
|
|
689
689
|
* Read-only reader over Lunora's system tables (`_scheduled_functions`,
|
|
690
690
|
* `_storage`), exposed as `ctx.db.system`. Mirrors Convex's `ctx.db.system`.
|
|
691
691
|
*
|
|
692
|
-
* **Best-effort and eventually consistent.** Unlike `ctx.db
|
|
692
|
+
* **Best-effort and eventually consistent.** Unlike `ctx.db.<table>` — which
|
|
693
693
|
* reads the shard's transactional SQLite snapshot — the data behind these tables
|
|
694
694
|
* lives OUTSIDE the shard (scheduled functions in the `SchedulerDO`, storage
|
|
695
695
|
* objects in R2). Every `collect()` / `get()` reaches across to that source.
|
|
@@ -728,7 +728,7 @@ interface DatabaseReader {
|
|
|
728
728
|
*
|
|
729
729
|
* This is the **parse boundary** for an id that arrived as a plain `string`: a
|
|
730
730
|
* wire payload, a mutator's args, a change plan computed on the client. The
|
|
731
|
-
* alternative is `value as Id
|
|
731
|
+
* alternative is `value as Id<"table">` at every such call site — an assertion,
|
|
732
732
|
* not a check, and one that has to be repeated for every table a helper is
|
|
733
733
|
* generic over:
|
|
734
734
|
*
|
|
@@ -794,8 +794,8 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
794
794
|
}
|
|
795
795
|
/**
|
|
796
796
|
* The fluent `ctx.db.query(table)` reader. Generic over the document type
|
|
797
|
-
* `Row` so the generated `ctx.db` can bind it to `Doc
|
|
798
|
-
* every terminal then resolve typed rows — no `as unknown as Doc
|
|
797
|
+
* `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
|
|
798
|
+
* every terminal then resolve typed rows — no `as unknown as Doc<...>` casts),
|
|
799
799
|
* and over the table's declared index names so `.withIndex()` / `.withSearchIndex()`
|
|
800
800
|
* / `.withGeoIndex()` reject a name the table does not declare.
|
|
801
801
|
*
|
|
@@ -815,9 +815,9 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
815
815
|
* **Why `with*` are method signatures and everything else is a property.**
|
|
816
816
|
* Narrowing a parameter makes the enclosing type contravariant in it, so as
|
|
817
817
|
* function properties these would make a BOUND reader
|
|
818
|
-
* (`TableReader
|
|
819
|
-
* the unbound `TableReader
|
|
820
|
-
* `(reader: TableReader
|
|
818
|
+
* (`TableReader<Doc, "by_x">`, what `ctx.db.query(t)` returns) unassignable to
|
|
819
|
+
* the unbound `TableReader<Doc>` — quietly breaking every helper factored as
|
|
820
|
+
* `(reader: TableReader<Doc<"users">>) => …`, which is the obvious way to share
|
|
821
821
|
* query logic. A method signature is bivariant in its parameters, which keeps
|
|
822
822
|
* that direction working while the narrow parameter still rejects an undeclared
|
|
823
823
|
* name at the call site. Both directions are pinned in `types.test-d.ts`.
|
|
@@ -1122,8 +1122,8 @@ interface ScheduledJob {
|
|
|
1122
1122
|
shardKey?: string;
|
|
1123
1123
|
}
|
|
1124
1124
|
/**
|
|
1125
|
-
* A schedulable durable-workflow reference — the generated `workflows
|
|
1126
|
-
* `agents
|
|
1125
|
+
* A schedulable durable-workflow reference — the generated `workflows.<name>` /
|
|
1126
|
+
* `agents.<name>` object, which carries its `WORKFLOW_*`/`AGENT_*` binding and
|
|
1127
1127
|
* stable name. Structural mirror of `@lunora/scheduler`'s `WorkflowReference` so
|
|
1128
1128
|
* `ctx.scheduler` can target a workflow/agent without a dependency on
|
|
1129
1129
|
* `@lunora/scheduler` / `@lunora/workflow`. A scheduled workflow target starts a
|
|
@@ -1147,8 +1147,8 @@ interface Scheduler {
|
|
|
1147
1147
|
list: () => Promise<ScheduledJob[]>;
|
|
1148
1148
|
/**
|
|
1149
1149
|
* Schedule a one-shot run `delayMs` from now. `target` is a function path
|
|
1150
|
-
* (`"ns:fn"`) dispatched as a one-shot, or a generated `workflows
|
|
1151
|
-
* `agents
|
|
1150
|
+
* (`"ns:fn"`) dispatched as a one-shot, or a generated `workflows.<name>` /
|
|
1151
|
+
* `agents.<name>` reference which starts a fresh durable instance on fire
|
|
1152
1152
|
* (the args become its `params`).
|
|
1153
1153
|
*/
|
|
1154
1154
|
runAfter: (delayMs: number, target: SchedulableWorkflowReference | string, args?: Record<string, unknown>) => Promise<string>;
|
|
@@ -1370,12 +1370,12 @@ interface TriggerRankPageOptions {
|
|
|
1370
1370
|
/**
|
|
1371
1371
|
* Portable, table/id-addressed ORM writer handed to trigger handlers via
|
|
1372
1372
|
* `ctx.db`. Mirrors `@lunora/do`'s runtime `DatabaseWriterLike` surface — it is
|
|
1373
|
-
* **not** the generated per-table `ctx.db
|
|
1373
|
+
* **not** the generated per-table `ctx.db.<table>` facade (which can't be typed
|
|
1374
1374
|
* from inside `defineTable`, where the full schema isn't known).
|
|
1375
1375
|
*
|
|
1376
1376
|
* `aggregate`/`groupBy`/`count`/`rank`/`rankPage` route through the same
|
|
1377
1377
|
* trigger-maintained counter and rank tables the user-facing reader uses, so
|
|
1378
|
-
* a handler's `ctx.db
|
|
1378
|
+
* a handler's `ctx.db.<table>.aggregate(...)` observes the just-staged write
|
|
1379
1379
|
* within the same DO transaction (the counter step happens before the trigger
|
|
1380
1380
|
* fires).
|
|
1381
1381
|
*/
|
|
@@ -1562,7 +1562,7 @@ interface VectorSearch<IndexName extends string = string> extends VectorSearchRe
|
|
|
1562
1562
|
}
|
|
1563
1563
|
/**
|
|
1564
1564
|
* Structured, filterable key/value fields attached to a log line — the second
|
|
1565
|
-
* argument of a `ctx.log
|
|
1565
|
+
* argument of a `ctx.log.<level>(message, fields)` call, or the fields bound by
|
|
1566
1566
|
* `ctx.log.with(fields)`. They travel to an `ObservabilitySink`'s `onLog` and,
|
|
1567
1567
|
* for a network sink, become OTLP log-record attributes a log pipeline (or the
|
|
1568
1568
|
* Cloud log viewer) can filter and index on. Primitive values pass through;
|
|
@@ -1682,7 +1682,7 @@ interface SpanHandle {
|
|
|
1682
1682
|
addLink: (link: SpanLink) => void;
|
|
1683
1683
|
/**
|
|
1684
1684
|
* Attach an AI **evaluation** verdict to this (generation) span as the
|
|
1685
|
-
* `gen_ai.evaluation
|
|
1685
|
+
* `gen_ai.evaluation.<name>.score` / `.label` OpenTelemetry attributes, so a
|
|
1686
1686
|
* scorer's grade rides the same trace as the generation it graded. Convenience
|
|
1687
1687
|
* over {@link SpanHandle.setAttributes} that owns the key format; privacy-safe —
|
|
1688
1688
|
* only the name, score, and optional label are emitted. Throws on an empty name
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.63",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -66,9 +66,9 @@
|
|
|
66
66
|
"access": "public"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
71
|
-
"@lunora/values": "1.0.0-alpha.
|
|
69
|
+
"@lunora/errors": "1.0.0-alpha.15",
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.22",
|
|
71
|
+
"@lunora/values": "1.0.0-alpha.20",
|
|
72
72
|
"drizzle-orm": "^0.45.2",
|
|
73
73
|
"hono": "^4.12.32"
|
|
74
74
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{indexRolePermissions as f,computeReadBaseWhere as h,permissionName as d}from"./rls-tRDkICWZ.mjs";import{l as u}from"./policy-tag-Dprt9JWo.mjs";import{deny as p}from"./allowAll-BnyNbJZT.mjs";const c=p(),b=t=>{const e=t?.rls?.tags;if(e)return e;const o=u(t);return o?[o]:[]},g=(t,e)=>{const o=f(e.roles),r=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=r.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),r.set(s.table,a);const i=n.get(s.table)??[];i.push(s),n.set(s.table,i)}for(const[s,a]of n){const i=t.get(s)??[];i.push({policies:a,rolePermissions:o}),t.set(s,i)}},l=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},m=(t,e)=>!t||Object.keys(t).length===0?e:l(t)||Object.keys(e).length===0?t:{AND:[t,e]},y=(t,e)=>{const o=new Set;for(const r of e.roles)for(const n of t.rolePermissions.get(r)??[])o.add(n);return h(t.policies,{auth:{can:r=>o.has(d(r)),identity:e.identity,roles:e.roles,userId:e.userId},ctx:e.ctx})},R=(t,e)=>{const o=t.byTable.get(e.table);if(!o||o.length===0)return e.rlsRequired&&!e.tablePublic?c:void 0;const r=[];for(const n of o){const s=y(n,e);if(s===void 0)return;l(s)||r.push(s)}return r.length===0?c:r.length===1?r[0]:{OR:r}},S=t=>{const e=new Map,o=new Set;for(const r of t)for(const n of b(r))o.has(n)||(o.add(n),g(e,n));return{byTable:e}},x=(t,e)=>m(R(t,e),e.shapeWhere);export{S as buildRlsReadRegistry,x as composeShapeReadWhere};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as E}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as v}from"@lunora/values";import{Hono as P}from"hono";import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";const H=e=>async t=>e(t.get("lunora"),t.req.raw),z=()=>{const e=new P;return e.use("*",async(t,a)=>{const r=t.env.__lunoraCtx;if(!r)throw new p("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",r),await a()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,y=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},_=(e,t,a)=>{const r=k(e);if(r.kind==="array"){const o=t.req.queries(a);if(o===void 0)return;const n=r._meta?.inner;return o.map(c=>y(n?.kind??"string",c))}const s=t.req.query(a);return s===void 0?void 0:y(r.kind,s)},S=(e,t)=>{const a={};for(const r of Object.keys(e)){const s=e[r];s&&(a[r]=_(s,t,r))}return R(e,a,"searchParams")},N=(e,t)=>{const a=t.req.param(),r={};for(const s of Object.keys(e)){const o=e[s];if(!o)continue;const n=a[s];r[s]=n===void 0?void 0:y(k(o).kind,n)}return R(e,r,"params")},x=async(e,t)=>{let a;try{a=await t.req.json()}catch{throw new p("BAD_REQUEST","Invalid JSON body")}if(typeof a!="object"||a===null||Array.isArray(a))throw new p("BAD_REQUEST","Expected a JSON object body");return R(e,a,"body")},A=(e,t)=>{try{return e.parse(t)}catch(a){throw a instanceof v?new p("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${a.message}`):a}},O=e=>{if(e instanceof v)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof p){const{body:t,redacted:a,status:r}=E(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return a&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:r})}throw e},q=(e,t)=>async a=>{try{const r=a.get("lunora"),s=Object.keys(e.searchParams).length>0?S(e.searchParams,a):{},o=Object.keys(e.params).length>0?N(e.params,a):{},n=Object.keys(e.body).length>0?await x(e.body,a):{},c=await t({body:n,ctx:r,params:o,searchParams:s}),i=e.output?A(e.output,c):c,u={};e.cacheControl&&(u["cache-control"]=e.cacheControl),e.cacheTag&&(u["cache-tag"]=e.cacheTag),e.vary&&(u.vary=e.vary);const m=Object.keys(u).length>0;return i===void 0?new Response(null,{headers:m?u:void 0,status:204}):Response.json(i,{headers:m?u:void 0})}catch(r){return O(r)}},g=(e,t)=>{const a=JSON.stringify(e);return`${t?`event: ${t}
|
|
2
|
-
`:""}data: ${a}
|
|
3
|
-
|
|
4
|
-
`},C=(e,t)=>async a=>{let r,s;try{r=Object.keys(e.searchParams).length>0?S(e.searchParams,a):{},s=Object.keys(e.params).length>0?N(e.params,a):{}}catch(d){return O(d)}const o=a.get("lunora"),n=a.req.raw,c=new TextEncoder,i=new AbortController;if(n.signal.aborted)return i.abort(),new Response(new ReadableStream({start:d=>{d.close()}}),{headers:{"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}});const u=()=>{i.abort()};n.signal.addEventListener("abort",u,{once:!0});const m=new ReadableStream({cancel(){n.signal.removeEventListener("abort",u),i.abort()},async start(d){try{const f=t({ctx:o,params:s,request:n,searchParams:r,signal:i.signal});for await(const b of f){if(i.signal.aborted)break;d.enqueue(c.encode(g(b)))}d.enqueue(c.encode(g({},"complete")))}catch(f){const{body:b,redacted:j}=E(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});j&&console.error("[lunora] unhandled stream handler error:",f),d.enqueue(c.encode(g({code:b.code,message:b.message},"error")))}finally{n.signal.removeEventListener("abort",u),d.close()}}}),T={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"};return new Response(m,{headers:T})},l=e=>({body:t=>l({...e,body:{...e.body,...t}}),cacheControl:t=>l({...e,cacheControl:t}),cacheTag:t=>l({...e,cacheTag:t}),handler:t=>q(e,t),output:t=>l({...e,output:t}),params:t=>l({...e,params:{...e.params,...t}}),searchParams:t=>l({...e,searchParams:{...e.searchParams,...t}}),stream:t=>C(e,t),vary:t=>l({...e,vary:t})}),h=e=>t=>l({body:{},method:e,params:{},path:t,searchParams:{}}),U={delete:h("DELETE"),get:h("GET"),head:h("HEAD"),options:h("OPTIONS"),patch:h("PATCH"),post:h("POST"),put:h("PUT")},$=/^bytes=(\d*)-(\d*)$/,w=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,I=e=>{for(let t=0;t<e.length;t+=1){const a=e.codePointAt(t);if(a===13||a===10||a===0)return!1}return!0},L=(e,t)=>{if(e===null)return{kind:"full"};const a=$.exec(e.trim());if(!a)return{kind:"full"};const r=a[1]??"",s=a[2]??"";if(r===""&&s==="")return{kind:"full"};let o,n;if(r===""){const c=Number(s);if(c===0)return{kind:"unsatisfiable"};o=Math.max(0,t-c),n=t-1}else o=Number(r),n=s===""?t-1:Math.min(Number(s),t-1);return o>n||o>=t?{kind:"unsatisfiable"}:{end:n,kind:"partial",start:o}},W=async(e,t,a)=>{const r=await e.storage.download(t);if(!r)return new Response("Not Found",{status:404});const s=r.httpMetadata?.contentType,o={"accept-ranges":"bytes","content-type":s!==void 0&&I(s)?s:"application/octet-stream",etag:w(r.etag)};r.sha256Base64!==void 0&&(o["repr-digest"]=`sha-256=:${r.sha256Base64}:`);const n=L(a.headers.get("range"),r.size);if(n.kind==="unsatisfiable")return r.body?.cancel().catch(()=>{}),new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:w(r.etag)},status:416});if(n.kind==="full")return new Response(r.body,{headers:{...o,"content-length":String(r.size)},status:200});r.body?.cancel().catch(()=>{});const c=n.end-n.start+1,i=await e.storage.download(t,{range:{length:c,offset:n.start}});return i?new Response(i.body,{headers:{...o,"content-length":String(c),"content-range":`bytes ${String(n.start)}-${String(n.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{H as httpAction,U as httpRoute,z as httpRouter,I as isSafeHeaderValue,W as serveStorageObject};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as g}from"./functions-CDC08CWY.mjs";import{readMaskTag as w}from"./buildMaskRegistry-BCIzKxdK.mjs";import{l as f}from"./policy-tag-Dprt9JWo.mjs";import{l as x}from"./run-middleware-BeEEqmdE.mjs";const y=(t,e)=>e===void 0||typeof t!="object"||t===null?t:Object.assign(Object.create(Object.getPrototypeOf(t)),t,{meta:e}),p=(t,e)=>x(t,e,s=>s),b=(t,e,s,a,i)=>async(r,d)=>{const l=g(t,d),n=await p(e,y(r,i)),m=await s({args:l,ctx:n});return a?a.parse(m):m},k=(t,e,s)=>(a,i,r)=>{const d=g(t,i);return(async function*(){const l=await p(e,a),n=s({args:d,ctx:l,signal:r})[Symbol.asyncIterator]();try{for(;;){if(r.aborted)return;const m=await n.next();if(m.done||r.aborted)return;yield m.value}}finally{await n.return?.()}})()},u=t=>{const e=[];for(const s of t){const a=f(s);a&&e.push(a)}return e.length>0?{tags:e}:void 0},c=t=>{const e=new Map;for(const s of t){const a=w(s);if(a)for(const[i,r]of a.columns){const d=e.get(i)??new Set;for(const l of r)d.add(l);e.set(i,d)}}return e.size>0?e:void 0},o=(t,e,s)=>({__lunoraProcedure:t,...s?{__lunoraVisibility:s}:{},input:a=>o(t,{...e,args:{...e.args,...a}},s),[t]:a=>{const i=u(e.middlewares),r=c(e.middlewares);return{args:e.args,...e.expose?{expose:e.expose}:{},handler:b(e.args,e.middlewares,a,e.output,e.meta),kind:t,...r?{maskedTables:r}:{},...e.meta?{meta:e.meta}:{},...i?{rls:i}:{},...s?{visibility:s}:{},...e.x402?{x402:e.x402}:{}}},meta:a=>o(t,{...e,meta:{...e.meta,...a}},s),output:a=>o(t,{...e,output:a},s),...t==="query"?{stream:a=>{const i=u(e.middlewares),r=c(e.middlewares);return{args:e.args,...e.expose?{expose:e.expose}:{},handler:k(e.args,e.middlewares,a),kind:"stream",...r?{maskedTables:r}:{},...i?{rls:i}:{},...s?{visibility:s}:{},...e.x402?{x402:e.x402}:{}}}}:{},use:a=>o(t,{...e,middlewares:[...e.middlewares,a]},s),...s?{}:{expose:a=>o(t,{...e,expose:a},s)},...s?{}:{x402:a=>o(t,{...e,x402:a},s)}}),q={dataModel:()=>({create:t=>({action:o("action",{args:{},middlewares:[]}),internalAction:o("action",{args:{},middlewares:[]},"internal"),internalMutation:o("mutation",{args:{},middlewares:[]},"internal"),internalQuery:o("query",{args:{},middlewares:[]},"internal"),mutation:o("mutation",{args:{},middlewares:[]}),query:o("query",{args:{},middlewares:[]})})})};export{q as initLunora};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";import{bindOrm as T,bindTableFacade as W}from"./bindOrm-Bp9hsM2q.mjs";import{o as P}from"./optional-writer-override-CXXO30sZ.mjs";import{tagMaskMiddleware as R}from"./buildMaskRegistry-BCIzKxdK.mjs";const O=n=>typeof n=="string"?n:n.name,F=n=>{const o=new Map;for(const s of n??[])o.set(s.name,new Set((s.permissions??[]).map(l=>O(l))));return o},j=n=>{let o=2166136261;for(let s=0;s<n.length;s+=1)o^=n.codePointAt(s)??0,o=Math.imul(o,16777619);return(o>>>0).toString(16).padStart(8,"0")},U=(n,o,s)=>{try{return n==="redact"?null:n==="hash"?o==null?o:j(typeof o=="string"?o:JSON.stringify(o)):n(o,s)}catch{return null}},u=(n,o,s)=>{const l={...n};for(const[w,h]of Object.entries(o))w in l&&(l[w]=U(h,n[w],{...s,column:w,row:n}));return l},N=(n,o,s)=>({...n,page:n.page.map(l=>u(l,o,s))}),v=(n,o,s,l)=>{if(typeof n!="function")return;const w=new Set,h=()=>new Proxy({},{get:()=>d=>(typeof d=="string"&&w.add(d),h())});n(h());for(const d of w)if(d in o)throw new p("MASK_UNSUPPORTED",`${l}() filtering "${s}" by masked column "${d}" is not supported`)},_=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return!1;const o=n;return typeof o.findMany=="function"&&typeof o.withSearchIndex=="function"},E=(n,o,s,l)=>{const w=n.rankBefore,h=n.rankPageRows,d=(t,e,a,r)=>{const i=o.get(t);if(!i)return;const c=l?.[t]?.[r]?.[e];if(!c)return;const A=c.find(B=>B in i);if(A!==void 0)throw new p("MASK_UNSUPPORTED",`${a}() reading "${t}" via index "${e}" would order rows by masked column "${A}" — use an index whose declared fields are all unmasked, or unmask the column`)},y=(t,e,a)=>({async*[Symbol.asyncIterator](){for await(const r of{[Symbol.asyncIterator]:()=>t[Symbol.asyncIterator]()})yield u(r,e,s)},collect:async()=>(await t.collect()).map(r=>u(r,e,s)),collectWithScores:async()=>(await t.collectWithScores()).map(r=>{const i=u(r.document,e,s);return"distanceMeters"in r?{distanceMeters:null,document:i}:{document:i,score:r.score}}),filter:r=>y(t.filter(i=>r(u(i,e,s))),e,a),first:async()=>{const r=await t.first();return r?u(r,e,s):null},order:r=>y(t.order(r),e,a),paginate:async r=>N(await t.paginate(r),e,s),take:async r=>(await t.take(r)).map(i=>u(i,e,s)),unique:async()=>{const r=await t.unique();return r?u(r,e,s):null},withIndex:(r,i)=>(d(a,r,"withIndex","index"),v(i,e,a,"withIndex"),y(t.withIndex(r,i),e,a)),withSearchIndex:(r,i)=>(v(i,e,a,"withSearchIndex"),y(t.withSearchIndex(r,i),e,a)),withGeoIndex:(r,i)=>(d(a,r,"withGeoIndex","geo"),y(t.withGeoIndex(r,i),e,a))}),S=async(t,e)=>{if(n.lookupById){const c=await n.lookupById(t,e);return c?{row:c.row,tableName:o.has(c.tableName)?c.tableName:void 0}:{row:null,tableName:void 0}}const a=await n.get(t,e);if(!a)return{row:null,tableName:void 0};let r;e===void 0?r=[...o.keys()]:o.has(e)?r=[e]:r=[];const i=await Promise.all(r.map(async c=>(await n.findFirst(c,{limit:1,where:{_id:t}}))?._id===t?c:void 0));return{row:a,tableName:i.find(c=>c!==void 0)}},M=(t,e,a)=>{const r=o.get(t);if(!r)return;const i=e.find(c=>typeof c=="string"&&c in r);if(i!==void 0)throw new p("MASK_UNSUPPORTED",`${a}() over masked column "${i}" on "${t}" is not supported`)},m=(t,e)=>{if(!(!t||typeof t!="object"||Array.isArray(t)))for(const[a,r]of Object.entries(t))if(a==="AND"||a==="OR"){if(Array.isArray(r))for(const i of r)m(i,e)}else a==="NOT"?m(r,e):a.startsWith("__")||e.add(a)},f=(t,e,a)=>{const r=o.get(t);if(!r||e===void 0)return;const i=new Set;m(e,i);for(const c of i)if(c in r)throw new p("MASK_UNSUPPORTED",`${a}() filtering "${t}" by masked column "${c}" is not supported`)},b=(t,e,a)=>{const r=o.get(t);if(!(!r||!Array.isArray(e))){for(const i of e)if(i&&typeof i=="object"&&!Array.isArray(i)){for(const c of Object.keys(i))if(c in r)throw new p("MASK_UNSUPPORTED",`${a}() ordering "${t}" by masked column "${c}" is not supported`)}}},I=t=>t&&typeof t=="object"&&!Array.isArray(t)?t:void 0,g=(t,e,a)=>{const r=I(e);f(t,r?.where,a),f(t,r?.baseWhere,a)},k={...n,async deleteWhere(t,e,a){if(f(t,e,"deleteMany({ where })"),n.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return n.deleteWhere(t,e,a)},async patchWhere(t,e,a){if(f(t,e.where,"patchMany({ where })"),n.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${t}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return n.patchWhere(t,e,a)},aggregate(t,e){return M(t,[e.field],"aggregate"),f(t,e.where,"aggregate"),n.aggregate(t,e)},count(t,e){const a=e&&typeof e=="object"&&!Array.isArray(e)?e:void 0,r=a&&("where"in a||"baseWhere"in a||"restrictsCounts"in a)?a.where:e;return f(t,r,"count"),a&&f(t,a.baseWhere,"count"),n.count(t,e)},async findFirst(t,e){f(t,e?.where,"findFirst"),f(t,e?.baseWhere,"findFirst"),b(t,e?.orderBy,"findFirst");const a=await n.findFirst(t,e),r=o.get(t);return a&&r?u(a,r,s):a},async findFirstOrThrow(t,e){f(t,e?.where,"findFirstOrThrow"),f(t,e?.baseWhere,"findFirstOrThrow"),b(t,e?.orderBy,"findFirstOrThrow");const a=await n.findFirstOrThrow(t,e),r=o.get(t);return r?u(a,r,s):a},async findMany(t,e){f(t,e?.where,"findMany"),f(t,e?.baseWhere,"findMany"),b(t,e?.orderBy,"findMany");const a=await n.findMany(t,e),r=o.get(t);return r?N(a,r,s):a},async get(t,e){const{row:a,tableName:r}=await S(t,e),i=r===void 0?void 0:o.get(r);return!a||!i?a:u(a,i,s)},async lookupById(t,e){const a=await n.lookupById?.(t,e);if(!a)return null;const r=o.get(a.tableName);return{row:r?u(a.row,r,s):a.row,tableName:a.tableName}},groupBy(t,e){return M(t,[...e.by,e.agg?.field],"groupBy"),f(t,e.where,"groupBy"),n.groupBy(t,e)},query(t){const e=n.query(t),a=o.get(t);return a?y(e,a,t):e},async rank(t,e,a){return g(t,a,"rank"),d(t,e,"rank","rank"),n.rank(t,e,a)},async rankPage(t,e,a){g(t,a,"rankPage"),d(t,e,"rankPage","rank");const r=await n.rankPage(t,e,a),i=o.get(t);return i?N(r,i,s):r},...P("rankBefore",w,t=>(e,a,r)=>(g(e,r,"rankBefore"),d(e,a,"rankBefore","rank"),t(e,a,r))),...P("rankPageRows",h,t=>async(e,a,r)=>{g(e,r,"rankPageRows"),d(e,a,"rankPageRows","rank");const i=await t(e,a,r),c=o.get(e);return c?{...i,rows:i.rows.map(A=>({...A,doc:u(A.doc,c,s)}))}:i})},x=k;for(const t of o.keys())_(n[t])&&(x[t]=W(k,t));return k},G=(n,o={})=>{const s=new Map(Object.entries(n)),l=F(o.roles),w=async({ctx:d,next:y})=>{const S=d.auth??{},M=await S.getIdentity?.()??null,m=S.roles??[],f=new Set;for(const x of m)for(const t of l.get(x)??[])f.add(t);const b={auth:{can:x=>f.has(O(x)),identity:M,roles:m,userId:S.userId??null},ctx:d};if(o.bypass?.(b))return y();const I=E(d.db,s,b,o.indexFields),g={db:I},{orm:k}=d;return k!==null&&typeof k=="object"&&(g.orm=T(I)),y({ctx:g})},h=new Map;for(const[d,y]of s)h.set(d,new Set(Object.keys(y)));return R(w,{columns:h})};export{G as mask};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=(t,o,c)=>o?{[t]:c(o)}:{};export{e as o};
|