@lunora/testing 1.0.0-alpha.344 → 1.0.0-alpha.345
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
CHANGED
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
|
|
35
35
|
---
|
|
36
36
|
|
|
37
|
-
Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions
|
|
37
|
+
Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions, plus the dev mail-catcher helpers, eval scorers and a Playwright double for the browser protocol (`@lunora/testing/playwright`). In `lunora dev`, `@lunora/mail` captures every outbound email into the studio's root-shard inbox, and these helpers read that inbox over the admin RPC so a Playwright (or any HTTP) test can drive "request reset → read the email → follow the link" deterministically.
|
|
38
38
|
|
|
39
39
|
Part of the [Lunora](https://github.com/anolilab/lunora) framework — a type-safe, real-time backend on Cloudflare Workers + Durable Objects with a Vite-first DX.
|
|
40
40
|
|
|
@@ -58,7 +58,7 @@ pnpm add @lunora/testing
|
|
|
58
58
|
|
|
59
59
|
`lunoraTest(schema)` runs your `query` / `mutation` / `action` functions against
|
|
60
60
|
an in-memory `node:sqlite` backend — no Durable Object, no `wrangler`, no
|
|
61
|
-
network. It
|
|
61
|
+
network. It exposes `query` / `mutation` / `action` /
|
|
62
62
|
`run` / `withIdentity`, all sharing one database so a write is visible to a
|
|
63
63
|
later read.
|
|
64
64
|
|
|
@@ -239,7 +239,7 @@ const resetLink = extractLink(mail, { match: "/reset-password" });
|
|
|
239
239
|
// → visit `resetLink`, set a new password, assert success.
|
|
240
240
|
```
|
|
241
241
|
|
|
242
|
-
> This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs)**.
|
|
242
|
+
> This README covers the basics. For the full API, options, and guides, see the **[documentation](https://lunora.sh/docs/packages/testing)**.
|
|
243
243
|
|
|
244
244
|
## Related
|
|
245
245
|
|
package/dist/index.d.mts
CHANGED
|
@@ -2,7 +2,7 @@ import { AgentMessageRow, AgentRunInput, AgentTokenDelta, AgentGenerateResult, A
|
|
|
2
2
|
import { SecretValueHost } from '@lunora/platform';
|
|
3
3
|
import { LanguageModel } from 'ai';
|
|
4
4
|
import { ArtifactsBindingLike, ArtifactsErrorCode, ArtifactsCommitMetadata, ArtifactsTreeEntry } from '@lunora/bindings/artifacts';
|
|
5
|
-
import { ScheduledJob, LogFields, RegisteredFunction, ArgsValidator, RegisteredAction,
|
|
5
|
+
import { ScheduledJob, LogFields, RegisteredFunction, ArgsValidator, RegisteredAction, InferArgsInput, ActionCtx, RegisteredMutation, MutationCtx, RegisteredQuery, QueryCtx, TableDefinition, Schema } from '@lunora/server';
|
|
6
6
|
import { NotifyDefinition } from '@lunora/notify';
|
|
7
7
|
import { ChannelType, ChannelPayloadMap } from '@visulima/notification';
|
|
8
8
|
import { QueueContentType } from '@lunora/queue';
|
|
@@ -622,9 +622,12 @@ interface LunoraTestOptions {
|
|
|
622
622
|
* `ctx.scheduler.runAfter` / `ctx.scheduler.runAt`) to the corresponding
|
|
623
623
|
* registered function object.
|
|
624
624
|
*
|
|
625
|
-
* Only required if your handlers schedule work.
|
|
626
|
-
* NOT listed here
|
|
627
|
-
*
|
|
625
|
+
* Only required if your handlers schedule work. A scheduled job whose path
|
|
626
|
+
* is NOT listed here fails with `FUNCTION_NOT_FOUND` when it comes due, as
|
|
627
|
+
* in production. It is retried with backoff on the virtual clock, and once
|
|
628
|
+
* the retry budget is spent the error is recorded on `t.scheduler.failures()`
|
|
629
|
+
* and re-thrown from `advance` / `runPending`, unless they were called with
|
|
630
|
+
* `{ throwOnError: false }`.
|
|
628
631
|
* @example
|
|
629
632
|
* ```ts
|
|
630
633
|
* const t = lunoraTest(schema, {
|
|
@@ -735,14 +738,14 @@ interface LunoraTestOptions {
|
|
|
735
738
|
interface TestHarness {
|
|
736
739
|
/** Run a registered `action` (or an inline `async (context) => …`) against the harness. */
|
|
737
740
|
action: {
|
|
738
|
-
<A extends ArgsValidator, R>(reference: RegisteredAction<A, R>, args:
|
|
741
|
+
<A extends ArgsValidator, R>(reference: RegisteredAction<A, R>, args: InferArgsInput<A>): Promise<R>;
|
|
739
742
|
<R>(inline: InlineActionFunction<R>): Promise<R>;
|
|
740
743
|
};
|
|
741
744
|
/** Close the underlying in-memory SQLite database, releasing the native handle. Idempotent; safe to call on any `withIdentity` view. */
|
|
742
745
|
close: () => void;
|
|
743
746
|
/** Run a registered `mutation` (or an inline `async (context) => …`) against the harness. */
|
|
744
747
|
mutation: {
|
|
745
|
-
<A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args:
|
|
748
|
+
<A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgsInput<A>): Promise<R>;
|
|
746
749
|
<R>(inline: InlineMutationFunction<R>): Promise<R>;
|
|
747
750
|
};
|
|
748
751
|
/**
|
|
@@ -753,7 +756,7 @@ interface TestHarness {
|
|
|
753
756
|
notify: FakeNotifyControls;
|
|
754
757
|
/** Run a registered `query` (or an inline `async (context) => …`) against the harness. */
|
|
755
758
|
query: {
|
|
756
|
-
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args:
|
|
759
|
+
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgsInput<A>): Promise<R>;
|
|
757
760
|
<R>(inline: InlineQueryFunction<R>): Promise<R>;
|
|
758
761
|
};
|
|
759
762
|
/**
|
|
@@ -812,7 +815,7 @@ interface TestHarness {
|
|
|
812
815
|
* are coalesced).
|
|
813
816
|
*/
|
|
814
817
|
subscribe: {
|
|
815
|
-
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args:
|
|
818
|
+
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgsInput<A>): TestSubscription<R>;
|
|
816
819
|
<R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
|
|
817
820
|
};
|
|
818
821
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { AgentMessageRow, AgentRunInput, AgentTokenDelta, AgentGenerateResult, A
|
|
|
2
2
|
import { SecretValueHost } from '@lunora/platform';
|
|
3
3
|
import { LanguageModel } from 'ai';
|
|
4
4
|
import { ArtifactsBindingLike, ArtifactsErrorCode, ArtifactsCommitMetadata, ArtifactsTreeEntry } from '@lunora/bindings/artifacts';
|
|
5
|
-
import { ScheduledJob, LogFields, RegisteredFunction, ArgsValidator, RegisteredAction,
|
|
5
|
+
import { ScheduledJob, LogFields, RegisteredFunction, ArgsValidator, RegisteredAction, InferArgsInput, ActionCtx, RegisteredMutation, MutationCtx, RegisteredQuery, QueryCtx, TableDefinition, Schema } from '@lunora/server';
|
|
6
6
|
import { NotifyDefinition } from '@lunora/notify';
|
|
7
7
|
import { ChannelType, ChannelPayloadMap } from '@visulima/notification';
|
|
8
8
|
import { QueueContentType } from '@lunora/queue';
|
|
@@ -622,9 +622,12 @@ interface LunoraTestOptions {
|
|
|
622
622
|
* `ctx.scheduler.runAfter` / `ctx.scheduler.runAt`) to the corresponding
|
|
623
623
|
* registered function object.
|
|
624
624
|
*
|
|
625
|
-
* Only required if your handlers schedule work.
|
|
626
|
-
* NOT listed here
|
|
627
|
-
*
|
|
625
|
+
* Only required if your handlers schedule work. A scheduled job whose path
|
|
626
|
+
* is NOT listed here fails with `FUNCTION_NOT_FOUND` when it comes due, as
|
|
627
|
+
* in production. It is retried with backoff on the virtual clock, and once
|
|
628
|
+
* the retry budget is spent the error is recorded on `t.scheduler.failures()`
|
|
629
|
+
* and re-thrown from `advance` / `runPending`, unless they were called with
|
|
630
|
+
* `{ throwOnError: false }`.
|
|
628
631
|
* @example
|
|
629
632
|
* ```ts
|
|
630
633
|
* const t = lunoraTest(schema, {
|
|
@@ -735,14 +738,14 @@ interface LunoraTestOptions {
|
|
|
735
738
|
interface TestHarness {
|
|
736
739
|
/** Run a registered `action` (or an inline `async (context) => …`) against the harness. */
|
|
737
740
|
action: {
|
|
738
|
-
<A extends ArgsValidator, R>(reference: RegisteredAction<A, R>, args:
|
|
741
|
+
<A extends ArgsValidator, R>(reference: RegisteredAction<A, R>, args: InferArgsInput<A>): Promise<R>;
|
|
739
742
|
<R>(inline: InlineActionFunction<R>): Promise<R>;
|
|
740
743
|
};
|
|
741
744
|
/** Close the underlying in-memory SQLite database, releasing the native handle. Idempotent; safe to call on any `withIdentity` view. */
|
|
742
745
|
close: () => void;
|
|
743
746
|
/** Run a registered `mutation` (or an inline `async (context) => …`) against the harness. */
|
|
744
747
|
mutation: {
|
|
745
|
-
<A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args:
|
|
748
|
+
<A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgsInput<A>): Promise<R>;
|
|
746
749
|
<R>(inline: InlineMutationFunction<R>): Promise<R>;
|
|
747
750
|
};
|
|
748
751
|
/**
|
|
@@ -753,7 +756,7 @@ interface TestHarness {
|
|
|
753
756
|
notify: FakeNotifyControls;
|
|
754
757
|
/** Run a registered `query` (or an inline `async (context) => …`) against the harness. */
|
|
755
758
|
query: {
|
|
756
|
-
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args:
|
|
759
|
+
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgsInput<A>): Promise<R>;
|
|
757
760
|
<R>(inline: InlineQueryFunction<R>): Promise<R>;
|
|
758
761
|
};
|
|
759
762
|
/**
|
|
@@ -812,7 +815,7 @@ interface TestHarness {
|
|
|
812
815
|
* are coalesced).
|
|
813
816
|
*/
|
|
814
817
|
subscribe: {
|
|
815
|
-
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args:
|
|
818
|
+
<A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgsInput<A>): TestSubscription<R>;
|
|
816
819
|
<R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
|
|
817
820
|
};
|
|
818
821
|
/**
|
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-
|
|
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-DESrxLrW.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 K,registeredFunctionKind as V}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,assertDedupKey as ke,MAX_RETRY_ATTEMPTS as qe,RETRY_BASE_DELAY_MS as De}from"@lunora/scheduler";import{DatabaseSync as Ce}from"node:sqlite";const O=(t,e)=>{throw new A("INTERNAL",e===void 0?`ctx.${t} is not available in the in-memory @lunora/testing harness (v1): it has no fake and no option to enable one. Keep the code that reaches it out of the unit under test, or exercise that path against a running worker (\`lunora dev\`).`:`ctx.${t} is not enabled in the @lunora/testing harness — pass lunoraTest(schema, { ${e} })`)},Me=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),Le=t=>new Proxy({...t},{get(e,r){if(!(Me.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)=>O(t,e),{apply:()=>O(t,e),get:()=>O(t,e)}),ae={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Fe={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>ae},Ke=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,a)=>{t.events.push({...a===void 0?{}:{attributes:{...a}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,Ae(r))},recordException:r=>{const a={"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&&(a["exception.stacktrace"]=r.stack),e.addEvent("exception",a)},setAttribute:(r,a)=>{t.attributes[r]=a},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>ae};return{handle:e,recorded:t}},Y=async(t,e)=>await e(Y,Fe),G={count:()=>{},gauge:()=>{},record:()=>{}},z={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>z},W="notify",Be=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},j=(t,e)=>typeof t=="function"?t(e):t,je=(t,e)=>{const r=[],a=(h,y)=>(r.push({channel:h,payload:structuredClone(y)}),{data:{messageId:`${h}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),g=h=>({channel:h,id:`lunora-testing-${h}`,initialize:()=>{},isAvailable:()=>!0,send:y=>a(h,y)}),c=j(t.webPush,e)!==void 0,w=j(t.fcm,e)!==void 0,f={...g("push"),send:h=>{const y=Array.isArray(h.to)?h.to:[h.to];if(y.length===0)throw new A("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const $ of y){const T=Be($)!==void 0;if(T?!c:!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 a("push",h)}},p={...c||w?{push:f}:{},...j(t.chat,e)===void 0?{}:{chat:g("chat")},...j(t.inApp,e)===void 0?{}:{inapp:g("inapp")},...j(t.webhook,e)===void 0?{}:{webhook:g("webhook")}},l=Ne(),{notify:v,push:S}=Re({...t,store:()=>l},e,{engine:Te(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:h=>h===void 0?[...r]:r.filter(y=>y.channel===h)},surfaces:{notify:v,push:S}}},Ue=(t,e)=>t!==void 0?je(t,e):{controls:{clear:()=>O("notify",W),sent:()=>O("notify",W)},surfaces:{notify:b("notify",W),push:b("push",W)}},Z="queues: [...]",re=128*1024,ne=256*1024,Je="json",oe=new TextEncoder,Qe=(t,e)=>{if(e==="v8"){const a=Pe(t);return{body:_e(a),bytes:a.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=[],a=(c,w,f)=>{const p=f?.contentType??Je,l=Qe(w,p);if(l.bytes>re)throw new A("VALIDATION_ERROR",`@lunora/queue: ${c} message is ${String(l.bytes)} bytes, over the Cloudflare Queues limit of ${String(re)} (128 KB)`);return{bytes:l.bytes,message:{body:l.body,contentType:p,...f?.delaySeconds===void 0?{}:{delaySeconds:f.delaySeconds},destination:c}}},g=c=>({send:(w,f)=>(r.push(a(c,w,f).message),Promise.resolve()),sendBatch:(w,f)=>{const p=[...w].map(v=>a(c,v.body,{contentType:v.contentType,delaySeconds:v.delaySeconds??f?.delaySeconds})),l=p.reduce((v,S)=>v+S.bytes,0);if(l>ne)throw new A("VALIDATION_ERROR",`@lunora/queue: ${c} batch is ${String(l)} bytes, over the Cloudflare Queues limit of ${String(ne)} (256 KB)`);return r.push(...p.map(v=>v.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(c=>[c,g(c)])),clear:()=>{r.length=0},read:(c,w,f)=>{if(c===void 0)return[...r];if(!e.has(c))throw new A("INTERNAL",`${w}("${c}"): no such ${f} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===c)}}},We=t=>{const e=ue(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:a,...g})=>({...g,queue:a}))},surfaces:{queues:Ie({bindings:e.bindings})}}},Ve=t=>t!==void 0?We(t):{controls:{clear:()=>O("queues",Z),sent:()=>O("queues",Z)},surfaces:{queues:b("queues",Z)}},Ye=864e5,ze=(t,e,r,a,g)=>{let c=g,w=1;const f=new Map,p=new Map,l=new Map,v=[],S=new Map,h=(o,n,s={},u,i)=>{ke(i);const E=ce(s);JSON.stringify(E);const P=ie(E),N=u??`fake-job-${String(w)}`;return w+=1,l.delete(N),f.set(N,{args:P,...i===void 0?{}:{dedupKey:i},enqueuedAt:c,functionPath:n,id:N,scheduledFor:o}),N},y=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",$={cancel:o=>{const n=f.get(o),s=n!==void 0;return n!==void 0&&l.set(o,{...n,completedAt:c,state:"canceled"}),f.delete(o),Promise.resolve({cancelled:s})},get:o=>{const n=f.get(o),s=p.get(o);let u=l.get(o);return u?.completedAt!==void 0&&u.completedAt<=c-$e&&(u=void 0),n!==void 0?u={...n,state:"pending"}:s!==void 0&&(u={...s,state:"running"}),Promise.resolve(u??null)},list:()=>Promise.resolve([...f.values()]),runAfter:(o,n,s,u)=>{xe(o,"ctx.scheduler.runAfter");const i=h(c+o,y(n),s,u?.id,u?.dedupKey);return Promise.resolve(i)},runAt:(o,n,s,u)=>{const i=h(o,y(n),s,u?.id,u?.dedupKey);return Promise.resolve(i)}},T=async o=>{f.delete(o.id);const n=a(),s=o.functionPath===void 0?void 0:n.get(o.functionPath);if(s===void 0)throw new A("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(s.kind!=="mutation"&&s.kind!=="action")throw new A("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${s.kind} — only mutations and actions can be scheduled`,{status:404});const u=o.dedupKey===void 0?void 0:`${o.functionPath??""}\0${o.dedupKey}`,i=u===void 0?void 0:S.get(u);if(i!==void 0&&c-i<Ye)return;const E=t(),P=s.kind==="action"?r():e();await E(s.kind,s,P,o.args,c),u!==void 0&&S.set(u,c)},_=async o=>{const n=[...f.values()].filter(i=>i.scheduledFor<=o).toSorted((i,E)=>i.scheduledFor-E.scheduledFor),s=[];let u=0;for(const i of n)if(f.has(i.id)){u+=1;try{p.set(i.id,i),await T(i),l.set(i.id,{...i,completedAt:c,state:"succeeded"})}catch(E){const P=(i.attempts??0)+1;if(P>qe){const N={args:i.args,error:E,functionPath:i.functionPath??"",id:i.id};s.push(N),v.push(N),l.set(i.id,{...i,attempts:P,completedAt:c,error:`dead-lettered after ${String(P)} attempts`,state:"failed"})}else{const N=De*2**(P-1);f.set(i.id,{...i,attempts:P,scheduledFor:c+N})}}finally{p.delete(i.id)}}return{executed:u,failed:s}},k=async(o,n)=>{const{executed:s,failed:u}=await _(o);if(u.length>0&&(n?.throwOnError??!0)){const[i]=u;throw u.length===1&&i!==void 0?i.error:new AggregateError(u.map(E=>E.error),`${String(u.length)} scheduled jobs failed: ${u.map(E=>E.functionPath).join(", ")}`)}return s};return{controls:{advance:(o,n)=>(c+=o,k(c,n)),failures:()=>[...v],list:()=>[...f.values()],runPending:o=>k(Number.POSITIVE_INFINITY,o)},scheduler:$}},ee="topics: [...]",Xe=t=>{if(t===void 0)return{controls:{clear:()=>O("topics",ee),published:()=>O("topics",ee)},surfaces:{topics:b("topics",ee)}};const e=ue(t),r=Oe(e.bindings,t.map(a=>({exportName:a,subscriptions:[{binding:a,exportName:a}]})));return{controls:{clear:e.clear,published:a=>e.read(a,"harness.topics.published","topic").map(({destination:g,...c})=>({...c,topic:g}))},surfaces:{topics:r}}},He=()=>{const t=new Ce(":memory:"),e=a=>({one(){if(a.length!==1)throw new A("INTERNAL",`expected exactly one row, received ${String(a.length)}`);const[g]=a;return g},[Symbol.iterator](){return a[Symbol.iterator]()},toArray(){return a}});return{close:()=>{t.close()},sql:{exec:(a,...g)=>{const w=t.prepare(a).all(...g);return e(w)}}}},B=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})}},Ge=new se,Ze=(t,e,r,a)=>(c,w)=>{let f=!1;const p=[];let l,v,S=0,h=0;const y=()=>B.run(a(),()=>V(c)?t("query",c,e,w,!1):Promise.resolve(c(e))),$=(n,s)=>{if(n<h)return;h=n;const u={done:!1,value:s};if(p.length===0)l=u,v=void 0;else{l=void 0,v=void 0;for(const i of p.splice(0))i.resolve(u)}},T=(n,s)=>{if(!(n<h))if(h=n,p.length===0)v={error:s},l=void 0;else{l=void 0,v=void 0;for(const u of p.splice(0))u.reject(s)}},_=n=>s=>{$(n,s)},k=n=>s=>{T(n,s)},D=()=>{if(f)return;S+=1;const n=S;y().then(_(n)).catch(k(n))};r.add(D);const o={[Symbol.asyncIterator](){return o},next:()=>{if(f)return Promise.resolve({done:!0,value:void 0});if(h===S){if(v!==void 0){const{error:n}=v;return v=void 0,Promise.reject(n)}if(l!==void 0){const n=l;return l=void 0,Promise.resolve(n)}}return h<S?new Promise((n,s)=>{p.push({reject:s,resolve:n})}):y().then(n=>{if(v!==void 0){const{error:s}=v;throw v=void 0,s}if(l!==void 0){const s=l;return l=void 0,s}return{done:!1,value:n}})},return:()=>{f=!0,r.delete(D);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(_(0)).catch(k(0)),o},ht=(t,e)=>{const{close:r,sql:a}=He();let g=!1;const c=()=>{g||(g=!0,r())},w=new Map(Object.entries(e?.functions??{}).map(([R,I])=>[R,I])),f=new Set,p=()=>{for(const R of f)R()},l=R=>(p(),R);let v,S,h;const y=()=>e?.now??Date.now(),$=y(),T=R=>((...I)=>B.run(y(),()=>R(...I))),_=Ke(),{controls:k,surfaces:D}=Ve(e?.queues),{controls:o,surfaces:n}=Xe(e?.topics),{controls:s,surfaces:u}=Ue(e?.notify,e?.env??{}),i=(R,I)=>{if(R===void 0)throw new A("INTERNAL",`[fake-scheduler] ${I} not yet available — scheduler.advance called before harness construction completed`);return R},{controls:E,scheduler:P}=ze(()=>i(v,"dispatch"),()=>i(S,"mutationContext"),()=>i(h,"actionContext"),()=>w,$),N=be(P),{createWriters:de,runInTransaction:J,runWithBudget:C}=Se(t,{enforceRls:e?.enforceRls,headroomScope:Ge,scheduler:N,sql:a}),te=R=>{const I=Ee(R),X={getIdentity:()=>Promise.resolve(I.claims),userId:I.userId},{database:H,rawDatabase:le}=de(I),M={...u,auth:X,db:H,env:e?.env,log:z,metrics:G,get now(){return B.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runQuery:((d,m)=>q("query",d,M,m)),secrets:b("secrets"),storage:b("storage"),vectors:b("vectors")},L={...u,...D,...n,auth:X,db:H,env:e?.env,log:z,metrics:G,get now(){return B.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runMutation:((d,m)=>q("mutation",d,L,m)),runQuery:((d,m)=>q("query",d,M,m)),scheduler:N,secrets:b("secrets"),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};S??=L;const fe=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(L),db:{enumerable:!0,value:le}}),Q={...u,...D,...n,auth:X,db:H,env:e?.env,fetch:e?.fetch??b("fetch","fetch"),log:z,metrics:G,get now(){return B.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runAction:((d,m)=>q("action",d,Q,m)),runMutation:((d,m)=>J(()=>q("mutation",d,L,m)).then(l)),runQuery:((d,m)=>q("query",d,M,m)),scheduler:N,secrets:b("secrets"),services:Le(e?.services),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};h??=Q;const q=(d,m,x,F)=>K(d,m,x,F,!0),he=(d,m,x,F)=>d==="mutation"?J(()=>K("mutation",m,x,F,!0).then(U)).then(l):C(()=>q("action",m,x,F));v??=(d,m,x,F,we)=>B.run(we,()=>he(d,m,x,F));const ve=((d,m)=>V(d)?C(()=>K("query",d,M,m,!1).then(U)):C(()=>Promise.resolve(d(M)))),me=((d,m)=>{const x=V(d)?()=>K("mutation",d,L,m,!1).then(U):()=>d(L);return J(x).then(l)}),pe=((d,m)=>V(d)?C(()=>K("action",d,Q,m,!1).then(U)):C(()=>Promise.resolve(d(Q)))),ye=Ze((...d)=>C(()=>K(...d).then(U)),M,f,()=>e?.now??Date.now()),ge=d=>J(()=>d(fe)).then(l);return{action:T(pe),close:c,mutation:T(me),notify:s,query:T(ve),queues:k,run:T(ge),scheduler:E,subscribe:ye,topics:o,wideEvent:()=>_.recorded,withIdentity:d=>te(d)}};return te(null)};export{ht as lunoraTest};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/testing",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.345",
|
|
4
4
|
"description": "Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"@lunora/platform": "^1.0.0-alpha.81",
|
|
59
59
|
"@lunora/queue": "^1.0.0-alpha.147",
|
|
60
60
|
"@lunora/scheduler": "^1.0.0-alpha.176",
|
|
61
|
-
"@lunora/server": "^1.0.0-alpha.
|
|
61
|
+
"@lunora/server": "^1.0.0-alpha.295",
|
|
62
62
|
"@lunora/wire": "^1.0.0-alpha.7",
|
|
63
63
|
"@visulima/notification": "2.0.3",
|
|
64
64
|
"ai": "7.0.184"
|
|
@@ -1 +0,0 @@
|
|
|
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 B,registeredFunctionKind as V}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,assertDedupKey as ke,MAX_RETRY_ATTEMPTS as qe,RETRY_BASE_DELAY_MS as De}from"@lunora/scheduler";import{DatabaseSync as Ce}from"node:sqlite";const O=(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} })`)},Me=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),Le=t=>new Proxy({...t},{get(e,r){if(!(Me.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)=>O(t,e),{apply:()=>O(t,e),get:()=>O(t,e)}),ae={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Fe={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>ae},Be=()=>{const t={attributes:{},events:[],links:[]},e={addEvent:(r,a)=>{t.events.push({...a===void 0?{}:{attributes:{...a}},name:r})},addLink:r=>{t.links.push({spanId:r.spanId,traceId:r.traceId})},recordEvaluation:r=>{Object.assign(t.attributes,Ae(r))},recordException:r=>{const a={"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&&(a["exception.stacktrace"]=r.stack),e.addEvent("exception",a)},setAttribute:(r,a)=>{t.attributes[r]=a},setAttributes:r=>{Object.assign(t.attributes,r)},spanContext:()=>ae};return{handle:e,recorded:t}},Y=async(t,e)=>await e(Y,Fe),G={count:()=>{},gauge:()=>{},record:()=>{}},z={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>z},W="notify",Ke=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},j=(t,e)=>typeof t=="function"?t(e):t,je=(t,e)=>{const r=[],a=(h,y)=>(r.push({channel:h,payload:structuredClone(y)}),{data:{messageId:`${h}-${String(r.length)}`,sent:!0,timestamp:new Date},success:!0}),g=h=>({channel:h,id:`lunora-testing-${h}`,initialize:()=>{},isAvailable:()=>!0,send:y=>a(h,y)}),c=j(t.webPush,e)!==void 0,w=j(t.fcm,e)!==void 0,f={...g("push"),send:h=>{const y=Array.isArray(h.to)?h.to:[h.to];if(y.length===0)throw new A("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const $ of y){const T=Ke($)!==void 0;if(T?!c:!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 a("push",h)}},p={...c||w?{push:f}:{},...j(t.chat,e)===void 0?{}:{chat:g("chat")},...j(t.inApp,e)===void 0?{}:{inapp:g("inapp")},...j(t.webhook,e)===void 0?{}:{webhook:g("webhook")}},l=Ne(),{notify:v,push:S}=Re({...t,store:()=>l},e,{engine:Te(p),silent:!0});return{controls:{clear:()=>{r.length=0},sent:h=>h===void 0?[...r]:r.filter(y=>y.channel===h)},surfaces:{notify:v,push:S}}},Ue=(t,e)=>t!==void 0?je(t,e):{controls:{clear:()=>O("notify",W),sent:()=>O("notify",W)},surfaces:{notify:b("notify",W),push:b("push",W)}},Z="queues: [...]",re=128*1024,ne=256*1024,Je="json",oe=new TextEncoder,Qe=(t,e)=>{if(e==="v8"){const a=Pe(t);return{body:_e(a),bytes:a.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=[],a=(c,w,f)=>{const p=f?.contentType??Je,l=Qe(w,p);if(l.bytes>re)throw new A("VALIDATION_ERROR",`@lunora/queue: ${c} message is ${String(l.bytes)} bytes, over the Cloudflare Queues limit of ${String(re)} (128 KB)`);return{bytes:l.bytes,message:{body:l.body,contentType:p,...f?.delaySeconds===void 0?{}:{delaySeconds:f.delaySeconds},destination:c}}},g=c=>({send:(w,f)=>(r.push(a(c,w,f).message),Promise.resolve()),sendBatch:(w,f)=>{const p=[...w].map(v=>a(c,v.body,{contentType:v.contentType,delaySeconds:v.delaySeconds??f?.delaySeconds})),l=p.reduce((v,S)=>v+S.bytes,0);if(l>ne)throw new A("VALIDATION_ERROR",`@lunora/queue: ${c} batch is ${String(l)} bytes, over the Cloudflare Queues limit of ${String(ne)} (256 KB)`);return r.push(...p.map(v=>v.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...e].map(c=>[c,g(c)])),clear:()=>{r.length=0},read:(c,w,f)=>{if(c===void 0)return[...r];if(!e.has(c))throw new A("INTERNAL",`${w}("${c}"): no such ${f} — declared: ${[...e].join(", ")||"(none)"}`);return r.filter(p=>p.destination===c)}}},We=t=>{const e=ue(t);return{controls:{clear:e.clear,sent:r=>e.read(r,"harness.queues.sent","queue").map(({destination:a,...g})=>({...g,queue:a}))},surfaces:{queues:Ie({bindings:e.bindings})}}},Ve=t=>t!==void 0?We(t):{controls:{clear:()=>O("queues",Z),sent:()=>O("queues",Z)},surfaces:{queues:b("queues",Z)}},Ye=864e5,ze=(t,e,r,a,g)=>{let c=g,w=1;const f=new Map,p=new Map,l=new Map,v=[],S=new Map,h=(o,n,s={},u,i)=>{ke(i);const E=ce(s);JSON.stringify(E);const P=ie(E),N=u??`fake-job-${String(w)}`;return w+=1,l.delete(N),f.set(N,{args:P,...i===void 0?{}:{dedupKey:i},enqueuedAt:c,functionPath:n,id:N,scheduledFor:o}),N},y=o=>typeof o=="string"?o:"__lunoraRef"in o?o.__lunoraRef:o.name??o.className??"",$={cancel:o=>{const n=f.get(o),s=n!==void 0;return n!==void 0&&l.set(o,{...n,completedAt:c,state:"canceled"}),f.delete(o),Promise.resolve({cancelled:s})},get:o=>{const n=f.get(o),s=p.get(o);let u=l.get(o);return u?.completedAt!==void 0&&u.completedAt<=c-$e&&(u=void 0),n!==void 0?u={...n,state:"pending"}:s!==void 0&&(u={...s,state:"running"}),Promise.resolve(u??null)},list:()=>Promise.resolve([...f.values()]),runAfter:(o,n,s,u)=>{xe(o,"ctx.scheduler.runAfter");const i=h(c+o,y(n),s,u?.id,u?.dedupKey);return Promise.resolve(i)},runAt:(o,n,s,u)=>{const i=h(o,y(n),s,u?.id,u?.dedupKey);return Promise.resolve(i)}},T=async o=>{f.delete(o.id);const n=a(),s=o.functionPath===void 0?void 0:n.get(o.functionPath);if(s===void 0)throw new A("FUNCTION_NOT_FOUND",`unknown functionPath "${o.functionPath??"(workflow-targeted)"}"`,{status:404});if(s.kind!=="mutation"&&s.kind!=="action")throw new A("FUNCTION_NOT_FOUND",`functionPath "${o.functionPath??"(workflow-targeted)"}" is a ${s.kind} — only mutations and actions can be scheduled`,{status:404});const u=o.dedupKey===void 0?void 0:`${o.functionPath??""}\0${o.dedupKey}`,i=u===void 0?void 0:S.get(u);if(i!==void 0&&c-i<Ye)return;const E=t(),P=s.kind==="action"?r():e();await E(s.kind,s,P,o.args,c),u!==void 0&&S.set(u,c)},_=async o=>{const n=[...f.values()].filter(i=>i.scheduledFor<=o).toSorted((i,E)=>i.scheduledFor-E.scheduledFor),s=[];let u=0;for(const i of n)if(f.has(i.id)){u+=1;try{p.set(i.id,i),await T(i),l.set(i.id,{...i,completedAt:c,state:"succeeded"})}catch(E){const P=(i.attempts??0)+1;if(P>qe){const N={args:i.args,error:E,functionPath:i.functionPath??"",id:i.id};s.push(N),v.push(N),l.set(i.id,{...i,attempts:P,completedAt:c,error:`dead-lettered after ${String(P)} attempts`,state:"failed"})}else{const N=De*2**(P-1);f.set(i.id,{...i,attempts:P,scheduledFor:c+N})}}finally{p.delete(i.id)}}return{executed:u,failed:s}},k=async(o,n)=>{const{executed:s,failed:u}=await _(o);if(u.length>0&&(n?.throwOnError??!0)){const[i]=u;throw u.length===1&&i!==void 0?i.error:new AggregateError(u.map(E=>E.error),`${String(u.length)} scheduled jobs failed: ${u.map(E=>E.functionPath).join(", ")}`)}return s};return{controls:{advance:(o,n)=>(c+=o,k(c,n)),failures:()=>[...v],list:()=>[...f.values()],runPending:o=>k(Number.POSITIVE_INFINITY,o)},scheduler:$}},ee="topics: [...]",Xe=t=>{if(t===void 0)return{controls:{clear:()=>O("topics",ee),published:()=>O("topics",ee)},surfaces:{topics:b("topics",ee)}};const e=ue(t),r=Oe(e.bindings,t.map(a=>({exportName:a,subscriptions:[{binding:a,exportName:a}]})));return{controls:{clear:e.clear,published:a=>e.read(a,"harness.topics.published","topic").map(({destination:g,...c})=>({...c,topic:g}))},surfaces:{topics:r}}},He=()=>{const t=new Ce(":memory:"),e=a=>({one(){if(a.length!==1)throw new A("INTERNAL",`expected exactly one row, received ${String(a.length)}`);const[g]=a;return g},[Symbol.iterator](){return a[Symbol.iterator]()},toArray(){return a}});return{close:()=>{t.close()},sql:{exec:(a,...g)=>{const w=t.prepare(a).all(...g);return e(w)}}}},K=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})}},Ge=new se,Ze=(t,e,r,a)=>(c,w)=>{let f=!1;const p=[];let l,v,S=0,h=0;const y=()=>K.run(a(),()=>V(c)?t("query",c,e,w,!1):Promise.resolve(c(e))),$=(n,s)=>{if(n<h)return;h=n;const u={done:!1,value:s};if(p.length===0)l=u,v=void 0;else{l=void 0,v=void 0;for(const i of p.splice(0))i.resolve(u)}},T=(n,s)=>{if(!(n<h))if(h=n,p.length===0)v={error:s},l=void 0;else{l=void 0,v=void 0;for(const u of p.splice(0))u.reject(s)}},_=n=>s=>{$(n,s)},k=n=>s=>{T(n,s)},D=()=>{if(f)return;S+=1;const n=S;y().then(_(n)).catch(k(n))};r.add(D);const o={[Symbol.asyncIterator](){return o},next:()=>{if(f)return Promise.resolve({done:!0,value:void 0});if(h===S){if(v!==void 0){const{error:n}=v;return v=void 0,Promise.reject(n)}if(l!==void 0){const n=l;return l=void 0,Promise.resolve(n)}}return h<S?new Promise((n,s)=>{p.push({reject:s,resolve:n})}):y().then(n=>{if(v!==void 0){const{error:s}=v;throw v=void 0,s}if(l!==void 0){const s=l;return l=void 0,s}return{done:!1,value:n}})},return:()=>{f=!0,r.delete(D);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(_(0)).catch(k(0)),o},ht=(t,e)=>{const{close:r,sql:a}=He();let g=!1;const c=()=>{g||(g=!0,r())},w=new Map(Object.entries(e?.functions??{}).map(([R,I])=>[R,I])),f=new Set,p=()=>{for(const R of f)R()},l=R=>(p(),R);let v,S,h;const y=()=>e?.now??Date.now(),$=y(),T=R=>((...I)=>K.run(y(),()=>R(...I))),_=Be(),{controls:k,surfaces:D}=Ve(e?.queues),{controls:o,surfaces:n}=Xe(e?.topics),{controls:s,surfaces:u}=Ue(e?.notify,e?.env??{}),i=(R,I)=>{if(R===void 0)throw new A("INTERNAL",`[fake-scheduler] ${I} not yet available — scheduler.advance called before harness construction completed`);return R},{controls:E,scheduler:P}=ze(()=>i(v,"dispatch"),()=>i(S,"mutationContext"),()=>i(h,"actionContext"),()=>w,$),N=be(P),{createWriters:de,runInTransaction:J,runWithBudget:C}=Se(t,{enforceRls:e?.enforceRls,headroomScope:Ge,scheduler:N,sql:a}),te=R=>{const I=Ee(R),X={getIdentity:()=>Promise.resolve(I.claims),userId:I.userId},{database:H,rawDatabase:le}=de(I),M={...u,auth:X,db:H,env:e?.env,log:z,metrics:G,get now(){return K.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runQuery:((d,m)=>q("query",d,M,m)),secrets:b("secrets"),storage:b("storage"),vectors:b("vectors")},L={...u,...D,...n,auth:X,db:H,env:e?.env,log:z,metrics:G,get now(){return K.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runMutation:((d,m)=>q("mutation",d,L,m)),runQuery:((d,m)=>q("query",d,M,m)),scheduler:N,secrets:b("secrets"),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};S??=L;const fe=Object.defineProperties({},{...Object.getOwnPropertyDescriptors(L),db:{enumerable:!0,value:le}}),Q={...u,...D,...n,auth:X,db:H,env:e?.env,fetch:e?.fetch??b("fetch"),log:z,metrics:G,get now(){return K.getStore()??y()},newId:()=>crypto.randomUUID(),random:()=>Math.random(),shardKey:e?.shardKey??"__root__",span:_.handle,trace:Y,runAction:((d,m)=>q("action",d,Q,m)),runMutation:((d,m)=>J(()=>q("mutation",d,L,m)).then(l)),runQuery:((d,m)=>q("query",d,M,m)),scheduler:N,secrets:b("secrets"),services:Le(e?.services),storage:b("storage"),vectors:b("vectors"),workflows:b("workflows")};h??=Q;const q=(d,m,x,F)=>B(d,m,x,F,!0),he=(d,m,x,F)=>d==="mutation"?J(()=>B("mutation",m,x,F,!0).then(U)).then(l):C(()=>q("action",m,x,F));v??=(d,m,x,F,we)=>K.run(we,()=>he(d,m,x,F));const ve=((d,m)=>V(d)?C(()=>B("query",d,M,m,!1).then(U)):C(()=>Promise.resolve(d(M)))),me=((d,m)=>{const x=V(d)?()=>B("mutation",d,L,m,!1).then(U):()=>d(L);return J(x).then(l)}),pe=((d,m)=>V(d)?C(()=>B("action",d,Q,m,!1).then(U)):C(()=>Promise.resolve(d(Q)))),ye=Ze((...d)=>C(()=>B(...d).then(U)),M,f,()=>e?.now??Date.now()),ge=d=>J(()=>d(fe)).then(l);return{action:T(pe),close:c,mutation:T(me),notify:s,query:T(ve),queues:k,run:T(ge),scheduler:E,subscribe:ye,topics:o,wideEvent:()=>_.recorded,withIdentity:d=>te(d)}};return te(null)};export{ht as lunoraTest};
|