channelstack 0.1.1 → 0.2.0

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 (28) hide show
  1. package/README.md +1 -1
  2. package/dist/integrations/checks/index.d.ts +40 -7
  3. package/dist/integrations/checks/index.js +525 -69
  4. package/dist/integrations/matchers-core/index.d.ts +90 -11
  5. package/dist/integrations/matchers-core/index.js +356 -15
  6. package/dist/integrations/matchers-core/matchers.test.js +251 -3
  7. package/dist/integrations/vitest/index.d.ts +4 -2
  8. package/dist/integrations/vitest/setup.js +33 -3
  9. package/dist/sdks/typescript/client.d.ts +5 -4
  10. package/dist/sdks/typescript/client.js +4 -4
  11. package/dist/sdks/typescript/generated/channels.d.ts +17 -9
  12. package/dist/sdks/typescript/generated/channels.js +3 -1
  13. package/dist/sdks/typescript/generated/index.d.ts +1744 -313
  14. package/dist/sdks/typescript/generated/index.js +1991 -422
  15. package/dist/sdks/typescript/generated/normalisation.d.ts +18 -0
  16. package/dist/sdks/typescript/generated/normalisation.js +14 -0
  17. package/dist/sdks/typescript/runtime/client.d.ts +9 -0
  18. package/dist/sdks/typescript/runtime/client.js +5 -0
  19. package/dist/sdks/typescript/runtime/files.d.ts +17 -2
  20. package/dist/sdks/typescript/runtime/files.js +11 -3
  21. package/dist/sdks/typescript/runtime/launcher.d.ts +5 -2
  22. package/dist/sdks/typescript/runtime/launcher.js +6 -3
  23. package/dist/sdks/typescript/runtime/responder.d.ts +26 -0
  24. package/dist/sdks/typescript/runtime/responder.js +42 -0
  25. package/dist/sdks/typescript/runtime/wait.d.ts +14 -0
  26. package/dist/sdks/typescript/runtime/wait.js +23 -0
  27. package/dist/sdks/typescript/types.d.ts +16 -6
  28. package/package.json +9 -7
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Text as the server compares it for attribution: each rule replaces every match of its pattern
3
+ * (`$1` is its first group), in order; then, as its flags say, whitespace collapsed and trimmed and case lowered.
4
+ */
5
+ export declare const TEXT_NORMALISATION: {
6
+ readonly rules: readonly [{
7
+ readonly pattern: "<[@#!][^>]*>";
8
+ readonly replacement: " ";
9
+ }, {
10
+ readonly pattern: "<(https?:[^>|]+)(\\|[^>]*)?>";
11
+ readonly replacement: " $1 ";
12
+ }, {
13
+ readonly pattern: "(^|\\s)@[A-Za-z0-9_.-]+";
14
+ readonly replacement: " ";
15
+ }];
16
+ readonly collapseWhitespace: true;
17
+ readonly lowercase: true;
18
+ };
@@ -0,0 +1,14 @@
1
+ // Generated by codegen from spec/ir.json. Do not edit: change the routes and run `pnpm sdk`.
2
+ /**
3
+ * Text as the server compares it for attribution: each rule replaces every match of its pattern
4
+ * (`$1` is its first group), in order; then, as its flags say, whitespace collapsed and trimmed and case lowered.
5
+ */
6
+ export const TEXT_NORMALISATION = {
7
+ rules: [
8
+ { pattern: "<[@#!][^>]*>", replacement: " " },
9
+ { pattern: "<(https?:[^>|]+)(\\|[^>]*)?>", replacement: " $1 " },
10
+ { pattern: "(^|\\s)@[A-Za-z0-9_.-]+", replacement: " " },
11
+ ],
12
+ collapseWhitespace: true,
13
+ lowercase: true,
14
+ };
@@ -17,6 +17,15 @@ export declare const QUIET: unique symbol;
17
17
  export interface InSession {
18
18
  [QUIET](): Promise<QuietState>;
19
19
  }
