@revenexx/integrations-node-devkit 0.8.0 → 0.8.2

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.
@@ -0,0 +1,96 @@
1
+ import type { INodeContext } from '@revenexx/integrations-node-sdk';
2
+ import type { AnyMock } from './mock.js';
3
+ /**
4
+ * Drop-in replacement for the `createMockContext` helper that was, until this
5
+ * package existed, copy-pasted byte-for-byte into every node repo's
6
+ * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with
7
+ * `vi.fn<AnyFn>()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a
8
+ * node's `execute` can be unit-tested in isolation.
9
+ *
10
+ * The state mock is **stateful on purpose**: what the node writes, it reads
11
+ * back. A node's interesting behaviour is precisely the second run — the one
12
+ * that finds the mapping it created the first time — and a mock that forgets
13
+ * would only ever exercise the create branch. It is the one place an author can
14
+ * test writes at all: in the real product, author-time execution is read-only.
15
+ *
16
+ * It reads back *when the store would let it*, which is not the same for all
17
+ * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take
18
+ * effect immediately, a cursor and a digest are staged and adopted only once the
19
+ * run completes. So `cursor.get` after `cursor.set` still answers what the last
20
+ * completed run left — call {@link MockContext.completeRun} between two
21
+ * `execute` calls to play the second run, and leave it uncalled to play the run
22
+ * that failed and left the watermark where it was.
23
+ */
24
+ export type MockLogger = {
25
+ info: AnyMock;
26
+ warn: AnyMock;
27
+ error: AnyMock;
28
+ };
29
+ export type MockSecrets = {
30
+ get: AnyMock;
31
+ };
32
+ export type MockCredentials = {
33
+ get: AnyMock;
34
+ };
35
+ /** Every state operation is a `vi.fn<AnyFn>()`, so calls can be asserted on. */
36
+ export type MockState = {
37
+ mapping: {
38
+ get: AnyMock;
39
+ put: AnyMock;
40
+ };
41
+ cursor: {
42
+ get: AnyMock;
43
+ set: AnyMock;
44
+ };
45
+ claim: AnyMock;
46
+ digest: {
47
+ unchanged: AnyMock;
48
+ set: AnyMock;
49
+ };
50
+ };
51
+ /**
52
+ * What the store already knows when the node starts — the "this ran before"
53
+ * half of any sync test.
54
+ */
55
+ export interface MockStateSeed {
56
+ /** namespace -> { leftKey: rightKey }; readable from either side. */
57
+ mappings?: Record<string, Record<string, string>>;
58
+ /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */
59
+ cursors?: Record<string, Record<string, unknown>>;
60
+ /** namespace -> keys already claimed, so `claim` returns false for them. */
61
+ claims?: Record<string, string[]>;
62
+ /** namespace -> { entityKey: digest }. */
63
+ digests?: Record<string, Record<string, string>>;
64
+ }
65
+ export type MockContext = INodeContext & {
66
+ logger: MockLogger;
67
+ secrets: MockSecrets;
68
+ credentials: MockCredentials;
69
+ state: MockState;
70
+ /**
71
+ * Adopts what this run staged — the cursors and digests it set — the way the
72
+ * engine does when a run completes. Not part of {@link INodeContext}: it is
73
+ * the harness standing in for the run's own ending, and a node can never call
74
+ * it. A test that never calls it has played a run that did not complete.
75
+ */
76
+ completeRun: () => void;
77
+ };
78
+ export interface CreateMockContextOptions {
79
+ signal?: AbortSignal;
80
+ /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */
81
+ secrets?: Record<string, string>;
82
+ /** When set, `secrets.get` rejects with this error instead of resolving. */
83
+ secretsError?: Error;
84
+ /** Credential instance id -> resolved access data returned by `credentials.get`. */
85
+ credentials?: Record<string, Record<string, unknown>>;
86
+ /** When set, `credentials.get` rejects with this error instead of resolving. */
87
+ credentialsError?: Error;
88
+ /** What the state store already holds when the node starts. */
89
+ state?: MockStateSeed;
90
+ /**
91
+ * When set, every state call rejects with this error — the shape of the
92
+ * engine refusing a namespace the workflow never declared.
93
+ */
94
+ stateError?: Error;
95
+ }
96
+ export declare function createMockContext(options?: CreateMockContextOptions): MockContext;
@@ -0,0 +1,66 @@
1
+ import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
2
+ import type { AnyMock } from './mock.js';
3
+ /**
4
+ * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged
5
+ * OAuth without the credentials broker or a real provider. Combine with
6
+ * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,
7
+ * and inspect the returned `persistDurableCreds` spy to assert refresh-token
8
+ * rotation.
9
+ */
10
+ export type MockCredentialLogger = {
11
+ info: AnyMock;
12
+ warn: AnyMock;
13
+ error: AnyMock;
14
+ };
15
+ export type MockCredentialContext = ICredentialContext & {
16
+ logger: MockCredentialLogger;
17
+ /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */
18
+ persistDurableCreds: AnyMock;
19
+ };
20
+ export interface CreateCredentialContextOptions {
21
+ signal?: AbortSignal;
22
+ }
23
+ export declare function createCredentialContext(options?: CreateCredentialContextOptions): MockCredentialContext;
24
+ export interface RunCredentialTestOptions {
25
+ config: Record<string, unknown>;
26
+ signal?: AbortSignal;
27
+ }
28
+ /** Runs a credential's `test(ctx, config)` and returns its result. */
29
+ export declare function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult>;
30
+ export interface RunCredentialResolveOptions {
31
+ config: Record<string, unknown>;
32
+ /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */
33
+ durableCreds?: Record<string, unknown> | null;
34
+ signal?: AbortSignal;
35
+ }
36
+ export interface RunCredentialResolveResult {
37
+ result: ICredentialResolveResult;
38
+ /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */
39
+ persistDurableCreds: AnyMock;
40
+ /** The context used, for further assertions (logger calls, etc.). */
41
+ ctx: MockCredentialContext;
42
+ }
43
+ /** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */
44
+ export declare function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult>;
45
+ export interface RunOAuthAuthorizeUrlOptions {
46
+ config: Record<string, unknown>;
47
+ redirectUri: string;
48
+ state: string;
49
+ signal?: AbortSignal;
50
+ }
51
+ /** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */
52
+ export declare function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{
53
+ authorizeUrl: string;
54
+ codeVerifier?: string;
55
+ }>;
56
+ export interface RunOAuthExchangeCodeOptions {
57
+ config: Record<string, unknown>;
58
+ code: string;
59
+ redirectUri: string;
60
+ codeVerifier?: string;
61
+ signal?: AbortSignal;
62
+ }
63
+ /** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */
64
+ export declare function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{
65
+ durableCreds: Record<string, unknown>;
66
+ }>;
@@ -0,0 +1,57 @@
1
+ import type { AnyMock } from './mock.js';
2
+ /**
3
+ * Utilities for stubbing the global `fetch` so a credential's `resolve` /
4
+ * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a
5
+ * node's `execute` (which uses `safeFetch` → global `fetch`) can be
6
+ * unit-tested without touching the network. Builds real `Response` objects so
7
+ * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as
8
+ * in production.
9
+ */
10
+ export interface StubResponseInit {
11
+ status?: number;
12
+ headers?: Record<string, string>;
13
+ /** JSON body — serialized and served as `application/json` unless `body` is set. */
14
+ json?: unknown;
15
+ /** Raw string body. Takes precedence over `json`. */
16
+ body?: string;
17
+ }
18
+ export interface StubbedRequest {
19
+ url: string;
20
+ method: string;
21
+ init?: RequestInit;
22
+ }
23
+ export type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;
24
+ /** Builds a real `Response` from a {@link StubResponseInit}. */
25
+ export declare function buildResponse(init: StubResponseInit): Response;
26
+ export interface StubFetchResult {
27
+ /** The `vi.fn<AnyFn>()` installed as `globalThis.fetch` — assert calls on it. */
28
+ fetchMock: AnyMock;
29
+ /** Restores the previous `globalThis.fetch`. */
30
+ restore(): void;
31
+ }
32
+ /**
33
+ * Replaces `globalThis.fetch` with a `vi.fn<AnyFn>()` driven by `handler`. Pass a
34
+ * static {@link StubResponseInit} to answer every request identically, or a
35
+ * {@link FetchHandler} to branch on url/method. Call `restore()` when done
36
+ * (e.g. in `afterEach`).
37
+ */
38
+ export declare function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult;
39
+ export interface FakeTokenEndpointOptions {
40
+ /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */
41
+ tokenUrl?: string;
42
+ accessToken?: string;
43
+ tokenType?: string;
44
+ /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */
45
+ expiresIn?: number | null;
46
+ /** Included as `refresh_token` when set (e.g. to assert rotation). */
47
+ refreshToken?: string;
48
+ /** Extra fields merged into the token response body. */
49
+ extra?: Record<string, unknown>;
50
+ }
51
+ /**
52
+ * A {@link FetchHandler} that emulates an OAuth token endpoint, returning
53
+ * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with
54
+ * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth
55
+ * `exchangeCode`.
56
+ */
57
+ export declare function fakeTokenEndpoint(options?: FakeTokenEndpointOptions): FetchHandler;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/testing/index.ts","../../src/testing/context.ts","../../src/state-rules.ts","../../src/testing/author.ts","../../src/testing/fetch.ts","../../src/testing/credentials.ts"],"sourcesContent":["export * from './context.js';\nexport * from './author.js';\nexport * from './fetch.js';\nexport * from './credentials.js';\n","import type { INodeContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport { assertNotRepointed, assertTtlInRange } from '../state-rules.js';\n\n/**\n * Drop-in replacement for the `createMockContext` helper that was, until this\n * package existed, copy-pasted byte-for-byte into every node repo's\n * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with\n * `vi.fn()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a\n * node's `execute` can be unit-tested in isolation.\n *\n * The state mock is **stateful on purpose**: what the node writes, it reads\n * back. A node's interesting behaviour is precisely the second run — the one\n * that finds the mapping it created the first time — and a mock that forgets\n * would only ever exercise the create branch. It is the one place an author can\n * test writes at all: in the real product, author-time execution is read-only.\n *\n * It reads back *when the store would let it*, which is not the same for all\n * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take\n * effect immediately, a cursor and a digest are staged and adopted only once the\n * run completes. So `cursor.get` after `cursor.set` still answers what the last\n * completed run left — call {@link MockContext.completeRun} between two\n * `execute` calls to play the second run, and leave it uncalled to play the run\n * that failed and left the watermark where it was.\n */\n\nexport type MockLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockSecrets = {\n get: ReturnType<typeof vi.fn>;\n};\n\nexport type MockCredentials = {\n get: ReturnType<typeof vi.fn>;\n};\n\n/** Every state operation is a `vi.fn()`, so calls can be asserted on. */\nexport type MockState = {\n mapping: { get: ReturnType<typeof vi.fn>; put: ReturnType<typeof vi.fn> };\n cursor: { get: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };\n claim: ReturnType<typeof vi.fn>;\n digest: { unchanged: ReturnType<typeof vi.fn>; set: ReturnType<typeof vi.fn> };\n};\n\n/**\n * What the store already knows when the node starts — the \"this ran before\"\n * half of any sync test.\n */\nexport interface MockStateSeed {\n /** namespace -> { leftKey: rightKey }; readable from either side. */\n mappings?: Record<string, Record<string, string>>;\n /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */\n cursors?: Record<string, Record<string, unknown>>;\n /** namespace -> keys already claimed, so `claim` returns false for them. */\n claims?: Record<string, string[]>;\n /** namespace -> { entityKey: digest }. */\n digests?: Record<string, Record<string, string>>;\n}\n\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\n state: MockState;\n /**\n * Adopts what this run staged — the cursors and digests it set — the way the\n * engine does when a run completes. Not part of {@link INodeContext}: it is\n * the harness standing in for the run's own ending, and a node can never call\n * it. A test that never calls it has played a run that did not complete.\n */\n completeRun: () => void;\n};\n\nexport interface CreateMockContextOptions {\n signal?: AbortSignal;\n /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */\n secrets?: Record<string, string>;\n /** When set, `secrets.get` rejects with this error instead of resolving. */\n secretsError?: Error;\n /** Credential instance id -> resolved access data returned by `credentials.get`. */\n credentials?: Record<string, Record<string, unknown>>;\n /** When set, `credentials.get` rejects with this error instead of resolving. */\n credentialsError?: Error;\n /** What the state store already holds when the node starts. */\n state?: MockStateSeed;\n /**\n * When set, every state call rejects with this error — the shape of the\n * engine refusing a namespace the workflow never declared.\n */\n stateError?: Error;\n}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\n const signal = options.signal ?? new AbortController().signal;\n const { state, completeRun } = createMockState(options.state, options.stateError);\n\n const secretsGet = options.secretsError\n ? vi.fn(async () => {\n throw options.secretsError;\n })\n : vi.fn(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn(async () => {\n throw options.credentialsError;\n })\n : vi.fn(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\n },\n state,\n completeRun,\n };\n}\n\n/**\n * A tiny in-memory stand-in for the four state roles. Seeds are copied rather\n * than referenced, so a test that writes cannot leak into the next one.\n *\n * The write calls split the way the store does. A mapping and a claim land in\n * the committed maps at once; a cursor and a digest land in a staging map that\n * only `completeRun` folds in, so a read during the run answers what the last\n * completed one left. That is the whole reason there are four operations rather\n * than a generic get/set, and a mock that adopted everything immediately would\n * hide the case the rule exists for: the run that fails after advancing its\n * watermark.\n */\nfunction createMockState(seed: MockStateSeed = {}, error?: Error): { state: MockState; completeRun: () => void } {\n const mappings = new Map<string, Map<string, string>>();\n const cursors = new Map<string, Map<string, unknown>>();\n const claims = new Map<string, Set<string>>();\n const digests = new Map<string, Map<string, string>>();\n /** What this run has staged: adopted by `completeRun`, dropped otherwise. */\n const stagedCursors = new Map<string, Map<string, unknown>>();\n const stagedDigests = new Map<string, Map<string, string>>();\n\n for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {\n mappings.set(namespace, new Map(Object.entries(pairs)));\n }\n for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {\n cursors.set(namespace, new Map(Object.entries(partitions)));\n }\n for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {\n claims.set(namespace, new Set(keys));\n }\n for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {\n digests.set(namespace, new Map(Object.entries(entries)));\n }\n\n /** Wraps an operation so `stateError` short-circuits every one of them. */\n const op = <A extends unknown[], R>(fn: (...args: A) => R) =>\n vi.fn(async (...args: A): Promise<R> => {\n if (error) {\n throw error;\n }\n return fn(...args);\n });\n\n const state: MockState = {\n mapping: {\n get: op((namespace: string, key: string, side: 'left' | 'right' = 'left') => {\n const pairs = mappings.get(namespace);\n if (!pairs) {\n return null;\n }\n if (side === 'left') {\n return pairs.get(key) ?? null;\n }\n for (const [left, right] of pairs) {\n if (right === key) {\n return left;\n }\n }\n return null;\n }),\n put: op((namespace: string, left: string, right: string) => {\n const pairs = mappings.get(namespace) ?? new Map<string, string>();\n assertNotRepointed(namespace, pairs, left, right);\n pairs.set(left, right);\n mappings.set(namespace, pairs);\n }),\n },\n cursor: {\n // The committed watermark: what *this* run staged is deliberately not in\n // the answer, exactly as the real store describes it.\n get: op((namespace: string, partitionKey = '') => cursors.get(namespace)?.get(partitionKey)),\n set: op((namespace: string, value: unknown, partitionKey = '') => {\n const partitions = stagedCursors.get(namespace) ?? new Map<string, unknown>();\n partitions.set(partitionKey, value);\n stagedCursors.set(namespace, partitions);\n }),\n },\n // First caller wins, like the real claim — so a test can drive both the\n // fresh and the duplicate path without reconfiguring the mock. A claim is\n // never handed on here: a TTL is a wall-clock window, and no unit test\n // outlives the shortest one the store accepts.\n claim: op((namespace: string, key: string, opts?: { ttlSeconds?: number }) => {\n assertTtlInRange(opts?.ttlSeconds);\n const held = claims.get(namespace) ?? new Set<string>();\n if (held.has(key)) {\n return false;\n }\n held.add(key);\n claims.set(namespace, held);\n return true;\n }),\n digest: {\n unchanged: op((namespace: string, entityKey: string, digest: string) => digests.get(namespace)?.get(entityKey) === digest),\n set: op((namespace: string, entityKey: string, digest: string) => {\n const entries = stagedDigests.get(namespace) ?? new Map<string, string>();\n entries.set(entityKey, digest);\n stagedDigests.set(namespace, entries);\n }),\n },\n };\n\n const completeRun = (): void => {\n for (const [namespace, partitions] of stagedCursors) {\n const committed = cursors.get(namespace) ?? new Map<string, unknown>();\n for (const [partitionKey, value] of partitions) {\n committed.set(partitionKey, value);\n }\n cursors.set(namespace, committed);\n }\n for (const [namespace, entries] of stagedDigests) {\n const committed = digests.get(namespace) ?? new Map<string, string>();\n for (const [entityKey, digest] of entries) {\n committed.set(entityKey, digest);\n }\n digests.set(namespace, committed);\n }\n stagedCursors.clear();\n stagedDigests.clear();\n };\n\n return { state, completeRun };\n}\n","import { NodeError } from '@revenexx/integrations-node-sdk';\n\n/**\n * The two rules the tenant state store keeps that neither the mock context nor\n * the local preview would otherwise have any reason to keep — and both of which\n * a node author only finds out about in production if we do not.\n *\n * They live here rather than in either caller because the testing harness and\n * the preview must refuse the same things: a node that passes its unit tests and\n * then trips the store on its first preview run has learnt nothing from either.\n * The rest of what the store promises — that a granted claim really excludes a\n * parallel run, that an undeclared namespace is refused — is the engine's, and\n * `specs/workflow-state.md` in the SDK records it as such.\n */\n\n/** Mirrors the engine's default claim lifetime (7 days). */\nexport const DEFAULT_CLAIM_TTL_SECONDS = 604_800;\n\n/** The window the store accepts: one second to one year. */\nexport const MIN_CLAIM_TTL_SECONDS = 1;\nexport const MAX_CLAIM_TTL_SECONDS = 31_536_000;\n\n/**\n * A `ttlSeconds` outside the accepted window is refused rather than clamped: the\n * figure is the duplicate-suppression window *and* the retry window, so a node\n * quietly given a different one than it asked for would suppress deliveries for\n * a stretch its author never chose.\n */\nexport function assertTtlInRange(ttlSeconds: number | undefined): void {\n if (ttlSeconds === undefined) {\n return;\n }\n if (!Number.isFinite(ttlSeconds) || ttlSeconds < MIN_CLAIM_TTL_SECONDS || ttlSeconds > MAX_CLAIM_TTL_SECONDS) {\n throw new NodeError('INVALID_TTL', `ttlSeconds must be between ${MIN_CLAIM_TTL_SECONDS} and ${MAX_CLAIM_TTL_SECONDS}, got ${String(ttlSeconds)}.`);\n }\n}\n\n/**\n * Re-pointing one side of an existing pair is refused, in both directions: an id\n * correlated two ways is always a bug, and no later sync can untangle it —\n * whichever of the two answers a lookup happens to give, half the records it\n * touches are the wrong ones. Writing the same pair again is not a re-point and\n * is allowed, so a node that puts unconditionally on every run stays green.\n */\nexport function assertNotRepointed(namespace: string, pairs: Iterable<[string, string]>, left: string, right: string): void {\n for (const [existingLeft, existingRight] of pairs) {\n if (existingLeft === left && existingRight !== right) {\n throw new NodeError('MAPPING_CONFLICT', `'${left}' is already correlated with '${existingRight}' in namespace '${namespace}'.`);\n }\n if (existingRight === right && existingLeft !== left) {\n throw new NodeError('MAPPING_CONFLICT', `'${right}' is already correlated with '${existingLeft}' in namespace '${namespace}'.`);\n }\n }\n}\n","import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\n\n/**\n * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*\n * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this\n * package existed, this factory was reinvented inline in each repo's resolver\n * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`\n * are `vi.fn()`-backed and seedable.\n */\n\nexport type MockAuthorLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockAuthorContext = INodeAuthorContext & {\n logger: MockAuthorLogger;\n secrets: { get: ReturnType<typeof vi.fn> };\n credentials: { get: ReturnType<typeof vi.fn> };\n};\n\nexport interface CreateAuthorContextOptions {\n signal?: AbortSignal;\n /** Preferred locale for resolved labels. */\n locale?: string;\n secrets?: Record<string, string>;\n secretsError?: Error;\n credentials?: Record<string, Record<string, unknown>>;\n credentialsError?: Error;\n}\n\nexport function createAuthorContext(config: Record<string, unknown> = {}, options: CreateAuthorContextOptions = {}): MockAuthorContext {\n const signal = options.signal ?? new AbortController().signal;\n\n const secretsGet = options.secretsError\n ? vi.fn(async () => {\n throw options.secretsError;\n })\n : vi.fn(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn(async () => {\n throw options.credentialsError;\n })\n : vi.fn(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n config,\n secrets: { get: secretsGet },\n credentials: { get: credentialsGet },\n locale: options.locale,\n };\n}\n","import { vi } from 'vitest';\n\n/**\n * Utilities for stubbing the global `fetch` so a credential's `resolve` /\n * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a\n * node's `execute` (which uses `safeFetch` → global `fetch`) can be\n * unit-tested without touching the network. Builds real `Response` objects so\n * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as\n * in production.\n */\n\nexport interface StubResponseInit {\n status?: number;\n headers?: Record<string, string>;\n /** JSON body — serialized and served as `application/json` unless `body` is set. */\n json?: unknown;\n /** Raw string body. Takes precedence over `json`. */\n body?: string;\n}\n\nexport interface StubbedRequest {\n url: string;\n method: string;\n init?: RequestInit;\n}\n\nexport type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;\n\n/** Builds a real `Response` from a {@link StubResponseInit}. */\nexport function buildResponse(init: StubResponseInit): Response {\n const headers = new Headers(init.headers ?? {});\n let body: string | undefined;\n if (init.body !== undefined) {\n body = init.body;\n } else if (init.json !== undefined) {\n body = JSON.stringify(init.json);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n return new Response(body, { status: init.status ?? 200, headers });\n}\n\nexport interface StubFetchResult {\n /** The `vi.fn()` installed as `globalThis.fetch` — assert calls on it. */\n fetchMock: ReturnType<typeof vi.fn>;\n /** Restores the previous `globalThis.fetch`. */\n restore(): void;\n}\n\n/**\n * Replaces `globalThis.fetch` with a `vi.fn()` driven by `handler`. Pass a\n * static {@link StubResponseInit} to answer every request identically, or a\n * {@link FetchHandler} to branch on url/method. Call `restore()` when done\n * (e.g. in `afterEach`).\n */\nexport function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult {\n const previous = globalThis.fetch;\n const resolveInit: FetchHandler = typeof handler === 'function' ? handler : () => handler;\n\n const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const out = await resolveInit({ url, method, init });\n return out instanceof Response ? out : buildResponse(out);\n });\n\n globalThis.fetch = fetchMock as unknown as typeof fetch;\n return {\n fetchMock,\n restore() {\n globalThis.fetch = previous;\n },\n };\n}\n\nexport interface FakeTokenEndpointOptions {\n /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */\n tokenUrl?: string;\n accessToken?: string;\n tokenType?: string;\n /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */\n expiresIn?: number | null;\n /** Included as `refresh_token` when set (e.g. to assert rotation). */\n refreshToken?: string;\n /** Extra fields merged into the token response body. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * A {@link FetchHandler} that emulates an OAuth token endpoint, returning\n * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with\n * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth\n * `exchangeCode`.\n */\nexport function fakeTokenEndpoint(options: FakeTokenEndpointOptions = {}): FetchHandler {\n const { tokenUrl, accessToken = 'fake-access-token', tokenType = 'Bearer', expiresIn = 3600, refreshToken, extra } = options;\n\n return ({ url }) => {\n if (tokenUrl && url !== tokenUrl) {\n return { status: 404, json: { error: `no stub for ${url}` } };\n }\n const json: Record<string, unknown> = {\n access_token: accessToken,\n token_type: tokenType,\n ...(expiresIn !== null ? { expires_in: expiresIn } : {}),\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...extra,\n };\n return { status: 200, json };\n };\n}\n","import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';\nimport { isOAuthAuthorizeCredential } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\n\n/**\n * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged\n * OAuth without the credentials broker or a real provider. Combine with\n * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,\n * and inspect the returned `persistDurableCreds` spy to assert refresh-token\n * rotation.\n */\n\nexport type MockCredentialLogger = {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n};\n\nexport type MockCredentialContext = ICredentialContext & {\n logger: MockCredentialLogger;\n /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */\n persistDurableCreds: ReturnType<typeof vi.fn>;\n};\n\nexport interface CreateCredentialContextOptions {\n signal?: AbortSignal;\n}\n\nexport function createCredentialContext(options: CreateCredentialContextOptions = {}): MockCredentialContext {\n const signal = options.signal ?? new AbortController().signal;\n const persistDurableCreds = vi.fn(async (_durableCreds: Record<string, unknown>) => {});\n return {\n signal,\n logger: {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n },\n persistDurableCreds,\n };\n}\n\nexport interface RunCredentialTestOptions {\n config: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Runs a credential's `test(ctx, config)` and returns its result. */\nexport async function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.test(ctx, options.config);\n}\n\nexport interface RunCredentialResolveOptions {\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */\n durableCreds?: Record<string, unknown> | null;\n signal?: AbortSignal;\n}\n\nexport interface RunCredentialResolveResult {\n result: ICredentialResolveResult;\n /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */\n persistDurableCreds: ReturnType<typeof vi.fn>;\n /** The context used, for further assertions (logger calls, etc.). */\n ctx: MockCredentialContext;\n}\n\n/** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */\nexport async function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n const result = await credential.resolve(ctx, options.config, options.durableCreds ?? null);\n return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };\n}\n\nexport interface RunOAuthAuthorizeUrlOptions {\n config: Record<string, unknown>;\n redirectUri: string;\n state: string;\n signal?: AbortSignal;\n}\n\n/** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.buildAuthorizeUrl(ctx, options.config, {\n redirectUri: options.redirectUri,\n state: options.state,\n });\n}\n\nexport interface RunOAuthExchangeCodeOptions {\n config: Record<string, unknown>;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n signal?: AbortSignal;\n}\n\n/** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{ durableCreds: Record<string, unknown> }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.exchangeCode(ctx, options.config, {\n code: options.code,\n redirectUri: options.redirectUri,\n codeVerifier: options.codeVerifier,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAAmB;;;ACDnB,mCAA0B;AAmBnB,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;AAQ9B,SAAS,iBAAiB,YAAsC;AACrE,MAAI,eAAe,QAAW;AAC5B;AAAA,EACF;AACA,MAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,yBAAyB,aAAa,uBAAuB;AAC5G,UAAM,IAAI,uCAAU,eAAe,8BAA8B,qBAAqB,QAAQ,qBAAqB,SAAS,OAAO,UAAU,CAAC,GAAG;AAAA,EACnJ;AACF;AASO,SAAS,mBAAmB,WAAmB,OAAmC,MAAc,OAAqB;AAC1H,aAAW,CAAC,cAAc,aAAa,KAAK,OAAO;AACjD,QAAI,iBAAiB,QAAQ,kBAAkB,OAAO;AACpD,YAAM,IAAI,uCAAU,oBAAoB,IAAI,IAAI,iCAAiC,aAAa,mBAAmB,SAAS,IAAI;AAAA,IAChI;AACA,QAAI,kBAAkB,SAAS,iBAAiB,MAAM;AACpD,YAAM,IAAI,uCAAU,oBAAoB,IAAI,KAAK,iCAAiC,YAAY,mBAAmB,SAAS,IAAI;AAAA,IAChI;AAAA,EACF;AACF;;;AD2CO,SAAS,kBAAkB,UAAoC,CAAC,GAAgB;AACrF,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AACvD,QAAM,EAAE,OAAO,YAAY,IAAI,gB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IACvD,aAAa,QAAQ;AAAA,IACrB,OAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAWA,eAAsB,qBAAqB,YAAyB,SAA0F;AAC5J,MAAI,KAAC,0DAA2B,UAAU,GAAG;AAC3C,UAAM,IAAI,MAAM,GAAG,WAAW,YAAY,IAAI,qCAAqC;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAClD,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["import_vitest","import_vitest","import_integrations_node_sdk","import_vitest"]}
1
+ {"version":3,"sources":["../../src/testing/index.ts","../../src/testing/context.ts","../../src/state-rules.ts","../../src/testing/author.ts","../../src/testing/fetch.ts","../../src/testing/credentials.ts"],"sourcesContent":["export * from './context.js';\nexport * from './author.js';\nexport * from './fetch.js';\nexport * from './credentials.js';\nexport type * from './mock.js';\n","import type { INodeContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\nimport { assertNotRepointed, assertTtlInRange } from '../state-rules.js';\n\n/**\n * Drop-in replacement for the `createMockContext` helper that was, until this\n * package existed, copy-pasted byte-for-byte into every node repo's\n * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with\n * `vi.fn<AnyFn>()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a\n * node's `execute` can be unit-tested in isolation.\n *\n * The state mock is **stateful on purpose**: what the node writes, it reads\n * back. A node's interesting behaviour is precisely the second run — the one\n * that finds the mapping it created the first time — and a mock that forgets\n * would only ever exercise the create branch. It is the one place an author can\n * test writes at all: in the real product, author-time execution is read-only.\n *\n * It reads back *when the store would let it*, which is not the same for all\n * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take\n * effect immediately, a cursor and a digest are staged and adopted only once the\n * run completes. So `cursor.get` after `cursor.set` still answers what the last\n * completed run left — call {@link MockContext.completeRun} between two\n * `execute` calls to play the second run, and leave it uncalled to play the run\n * that failed and left the watermark where it was.\n */\n\nexport type MockLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockSecrets = {\n get: AnyMock;\n};\n\nexport type MockCredentials = {\n get: AnyMock;\n};\n\n/** Every state operation is a `vi.fn<AnyFn>()`, so calls can be asserted on. */\nexport type MockState = {\n mapping: { get: AnyMock; put: AnyMock };\n cursor: { get: AnyMock; set: AnyMock };\n claim: AnyMock;\n digest: { unchanged: AnyMock; set: AnyMock };\n};\n\n/**\n * What the store already knows when the node starts — the \"this ran before\"\n * half of any sync test.\n */\nexport interface MockStateSeed {\n /** namespace -> { leftKey: rightKey }; readable from either side. */\n mappings?: Record<string, Record<string, string>>;\n /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */\n cursors?: Record<string, Record<string, unknown>>;\n /** namespace -> keys already claimed, so `claim` returns false for them. */\n claims?: Record<string, string[]>;\n /** namespace -> { entityKey: digest }. */\n digests?: Record<string, Record<string, string>>;\n}\n\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\n state: MockState;\n /**\n * Adopts what this run staged — the cursors and digests it set — the way the\n * engine does when a run completes. Not part of {@link INodeContext}: it is\n * the harness standing in for the run's own ending, and a node can never call\n * it. A test that never calls it has played a run that did not complete.\n */\n completeRun: () => void;\n};\n\nexport interface CreateMockContextOptions {\n signal?: AbortSignal;\n /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */\n secrets?: Record<string, string>;\n /** When set, `secrets.get` rejects with this error instead of resolving. */\n secretsError?: Error;\n /** Credential instance id -> resolved access data returned by `credentials.get`. */\n credentials?: Record<string, Record<string, unknown>>;\n /** When set, `credentials.get` rejects with this error instead of resolving. */\n credentialsError?: Error;\n /** What the state store already holds when the node starts. */\n state?: MockStateSeed;\n /**\n * When set, every state call rejects with this error — the shape of the\n * engine refusing a namespace the workflow never declared.\n */\n stateError?: Error;\n}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\n const signal = options.signal ?? new AbortController().signal;\n const { state, completeRun } = createMockState(options.state, options.stateError);\n\n const secretsGet = options.secretsError\n ? vi.fn<AnyFn>(async () => {\n throw options.secretsError;\n })\n : vi.fn<AnyFn>(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn<AnyFn>(async () => {\n throw options.credentialsError;\n })\n : vi.fn<AnyFn>(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\n },\n state,\n completeRun,\n };\n}\n\n/**\n * A tiny in-memory stand-in for the four state roles. Seeds are copied rather\n * than referenced, so a test that writes cannot leak into the next one.\n *\n * The write calls split the way the store does. A mapping and a claim land in\n * the committed maps at once; a cursor and a digest land in a staging map that\n * only `completeRun` folds in, so a read during the run answers what the last\n * completed one left. That is the whole reason there are four operations rather\n * than a generic get/set, and a mock that adopted everything immediately would\n * hide the case the rule exists for: the run that fails after advancing its\n * watermark.\n */\nfunction createMockState(seed: MockStateSeed = {}, error?: Error): { state: MockState; completeRun: () => void } {\n const mappings = new Map<string, Map<string, string>>();\n const cursors = new Map<string, Map<string, unknown>>();\n const claims = new Map<string, Set<string>>();\n const digests = new Map<string, Map<string, string>>();\n /** What this run has staged: adopted by `completeRun`, dropped otherwise. */\n const stagedCursors = new Map<string, Map<string, unknown>>();\n const stagedDigests = new Map<string, Map<string, string>>();\n\n for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {\n mappings.set(namespace, new Map(Object.entries(pairs)));\n }\n for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {\n cursors.set(namespace, new Map(Object.entries(partitions)));\n }\n for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {\n claims.set(namespace, new Set(keys));\n }\n for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {\n digests.set(namespace, new Map(Object.entries(entries)));\n }\n\n /** Wraps an operation so `stateError` short-circuits every one of them. */\n const op = <A extends unknown[], R>(fn: (...args: A) => R) =>\n vi.fn(async (...args: A): Promise<R> => {\n if (error) {\n throw error;\n }\n return fn(...args);\n });\n\n const state: MockState = {\n mapping: {\n get: op((namespace: string, key: string, side: 'left' | 'right' = 'left') => {\n const pairs = mappings.get(namespace);\n if (!pairs) {\n return null;\n }\n if (side === 'left') {\n return pairs.get(key) ?? null;\n }\n for (const [left, right] of pairs) {\n if (right === key) {\n return left;\n }\n }\n return null;\n }),\n put: op((namespace: string, left: string, right: string) => {\n const pairs = mappings.get(namespace) ?? new Map<string, string>();\n assertNotRepointed(namespace, pairs, left, right);\n pairs.set(left, right);\n mappings.set(namespace, pairs);\n }),\n },\n cursor: {\n // The committed watermark: what *this* run staged is deliberately not in\n // the answer, exactly as the real store describes it.\n get: op((namespace: string, partitionKey = '') => cursors.get(namespace)?.get(partitionKey)),\n set: op((namespace: string, value: unknown, partitionKey = '') => {\n const partitions = stagedCursors.get(namespace) ?? new Map<string, unknown>();\n partitions.set(partitionKey, value);\n stagedCursors.set(namespace, partitions);\n }),\n },\n // First caller wins, like the real claim — so a test can drive both the\n // fresh and the duplicate path without reconfiguring the mock. A claim is\n // never handed on here: a TTL is a wall-clock window, and no unit test\n // outlives the shortest one the store accepts.\n claim: op((namespace: string, key: string, opts?: { ttlSeconds?: number }) => {\n assertTtlInRange(opts?.ttlSeconds);\n const held = claims.get(namespace) ?? new Set<string>();\n if (held.has(key)) {\n return false;\n }\n held.add(key);\n claims.set(namespace, held);\n return true;\n }),\n digest: {\n unchanged: op((namespace: string, entityKey: string, digest: string) => digests.get(namespace)?.get(entityKey) === digest),\n set: op((namespace: string, entityKey: string, digest: string) => {\n const entries = stagedDigests.get(namespace) ?? new Map<string, string>();\n entries.set(entityKey, digest);\n stagedDigests.set(namespace, entries);\n }),\n },\n };\n\n const completeRun = (): void => {\n for (const [namespace, partitions] of stagedCursors) {\n const committed = cursors.get(namespace) ?? new Map<string, unknown>();\n for (const [partitionKey, value] of partitions) {\n committed.set(partitionKey, value);\n }\n cursors.set(namespace, committed);\n }\n for (const [namespace, entries] of stagedDigests) {\n const committed = digests.get(namespace) ?? new Map<string, string>();\n for (const [entityKey, digest] of entries) {\n committed.set(entityKey, digest);\n }\n digests.set(namespace, committed);\n }\n stagedCursors.clear();\n stagedDigests.clear();\n };\n\n return { state, completeRun };\n}\n","import { NodeError } from '@revenexx/integrations-node-sdk';\n\n/**\n * The two rules the tenant state store keeps that neither the mock context nor\n * the local preview would otherwise have any reason to keep — and both of which\n * a node author only finds out about in production if we do not.\n *\n * They live here rather than in either caller because the testing harness and\n * the preview must refuse the same things: a node that passes its unit tests and\n * then trips the store on its first preview run has learnt nothing from either.\n * The rest of what the store promises — that a granted claim really excludes a\n * parallel run, that an undeclared namespace is refused — is the engine's, and\n * `specs/workflow-state.md` in the SDK records it as such.\n */\n\n/** Mirrors the engine's default claim lifetime (7 days). */\nexport const DEFAULT_CLAIM_TTL_SECONDS = 604_800;\n\n/** The window the store accepts: one second to one year. */\nexport const MIN_CLAIM_TTL_SECONDS = 1;\nexport const MAX_CLAIM_TTL_SECONDS = 31_536_000;\n\n/**\n * A `ttlSeconds` outside the accepted window is refused rather than clamped: the\n * figure is the duplicate-suppression window *and* the retry window, so a node\n * quietly given a different one than it asked for would suppress deliveries for\n * a stretch its author never chose.\n */\nexport function assertTtlInRange(ttlSeconds: number | undefined): void {\n if (ttlSeconds === undefined) {\n return;\n }\n if (!Number.isFinite(ttlSeconds) || ttlSeconds < MIN_CLAIM_TTL_SECONDS || ttlSeconds > MAX_CLAIM_TTL_SECONDS) {\n throw new NodeError('INVALID_TTL', `ttlSeconds must be between ${MIN_CLAIM_TTL_SECONDS} and ${MAX_CLAIM_TTL_SECONDS}, got ${String(ttlSeconds)}.`);\n }\n}\n\n/**\n * Re-pointing one side of an existing pair is refused, in both directions: an id\n * correlated two ways is always a bug, and no later sync can untangle it —\n * whichever of the two answers a lookup happens to give, half the records it\n * touches are the wrong ones. Writing the same pair again is not a re-point and\n * is allowed, so a node that puts unconditionally on every run stays green.\n */\nexport function assertNotRepointed(namespace: string, pairs: Iterable<[string, string]>, left: string, right: string): void {\n for (const [existingLeft, existingRight] of pairs) {\n if (existingLeft === left && existingRight !== right) {\n throw new NodeError('MAPPING_CONFLICT', `'${left}' is already correlated with '${existingRight}' in namespace '${namespace}'.`);\n }\n if (existingRight === right && existingLeft !== left) {\n throw new NodeError('MAPPING_CONFLICT', `'${right}' is already correlated with '${existingLeft}' in namespace '${namespace}'.`);\n }\n }\n}\n","import type { INodeAuthorContext } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*\n * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this\n * package existed, this factory was reinvented inline in each repo's resolver\n * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`\n * are `vi.fn<AnyFn>()`-backed and seedable.\n */\n\nexport type MockAuthorLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockAuthorContext = INodeAuthorContext & {\n logger: MockAuthorLogger;\n secrets: { get: AnyMock };\n credentials: { get: AnyMock };\n};\n\nexport interface CreateAuthorContextOptions {\n signal?: AbortSignal;\n /** Preferred locale for resolved labels. */\n locale?: string;\n secrets?: Record<string, string>;\n secretsError?: Error;\n credentials?: Record<string, Record<string, unknown>>;\n credentialsError?: Error;\n}\n\nexport function createAuthorContext(config: Record<string, unknown> = {}, options: CreateAuthorContextOptions = {}): MockAuthorContext {\n const signal = options.signal ?? new AbortController().signal;\n\n const secretsGet = options.secretsError\n ? vi.fn<AnyFn>(async () => {\n throw options.secretsError;\n })\n : vi.fn<AnyFn>(async (key: string) => {\n if (options.secrets && key in options.secrets) {\n return options.secrets[key];\n }\n return `secret-value-for-${key}`;\n });\n\n const credentialsGet = options.credentialsError\n ? vi.fn<AnyFn>(async () => {\n throw options.credentialsError;\n })\n : vi.fn<AnyFn>(async (id: string) => {\n if (options.credentials && id in options.credentials) {\n return options.credentials[id];\n }\n return {};\n });\n\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n config,\n secrets: { get: secretsGet },\n credentials: { get: credentialsGet },\n locale: options.locale,\n };\n}\n","import { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Utilities for stubbing the global `fetch` so a credential's `resolve` /\n * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a\n * node's `execute` (which uses `safeFetch` → global `fetch`) can be\n * unit-tested without touching the network. Builds real `Response` objects so\n * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as\n * in production.\n */\n\nexport interface StubResponseInit {\n status?: number;\n headers?: Record<string, string>;\n /** JSON body — serialized and served as `application/json` unless `body` is set. */\n json?: unknown;\n /** Raw string body. Takes precedence over `json`. */\n body?: string;\n}\n\nexport interface StubbedRequest {\n url: string;\n method: string;\n init?: RequestInit;\n}\n\nexport type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;\n\n/** Builds a real `Response` from a {@link StubResponseInit}. */\nexport function buildResponse(init: StubResponseInit): Response {\n const headers = new Headers(init.headers ?? {});\n let body: string | undefined;\n if (init.body !== undefined) {\n body = init.body;\n } else if (init.json !== undefined) {\n body = JSON.stringify(init.json);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n }\n return new Response(body, { status: init.status ?? 200, headers });\n}\n\nexport interface StubFetchResult {\n /** The `vi.fn<AnyFn>()` installed as `globalThis.fetch` — assert calls on it. */\n fetchMock: AnyMock;\n /** Restores the previous `globalThis.fetch`. */\n restore(): void;\n}\n\n/**\n * Replaces `globalThis.fetch` with a `vi.fn<AnyFn>()` driven by `handler`. Pass a\n * static {@link StubResponseInit} to answer every request identically, or a\n * {@link FetchHandler} to branch on url/method. Call `restore()` when done\n * (e.g. in `afterEach`).\n */\nexport function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult {\n const previous = globalThis.fetch;\n const resolveInit: FetchHandler = typeof handler === 'function' ? handler : () => handler;\n\n const fetchMock = vi.fn<AnyFn>(async (input: RequestInfo | URL, init?: RequestInit) => {\n const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();\n const out = await resolveInit({ url, method, init });\n return out instanceof Response ? out : buildResponse(out);\n });\n\n globalThis.fetch = fetchMock as unknown as typeof fetch;\n return {\n fetchMock,\n restore() {\n globalThis.fetch = previous;\n },\n };\n}\n\nexport interface FakeTokenEndpointOptions {\n /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */\n tokenUrl?: string;\n accessToken?: string;\n tokenType?: string;\n /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */\n expiresIn?: number | null;\n /** Included as `refresh_token` when set (e.g. to assert rotation). */\n refreshToken?: string;\n /** Extra fields merged into the token response body. */\n extra?: Record<string, unknown>;\n}\n\n/**\n * A {@link FetchHandler} that emulates an OAuth token endpoint, returning\n * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with\n * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth\n * `exchangeCode`.\n */\nexport function fakeTokenEndpoint(options: FakeTokenEndpointOptions = {}): FetchHandler {\n const { tokenUrl, accessToken = 'fake-access-token', tokenType = 'Bearer', expiresIn = 3600, refreshToken, extra } = options;\n\n return ({ url }) => {\n if (tokenUrl && url !== tokenUrl) {\n return { status: 404, json: { error: `no stub for ${url}` } };\n }\n const json: Record<string, unknown> = {\n access_token: accessToken,\n token_type: tokenType,\n ...(expiresIn !== null ? { expires_in: expiresIn } : {}),\n ...(refreshToken !== undefined ? { refresh_token: refreshToken } : {}),\n ...extra,\n };\n return { status: 200, json };\n };\n}\n","import type { ICredential, ICredentialContext, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';\nimport { isOAuthAuthorizeCredential } from '@revenexx/integrations-node-sdk';\nimport { vi } from 'vitest';\nimport type { AnyFn, AnyMock } from './mock.js';\n\n/**\n * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged\n * OAuth without the credentials broker or a real provider. Combine with\n * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,\n * and inspect the returned `persistDurableCreds` spy to assert refresh-token\n * rotation.\n */\n\nexport type MockCredentialLogger = {\n info: AnyMock;\n warn: AnyMock;\n error: AnyMock;\n};\n\nexport type MockCredentialContext = ICredentialContext & {\n logger: MockCredentialLogger;\n /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */\n persistDurableCreds: AnyMock;\n};\n\nexport interface CreateCredentialContextOptions {\n signal?: AbortSignal;\n}\n\nexport function createCredentialContext(options: CreateCredentialContextOptions = {}): MockCredentialContext {\n const signal = options.signal ?? new AbortController().signal;\n const persistDurableCreds = vi.fn<AnyFn>(async (_durableCreds: Record<string, unknown>) => {});\n return {\n signal,\n logger: {\n info: vi.fn<AnyFn>(),\n warn: vi.fn<AnyFn>(),\n error: vi.fn<AnyFn>(),\n },\n persistDurableCreds,\n };\n}\n\nexport interface RunCredentialTestOptions {\n config: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Runs a credential's `test(ctx, config)` and returns its result. */\nexport async function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.test(ctx, options.config);\n}\n\nexport interface RunCredentialResolveOptions {\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */\n durableCreds?: Record<string, unknown> | null;\n signal?: AbortSignal;\n}\n\nexport interface RunCredentialResolveResult {\n result: ICredentialResolveResult;\n /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */\n persistDurableCreds: AnyMock;\n /** The context used, for further assertions (logger calls, etc.). */\n ctx: MockCredentialContext;\n}\n\n/** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */\nexport async function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult> {\n const ctx = createCredentialContext({ signal: options.signal });\n const result = await credential.resolve(ctx, options.config, options.durableCreds ?? null);\n return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };\n}\n\nexport interface RunOAuthAuthorizeUrlOptions {\n config: Record<string, unknown>;\n redirectUri: string;\n state: string;\n signal?: AbortSignal;\n}\n\n/** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.buildAuthorizeUrl(ctx, options.config, {\n redirectUri: options.redirectUri,\n state: options.state,\n });\n}\n\nexport interface RunOAuthExchangeCodeOptions {\n config: Record<string, unknown>;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n signal?: AbortSignal;\n}\n\n/** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */\nexport async function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{ durableCreds: Record<string, unknown> }> {\n if (!isOAuthAuthorizeCredential(credential)) {\n throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);\n }\n const ctx = createCredentialContext({ signal: options.signal });\n return credential.exchang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;AAAA,EACrF;AACA,QAAM,MAAM,wBAAwB,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAC9D,SAAO,WAAW,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAClD,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["import_vitest","import_vitest","import_integrations_node_sdk","import_vitest"]}
@@ -1,253 +1,5 @@
1
- import { INodeContext, INodeAuthorContext, ICredentialContext, ICredentialResolveResult, ICredential, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
2
- import { vi } from 'vitest';
3
-
4
- /**
5
- * Drop-in replacement for the `createMockContext` helper that was, until this
6
- * package existed, copy-pasted byte-for-byte into every node repo's
7
- * `tests/helpers/context.ts`. Builds a full {@link INodeContext} with
8
- * `vi.fn()`-backed `logger`, `secrets.get`, `credentials.get` and `state` so a
9
- * node's `execute` can be unit-tested in isolation.
10
- *
11
- * The state mock is **stateful on purpose**: what the node writes, it reads
12
- * back. A node's interesting behaviour is precisely the second run — the one
13
- * that finds the mapping it created the first time — and a mock that forgets
14
- * would only ever exercise the create branch. It is the one place an author can
15
- * test writes at all: in the real product, author-time execution is read-only.
16
- *
17
- * It reads back *when the store would let it*, which is not the same for all
18
- * four roles (SDK 1.0.0, `specs/workflow-state.md`): a mapping and a claim take
19
- * effect immediately, a cursor and a digest are staged and adopted only once the
20
- * run completes. So `cursor.get` after `cursor.set` still answers what the last
21
- * completed run left — call {@link MockContext.completeRun} between two
22
- * `execute` calls to play the second run, and leave it uncalled to play the run
23
- * that failed and left the watermark where it was.
24
- */
25
- type MockLogger = {
26
- info: ReturnType<typeof vi.fn>;
27
- warn: ReturnType<typeof vi.fn>;
28
- error: ReturnType<typeof vi.fn>;
29
- };
30
- type MockSecrets = {
31
- get: ReturnType<typeof vi.fn>;
32
- };
33
- type MockCredentials = {
34
- get: ReturnType<typeof vi.fn>;
35
- };
36
- /** Every state operation is a `vi.fn()`, so calls can be asserted on. */
37
- type MockState = {
38
- mapping: {
39
- get: ReturnType<typeof vi.fn>;
40
- put: ReturnType<typeof vi.fn>;
41
- };
42
- cursor: {
43
- get: ReturnType<typeof vi.fn>;
44
- set: ReturnType<typeof vi.fn>;
45
- };
46
- claim: ReturnType<typeof vi.fn>;
47
- digest: {
48
- unchanged: ReturnType<typeof vi.fn>;
49
- set: ReturnType<typeof vi.fn>;
50
- };
51
- };
52
- /**
53
- * What the store already knows when the node starts — the "this ran before"
54
- * half of any sync test.
55
- */
56
- interface MockStateSeed {
57
- /** namespace -> { leftKey: rightKey }; readable from either side. */
58
- mappings?: Record<string, Record<string, string>>;
59
- /** namespace -> partitionKey ('' for the unpartitioned one) -> watermark. */
60
- cursors?: Record<string, Record<string, unknown>>;
61
- /** namespace -> keys already claimed, so `claim` returns false for them. */
62
- claims?: Record<string, string[]>;
63
- /** namespace -> { entityKey: digest }. */
64
- digests?: Record<string, Record<string, string>>;
65
- }
66
- type MockContext = INodeContext & {
67
- logger: MockLogger;
68
- secrets: MockSecrets;
69
- credentials: MockCredentials;
70
- state: MockState;
71
- /**
72
- * Adopts what this run staged — the cursors and digests it set — the way the
73
- * engine does when a run completes. Not part of {@link INodeContext}: it is
74
- * the harness standing in for the run's own ending, and a node can never call
75
- * it. A test that never calls it has played a run that did not complete.
76
- */
77
- completeRun: () => void;
78
- };
79
- interface CreateMockContextOptions {
80
- signal?: AbortSignal;
81
- /** Secret key -> value returned by `secrets.get`. Unknown keys fall back to a deterministic stub. */
82
- secrets?: Record<string, string>;
83
- /** When set, `secrets.get` rejects with this error instead of resolving. */
84
- secretsError?: Error;
85
- /** Credential instance id -> resolved access data returned by `credentials.get`. */
86
- credentials?: Record<string, Record<string, unknown>>;
87
- /** When set, `credentials.get` rejects with this error instead of resolving. */
88
- credentialsError?: Error;
89
- /** What the state store already holds when the node starts. */
90
- state?: MockStateSeed;
91
- /**
92
- * When set, every state call rejects with this error — the shape of the
93
- * engine refusing a namespace the workflow never declared.
94
- */
95
- stateError?: Error;
96
- }
97
- declare function createMockContext(options?: CreateMockContextOptions): MockContext;
98
-
99
- /**
100
- * Builds an {@link INodeAuthorContext} for unit-testing a node's *author-time*
101
- * resolvers (`loadOptions`, `resolveConfigSchema`, `resolveOutputs`). Until this
102
- * package existed, this factory was reinvented inline in each repo's resolver
103
- * tests. Mirrors {@link createMockContext}: `secrets.get` / `credentials.get`
104
- * are `vi.fn()`-backed and seedable.
105
- */
106
- type MockAuthorLogger = {
107
- info: ReturnType<typeof vi.fn>;
108
- warn: ReturnType<typeof vi.fn>;
109
- error: ReturnType<typeof vi.fn>;
110
- };
111
- type MockAuthorContext = INodeAuthorContext & {
112
- logger: MockAuthorLogger;
113
- secrets: {
114
- get: ReturnType<typeof vi.fn>;
115
- };
116
- credentials: {
117
- get: ReturnType<typeof vi.fn>;
118
- };
119
- };
120
- interface CreateAuthorContextOptions {
121
- signal?: AbortSignal;
122
- /** Preferred locale for resolved labels. */
123
- locale?: string;
124
- secrets?: Record<string, string>;
125
- secretsError?: Error;
126
- credentials?: Record<string, Record<string, unknown>>;
127
- credentialsError?: Error;
128
- }
129
- declare function createAuthorContext(config?: Record<string, unknown>, options?: CreateAuthorContextOptions): MockAuthorContext;
130
-
131
- /**
132
- * Utilities for stubbing the global `fetch` so a credential's `resolve` /
133
- * `test` (which reach an OAuth token endpoint via the SDK's `postForm`) or a
134
- * node's `execute` (which uses `safeFetch` → global `fetch`) can be
135
- * unit-tested without touching the network. Builds real `Response` objects so
136
- * `res.ok` / `res.status` / `res.text()` / `res.json()` all behave exactly as
137
- * in production.
138
- */
139
- interface StubResponseInit {
140
- status?: number;
141
- headers?: Record<string, string>;
142
- /** JSON body — serialized and served as `application/json` unless `body` is set. */
143
- json?: unknown;
144
- /** Raw string body. Takes precedence over `json`. */
145
- body?: string;
146
- }
147
- interface StubbedRequest {
148
- url: string;
149
- method: string;
150
- init?: RequestInit;
151
- }
152
- type FetchHandler = (request: StubbedRequest) => StubResponseInit | Response | Promise<StubResponseInit | Response>;
153
- /** Builds a real `Response` from a {@link StubResponseInit}. */
154
- declare function buildResponse(init: StubResponseInit): Response;
155
- interface StubFetchResult {
156
- /** The `vi.fn()` installed as `globalThis.fetch` — assert calls on it. */
157
- fetchMock: ReturnType<typeof vi.fn>;
158
- /** Restores the previous `globalThis.fetch`. */
159
- restore(): void;
160
- }
161
- /**
162
- * Replaces `globalThis.fetch` with a `vi.fn()` driven by `handler`. Pass a
163
- * static {@link StubResponseInit} to answer every request identically, or a
164
- * {@link FetchHandler} to branch on url/method. Call `restore()` when done
165
- * (e.g. in `afterEach`).
166
- */
167
- declare function stubFetch(handler: FetchHandler | StubResponseInit): StubFetchResult;
168
- interface FakeTokenEndpointOptions {
169
- /** Only answer requests to this exact URL; other requests 404. Omit to answer any URL. */
170
- tokenUrl?: string;
171
- accessToken?: string;
172
- tokenType?: string;
173
- /** Seconds until expiry (OAuth `expires_in`). Set `null` to omit the field. */
174
- expiresIn?: number | null;
175
- /** Included as `refresh_token` when set (e.g. to assert rotation). */
176
- refreshToken?: string;
177
- /** Extra fields merged into the token response body. */
178
- extra?: Record<string, unknown>;
179
- }
180
- /**
181
- * A {@link FetchHandler} that emulates an OAuth token endpoint, returning
182
- * `{ access_token, token_type, expires_in, refresh_token? }`. Compose with
183
- * {@link stubFetch} to unit-test `oauth2-*` credentials' `resolve` / OAuth
184
- * `exchangeCode`.
185
- */
186
- declare function fakeTokenEndpoint(options?: FakeTokenEndpointOptions): FetchHandler;
187
-
188
- /**
189
- * Harness for unit-testing a credential type's `test` / `resolve` / 3-legged
190
- * OAuth without the credentials broker or a real provider. Combine with
191
- * {@link stubFetch} / {@link fakeTokenEndpoint} to drive the token endpoint,
192
- * and inspect the returned `persistDurableCreds` spy to assert refresh-token
193
- * rotation.
194
- */
195
- type MockCredentialLogger = {
196
- info: ReturnType<typeof vi.fn>;
197
- warn: ReturnType<typeof vi.fn>;
198
- error: ReturnType<typeof vi.fn>;
199
- };
200
- type MockCredentialContext = ICredentialContext & {
201
- logger: MockCredentialLogger;
202
- /** Spy wired to `ctx.persistDurableCreds`; assert `.toHaveBeenCalledWith(...)`. */
203
- persistDurableCreds: ReturnType<typeof vi.fn>;
204
- };
205
- interface CreateCredentialContextOptions {
206
- signal?: AbortSignal;
207
- }
208
- declare function createCredentialContext(options?: CreateCredentialContextOptions): MockCredentialContext;
209
- interface RunCredentialTestOptions {
210
- config: Record<string, unknown>;
211
- signal?: AbortSignal;
212
- }
213
- /** Runs a credential's `test(ctx, config)` and returns its result. */
214
- declare function runCredentialTest(credential: ICredential, options: RunCredentialTestOptions): Promise<ICredentialTestResult>;
215
- interface RunCredentialResolveOptions {
216
- config: Record<string, unknown>;
217
- /** System-managed long-lived secrets (e.g. an OAuth `refresh_token`). */
218
- durableCreds?: Record<string, unknown> | null;
219
- signal?: AbortSignal;
220
- }
221
- interface RunCredentialResolveResult {
222
- result: ICredentialResolveResult;
223
- /** Spy wired to `ctx.persistDurableCreds` — assert rotation happened. */
224
- persistDurableCreds: ReturnType<typeof vi.fn>;
225
- /** The context used, for further assertions (logger calls, etc.). */
226
- ctx: MockCredentialContext;
227
- }
228
- /** Runs a credential's `resolve(ctx, config, durableCreds)` and captures rotation. */
229
- declare function runCredentialResolve(credential: ICredential, options: RunCredentialResolveOptions): Promise<RunCredentialResolveResult>;
230
- interface RunOAuthAuthorizeUrlOptions {
231
- config: Record<string, unknown>;
232
- redirectUri: string;
233
- state: string;
234
- signal?: AbortSignal;
235
- }
236
- /** Runs `buildAuthorizeUrl` on a 3-legged OAuth credential; throws if unsupported. */
237
- declare function runOAuthAuthorizeUrl(credential: ICredential, options: RunOAuthAuthorizeUrlOptions): Promise<{
238
- authorizeUrl: string;
239
- codeVerifier?: string;
240
- }>;
241
- interface RunOAuthExchangeCodeOptions {
242
- config: Record<string, unknown>;
243
- code: string;
244
- redirectUri: string;
245
- codeVerifier?: string;
246
- signal?: AbortSignal;
247
- }
248
- /** Runs `exchangeCode` on a 3-legged OAuth credential; throws if unsupported. */
249
- declare function runOAuthExchangeCode(credential: ICredential, options: RunOAuthExchangeCodeOptions): Promise<{
250
- durableCreds: Record<string, unknown>;
251
- }>;
252
-
253
- export { type CreateAuthorContextOptions, type CreateCredentialContextOptions, type CreateMockContextOptions, type FakeTokenEndpointOptions, type FetchHandler, type MockAuthorContext, type MockAuthorLogger, type MockContext, type MockCredentialContext, type MockCredentialLogger, type MockCredentials, type MockLogger, type MockSecrets, type MockState, type MockStateSeed, type RunCredentialResolveOptions, type RunCredentialResolveResult, type RunCredentialTestOptions, type RunOAuthAuthorizeUrlOptions, type RunOAuthExchangeCodeOptions, type StubFetchResult, type StubResponseInit, type StubbedRequest, buildResponse, createAuthorContext, createCredentialContext, createMockContext, fakeTokenEndpoint, runCredentialResolve, runCredentialTest, runOAuthAuthorizeUrl, runOAuthExchangeCode, stubFetch };
1
+ export * from './context.js';
2
+ export * from './author.js';
3
+ export * from './fetch.js';
4
+ export * from './credentials.js';
5
+ export type * from './mock.js';