@lunora/testing 1.0.0-alpha.336 → 1.0.0-alpha.338

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-BM24QFnh.mjs";import{evaluationAttributes as l,recordEvaluation as n}from"./packem_shared/evaluationAttributes-CYLgTP1P.mjs";import{createArtifactsFake as m}from"./packem_shared/createArtifactsFake-L0tjki11.mjs";import{createFakeSecretValues as p}from"./packem_shared/createFakeSecretValues-BTNOscqQ.mjs";import{lunoraTest as f}from"./packem_shared/lunoraTest-CtgiZ7sN.mjs";import{createStreamGate as u,recordedModel as d}from"./packem_shared/createStreamGate-Geg-yvx6.mjs";import{groundednessScorer as g,mrrScorer as k,ndcgAtK as M,precisionAtK as v,recallAtK as F}from"./packem_shared/groundednessScorer-D8-EWo1j.mjs";import{absentScorer as T,containsScorer as b,evaluate as w,exactMatchScorer as C,keywordScorer as h,llmScorer as y,regexScorer as E,scoreSample as G}from"./packem_shared/absentScorer-tcGbGxnq.mjs";import{extractLink as L,listCapturedMail as V,waitForMail as j}from"@lunora/mail/testing";export{T as absentScorer,o as agentHarness,b as containsScorer,m as createArtifactsFake,p as createFakeSecretValues,u as createStreamGate,w as evaluate,l as evaluationAttributes,C as exactMatchScorer,L as extractLink,t as finalTurn,g as groundednessScorer,h as keywordScorer,V as listCapturedMail,y as llmScorer,f as lunoraTest,k as mrrScorer,M as ndcgAtK,v as precisionAtK,F as recallAtK,n as recordEvaluation,d as recordedModel,E as regexScorer,G as scoreSample,a as toolCallTurn,j as waitForMail};
1
+ import{agentHarness as o,finalTurn as t,toolCallTurn as a}from"./packem_shared/agentHarness-BM24QFnh.mjs";import{evaluationAttributes as l,recordEvaluation as n}from"./packem_shared/evaluationAttributes-CYLgTP1P.mjs";import{createArtifactsFake as m}from"./packem_shared/createArtifactsFake-L0tjki11.mjs";import{createFakeSecretValues as p}from"./packem_shared/createFakeSecretValues-BTNOscqQ.mjs";import{lunoraTest as f}from"./packem_shared/lunoraTest-BoZIBXbT.mjs";import{createStreamGate as u,recordedModel as d}from"./packem_shared/createStreamGate-Geg-yvx6.mjs";import{groundednessScorer as g,mrrScorer as k,ndcgAtK as M,precisionAtK as v,recallAtK as F}from"./packem_shared/groundednessScorer-D8-EWo1j.mjs";import{absentScorer as T,containsScorer as b,evaluate as w,exactMatchScorer as C,keywordScorer as h,llmScorer as y,regexScorer as E,scoreSample as G}from"./packem_shared/absentScorer-tcGbGxnq.mjs";import{extractLink as L,listCapturedMail as V,waitForMail as j}from"@lunora/mail/testing";export{T as absentScorer,o as agentHarness,b as containsScorer,m as createArtifactsFake,p as createFakeSecretValues,u as createStreamGate,w as evaluate,l as evaluationAttributes,C as exactMatchScorer,L as extractLink,t as finalTurn,g as groundednessScorer,h as keywordScorer,V as listCapturedMail,y as llmScorer,f as lunoraTest,k as mrrScorer,M as ndcgAtK,v as precisionAtK,F as recallAtK,n as recordEvaluation,d as recordedModel,E as regexScorer,G as scoreSample,a as toolCallTurn,j as waitForMail};
@@ -0,0 +1 @@
1
+ import{AsyncLocalStorage as se}from"node:async_hooks";import{LunoraError as A}from"@lunora/errors";import{withDeferredSchedules as be}from"@lunora/server";import{createInProcessRuntime as Se,resolveInProcessIdentity as Ee,runRegisteredFunction as M,registeredFunctionKind as W}from"@lunora/server/in-process";import{encodeWire as ce,decodeWire as ie}from"@lunora/wire";import{evaluationAttributes as Ae}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as Ne,createNotify as Re}from"@lunora/notify";import{createNotification as Te}from"@visulima/notification";import{serialize as Pe,deserialize as _e}from"node:v8";import{createQueues as Ie,createTopicContext as Oe}from"@lunora/queue";import{assertScheduleDelay as xe,TERMINAL_RETENTION_MS as $e,MAX_RETRY_ATTEMPTS as ke,RETRY_BASE_DELAY_MS as qe}from"@lunora/scheduler";import{DatabaseSync as De}from"node:sqlite";const I=(t,e)=>{throw new A("INTERNAL",e===void 0?`ctx.${t} is not available in the in-memory @lunora/testing harness (v1)`:`ctx.${t} is not enabled in the @lunora/testing harness — pass lunoraTest(schema, { ${e} })`)},Ce=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),Le=t=>new Proxy({...t},{get(e,r){if(!(Ce.has(r)&&!Object.hasOwn(e,r))){if(typeof r=="symbol"||Object.hasOwn(e,r)||r in Object.prototype)return Reflect.get(e,r);throw new A("INTERNAL",`ctx.services.${r} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${r}: … } })`)}}}),b=(t,e)=>new Proxy((...r)=>I(t,e),{apply:()=>I(t,e),get:()=>I(t,e)}),ae={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Me={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>ae},Fe=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,i)=>{t.events.push({...i===void 0?{}:{attributes:{...i}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,Ae(r))},recordException:r=>{const i={"exception.message":r instanceof Error?r.message:String(r),"exception.type":r instanceof Error?r.constructor.name:"Error"};r instanceof Error&&r.stack!==void 0&&(i["exception.stacktrace"]=r.stack),e.addEvent("exception",i)},setAttribute:(r,i)=>{t.attributes[r]=i},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>ae};return{handle:e,recorded:t}},V=async(t,e)=>await e(V,Me),G={count:()=>{},gauge:()=>{},record:()=>{}},Y={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>Y},Q="notify",je=t=>{let e=t;if(typeof t=="string"){if(!t.startsWith("{"))return;try{e=JSON.parse(t)}catch{return}}const r=e?.endpoint;return typeof r=="string"?r:void 0},B=(t,e)=>typeof t=="function"?t(e):t,Be=(t,e)=>{const r=[],i=(f,y)=>(r.push({channel:f,payload:structuredClone(y)}),{data:{messageId:`${f}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),g=f=>({channel:f,id:`lunora-testing-${f}`,initialize:()=>{},isAvailable:()=>!0,send:y=>i(f,y)}),a=B(t.webPush,e)!==void 0,w=B(t.fcm,e)!==void 0,l={...g("push"),send:f=>{const y=Array.isArray(f.to)?f.to:[f.to];if(y.length===0)throw new A("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const x of y){const T=je(x)!==void 0;if(T?!a:!w)throw new Error(T?"@lunora/notify: received a web-push target but no `webPush` channel is configured":"@lunora/notify: received an FCM token target but no `fcm` channel is configured")}return i("push",f)}},p={...a||w?{push:l}:{},...B(t.chat,e)===void 0?{}:{chat:g("chat")},...B(t.inApp,e)===void 0?{}:{inapp:g("inapp")},...B(t.webhook,e)===void 0?{}:{webhook:g("webhook")}},d=Ne(),{notify:h,push:E}=Re({...t,store:()=>d},e,{engine:Te(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:f=>f===void 0?[...r]:r.filter(y=>y.channel===f)},surfaces:{notify:h,push:E}}},Ue=(t,e)=>t!==void 0?Be(t,e):{controls:{clear:()=>I("notify",Q),sent:()=>I("notify",Q)},surfaces:{notify:b("notify",Q),push:b("push",Q)}},Z="queues: [...]",re=128*1024,ne=256*1024,Je="json",oe=new TextEncoder,Ke=(t,e)=>{if(e==="v8"){const i=Pe(t);return{body:_e(i),bytes:i.byteLength}}if(e==="text"){if(typeof t!="string")throw new A("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof t}`);return{body:t,bytes:oe.encode(t).byteLength}}if(e==="bytes"){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw new A("VALIDATION_ERROR",'@lunora/queue: a "bytes" message body must be an ArrayBuffer or an ArrayBufferView');return{body:t,bytes:t.byteLength}}const r=JSON.stringify(t);if(typeof r!="string")throw new A("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof t}`);return{body:JSON.parse(r),bytes:oe.encode(r).byteLength}},ue=t=>{const e=new Set(t),r=[],i=(a,w,l)=>{const p=l?.contentType??Je,d=Ke(w,p);if(d.bytes>re)throw new A("VALIDATION_ERROR",`@lunora/queue: ${a} message is ${String(d.bytes)} bytes, over the Cloudflare Queues limit of ${String(re)} (128 KB)`);return{bytes:d.bytes,message:{body:d.body,contentType:p,...l?.delaySeconds===void 0?{}:{delaySeconds:l.delaySeconds},destination:a}}},g=a=>({send:(w,l)=>(r.push(i(a,w,l).message),Promise.resolve()),sendBatch:(w,l)=>{const p=[...w].map(h=>i(a,h.body,{contentType:h.contentType,delaySeconds:h.delaySeconds??l?.delaySeconds})),d=p.reduce((h,E)=>h+E.bytes,0);if(d>ne)throw new A("VALIDATION_ERROR",`@lunora/queue: ${a} batch is ${String(d)} bytes, over the Cloudflare Queues limit of ${String(ne)} (256 KB)`);return r.push(...p.map(h=>h.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(a=>[a,g(a)])),clear:()=>{r.length=0},read:(a,w,l)=>{if(a===void 0)return[...r];if(!e.has(a))throw new A("INTERNAL",`${w}("${a}"): no such ${l} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===a)}}},Qe=t=>{const e=ue(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:i,...g})=>({...g,queue:i}))},surfaces:{queues:Ie({bindings:e.bindings})}}},We=t=>t!==void 0?Qe(t):{controls:{clear:()=>I("queues",Z),sent:()=>I("queues",Z)},surfaces:{queues:b("queues",Z)}},Ve=(t,e,r,i,g)=>{let a=g,w=1;const l=new Map,p=new Map,d=new Map,h=[],E=(o,m,n={},s)=>{const c=ce(n);JSON.stringify(c);const S=ie(c),N=s??`fake-job-${String(w)}`;return w+=1,d.delete(N),l.set(N,{args:S,enqueuedAt:a,functionPath:m,id:N,scheduledFor:o}),N},f=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",y={cancel:o=>{const m=l.get(o),n=m!==void 0;return m!==void 0&&d.set(o,{...m,completedAt:a,state:"canceled"}),l.delete(o),Promise.resolve({cancelled:n})},get:o=>{const m=l.get(o),n=p.get(o);let s=d.get(o);return s?.completedAt!==void 0&&s.completedAt<=a-$e&&(s=void 0),m!==void 0?s={...m,state:"pending"}:n!==void 0&&(s={...n,state:"running"}),Promise.resolve(s??null)},list:()=>Promise.resolve([...l.values()]),runAfter:(o,m,n,s)=>{xe(o,"ctx.scheduler.runAfter");const c=E(a+o,f(m),n,s?.id);return Promise.resolve(c)},runAt:(o,m,n,s)=>{const c=E(o,f(m),n,s?.id);return Promise.resolve(c)}},x=async o=>{l.delete(o.id);const m=i(),n=o.functionPath===void 0?void 0:m.get(o.functionPath);if(n===void 0)throw new A("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(n.kind!=="mutation"&&n.kind!=="action")throw new A("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${n.kind} — only mutations and actions can be scheduled`,{status:404});const s=t(),c=n.kind==="action"?r():e();await s(n.kind,n,c,o.args,a)},T=async o=>{const m=[...l.values()].filter(c=>c.scheduledFor<=o).toSorted((c,S)=>c.scheduledFor-S.scheduledFor),n=[];let s=0;for(const c of m)if(l.has(c.id)){s+=1;try{p.set(c.id,c),await x(c),d.set(c.id,{...c,completedAt:a,state:"succeeded"})}catch(S){const N=(c.attempts??0)+1;if(N>ke){const k={args:c.args,error:S,functionPath:c.functionPath??"",id:c.id};n.push(k),h.push(k),d.set(c.id,{...c,attempts:N,completedAt:a,error:`dead-lettered after ${String(N)} attempts`,state:"failed"})}else{const k=qe*2**(N-1);l.set(c.id,{...c,attempts:N,scheduledFor:a+k})}}finally{p.delete(c.id)}}return{executed:s,failed:n}},P=async(o,m)=>{const{executed:n,failed:s}=await T(o);if(s.length>0&&(m?.throwOnError??!0)){const[c]=s;throw s.length===1&&c!==void 0?c.error:new AggregateError(s.map(S=>S.error),`${String(s.length)} scheduled jobs failed: ${s.map(S=>S.functionPath).join(", ")}`)}return n};return{controls:{advance:(o,m)=>(a+=o,P(a,m)),failures:()=>[...h],list:()=>[...l.values()],runPending:o=>P(Number.POSITIVE_INFINITY,o)},scheduler:y}},ee="topics: [...]",Ye=t=>{if(t===void 0)return{controls:{clear:()=>I("topics",ee),published:()=>I("topics",ee)},surfaces:{topics:b("topics",ee)}};const e=ue(t),r=Oe(e.bindings,t.map(i=>({exportName:i,subscriptions:[{binding:i,exportName:i}]})));return{controls:{clear:e.clear,published:i=>e.read(i,"harness.topics.published","topic").map(({destination:g,...a})=>({...a,topic:g}))},surfaces:{topics:r}}},ze=()=>{const t=new De(":memory:"),e=i=>({one(){if(i.length!==1)throw new A("INTERNAL",`expected exactly one row, received ${String(i.length)}`);const[g]=i;return g},[Symbol.iterator](){return i[Symbol.iterator]()},toArray(){return i}});return{close:()=>{t.close()},sql:{exec:(i,...g)=>{const w=t.prepare(i).all(...g);return e(w)}}}},F=new se,U=t=>{try{const e=JSON.stringify({result:ce(t)}),r=JSON.parse(e);return ie(r.result)}catch(e){throw new A("WIRE_ENCODE_FAILED",e instanceof Error?e.message:String(e),{cause:e})}},Xe=new se,He=(t,e,r,i)=>(a,w)=>{let l=!1;const p=[];let d,h,E=0,f=0;const y=()=>F.run(i(),()=>W(a)?t("query",a,e,w,!1):Promise.resolve(a(e))),x=(n,s)=>{if(n<f)return;f=n;const c={done:!1,value:s};if(p.length===0)d=c,h=void 0;else{d=void 0,h=void 0;for(const S of p.splice(0))S.resolve(c)}},T=(n,s)=>{if(!(n<f))if(f=n,p.length===0)h={error:s},d=void 0;else{d=void 0,h=void 0;for(const c of p.splice(0))c.reject(s)}},P=n=>s=>{x(n,s)},j=n=>s=>{T(n,s)},o=()=>{if(l)return;E+=1;const n=E;y().then(P(n)).catch(j(n))};r.add(o);const m={[Symbol.asyncIterator](){return m},next:()=>{if(l)return Promise.resolve({done:!0,value:void 0});if(f===E){if(h!==void 0){const{error:n}=h;return h=void 0,Promise.reject(n)}if(d!==void 0){const n=d;return d=void 0,Promise.resolve(n)}}return f<E?new Promise((n,s)=>{p.push({reject:s,resolve:n})}):y().then(n=>{if(h!==void 0){const{error:s}=h;throw h=void 0,s}if(d!==void 0){const s=d;return d=void 0,s}return{done:!1,value:n}})},return:()=>{l=!0,r.delete(o);for(const n of p.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return y().then(P(0)).catch(j(0)),m},lt=(t,e)=>{const{close:r,sql:i}=ze();let g=!1;const a=()=>{g||(g=!0,r())},w=new Map(Object.entries(e?.functions??{}).map(([R,_])=>[R,_])),l=new Set,p=()=>{for(const R of l)R()},d=R=>(p(),R);let h,E,f;const y=()=>e?.now??Date.now(),x=y(),T=R=>((..._)=>F.run(y(),()=>R(..._))),P=Fe(),{controls:j,surfaces:o}=We(e?.queues),{controls:m,surfaces:n}=Ye(e?.topics),{controls:s,surfaces:c}=Ue(e?.notify,e?.env??{}),S=(R,_)=>{if(R===void 0)throw new A("INTERNAL",`[fake-scheduler] ${_} not yet available — scheduler.advance called before harness construction completed`);return R},{controls:N,scheduler:k}=Ve(()=>S(h,"dispatch"),()=>S(E,"mutationContext"),()=>S(f,"actionContext"),()=>w,x),z=be(k),{createWriters:de,runInTransaction:J,runWithBudget:q}=Se(t,{enforceRls:e?.enforceRls,headroomScope:Xe,scheduler:z,sql:i}),te=R=>{const _=Ee(R),X={getIdentity:()=>Promise.resolve(_.claims),userId:_.userId},{database:H,rawDatabase:le}=de(_),D={...c,auth:X,db:H,env:e?.env,log:Y,metrics:G,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runQuery:((u,v)=>$("query",u,D,v)),secrets:b("secrets"),storage:b("storage"),vectors:b("vectors")},C={...c,...o,...n,auth:X,db:H,env:e?.env,log:Y,metrics:G,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runMutation:((u,v)=>$("mutation",u,C,v)),runQuery:((u,v)=>$("query",u,D,v)),scheduler:z,secrets:b("secrets"),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};E??=C;const fe=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(C),db:{enumerable:!0,value:le}}),K={...c,...o,...n,auth:X,db:H,env:e?.env,fetch:e?.fetch??b("fetch"),log:Y,metrics:G,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runAction:((u,v)=>$("action",u,K,v)),runMutation:((u,v)=>J(()=>$("mutation",u,C,v)).then(d)),runQuery:((u,v)=>$("query",u,D,v)),scheduler:z,secrets:b("secrets"),services:Le(e?.services),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};f??=K;const $=(u,v,O,L)=>M(u,v,O,L,!0),he=(u,v,O,L)=>u==="mutation"?J(()=>M("mutation",v,O,L,!0).then(U)).then(d):q(()=>$("action",v,O,L));h??=(u,v,O,L,we)=>F.run(we,()=>he(u,v,O,L));const me=((u,v)=>W(u)?q(()=>M("query",u,D,v,!1).then(U)):q(()=>Promise.resolve(u(D)))),ve=((u,v)=>{const O=W(u)?()=>M("mutation",u,C,v,!1).then(U):()=>u(C);return J(O).then(d)}),pe=((u,v)=>W(u)?q(()=>M("action",u,K,v,!1).then(U)):q(()=>Promise.resolve(u(K)))),ge=He((...u)=>q(()=>M(...u).then(U)),D,l,()=>e?.now??Date.now()),ye=u=>J(()=>u(fe)).then(d);return{action:T(pe),close:a,mutation:T(ve),notify:s,query:T(me),queues:j,run:T(ye),scheduler:N,subscribe:ge,topics:m,wideEvent:()=>P.recorded,withIdentity:u=>te(u)}};return te(null)};export{lt as lunoraTest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/testing",
3
- "version": "1.0.0-alpha.336",
3
+ "version": "1.0.0-alpha.338",
4
4
  "description": "Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -50,7 +50,7 @@
50
50
  "access": "public"
51
51
  },
52
52
  "dependencies": {
53
- "@lunora/agent": "^1.0.0-alpha.282",
53
+ "@lunora/agent": "^1.0.0-alpha.283",
54
54
  "@lunora/bindings": "1.0.0-alpha.151",
55
55
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
56
56
  "@lunora/mail": "^1.0.0-alpha.139",
@@ -1 +0,0 @@
1
- import{AsyncLocalStorage as oe}from"node:async_hooks";import{LunoraError as E}from"@lunora/errors";import{withDeferredSchedules as ge}from"@lunora/server";import{createInProcessRuntime as ye,resolveInProcessIdentity as we,runRegisteredFunction as M,registeredFunctionKind as J}from"@lunora/server/in-process";import{evaluationAttributes as be}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as Se,createNotify as Ae}from"@lunora/notify";import{createNotification as Ee}from"@visulima/notification";import{serialize as Ne,deserialize as Re}from"node:v8";import{createQueues as Te,createTopicContext as Pe}from"@lunora/queue";import{assertScheduleDelay as _e,TERMINAL_RETENTION_MS as Ie,MAX_RETRY_ATTEMPTS as xe,RETRY_BASE_DELAY_MS as Oe}from"@lunora/scheduler";import{encodeWire as $e,decodeWire as ke}from"@lunora/wire";import{DatabaseSync as qe}from"node:sqlite";const I=(t,e)=>{throw new E("INTERNAL",e===void 0?`ctx.${t} is not available in the in-memory @lunora/testing harness (v1)`:`ctx.${t} is not enabled in the @lunora/testing harness — pass lunoraTest(schema, { ${e} })`)},Ce=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),De=t=>new Proxy({...t},{get(e,r){if(!(Ce.has(r)&&!Object.hasOwn(e,r))){if(typeof r=="symbol"||Object.hasOwn(e,r)||r in Object.prototype)return Reflect.get(e,r);throw new E("INTERNAL",`ctx.services.${r} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${r}: … } })`)}}}),b=(t,e)=>new Proxy((...r)=>I(t,e),{apply:()=>I(t,e),get:()=>I(t,e)}),se={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Le={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>se},Me=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,i)=>{t.events.push({...i===void 0?{}:{attributes:{...i}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,be(r))},recordException:r=>{const i={"exception.message":r instanceof Error?r.message:String(r),"exception.type":r instanceof Error?r.constructor.name:"Error"};r instanceof Error&&r.stack!==void 0&&(i["exception.stacktrace"]=r.stack),e.addEvent("exception",i)},setAttribute:(r,i)=>{t.attributes[r]=i},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>se};return{handle:e,recorded:t}},V=async(t,e)=>await e(V,Le),H={count:()=>{},gauge:()=>{},record:()=>{}},W={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>W},Q="notify",Fe=t=>{let e=t;if(typeof t=="string"){if(!t.startsWith("{"))return;try{e=JSON.parse(t)}catch{return}}const r=e?.endpoint;return typeof r=="string"?r:void 0},B=(t,e)=>typeof t=="function"?t(e):t,je=(t,e)=>{const r=[],i=(f,y)=>(r.push({channel:f,payload:structuredClone(y)}),{data:{messageId:`${f}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),g=f=>({channel:f,id:`lunora-testing-${f}`,initialize:()=>{},isAvailable:()=>!0,send:y=>i(f,y)}),a=B(t.webPush,e)!==void 0,w=B(t.fcm,e)!==void 0,l={...g("push"),send:f=>{const y=Array.isArray(f.to)?f.to:[f.to];if(y.length===0)throw new E("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const O of y){const T=Fe(O)!==void 0;if(T?!a:!w)throw new Error(T?"@lunora/notify: received a web-push target but no `webPush` channel is configured":"@lunora/notify: received an FCM token target but no `fcm` channel is configured")}return i("push",f)}},p={...a||w?{push:l}:{},...B(t.chat,e)===void 0?{}:{chat:g("chat")},...B(t.inApp,e)===void 0?{}:{inapp:g("inapp")},...B(t.webhook,e)===void 0?{}:{webhook:g("webhook")}},d=Se(),{notify:h,push:A}=Ae({...t,store:()=>d},e,{engine:Ee(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:f=>f===void 0?[...r]:r.filter(y=>y.channel===f)},surfaces:{notify:h,push:A}}},Be=(t,e)=>t!==void 0?je(t,e):{controls:{clear:()=>I("notify",Q),sent:()=>I("notify",Q)},surfaces:{notify:b("notify",Q),push:b("push",Q)}},G="queues: [...]",te=128*1024,re=256*1024,Ue="json",ne=new TextEncoder,Ke=(t,e)=>{if(e==="v8"){const i=Ne(t);return{body:Re(i),bytes:i.byteLength}}if(e==="text"){if(typeof t!="string")throw new E("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof t}`);return{body:t,bytes:ne.encode(t).byteLength}}if(e==="bytes"){if(!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw new E("VALIDATION_ERROR",'@lunora/queue: a "bytes" message body must be an ArrayBuffer or an ArrayBufferView');return{body:t,bytes:t.byteLength}}const r=JSON.stringify(t);if(typeof r!="string")throw new E("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof t}`);return{body:JSON.parse(r),bytes:ne.encode(r).byteLength}},ce=t=>{const e=new Set(t),r=[],i=(a,w,l)=>{const p=l?.contentType??Ue,d=Ke(w,p);if(d.bytes>te)throw new E("VALIDATION_ERROR",`@lunora/queue: ${a} message is ${String(d.bytes)} bytes, over the Cloudflare Queues limit of ${String(te)} (128 KB)`);return{bytes:d.bytes,message:{body:d.body,contentType:p,...l?.delaySeconds===void 0?{}:{delaySeconds:l.delaySeconds},destination:a}}},g=a=>({send:(w,l)=>(r.push(i(a,w,l).message),Promise.resolve()),sendBatch:(w,l)=>{const p=[...w].map(h=>i(a,h.body,{contentType:h.contentType,delaySeconds:h.delaySeconds??l?.delaySeconds})),d=p.reduce((h,A)=>h+A.bytes,0);if(d>re)throw new E("VALIDATION_ERROR",`@lunora/queue: ${a} batch is ${String(d)} bytes, over the Cloudflare Queues limit of ${String(re)} (256 KB)`);return r.push(...p.map(h=>h.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(a=>[a,g(a)])),clear:()=>{r.length=0},read:(a,w,l)=>{if(a===void 0)return[...r];if(!e.has(a))throw new E("INTERNAL",`${w}("${a}"): no such ${l} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===a)}}},Qe=t=>{const e=ce(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:i,...g})=>({...g,queue:i}))},surfaces:{queues:Te({bindings:e.bindings})}}},Je=t=>t!==void 0?Qe(t):{controls:{clear:()=>I("queues",G),sent:()=>I("queues",G)},surfaces:{queues:b("queues",G)}},Ve=(t,e,r,i,g)=>{let a=g,w=1;const l=new Map,p=new Map,d=new Map,h=[],A=(o,v,n={},s)=>{const c=$e(n);JSON.stringify(c);const S=ke(c),N=s??`fake-job-${String(w)}`;return w+=1,d.delete(N),l.set(N,{args:S,enqueuedAt:a,functionPath:v,id:N,scheduledFor:o}),N},f=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",y={cancel:o=>{const v=l.get(o),n=v!==void 0;return v!==void 0&&d.set(o,{...v,completedAt:a,state:"canceled"}),l.delete(o),Promise.resolve({cancelled:n})},get:o=>{const v=l.get(o),n=p.get(o);let s=d.get(o);return s?.completedAt!==void 0&&s.completedAt<=a-Ie&&(s=void 0),v!==void 0?s={...v,state:"pending"}:n!==void 0&&(s={...n,state:"running"}),Promise.resolve(s??null)},list:()=>Promise.resolve([...l.values()]),runAfter:(o,v,n,s)=>{_e(o,"ctx.scheduler.runAfter");const c=A(a+o,f(v),n,s?.id);return Promise.resolve(c)},runAt:(o,v,n,s)=>{const c=A(o,f(v),n,s?.id);return Promise.resolve(c)}},O=async o=>{l.delete(o.id);const v=i(),n=o.functionPath===void 0?void 0:v.get(o.functionPath);if(n===void 0)throw new E("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(n.kind!=="mutation"&&n.kind!=="action")throw new E("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${n.kind} — only mutations and actions can be scheduled`,{status:404});const s=t(),c=n.kind==="action"?r():e();await s(n.kind,n,c,o.args,a)},T=async o=>{const v=[...l.values()].filter(c=>c.scheduledFor<=o).toSorted((c,S)=>c.scheduledFor-S.scheduledFor),n=[];let s=0;for(const c of v)if(l.has(c.id)){s+=1;try{p.set(c.id,c),await O(c),d.set(c.id,{...c,completedAt:a,state:"succeeded"})}catch(S){const N=(c.attempts??0)+1;if(N>xe){const k={args:c.args,error:S,functionPath:c.functionPath??"",id:c.id};n.push(k),h.push(k),d.set(c.id,{...c,attempts:N,completedAt:a,error:`dead-lettered after ${String(N)} attempts`,state:"failed"})}else{const k=Oe*2**(N-1);l.set(c.id,{...c,attempts:N,scheduledFor:a+k})}}finally{p.delete(c.id)}}return{executed:s,failed:n}},P=async(o,v)=>{const{executed:n,failed:s}=await T(o);if(s.length>0&&(v?.throwOnError??!0)){const[c]=s;throw s.length===1&&c!==void 0?c.error:new AggregateError(s.map(S=>S.error),`${String(s.length)} scheduled jobs failed: ${s.map(S=>S.functionPath).join(", ")}`)}return n};return{controls:{advance:(o,v)=>(a+=o,P(a,v)),failures:()=>[...h],list:()=>[...l.values()],runPending:o=>P(Number.POSITIVE_INFINITY,o)},scheduler:y}},Z="topics: [...]",We=t=>{if(t===void 0)return{controls:{clear:()=>I("topics",Z),published:()=>I("topics",Z)},surfaces:{topics:b("topics",Z)}};const e=ce(t),r=Pe(e.bindings,t.map(i=>({exportName:i,subscriptions:[{binding:i,exportName:i}]})));return{controls:{clear:e.clear,published:i=>e.read(i,"harness.topics.published","topic").map(({destination:g,...a})=>({...a,topic:g}))},surfaces:{topics:r}}},Ye=()=>{const t=new qe(":memory:"),e=i=>({one(){if(i.length!==1)throw new E("INTERNAL",`expected exactly one row, received ${String(i.length)}`);const[g]=i;return g},[Symbol.iterator](){return i[Symbol.iterator]()},toArray(){return i}});return{close:()=>{t.close()},sql:{exec:(i,...g)=>{const w=t.prepare(i).all(...g);return e(w)}}}},F=new oe,ze=new oe,Xe=(t,e,r,i)=>(a,w)=>{let l=!1;const p=[];let d,h,A=0,f=0;const y=()=>F.run(i(),()=>J(a)?t("query",a,e,w,!1):Promise.resolve(a(e))),O=(n,s)=>{if(n<f)return;f=n;const c={done:!1,value:s};if(p.length===0)d=c,h=void 0;else{d=void 0,h=void 0;for(const S of p.splice(0))S.resolve(c)}},T=(n,s)=>{if(!(n<f))if(f=n,p.length===0)h={error:s},d=void 0;else{d=void 0,h=void 0;for(const c of p.splice(0))c.reject(s)}},P=n=>s=>{O(n,s)},j=n=>s=>{T(n,s)},o=()=>{if(l)return;A+=1;const n=A;y().then(P(n)).catch(j(n))};r.add(o);const v={[Symbol.asyncIterator](){return v},next:()=>{if(l)return Promise.resolve({done:!0,value:void 0});if(f===A){if(h!==void 0){const{error:n}=h;return h=void 0,Promise.reject(n)}if(d!==void 0){const n=d;return d=void 0,Promise.resolve(n)}}return f<A?new Promise((n,s)=>{p.push({reject:s,resolve:n})}):y().then(n=>{if(h!==void 0){const{error:s}=h;throw h=void 0,s}if(d!==void 0){const s=d;return d=void 0,s}return{done:!1,value:n}})},return:()=>{l=!0,r.delete(o);for(const n of p.splice(0))n.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return y().then(P(0)).catch(j(0)),v},dt=(t,e)=>{const{close:r,sql:i}=Ye();let g=!1;const a=()=>{g||(g=!0,r())},w=new Map(Object.entries(e?.functions??{}).map(([R,_])=>[R,_])),l=new Set,p=()=>{for(const R of l)R()},d=R=>(p(),R);let h,A,f;const y=()=>e?.now??Date.now(),O=y(),T=R=>((..._)=>F.run(y(),()=>R(..._))),P=Me(),{controls:j,surfaces:o}=Je(e?.queues),{controls:v,surfaces:n}=We(e?.topics),{controls:s,surfaces:c}=Be(e?.notify,e?.env??{}),S=(R,_)=>{if(R===void 0)throw new E("INTERNAL",`[fake-scheduler] ${_} not yet available — scheduler.advance called before harness construction completed`);return R},{controls:N,scheduler:k}=Ve(()=>S(h,"dispatch"),()=>S(A,"mutationContext"),()=>S(f,"actionContext"),()=>w,O),Y=ge(k),{createWriters:ie,runInTransaction:U,runWithBudget:q}=ye(t,{enforceRls:e?.enforceRls,headroomScope:ze,scheduler:Y,sql:i}),ee=R=>{const _=we(R),z={getIdentity:()=>Promise.resolve(_.claims),userId:_.userId},{database:X,rawDatabase:ae}=ie(_),C={...c,auth:z,db:X,env:e?.env,log:W,metrics:H,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runQuery:((u,m)=>$("query",u,C,m)),secrets:b("secrets"),storage:b("storage"),vectors:b("vectors")},D={...c,...o,...n,auth:z,db:X,env:e?.env,log:W,metrics:H,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runMutation:((u,m)=>$("mutation",u,D,m)),runQuery:((u,m)=>$("query",u,C,m)),scheduler:Y,secrets:b("secrets"),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};A??=D;const ue=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(D),db:{enumerable:!0,value:ae}}),K={...c,...o,...n,auth:z,db:X,env:e?.env,fetch:e?.fetch??b("fetch"),log:W,metrics:H,get now(){return F.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:P.handle,trace:V,runAction:((u,m)=>$("action",u,K,m)),runMutation:((u,m)=>U(()=>$("mutation",u,D,m)).then(d)),runQuery:((u,m)=>$("query",u,C,m)),scheduler:Y,secrets:b("secrets"),services:De(e?.services),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};f??=K;const $=(u,m,x,L)=>M(u,m,x,L,!0),de=(u,m,x,L)=>u==="mutation"?U(()=>M("mutation",m,x,L,!0)).then(d):q(()=>$("action",m,x,L));h??=(u,m,x,L,pe)=>F.run(pe,()=>de(u,m,x,L));const le=((u,m)=>J(u)?q(()=>M("query",u,C,m,!1)):q(()=>Promise.resolve(u(C)))),fe=((u,m)=>{const x=J(u)?()=>M("mutation",u,D,m,!1):()=>u(D);return U(x).then(d)}),he=((u,m)=>J(u)?q(()=>M("action",u,K,m,!1)):q(()=>Promise.resolve(u(K)))),ve=Xe((...u)=>q(()=>M(...u)),C,l,()=>e?.now??Date.now()),me=u=>U(()=>u(ue)).then(d);return{action:T(he),close:a,mutation:T(fe),notify:s,query:T(le),queues:j,run:T(me),scheduler:N,subscribe:ve,topics:v,wideEvent:()=>P.recorded,withIdentity:u=>ee(u)}};return ee(null)};export{dt as lunoraTest};