channelstack 0.0.0-stage → 0.1.1

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/bin/channelstack.mjs +31 -0
  4. package/dist/integrations/checks/checks.test.d.ts +1 -0
  5. package/dist/integrations/checks/checks.test.js +31 -0
  6. package/dist/integrations/checks/index.d.ts +69 -0
  7. package/dist/integrations/checks/index.js +578 -0
  8. package/dist/integrations/matchers-core/index.d.ts +138 -0
  9. package/dist/integrations/matchers-core/index.js +458 -0
  10. package/dist/integrations/matchers-core/matchers.test.d.ts +1 -0
  11. package/dist/integrations/matchers-core/matchers.test.js +159 -0
  12. package/dist/integrations/vitest/global-setup.d.ts +3 -0
  13. package/dist/integrations/vitest/global-setup.js +19 -0
  14. package/dist/integrations/vitest/index.d.ts +80 -0
  15. package/dist/integrations/vitest/index.js +42 -0
  16. package/dist/integrations/vitest/plugin.test.d.ts +1 -0
  17. package/dist/integrations/vitest/plugin.test.js +19 -0
  18. package/dist/integrations/vitest/refused.d.ts +22 -0
  19. package/dist/integrations/vitest/refused.js +49 -0
  20. package/dist/integrations/vitest/setup.d.ts +1 -0
  21. package/dist/integrations/vitest/setup.js +109 -0
  22. package/dist/sdks/typescript/client.d.ts +13 -0
  23. package/dist/sdks/typescript/client.js +11 -0
  24. package/dist/sdks/typescript/generated/channels.d.ts +24 -0
  25. package/dist/sdks/typescript/generated/channels.js +2 -0
  26. package/dist/sdks/typescript/generated/index.d.ts +2747 -0
  27. package/dist/sdks/typescript/generated/index.js +3039 -0
  28. package/dist/sdks/typescript/runtime/client.d.ts +47 -0
  29. package/dist/sdks/typescript/runtime/client.js +69 -0
  30. package/dist/sdks/typescript/runtime/credentials.d.ts +7 -0
  31. package/dist/sdks/typescript/runtime/credentials.js +20 -0
  32. package/dist/sdks/typescript/runtime/duration.d.ts +4 -0
  33. package/dist/sdks/typescript/runtime/duration.js +13 -0
  34. package/dist/sdks/typescript/runtime/files.d.ts +32 -0
  35. package/dist/sdks/typescript/runtime/files.js +45 -0
  36. package/dist/sdks/typescript/runtime/launcher.d.ts +24 -0
  37. package/dist/sdks/typescript/runtime/launcher.js +121 -0
  38. package/dist/sdks/typescript/runtime/transport.d.ts +43 -0
  39. package/dist/sdks/typescript/runtime/transport.js +95 -0
  40. package/dist/sdks/typescript/runtime/wait.d.ts +82 -0
  41. package/dist/sdks/typescript/runtime/wait.js +136 -0
  42. package/dist/sdks/typescript/types.d.ts +72 -0
  43. package/dist/sdks/typescript/types.js +1 -0
  44. package/package.json +80 -4