20
+ /**
21
+ * Every generated handle answers this with its context: the server and the session it lives in. A
22
+ * failing matcher reads the session's model calls with it, whatever handle it was given.
23
+ */
24
+ export declare const CONTEXT: unique symbol;
25
+ /** A handle a matcher can read its session through. */
26
+ export interface WithContext {
27
+ [CONTEXT](): HandleContext;
28
+ }
20
29
  /** Give a value its text form: `String(value)` and `value.toString()` return `text`, and the value keeps its fields. */
21
30
  export declare function printsAs<T extends object>(value: T, text: string): T & {
22
31
  toString(): string;
@@ -11,6 +11,11 @@ export function sessionOf(context) {
11
11
  * negative and exact-count checks, whatever handle they are given.
12
12
  */
13
13
  export const QUIET = Symbol.for("channelstack.quiet");
14
+ /**
15
+ * Every generated handle answers this with its context: the server and the session it lives in. A
16
+ * failing matcher reads the session's model calls with it, whatever handle it was given.
17
+ */
18
+ export const CONTEXT = Symbol.for("channelstack.context");
14
19
  /** Give a value its text form: `String(value)` and `value.toString()` return `text`, and the value keeps its fields. */
15
20
  export function printsAs(value, text) {
16
21
  return Object.defineProperty(value, "toString", { value: () => text, enumerable: false });
@@ -1,4 +1,4 @@
1
- /** Files in a test: inline contents, or a path to a fixture file or directory (`api/common.d.ts`). */
1
+ /** Files in a test: inline contents, or a path to a fixture file or directory. */
2
2
  export type FileInput = {
3
3
  name: string;
4
4
  content: string | Uint8Array;
@@ -18,7 +18,7 @@ interface WireFile {
18
18
  * paths start from the working directory.
19
19
  */
20
20
  export declare function setFilesRoot(directory: string | undefined): void;
21
- /** A whole tree of files: a fixture directory, or a list of files. */
21
+ /** A whole tree of files: a fixture directory, one fixture file, or a list of files. */
22
22
  export declare function readTree(input: string | FileInput[]): WireFile[];
23
23
  /** Changes to files: a list of files, or a map of path to its new contents, where `null` deletes the file. */
24
24
  export declare function readChanges(input: FileInput[] | Record<string, string | null>): Array<{
@@ -29,4 +29,19 @@ export declare function readChanges(input: FileInput[] | Record<string, string |
29
29
  export declare function readDocument(input: string | {
30
30
  path: string;
31
31
  } | unknown[]): string | unknown[];
32
+ /** A placeholder picture, recording or video the server makes: its size, or its length in seconds. */
33
+ interface Placeholder {
34
+ placeholder: {
35
+ width?: number;
36
+ height?: number;
37
+ seconds?: number;
38
+ };
39
+ }
40
+ /** A picture, a recording or a video a test hands over: a fixture file's path, its bytes, or a placeholder. */
41
+ export type MediaSource = string | Uint8Array | Placeholder;
42
+ /** One media source as it travels to the server: a file's bytes in base64 (and its name), or a placeholder as it is. */
43
+ export declare function readMedia(input: MediaSource): {
44
+ content: string;
45
+ name?: string;
46
+ } | Placeholder;
32
47
  export {};
@@ -1,5 +1,5 @@
1
1
  import { readdirSync, readFileSync, statSync } from "node:fs";
2
- import { isAbsolute, join, relative, resolve, sep } from "node:path";
2
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  let root;
4
4
  /**
5
5
  * Where relative fixture paths start from. A test framework integration sets it to the directory
@@ -29,9 +29,9 @@ function read(input) {
29
29
  }
30
30
  return [{ path: input.name ?? input.path.split(/[\\/]/).at(-1) ?? input.path, content: base64(readFileSync(path)) }];
31
31
  }
32
- /** A whole tree of files: a fixture directory, or a list of files. */
32
+ /** A whole tree of files: a fixture directory, one fixture file, or a list of files. */
33
33
  export function readTree(input) {
34
- return typeof input === "string" ? walk(located(input)) : input.flatMap(read);
34
+ return typeof input === "string" ? read({ path: input }) : input.flatMap(read);
35
35
  }
36
36
  /** Changes to files: a list of files, or a map of path to its new contents, where `null` deletes the file. */
37
37
  export function readChanges(input) {
@@ -43,3 +43,11 @@ export function readChanges(input) {
43
43
  export function readDocument(input) {
44
44
  return typeof input === "string" || Array.isArray(input) ? input : readFileSync(located(input.path), "utf8");
45
45
  }
46
+ /** One media source as it travels to the server: a file's bytes in base64 (and its name), or a placeholder as it is. */
47
+ export function readMedia(input) {
48
+ if (input instanceof Uint8Array)
49
+ return { content: base64(input) };
50
+ if (typeof input !== "string")
51
+ return input;
52
+ return { content: base64(readFileSync(located(input))), name: basename(input) };
53
+ }
@@ -18,7 +18,10 @@ export interface ServerConnection {
18
18
  /** The npm package that carries the server binary for this machine. */
19
19
  export declare function serverPackageName(platform?: string, arch?: string): string;
20
20
  export declare function serverBinaryName(platform?: string): string;
21
- /** The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package. */
22
- export declare function resolveServerBinary(env?: NodeJS.ProcessEnv): string;
21
+ /**
22
+ * The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package
23
+ * (found with `resolve`, Node's module resolution from this file).
24
+ */
25
+ export declare function resolveServerBinary(env?: NodeJS.ProcessEnv, resolve?: (specifier: string) => string): string;
23
26
  /** Find or start the server, by `mode`. */
24
27
  export declare function launch(options?: LaunchOptions, env?: NodeJS.ProcessEnv): Promise<ServerConnection>;
@@ -47,13 +47,16 @@ export function serverPackageName(platform = process.platform, arch = process.ar
47
47
  export function serverBinaryName(platform = process.platform) {
48
48
  return platform === "win32" ? "channelstack.exe" : "channelstack";
49
49
  }
50
- /** The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package. */
51
- export function resolveServerBinary(env = process.env) {
50
+ /**
51
+ * The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package
52
+ * (found with `resolve`, Node's module resolution from this file).
53
+ */
54
+ export function resolveServerBinary(env = process.env, resolve = createRequire(import.meta.url).resolve) {
52
55
  if (env.CHANNELSTACK_SERVER_BIN)
53
56
  return env.CHANNELSTACK_SERVER_BIN;
54
57
  const name = serverPackageName();
55
58
  try {
56
- return createRequire(import.meta.url).resolve(`${name}/bin/${serverBinaryName()}`);
59
+ return resolve(`${name}/bin/${serverBinaryName()}`);
57
60
  }
58
61
  catch {
59
62
  throw new Error(`channelstack has no server binary for ${process.platform}-${process.arch}: the optional dependency ${name} isn't installed. ` +
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Answering model calls from the test (decision 0029): the server holds each call a responder
3
+ * script matches, and this loop reads them (a long poll), runs the test's function and posts what
4
+ * it returns. It runs until the script is undone or its session closes, which end its reads.
5
+ */
6
+ /** What the loop needs of a responder's handle: its long-poll read, and the way to answer. */
7
+ export interface ResponderIo<Request, Turn> {
8
+ held(options: {
9
+ since?: string;
10
+ waitMs?: number;
11
+ }): Promise<{
12
+ held: ReadonlyArray<{
13
+ id: string;
14
+ request: Request;
15
+ }>;
16
+ cursor: string;
17
+ }>;
18
+ answer(id: string, options: {
19
+ turn?: Turn;
20
+ error?: string;
21
+ }): Promise<void>;
22
+ }
23
+ /** A function a test answers model calls with: `Responder<OpenAIRequest, OpenAITurnInput>` for the fake OpenAI. */
24
+ export type Responder<Request = unknown, Turn = unknown> = (request: Request) => Turn | Promise<Turn>;
25
+ /** Start answering a responder script's calls in the background. */
26
+ export declare function respondWith<Request, Turn>(io: ResponderIo<Request, Turn>, respond: Responder<Request, Turn>): void;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Answering model calls from the test (decision 0029): the server holds each call a responder
3
+ * script matches, and this loop reads them (a long poll), runs the test's function and posts what
4
+ * it returns. It runs until the script is undone or its session closes, which end its reads.
5
+ */
6
+ /** How long one read waits on the server for a held call: well inside any HTTP timeout. */
7
+ const LONG_POLL_MS = 20_000;
8
+ /** Start answering a responder script's calls in the background. */
9
+ export function respondWith(io, respond) {
10
+ void (async () => {
11
+ let since;
12
+ for (;;) {
13
+ let page;
14
+ try {
15
+ page = await io.held({ ...(since === undefined ? {} : { since }), waitMs: LONG_POLL_MS });
16
+ }
17
+ catch {
18
+ // The script was undone, or its session closed: nothing more will be held for it.
19
+ return;
20
+ }
21
+ since = page.cursor;
22
+ for (const held of page.held) {
23
+ // Each call is answered on its own, so a slow answer doesn't hold up the next call.
24
+ void (async () => {
25
+ let answer;
26
+ try {
27
+ answer = { turn: await respond(held.request) };
28
+ }
29
+ catch (error) {
30
+ answer = { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };
31
+ }
32
+ try {
33
+ await io.answer(held.id, answer);
34
+ }
35
+ catch {
36
+ // The agent hung up, or the call was answered by its timeout: the server has recorded why.
37
+ }
38
+ })();
39
+ }
40
+ }
41
+ })();
42
+ }
@@ -44,6 +44,15 @@ export interface QuietState {
44
44
  quietForMs: number;
45
45
  /** What is still open, in words: a delivery in flight or about to be retried, a stream the agent never stopped. */
46
46
  open: string[];
47
+ /** What should fail a test at once: a model call no script answered (decision 0029). */
48
+ problems?: string[];
49
+ /** The bot loops the fake stopped in the session (decision 0027), when there are any. */
50
+ loops?: string[];
51
+ }
52
+ /** A wait that stopped because the session's model calls went wrong: no script answered one, a script ran out. */
53
+ export declare class ModelProblemError extends Error {
54
+ readonly problems: readonly string[];
55
+ constructor(problems: readonly string[]);
47
56
  }
48
57
  /** Anyone who can author something: a handle with an id and a name. */
49
58
  interface Author {
@@ -54,6 +63,11 @@ interface Author {
54
63
  export declare function fromMatches(author: Author, from: Author | string | undefined): boolean;
55
64
  /** Does a text match what was asked for: a string it contains, a pattern, or nothing (any text)? */
56
65
  export declare function textMatches(text: string, expected: string | RegExp | undefined): boolean;
66
+ /**
67
+ * Text as the server compares it for attribution, by the rules the spec publishes
68
+ * (`TEXT_NORMALISATION`, generated): what `toHaveSent` compares.
69
+ */
70
+ export declare function normalisedText(text: string): string;
57
71
  /** Text to find as it goes to the server: a string as it is, a `RegExp` as its source and flags. */
58
72
  export declare function patternOnWire(pattern: string | RegExp): string | {
59
73
  source: string;
@@ -1,3 +1,4 @@
1
+ import { TEXT_NORMALISATION } from "../generated/normalisation.js";
1
2
  import { parseDuration } from "./duration.js";
2
3
  const defaults = { timeout: "10s", quietFor: "750ms" };
3
4
  /**
@@ -64,6 +65,15 @@ export async function retryWhile(codes, call, options = {}) {
64
65
  throw error instanceof WaitTimeoutError && refusal !== undefined ? refusal : error;
65
66
  }
66
67
  }
68
+ /** A wait that stopped because the session's model calls went wrong: no script answered one, a script ran out. */
69
+ export class ModelProblemError extends Error {
70
+ problems;
71
+ constructor(problems) {
72
+ super(`The model calls of this test went wrong:\n${problems.map((problem) => ` ${problem}`).join("\n")}`);
73
+ this.name = "ModelProblemError";
74
+ this.problems = problems;
75
+ }
76
+ }
67
77
  /** Does an item's author match a `from` filter: a handle, a name, or nothing (anyone)? */
68
78
  export function fromMatches(author, from) {
69
79
  if (from === undefined)
@@ -80,6 +90,17 @@ export function textMatches(text, expected) {
80
90
  expected.lastIndex = 0;
81
91
  return expected.test(text);
82
92
  }
93
+ const NORMALISATION_RULES = TEXT_NORMALISATION.rules.map(({ pattern, replacement }) => [new RegExp(pattern, "g"), replacement]);
94
+ /**
95
+ * Text as the server compares it for attribution, by the rules the spec publishes
96
+ * (`TEXT_NORMALISATION`, generated): what `toHaveSent` compares.
97
+ */
98
+ export function normalisedText(text) {
99
+ let normalised = NORMALISATION_RULES.reduce((current, [pattern, replacement]) => current.replace(pattern, replacement), text);
100
+ if (TEXT_NORMALISATION.collapseWhitespace)
101
+ normalised = normalised.replace(/\s+/g, " ").trim();
102
+ return TEXT_NORMALISATION.lowercase ? normalised.toLowerCase() : normalised;
103
+ }
83
104
  /** Text to find as it goes to the server: a string as it is, a `RegExp` as its source and flags. */
84
105
  export function patternOnWire(pattern) {
85
106
  return typeof pattern === "string" ? pattern : { source: pattern.source, flags: pattern.flags };
@@ -121,6 +142,8 @@ export async function untilQuiet(quiet, options = {}) {
121
142
  () => `the agent to be quiet for ${quietFor}ms${open.length > 0 ? `. Still open: ${open.join("; ")}` : ""}`, async () => {
122
143
  const state = await quiet();
123
144
  open = state.open;
145
+ if (state.problems !== undefined && state.problems.length > 0)
146
+ throw new ModelProblemError(state.problems);
124
147
  if (options.watching && Date.now() - started < quietFor)
125
148
  return undefined;
126
149
  return !state.busy && state.quietForMs >= quietFor ? true : undefined;
@@ -1,8 +1,8 @@
1
1
  /**
2
- * The contract's type names (`api/*.d.ts`) that the generated SDK has no type of its own for: unions
3
- * of its handles, the option bags of its methods, and the values of its fields. Each one is read
4
- * from the generated code, so it can't drift from it. With them, `import type { AuthorRef } from
5
- * "channelstack"` works as the contract says.
2
+ * The type names tests import that the generated SDK has no type of its own for: unions of its
3
+ * handles, the option bags of its methods, and the values of its fields. Each one is read from the
4
+ * generated code, so it can't drift from it. With them, `import type { AuthorRef } from
5
+ * "channelstack"` works.
6
6
  *
7
7
  * Not here: the test framework's own types (`ChannelstackFixture`, `ChannelstackIntegrationOptions`,
8
8
  * `ChannelstackMatchers`, `TextOptions`, in `channelstack/vitest`), and `SlackInjectedFault`, which
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import type { AnyDelivery, App, Transcript, User } from "./generated/channels.ts";
12
12
  import type * as G from "./generated/index.ts";
13
- export type { ApiCall, App, ChannelKind, DeliveryFilter, Inspectable, Resource, Transcript, User, } from "./generated/channels.ts";
13
+ export type { ApiCall, App, ChannelKind, DeliveryFilter, ProviderKind, Inspectable, Resource, Transcript, User, } from "./generated/channels.ts";
14
14
  type Option<Method extends (...args: never[]) => unknown> = NonNullable<Parameters<Method>[0]>;
15
15
  /** Text that may contain `@name` mentions. */
16
16
  export type RichText = string;
@@ -23,7 +23,7 @@ export type NotionAuthor = G.NotionUser | G.NotionIntegration;
23
23
  export type Principal = User | App;
24
24
  /** Anything that can be named as an author in a matcher: a handle or its `name`. */
25
25
  export type AuthorRef = Principal | string;
26
- /** A delivery of any channel, narrowed by its `type` and `payload` as the contract's `Delivery<TType, TPayload>` is. */
26
+ /** A delivery of any channel, narrowed by its `type` and `payload` as `Delivery<TType, TPayload>`. */
27
27
  export type Delivery<TType extends string = string, TPayload = unknown> = AnyDelivery & {
28
28
  readonly type: TType;
29
29
  readonly payload: TPayload;
@@ -70,3 +70,13 @@ export type EmailSendOptions<TRecipient = unknown> = Omit<Option<G.ResendUser["s
70
70
  cc?: readonly TRecipient[];
71
71
  };
72
72
  export type EmailReplyOptions = NonNullable<Parameters<G.ResendUser["reply"]>[1]>;
73
+ export type DiscordParticipant = G.DiscordUser | G.DiscordApp;
74
+ export type DiscordUserOptions = Option<G.DiscordFixture["createUser"]>;
75
+ export type DiscordChannelOptions = Option<G.DiscordFixture["createChannel"]>;
76
+ export type DiscordFaultOptions = Option<G.DiscordFixture["fault"]>;
77
+ /** Read as one person: Discord shows an ephemeral message only to its person. */
78
+ export type DiscordHasTranscript = {
79
+ transcript(options?: {
80
+ as?: DiscordParticipant;
81
+ }): Promise<G.DiscordTranscript>;
82
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "channelstack",
3
- "version": "0.1.1",
4
- "description": "Test the apps and agents you build for Slack, GitHub, Linear, Notion, Resend and Gmail: fake platforms on localhost, the TypeScript SDK, Vitest fixtures and matchers.",
3
+ "version": "0.2.0",
4
+ "description": "Test the apps and agents you build for Slack, GitHub, Linear, Notion, Resend, Gmail and Discord: fake platforms and a fake OpenAI on localhost, the TypeScript SDK, Vitest fixtures and matchers.",
5
5
  "keywords": [
6
6
  "testing",
7
7
  "test-harness",
@@ -12,6 +12,8 @@
12
12
  "notion",
13
13
  "resend",
14
14
  "gmail",
15
+ "discord",
16
+ "openai",
15
17
  "agents",
16
18
  "vitest"
17
19
  ],
@@ -65,11 +67,11 @@
65
67
  "build": "tsc -p tsconfig.build.json"
66
68
  },
67
69
  "optionalDependencies": {
68
- "@channelstack/server-darwin-arm64": "0.1.1",
69
- "@channelstack/server-darwin-x64": "0.1.1",
70
- "@channelstack/server-linux-arm64": "0.1.1",
71
- "@channelstack/server-linux-x64": "0.1.1",
72
- "@channelstack/server-win32-x64": "0.1.1"
70
+ "@channelstack/server-darwin-arm64": "0.2.0",
71
+ "@channelstack/server-darwin-x64": "0.2.0",
72
+ "@channelstack/server-linux-arm64": "0.2.0",
73
+ "@channelstack/server-linux-x64": "0.2.0",
74
+ "@channelstack/server-win32-x64": "0.2.0"
73
75
  },
74
76
  "peerDependencies": {
75
77
  "vitest": ">=5.0.0 <6"