@lunora/server 1.0.0-alpha.94 → 1.0.0-alpha.96
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/README.md +1 -1
- package/dist/index.d.mts +85 -50
- package/dist/index.d.ts +85 -50
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-BG6A6rHA.mjs → ACTION_CACHE_DEFAULT_TTL_MS-OuQ-AJjz.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-CXOIUOBE.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-wgfbacHx.mjs} +1 -1
- package/dist/packem_shared/{LunoraEnvError-_BakoYQ3.mjs → LunoraEnvError-CXbrsFI8.mjs} +2 -2
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-lsooaSaF.mjs +1 -0
- package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
- package/dist/packem_shared/{bindOrm-lWdeDi9P.mjs → bindOrm-ChQydkdL.mjs} +1 -1
- package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
- package/dist/packem_shared/buildRlsReadRegistry-CIGmNx0b.mjs +1 -0
- package/dist/packem_shared/compose-middleware-3i5Qk3sb.mjs +1 -0
- package/dist/packem_shared/composePluginMiddleware-pe7Ncehp.mjs +1 -0
- package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
- package/dist/packem_shared/{createSecrets-CyrEddTF.mjs → createSecrets-D6rLB42U.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-C3kWoQ-P.mjs → defineAggregateIndex-DFVCeuX1.mjs} +1 -1
- package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
- package/dist/packem_shared/{defineShape-DYxbNl5W.mjs → defineShape-BWgwFuMT.mjs} +1 -1
- package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
- package/dist/packem_shared/httpAction-B8X6jXen.mjs +5 -0
- package/dist/packem_shared/initLunora-D5TSiy5j.mjs +1 -0
- package/dist/packem_shared/mask-pIhIWBcr.mjs +1 -0
- package/dist/packem_shared/middleware-Cz5s6CH-.mjs +1 -0
- package/dist/packem_shared/plugin-yKCbHnlj.mjs +1 -0
- package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
- package/dist/packem_shared/protectPublic-Csf6ObbJ.mjs +1 -0
- package/dist/packem_shared/rls-BjRa5pMm.mjs +1 -0
- package/dist/packem_shared/run-middleware-CuM-Chm3.mjs +1 -0
- package/dist/packem_shared/storageRules-DHvF6Fjq.mjs +1 -0
- package/dist/packem_shared/{wire-codec-hZHn-Ooo.mjs → wire-codec-uveYSVra.mjs} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +83 -22
- package/dist/types.d.ts +83 -22
- package/package.json +4 -4
- package/dist/packem_shared/LunoraError-DcKdk9Ti.mjs +0 -1
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-B6z9BcPN.mjs +0 -1
- package/dist/packem_shared/apply-output-D7vpBeeu.mjs +0 -1
- package/dist/packem_shared/buildMaskRegistry-72SL8fJn.mjs +0 -1
- package/dist/packem_shared/buildRlsReadRegistry-Ct60PLD-.mjs +0 -1
- package/dist/packem_shared/composePluginMiddleware-D8I_XMLV.mjs +0 -1
- package/dist/packem_shared/createPolicyDsl-DNfByAUX.mjs +0 -1
- package/dist/packem_shared/defineMigration-7GI9Qbtd.mjs +0 -1
- package/dist/packem_shared/defineStorageRule-BvxHVq3b.mjs +0 -1
- package/dist/packem_shared/httpAction-DEN_78Kj.mjs +0 -5
- package/dist/packem_shared/initLunora-BxNkWYTz.mjs +0 -1
- package/dist/packem_shared/mask-NVloFLLY.mjs +0 -1
- package/dist/packem_shared/middleware-EloVU9X1.mjs +0 -1
- package/dist/packem_shared/plugin-DfuRhJS1.mjs +0 -1
- package/dist/packem_shared/policy-tag-D4RzgQnw.mjs +0 -1
- package/dist/packem_shared/protectPublic-Bo4G9xaV.mjs +0 -1
- package/dist/packem_shared/rls-B6du_B-q.mjs +0 -1
- package/dist/packem_shared/run-middleware-B-JeGGp9.mjs +0 -1
- package/dist/packem_shared/storageRules-91NHMDL6.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-uveYSVra.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-D5TSiy5j.mjs";import{g as k,h as q,a as B}from"./plugin-yKCbHnlj.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as A,e as h}from"./wire-codec-uveYSVra.mjs";import{initLunora as v}from"./initLunora-D5TSiy5j.mjs";import{g as x,h as R,a as U}from"./plugin-yKCbHnlj.mjs";const H=2160*60*60*1e3,q=64*1024,E=200,C=64,F=512,y=16,L=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],p="documentHistory",I="versions",l=`${p}_${I}`,P=x(p,{tables:{[I]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:j}=v.dataModel().create(),X=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):q,D=new Set([...B,...d.redact??[]]);let b=0;const M=()=>(b+=1,b),m=(e,t=0)=>{if(Array.isArray(e))return t>=y?void 0:e.map(o=>m(o,t+1));if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=y))return Object.fromEntries(Object.entries(e).filter(([o])=>!D.has(o)).map(([o,i])=>[o,m(i,t+1)]))},f=e=>{if(e===void 0)return;const t=JSON.stringify(h(m(e)));return new TextEncoder().encode(t).length>_?void 0:t},u=async(e,t)=>{const o=f(t.doc),i=f(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:M(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},S=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>u(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>u(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=j.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):E,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,a)=>{for(const c of L){const s=(a[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:A(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:A(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let a=0;a<C&&n<i;a+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(E,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(p,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:S}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,X as defineDocumentHistory,P as documentHistoryExtension};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{optionalInner as h}from"@lunora/values";const b=/(?:key|password|secret|token)$/iu,d=t=>b.test(t),
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{optionalInner as h}from"@lunora/values";const b=/(?:key|password|secret|token)$/iu,d=t=>b.test(t),w=[/^sk_/u,/^pk_/u,/^rk_/u,/^ghp_/u,/^gho_/u,/^ghs_/u,/^ghr_/u,/^github_pat_/u,/^xox[baprs]-/u,/^AKIA/u,/^AIza/u,/^Bearer\s/u],L=/[\w./+-]{24,}/gu,p=/^[\w./+-]+$/u,I=/\b(?:(?:sk|pk|rk|ghp|gho|ghs|ghr)_[\w./+-]*|github_pat_[\w./+-]*|xox[baprs]-[\w./+-]*)/gu,N=/\b(?:AKIA|AIza)[\w./+-]+|Bearer\s+[\w./+-]+/gu,v=/:\/\/([\w.%+-]*):[\w.%+-]+@/gu,a="[redacted]",D=t=>{if(w.some(n=>n.test(t)))return!0;const e=t.trim();return e.length>=24&&p.test(e)},S=/(["'])(?<inner>(?:\\.|(?!\1).)*)\1/gu,y=/\b(?<key>[A-Za-z_]\w*)\s*[=:]\s*\S+/gu,T=t=>{let e=t;return e=e.replaceAll(S,(n,...r)=>{const s=r.at(-1);return s?.inner!==void 0&&D(s.inner)?a:n}),e=e.replaceAll(v,(n,r)=>`://${r}:${a}@`),e=e.replaceAll(I,a),e=e.replaceAll(N,a),e=e.replaceAll(y,(n,...r)=>{const s=r.at(-1);return s?.key!==void 0&&d(s.key)?`${s.key}=${a}`:n}),e=e.replaceAll(L,a),e},R=(t,e,n)=>{const r=T(t);return typeof n=="string"&&n!==""&&d(e)?r.replaceAll(n,a):r};class g extends A{failures;constructor(e){const n=e.map(r=>` - ${r.key}: ${r.message}`).join(`
|
|
2
2
|
`);super("ENV_INVALID",`Invalid environment (${String(e.length)} key(s)):
|
|
3
|
-
${n}`,{name:"LunoraEnvError"}),this.failures=e}}const
|
|
3
|
+
${n}`,{name:"LunoraEnvError"}),this.failures=e}}const K=new Set(["1","on","true","yes"]),O=new Set(["0","false","no","off"]),$=/^-?\d+$/u,k=t=>{if(t.kind!=="optional")return t.kind;const e=h(t);return e?k(e):t.kind},U=(t,e)=>{if(typeof e!="string")return e;switch(k(t)){case"bigint":return $.test(e.trim())?BigInt(e.trim()):e;case"boolean":{const n=e.trim().toLowerCase();return K.has(n)?!0:O.has(n)?!1:e}case"number":{const n=e.trim();if(n==="")return e;const r=Number(n);return Number.isNaN(r)?e:r}default:return e}},_=(t,e,n,r)=>{const s=n[t];if(s===void 0&&e.kind==="optional")return{ok:!0,value:void 0};const c=e.safeParse(U(e,s));return c.ok?{ok:!0,value:c.value}:(r.push({key:t,message:R(c.error.message,t,s)}),{ok:!1})},m=t=>{if(typeof t!="object"||t===null)throw new g([{key:"<env>",message:`expected an object, received ${t===null?"null":typeof t}`}]);return t},F=t=>{const e=Object.keys(t),n=new WeakMap,r=(s=>{const c=m(s);let i=n.get(c);i===void 0&&(i=new Map,n.set(c,i));const l=i,E=u=>{if(l.has(u))return l.get(u);const o=[],f=_(u,t[u],c,o);if(!f.ok)throw new g(o);return l.set(u,f.value),f.value};return new Proxy({},{get(u,o){if(!(typeof o!="string"||!(o in t)))return E(o)},getOwnPropertyDescriptor(u,o){if(typeof o=="string"&&o in t)return{configurable:!0,enumerable:!0,value:E(o),writable:!1}},has(u,o){return typeof o=="string"&&o in t},ownKeys(){return e}})});return r.parse=s=>{const c=m(s),i=[],l={};for(const E of e){const u=_(E,t[E],c,i);u.ok&&u.value!==void 0&&(l[E]=u.value)}if(i.length>0)throw new g(i);return l},r};export{g as LunoraEnvError,F as defineEnv,T as redactSecrets};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-D5TSiy5j.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-yKCbHnlj.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({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"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.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(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("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},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).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 I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";import{ValidationError as a}from"@lunora/values";const p=(t,e)=>{try{return t.parse(e,{rejectUnknownKeys:!0})}catch(r){throw r instanceof a?new o("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${r.message}`):r}};export{p as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";const u=e=>typeof e=="object"&&e!==null&&e.code==="CONFLICT"&&e.kind==="unique",a=(e,t,
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";const u=e=>typeof e=="object"&&e!==null&&e.code==="CONFLICT"&&e.kind==="unique",a=(e,t,r)=>{const i=typeof t=="string"?[t]:t;if(i.length===0)throw new h("INTERNAL",`ctx.db.${e}.upsert: "target" must name at least one field`);const n={};for(const s of i){if(!(s in r))throw new h("INTERNAL",`ctx.db.${e}.upsert: target field "${s}" is missing from the create document`);n[s]=r[s]}return n},f=(e,t)=>{const r=async(n,s)=>{if(s?.skipDuplicates!==!0)return e.insert(t,n);try{return await e.insert(t,n)}catch(o){if(u(o))return null;throw o}},i=async({create:n,target:s,update:o})=>{const d=a(t,s,n),c=await e.findFirst(t,{where:d});return c&&typeof c._id=="string"?(await e.patch(c._id,o??n,t),{created:!1,id:c._id}):{created:!0,id:await e.insert(t,n)}};return{aggregate:n=>e.aggregate(t,n),count:n=>e.count(t,n),delete:n=>e.delete(n,t),deleteMany:(n,s)=>{if(Array.isArray(n)){if(e.deleteMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return e.deleteMany(n,s,t)}if(e.deleteWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const o=n;return e.deleteWhere(t,o.where,{limit:o.limit})},exists:async n=>await e.findFirst(t,n===void 0?void 0:{where:n})!==null,findFirst:n=>e.findFirst(t,n),findFirstOrThrow:n=>e.findFirstOrThrow(t,n),findMany:n=>e.findMany(t,n),get:n=>e.get(n,t),groupBy:n=>e.groupBy(t,n),hardDelete:n=>e.delete(n,t,{hard:!0}),insert:r,insertMany:(n,s)=>{if(e.insertMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return e.insertMany(t,n,s)},patch:(n,s)=>e.patch(n,s,t),patchMany:(n,s)=>{if(Array.isArray(n)){if(e.patchMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return e.patchMany(n.map(d=>({id:d.id,patch:d.values})),s,t)}if(e.patchWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const o=n;return e.patchWhere(t,{patch:o.values,where:o.where},{limit:o.limit})},rank:(n,s)=>e.rank(t,n,s),rankPage:(n,s)=>e.rankPage(t,n,s),replace:(n,s)=>e.replace(n,s,t),restore:async n=>{if(!e.restore)throw new h("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await e.restore(n,t)},upsert:i,upsertMany:async({rows:n,target:s})=>{const o=[];for(const d of n)o.push(await i({create:d.create,target:s,update:d.update}));return o},withGeoIndex:(n,s)=>e.query(t).withGeoIndex(n,s),withSearchIndex:(n,s)=>e.query(t).withSearchIndex(n,s)}},l=e=>{const t=r=>{const i=e[r];if(!i)throw new h("INTERNAL",`unknown table: ${r}`);return i};return{delete:(r,i)=>t(r).delete(i),insert:r=>({values:i=>t(r).insert(i)}),query:e,replace:(r,i)=>({with:n=>t(r).replace(i,n)}),update:(r,i)=>({set:n=>t(r).patch(i,n)})}};export{l as bindOrm,f as bindTableFacade};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const u=Symbol.for("lunora.mask.middleware-columns"),l=(o,n)=>(Object.defineProperty(o,u,{configurable:!0,enumerable:!1,value:n}),o),f=o=>{if(!(o===null||typeof o!="function"&&typeof o!="object"))return o[u]},i=o=>{const n=new Map;for(const c of o){const t=f(c);if(t)for(const[e,r]of t.columns){const s=n.get(e)??new Set;for(const a of r)s.add(a);n.set(e,s)}}return n.size>0?n:void 0},b=o=>{const n=new Map;for(const c of o){const t=c?.maskedTables;if(t)for(const[e,r]of t){const s=n.get(e)??new Set;for(const a of r)s.add(a);n.set(e,s)}}return n};export{b as buildMaskRegistry,f as readMaskTag,l as tagMaskMiddleware,i as unionMaskColumns};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as d,c as f,d as h}from"./middleware-Cz5s6CH-.mjs";import{r as p}from"./policy-tag-V0lqFzgS.mjs";import{deny as u}from"./allowAll-DkRAgItV.mjs";const c=u(),g=s=>{const e=s?.rls?.tags;return e||p(s)},b=(s,e)=>{const r=d(e.roles),t=new Map,n=new Map;for(const o of e.policies){if(o.on!=="read")continue;const a=t.get(o.table)??new Set;if(a.has(o.when))continue;a.add(o.when),t.set(o.table,a);const i=n.get(o.table)??[];i.push(o),n.set(o.table,i)}for(const[o,a]of n){const i=s.get(o)??[];i.push({policies:a,rolePermissions:r}),s.set(o,i)}},l=s=>{const e=s.OR;return Array.isArray(e)&&e.length===0&&Object.keys(s).length===1},y=(s,e)=>!s||Object.keys(s).length===0?e:l(s)||Object.keys(e).length===0?s:{AND:[s,e]},R=(s,e)=>f(s.policies,{auth:{can:h(e.roles,s.rolePermissions),identity:e.identity,roles:e.roles,userId:e.userId},ctx:e.ctx}),m=(s,e)=>{const r=s.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?c:void 0;const t=[];for(const n of r){const o=R(n,e);if(o===void 0)return;l(o)||t.push(o)}return t.length===0?c:t.length===1?t[0]:{OR:t}},P=s=>{const e=new Map,r=new Set;for(const t of s)for(const n of g(t))r.has(n)||(r.add(n),b(e,n));return{byTable:e}},W=(s,e)=>y(m(s,e),e.shapeWhere);export{P as buildRlsReadRegistry,W as composeShapeReadWhere};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{unionMaskColumns as n,tagMaskMiddleware as d}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as m,t as i}from"./policy-tag-V0lqFzgS.mjs";import{r as c}from"./run-middleware-CuM-Chm3.mjs";const g=s=>{const o=(async({ctx:r,next:e})=>c(s,r,l=>e({ctx:l}))),a=s.flatMap(r=>m(r));a.length>0&&i(o,a);const t=n(s);return t&&d(o,{columns:t}),o};export{g as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./compose-middleware-3i5Qk3sb.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-yKCbHnlj.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";const c=e=>({on:e.on,table:e.table,when:e.when}),l=()=>e=>({on:e.on,table:e.table,when:e.when}),a=(e,n={})=>({name:e,...n}),d=e=>{const n=new Map;for(const o of e){const r=JSON.stringify([o.table,o.on]),t=n.get(r)??new Set;if(t.has(o.when))throw new i("INTERNAL",`definePolicies: duplicate policy for (table "${o.table}", on "${o.on}") — the same decision function is registered more than once. Multiple distinct policies per (table, on) are allowed (reads OR, writes AND); remove the duplicate.`);t.add(o.when),n.set(r,t)}return e},h=(e,n={})=>({name:e,...n});export{l as createPolicyDsl,a as definePermission,d as definePolicies,c as definePolicy,h as defineRole};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as n}from"@lunora/errors";const o=["put","list","delete","getWithMetadata","head","createMultipartUpload","idFromName","newUniqueId","getByName","send","sendBatch","writeDataPoint","create","createBatch"],s=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.get!="function"?!1:!o.some(r=>typeof e[r]=="function")},
|
|
1
|
+
import{LunoraError as n}from"@lunora/errors";const o=["put","list","delete","getWithMetadata","head","createMultipartUpload","idFromName","newUniqueId","getByName","send","sendBatch","writeDataPoint","create","createBatch"],s=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.get!="function"?!1:!o.some(r=>typeof e[r]=="function")},i=t=>({get:async e=>{const r=t[e];if(!s(r))throw new n("INTERNAL",`ctx.secrets: no Secrets Store binding named "${e}". Add a \`secrets_store_secrets[]\` entry (binding "${e}", pointing at your store + secret) to wrangler.jsonc — \`ctx.secrets\` reads a Secrets Store binding, not a plain \`.dev.vars\` value.`);return r.get()}});export{i as createSecrets};
|
package/dist/packem_shared/{defineAggregateIndex-C3kWoQ-P.mjs → defineAggregateIndex-DFVCeuX1.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-
|
|
1
|
+
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-yKCbHnlj.mjs";export{d as defineAggregateIndex,n as defineRankIndex,i as defineSchema,s as defineTable,f as defineVectorIndex,x as indexFieldsFromSchema,r as validateIndexFields};
|
|
@@ -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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as 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,
|
|
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,5 @@
|
|
|
1
|
+
import{LunoraError as y,toErrorBody as k,isLunoraError as x}from"@lunora/errors";import{parseValidatorMap as E,ValidationError as H}from"@lunora/values";import{Hono as C}from"hono";import{a as L}from"./apply-output-C5wZ5EAL.mjs";const Q=e=>async t=>e(t.get("lunora"),t.req.raw),Y=()=>{const e=new C;return e.use("*",async(t,r)=>{const n=t.env.__lunoraCtx;if(!n)throw new y("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",n),await r()}),e},O=e=>e.kind==="optional"?e._meta?.inner??e:e,R=(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,r)=>{const n=O(e);if(n.kind==="array"){const a=t.req.queries(r);if(a===void 0)return;const s=n._meta?.inner;return a.map(c=>R(s?.kind??"string",c))}const o=t.req.query(r);return o===void 0?void 0:R(n.kind,o)},N=(e,t)=>{const r={};for(const n of Object.keys(e)){const o=e[n];o&&(r[n]=$(o,t,n))}return E(e,r,"searchParams")},v=(e,t)=>{const r=t.req.param(),n={};for(const o of Object.keys(e)){const a=e[o];if(!a)continue;const s=r[o];n[o]=s===void 0?void 0:R(O(a).kind,s)}return E(e,n,"params")},B=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new y("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new y("BAD_REQUEST","Expected a JSON object body");return E(e,r,"body")},T=e=>{if(e instanceof H)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(x(e)){const{body:t,redacted:r,status:n}=k(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:n})}throw e},j=(e,t)=>{const{method:r}=t.req;if(!(r===e.method||e.method==="GET"&&r==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${r} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},D=(e,t)=>async r=>{const n=j(e,r);if(n)return n;try{const o=r.get("lunora"),a=Object.keys(e.searchParams).length>0?N(e.searchParams,r):{},s=Object.keys(e.params).length>0?v(e.params,r):{},c=Object.keys(e.body).length>0?await B(e.body,r):{},h=await t({body:c,ctx:o,params:s,searchParams:a}),i=e.output?L(e.output,h):h,d={};e.cacheControl&&(d["cache-control"]=e.cacheControl),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const f=Object.keys(d).length>0;return i===void 0?new Response(null,{headers:f?d:void 0,status:204}):Response.json(i,{headers:f?d:void 0})}catch(o){return T(o)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,t)=>{const r=JSON.stringify(e);return`${t?`event: ${t}
|
|
2
|
+
`:""}data: ${r}
|
|
3
|
+
|
|
4
|
+
`},I=(e,t)=>(async r=>{const n=j(e,r);if(n)return n;let o,a;try{o=Object.keys(e.searchParams).length>0?N(e.searchParams,r):{},a=Object.keys(e.params).length>0?v(e.params,r):{}}catch(p){return T(p)}const s=r.get("lunora"),c=r.req.raw,h=new TextEncoder,i=new AbortController;if(c.signal.aborted)return i.abort(),new Response("",{headers:w});const d=()=>{i.abort()};c.signal.addEventListener("abort",d,{once:!0});const f=new ReadableStream({cancel(){c.signal.removeEventListener("abort",d),i.abort()},async start(p){try{const m=t({ctx:s,params:a,request:c,searchParams:o,signal:i.signal});for await(const g of m){if(i.signal.aborted)break;p.enqueue(h.encode(b(g)))}i.signal.aborted||p.enqueue(h.encode(b({},"complete")))}catch(m){const{body:g,redacted:q}=k(m,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});q&&console.error("[lunora] unhandled stream handler error:",m),i.signal.aborted||p.enqueue(h.encode(b({code:g.code,message:g.message},"error")))}finally{c.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:t=>u({...e,body:{...e.body,...t}}),cacheControl:t=>u({...e,cacheControl:t}),cacheTag:t=>u({...e,cacheTag:t}),handler:t=>D(e,t),output:t=>u({...e,output:t}),params:t=>u({...e,params:{...e.params,...t}}),searchParams:t=>u({...e,searchParams:{...e.searchParams,...t}}),stream:t=>I(e,t),vary:t=>u({...e,vary:t})}),l=e=>t=>u({body:{},method:e,params:{},path:t,searchParams:{}}),z={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},M=/^bytes=(\d*)-(\d*)$/,A=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,W=e=>!(e.includes("\r")||e.includes(`
|
|
5
|
+
`)||e.includes("\0")),_=(e,t)=>{if(e===null)return{kind:"full"};const r=M.exec(e.trim());if(!r)return{kind:"full"};const n=r[1]??"",o=r[2]??"";if(n===""&&o==="")return{kind:"full"};let a,s;if(n===""){const c=Number(o);if(c===0)return{kind:"unsatisfiable"};a=Math.max(0,t-c),s=t-1}else a=Number(n),s=o===""?t-1:Math.min(Number(o),t-1);return a>s||a>=t?{kind:"unsatisfiable"}:{end:s,kind:"partial",start:a}},P=e=>{const t=e.httpMetadata?.contentType,r={"accept-ranges":"bytes","content-type":t!==void 0&&W(t)?t:"application/octet-stream",etag:A(e.etag)};return e.sha256Base64!==void 0&&(r["repr-digest"]=`sha-256=:${e.sha256Base64}:`),r},V=e=>_(e,0).kind==="full",S=async(e,t)=>{const r=await e.storage.download(t);return r?new Response(r.body,{headers:{...P(r),"content-length":String(r.size)},status:200}):new Response("Not Found",{status:404})},K=async(e,t,r)=>{const n=r.headers.get("range");if(V(n))return S(e,t);const o=await e.storage.head(t);if(!o)return new Response("Not Found",{status:404});const a=_(n,o.size);if(a.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(o.size)}`,"content-type":"text/plain; charset=utf-8",etag:A(o.etag)},status:416});if(a.kind==="full")return S(e,t);const s=a.end-a.start+1,c=await e.storage.download(t,{range:{length:s,offset:a.start}});return c?new Response(c.body,{headers:{...P(o),"content-length":String(s),"content-range":`bytes ${String(a.start)}-${String(a.end)}/${String(o.size)}`},status:206}):new Response("Not Found",{status:404})};export{Q as httpAction,z as httpRoute,Y as httpRouter,W as isSafeHeaderValue,K as serveStorageObject};
|
|
@@ -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 P}from"@lunora/errors";import{f as B}from"./fnv1a-D6VtE8WR.mjs";import{bindTableFacade as E,bindOrm as _}from"./bindOrm-ChQydkdL.mjs";import{i as D,a as K,o as v,b as q}from"./middleware-Cz5s6CH-.mjs";import{tagMaskMiddleware as m}from"./buildMaskRegistry-DpWMtalG.mjs";const G=(i,e,c)=>{try{return i==="redact"?null:i==="hash"?e==null?e:typeof e=="bigint"?B(e.toString()):B(typeof e=="string"?e:JSON.stringify(e)):i(e,c)}catch{return null}},a=(i,e,c)=>{const y={...i};for(const[h,g]of Object.entries(e))h in y&&(y[h]=G(g,i[h],{...c,column:h,row:i}));return y},W=(i,e,c)=>({...i,page:i.page.map(y=>a(y,e,c))}),U=(i,e,c,y)=>{if(typeof i!="function")return;const h=new Set,g=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&h.add(f),g())});i(g());for(const f of h)if(f in e)throw new P("MASK_UNSUPPORTED",`${y}() filtering "${c}" by masked column "${f}" is not supported`)},L=(i,e,c,y)=>{const h=i.rankBefore,g=i.rankPageRows,f=(r,n)=>{const t=e.get(r);return t?n.map(o=>a(o,t,c)):n},p=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?f:(t,o)=>n(t,f(t,o))}},k=(r,n,t,o)=>{const s=e.get(r);if(!s)return;const d=y?.[r]?.[o]?.[n];if(!d)return;const w=d.find($=>$ in s);if(w!==void 0)throw new P("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${w}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,n,c)},collect:async()=>(await r.collect()).map(s=>a(s,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const d=a(s.document,n,c);return"distanceMeters"in s?{distanceMeters:null,document:d}:{document:d,score:s.score}}),filter:o=>l(r.filter(s=>o(a(s,n,c))),n,t),first:async()=>{const o=await r.first();return o?a(o,n,c):null},order:o=>l(r.order(o),n,t),paginate:async o=>W(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(d=>a(d,n,c)),unique:async()=>{const o=await r.unique();return o?a(o,n,c):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),U(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(U(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),S=async(r,n)=>{if(i.lookupById){const w=await i.lookupById(r,n);return w?{row:w.row,tableName:e.has(w.tableName)?w.tableName:void 0}:{row:null,tableName:void 0}}const t=await i.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&e.has(n)?[n]:[],s=n===void 0?[...e.keys()]:o,d=await Promise.all(s.map(async w=>(await i.findFirst(w,{limit:1,where:{_id:r}}))?._id===r?w:void 0));return{row:t,tableName:d.find(w=>w!==void 0)}},M=(r,n,t)=>{const o=e.get(r);if(!o)return;const s=n.find(d=>typeof d=="string"&&d in o);if(s!==void 0)throw new P("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},R=(r,n)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[t,o]of Object.entries(r))if(t==="AND"||t==="OR"){if(Array.isArray(o))for(const s of o)R(s,n)}else t==="NOT"?R(o,n):t.startsWith("__")||n.add(t)},u=(r,n,t)=>{const o=e.get(r);if(!o||n===void 0)return;const s=new Set;R(n,s);for(const d of s)if(d in o)throw new P("MASK_UNSUPPORTED",`${t}() filtering "${r}" by masked column "${d}" is not supported`)},I=(r,n,t)=>{const o=e.get(r);if(!(!o||!Array.isArray(n))){for(const s of n)if(s&&typeof s=="object"&&!Array.isArray(s)){for(const d of Object.keys(s))if(d in o)throw new P("MASK_UNSUPPORTED",`${t}() ordering "${r}" by masked column "${d}" is not supported`)}}},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,A=(r,n,t)=>{const o=F(n);u(r,o?.where,t),u(r,o?.baseWhere,t)},O={...i,async deleteWhere(r,n,t){if(u(r,n,"deleteMany({ where })"),i.deleteWhere===void 0)throw new P("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return i.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(u(r,n.where,"patchMany({ where })"),i.patchWhere===void 0)throw new P("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return i.patchWhere(r,n,t)},aggregate(r,n){return M(r,[n.field],"aggregate"),u(r,n.where,"aggregate"),i.aggregate(r,n)},count(r,n){const t=F(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return u(r,o,"count"),t&&u(r,t.baseWhere,"count"),i.count(r,n)},async findFirst(r,n){u(r,n?.where,"findFirst"),u(r,n?.baseWhere,"findFirst"),I(r,n?.orderBy,"findFirst");const t=await i.findFirst(r,p(n)),o=e.get(r);return t&&o?a(t,o,c):t},async findFirstOrThrow(r,n){u(r,n?.where,"findFirstOrThrow"),u(r,n?.baseWhere,"findFirstOrThrow"),I(r,n?.orderBy,"findFirstOrThrow");const t=await i.findFirstOrThrow(r,p(n)),o=e.get(r);return o?a(t,o,c):t},async findMany(r,n){u(r,n?.where,"findMany"),u(r,n?.baseWhere,"findMany"),I(r,n?.orderBy,"findMany");const t=await i.findMany(r,p(n)),o=e.get(r);return o?W(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await S(r,n),s=o===void 0?void 0:e.get(o);return!t||!s?t:a(t,s,c)},async lookupById(r,n){const t=await i.lookupById?.(r,n);if(!t)return null;const o=e.get(t.tableName);return{row:o?a(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return M(r,[...n.by,n.agg?.field],"groupBy"),u(r,n.where,"groupBy"),i.groupBy(r,n)},query(r){const n=i.query(r),t=e.get(r);return t?l(n,t,r):n},async rank(r,n,t){return A(r,t,"rank"),k(r,n,"rank","rank"),i.rank(r,n,t)},async rankPage(r,n,t){A(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await i.rankPage(r,n,t),s=e.get(r);return s?W(o,s,c):o},...v("rankBefore",h,r=>(n,t,o)=>(A(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),...v("rankPageRows",g,r=>async(n,t,o)=>{A(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),d=e.get(n);return d?{...s,rows:s.rows.map(w=>({...w,doc:a(w.doc,d,c)}))}:s})},j=O;for(const r of e.keys())q(i[r])&&(j[r]=E(O,r));return O},V=(i,e={})=>{const c=new Map(Object.entries(i)),y=D(e.roles),h=async({ctx:f,next:p})=>{const k={auth:await K(f.auth??{},y),ctx:f};if(e.bypass?.(k))return p();const l=L(f.db,c,k,e.indexFields),S={db:l},{orm:M}=f;return M!==null&&typeof M=="object"&&(S.orm=_(l)),p({ctx:S})},g=new Map;for(const[f,p]of c)g.set(f,new Set(Object.keys(p)));return m(h,{columns:g})};export{V as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as W}from"@lunora/errors";import{bindTableFacade as L,bindOrm as T}from"./bindOrm-ChQydkdL.mjs";import{t as j}from"./policy-tag-V0lqFzgS.mjs";import{deny as $}from"./allowAll-DkRAgItV.mjs";const S=(r,t,i)=>t?{[r]:i(t)}:{},D=500,B=(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})},q=$(),N=Symbol.for("lunora.ctxdb.rls-unwrap"),K=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},Y=(r,t)=>{const i=[];let a=!1;for(const h of r){if(h.on!=="read")continue;const f=h.when(t);if(f!==void 0){if(f===!0){a=!0;break}f!==!1&&i.push(f)}}if(!a)return i.length===0?q:i.length===1?i[0]:{OR:i}},P=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),z=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],p=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},H=(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)),G=(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))},Q=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:G(r,t)&&H(r,t),X=(r,t,i,a)=>t==="AND"?Array.isArray(i)&&i.every(h=>a(r,h)):t==="OR"?Array.isArray(i)&&i.some(h=>a(r,h)):!a(r,i??{}),C=r=>r==="AND"||r==="OR"||r==="NOT",J=r=>P(r)&&Object.keys(r).every(t=>z.includes(t)),Z=["every","is","isNot","none","some"],x=r=>P(r)&&Object.keys(r).length>0&&Object.keys(r).every(t=>Z.includes(t)),E=r=>Object.keys(r).some(t=>{const i=r[t];return C(t)?t==="NOT"?E(i??{}):Array.isArray(i)&&i.some(a=>E(a??{})):x(i)}),A=(r,t)=>{for(const i of Object.keys(t)){const a=t[i];if(C(i)){if(!X(r,i,a,A))return!1;continue}const h=r[i];if(J(a)){if(!Q(h,a))return!1;continue}if(h!==a)return!1}return!0},V=(r,t,i)=>{const a=r.when({...t,row:i});if(a===void 0||a===!0)return!0;if(a===!1)return!1;if(E(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 A(i,a)},ee=(r,t,i)=>{const a=r.when(t);if(a===void 0||a===!0)return i===void 0||V(r,t,i);if(a===!1)return!1;if(E(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||!A(t.row,a)?!1:i===void 0||A(i,a)},_=(r,t,i,a)=>{let h=!1;for(const f of r)if(f.on===t&&(h=!0,!ee(f,i,a)))return!1;return h},re=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),te=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":P(t),ne=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(i=>re.has(i)&&te(i,r[i]))},se=r=>r===void 0?{}:P(r)&&ne(r)?r:{where:r},w=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},ie=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},oe=(r,t,i,a)=>{const h=new Map,f=e=>{const n=h.get(e);if(n)return n;const s=i.get(e);if(!s||s.length===0||!s.some(l=>l.on==="read")){const l={baseWhere:void 0,restricts:!1};return h.set(e,l),l}const c={baseWhere:Y(s,a),restricts:!0};return h.set(e,c),c},d=e=>f(e).restricts?t:r,y=e=>f(e).baseWhere,O=async(e,n)=>{if(t.lookupById){const u=await t.lookupById(e,n);return u?{row:u.row,tableName:i.has(u.tableName)?u.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,l=await Promise.all(c.map(async u=>(await t.findFirst(u,{limit:1,where:{_id:e}}))?._id===e?u:void 0));return{row:s,tableName:l.find(u=>u!==void 0)}},M=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 l=await M(e,c);if(!l)return s(r);const u=i.get(l.tableName);if(u){const k=o?o(l.row):void 0;if(!_(u,n,{...a,row:l.row},k))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},v=r.rankBefore,m=r.rankPageRows,R={...r,async count(e,n){const{baseWhere:s,restricts:o}=f(e),c=se(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 u=(await d(e).findMany(e,{baseWhere:o,limit:s,relationBaseWhere:y})).page.map(k=>String(k._id));if(u.length===0)break;for(const k of u)await g(k,"delete",I=>I.delete(k,void 0,n?.hard===void 0?void 0:{hard:n.hard})),c+=1;if(u.length<s)break}return{deleted:c}},async deleteMany(e,n,s){B(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),l=(await d(e).findMany(e,{baseWhere:w(n,o),relationBaseWhere:y})).page.map(u=>String(u._id));return B(l.length,s?.limit,"deleteWhere"),R.deleteMany(l,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 l=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return l?._id===e?l: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){B(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){B(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){B(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),l=(await d(e).findMany(e,{baseWhere:w(n.where,o),relationBaseWhere:y})).page.map(u=>({id:String(u._id),patch:n.patch}));return B(l.length,s?.limit,"patchWhere"),R.patchMany(l,s)},query(e){const{baseWhere:n}=f(e),s=d(e).query(e);return n?s.filter(o=>A(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})},...S("rankBefore",v,e=>(n,s,o)=>(b(n,"rankBefore"),(d(n).rankBefore??e)(n,s,o))),...S("rankPageRows",m,e=>(n,s,o)=>{const c=b(n,"rankPageRows");return(d(n).rankPageRows??e)(n,s,{...o,baseWhere:w(o?.baseWhere,c)})})},U=R;for(const e of i.keys())ie(r[e])&&(U[e]=L(R,e));return R},F=r=>typeof r=="string"?r:r.name,ae=r=>{const t=new Map;for(const i of r??[])t.set(i.name,new Set((i.permissions??[]).map(a=>F(a))));return t},ce=(r,t)=>{const i=new Set;for(const a of r)for(const h of t.get(a)??[])i.add(h);return a=>i.has(F(a))},fe=async(r,t)=>{const i=r.roles??[];return{can:ce(i,t),identity:await r.getIdentity?.()??null,roles:i,userId:r.userId??null}},ye=(r,t={})=>{const i=K(r),a=ae(t.roles);return j(async({ctx:f,next:d})=>{const y={auth:await fe(f.auth??{},a),ctx:f},O=f.db,M=O[N]??O,g=oe(O,M,i,y),b={db:g},{orm:v}=f;return v!==null&&typeof v=="object"&&(b.orm=T(g)),d({ctx:b})},[{policies:r,roles:t.roles??[]}])};export{fe as a,ie as b,Y as c,ce as d,_ as e,ae as i,A as m,S as o,F as p,ye as r};
|
|
@@ -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"./bindOrm-ChQydkdL.mjs";import{c as o,e as m,i as t,b as p,m as l,p as c,d as n,a as d,r as h}from"./middleware-Cz5s6CH-.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{o as computeReadBaseWhere,m as evaluateWrite,t as indexRolePermissions,p as isFacadeEntry,l as matchesWhere,c as permissionName,n as resolveCan,d as resolvePolicyAuth,h 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{LunoraError as y}from"@lunora/errors";import{i as U,a as v}from"./middleware-Cz5s6CH-.mjs";const D=(o,e)=>o===void 0||e.startsWith(o),k=o=>{const e=o[1],c=typeof e=="object"&&e!==null?e.method:void 0;return typeof c=="string"&&c.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",k],["getUrl","read"],["head","read"],["store","write"]],S=(o,e={})=>{const c=U(e.roles);return async({ctx:u,next:f})=>{const w=await v(u.auth??{},c),g=(n,r,s)=>{const i=o.filter(t=>t.on===n&&t.bucket===s);if(i.length===0)return;const a={auth:w,ctx:u,key:r};if(!i.some(t=>D(t.prefix,r)&&t.when(a)===!0))throw new y("FORBIDDEN",`storage ${n} on "${r}" in bucket "${s}" denied by access rule`)},p=n=>{const r=n.bucketName??"default",s={bucketName:r};for(const[a,d]of E){const t=n[a];typeof t=="function"&&(s[a]=(...l)=>{const m=typeof l[0]=="string"?l[0]:"",b=typeof d=="function"?d(l):d;return g(b,m,r),t(...l)})}const{bucket:i}=n;return typeof i=="function"&&(s.bucket=a=>p(i(a))),s},h=u.storage;return h===void 0?f():f({ctx:{storage:p(h)}})}};export{S as storageRules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const A=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},
|
|
1
|
+
const A=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),f=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)f[o]=t.codePointAt(o)??0;return f},i="$lunora.wire$";const d="__proto__",m={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},w={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},E=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 f=typeof e;if(f==="bigint")return[i,"bigint",e.toString()];if(f==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(f!=="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 a of Object.keys(r))r[a]!==void 0&&(n[a]=u(r[a],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",A(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",A(c)]:[i,"bytes",A(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(!E(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===d?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":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(w,r)?w[r]:void 0)??Error,a=new c(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const g=y(e[4],t+1);for(const b of Object.keys(g))b===d?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:g[b],writable:!0}):a[b]=g[b];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}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(m,n)?m[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 f=e,o={};for(const s of Object.keys(f)){const r=y(f[s],t+1);s===d?Object.defineProperty(o,s,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[s]=r}return o};export{y as d,u as e};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as b,d as P,c as W,m as v,e as y}from"../packem_shared/middleware-
|
|
1
|
+
import{i as b,d as P,c as W,m as v,e as y}from"../packem_shared/middleware-Cz5s6CH-.mjs";const C=(d,c={})=>{const m=b(c.roles),h=c.ctx??{};return{as:x=>{const n=x??{},i=n.roles??[],l={auth:{can:P(i,m),identity:n.identity??null,roles:i,userId:n.userId??null},ctx:h},u=(e,o,t,a)=>{const r=d.filter(s=>s.table===o);if(r.length===0)return!0;if(e==="read"){if(!r.some(f=>f.on==="read"))return!0;const s=W(r,l);return s===void 0||v(t??{},s)}return y(r,e,{...l,row:t},a)};return{can:u,cannot:(e,o,t,a)=>!u(e,o,t,a)}}}};export{C as expectPolicy};
|
package/dist/types.d.mts
CHANGED
|
@@ -575,12 +575,6 @@ interface RegisteredFunction<A extends ArgsValidator, R, Kind extends FunctionKi
|
|
|
575
575
|
* Absent on ordinary registrations.
|
|
576
576
|
*/
|
|
577
577
|
readonly lifecycle?: LifecycleEventKind;
|
|
578
|
-
/**
|
|
579
|
-
* Static per-procedure metadata declared with `.meta(...)`. Present so
|
|
580
|
-
* middleware (via `ctx.meta`) and tooling can read the same object; absent
|
|
581
|
-
* when the chain never called `.meta()`.
|
|
582
|
-
*/
|
|
583
|
-
readonly meta?: Readonly<Record<string, unknown>>;
|
|
584
578
|
readonly visibility?: FunctionVisibility;
|
|
585
579
|
/**
|
|
586
580
|
* Set by the `.x402({ price })` builder modifier. Marks the procedure as paid
|
|
@@ -747,8 +741,6 @@ interface RegisteredStream<A extends ArgsValidator, R> {
|
|
|
747
741
|
readonly durable?: DurableStreamOptions;
|
|
748
742
|
readonly handler: (context: unknown, args: InferArgs<A>, signal: AbortSignal) => AsyncIterable<R>;
|
|
749
743
|
readonly kind: "stream";
|
|
750
|
-
/** Static per-procedure metadata attached via `.meta()`. See {@link RegisteredFunction.meta}. */
|
|
751
|
-
readonly meta?: Readonly<Record<string, unknown>>;
|
|
752
744
|
readonly visibility?: FunctionVisibility;
|
|
753
745
|
}
|
|
754
746
|
/**
|
|
@@ -1603,8 +1595,12 @@ interface StorageMetadata {
|
|
|
1603
1595
|
interface StorageObjectHead {
|
|
1604
1596
|
/** Custom metadata set at upload time, if any. */
|
|
1605
1597
|
customMetadata?: Record<string, string>;
|
|
1606
|
-
/**
|
|
1607
|
-
|
|
1598
|
+
/**
|
|
1599
|
+
* R2's unquoted etag (the MD5 hex for a single-part upload). Required: R2
|
|
1600
|
+
* reports one on every object, and an HTTP layer built on `head()` (the
|
|
1601
|
+
* `serveStorageObject` helper) needs it to emit a validator.
|
|
1602
|
+
*/
|
|
1603
|
+
etag: string;
|
|
1608
1604
|
/** The already-quoted form of {@link StorageObjectHead.etag}, when the binding reports one. */
|
|
1609
1605
|
httpEtag?: string;
|
|
1610
1606
|
/** Recorded HTTP metadata, notably the `Content-Type`. */
|
|
@@ -1622,6 +1618,30 @@ interface StorageObjectHead {
|
|
|
1622
1618
|
/** When the object was last written. */
|
|
1623
1619
|
uploaded?: Date;
|
|
1624
1620
|
}
|
|
1621
|
+
/**
|
|
1622
|
+
* Byte window forwarded to {@link ReadOnlyStorage.download} so R2 resolves the
|
|
1623
|
+
* slice server-side and streams only those bytes back. Mirrors R2's own `range`
|
|
1624
|
+
* option (`@lunora/platform`'s `R2RangeLike`), restated structurally so
|
|
1625
|
+
* `@lunora/server` takes no dependency on the bindings package.
|
|
1626
|
+
*/
|
|
1627
|
+
type StorageRange = {
|
|
1628
|
+
length?: number;
|
|
1629
|
+
offset: number;
|
|
1630
|
+
} | {
|
|
1631
|
+
length: number;
|
|
1632
|
+
offset?: number;
|
|
1633
|
+
} | {
|
|
1634
|
+
suffix: number;
|
|
1635
|
+
};
|
|
1636
|
+
/**
|
|
1637
|
+
* A downloaded object: the same metadata {@link StorageObjectHead} carries, plus
|
|
1638
|
+
* the body stream. This is what `download()` resolves to — R2's object, NOT a
|
|
1639
|
+
* bare stream.
|
|
1640
|
+
*/
|
|
1641
|
+
interface StorageObjectBody extends StorageObjectHead {
|
|
1642
|
+
/** The object body stream. `null` for a zero-byte object. */
|
|
1643
|
+
body: ReadableStream | null;
|
|
1644
|
+
}
|
|
1625
1645
|
/**
|
|
1626
1646
|
* Read-only projection of `Storage` exposed on `QueryCtx` / `MutationCtx`.
|
|
1627
1647
|
*
|
|
@@ -1641,8 +1661,29 @@ interface ReadOnlyStorage<Buckets extends string = string> {
|
|
|
1641
1661
|
bucket: (name: Buckets) => ReadOnlyStorage<Buckets>;
|
|
1642
1662
|
/** The bucket this accessor's operations target (the default for the bare `ctx.storage`). */
|
|
1643
1663
|
readonly bucketName: string;
|
|
1644
|
-
/**
|
|
1645
|
-
|
|
1664
|
+
/**
|
|
1665
|
+
* Fetch an existing object. Returns the R2 object — metadata plus a `body`
|
|
1666
|
+
* stream — or `null` when absent.
|
|
1667
|
+
*
|
|
1668
|
+
* NOT a bare stream: `new Response(await ctx.storage.download(key))` would
|
|
1669
|
+
* stringify the object and serve the literal text `[object Object]`. Reach
|
|
1670
|
+
* for the body explicitly:
|
|
1671
|
+
*
|
|
1672
|
+
* ```ts
|
|
1673
|
+
* const object = await ctx.storage.download(key);
|
|
1674
|
+
*
|
|
1675
|
+
* return object ? new Response(object.body) : new Response("Not found", { status: 404 });
|
|
1676
|
+
* ```
|
|
1677
|
+
*
|
|
1678
|
+
* (`serveStorageObject` from `@lunora/server` does this, plus range/ETag
|
|
1679
|
+
* handling, for the common "serve a stored file over HTTP" case.)
|
|
1680
|
+
*
|
|
1681
|
+
* Pass `range` to have R2 resolve the byte window server-side, so the
|
|
1682
|
+
* unwanted bytes never reach the worker.
|
|
1683
|
+
*/
|
|
1684
|
+
download: (key: string, options?: {
|
|
1685
|
+
range?: StorageRange;
|
|
1686
|
+
}) => Promise<StorageObjectBody | null>;
|
|
1646
1687
|
/**
|
|
1647
1688
|
* Read a file's metadata (size, content-type, sha256, upload time, custom
|
|
1648
1689
|
* metadata) without fetching its body. Returns `null` when the object is
|
|
@@ -1697,6 +1738,23 @@ interface Storage<Buckets extends string = string> extends ReadOnlyStorage<Bucke
|
|
|
1697
1738
|
contentType?: string;
|
|
1698
1739
|
expiresInSeconds?: number;
|
|
1699
1740
|
}) => Promise<string>;
|
|
1741
|
+
/**
|
|
1742
|
+
* Mint a native S3 SigV4 URL that hits R2 **directly**, so the bytes never
|
|
1743
|
+
* pass through the Worker — unlike {@link Storage.generateUploadUrl}, whose
|
|
1744
|
+
* signed URL points back at this app so its storage rules still apply.
|
|
1745
|
+
*
|
|
1746
|
+
* Requires `s3` credentials on the `.storage({ s3 })` declaration; without
|
|
1747
|
+
* them the call throws. That is the trade-off: no Worker in the path also
|
|
1748
|
+
* means no rule enforcement in the path.
|
|
1749
|
+
*
|
|
1750
|
+
* Declared structurally rather than imported — `@lunora/server` does not
|
|
1751
|
+
* depend on `@lunora/storage`, and this file mirrors that surface the same
|
|
1752
|
+
* way `head` and `download` do.
|
|
1753
|
+
*/
|
|
1754
|
+
getPresignedUrl: (key: string, options?: {
|
|
1755
|
+
expiresInSeconds?: number;
|
|
1756
|
+
method?: "GET" | "PUT";
|
|
1757
|
+
}) => Promise<string>;
|
|
1700
1758
|
/**
|
|
1701
1759
|
* Upload `body` to `key` from the server, returning the stored object's key
|
|
1702
1760
|
* and etag. Mirrors Convex's `storage.store`. Accepts the same guard fields
|
|
@@ -2106,9 +2164,10 @@ interface QueryCtx {
|
|
|
2106
2164
|
/** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
|
|
2107
2165
|
/**
|
|
2108
2166
|
* Static metadata declared on this procedure with `.meta(...)`, merged
|
|
2109
|
-
* across calls. Present so middleware can read the policy it
|
|
2110
|
-
* enforce (`ctx.meta.rateLimit`, …) instead of having it
|
|
2111
|
-
* `.use()` site; absent when the procedure never called
|
|
2167
|
+
* across calls and deep-frozen. Present so middleware can read the policy it
|
|
2168
|
+
* is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
|
|
2169
|
+
* hard-wired at each `.use()` site; absent when the procedure never called
|
|
2170
|
+
* `.meta()`.
|
|
2112
2171
|
*/
|
|
2113
2172
|
readonly meta?: Readonly<Record<string, unknown>>;
|
|
2114
2173
|
readonly metrics: LunoraMetrics;
|
|
@@ -2161,9 +2220,10 @@ interface MutationCtx {
|
|
|
2161
2220
|
/** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
|
|
2162
2221
|
/**
|
|
2163
2222
|
* Static metadata declared on this procedure with `.meta(...)`, merged
|
|
2164
|
-
* across calls. Present so middleware can read the policy it
|
|
2165
|
-
* enforce (`ctx.meta.rateLimit`, …) instead of having it
|
|
2166
|
-
* `.use()` site; absent when the procedure never called
|
|
2223
|
+
* across calls and deep-frozen. Present so middleware can read the policy it
|
|
2224
|
+
* is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
|
|
2225
|
+
* hard-wired at each `.use()` site; absent when the procedure never called
|
|
2226
|
+
* `.meta()`.
|
|
2167
2227
|
*/
|
|
2168
2228
|
readonly meta?: Readonly<Record<string, unknown>>;
|
|
2169
2229
|
readonly metrics: LunoraMetrics;
|
|
@@ -2234,9 +2294,10 @@ interface ActionCtx {
|
|
|
2234
2294
|
/** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
|
|
2235
2295
|
/**
|
|
2236
2296
|
* Static metadata declared on this procedure with `.meta(...)`, merged
|
|
2237
|
-
* across calls. Present so middleware can read the policy it
|
|
2238
|
-
* enforce (`ctx.meta.rateLimit`, …) instead of having it
|
|
2239
|
-
* `.use()` site; absent when the procedure never called
|
|
2297
|
+
* across calls and deep-frozen. Present so middleware can read the policy it
|
|
2298
|
+
* is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
|
|
2299
|
+
* hard-wired at each `.use()` site; absent when the procedure never called
|
|
2300
|
+
* `.meta()`.
|
|
2240
2301
|
*/
|
|
2241
2302
|
readonly meta?: Readonly<Record<string, unknown>>;
|
|
2242
2303
|
readonly metrics: LunoraMetrics;
|
|
@@ -2267,4 +2328,4 @@ interface ActionCtx {
|
|
|
2267
2328
|
*/
|
|
2268
2329
|
type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
|
|
2269
2330
|
declare const anyApi: AnyApi;
|
|
2270
|
-
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectHead, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
|
2331
|
+
export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|