@@ -0,0 +1,159 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { ChannelstackError, QUIET } from "../../sdks/typescript/client.js";
3
+ import { matchers } from "./index.js";
4
+ const state = { isNot: false, timeout: "100ms", quietFor: "10ms" };
5
+ const negated = { ...state, isNot: true };
6
+ const quiet = { [QUIET]: async () => ({ busy: false, quietForMs: 60_000, open: [] }) };
7
+ const ana = { id: "U0ANA", name: "Ana", kind: "user" };
8
+ const agent = { id: "A0APP", name: "my-agent", kind: "app" };
9
+ const entry = (id, author, text, extra = {}) => ({
10
+ id,
11
+ author,
12
+ text,
13
+ controls: [],
14
+ ...extra,
15
+ });
16
+ /** A conversation: no `replies()`, only what its transcript shows. `seenAs` records who it was read as. */
17
+ const conversation = (entries, forViewer = []) => {
18
+ const seenAs = [];
19
+ return {
20
+ ...quiet,
21
+ seenAs,
22
+ transcript: async (options = {}) => {
23
+ seenAs.push(options.as);
24
+ return { entries: options.as === undefined ? entries : [...entries, ...forViewer] };
25
+ },
26
+ };
27
+ };
28
+ /** A thread: its replies, its root's `ts`, and a transcript. */
29
+ const thread = (root, replies) => ({
30
+ ...conversation([root, ...replies]),
31
+ ts: root.id,
32
+ replies: async () => replies,
33
+ });
34
+ const deliveryWith = (attempt) => ({
35
+ id: "Ev0TEST",
36
+ refresh: async () => ({ attempts: [{ forgedSignature: false, ...attempt }] }),
37
+ });
38
+ describe("toBeAccepted", () => {
39
+ test("with `within`, an acknowledgement that came too late fails, and the message says how long it took", async () => {
40
+ const slow = deliveryWith({ status: "acknowledged", responseStatus: 200, durationMs: 2900 });
41
+ expect((await matchers.toBeAccepted(state, slow)).pass).toBe(true);
42
+ expect((await matchers.toBeAccepted(state, slow, { within: "3s" })).pass).toBe(true);
43
+ const late = await matchers.toBeAccepted(state, slow, { within: "1s" });
44
+ expect(late.pass).toBe(false);
45
+ expect(late.message()).toBe("Expected delivery Ev0TEST to be accepted within 1000ms, its first attempt is acknowledged (HTTP 200) after 2900ms");
46
+ });
47
+ test("an attempt the agent didn't acknowledge fails with or without `within`", async () => {
48
+ const timedOut = deliveryWith({ status: "timed_out", durationMs: 3000 });
49
+ const result = await matchers.toBeAccepted(state, timedOut);
50
+ expect(result.pass).toBe(false);
51
+ expect(result.message()).toBe("Expected delivery Ev0TEST to be accepted, its first attempt is timed_out after 3000ms");
52
+ });
53
+ });
54
+ describe("replies", () => {
55
+ const question = entry("1.1", ana, "status?");
56
+ test("toHaveReplyFrom passes on a reply, and says what the thread has when there is none", async () => {
57
+ const answered = thread(question, [entry("1.2", agent, "all green")]);
58
+ expect((await matchers.toHaveReplyFrom(state, answered, "my-agent")).pass).toBe(true);
59
+ const silent = await matchers.toHaveReplyFrom(state, thread(question, [entry("1.2", ana, "hello?")]), "my-agent");
60
+ expect(silent.pass).toBe(false);
61
+ expect(silent.message()).toBe("Expected a reply from my-agent. The thread has:\n Ana: hello?");
62
+ const unwanted = await matchers.toHaveReplyFrom(negated, answered, "my-agent");
63
+ expect(unwanted.pass).toBe(true);
64
+ expect(unwanted.message()).toBe("Expected no reply from my-agent. The thread has:\n my-agent: all green");
65
+ });
66
+ test("toHaveRepliesFrom counts exactly", async () => {
67
+ const twice = thread(question, [entry("1.2", agent, "one"), entry("1.3", agent, "two")]);
68
+ expect((await matchers.toHaveRepliesFrom(state, twice, "my-agent", { count: 2 })).pass).toBe(true);
69
+ const result = await matchers.toHaveRepliesFrom(state, twice, "my-agent", { count: 1 });
70
+ expect(result.pass).toBe(false);
71
+ expect(result.message()).toContain("Expected exactly 1 reply from my-agent, found 2");
72
+ });
73
+ test("toHaveStreamingReplyFrom reads a thread's messages and a conversation's transcript alike", async () => {
74
+ const streaming = { ...entry("1.2", agent, "Thinking"), stream: { state: "open" } };
75
+ expect((await matchers.toHaveStreamingReplyFrom(state, thread(question, [streaming]), "my-agent")).pass).toBe(true);
76
+ const dm = conversation([question, entry("1.2", agent, "Thinking", { streaming: "open" })]);
77
+ expect((await matchers.toHaveStreamingReplyFrom(state, dm, "my-agent")).pass).toBe(true);
78
+ const done = conversation([question, entry("1.2", agent, "Done", { streaming: "completed" })]);
79
+ expect((await matchers.toHaveStreamingReplyFrom(state, done, "my-agent")).pass).toBe(false);
80
+ });
81
+ });
82
+ describe("toContainText", () => {
83
+ test("`as` reads the transcript as that person, handed over as the handle", async () => {
84
+ const refusal = entry("1.2", agent, "You may not approve");
85
+ const subject = conversation([entry("1.1", ana, "approve it")], [refusal]);
86
+ expect((await matchers.toContainText(state, subject, "may not approve")).pass).toBe(false);
87
+ expect((await matchers.toContainText(state, subject, "may not approve", { as: ana })).pass).toBe(true);
88
+ expect(subject.seenAs.at(-1)).toBe(ana);
89
+ });
90
+ test("a pattern with the g flag counts every entry", async () => {
91
+ const subject = conversation([entry("1.1", agent, "done"), entry("1.2", agent, "done")]);
92
+ expect((await matchers.toContainText(state, subject, /done/g, { count: 2 })).pass).toBe(true);
93
+ });
94
+ });
95
+ describe("toHaveButton", () => {
96
+ const ask = entry("1.2", agent, "Deploy?", { controls: ["Approve", "Deny"] });
97
+ const subject = thread(entry("1.1", ana, "deploy"), [ask]);
98
+ test("on a thread it looks at the agent's latest message, on a message at that message", async () => {
99
+ expect((await matchers.toHaveButton(state, subject, "Approve")).pass).toBe(true);
100
+ expect((await matchers.toHaveButton(negated, subject, "Approve")).pass).toBe(true);
101
+ const message = { ...quiet, ts: "1.2", thread: subject };
102
+ expect((await matchers.toHaveButton(state, message, /^Deny$/)).pass).toBe(true);
103
+ const root = { ...quiet, ts: "1.1", thread: subject };
104
+ const none = await matchers.toHaveButton(state, root, "Approve");
105
+ expect([none.pass, none.message()]).toEqual([false, 'Expected a button matching "Approve". Buttons there: none']);
106
+ });
107
+ });
108
+ describe("toHaveReceivedCall", () => {
109
+ test("matches by name or pattern, and counts with `times`", async () => {
110
+ const fixture = {
111
+ ...quiet,
112
+ calls: async () => [{ operation: "chat.postMessage" }, { operation: "chat.postMessage" }],
113
+ };
114
+ expect((await matchers.toHaveReceivedCall(state, fixture, "chat.postMessage", { times: 2 })).pass).toBe(true);
115
+ expect((await matchers.toHaveReceivedCall(state, fixture, /^chat\./g, { times: 2 })).pass).toBe(true);
116
+ const missing = await matchers.toHaveReceivedCall(state, fixture, "reactions.add");
117
+ expect(missing.pass).toBe(false);
118
+ expect(missing.message()).toContain('Expected the agent to call "reactions.add", found 0');
119
+ });
120
+ });
121
+ describe("toHaveOpenedModal", () => {
122
+ test("looks at the modals the agent opened for a person, by title when one is given", async () => {
123
+ const person = { ...quiet, modals: async () => [{ title: "File an incident" }] };
124
+ expect((await matchers.toHaveOpenedModal(state, person)).pass).toBe(true);
125
+ expect((await matchers.toHaveOpenedModal(state, person, /incident/i)).pass).toBe(true);
126
+ const other = await matchers.toHaveOpenedModal(state, person, "Deploy");
127
+ expect([other.pass, other.message()]).toEqual([
128
+ false,
129
+ 'Expected a modal titled "Deploy" to have been opened. Opened: "File an incident"',
130
+ ]);
131
+ });
132
+ });
133
+ describe("a failure's message", () => {
134
+ test("leaves out what is still open when the server can't tell (live), and still fails", async () => {
135
+ // Live, without proxy mode, the server refuses to say when the agent is done.
136
+ const refused = async () => {
137
+ throw new ChannelstackError("action_requires", 422, "Session.quiet live needs proxy mode");
138
+ };
139
+ const issue = { [QUIET]: refused, comments: async () => [] };
140
+ const result = await matchers.toHaveCommentFrom(state, issue, agent);
141
+ expect(result.pass).toBe(false);
142
+ expect(result.message()).not.toContain("Still open");
143
+ });
144
+ });
145
+ describe("comments", () => {
146
+ test("on a Notion page, the comment matchers say to pass a discussion: a page has no comments of its own", async () => {
147
+ const page = { ...quiet, title: "Spec", discussions: async () => [], blocks: async () => [] };
148
+ const wanted = "needs a Notion discussion, not a page: a page's comments are in its discussions.";
149
+ const positive = matchers.toHaveCommentFrom(state, page, agent);
150
+ await expect(positive).rejects.toThrow(`toHaveCommentFrom ${wanted}`);
151
+ await expect(positive).rejects.not.toBeInstanceOf(TypeError);
152
+ await expect(matchers.toHaveCommentsFrom(state, page, agent, { count: 1 })).rejects.toThrow(`toHaveCommentsFrom ${wanted}`);
153
+ });
154
+ test("on a discussion, they read its comments", async () => {
155
+ const discussion = { ...quiet, comments: async () => [{ author: agent, text: "Summary: all green" }] };
156
+ expect((await matchers.toHaveCommentFrom(state, discussion, agent, { text: /green/ })).pass).toBe(true);
157
+ expect((await matchers.toHaveCommentsFrom(state, discussion, agent, { count: 1 })).pass).toBe(true);
158
+ });
159
+ });
@@ -0,0 +1,3 @@
1
+ import type { TestProject } from "vitest/node";
2
+ /** Runs once per test run: find or start the server, and tell the test workers where it is. */
3
+ export default function setup(project: TestProject): Promise<() => Promise<void>>;
@@ -0,0 +1,19 @@
1
+ import { launch } from "../../sdks/typescript/runtime/launcher.js";
2
+ import { waitDefaults } from "../../sdks/typescript/runtime/wait.js";
3
+ import { OPTIONS_ENV } from "./index.js";
4
+ /** Runs once per test run: find or start the server, and tell the test workers where it is. */
5
+ export default async function setup(project) {
6
+ const options = JSON.parse(project.config.env[OPTIONS_ENV] ?? "{}");
7
+ const server = await launch({
8
+ ...(options.mode ? { mode: options.mode } : {}),
9
+ ...(options.server ? { server: options.server } : {}),
10
+ });
11
+ project.provide("channelstack", {
12
+ url: server.url,
13
+ token: server.token,
14
+ // Unset, they are the wait module's own defaults: the one place they live.
15
+ timeout: options.timeout ?? waitDefaults().timeout,
16
+ quietFor: options.quietFor ?? waitDefaults().quietFor,
17
+ });
18
+ return () => server.stop();
19
+ }
@@ -0,0 +1,80 @@
1
+ import type { ChannelFixtures, Duration } from "../../sdks/typescript/client.ts";
2
+ import type { MatcherName, matchers } from "../matchers-core/index.ts";
3
+ export interface ChannelstackIntegrationOptions {
4
+ /** Attach to this server instead of the one in `server.json`. Also `CHANNELSTACK_URL`. */
5
+ server?: string;
6
+ /**
7
+ * `auto` (default): attach if a server is running, otherwise start one for the run.
8
+ * `attach`: fail if none is running. `start`: always start a private one.
9
+ */
10
+ mode?: "auto" | "attach" | "start";
11
+ /**
12
+ * Default timeout for matchers and every SDK wait (`waitFor…`, `latest…`, `settled`). Default "10s".
13
+ * A project without its own `testTimeout` gets one above it: 30s, or three times this.
14
+ */
15
+ timeout?: Duration;
16
+ /** Default quiet window for negative and exact-count matchers and `latest…` reads. Default "750ms". */
17
+ quietFor?: Duration;
18
+ }
19
+ /** The `channelstack` fixture: the server itself, across all channels. */
20
+ export interface ChannelstackFixture {
21
+ /** Control API and UI base, e.g. `https://channelstack.localhost`. */
22
+ readonly url: string;
23
+ /** Env vars for the agent: tokens, secrets and API URLs (what `channelstack env` prints). */
24
+ env(): Promise<Record<string, string>>;
25
+ /** Resolve when the agent is quiet in this test's session. */
26
+ quiet(options?: {
27
+ quietFor?: Duration;
28
+ timeout?: Duration;
29
+ }): Promise<void>;
30
+ /** Drop all state on every channel. Avoid in parallel suites. */
31
+ reset(): Promise<void>;
32
+ }
33
+ /** Each matcher's arguments after the subject, as `expect(subject).<matcher>(...)` takes them. */
34
+ type MatcherArguments<Name extends MatcherName> = (typeof matchers)[Name] extends (state: never, subject: never, ...rest: infer Rest) => unknown ? Rest : never;
35
+ type ChannelstackMatchers = {
36
+ [Name in MatcherName]: (...args: MatcherArguments<Name>) => Promise<void>;
37
+ };
38
+ declare module "vitest" {
39
+ interface TestContext extends ChannelFixtures {
40
+ channelstack: ChannelstackFixture;
41
+ }
42
+ interface Matchers<R extends void | Promise<void> = void | Promise<void>, T = unknown> extends ChannelstackMatchers {
43
+ }
44
+ interface ProvidedContext {
45
+ /** Where the test workers find the server the global setup attached to or started. */
46
+ channelstack: {
47
+ url: string;
48
+ token: string;
49
+ timeout: Duration;
50
+ quietFor: Duration;
51
+ };
52
+ }
53
+ }
54
+ /** The environment variable the plugin hands its options to the global setup in. */
55
+ export declare const OPTIONS_ENV = "CHANNELSTACK_VITEST_OPTIONS";
56
+ /**
57
+ * The test timeout the plugin gives a project that sets none: comfortably above a check's own wait,
58
+ * so a failing check reports its own message instead of Vitest's "Test timed out in 5000ms". A
59
+ * check waits at most `timeout` (a negative one waits for quiet within it, then reads once), so
60
+ * this is 30s, or three times the `timeout` if that's longer.
61
+ */
62
+ export declare function defaultTestTimeout(options: Pick<ChannelstackIntegrationOptions, "timeout">): number;
63
+ /** The Vitest plugin. */
64
+ export default function channelstack(options?: ChannelstackIntegrationOptions): {
65
+ name: string;
66
+ config(config: {
67
+ test?: {
68
+ setupFiles?: string | string[];
69
+ testTimeout?: number;
70
+ };
71
+ }): {
72
+ test: {
73
+ globalSetup: string[];
74
+ env: {
75
+ CHANNELSTACK_VITEST_OPTIONS: string;
76
+ };
77
+ };
78
+ };
79
+ };
80
+ export {};
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `channelstack/vitest`: the Vitest plugin.
3
+ *
4
+ * // vitest.config.ts
5
+ * import channelstack from "channelstack/vitest";
6
+ * export default defineConfig({ plugins: [channelstack()] });
7
+ *
8
+ * It adds a global setup (attach to a running server, or start one), a setup file that gives
9
+ * every test its own session and fixtures and registers the matchers, and the types below.
10
+ */
11
+ import { extname } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { parseDuration } from "../../sdks/typescript/runtime/duration.js";
14
+ import { waitDefaults } from "../../sdks/typescript/runtime/wait.js";
15
+ /** The environment variable the plugin hands its options to the global setup in. */
16
+ export const OPTIONS_ENV = "CHANNELSTACK_VITEST_OPTIONS";
17
+ const sibling = (name) => fileURLToPath(new URL(`./${name}${extname(import.meta.url)}`, import.meta.url));
18
+ /**
19
+ * The test timeout the plugin gives a project that sets none: comfortably above a check's own wait,
20
+ * so a failing check reports its own message instead of Vitest's "Test timed out in 5000ms". A
21
+ * check waits at most `timeout` (a negative one waits for quiet within it, then reads once), so
22
+ * this is 30s, or three times the `timeout` if that's longer.
23
+ */
24
+ export function defaultTestTimeout(options) {
25
+ return Math.max(30_000, 3 * parseDuration(options.timeout ?? waitDefaults().timeout));
26
+ }
27
+ /** The Vitest plugin. */
28
+ export default function channelstack(options = {}) {
29
+ return {
30
+ name: "channelstack",
31
+ config(config) {
32
+ // The plugin's setup comes before the project's own setup files: its `beforeEach` (the
33
+ // fixtures) runs first and its `afterEach` (closing the session) last, so a project's own
34
+ // hooks can still use the fixtures.
35
+ config.test ??= {};
36
+ config.test.setupFiles = [sibling("setup"), ...[config.test.setupFiles ?? []].flat()];
37
+ // A project's own `testTimeout` always wins.
38
+ config.test.testTimeout ??= defaultTestTimeout(options);
39
+ return { test: { globalSetup: [sibling("global-setup")], env: { [OPTIONS_ENV]: JSON.stringify(options) } } };
40
+ },
41
+ };
42
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import channelstack, { defaultTestTimeout } from "./index.js";
3
+ /** What the plugin's `config` hook leaves in a project's `test` settings. */
4
+ const configured = (options, test = {}) => {
5
+ const config = { test: { ...test } };
6
+ channelstack(options).config(config);
7
+ return config.test;
8
+ };
9
+ describe("the test timeout", () => {
10
+ test("a project that sets none gets one well above a check's own wait, not Vitest's 5s", () => {
11
+ expect(configured({}).testTimeout).toBe(30_000);
12
+ expect(defaultTestTimeout({})).toBeGreaterThan(10_000 + 750);
13
+ // A longer timeout gets three times as long.
14
+ expect(configured({ timeout: "20s", quietFor: "1s" }).testTimeout).toBe(60_000);
15
+ });
16
+ test("a project's own testTimeout always wins", () => {
17
+ expect(configured({ timeout: "20s" }, { testTimeout: 5_000 }).testTimeout).toBe(5_000);
18
+ });
19
+ });
@@ -0,0 +1,22 @@
1
+ import { type Session } from "../../sdks/typescript/client.ts";
2
+ /** The refusals live mode skips a test for (setup.ts): what it can't do, or needs a piece this run lacks. */
3
+ export declare const SKIPS_LIVE: ReadonlySet<string>;
4
+ /** A test context with the test's session, as the integration's own fixture holds it. */
5
+ export type WithSession = {
6
+ channelstackSession?: Session | undefined;
7
+ };
8
+ /** Sessions whose refused requests don't skip their test right now: the caller handles the refusal. */
9
+ export declare const unskipped: Set<string>;
10
+ /**
11
+ * Run a read that may be refused live, without skipping the test for it: for channelstack's own
12
+ * per-test checks of what the fake sends (its calls, its webhooks), which a live channel has none
13
+ * of. Resolves with nothing when the read is refused live.
14
+ */
15
+ export declare function withoutLiveSkips<T>(context: WithSession, read: () => Promise<T>): Promise<T | undefined>;
16
+ /** A stand-in for a channel's fixture that was refused live: any use of it throws `refuse()`. */
17
+ export declare function refusedFixture(refuse: () => never): object;
18
+ /**
19
+ * Was this channel refused live (its live backend isn't built, or its credentials are set in part)?
20
+ * For channelstack's own per-test checks of what the fake sends, which a refused channel has none of.
21
+ */
22
+ export declare function refusedLive(fixture: unknown): boolean;
@@ -0,0 +1,49 @@
1
+ import { ChannelstackError } from "../../sdks/typescript/client.js";
2
+ /** The refusals live mode skips a test for (setup.ts): what it can't do, or needs a piece this run lacks. */
3
+ export const SKIPS_LIVE = new Set(["unsupported_in_live", "action_requires"]);
4
+ /** Sessions whose refused requests don't skip their test right now: the caller handles the refusal. */
5
+ export const unskipped = new Set();
6
+ /**
7
+ * Run a read that may be refused live, without skipping the test for it: for channelstack's own
8
+ * per-test checks of what the fake sends (its calls, its webhooks), which a live channel has none
9
+ * of. Resolves with nothing when the read is refused live.
10
+ */
11
+ export async function withoutLiveSkips(context, read) {
12
+ const session = context.channelstackSession;
13
+ if (session)
14
+ unskipped.add(session.sessionId);
15
+ try {
16
+ return await read();
17
+ }
18
+ catch (error) {
19
+ if (error instanceof ChannelstackError && SKIPS_LIVE.has(error.code))
20
+ return undefined;
21
+ throw error;
22
+ }
23
+ finally {
24
+ if (session)
25
+ unskipped.delete(session.sessionId);
26
+ }
27
+ }
28
+ /** What a channel's fixture answers when it was refused live: the stand-in says so without throwing. */
29
+ const REFUSED = Symbol.for("channelstack.refusedLive");
30
+ /** A stand-in for a channel's fixture that was refused live: any use of it throws `refuse()`. */
31
+ export function refusedFixture(refuse) {
32
+ return new Proxy({}, {
33
+ get: (_, property) => {
34
+ if (property === REFUSED)
35
+ return true;
36
+ // `then` is looked up when a value is awaited: the stand-in isn't a promise.
37
+ if (property === "then")
38
+ return undefined;
39
+ return refuse();
40
+ },
41
+ });
42
+ }
43
+ /**
44
+ * Was this channel refused live (its live backend isn't built, or its credentials are set in part)?
45
+ * For channelstack's own per-test checks of what the fake sends, which a refused channel has none of.
46
+ */
47
+ export function refusedLive(fixture) {
48
+ return typeof fixture === "object" && fixture !== null && fixture[REFUSED] === true;
49
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,109 @@
1
+ import { dirname } from "node:path";
2
+ import { expect, inject, test } from "vitest";
3
+ import { CHANNEL_NAMES, ChannelstackError, connect, onRefusal, setFilesRoot, setWaitDefaults, untilQuiet, } from "../../sdks/typescript/client.js";
4
+ import { matchers } from "../matchers-core/index.js";
5
+ import { refusedFixture, SKIPS_LIVE, unskipped } from "./refused.js";
6
+ /** Runs in every test worker: one client per worker, one session per test, and the matchers. */
7
+ const server = inject("channelstack");
8
+ // The plugin's `timeout` and `quietFor` are every SDK wait's defaults, not only the matchers':
9
+ // `thread.waitForReply()`, `latestReply()`, `delivery.settled()`, …
10
+ setWaitDefaults({ timeout: server.timeout, quietFor: server.quietFor });
11
+ let client;
12
+ const connected = () => {
13
+ // The worker attaches to the server the global setup found; it never starts one itself. The
14
+ // token is handed over directly, so nothing a test spawns inherits it.
15
+ client ??= connect({ mode: "attach", server: server.url, token: server.token });
16
+ return client;
17
+ };
18
+ /**
19
+ * What live mode can't do skips the test, with the reason, instead of failing it: a fake-only
20
+ * feature (`unsupported_in_live`), or one that needs a piece this run doesn't have (`action_requires`:
21
+ * the browser actor, proxy mode). The fake run never sees these refusals, so a
22
+ * test still runs in full on every PR (reality-matrix.md, "What this means for test authors").
23
+ */
24
+ /** Each running test's `skip`, by its session: the refused request names the session, so concurrent tests skip only themselves. */
25
+ const skips = new Map();
26
+ onRefusal((error, path) => {
27
+ const session = /^\/sessions\/([^/]+)/.exec(path)?.[1];
28
+ if (session === undefined || unskipped.has(session))
29
+ return;
30
+ const skip = skips.get(session);
31
+ if (skip && SKIPS_LIVE.has(error.code))
32
+ skip(`live: ${error.message}`);
33
+ });
34
+ /**
35
+ * A channel's fixture. Every test gets all four, so a channel that is refused live (its live
36
+ * backend isn't built, its credentials are set in part) must not touch the tests of the others:
37
+ * the refusal is kept, and comes when the test first uses that channel. It skips the test or fails
38
+ * it, as the refusal would have.
39
+ */
40
+ function channelFixture(open) {
41
+ return async ({ channelstackSession: session, skip }, use) => {
42
+ let fixture;
43
+ // A refusal while setting up is kept for the test's first use of that channel.
44
+ unskipped.add(session.sessionId);
45
+ try {
46
+ fixture = await open(session);
47
+ }
48
+ catch (error) {
49
+ const refuse = () => {
50
+ if (error instanceof ChannelstackError && SKIPS_LIVE.has(error.code))
51
+ skip(`live: ${error.message}`);
52
+ throw error;
53
+ };
54
+ fixture = refusedFixture(refuse);
55
+ }
56
+ finally {
57
+ unskipped.delete(session.sessionId);
58
+ }
59
+ await use(fixture);
60
+ };
61
+ }
62
+ const auto = { auto: true };
63
+ test.override({
64
+ channelstackSession: [
65
+ async ({ task, skip }, use) => {
66
+ const session = await (await connected()).openSession();
67
+ // A fixture path in a test (`files: "./fixtures/web"`) starts from the test file, like an import.
68
+ setFilesRoot(dirname(task.file.filepath));
69
+ skips.set(session.sessionId, skip);
70
+ try {
71
+ await use(session);
72
+ }
73
+ finally {
74
+ skips.delete(session.sessionId);
75
+ // Closing the session removes everything the test created. Disposing never fails a test.
76
+ await session[Symbol.asyncDispose]();
77
+ }
78
+ },
79
+ auto,
80
+ ],
81
+ channelstack: [
82
+ async ({ channelstackSession: session }, use) => {
83
+ const channelstack = await connected();
84
+ await use({
85
+ url: server.url,
86
+ env: () => channelstack.env(),
87
+ quiet: (options = {}) => untilQuiet(() => session.quiet(), options),
88
+ reset: () => channelstack.reset(),
89
+ });
90
+ },
91
+ auto,
92
+ ],
93
+ // One fixture per channel, by its name: `slack` opens `session.slack()`.
94
+ ...Object.fromEntries(CHANNEL_NAMES.map((name) => [name, [channelFixture((session) => session[name]()), auto]])),
95
+ });
96
+ expect.extend(
97
+ // Vitest types a matcher's `this` as its own state; the adapter only needs `isNot` from it.
98
+ Object.fromEntries(Object.keys(matchers).map((name) => [
99
+ name,
100
+ function (subject, ...args) {
101
+ const state = {
102
+ isNot: this.isNot === true,
103
+ timeout: server.timeout,
104
+ quietFor: server.quietFor,
105
+ ...(this.equals ? { equals: this.equals } : {}),
106
+ };
107
+ return matchers[name](state, subject, ...args);
108
+ },
109
+ ])));
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `channelstack` and `channelstack/client`: the generated client the test integrations are built
3
+ * on, and its types (`import type { SlackUser } from "channelstack"`). The public contract is `api/*.d.ts`.
4
+ */
5
+ export { CHANNEL_NAMES, type ChannelFixtures } from "./generated/channels.ts";
6
+ export * from "./generated/index.ts";
7
+ export { type Duration, parseDuration } from "./runtime/duration.ts";
8
+ export { type FileInput, setFilesRoot } from "./runtime/files.ts";
9
+ export { type InSession, QUIET } from "./runtime/client.ts";
10
+ export type { LaunchOptions } from "./runtime/launcher.ts";
11
+ export { ChannelstackError, onRefusal, unreportedRefusals } from "./runtime/transport.ts";
12
+ export type * from "./types.ts";
13
+ export { fromMatches, type QuietOptions, type QuietState, setWaitDefaults, textMatches, untilQuiet, type WaitDefaults, type WaitOptions, WaitTimeoutError, waitDefaults, waitFor, } from "./runtime/wait.ts";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `channelstack` and `channelstack/client`: the generated client the test integrations are built
3
+ * on, and its types (`import type { SlackUser } from "channelstack"`). The public contract is `api/*.d.ts`.
4
+ */
5
+ export { CHANNEL_NAMES } from "./generated/channels.js";
6
+ export * from "./generated/index.js";
7
+ export { parseDuration } from "./runtime/duration.js";
8
+ export { setFilesRoot } from "./runtime/files.js";
9
+ export { QUIET } from "./runtime/client.js";
10
+ export { ChannelstackError, onRefusal, unreportedRefusals } from "./runtime/transport.js";
11
+ export { fromMatches, setWaitDefaults, textMatches, untilQuiet, WaitTimeoutError, waitDefaults, waitFor, } from "./runtime/wait.js";
@@ -0,0 +1,24 @@
1
+ import type * as G from "./index.ts";
2
+ type Option<Method extends (...args: never[]) => unknown> = NonNullable<Parameters<Method>[0]>;
3
+ /** Every channel, by name, in the server's order. */
4
+ export declare const CHANNEL_NAMES: readonly ["slack", "github", "linear", "notion", "resend", "google"];
5
+ export type ChannelKind = (typeof CHANNEL_NAMES)[number];
6
+ /** Each channel's fixture, by its name: what a test framework hands a test. */
7
+ export interface ChannelFixtures {
8
+ slack: G.SlackFixture;
9
+ github: G.GitHubFixture;
10
+ linear: G.LinearFixture;
11
+ notion: G.NotionFixture;
12
+ resend: G.ResendFixture;
13
+ google: G.GoogleFixture;
14
+ }
15
+ export type User = G.SlackUser | G.GitHubUser | G.LinearUser | G.NotionUser | G.ResendUser | G.GoogleUser;
16
+ export type App = G.SlackApp | G.GitHubApp | G.LinearApp | G.NotionIntegration | G.ResendApp | G.GoogleApp;
17
+ export type Resource = G.SlackConversation | G.GitHubRepo | G.LinearTeam | G.NotionPage | G.NotionDatabase | G.ResendThread | G.GoogleThread;
18
+ export type AnyDelivery = G.SlackDelivery | G.GitHubDelivery | G.LinearDelivery | G.NotionDelivery | G.ResendDelivery | G.GoogleDelivery;
19
+ export type DeliveryFilter = Option<G.GitHubFixture["deliveries"]> | Option<G.LinearFixture["deliveries"]> | Option<G.NotionFixture["deliveries"]> | Option<G.ResendFixture["deliveries"]> | Option<G.GoogleFixture["deliveries"]>;
20
+ export type ApiCall = G.SlackApiCall | G.GitHubApiCall | G.LinearApiCall | G.NotionApiCall | G.ResendApiCall | G.GoogleApiCall;
21
+ export type Transcript = G.SlackTranscript | G.GitHubTranscript | G.LinearTranscript | G.NotionTranscript | G.ResendTranscript | G.GoogleTranscript;
22
+ /** What every channel fixture has to inspect what the agent did: the fixture whose deliveries are `TDelivery`. */
23
+ export type Inspectable<TDelivery extends AnyDelivery = AnyDelivery> = TDelivery extends G.SlackDelivery ? G.SlackFixture : TDelivery extends G.GitHubDelivery ? G.GitHubFixture : TDelivery extends G.LinearDelivery ? G.LinearFixture : TDelivery extends G.NotionDelivery ? G.NotionFixture : TDelivery extends G.ResendDelivery ? G.ResendFixture : TDelivery extends G.GoogleDelivery ? G.GoogleFixture : never;
24
+ export {};
@@ -0,0 +1,2 @@
1
+ /** Every channel, by name, in the server's order. */
2
+ export const CHANNEL_NAMES = ["slack", "github", "linear", "notion", "resend", "google"];