@lunora/testing 1.0.0-alpha.151 → 1.0.0-alpha.153

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/index.mjs CHANGED
@@ -1 +1 @@
1
- import{agentHarness as o,finalTurn as t,toolCallTurn as a}from"./packem_shared/agentHarness-DA9onGVO.mjs";import{evaluationAttributes as l,recordEvaluation as n}from"./packem_shared/evaluationAttributes-CYLgTP1P.mjs";import{lunoraTest as s}from"./packem_shared/lunoraTest-PUpvwIBo.mjs";import{groundednessScorer as p,mrrScorer as u,ndcgAtK as x,precisionAtK as S,recallAtK as f}from"./packem_shared/groundednessScorer-kgXJCZDg.mjs";import{containsScorer as g,evaluate as A,exactMatchScorer as v,keywordScorer as K,llmScorer as M,regexScorer as T,scoreSample as k}from"./packem_shared/containsScorer-DoLfFOs6.mjs";import{extractLink as C,listCapturedMail as b,waitForMail as h}from"@lunora/mail/testing";export{o as agentHarness,g as containsScorer,A as evaluate,l as evaluationAttributes,v as exactMatchScorer,C as extractLink,t as finalTurn,p as groundednessScorer,K as keywordScorer,b as listCapturedMail,M as llmScorer,s as lunoraTest,u as mrrScorer,x as ndcgAtK,S as precisionAtK,f as recallAtK,n as recordEvaluation,T as regexScorer,k as scoreSample,a as toolCallTurn,h as waitForMail};
1
+ import{agentHarness as o,finalTurn as t,toolCallTurn as a}from"./packem_shared/agentHarness-DA9onGVO.mjs";import{evaluationAttributes as l,recordEvaluation as n}from"./packem_shared/evaluationAttributes-CYLgTP1P.mjs";import{lunoraTest as s}from"./packem_shared/lunoraTest-DG9YgGp-.mjs";import{groundednessScorer as p,mrrScorer as u,ndcgAtK as x,precisionAtK as S,recallAtK as f}from"./packem_shared/groundednessScorer-kgXJCZDg.mjs";import{containsScorer as g,evaluate as A,exactMatchScorer as v,keywordScorer as K,llmScorer as M,regexScorer as T,scoreSample as k}from"./packem_shared/containsScorer-DoLfFOs6.mjs";import{extractLink as C,listCapturedMail as b,waitForMail as h}from"@lunora/mail/testing";export{o as agentHarness,g as containsScorer,A as evaluate,l as evaluationAttributes,v as exactMatchScorer,C as extractLink,t as finalTurn,p as groundednessScorer,K as keywordScorer,b as listCapturedMail,M as llmScorer,s as lunoraTest,u as mrrScorer,x as ndcgAtK,S as precisionAtK,f as recallAtK,n as recordEvaluation,T as regexScorer,k as scoreSample,a as toolCallTurn,h as waitForMail};
@@ -0,0 +1 @@
1
+ import{LunoraError as O}from"@lunora/errors";import{withDeferredSchedules as fe,beginDeferredSchedules as le}from"@lunora/server";import{runShardMigrations as me,TransactionHeadroomTracker as V,createShardCtxDb as ye,RLS_UNWRAP_SYMBOL as he}from"@lunora/shard-engine";import{evaluationAttributes as be}from"./evaluationAttributes-CYLgTP1P.mjs";import{assertScheduleDelay as we,MAX_RETRY_ATTEMPTS as ge,RETRY_BASE_DELAY_MS as pe}from"@lunora/scheduler";import{DatabaseSync as ve}from"node:sqlite";const W=e=>{let r="";for(let i=0;i<e.length;i+=32768)r+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(r)},Ae=e=>{const r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)s[i]=r.codePointAt(i)??0;return s},v="$lunora.wire$",G=64,te=1024,X="__proto__",re={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},ne={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Ee=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===null||r===Object.prototype},T=(e,r=0)=>{if(r>G)throw new RangeError(`wire-codec: value nesting exceeds the ${G}-level limit`);if(e===void 0)return[v,"undefined"];if(e===null)return null;const s=typeof e;if(s==="bigint")return[v,"bigint",e.toString()];if(s==="number"){const t=e;return Number.isNaN(t)?[v,"nan"]:t===1/0?[v,"inf"]:t===-1/0?[v,"-inf"]:t}if(s!=="object")return e;if(e instanceof Date)return[v,"date",T(e.getTime(),r+1)];if(e instanceof Error){const t=e,c={};for(const f of Object.keys(t)){if(t[f]===void 0)continue;const l=T(t[f],r+1);f===X?Object.defineProperty(c,f,{configurable:!0,enumerable:!0,value:l,writable:!0}):c[f]=l}const d=[v,"error",String(t.name),String(t.message),c];return t.cause!==void 0&&d.push(T(t.cause,r+1)),d}if(e instanceof URL)return[v,"url",e.href];if(e instanceof Map)return[v,"map",[...e.entries()].map(([t,c])=>[T(t,r+1),T(c,r+1)])];if(e instanceof Set)return[v,"set",[...e].map(t=>T(t,r+1))];if(e instanceof ArrayBuffer)return[v,"bytes",W(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,c=t.constructor.name,d=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return c==="Uint8Array"?[v,"bytes",W(d)]:[v,"bytes",W(d),c]}if(Array.isArray(e)){const t=e.map(c=>T(c,r+1));return t.length>0&&t[0]===v?[v,"arr",t]:t}if(!Ee(e)){const t=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${t} 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 i=e,y={};for(const t of Object.keys(i)){const c=i[t];if(c===void 0)continue;const d=T(c,r+1);t===X?Object.defineProperty(y,t,{configurable:!0,enumerable:!0,value:d,writable:!0}):y[t]=d}return y},P=(e,r=0)=>{if(r>G)throw new RangeError(`wire-codec: value nesting exceeds the ${G}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===v)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(t=>P(t,r+1));case"bigint":{const t=e[2];if(typeof t!="string"||t.length>te||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${te} digits)`);return BigInt(t)}case"date":{const t=P(e[2],r+1);if(typeof t!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(t)}case"map":{const t=e[2];return new Map(t.map(c=>{if(!Array.isArray(c)||c.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[P(c[0],r+1),P(c[1],r+1)]}))}case"set":return new Set(e[2].map(t=>P(t,r+1)));case"url":{const t=e[2];if(typeof t!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(t)}case"error":{const t=e[2],c=e[3];if(typeof t!="string"||typeof c!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const d=(Object.hasOwn(ne,t)?ne[t]:void 0)??Error,f=new d(c);f.name!==t&&Object.defineProperty(f,"name",{configurable:!0,value:t,writable:!0});const l=P(e[4],r+1);if(l===null||typeof l!="object"||Array.isArray(l))throw new TypeError("wire-codec: malformed error — props must be an object");for(const p of Object.keys(l))p===X?Object.defineProperty(f,p,{configurable:!0,enumerable:!0,value:l[p],writable:!0}):f[p]=l[p];return e.length>5&&Object.defineProperty(f,"cause",{configurable:!0,value:P(e[5],r+1),writable:!0}),f}case"bytes":{const t=e[2];if(typeof t!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const c=Ae(t);if(W(c)!==t)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const d=e[3]??"Uint8Array";if(d==="ArrayBuffer")return c.buffer.byteLength===c.byteLength?c.buffer:c.slice().buffer;const f=Object.hasOwn(re,d)?re[d]:void 0;return f?new f(c.slice().buffer):c}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(t=>P(t,r+1))}return e.map(y=>P(y,r+1))}const s=e,i={};for(const y of Object.keys(s)){const t=P(s[y],r+1);y===X?Object.defineProperty(i,y,{configurable:!0,enumerable:!0,value:t,writable:!0}):i[y]=t}return i},Se=(e,r,s,i,y)=>{let t=y,c=1;const d=new Map,f=[],l=(a,b,h={},n)=>{const o=T(h);JSON.stringify(o);const w=P(o),S=n??`fake-job-${String(c)}`;return c+=1,d.set(S,{args:w,enqueuedAt:t,functionPath:b,id:S,scheduledFor:a}),S},p=a=>typeof a=="string"?a:"__lunoraRef"in a?a.__lunoraRef:a.name??a.binding??"",R={cancel:a=>{const b=d.has(a);return d.delete(a),Promise.resolve({cancelled:b})},get:a=>Promise.resolve(d.get(a)??null),list:()=>Promise.resolve([...d.values()]),runAfter:(a,b,h,n)=>{we(a,"ctx.scheduler.runAfter");const o=l(t+a,p(b),h,n?.id);return Promise.resolve(o)},runAt:(a,b,h,n)=>{const o=l(a,p(b),h,n?.id);return Promise.resolve(o)}},k=async a=>{d.delete(a.id);const b=i(),h=a.functionPath===void 0?void 0:b.get(a.functionPath);if(h===void 0)throw new O("FUNCTION_NOT_FOUND",`unknown functionPath "${a.functionPath??"(workflow-targeted)"}"`,{status:404});if(h.kind!=="mutation"&&h.kind!=="action")throw new O("FUNCTION_NOT_FOUND",`functionPath "${a.functionPath??"(workflow-targeted)"}" is a ${h.kind} — only mutations and actions can be scheduled`,{status:404});const n=e(),o=h.kind==="action"?s():r();await n(h.kind,h,{...o,now:t},a.args)},_=async a=>{const b=[...d.values()].filter(o=>o.scheduledFor<=a).toSorted((o,w)=>o.scheduledFor-w.scheduledFor),h=[];let n=0;for(const o of b)if(d.has(o.id)){n+=1;try{await k(o)}catch(w){const S=(o.attempts??0)+1;if(S>ge){const C={args:o.args,error:w,functionPath:o.functionPath??"",id:o.id};h.push(C),f.push(C)}else{const C=pe*2**(S-1);d.set(o.id,{...o,attempts:S,scheduledFor:t+C})}}}return{executed:n,failed:h}},j=async(a,b)=>{const{executed:h,failed:n}=await _(a);if(n.length>0&&(b?.throwOnError??!0)){const[o]=n;throw n.length===1&&o!==void 0?o.error:new AggregateError(n.map(w=>w.error),`${String(n.length)} scheduled jobs failed: ${n.map(w=>w.functionPath).join(", ")}`)}return h};return{controls:{advance:(a,b)=>(t+=a,j(t,b)),failures:()=>[...f],list:()=>[...d.values()],runPending:a=>j(Number.POSITIVE_INFINITY,a)},scheduler:R}},Pe=()=>{const e=new ve(":memory:"),r=i=>({one(){if(i.length!==1)throw new O("INTERNAL",`expected exactly one row, received ${String(i.length)}`);const[y]=i;return y},[Symbol.iterator](){return i[Symbol.iterator]()},toArray(){return i}});return{close:()=>{e.close()},sql:{exec:(i,...y)=>{const c=e.prepare(i).all(...y);return r(c)}}}},Re=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...s}=e;return{claims:Object.keys(s).length>0?s:null,userId:r}};class Te extends V{current=new V;reset(){this.current=new V}headroom(){return this.current.headroom()}recordRead(r){this.current.recordRead(r)}recordWrite(r){this.current.recordWrite(r)}}const q=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},xe=e=>typeof e=="object"&&e!==null&&e.visibility==="internal"?"internal":"public",J=e=>{throw new O("INTERNAL",`ctx.${e} is not available in the in-memory @lunora/testing harness (v1)`)},E=e=>new Proxy((...r)=>J(e),{apply:()=>J(e),get:()=>J(e)}),oe={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Ie={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>oe},ke=()=>{const e={attributes:{},events:[],links:[]},r={addEvent:(s,i)=>{e.events.push({...i===void 0?{}:{attributes:{...i}},name:s})},addLink:s=>{e.links.push({spanId:s.spanId,traceId:s.traceId})},recordEvaluation:s=>{Object.assign(e.attributes,be(s))},recordException:s=>{const i={"exception.message":s instanceof Error?s.message:String(s),"exception.type":s instanceof Error?s.constructor.name:"Error"};s instanceof Error&&s.stack!==void 0&&(i["exception.stacktrace"]=s.stack),r.addEvent("exception",i)},setAttribute:(s,i)=>{e.attributes[s]=i},setAttributes:s=>{Object.assign(e.attributes,s)},spanContext:()=>oe};return{handle:r,recorded:e}},H=async(e,r)=>await r(H,Ie),z={count:()=>{},gauge:()=>{},record:()=>{}},Q={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>Q},Ne=(e,r,s)=>(y,t)=>{let c=!1;const d=[];let f,l,p=0,R=0;const k=()=>q(y)?e("query",y,r,t,!1):Promise.resolve(y(r)),_=(n,o)=>{if(n<R)return;R=n;const w={done:!1,value:o};if(d.length===0)f=w,l=void 0;else{f=void 0,l=void 0;for(const S of d.splice(0))S.resolve(w)}},j=(n,o)=>{if(!(n<R))if(R=n,d.length===0)l={error:o},f=void 0;else{f=void 0,l=void 0;for(const w of d.splice(0))w.reject(o)}},x=n=>o=>{_(n,o)},a=n=>o=>{j(n,o)},b=()=>{if(c)return;p+=1;const n=p;k().then(x(n)).catch(a(n))};s.add(b);const h={[Symbol.asyncIterator](){return h},next:()=>{if(c)return Promise.resolve({done:!0,value:void 0});if(R===p){if(l!==void 0){const{error:n}=l;return l=void 0,Promise.reject(n)}if(f!==void 0){const n=f;return f=void 0,Promise.resolve(n)}}return R<p?new Promise((n,o)=>{d.push({reject:o,resolve:n})}):k().then(n=>{if(l!==void 0){const{error:o}=l;throw l=void 0,o}if(f!==void 0){const o=f;return f=void 0,o}return{done:!1,value:n}})},return:()=>{c=!0,s.delete(b);for(const n of d.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return k().then(x(0)).catch(a(0)),h},Ue=(e,r)=>{const{close:s,sql:i}=Pe(),y=e;me(i,y);const t=new Te,c=g=>{const A=ye({auth:{identity:g.claims,userId:g.userId},enforceRls:r?.enforceRls??!0,headroom:t,schema:y,sql:i});return{database:A,rawDatabase:A[he]??A}},d=g=>{i.exec.call(i,g)};let f=Promise.resolve();const l=g=>{const A=async()=>{const M=le({scheduler:K});t.reset(),d("BEGIN");try{const B=await g();return d("COMMIT"),await M(!0),B}catch(B){try{d("ROLLBACK")}catch{}throw await M(!1),B}},L=f.then(A);return f=L.then(()=>{},()=>{}),L};let p=!1;const R=()=>{p||(p=!0,s())},k=new Map(Object.entries(r?.functions??{}).map(([g,A])=>[g,A])),_=new Set,j=()=>{for(const g of _)g()},x=g=>(j(),g);let a,b,h;const n=r?.now??Date.now(),o=ke(),w=(g,A)=>{if(g===void 0)throw new O("INTERNAL",`[fake-scheduler] ${A} not yet available — scheduler.advance called before harness construction completed`);return g},{controls:S,scheduler:C}=Se(()=>w(a,"dispatch"),()=>w(b,"mutationContext"),()=>w(h,"actionContext"),()=>k,n),K=fe(C),Z=g=>{const A=Re(g),L={getIdentity:()=>Promise.resolve(A.claims),userId:A.userId},{database:M,rawDatabase:B}=c(A),D={auth:L,db:M,env:r?.env,log:Q,metrics:z,now:n,span:o.handle,trace:H,runQuery:((u,m)=>N("query",u,D,m)),secrets:E("secrets"),storage:E("storage"),vectors:E("vectors")},U={auth:L,db:M,env:r?.env,log:Q,metrics:z,now:n,span:o.handle,trace:H,runMutation:((u,m)=>N("mutation",u,U,m)),runQuery:((u,m)=>N("query",u,D,m)),scheduler:K,secrets:E("secrets"),storage:E("storage"),vectors:E("vectors"),workflows:E("workflows")};b??=U;const se={...U,db:B},Y={auth:L,db:M,env:r?.env,fetch:r?.fetch??E("fetch"),log:Q,metrics:z,now:n,span:o.handle,trace:H,runAction:((u,m)=>N("action",u,Y,m)),runMutation:((u,m)=>l(()=>N("mutation",u,U,m)).then(x)),runQuery:((u,m)=>N("query",u,D,m)),scheduler:K,secrets:E("secrets"),storage:E("storage"),vectors:E("vectors"),workflows:E("workflows")};h??=Y;const $=(u,m,I,F,de)=>{const ee=q(m);if(ee!==u)throw new O("INTERNAL",`expected a registered ${u}, received a ${ee??"non-function"} reference`);if(!de&&xe(m)==="internal")throw new O("INTERNAL",`This ${u} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${u.charAt(0).toUpperCase()}${u.slice(1)} from another function instead.`);return Promise.resolve(m.handler(I,F??{}))},N=(u,m,I,F)=>$(u,m,I,F,!0);a??=(u,m,I,F)=>u==="mutation"?l(()=>$("mutation",m,I,F,!0)).then(x):(t.reset(),N("action",m,I,F));const ie=((u,m)=>(t.reset(),q(u)?$("query",u,D,m,!1):Promise.resolve(u(D)))),ce=((u,m)=>{const I=q(u)?()=>$("mutation",u,U,m,!1):()=>u(U);return l(I).then(x)}),ae=((u,m)=>(t.reset(),q(u)?$("action",u,Y,m,!1):Promise.resolve(u(Y)))),ue=Ne((...u)=>(t.reset(),$(...u)),D,_);return{action:ae,close:R,mutation:ce,query:ie,run:u=>l(()=>u(se)).then(x),scheduler:S,subscribe:ue,wideEvent:()=>o.recorded,withIdentity:u=>Z(u)}};return Z(null)};export{Ue as lunoraTest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/testing",
3
- "version": "1.0.0-alpha.151",
3
+ "version": "1.0.0-alpha.153",
4
4
  "description": "Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,12 +50,12 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/agent": "1.0.0-alpha.93",
54
- "@lunora/errors": "1.0.0-alpha.34",
55
- "@lunora/mail": "1.0.0-alpha.66",
56
- "@lunora/scheduler": "1.0.0-alpha.57",
57
- "@lunora/server": "1.0.0-alpha.107",
58
- "@lunora/shard-engine": "1.0.0-alpha.59"
53
+ "@lunora/agent": "1.0.0-alpha.95",
54
+ "@lunora/errors": "1.0.0-alpha.35",
55
+ "@lunora/mail": "1.0.0-alpha.67",
56
+ "@lunora/scheduler": "1.0.0-alpha.58",
57
+ "@lunora/server": "1.0.0-alpha.108",
58
+ "@lunora/shard-engine": "1.0.0-alpha.60"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@playwright/test": "^1.61.1"
@@ -1 +0,0 @@
1
- import{LunoraError as k}from"@lunora/errors";import{withDeferredSchedules as rt,beginDeferredSchedules as nt}from"@lunora/server";import{runShardMigrations as ot,TransactionHeadroomTracker as Y,createShardCtxDb as st,RLS_UNWRAP_SYMBOL as it}from"@lunora/shard-engine";import{evaluationAttributes as ct}from"./evaluationAttributes-CYLgTP1P.mjs";import{assertScheduleDelay as at,MAX_RETRY_ATTEMPTS as ut,RETRY_BASE_DELAY_MS as dt}from"@lunora/scheduler";import{DatabaseSync as lt}from"node:sqlite";const ht=(o,s,i,u,g)=>{let v=g,b=1;const d=new Map,m=[],h=(r,l,a={},t)=>{JSON.stringify(a);const e=t??`fake-job-${String(b)}`;return b+=1,d.set(e,{args:a,enqueuedAt:v,functionPath:l,id:e,scheduledFor:r}),e},S=r=>typeof r=="string"?r:"__lunoraRef"in r?r.__lunoraRef:r.name??r.binding??"",x={cancel:r=>{const l=d.has(r);return d.delete(r),Promise.resolve({cancelled:l})},get:r=>Promise.resolve(d.get(r)??null),list:()=>Promise.resolve([...d.values()]),runAfter:(r,l,a,t)=>{at(r,"ctx.scheduler.runAfter");const e=h(v+r,S(l),a,t?.id);return Promise.resolve(e)},runAt:(r,l,a,t)=>{const e=h(r,S(l),a,t?.id);return Promise.resolve(e)}},A=async r=>{d.delete(r.id);const l=u(),a=r.functionPath===void 0?void 0:l.get(r.functionPath);if(a===void 0)throw new k("FUNCTION_NOT_FOUND",`unknown functionPath "${r.functionPath??"(workflow-targeted)"}"`,{status:404});if(a.kind!=="mutation"&&a.kind!=="action")throw new k("FUNCTION_NOT_FOUND",`functionPath "${r.functionPath??"(workflow-targeted)"}" is a ${a.kind} — only mutations and actions can be scheduled`,{status:404});const t=o(),e=a.kind==="action"?i():s();await t(a.kind,a,{...e,now:v},r.args)},I=async r=>{const l=[...d.values()].filter(e=>e.scheduledFor<=r).toSorted((e,w)=>e.scheduledFor-w.scheduledFor),a=[];let t=0;for(const e of l)if(d.has(e.id)){t+=1;try{await A(e)}catch(w){const R=(e.attempts??0)+1;if(R>ut){const _={args:e.args,error:w,functionPath:e.functionPath??"",id:e.id};a.push(_),m.push(_)}else{const _=dt*2**(R-1);d.set(e.id,{...e,attempts:R,scheduledFor:v+_})}}}return{executed:t,failed:a}},T=async(r,l)=>{const{executed:a,failed:t}=await I(r);if(t.length>0&&(l?.throwOnError??!0)){const[e]=t;throw t.length===1&&e!==void 0?e.error:new AggregateError(t.map(w=>w.error),`${String(t.length)} scheduled jobs failed: ${t.map(w=>w.functionPath).join(", ")}`)}return a};return{controls:{advance:(r,l)=>(v+=r,T(v,l)),failures:()=>[...m],list:()=>[...d.values()],runPending:r=>T(Number.POSITIVE_INFINITY,r)},scheduler:x}},ft=()=>{const o=new lt(":memory:"),s=u=>({one(){if(u.length!==1)throw new k("INTERNAL",`expected exactly one row, received ${String(u.length)}`);const[g]=u;return g},[Symbol.iterator](){return u[Symbol.iterator]()},toArray(){return u}});return{close:()=>{o.close()},sql:{exec:(u,...g)=>{const b=o.prepare(u).all(...g);return s(b)}}}},vt=o=>{if(o===null||typeof o.userId!="string"||o.userId.length===0)return{claims:null,userId:null};const{userId:s,...i}=o;return{claims:Object.keys(i).length>0?i:null,userId:s}};class mt extends Y{current=new Y;reset(){this.current=new Y}headroom(){return this.current.headroom()}recordRead(s){this.current.recordRead(s)}recordWrite(s){this.current.recordWrite(s)}}const O=o=>{if(typeof o!="object"||o===null)return;const{kind:s}=o;if(s==="query"||s==="mutation"||s==="action")return s},wt=o=>typeof o=="object"&&o!==null&&o.visibility==="internal"?"internal":"public",B=o=>{throw new k("INTERNAL",`ctx.${o} is not available in the in-memory @lunora/testing harness (v1)`)},y=o=>new Proxy((...s)=>B(o),{apply:()=>B(o),get:()=>B(o)}),V={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},pt={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>V},gt=()=>{const o={attributes:{},events:[],links:[]},s={addEvent:(i,u)=>{o.events.push({...u===void 0?{}:{attributes:{...u}},name:i})},addLink:i=>{o.links.push({spanId:i.spanId,traceId:i.traceId})},recordEvaluation:i=>{Object.assign(o.attributes,ct(i))},recordException:i=>{const u={"exception.message":i instanceof Error?i.message:String(i),"exception.type":i instanceof Error?i.constructor.name:"Error"};i instanceof Error&&i.stack!==void 0&&(u["exception.stacktrace"]=i.stack),s.addEvent("exception",u)},setAttribute:(i,u)=>{o.attributes[i]=u},setAttributes:i=>{Object.assign(o.attributes,i)},spanContext:()=>V};return{handle:s,recorded:o}},U=async(o,s)=>await s(U,pt),H={count:()=>{},gauge:()=>{},record:()=>{}},Q={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>Q},yt=(o,s,i)=>(g,v)=>{let b=!1;const d=[];let m,h,S=0,x=0;const A=()=>O(g)?o("query",g,s,v,!1):Promise.resolve(g(s)),I=(t,e)=>{if(t<x)return;x=t;const w={done:!1,value:e};if(d.length===0)m=w,h=void 0;else{m=void 0,h=void 0;for(const R of d.splice(0))R.resolve(w)}},T=(t,e)=>{if(!(t<x))if(x=t,d.length===0)h={error:e},m=void 0;else{m=void 0,h=void 0;for(const w of d.splice(0))w.reject(e)}},P=t=>e=>{I(t,e)},r=t=>e=>{T(t,e)},l=()=>{if(b)return;S+=1;const t=S;A().then(P(t)).catch(r(t))};i.add(l);const a={[Symbol.asyncIterator](){return a},next:()=>{if(b)return Promise.resolve({done:!0,value:void 0});if(x===S){if(h!==void 0){const{error:t}=h;return h=void 0,Promise.reject(t)}if(m!==void 0){const t=m;return m=void 0,Promise.resolve(t)}}return x<S?new Promise((t,e)=>{d.push({reject:e,resolve:t})}):A().then(t=>{if(h!==void 0){const{error:e}=h;throw h=void 0,e}if(m!==void 0){const e=m;return m=void 0,e}return{done:!1,value:t}})},return:()=>{b=!0,i.delete(l);for(const t of d.splice(0))t.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return A().then(P(0)).catch(r(0)),a},Nt=(o,s)=>{const{close:i,sql:u}=ft(),g=o;ot(u,g);const v=new mt,b=f=>{const p=st({auth:{identity:f.claims,userId:f.userId},enforceRls:s?.enforceRls??!0,headroom:v,schema:g,sql:u});return{database:p,rawDatabase:p[it]??p}},d=f=>{u.exec.call(u,f)};let m=Promise.resolve();const h=f=>{const p=async()=>{const M=nt({scheduler:W});v.reset(),d("BEGIN");try{const F=await f();return d("COMMIT"),await M(!0),F}catch(F){try{d("ROLLBACK")}catch{}throw await M(!1),F}},C=m.then(p);return m=C.then(()=>{},()=>{}),C};let S=!1;const x=()=>{S||(S=!0,i())},A=new Map(Object.entries(s?.functions??{}).map(([f,p])=>[f,p])),I=new Set,T=()=>{for(const f of I)f()},P=f=>(T(),f);let r,l,a;const t=s?.now??Date.now(),e=gt(),w=(f,p)=>{if(f===void 0)throw new k("INTERNAL",`[fake-scheduler] ${p} not yet available — scheduler.advance called before harness construction completed`);return f},{controls:R,scheduler:_}=ht(()=>w(r,"dispatch"),()=>w(l,"mutationContext"),()=>w(a,"actionContext"),()=>A,t),W=rt(_),J=f=>{const p=vt(f),C={getIdentity:()=>Promise.resolve(p.claims),userId:p.userId},{database:M,rawDatabase:F}=b(p),D={auth:C,db:M,env:s?.env,log:Q,metrics:H,now:t,span:e.handle,trace:U,runQuery:((n,c)=>N("query",n,D,c)),secrets:y("secrets"),storage:y("storage"),vectors:y("vectors")},L={auth:C,db:M,env:s?.env,log:Q,metrics:H,now:t,span:e.handle,trace:U,runMutation:((n,c)=>N("mutation",n,L,c)),runQuery:((n,c)=>N("query",n,D,c)),scheduler:W,secrets:y("secrets"),storage:y("storage"),vectors:y("vectors"),workflows:y("workflows")};l??=L;const X={...L,db:F},j={auth:C,db:M,env:s?.env,fetch:s?.fetch??y("fetch"),log:Q,metrics:H,now:t,span:e.handle,trace:U,runAction:((n,c)=>N("action",n,j,c)),runMutation:((n,c)=>h(()=>N("mutation",n,L,c)).then(P)),runQuery:((n,c)=>N("query",n,D,c)),scheduler:W,secrets:y("secrets"),storage:y("storage"),vectors:y("vectors"),workflows:y("workflows")};a??=j;const q=(n,c,E,$,et)=>{const K=O(c);if(K!==n)throw new k("INTERNAL",`expected a registered ${n}, received a ${K??"non-function"} reference`);if(!et&&wt(c)==="internal")throw new k("INTERNAL",`This ${n} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${n.charAt(0).toUpperCase()}${n.slice(1)} from another function instead.`);return Promise.resolve(c.handler(E,$??{}))},N=(n,c,E,$)=>q(n,c,E,$,!0);r??=(n,c,E,$)=>n==="mutation"?h(()=>q("mutation",c,E,$,!0)).then(P):(v.reset(),N("action",c,E,$));const G=((n,c)=>(v.reset(),O(n)?q("query",n,D,c,!1):Promise.resolve(n(D)))),z=((n,c)=>{const E=O(n)?()=>q("mutation",n,L,c,!1):()=>n(L);return h(E).then(P)}),Z=((n,c)=>(v.reset(),O(n)?q("action",n,j,c,!1):Promise.resolve(n(j)))),tt=yt((...n)=>(v.reset(),q(...n)),D,I);return{action:Z,close:x,mutation:z,query:G,run:n=>h(()=>n(X)).then(P),scheduler:R,subscribe:tt,wideEvent:()=>e.recorded,withIdentity:n=>J(n)}};return J(null)};export{Nt as lunoraTest};