@lunora/testing 1.0.0-alpha.246 → 1.0.0-alpha.248

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
@@ -122,6 +122,18 @@ Pass a `services` option with a fake per `lunora.config` service an action calls
122
122
  (`{ documentParser: { fetch } }`). See the [package docs](https://lunora.sh/docs/packages/testing#injectable-ctxservices)
123
123
  for an example.
124
124
 
125
+ #### Recording `ctx.queues`, `ctx.topics` and `ctx.notify` / `ctx.push`
126
+
127
+ Pass `queues` / `topics` (the queue and topic export names from
128
+ `lunora/queues.ts`) and/or `notify` (the `lunora/notify.ts` default export).
129
+ Sends are recorded instead of delivered, and read back with
130
+ `t.queues.sent(name)` / `t.topics.published(name)` / `t.notify.sent(channel)`. See the
131
+ [package docs](https://lunora.sh/docs/packages/testing#queues) for details.
132
+
133
+ ```ts
134
+ const t = lunoraTest(schema, { notify, queues: ["jobs"], topics: ["signups"] });
135
+ ```
136
+
125
137
  #### Fixed `ctx.now`
126
138
 
127
139
  Pass a `now` option (epoch ms) to pin `ctx.now` across every context, so
package/dist/index.d.mts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { AgentMessageRow, AgentRunInput, AgentGenerateResult, AgentRunResult, AgentDefinition } from '@lunora/agent';
2
2
  import { ArtifactsBindingLike, ArtifactsErrorCode, ArtifactsCommitMetadata, ArtifactsTreeEntry } from '@lunora/bindings/artifacts';
3
3
  import { ScheduledJob, LogFields, RegisteredAction, RegisteredMutation, RegisteredQuery, ArgsValidator, InferArgs, ActionCtx, MutationCtx, QueryCtx, TableDefinition, Schema } from '@lunora/server';
4
+ import { NotifyDefinition } from '@lunora/notify';
5
+ import { ChannelType, ChannelPayloadMap } from '@visulima/notification';
6
+ import { QueueContentType } from '@lunora/queue';
4
7
  export {
5
8
  /**
6
9
  * `@lunora/testing` — the user-facing toolkit for end-to-end testing a Lunora app.
@@ -386,6 +389,62 @@ interface RecordedWideEvent {
386
389
  traceId: string;
387
390
  }[];
388
391
  }
392
+ /** The channels `ctx.notify` can deliver on. */
393
+ type NotifyChannel = Extract<ChannelType, "chat" | "inapp" | "push" | "webhook">;
394
+ /**
395
+ * One delivery a handler made through `ctx.notify` / `ctx.push`. For push,
396
+ * `payload.to` is the device target: the FCM token, or for Web Push the
397
+ * JSON-stringified subscription (keys included).
398
+ */
399
+ type SentNotification = { [C in NotifyChannel]: {
400
+ channel: C;
401
+ payload: ChannelPayloadMap[C];
402
+ }; }[NotifyChannel];
403
+ /** Inspect what handlers delivered through `ctx.notify` / `ctx.push`. */
404
+ interface FakeNotifyControls {
405
+ /** Forget every recorded delivery (registered subscriptions are kept). */
406
+ clear: () => void;
407
+ /** Recorded deliveries in send order, optionally only those on `channel`. Throws when `options.notify` was not passed. */
408
+ sent: (channel?: NotifyChannel) => SentNotification[];
409
+ }
410
+ /** One message a handler enqueued through `ctx.queues.<name>`, as the consumer decodes it. */
411
+ interface SentQueueMessage {
412
+ body: unknown;
413
+ contentType?: QueueContentType;
414
+ delaySeconds?: number;
415
+ /** The `lunora/queues.ts` export name the message was sent through. */
416
+ queue: string;
417
+ }
418
+ /**
419
+ * Inspect what handlers enqueued. Production sends are not transactional — a
420
+ * mutation that throws after `ctx.queues.x.send(...)` has still sent it — so the
421
+ * record keeps those too. Nothing is consumed: a test asserts on the messages and
422
+ * drives the consumer itself if it wants to.
423
+ */
424
+ interface FakeQueueControls {
425
+ /** Forget every recorded message. */
426
+ clear: () => void;
427
+ /** Recorded messages in send order, optionally only those sent to `queue`; an undeclared `queue` throws. */
428
+ sent: (queue?: string) => SentQueueMessage[];
429
+ }
430
+ /** One message a handler published through `ctx.topics.<name>`, as a subscriber decodes it. */
431
+ interface PublishedTopicMessage {
432
+ body: unknown;
433
+ contentType?: QueueContentType;
434
+ delaySeconds?: number;
435
+ /** The `lunora/queues.ts` topic export name the message was published to. */
436
+ topic: string;
437
+ }
438
+ /**
439
+ * Inspect what handlers published. Like queue sends, a publish is not
440
+ * transactional, so one made by a mutation that then threw stays recorded.
441
+ */
442
+ interface FakeTopicControls {
443
+ /** Forget every recorded message. */
444
+ clear: () => void;
445
+ /** Recorded messages in publish order, optionally only those published to `topic`; an undeclared `topic` throws. */
446
+ published: (topic?: string) => PublishedTopicMessage[];
447
+ }
389
448
  /** The schema value produced by `@lunora/server`'s `defineSchema`. */
390
449
  type TestSchema = Schema<Record<string, TableDefinition>>;
391
450
  /**
@@ -503,6 +562,28 @@ interface LunoraTestOptions {
503
562
  * ```
504
563
  */
505
564
  functions?: FunctionRegistry;
565
+ /**
566
+ * The app's `lunora/notify.ts` default export. Enables `ctx.notify` and its
567
+ * `ctx.push` alias on every context, built by `@lunora/notify`'s own
568
+ * `createNotify` — so register / list / unregister / broadcast behave as in
569
+ * production, and channels are wired exactly when production wires them
570
+ * (each factory is called with `options.env`; a push target for a transport
571
+ * that resolved to nothing fails). Differences: deliveries are recorded and
572
+ * report accepted instead of reaching a service (no send-time DNS re-check,
573
+ * retry or circuit breaker), and subscriptions live in an in-memory store —
574
+ * the definition's `store` is never called. Assert on deliveries with
575
+ * `harness.notify.sent()`. Left unset, touching `ctx.notify` / `ctx.push` —
576
+ * or calling `harness.notify.sent()` — throws, naming this option.
577
+ * @example
578
+ * ```ts
579
+ * import notify from "../lunora/notify";
580
+ *
581
+ * const t = lunoraTest(schema, { notify });
582
+ * await t.action(alertOwner, { orderId });
583
+ * expect(t.notify.sent("push")).toHaveLength(1);
584
+ * ```
585
+ */
586
+ notify?: NotifyDefinition;
506
587
  /**
507
588
  * Fixed value for `ctx.now` (epoch ms) in every context. Production captures
508
589
  * `Date.now()` once per execution; in tests a fixed `now` makes time-dependent
@@ -513,6 +594,23 @@ interface LunoraTestOptions {
513
594
  * ```
514
595
  */
515
596
  now?: number;
597
+ /**
598
+ * The export names of the queues in `lunora/queues.ts` (the keys of
599
+ * `ctx.queues`). Each gets a recording producer on mutation and action
600
+ * contexts, behind `@lunora/queue`'s own validation (batch cap, delay
601
+ * ceiling), so a send the platform would refuse rejects here too. A name not
602
+ * listed rejects on use, as an undeclared queue does in production. Assert
603
+ * on sends with `harness.queues.sent(name)`. Left unset, touching
604
+ * `ctx.queues` — or calling `harness.queues.sent()` — throws, naming this
605
+ * option.
606
+ * @example
607
+ * ```ts
608
+ * const t = lunoraTest(schema, { queues: ["jobs"] });
609
+ * await t.mutation(enqueueJob, { id: "a" });
610
+ * expect(t.queues.sent("jobs")).toEqual([{ body: { id: "a" }, queue: "jobs" }]);
611
+ * ```
612
+ */
613
+ queues?: ReadonlyArray<string>;
516
614
  /**
517
615
  * Fakes for `ctx.services` (the `lunora.config` `services` an app calls),
518
616
  * keyed like `ctx.services`. Set on action contexts only — queries and
@@ -526,6 +624,24 @@ interface LunoraTestOptions {
526
624
  * ```
527
625
  */
528
626
  services?: Record<string, object>;
627
+ /**
628
+ * The export names of the topics in `lunora/queues.ts` (the keys of
629
+ * `ctx.topics`). Each gets a recording publisher on mutation and action
630
+ * contexts, built by `@lunora/queue`'s own `createTopicContext` — so the
631
+ * batch cap, delay ceiling and reserved-key check reject as in production,
632
+ * and a name not listed rejects on use. Bodies are recorded and size-checked
633
+ * as `queues` records them, once per message however many subscriptions the
634
+ * app declares; no subscription handler runs. Assert with
635
+ * `harness.topics.published(name)`. Left unset, touching `ctx.topics` — or
636
+ * calling `harness.topics.published()` — throws, naming this option.
637
+ * @example
638
+ * ```ts
639
+ * const t = lunoraTest(schema, { topics: ["signups"] });
640
+ * await t.mutation(signUp, { email: "a@example.test" });
641
+ * expect(t.topics.published("signups")).toHaveLength(1);
642
+ * ```
643
+ */
644
+ topics?: ReadonlyArray<string>;
529
645
  }
530
646
  /**
531
647
  * The in-memory test harness returned by {@link lunoraTest}. Mirrors the first
@@ -547,11 +663,25 @@ interface TestHarness {
547
663
  <A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgs<A>): Promise<R>;
548
664
  <R>(inline: InlineMutationFunction<R>): Promise<R>;
549
665
  };
666
+ /**
667
+ * What handlers delivered through `ctx.notify` / `ctx.push` (enabled by
668
+ * `options.notify`): `sent(channel?)` in send order, `clear()` to reset.
669
+ * Both throw when the option was not passed. Shared with any `withIdentity` view.
670
+ */
671
+ notify: FakeNotifyControls;
550
672
  /** Run a registered `query` (or an inline `async (context) => …`) against the harness. */
551
673
  query: {
552
674
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): Promise<R>;
553
675
  <R>(inline: InlineQueryFunction<R>): Promise<R>;
554
676
  };
677
+ /**
678
+ * What handlers enqueued through `ctx.queues` (declared by `options.queues`):
679
+ * `sent(name?)` in send order, `clear()` to reset. Sends are not
680
+ * transactional in production, so one made by a mutation that then threw is
681
+ * recorded too. Both throw when the option was not passed. Shared with any
682
+ * `withIdentity` view.
683
+ */
684
+ queues: FakeQueueControls;
555
685
  /**
556
686
  * Direct db access at mutation-level (read + write), mirroring `convexTest`'s
557
687
  * `run`. This is the harness's trusted escape hatch: `ctx.db` here is always
@@ -603,6 +733,13 @@ interface TestHarness {
603
733
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): TestSubscription<R>;
604
734
  <R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
605
735
  };
736
+ /**
737
+ * What handlers published through `ctx.topics` (declared by `options.topics`):
738
+ * `published(name?)` in publish order, `clear()` to reset. Like queue sends,
739
+ * publishes are not transactional. Both throw when the option was not passed.
740
+ * Shared with any `withIdentity` view.
741
+ */
742
+ topics: FakeTopicControls;
606
743
  /**
607
744
  * What handlers attached to `ctx.span` — the **wide event** — during this
608
745
  * harness's runs, so a test can assert the instrumentation itself:
@@ -642,6 +779,12 @@ interface TestHarness {
642
779
  * control via `harness.scheduler.advance(ms)` / `runPending()` / `list()`. As in
643
780
  * production it is transactional inside a mutation: a job scheduled by a mutation
644
781
  * that then throws never becomes pending.
782
+ * - `ctx.queues` (mutations + actions): recording producers for `options.queues`;
783
+ * inspect via `harness.queues.sent(name)`.
784
+ * - `ctx.topics` (mutations + actions): recording publishers for `options.topics`;
785
+ * inspect via `harness.topics.published(name)`.
786
+ * - `ctx.notify` / `ctx.push` (all contexts): built from `options.notify` with
787
+ * recorded deliveries and in-memory subscriptions; inspect via `harness.notify.sent()`.
645
788
  * - `harness.subscribe(query, args)`: async iterable that re-emits after mutations.
646
789
  *
647
790
  * **v1 stubs (still throwing):** `ctx.storage`, `ctx.vectors`, `ctx.workflows`.
@@ -799,4 +942,4 @@ declare const groundednessScorer: (options: {
799
942
  judge: (prompt: string) => Promise<string>;
800
943
  name?: string;
801
944
  }) => Scorer;
802
- export { type AgentHarness, type AgentHarnessOptions, type AgentRunOverrides, type ArtifactsFake, type EvalCase, type EvalItemResult, type EvalResult, type EvaluationAttributeValue, type EvaluationMetrics, type EvaluationSpanHandle, type FakeScheduledJob, type FakeSchedulerControls, type FunctionRegistry, type HarnessDispatch, type HarnessMessage, type HarnessThread, type LunoraTestOptions, type ProducedOutput, type RecordEvaluationInput, type RetrievalScorerOptions, type ScheduledJobFailure, type ScoreResult, type Scorer, type ScorerSample, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, agentHarness, containsScorer, createArtifactsFake, evaluate, evaluationAttributes, exactMatchScorer, finalTurn, groundednessScorer, keywordScorer, llmScorer, lunoraTest, mrrScorer, ndcgAtK, precisionAtK, recallAtK, recordEvaluation, regexScorer, scoreSample, toolCallTurn };
945
+ export { type AgentHarness, type AgentHarnessOptions, type AgentRunOverrides, type ArtifactsFake, type EvalCase, type EvalItemResult, type EvalResult, type EvaluationAttributeValue, type EvaluationMetrics, type EvaluationSpanHandle, type FakeNotifyControls, type FakeQueueControls, type FakeScheduledJob, type FakeSchedulerControls, type FakeTopicControls, type FunctionRegistry, type HarnessDispatch, type HarnessMessage, type HarnessThread, type LunoraTestOptions, type NotifyChannel, type ProducedOutput, type PublishedTopicMessage, type RecordEvaluationInput, type RetrievalScorerOptions, type ScheduledJobFailure, type ScoreResult, type Scorer, type ScorerSample, type SentNotification, type SentQueueMessage, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, agentHarness, containsScorer, createArtifactsFake, evaluate, evaluationAttributes, exactMatchScorer, finalTurn, groundednessScorer, keywordScorer, llmScorer, lunoraTest, mrrScorer, ndcgAtK, precisionAtK, recallAtK, recordEvaluation, regexScorer, scoreSample, toolCallTurn };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { AgentMessageRow, AgentRunInput, AgentGenerateResult, AgentRunResult, AgentDefinition } from '@lunora/agent';
2
2
  import { ArtifactsBindingLike, ArtifactsErrorCode, ArtifactsCommitMetadata, ArtifactsTreeEntry } from '@lunora/bindings/artifacts';
3
3
  import { ScheduledJob, LogFields, RegisteredAction, RegisteredMutation, RegisteredQuery, ArgsValidator, InferArgs, ActionCtx, MutationCtx, QueryCtx, TableDefinition, Schema } from '@lunora/server';
4
+ import { NotifyDefinition } from '@lunora/notify';
5
+ import { ChannelType, ChannelPayloadMap } from '@visulima/notification';
6
+ import { QueueContentType } from '@lunora/queue';
4
7
  export {
5
8
  /**
6
9
  * `@lunora/testing` — the user-facing toolkit for end-to-end testing a Lunora app.
@@ -386,6 +389,62 @@ interface RecordedWideEvent {
386
389
  traceId: string;
387
390
  }[];
388
391
  }
392
+ /** The channels `ctx.notify` can deliver on. */
393
+ type NotifyChannel = Extract<ChannelType, "chat" | "inapp" | "push" | "webhook">;
394
+ /**
395
+ * One delivery a handler made through `ctx.notify` / `ctx.push`. For push,
396
+ * `payload.to` is the device target: the FCM token, or for Web Push the
397
+ * JSON-stringified subscription (keys included).
398
+ */
399
+ type SentNotification = { [C in NotifyChannel]: {
400
+ channel: C;
401
+ payload: ChannelPayloadMap[C];
402
+ }; }[NotifyChannel];
403
+ /** Inspect what handlers delivered through `ctx.notify` / `ctx.push`. */
404
+ interface FakeNotifyControls {
405
+ /** Forget every recorded delivery (registered subscriptions are kept). */
406
+ clear: () => void;
407
+ /** Recorded deliveries in send order, optionally only those on `channel`. Throws when `options.notify` was not passed. */
408
+ sent: (channel?: NotifyChannel) => SentNotification[];
409
+ }
410
+ /** One message a handler enqueued through `ctx.queues.<name>`, as the consumer decodes it. */
411
+ interface SentQueueMessage {
412
+ body: unknown;
413
+ contentType?: QueueContentType;
414
+ delaySeconds?: number;
415
+ /** The `lunora/queues.ts` export name the message was sent through. */
416
+ queue: string;
417
+ }
418
+ /**
419
+ * Inspect what handlers enqueued. Production sends are not transactional — a
420
+ * mutation that throws after `ctx.queues.x.send(...)` has still sent it — so the
421
+ * record keeps those too. Nothing is consumed: a test asserts on the messages and
422
+ * drives the consumer itself if it wants to.
423
+ */
424
+ interface FakeQueueControls {
425
+ /** Forget every recorded message. */
426
+ clear: () => void;
427
+ /** Recorded messages in send order, optionally only those sent to `queue`; an undeclared `queue` throws. */
428
+ sent: (queue?: string) => SentQueueMessage[];
429
+ }
430
+ /** One message a handler published through `ctx.topics.<name>`, as a subscriber decodes it. */
431
+ interface PublishedTopicMessage {
432
+ body: unknown;
433
+ contentType?: QueueContentType;
434
+ delaySeconds?: number;
435
+ /** The `lunora/queues.ts` topic export name the message was published to. */
436
+ topic: string;
437
+ }
438
+ /**
439
+ * Inspect what handlers published. Like queue sends, a publish is not
440
+ * transactional, so one made by a mutation that then threw stays recorded.
441
+ */
442
+ interface FakeTopicControls {
443
+ /** Forget every recorded message. */
444
+ clear: () => void;
445
+ /** Recorded messages in publish order, optionally only those published to `topic`; an undeclared `topic` throws. */
446
+ published: (topic?: string) => PublishedTopicMessage[];
447
+ }
389
448
  /** The schema value produced by `@lunora/server`'s `defineSchema`. */
390
449
  type TestSchema = Schema<Record<string, TableDefinition>>;
391
450
  /**
@@ -503,6 +562,28 @@ interface LunoraTestOptions {
503
562
  * ```
504
563
  */
505
564
  functions?: FunctionRegistry;
565
+ /**
566
+ * The app's `lunora/notify.ts` default export. Enables `ctx.notify` and its
567
+ * `ctx.push` alias on every context, built by `@lunora/notify`'s own
568
+ * `createNotify` — so register / list / unregister / broadcast behave as in
569
+ * production, and channels are wired exactly when production wires them
570
+ * (each factory is called with `options.env`; a push target for a transport
571
+ * that resolved to nothing fails). Differences: deliveries are recorded and
572
+ * report accepted instead of reaching a service (no send-time DNS re-check,
573
+ * retry or circuit breaker), and subscriptions live in an in-memory store —
574
+ * the definition's `store` is never called. Assert on deliveries with
575
+ * `harness.notify.sent()`. Left unset, touching `ctx.notify` / `ctx.push` —
576
+ * or calling `harness.notify.sent()` — throws, naming this option.
577
+ * @example
578
+ * ```ts
579
+ * import notify from "../lunora/notify";
580
+ *
581
+ * const t = lunoraTest(schema, { notify });
582
+ * await t.action(alertOwner, { orderId });
583
+ * expect(t.notify.sent("push")).toHaveLength(1);
584
+ * ```
585
+ */
586
+ notify?: NotifyDefinition;
506
587
  /**
507
588
  * Fixed value for `ctx.now` (epoch ms) in every context. Production captures
508
589
  * `Date.now()` once per execution; in tests a fixed `now` makes time-dependent
@@ -513,6 +594,23 @@ interface LunoraTestOptions {
513
594
  * ```
514
595
  */
515
596
  now?: number;
597
+ /**
598
+ * The export names of the queues in `lunora/queues.ts` (the keys of
599
+ * `ctx.queues`). Each gets a recording producer on mutation and action
600
+ * contexts, behind `@lunora/queue`'s own validation (batch cap, delay
601
+ * ceiling), so a send the platform would refuse rejects here too. A name not
602
+ * listed rejects on use, as an undeclared queue does in production. Assert
603
+ * on sends with `harness.queues.sent(name)`. Left unset, touching
604
+ * `ctx.queues` — or calling `harness.queues.sent()` — throws, naming this
605
+ * option.
606
+ * @example
607
+ * ```ts
608
+ * const t = lunoraTest(schema, { queues: ["jobs"] });
609
+ * await t.mutation(enqueueJob, { id: "a" });
610
+ * expect(t.queues.sent("jobs")).toEqual([{ body: { id: "a" }, queue: "jobs" }]);
611
+ * ```
612
+ */
613
+ queues?: ReadonlyArray<string>;
516
614
  /**
517
615
  * Fakes for `ctx.services` (the `lunora.config` `services` an app calls),
518
616
  * keyed like `ctx.services`. Set on action contexts only — queries and
@@ -526,6 +624,24 @@ interface LunoraTestOptions {
526
624
  * ```
527
625
  */
528
626
  services?: Record<string, object>;
627
+ /**
628
+ * The export names of the topics in `lunora/queues.ts` (the keys of
629
+ * `ctx.topics`). Each gets a recording publisher on mutation and action
630
+ * contexts, built by `@lunora/queue`'s own `createTopicContext` — so the
631
+ * batch cap, delay ceiling and reserved-key check reject as in production,
632
+ * and a name not listed rejects on use. Bodies are recorded and size-checked
633
+ * as `queues` records them, once per message however many subscriptions the
634
+ * app declares; no subscription handler runs. Assert with
635
+ * `harness.topics.published(name)`. Left unset, touching `ctx.topics` — or
636
+ * calling `harness.topics.published()` — throws, naming this option.
637
+ * @example
638
+ * ```ts
639
+ * const t = lunoraTest(schema, { topics: ["signups"] });
640
+ * await t.mutation(signUp, { email: "a@example.test" });
641
+ * expect(t.topics.published("signups")).toHaveLength(1);
642
+ * ```
643
+ */
644
+ topics?: ReadonlyArray<string>;
529
645
  }
530
646
  /**
531
647
  * The in-memory test harness returned by {@link lunoraTest}. Mirrors the first
@@ -547,11 +663,25 @@ interface TestHarness {
547
663
  <A extends ArgsValidator, R>(reference: RegisteredMutation<A, R>, args: InferArgs<A>): Promise<R>;
548
664
  <R>(inline: InlineMutationFunction<R>): Promise<R>;
549
665
  };
666
+ /**
667
+ * What handlers delivered through `ctx.notify` / `ctx.push` (enabled by
668
+ * `options.notify`): `sent(channel?)` in send order, `clear()` to reset.
669
+ * Both throw when the option was not passed. Shared with any `withIdentity` view.
670
+ */
671
+ notify: FakeNotifyControls;
550
672
  /** Run a registered `query` (or an inline `async (context) => …`) against the harness. */
551
673
  query: {
552
674
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): Promise<R>;
553
675
  <R>(inline: InlineQueryFunction<R>): Promise<R>;
554
676
  };
677
+ /**
678
+ * What handlers enqueued through `ctx.queues` (declared by `options.queues`):
679
+ * `sent(name?)` in send order, `clear()` to reset. Sends are not
680
+ * transactional in production, so one made by a mutation that then threw is
681
+ * recorded too. Both throw when the option was not passed. Shared with any
682
+ * `withIdentity` view.
683
+ */
684
+ queues: FakeQueueControls;
555
685
  /**
556
686
  * Direct db access at mutation-level (read + write), mirroring `convexTest`'s
557
687
  * `run`. This is the harness's trusted escape hatch: `ctx.db` here is always
@@ -603,6 +733,13 @@ interface TestHarness {
603
733
  <A extends ArgsValidator, R>(reference: RegisteredQuery<A, R>, args: InferArgs<A>): TestSubscription<R>;
604
734
  <R>(inline: InlineQueryFunction<R>): TestSubscription<R>;
605
735
  };
736
+ /**
737
+ * What handlers published through `ctx.topics` (declared by `options.topics`):
738
+ * `published(name?)` in publish order, `clear()` to reset. Like queue sends,
739
+ * publishes are not transactional. Both throw when the option was not passed.
740
+ * Shared with any `withIdentity` view.
741
+ */
742
+ topics: FakeTopicControls;
606
743
  /**
607
744
  * What handlers attached to `ctx.span` — the **wide event** — during this
608
745
  * harness's runs, so a test can assert the instrumentation itself:
@@ -642,6 +779,12 @@ interface TestHarness {
642
779
  * control via `harness.scheduler.advance(ms)` / `runPending()` / `list()`. As in
643
780
  * production it is transactional inside a mutation: a job scheduled by a mutation
644
781
  * that then throws never becomes pending.
782
+ * - `ctx.queues` (mutations + actions): recording producers for `options.queues`;
783
+ * inspect via `harness.queues.sent(name)`.
784
+ * - `ctx.topics` (mutations + actions): recording publishers for `options.topics`;
785
+ * inspect via `harness.topics.published(name)`.
786
+ * - `ctx.notify` / `ctx.push` (all contexts): built from `options.notify` with
787
+ * recorded deliveries and in-memory subscriptions; inspect via `harness.notify.sent()`.
645
788
  * - `harness.subscribe(query, args)`: async iterable that re-emits after mutations.
646
789
  *
647
790
  * **v1 stubs (still throwing):** `ctx.storage`, `ctx.vectors`, `ctx.workflows`.
@@ -799,4 +942,4 @@ declare const groundednessScorer: (options: {
799
942
  judge: (prompt: string) => Promise<string>;
800
943
  name?: string;
801
944
  }) => Scorer;
802
- export { type AgentHarness, type AgentHarnessOptions, type AgentRunOverrides, type ArtifactsFake, type EvalCase, type EvalItemResult, type EvalResult, type EvaluationAttributeValue, type EvaluationMetrics, type EvaluationSpanHandle, type FakeScheduledJob, type FakeSchedulerControls, type FunctionRegistry, type HarnessDispatch, type HarnessMessage, type HarnessThread, type LunoraTestOptions, type ProducedOutput, type RecordEvaluationInput, type RetrievalScorerOptions, type ScheduledJobFailure, type ScoreResult, type Scorer, type ScorerSample, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, agentHarness, containsScorer, createArtifactsFake, evaluate, evaluationAttributes, exactMatchScorer, finalTurn, groundednessScorer, keywordScorer, llmScorer, lunoraTest, mrrScorer, ndcgAtK, precisionAtK, recallAtK, recordEvaluation, regexScorer, scoreSample, toolCallTurn };
945
+ export { type AgentHarness, type AgentHarnessOptions, type AgentRunOverrides, type ArtifactsFake, type EvalCase, type EvalItemResult, type EvalResult, type EvaluationAttributeValue, type EvaluationMetrics, type EvaluationSpanHandle, type FakeNotifyControls, type FakeQueueControls, type FakeScheduledJob, type FakeSchedulerControls, type FakeTopicControls, type FunctionRegistry, type HarnessDispatch, type HarnessMessage, type HarnessThread, type LunoraTestOptions, type NotifyChannel, type ProducedOutput, type PublishedTopicMessage, type RecordEvaluationInput, type RetrievalScorerOptions, type ScheduledJobFailure, type ScoreResult, type Scorer, type ScorerSample, type SentNotification, type SentQueueMessage, type SweepOptions, type TestHarness, type TestIdentity, type TestSubscription, agentHarness, containsScorer, createArtifactsFake, evaluate, evaluationAttributes, exactMatchScorer, finalTurn, groundednessScorer, keywordScorer, llmScorer, lunoraTest, mrrScorer, ndcgAtK, precisionAtK, recallAtK, recordEvaluation, regexScorer, scoreSample, toolCallTurn };
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{createArtifactsFake as s}from"./packem_shared/createArtifactsFake-L0tjki11.mjs";import{lunoraTest as p}from"./packem_shared/lunoraTest-oQEDNSxM.mjs";import{groundednessScorer as f,mrrScorer as u,ndcgAtK as S,precisionAtK as d,recallAtK as A}from"./packem_shared/groundednessScorer-kgXJCZDg.mjs";import{containsScorer as k,evaluate as v,exactMatchScorer as K,keywordScorer as M,llmScorer as T,regexScorer as w,scoreSample as C}from"./packem_shared/containsScorer-DoLfFOs6.mjs";import{extractLink as b,listCapturedMail as h,waitForMail as y}from"@lunora/mail/testing";export{o as agentHarness,k as containsScorer,s as createArtifactsFake,v as evaluate,l as evaluationAttributes,K as exactMatchScorer,b as extractLink,t as finalTurn,f as groundednessScorer,M as keywordScorer,h as listCapturedMail,T as llmScorer,p as lunoraTest,u as mrrScorer,S as ndcgAtK,d as precisionAtK,A as recallAtK,n as recordEvaluation,w as regexScorer,C as scoreSample,a as toolCallTurn,y 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{createArtifactsFake as s}from"./packem_shared/createArtifactsFake-L0tjki11.mjs";import{lunoraTest as p}from"./packem_shared/lunoraTest-XYylSvj1.mjs";import{groundednessScorer as f,mrrScorer as u,ndcgAtK as S,precisionAtK as d,recallAtK as A}from"./packem_shared/groundednessScorer-kgXJCZDg.mjs";import{containsScorer as k,evaluate as v,exactMatchScorer as K,keywordScorer as M,llmScorer as T,regexScorer as w,scoreSample as C}from"./packem_shared/containsScorer-DoLfFOs6.mjs";import{extractLink as b,listCapturedMail as h,waitForMail as y}from"@lunora/mail/testing";export{o as agentHarness,k as containsScorer,s as createArtifactsFake,v as evaluate,l as evaluationAttributes,K as exactMatchScorer,b as extractLink,t as finalTurn,f as groundednessScorer,M as keywordScorer,h as listCapturedMail,T as llmScorer,p as lunoraTest,u as mrrScorer,S as ndcgAtK,d as precisionAtK,A as recallAtK,n as recordEvaluation,w as regexScorer,C as scoreSample,a as toolCallTurn,y as waitForMail};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{withDeferredSchedules as we}from"@lunora/server";import{createInProcessRuntime as ve,resolveInProcessIdentity as Ae,registeredFunctionKind as V,runRegisteredFunction as D}from"@lunora/server/in-process";import{evaluationAttributes as Ee}from"./evaluationAttributes-CYLgTP1P.mjs";import{memorySubscriptionStore as Se,createNotify as Re}from"@lunora/notify";import{createNotification as Te}from"@visulima/notification";import{serialize as Ne,deserialize as Oe}from"node:v8";import{createQueues as Pe,createTopicContext as xe}from"@lunora/queue";import{assertScheduleDelay as Ie,MAX_RETRY_ATTEMPTS as ke,RETRY_BASE_DELAY_MS as _e}from"@lunora/scheduler";import{DatabaseSync as $e}from"node:sqlite";const I=(e,r)=>{throw new R("INTERNAL",r===void 0?`ctx.${e} is not available in the in-memory @lunora/testing harness (v1)`:`ctx.${e} is not enabled in the @lunora/testing harness — pass lunoraTest(schema, { ${r} })`)},je=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),qe=e=>new Proxy({...e},{get(r,n){if(!(je.has(n)&&!Object.hasOwn(r,n))){if(typeof n=="symbol"||Object.hasOwn(r,n)||n in Object.prototype)return Reflect.get(r,n);throw new R("INTERNAL",`ctx.services.${n} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${n}: … } })`)}}}),E=(e,r)=>new Proxy((...n)=>I(e,r),{apply:()=>I(e,r),get:()=>I(e,r)}),de={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},Ce={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>de},Le=()=>{const e={attributes:{},events:[],links:[]},r={addEvent:(n,o)=>{e.events.push({...o===void 0?{}:{attributes:{...o}},name:n})},addLink:n=>{e.links.push({spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{Object.assign(e.attributes,Ee(n))},recordException:n=>{const o={"exception.message":n instanceof Error?n.message:String(n),"exception.type":n instanceof Error?n.constructor.name:"Error"};n instanceof Error&&n.stack!==void 0&&(o["exception.stacktrace"]=n.stack),r.addEvent("exception",o)},setAttribute:(n,o)=>{e.attributes[n]=o},setAttributes:n=>{Object.assign(e.attributes,n)},spanContext:()=>de};return{handle:r,recorded:e}},J=async(e,r)=>await r(J,Ce),ee={count:()=>{},gauge:()=>{},record:()=>{}},W={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>W},Q="notify",De=e=>{let r=e;if(typeof e=="string"){if(!e.startsWith("{"))return;try{r=JSON.parse(e)}catch{return}}const n=r?.endpoint;return typeof n=="string"?n:void 0},F=(e,r)=>typeof e=="function"?e(r):e,Fe=(e,r)=>{const n=[],o=(b,v)=>(n.push({channel:b,payload:structuredClone(v)}),{data:{messageId:`${b}-${String(n.length)}`,sent:!0,timestamp:new Date},success:!0}),f=b=>({channel:b,id:`lunora-testing-${b}`,initialize:()=>{},isAvailable:()=>!0,send:v=>o(b,v)}),t=F(e.webPush,r)!==void 0,s=F(e.fcm,r)!==void 0,c={...f("push"),send:b=>{const v=Array.isArray(b.to)?b.to:[b.to];if(v.length===0)throw new R("BAD_REQUEST","@lunora/notify: push send has no recipients — `to` is an empty array");for(const T of v){const k=De(T)!==void 0;if(k?!t:!s)throw new Error(k?"@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 o("push",b)}},d={...t||s?{push:c}:{},...F(e.chat,r)===void 0?{}:{chat:f("chat")},...F(e.inApp,r)===void 0?{}:{inapp:f("inapp")},...F(e.webhook,r)===void 0?{}:{webhook:f("webhook")}},l=Se(),{notify:h,push:S}=Re({...e,store:()=>l},r,{engine:Te(d),silent:!0});return{controls:{clear:()=>{n.length=0},sent:b=>b===void 0?[...n]:n.filter(v=>v.channel===b)},surfaces:{notify:h,push:S}}},Be=(e,r)=>e!==void 0?Fe(e,r):{controls:{clear:()=>I("notify",Q),sent:()=>I("notify",Q)},surfaces:{notify:E("notify",Q),push:E("push",Q)}},te="queues: [...]",se=128*1024,ce=256*1024,Me="json",ie=new TextEncoder,Ue=(e,r)=>{if(r==="v8"){const o=Ne(e);return{body:Oe(o),bytes:o.byteLength}}if(r==="text"){if(typeof e!="string")throw new R("VALIDATION_ERROR",`@lunora/queue: a "text" message body must be a string, got ${typeof e}`);return{body:e,bytes:ie.encode(e).byteLength}}if(r==="bytes"){if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw new R("VALIDATION_ERROR",'@lunora/queue: a "bytes" message body must be an ArrayBuffer or an ArrayBufferView');return{body:e,bytes:e.byteLength}}const n=JSON.stringify(e);if(typeof n!="string")throw new R("VALIDATION_ERROR",`@lunora/queue: a "json" message body must be JSON-serializable, got ${typeof e}`);return{body:JSON.parse(n),bytes:ie.encode(n).byteLength}},fe=e=>{const r=new Set(e),n=[],o=(t,s,c)=>{const d=c?.contentType??Me,l=Ue(s,d);if(l.bytes>se)throw new R("VALIDATION_ERROR",`@lunora/queue: ${t} message is ${String(l.bytes)} bytes, over the Cloudflare Queues limit of ${String(se)} (128 KB)`);return{bytes:l.bytes,message:{body:l.body,contentType:d,...c?.delaySeconds===void 0?{}:{delaySeconds:c.delaySeconds},destination:t}}},f=t=>({send:(s,c)=>(n.push(o(t,s,c).message),Promise.resolve()),sendBatch:(s,c)=>{const d=[...s].map(h=>o(t,h.body,{contentType:h.contentType,delaySeconds:h.delaySeconds??c?.delaySeconds})),l=d.reduce((h,S)=>h+S.bytes,0);if(l>ce)throw new R("VALIDATION_ERROR",`@lunora/queue: ${t} batch is ${String(l)} bytes, over the Cloudflare Queues limit of ${String(ce)} (256 KB)`);return n.push(...d.map(h=>h.message)),Promise.resolve()}});return{bindings:Object.fromEntries([...r].map(t=>[t,f(t)])),clear:()=>{n.length=0},read:(t,s,c)=>{if(t===void 0)return[...n];if(!r.has(t))throw new R("INTERNAL",`${s}("${t}"): no such ${c} — declared: ${[...r].join(", ")||"(none)"}`);return n.filter(d=>d.destination===t)}}},Ye=e=>{const r=fe(e);return{controls:{clear:r.clear,sent:n=>r.read(n,"harness.queues.sent","queue").map(({destination:o,...f})=>({...f,queue:o}))},surfaces:{queues:Pe({bindings:r.bindings})}}},Qe=e=>e!==void 0?Ye(e):{controls:{clear:()=>I("queues",te),sent:()=>I("queues",te)},surfaces:{queues:E("queues",te)}},X=e=>{let r="";for(let o=0;o<e.length;o+=32768)r+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(r)},Ve=e=>{const r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o+=1)n[o]=r.codePointAt(o)??0;return n},A="$lunora.wire$",H=64,K=1024,ne="__proto__",ae={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},ue={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},Je=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===null||r===Object.prototype},x=(e,r=0)=>{if(r>H)throw new RangeError(`wire-codec: value nesting exceeds the ${H}-level limit`);if(e===void 0)return[A,"undefined"];if(e===null)return null;const n=typeof e;if(n==="bigint"){const t=e.toString();if(t.length>K)throw new RangeError(`wire-codec: over-long bigint (max ${K} digits)`);return[A,"bigint",t]}if(n==="number"){const t=e;return Number.isNaN(t)?[A,"nan"]:t===1/0?[A,"inf"]:t===-1/0?[A,"-inf"]:t}if(n!=="object")return e;if(e instanceof Date)return[A,"date",x(e.getTime(),r+1)];if(e instanceof Error){const t=e,s=x(Object.fromEntries(Object.keys(t).map(d=>[d,t[d]])),r+1),c=[A,"error",String(t.name),String(t.message),s];return t.cause!==void 0&&c.push(x(t.cause,r+1)),c}if(e instanceof URL)return[A,"url",e.href];if(e instanceof Map)return[A,"map",[...e.entries()].map(([t,s])=>[x(t,r+1),x(s,r+1)])];if(e instanceof Set)return[A,"set",[...e].map(t=>x(t,r+1))];if(e instanceof ArrayBuffer)return[A,"bytes",X(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,s=t.constructor.name,c=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return s==="Uint8Array"?[A,"bytes",X(c)]:[A,"bytes",X(c),s]}if(Array.isArray(e)){const t=e.map(s=>x(s,r+1));return t.length>0&&t[0]===A?[A,"arr",t]:t}if(!Je(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 o=e,f={};for(const t of Object.keys(o)){const s=o[t];if(s===void 0)continue;const c=x(s,r+1);t===ne?Object.defineProperty(f,t,{configurable:!0,enumerable:!0,value:c,writable:!0}):f[t]=c}return f},O=(e,r=0)=>{if(r>H)throw new RangeError(`wire-codec: value nesting exceeds the ${H}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===A)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(t=>O(t,r+1));case"bigint":{const t=e[2];if(typeof t!="string"||t.length>K||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${K} digits)`);return BigInt(t)}case"date":{const t=O(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(s=>{if(!Array.isArray(s)||s.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[O(s[0],r+1),O(s[1],r+1)]}))}case"set":return new Set(e[2].map(t=>O(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],s=e[3];if(typeof t!="string"||typeof s!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const c=(Object.hasOwn(ue,t)?ue[t]:void 0)??Error,d=new c(s);d.name!==t&&Object.defineProperty(d,"name",{configurable:!0,value:t,writable:!0});const l=O(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 h of Object.keys(l))h===ne?Object.defineProperty(d,h,{configurable:!0,enumerable:!0,value:l[h],writable:!0}):d[h]=l[h];return e.length>5&&Object.defineProperty(d,"cause",{configurable:!0,value:O(e[5],r+1),writable:!0}),d}case"bytes":{const t=e[2];if(typeof t!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const s=Ve(t);if(X(s)!==t)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const c=e[3]??"Uint8Array";if(c==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:s.slice().buffer;const d=Object.hasOwn(ae,c)?ae[c]:void 0;return d?new d(s.slice().buffer):s}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(t=>O(t,r+1))}return e.map(f=>O(f,r+1))}const n=e,o={};for(const f of Object.keys(n)){const t=O(n[f],r+1);f===ne?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:t,writable:!0}):o[f]=t}return o},We=(e,r,n,o,f)=>{let t=f,s=1;const c=new Map,d=[],l=(u,g,m={},a)=>{const i=x(m);JSON.stringify(i);const w=O(i),N=a??`fake-job-${String(s)}`;return s+=1,c.set(N,{args:w,enqueuedAt:t,functionPath:g,id:N,scheduledFor:u}),N},h=u=>typeof u=="string"?u:"__lunoraRef"in u?u.__lunoraRef:u.name??u.className??"",S={cancel:u=>{const g=c.has(u);return c.delete(u),Promise.resolve({cancelled:g})},get:u=>Promise.resolve(c.get(u)??null),list:()=>Promise.resolve([...c.values()]),runAfter:(u,g,m,a)=>{Ie(u,"ctx.scheduler.runAfter");const i=l(t+u,h(g),m,a?.id);return Promise.resolve(i)},runAt:(u,g,m,a)=>{const i=l(u,h(g),m,a?.id);return Promise.resolve(i)}},b=async u=>{c.delete(u.id);const g=o(),m=u.functionPath===void 0?void 0:g.get(u.functionPath);if(m===void 0)throw new R("FUNCTION_NOT_FOUND",`unknown functionPath "${u.functionPath??"(workflow-targeted)"}"`,{status:404});if(m.kind!=="mutation"&&m.kind!=="action")throw new R("FUNCTION_NOT_FOUND",`functionPath "${u.functionPath??"(workflow-targeted)"}" is a ${m.kind} — only mutations and actions can be scheduled`,{status:404});const a=e(),i=m.kind==="action"?n():r();await a(m.kind,m,{...i,now:t},u.args)},v=async u=>{const g=[...c.values()].filter(i=>i.scheduledFor<=u).toSorted((i,w)=>i.scheduledFor-w.scheduledFor),m=[];let a=0;for(const i of g)if(c.has(i.id)){a+=1;try{await b(i)}catch(w){const N=(i.attempts??0)+1;if(N>ke){const j={args:i.args,error:w,functionPath:i.functionPath??"",id:i.id};m.push(j),d.push(j)}else{const j=_e*2**(N-1);c.set(i.id,{...i,attempts:N,scheduledFor:t+j})}}}return{executed:a,failed:m}},T=async(u,g)=>{const{executed:m,failed:a}=await v(u);if(a.length>0&&(g?.throwOnError??!0)){const[i]=a;throw a.length===1&&i!==void 0?i.error:new AggregateError(a.map(w=>w.error),`${String(a.length)} scheduled jobs failed: ${a.map(w=>w.functionPath).join(", ")}`)}return m};return{controls:{advance:(u,g)=>(t+=u,T(t,g)),failures:()=>[...d],list:()=>[...c.values()],runPending:u=>T(Number.POSITIVE_INFINITY,u)},scheduler:S}},re="topics: [...]",Xe=e=>{if(e===void 0)return{controls:{clear:()=>I("topics",re),published:()=>I("topics",re)},surfaces:{topics:E("topics",re)}};const r=fe(e),n=xe(r.bindings,e.map(o=>({exportName:o,subscriptions:[{binding:o,exportName:o}]})));return{controls:{clear:r.clear,published:o=>r.read(o,"harness.topics.published","topic").map(({destination:f,...t})=>({...t,topic:f}))},surfaces:{topics:n}}},He=()=>{const e=new $e(":memory:"),r=o=>({one(){if(o.length!==1)throw new R("INTERNAL",`expected exactly one row, received ${String(o.length)}`);const[f]=o;return f},[Symbol.iterator](){return o[Symbol.iterator]()},toArray(){return o}});return{close:()=>{e.close()},sql:{exec:(o,...f)=>{const s=e.prepare(o).all(...f);return r(s)}}}},Ke=(e,r,n)=>(f,t)=>{let s=!1;const c=[];let d,l,h=0,S=0;const b=()=>V(f)?e("query",f,r,t,!1):Promise.resolve(f(r)),v=(a,i)=>{if(a<S)return;S=a;const w={done:!1,value:i};if(c.length===0)d=w,l=void 0;else{d=void 0,l=void 0;for(const N of c.splice(0))N.resolve(w)}},T=(a,i)=>{if(!(a<S))if(S=a,c.length===0)l={error:i},d=void 0;else{d=void 0,l=void 0;for(const w of c.splice(0))w.reject(i)}},k=a=>i=>{v(a,i)},u=a=>i=>{T(a,i)},g=()=>{if(s)return;h+=1;const a=h;b().then(k(a)).catch(u(a))};n.add(g);const m={[Symbol.asyncIterator](){return m},next:()=>{if(s)return Promise.resolve({done:!0,value:void 0});if(S===h){if(l!==void 0){const{error:a}=l;return l=void 0,Promise.reject(a)}if(d!==void 0){const a=d;return d=void 0,Promise.resolve(a)}}return S<h?new Promise((a,i)=>{c.push({reject:i,resolve:a})}):b().then(a=>{if(l!==void 0){const{error:i}=l;throw l=void 0,i}if(d!==void 0){const i=d;return d=void 0,i}return{done:!1,value:a}})},return:()=>{s=!0,n.delete(g);for(const a of c.splice(0))a.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return b().then(k(0)).catch(u(0)),m},at=(e,r)=>{const{close:n,sql:o}=He();let f=!1;const t=()=>{f||(f=!0,n())},s=new Map(Object.entries(r?.functions??{}).map(([P,_])=>[P,_])),c=new Set,d=()=>{for(const P of c)P()},l=P=>(d(),P);let h,S,b;const v=r?.now??Date.now(),T=Le(),{controls:k,surfaces:u}=Qe(r?.queues),{controls:g,surfaces:m}=Xe(r?.topics),{controls:a,surfaces:i}=Be(r?.notify,r?.env??{}),w=(P,_)=>{if(P===void 0)throw new R("INTERNAL",`[fake-scheduler] ${_} not yet available — scheduler.advance called before harness construction completed`);return P},{controls:N,scheduler:j}=We(()=>w(h,"dispatch"),()=>w(S,"mutationContext"),()=>w(b,"actionContext"),()=>s,v),z=we(j),{createWriters:le,resetHeadroom:B,runInTransaction:M}=ve(e,{enforceRls:r?.enforceRls,scheduler:z,sql:o}),oe=P=>{const _=Ae(P),G={getIdentity:()=>Promise.resolve(_.claims),userId:_.userId},{database:Z,rawDatabase:ye}=le(_),q={...i,auth:G,db:Z,env:r?.env,log:W,metrics:ee,now:v,span:T.handle,trace:J,runQuery:((y,p)=>$("query",y,q,p)),secrets:E("secrets"),storage:E("storage"),vectors:E("vectors")},C={...i,...u,...m,auth:G,db:Z,env:r?.env,log:W,metrics:ee,now:v,span:T.handle,trace:J,runMutation:((y,p)=>$("mutation",y,C,p)),runQuery:((y,p)=>$("query",y,q,p)),scheduler:z,secrets:E("secrets"),storage:E("storage"),vectors:E("vectors"),workflows:E("workflows")};S??=C;const he={...C,db:ye},U={...i,...u,...m,auth:G,db:Z,env:r?.env,fetch:r?.fetch??E("fetch"),log:W,metrics:ee,now:v,span:T.handle,trace:J,runAction:((y,p)=>$("action",y,U,p)),runMutation:((y,p)=>M(()=>$("mutation",y,C,p)).then(l)),runQuery:((y,p)=>$("query",y,q,p)),scheduler:z,secrets:E("secrets"),services:qe(r?.services),storage:E("storage"),vectors:E("vectors"),workflows:E("workflows")};b??=U;const $=(y,p,L,Y)=>D(y,p,L,Y,!0);h??=(y,p,L,Y)=>y==="mutation"?M(()=>D("mutation",p,L,Y,!0)).then(l):(B(),$("action",p,L,Y));const me=((y,p)=>(B(),V(y)?D("query",y,q,p,!1):Promise.resolve(y(q)))),be=((y,p)=>{const L=V(y)?()=>D("mutation",y,C,p,!1):()=>y(C);return M(L).then(l)}),pe=((y,p)=>(B(),V(y)?D("action",y,U,p,!1):Promise.resolve(y(U)))),ge=Ke((...y)=>(B(),D(...y)),q,c);return{action:pe,close:t,mutation:be,notify:a,query:me,queues:k,run:y=>M(()=>y(he)).then(l),scheduler:N,subscribe:ge,topics:g,wideEvent:()=>T.recorded,withIdentity:y=>oe(y)}};return oe(null)};export{at as lunoraTest};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/testing",
3
- "version": "1.0.0-alpha.246",
3
+ "version": "1.0.0-alpha.248",
4
4
  "description": "Testing toolkit for Lunora: an in-memory harness for queries, mutations, and actions",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -54,8 +54,11 @@
54
54
  "@lunora/bindings": "1.0.0-alpha.103",
55
55
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
56
56
  "@lunora/mail": "1.0.0-alpha.103",
57
+ "@lunora/notify": "1.0.0-alpha.77",
58
+ "@lunora/queue": "1.0.0-alpha.97",
57
59
  "@lunora/scheduler": "1.0.0-alpha.116",
58
- "@lunora/server": "1.0.0-alpha.187"
60
+ "@lunora/server": "1.0.0-alpha.187",
61
+ "@visulima/notification": "1.2.0"
59
62
  },
60
63
  "peerDependencies": {
61
64
  "@playwright/test": "^1.61.1"
@@ -1 +0,0 @@
1
- import{LunoraError as U}from"@lunora/errors";import{withDeferredSchedules as se}from"@lunora/server";import{createInProcessRuntime as ie,resolveInProcessIdentity as ce,registeredFunctionKind as L,runRegisteredFunction as $}from"@lunora/server/in-process";import{evaluationAttributes as ae}from"./evaluationAttributes-CYLgTP1P.mjs";import{assertScheduleDelay as ue,MAX_RETRY_ATTEMPTS as de,RETRY_BASE_DELAY_MS as fe}from"@lunora/scheduler";import{DatabaseSync as le}from"node:sqlite";const X=e=>{throw new U("INTERNAL",`ctx.${e} is not available in the in-memory @lunora/testing harness (v1)`)},me=new Set(["$$typeof","asymmetricMatch","then","toJSON"]),ye=e=>new Proxy({...e},{get(r,n){if(!(me.has(n)&&!Object.hasOwn(r,n))){if(typeof n=="symbol"||Object.hasOwn(r,n)||n in Object.prototype)return Reflect.get(r,n);throw new U("INTERNAL",`ctx.services.${n} has no fake in the @lunora/testing harness — pass lunoraTest(schema, { services: { ${n}: … } })`)}}}),A=e=>new Proxy((...r)=>X(e),{apply:()=>X(e),get:()=>X(e)}),z={spanId:"0000000000000001",traceId:"00000000000000000000000000000001"},we={addEvent:()=>{},addLink:()=>{},recordEvaluation:()=>{},recordException:()=>{},setAttribute:()=>{},setAttributes:()=>{},spanContext:()=>z},be=()=>{const e={attributes:{},events:[],links:[]},r={addEvent:(n,a)=>{e.events.push({...a===void 0?{}:{attributes:{...a}},name:n})},addLink:n=>{e.links.push({spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{Object.assign(e.attributes,ae(n))},recordException:n=>{const a={"exception.message":n instanceof Error?n.message:String(n),"exception.type":n instanceof Error?n.constructor.name:"Error"};n instanceof Error&&n.stack!==void 0&&(a["exception.stacktrace"]=n.stack),r.addEvent("exception",a)},setAttribute:(n,a)=>{e.attributes[n]=a},setAttributes:n=>{Object.assign(e.attributes,n)},spanContext:()=>z};return{handle:r,recorded:e}},F=async(e,r)=>await r(F,we),G={count:()=>{},gauge:()=>{},record:()=>{}},q={debug:()=>{},error:()=>{},event:()=>{},fatal:()=>{},info:()=>{},log:()=>{},trace:()=>{},warn:()=>{},with:()=>q},B=e=>{let r="";for(let a=0;a<e.length;a+=32768)r+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(r)},he=e=>{const r=atob(e),n=new Uint8Array(r.length);for(let a=0;a<r.length;a+=1)n[a]=r.codePointAt(a)??0;return n},p="$lunora.wire$",Y=64,H=1024,J="__proto__",K={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},V={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},ge=e=>{if(e===null||typeof e!="object")return!1;const r=Object.getPrototypeOf(e);return r===null||r===Object.prototype},x=(e,r=0)=>{if(r>Y)throw new RangeError(`wire-codec: value nesting exceeds the ${Y}-level limit`);if(e===void 0)return[p,"undefined"];if(e===null)return null;const n=typeof e;if(n==="bigint"){const t=e.toString();if(t.length>H)throw new RangeError(`wire-codec: over-long bigint (max ${H} digits)`);return[p,"bigint",t]}if(n==="number"){const t=e;return Number.isNaN(t)?[p,"nan"]:t===1/0?[p,"inf"]:t===-1/0?[p,"-inf"]:t}if(n!=="object")return e;if(e instanceof Date)return[p,"date",x(e.getTime(),r+1)];if(e instanceof Error){const t=e,i=x(Object.fromEntries(Object.keys(t).map(f=>[f,t[f]])),r+1),u=[p,"error",String(t.name),String(t.message),i];return t.cause!==void 0&&u.push(x(t.cause,r+1)),u}if(e instanceof URL)return[p,"url",e.href];if(e instanceof Map)return[p,"map",[...e.entries()].map(([t,i])=>[x(t,r+1),x(i,r+1)])];if(e instanceof Set)return[p,"set",[...e].map(t=>x(t,r+1))];if(e instanceof ArrayBuffer)return[p,"bytes",B(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const t=e,i=t.constructor.name,u=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return i==="Uint8Array"?[p,"bytes",B(u)]:[p,"bytes",B(u),i]}if(Array.isArray(e)){const t=e.map(i=>x(i,r+1));return t.length>0&&t[0]===p?[p,"arr",t]:t}if(!ge(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 a=e,y={};for(const t of Object.keys(a)){const i=a[t];if(i===void 0)continue;const u=x(i,r+1);t===J?Object.defineProperty(y,t,{configurable:!0,enumerable:!0,value:u,writable:!0}):y[t]=u}return y},P=(e,r=0)=>{if(r>Y)throw new RangeError(`wire-codec: value nesting exceeds the ${Y}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===p)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>H||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${H} 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(i=>{if(!Array.isArray(i)||i.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[P(i[0],r+1),P(i[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],i=e[3];if(typeof t!="string"||typeof i!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const u=(Object.hasOwn(V,t)?V[t]:void 0)??Error,f=new u(i);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 g of Object.keys(l))g===J?Object.defineProperty(f,g,{configurable:!0,enumerable:!0,value:l[g],writable:!0}):f[g]=l[g];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 i=he(t);if(B(i)!==t)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const u=e[3]??"Uint8Array";if(u==="ArrayBuffer")return i.buffer.byteLength===i.byteLength?i.buffer:i.slice().buffer;const f=Object.hasOwn(K,u)?K[u]:void 0;return f?new f(i.slice().buffer):i}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 n=e,a={};for(const y of Object.keys(n)){const t=P(n[y],r+1);y===J?Object.defineProperty(a,y,{configurable:!0,enumerable:!0,value:t,writable:!0}):a[y]=t}return a},pe=(e,r,n,a,y)=>{let t=y,i=1;const u=new Map,f=[],l=(c,b,m={},s)=>{const o=x(m);JSON.stringify(o);const h=P(o),E=s??`fake-job-${String(i)}`;return i+=1,u.set(E,{args:h,enqueuedAt:t,functionPath:b,id:E,scheduledFor:c}),E},g=c=>typeof c=="string"?c:"__lunoraRef"in c?c.__lunoraRef:c.name??c.className??"",S={cancel:c=>{const b=u.has(c);return u.delete(c),Promise.resolve({cancelled:b})},get:c=>Promise.resolve(u.get(c)??null),list:()=>Promise.resolve([...u.values()]),runAfter:(c,b,m,s)=>{ue(c,"ctx.scheduler.runAfter");const o=l(t+c,g(b),m,s?.id);return Promise.resolve(o)},runAt:(c,b,m,s)=>{const o=l(c,g(b),m,s?.id);return Promise.resolve(o)}},T=async c=>{u.delete(c.id);const b=a(),m=c.functionPath===void 0?void 0:b.get(c.functionPath);if(m===void 0)throw new U("FUNCTION_NOT_FOUND",`unknown functionPath "${c.functionPath??"(workflow-targeted)"}"`,{status:404});if(m.kind!=="mutation"&&m.kind!=="action")throw new U("FUNCTION_NOT_FOUND",`functionPath "${c.functionPath??"(workflow-targeted)"}" is a ${m.kind} — only mutations and actions can be scheduled`,{status:404});const s=e(),o=m.kind==="action"?n():r();await s(m.kind,m,{...o,now:t},c.args)},N=async c=>{const b=[...u.values()].filter(o=>o.scheduledFor<=c).toSorted((o,h)=>o.scheduledFor-h.scheduledFor),m=[];let s=0;for(const o of b)if(u.has(o.id)){s+=1;try{await T(o)}catch(h){const E=(o.attempts??0)+1;if(E>de){const v={args:o.args,error:h,functionPath:o.functionPath??"",id:o.id};m.push(v),f.push(v)}else{const v=fe*2**(E-1);u.set(o.id,{...o,attempts:E,scheduledFor:t+v})}}}return{executed:s,failed:m}},R=async(c,b)=>{const{executed:m,failed:s}=await N(c);if(s.length>0&&(b?.throwOnError??!0)){const[o]=s;throw s.length===1&&o!==void 0?o.error:new AggregateError(s.map(h=>h.error),`${String(s.length)} scheduled jobs failed: ${s.map(h=>h.functionPath).join(", ")}`)}return m};return{controls:{advance:(c,b)=>(t+=c,R(t,b)),failures:()=>[...f],list:()=>[...u.values()],runPending:c=>R(Number.POSITIVE_INFINITY,c)},scheduler:S}},ve=()=>{const e=new le(":memory:"),r=a=>({one(){if(a.length!==1)throw new U("INTERNAL",`expected exactly one row, received ${String(a.length)}`);const[y]=a;return y},[Symbol.iterator](){return a[Symbol.iterator]()},toArray(){return a}});return{close:()=>{e.close()},sql:{exec:(a,...y)=>{const i=e.prepare(a).all(...y);return r(i)}}}},Ee=(e,r,n)=>(y,t)=>{let i=!1;const u=[];let f,l,g=0,S=0;const T=()=>L(y)?e("query",y,r,t,!1):Promise.resolve(y(r)),N=(s,o)=>{if(s<S)return;S=s;const h={done:!1,value:o};if(u.length===0)f=h,l=void 0;else{f=void 0,l=void 0;for(const E of u.splice(0))E.resolve(h)}},R=(s,o)=>{if(!(s<S))if(S=s,u.length===0)l={error:o},f=void 0;else{f=void 0,l=void 0;for(const h of u.splice(0))h.reject(o)}},k=s=>o=>{N(s,o)},c=s=>o=>{R(s,o)},b=()=>{if(i)return;g+=1;const s=g;T().then(k(s)).catch(c(s))};n.add(b);const m={[Symbol.asyncIterator](){return m},next:()=>{if(i)return Promise.resolve({done:!0,value:void 0});if(S===g){if(l!==void 0){const{error:s}=l;return l=void 0,Promise.reject(s)}if(f!==void 0){const s=f;return f=void 0,Promise.resolve(s)}}return S<g?new Promise((s,o)=>{u.push({reject:o,resolve:s})}):T().then(s=>{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:s}})},return:()=>{i=!0,n.delete(b);for(const s of u.splice(0))s.resolve({done:!0,value:void 0});return Promise.resolve({done:!0,value:void 0})}};return T().then(k(0)).catch(c(0)),m},ke=(e,r)=>{const{close:n,sql:a}=ve();let y=!1;const t=()=>{y||(y=!0,n())},i=new Map(Object.entries(r?.functions??{}).map(([v,I])=>[v,I])),u=new Set,f=()=>{for(const v of u)v()},l=v=>(f(),v);let g,S,T;const N=r?.now??Date.now(),R=be(),k=(v,I)=>{if(v===void 0)throw new U("INTERNAL",`[fake-scheduler] ${I} not yet available — scheduler.advance called before harness construction completed`);return v},{controls:c,scheduler:b}=pe(()=>k(g,"dispatch"),()=>k(S,"mutationContext"),()=>k(T,"actionContext"),()=>i,N),m=se(b),{createWriters:s,resetHeadroom:o,runInTransaction:h}=ie(e,{enforceRls:r?.enforceRls,scheduler:m,sql:a}),E=v=>{const I=ce(v),Q={getIdentity:()=>Promise.resolve(I.claims),userId:I.userId},{database:W,rawDatabase:Z}=s(I),_={auth:Q,db:W,env:r?.env,log:q,metrics:G,now:N,span:R.handle,trace:F,runQuery:((d,w)=>O("query",d,_,w)),secrets:A("secrets"),storage:A("storage"),vectors:A("vectors")},j={auth:Q,db:W,env:r?.env,log:q,metrics:G,now:N,span:R.handle,trace:F,runMutation:((d,w)=>O("mutation",d,j,w)),runQuery:((d,w)=>O("query",d,_,w)),scheduler:m,secrets:A("secrets"),storage:A("storage"),vectors:A("vectors"),workflows:A("workflows")};S??=j;const ee={...j,db:Z},D={auth:Q,db:W,env:r?.env,fetch:r?.fetch??A("fetch"),log:q,metrics:G,now:N,span:R.handle,trace:F,runAction:((d,w)=>O("action",d,D,w)),runMutation:((d,w)=>h(()=>O("mutation",d,j,w)).then(l)),runQuery:((d,w)=>O("query",d,_,w)),scheduler:m,secrets:A("secrets"),services:ye(r?.services),storage:A("storage"),vectors:A("vectors"),workflows:A("workflows")};T??=D;const O=(d,w,C,M)=>$(d,w,C,M,!0);g??=(d,w,C,M)=>d==="mutation"?h(()=>$("mutation",w,C,M,!0)).then(l):(o(),O("action",w,C,M));const te=((d,w)=>(o(),L(d)?$("query",d,_,w,!1):Promise.resolve(d(_)))),re=((d,w)=>{const C=L(d)?()=>$("mutation",d,j,w,!1):()=>d(j);return h(C).then(l)}),ne=((d,w)=>(o(),L(d)?$("action",d,D,w,!1):Promise.resolve(d(D)))),oe=Ee((...d)=>(o(),$(...d)),_,u);return{action:ne,close:t,mutation:re,query:te,run:d=>h(()=>d(ee)).then(l),scheduler:c,subscribe:oe,wideEvent:()=>R.recorded,withIdentity:d=>E(d)}};return E(null)};export{ke as lunoraTest};