@revenexx/integrations-node-devkit 0.6.0 → 0.8.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.
- package/README.md +74 -0
- package/dist/chunk-PME34X7E.js +30 -0
- package/dist/chunk-PME34X7E.js.map +1 -0
- package/dist/{chunk-YXIYTBOZ.js → chunk-YUUW37NC.js} +179 -13
- package/dist/chunk-YUUW37NC.js.map +1 -0
- package/dist/cli.cjs +199 -15
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +201 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +56 -6
- package/dist/index.d.ts +56 -6
- package/dist/index.js +4 -1
- package/dist/testing/index.cjs +133 -3
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +62 -3
- package/dist/testing/index.d.ts +62 -3
- package/dist/testing/index.js +110 -0
- package/dist/testing/index.js.map +1 -1
- package/package.json +6 -6
- package/preview-host/package.json +2 -2
- package/preview-host/pages/nodes.vue +29 -0
- package/dist/chunk-YXIYTBOZ.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { INode, ICredential, ITemplateDescription, NodeManifest, IConfigOption, IConfigField, IOutputPort, ICredentialDescription, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
|
|
1
|
+
import { INode, ICredential, ITemplateDescription, NodeManifest, IConfigOption, IConfigField, IOutputPort, ICredentialDescription, INodeDescription, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
|
|
2
2
|
import http from 'node:http';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -190,27 +190,48 @@ interface TriggerRecord {
|
|
|
190
190
|
createdAt: string;
|
|
191
191
|
updatedAt: string;
|
|
192
192
|
}
|
|
193
|
+
/**
|
|
194
|
+
* One entry of the tenant state store (PO-374), flattened across the four
|
|
195
|
+
* roles: `key` is the mapping's left id, the cursor's partition key, the
|
|
196
|
+
* claimed key or the digest's entity key, and `value` the partner id, the
|
|
197
|
+
* watermark, the expiry or the hash.
|
|
198
|
+
*
|
|
199
|
+
* The mock keeps them in one list rather than four tables because nothing here
|
|
200
|
+
* enforces integrity — the real store's constraints are the product, this is a
|
|
201
|
+
* scratchpad that makes a node's second run behave like a second run.
|
|
202
|
+
*/
|
|
203
|
+
interface StateEntryRecord {
|
|
204
|
+
namespace: string;
|
|
205
|
+
role: 'mapping' | 'cursor' | 'dedupe' | 'digest';
|
|
206
|
+
key: string;
|
|
207
|
+
value: unknown;
|
|
208
|
+
updatedAt: string;
|
|
209
|
+
}
|
|
193
210
|
interface DevStoreSnapshot {
|
|
194
211
|
schemaVersion: number;
|
|
195
212
|
credentials: CredentialRecord[];
|
|
196
213
|
secrets: SecretRecord[];
|
|
197
214
|
workflows: WorkflowRecord[];
|
|
198
215
|
triggers: TriggerRecord[];
|
|
216
|
+
stateEntries?: StateEntryRecord[];
|
|
199
217
|
nextWorkflowId: number;
|
|
200
218
|
}
|
|
201
219
|
/**
|
|
202
220
|
* Bumped to 2 when workflows moved from `definition` to the contract's `blob` /
|
|
203
|
-
* `blob_definition_version` / `active` / `execution_mode
|
|
204
|
-
*
|
|
205
|
-
*
|
|
221
|
+
* `blob_definition_version` / `active` / `execution_mode`, and to 3 when the
|
|
222
|
+
* state store (PO-374) arrived. `loadState` discards an overlay whose version
|
|
223
|
+
* does not match, which is the migration: seeds are the source of truth, the
|
|
224
|
+
* overlay is disposable session state.
|
|
206
225
|
*/
|
|
207
|
-
declare const STORE_SCHEMA_VERSION =
|
|
226
|
+
declare const STORE_SCHEMA_VERSION = 3;
|
|
208
227
|
declare class DevStore {
|
|
209
228
|
private onChange?;
|
|
210
229
|
private credentials;
|
|
211
230
|
private secrets;
|
|
212
231
|
private workflows;
|
|
213
232
|
private triggers;
|
|
233
|
+
/** Keyed by `${role}\u0000${namespace}\u0000${key}` — a NUL occurs in no part. */
|
|
234
|
+
private stateEntries;
|
|
214
235
|
private nextWorkflowId;
|
|
215
236
|
/**
|
|
216
237
|
* @param onChange fired after any mutation so a caller (the CLI) can persist
|
|
@@ -274,6 +295,11 @@ declare class DevStore {
|
|
|
274
295
|
active?: boolean;
|
|
275
296
|
}): TriggerRecord | undefined;
|
|
276
297
|
deleteTrigger(id: string): boolean;
|
|
298
|
+
/** The stored entry for a role/namespace/key, or undefined when unknown. */
|
|
299
|
+
getStateEntry(role: StateEntryRecord['role'], namespace: string, key: string): StateEntryRecord | undefined;
|
|
300
|
+
/** Every entry a namespace holds in one role — how a reverse mapping lookup is answered. */
|
|
301
|
+
listStateEntries(role: StateEntryRecord['role'], namespace: string): StateEntryRecord[];
|
|
302
|
+
putStateEntry(entry: Omit<StateEntryRecord, 'updatedAt'>): StateEntryRecord;
|
|
277
303
|
toSnapshot(): DevStoreSnapshot;
|
|
278
304
|
loadSnapshot(snapshot: DevStoreSnapshot): void;
|
|
279
305
|
/**
|
|
@@ -346,6 +372,22 @@ declare function saveState(file: string, snapshot: DevStoreSnapshot): void;
|
|
|
346
372
|
declare function loadSeedsFromDir(dir: string): Promise<DevSeeds>;
|
|
347
373
|
|
|
348
374
|
declare function nodeVersions(loaded: LoadedPackage, slug: string): string[];
|
|
375
|
+
/**
|
|
376
|
+
* The order `GET /nodes` lists a package's nodes in: every version of a slug
|
|
377
|
+
* together, newest first, with the slugs themselves in the order the package
|
|
378
|
+
* exports them.
|
|
379
|
+
*
|
|
380
|
+
* Export order alone is not enough any more. The registry answers each slug's
|
|
381
|
+
* versions semver-descending, and the studio's catalogue takes that order as
|
|
382
|
+
* given rather than parsing a semver of its own — since
|
|
383
|
+
* `@revenexx/studio-integrations` 1.3.0 `newerExecutableVersions()` reads "newer
|
|
384
|
+
* than the pinned one" as "earlier in this array". A package that exports 1.0.0
|
|
385
|
+
* before 2.0.0 — the order a human writes them in — would therefore have the
|
|
386
|
+
* inspector announce the OLDER version as the upgrade, and say nothing about the
|
|
387
|
+
* real one. `GET /nodes/{slug}/versions` has always sorted; this is the same
|
|
388
|
+
* order on the listing the catalogue is actually built from.
|
|
389
|
+
*/
|
|
390
|
+
declare function listNodesNewestFirst(nodes: readonly INodeDescription[]): INodeDescription[];
|
|
349
391
|
declare function findNode(loaded: LoadedPackage, slug: string, version?: string): INode;
|
|
350
392
|
declare function findCredential(loaded: LoadedPackage, slug: string): ICredential;
|
|
351
393
|
declare function findCredentialType(loaded: LoadedPackage, slug: string): ICredentialDescription;
|
|
@@ -387,6 +429,14 @@ interface ValidateNodeConfigResult {
|
|
|
387
429
|
* flattened keys. Deep cross-field validation is intentionally out of scope
|
|
388
430
|
* (the production service does that on save); this mirrors the mock's
|
|
389
431
|
* "light, schema-based" fidelity. Unknown extra keys are ignored.
|
|
432
|
+
*
|
|
433
|
+
* A field whose `showIf` does not hold (SDK 1.0.0, PO-410) is skipped whole —
|
|
434
|
+
* not demanded when required, and not type-checked either. The editor does not
|
|
435
|
+
* draw it, so whatever is left under its key is a leftover from a choice the
|
|
436
|
+
* author has since changed, and refusing to save because of it would leave them
|
|
437
|
+
* with an error against a field they cannot see. `settingApplies` comes from the
|
|
438
|
+
* SDK rather than being re-implemented here: the editor drawing the field and
|
|
439
|
+
* this validator deciding whether to demand it have to agree word for word.
|
|
390
440
|
*/
|
|
391
441
|
declare function validateNodeConfig(loaded: LoadedPackage, store: DevStore, input: ValidateNodeConfigInput): Promise<ValidateNodeConfigResult>;
|
|
392
442
|
/** Runs a credential type's `test` against inline (unsaved) config. */
|
|
@@ -429,4 +479,4 @@ declare function createDevServer(deps: DevServerDeps): http.Server;
|
|
|
429
479
|
*/
|
|
430
480
|
declare const DEVKIT_VERSION: string;
|
|
431
481
|
|
|
432
|
-
export { type CredentialRecord, type CredentialSeed, DEVKIT_VERSION, DEV_TENANT_ID, DevApiError, type DevSeeds, type DevServerDeps, DevStore, type DevStoreSnapshot, ENV_FILE_MIN_NODE, type EnvFileChoice, type LoadEnvFileOptions, type LoadedPackage, type ResolveNodeConfigInput, type ResolveNodeConfigResult, STORE_SCHEMA_VERSION, type SecretRecord, type SecretSeed, type TriggerRecord, type ValidateNodeConfigInput, type ValidateNodeConfigResult, type WorkflowRecord, type WorkflowSeed, applySeeds, buildOAuthAuthorizeUrl, createDevServer, createRequestListener, ensureTsxRegistered, exchangeOAuthCode, findCredential, findCredentialType, findNode, importFresh, interpolateEnv, loadEnvFile, loadPackageFromEntry, loadSeedsFromDir, loadState, nodeOwnedEnvFlag, nodeVersions, resolveCredentialInstance, resolveEnvFile, resolveExports, resolveNodeConfig, saveState, testCredentialConfig, testCredentialInstance, validateNodeConfig };
|
|
482
|
+
export { type CredentialRecord, type CredentialSeed, DEVKIT_VERSION, DEV_TENANT_ID, DevApiError, type DevSeeds, type DevServerDeps, DevStore, type DevStoreSnapshot, ENV_FILE_MIN_NODE, type EnvFileChoice, type LoadEnvFileOptions, type LoadedPackage, type ResolveNodeConfigInput, type ResolveNodeConfigResult, STORE_SCHEMA_VERSION, type SecretRecord, type SecretSeed, type TriggerRecord, type ValidateNodeConfigInput, type ValidateNodeConfigResult, type WorkflowRecord, type WorkflowSeed, applySeeds, buildOAuthAuthorizeUrl, createDevServer, createRequestListener, ensureTsxRegistered, exchangeOAuthCode, findCredential, findCredentialType, findNode, importFresh, interpolateEnv, listNodesNewestFirst, loadEnvFile, loadPackageFromEntry, loadSeedsFromDir, loadState, nodeOwnedEnvFlag, nodeVersions, resolveCredentialInstance, resolveEnvFile, resolveExports, resolveNodeConfig, saveState, testCredentialConfig, testCredentialInstance, validateNodeConfig };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { INode, ICredential, ITemplateDescription, NodeManifest, IConfigOption, IConfigField, IOutputPort, ICredentialDescription, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
|
|
1
|
+
import { INode, ICredential, ITemplateDescription, NodeManifest, IConfigOption, IConfigField, IOutputPort, ICredentialDescription, INodeDescription, ICredentialResolveResult, ICredentialTestResult } from '@revenexx/integrations-node-sdk';
|
|
2
2
|
import http from 'node:http';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -190,27 +190,48 @@ interface TriggerRecord {
|
|
|
190
190
|
createdAt: string;
|
|
191
191
|
updatedAt: string;
|
|
192
192
|
}
|
|
193
|
+
/**
|
|
194
|
+
* One entry of the tenant state store (PO-374), flattened across the four
|
|
195
|
+
* roles: `key` is the mapping's left id, the cursor's partition key, the
|
|
196
|
+
* claimed key or the digest's entity key, and `value` the partner id, the
|
|
197
|
+
* watermark, the expiry or the hash.
|
|
198
|
+
*
|
|
199
|
+
* The mock keeps them in one list rather than four tables because nothing here
|
|
200
|
+
* enforces integrity — the real store's constraints are the product, this is a
|
|
201
|
+
* scratchpad that makes a node's second run behave like a second run.
|
|
202
|
+
*/
|
|
203
|
+
interface StateEntryRecord {
|
|
204
|
+
namespace: string;
|
|
205
|
+
role: 'mapping' | 'cursor' | 'dedupe' | 'digest';
|
|
206
|
+
key: string;
|
|
207
|
+
value: unknown;
|
|
208
|
+
updatedAt: string;
|
|
209
|
+
}
|
|
193
210
|
interface DevStoreSnapshot {
|
|
194
211
|
schemaVersion: number;
|
|
195
212
|
credentials: CredentialRecord[];
|
|
196
213
|
secrets: SecretRecord[];
|
|
197
214
|
workflows: WorkflowRecord[];
|
|
198
215
|
triggers: TriggerRecord[];
|
|
216
|
+
stateEntries?: StateEntryRecord[];
|
|
199
217
|
nextWorkflowId: number;
|
|
200
218
|
}
|
|
201
219
|
/**
|
|
202
220
|
* Bumped to 2 when workflows moved from `definition` to the contract's `blob` /
|
|
203
|
-
* `blob_definition_version` / `active` / `execution_mode
|
|
204
|
-
*
|
|
205
|
-
*
|
|
221
|
+
* `blob_definition_version` / `active` / `execution_mode`, and to 3 when the
|
|
222
|
+
* state store (PO-374) arrived. `loadState` discards an overlay whose version
|
|
223
|
+
* does not match, which is the migration: seeds are the source of truth, the
|
|
224
|
+
* overlay is disposable session state.
|
|
206
225
|
*/
|
|
207
|
-
declare const STORE_SCHEMA_VERSION =
|
|
226
|
+
declare const STORE_SCHEMA_VERSION = 3;
|
|
208
227
|
declare class DevStore {
|
|
209
228
|
private onChange?;
|
|
210
229
|
private credentials;
|
|
211
230
|
private secrets;
|
|
212
231
|
private workflows;
|
|
213
232
|
private triggers;
|
|
233
|
+
/** Keyed by `${role}\u0000${namespace}\u0000${key}` — a NUL occurs in no part. */
|
|
234
|
+
private stateEntries;
|
|
214
235
|
private nextWorkflowId;
|
|
215
236
|
/**
|
|
216
237
|
* @param onChange fired after any mutation so a caller (the CLI) can persist
|
|
@@ -274,6 +295,11 @@ declare class DevStore {
|
|
|
274
295
|
active?: boolean;
|
|
275
296
|
}): TriggerRecord | undefined;
|
|
276
297
|
deleteTrigger(id: string): boolean;
|
|
298
|
+
/** The stored entry for a role/namespace/key, or undefined when unknown. */
|
|
299
|
+
getStateEntry(role: StateEntryRecord['role'], namespace: string, key: string): StateEntryRecord | undefined;
|
|
300
|
+
/** Every entry a namespace holds in one role — how a reverse mapping lookup is answered. */
|
|
301
|
+
listStateEntries(role: StateEntryRecord['role'], namespace: string): StateEntryRecord[];
|
|
302
|
+
putStateEntry(entry: Omit<StateEntryRecord, 'updatedAt'>): StateEntryRecord;
|
|
277
303
|
toSnapshot(): DevStoreSnapshot;
|
|
278
304
|
loadSnapshot(snapshot: DevStoreSnapshot): void;
|
|
279
305
|
/**
|
|
@@ -346,6 +372,22 @@ declare function saveState(file: string, snapshot: DevStoreSnapshot): void;
|
|
|
346
372
|
declare function loadSeedsFromDir(dir: string): Promise<DevSeeds>;
|
|
347
373
|
|
|
348
374
|
declare function nodeVersions(loaded: LoadedPackage, slug: string): string[];
|
|
375
|
+
/**
|
|
376
|
+
* The order `GET /nodes` lists a package's nodes in: every version of a slug
|
|
377
|
+
* together, newest first, with the slugs themselves in the order the package
|
|
378
|
+
* exports them.
|
|
379
|
+
*
|
|
380
|
+
* Export order alone is not enough any more. The registry answers each slug's
|
|
381
|
+
* versions semver-descending, and the studio's catalogue takes that order as
|
|
382
|
+
* given rather than parsing a semver of its own — since
|
|
383
|
+
* `@revenexx/studio-integrations` 1.3.0 `newerExecutableVersions()` reads "newer
|
|
384
|
+
* than the pinned one" as "earlier in this array". A package that exports 1.0.0
|
|
385
|
+
* before 2.0.0 — the order a human writes them in — would therefore have the
|
|
386
|
+
* inspector announce the OLDER version as the upgrade, and say nothing about the
|
|
387
|
+
* real one. `GET /nodes/{slug}/versions` has always sorted; this is the same
|
|
388
|
+
* order on the listing the catalogue is actually built from.
|
|
389
|
+
*/
|
|
390
|
+
declare function listNodesNewestFirst(nodes: readonly INodeDescription[]): INodeDescription[];
|
|
349
391
|
declare function findNode(loaded: LoadedPackage, slug: string, version?: string): INode;
|
|
350
392
|
declare function findCredential(loaded: LoadedPackage, slug: string): ICredential;
|
|
351
393
|
declare function findCredentialType(loaded: LoadedPackage, slug: string): ICredentialDescription;
|
|
@@ -387,6 +429,14 @@ interface ValidateNodeConfigResult {
|
|
|
387
429
|
* flattened keys. Deep cross-field validation is intentionally out of scope
|
|
388
430
|
* (the production service does that on save); this mirrors the mock's
|
|
389
431
|
* "light, schema-based" fidelity. Unknown extra keys are ignored.
|
|
432
|
+
*
|
|
433
|
+
* A field whose `showIf` does not hold (SDK 1.0.0, PO-410) is skipped whole —
|
|
434
|
+
* not demanded when required, and not type-checked either. The editor does not
|
|
435
|
+
* draw it, so whatever is left under its key is a leftover from a choice the
|
|
436
|
+
* author has since changed, and refusing to save because of it would leave them
|
|
437
|
+
* with an error against a field they cannot see. `settingApplies` comes from the
|
|
438
|
+
* SDK rather than being re-implemented here: the editor drawing the field and
|
|
439
|
+
* this validator deciding whether to demand it have to agree word for word.
|
|
390
440
|
*/
|
|
391
441
|
declare function validateNodeConfig(loaded: LoadedPackage, store: DevStore, input: ValidateNodeConfigInput): Promise<ValidateNodeConfigResult>;
|
|
392
442
|
/** Runs a credential type's `test` against inline (unsaved) config. */
|
|
@@ -429,4 +479,4 @@ declare function createDevServer(deps: DevServerDeps): http.Server;
|
|
|
429
479
|
*/
|
|
430
480
|
declare const DEVKIT_VERSION: string;
|
|
431
481
|
|
|
432
|
-
export { type CredentialRecord, type CredentialSeed, DEVKIT_VERSION, DEV_TENANT_ID, DevApiError, type DevSeeds, type DevServerDeps, DevStore, type DevStoreSnapshot, ENV_FILE_MIN_NODE, type EnvFileChoice, type LoadEnvFileOptions, type LoadedPackage, type ResolveNodeConfigInput, type ResolveNodeConfigResult, STORE_SCHEMA_VERSION, type SecretRecord, type SecretSeed, type TriggerRecord, type ValidateNodeConfigInput, type ValidateNodeConfigResult, type WorkflowRecord, type WorkflowSeed, applySeeds, buildOAuthAuthorizeUrl, createDevServer, createRequestListener, ensureTsxRegistered, exchangeOAuthCode, findCredential, findCredentialType, findNode, importFresh, interpolateEnv, loadEnvFile, loadPackageFromEntry, loadSeedsFromDir, loadState, nodeOwnedEnvFlag, nodeVersions, resolveCredentialInstance, resolveEnvFile, resolveExports, resolveNodeConfig, saveState, testCredentialConfig, testCredentialInstance, validateNodeConfig };
|
|
482
|
+
export { type CredentialRecord, type CredentialSeed, DEVKIT_VERSION, DEV_TENANT_ID, DevApiError, type DevSeeds, type DevServerDeps, DevStore, type DevStoreSnapshot, ENV_FILE_MIN_NODE, type EnvFileChoice, type LoadEnvFileOptions, type LoadedPackage, type ResolveNodeConfigInput, type ResolveNodeConfigResult, STORE_SCHEMA_VERSION, type SecretRecord, type SecretSeed, type TriggerRecord, type ValidateNodeConfigInput, type ValidateNodeConfigResult, type WorkflowRecord, type WorkflowSeed, applySeeds, buildOAuthAuthorizeUrl, createDevServer, createRequestListener, ensureTsxRegistered, exchangeOAuthCode, findCredential, findCredentialType, findNode, importFresh, interpolateEnv, listNodesNewestFirst, loadEnvFile, loadPackageFromEntry, loadSeedsFromDir, loadState, nodeOwnedEnvFlag, nodeVersions, resolveCredentialInstance, resolveEnvFile, resolveExports, resolveNodeConfig, saveState, testCredentialConfig, testCredentialInstance, validateNodeConfig };
|
package/dist/index.js
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
findNode,
|
|
17
17
|
importFresh,
|
|
18
18
|
interpolateEnv,
|
|
19
|
+
listNodesNewestFirst,
|
|
19
20
|
loadEnvFile,
|
|
20
21
|
loadPackageFromEntry,
|
|
21
22
|
loadSeedsFromDir,
|
|
@@ -30,7 +31,8 @@ import {
|
|
|
30
31
|
testCredentialConfig,
|
|
31
32
|
testCredentialInstance,
|
|
32
33
|
validateNodeConfig
|
|
33
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-YUUW37NC.js";
|
|
35
|
+
import "./chunk-PME34X7E.js";
|
|
34
36
|
export {
|
|
35
37
|
DEVKIT_VERSION,
|
|
36
38
|
DEV_TENANT_ID,
|
|
@@ -49,6 +51,7 @@ export {
|
|
|
49
51
|
findNode,
|
|
50
52
|
importFresh,
|
|
51
53
|
interpolateEnv,
|
|
54
|
+
listNodesNewestFirst,
|
|
52
55
|
loadEnvFile,
|
|
53
56
|
loadPackageFromEntry,
|
|
54
57
|
loadSeedsFromDir,
|
package/dist/testing/index.cjs
CHANGED
|
@@ -35,8 +35,34 @@ module.exports = __toCommonJS(testing_exports);
|
|
|
35
35
|
|
|
36
36
|
// src/testing/context.ts
|
|
37
37
|
var import_vitest = require("vitest");
|
|
38
|
+
|
|
39
|
+
// src/state-rules.ts
|
|
40
|
+
var import_integrations_node_sdk = require("@revenexx/integrations-node-sdk");
|
|
41
|
+
var MIN_CLAIM_TTL_SECONDS = 1;
|
|
42
|
+
var MAX_CLAIM_TTL_SECONDS = 31536e3;
|
|
43
|
+
function assertTtlInRange(ttlSeconds) {
|
|
44
|
+
if (ttlSeconds === void 0) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (!Number.isFinite(ttlSeconds) || ttlSeconds < MIN_CLAIM_TTL_SECONDS || ttlSeconds > MAX_CLAIM_TTL_SECONDS) {
|
|
48
|
+
throw new import_integrations_node_sdk.NodeError("INVALID_TTL", `ttlSeconds must be between ${MIN_CLAIM_TTL_SECONDS} and ${MAX_CLAIM_TTL_SECONDS}, got ${String(ttlSeconds)}.`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function assertNotRepointed(namespace, pairs, left, right) {
|
|
52
|
+
for (const [existingLeft, existingRight] of pairs) {
|
|
53
|
+
if (existingLeft === left && existingRight !== right) {
|
|
54
|
+
throw new import_integrations_node_sdk.NodeError("MAPPING_CONFLICT", `'${left}' is already correlated with '${existingRight}' in namespace '${namespace}'.`);
|
|
55
|
+
}
|
|
56
|
+
if (existingRight === right && existingLeft !== left) {
|
|
57
|
+
throw new import_integrations_node_sdk.NodeError("MAPPING_CONFLICT", `'${right}' is already correlated with '${existingLeft}' in namespace '${namespace}'.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/testing/context.ts
|
|
38
63
|
function createMockContext(options = {}) {
|
|
39
64
|
const signal = options.signal ?? new AbortController().signal;
|
|
65
|
+
const { state, completeRun } = createMockState(options.state, options.stateError);
|
|
40
66
|
const secretsGet = options.secretsError ? import_vitest.vi.fn(async () => {
|
|
41
67
|
throw options.secretsError;
|
|
42
68
|
}) : import_vitest.vi.fn(async (key) => {
|
|
@@ -65,8 +91,112 @@ function createMockContext(options = {}) {
|
|
|
65
91
|
},
|
|
66
92
|
credentials: {
|
|
67
93
|
get: credentialsGet
|
|
94
|
+
},
|
|
95
|
+
state,
|
|
96
|
+
completeRun
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
function createMockState(seed = {}, error) {
|
|
100
|
+
const mappings = /* @__PURE__ */ new Map();
|
|
101
|
+
const cursors = /* @__PURE__ */ new Map();
|
|
102
|
+
const claims = /* @__PURE__ */ new Map();
|
|
103
|
+
const digests = /* @__PURE__ */ new Map();
|
|
104
|
+
const stagedCursors = /* @__PURE__ */ new Map();
|
|
105
|
+
const stagedDigests = /* @__PURE__ */ new Map();
|
|
106
|
+
for (const [namespace, pairs] of Object.entries(seed.mappings ?? {})) {
|
|
107
|
+
mappings.set(namespace, new Map(Object.entries(pairs)));
|
|
108
|
+
}
|
|
109
|
+
for (const [namespace, partitions] of Object.entries(seed.cursors ?? {})) {
|
|
110
|
+
cursors.set(namespace, new Map(Object.entries(partitions)));
|
|
111
|
+
}
|
|
112
|
+
for (const [namespace, keys] of Object.entries(seed.claims ?? {})) {
|
|
113
|
+
claims.set(namespace, new Set(keys));
|
|
114
|
+
}
|
|
115
|
+
for (const [namespace, entries] of Object.entries(seed.digests ?? {})) {
|
|
116
|
+
digests.set(namespace, new Map(Object.entries(entries)));
|
|
117
|
+
}
|
|
118
|
+
const op = (fn) => import_vitest.vi.fn(async (...args) => {
|
|
119
|
+
if (error) {
|
|
120
|
+
throw error;
|
|
68
121
|
}
|
|
122
|
+
return fn(...args);
|
|
123
|
+
});
|
|
124
|
+
const state = {
|
|
125
|
+
mapping: {
|
|
126
|
+
get: op((namespace, key, side = "left") => {
|
|
127
|
+
const pairs = mappings.get(namespace);
|
|
128
|
+
if (!pairs) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
if (side === "left") {
|
|
132
|
+
return pairs.get(key) ?? null;
|
|
133
|
+
}
|
|
134
|
+
for (const [left, right] of pairs) {
|
|
135
|
+
if (right === key) {
|
|
136
|
+
return left;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}),
|
|
141
|
+
put: op((namespace, left, right) => {
|
|
142
|
+
const pairs = mappings.get(namespace) ?? /* @__PURE__ */ new Map();
|
|
143
|
+
assertNotRepointed(namespace, pairs, left, right);
|
|
144
|
+
pairs.set(left, right);
|
|
145
|
+
mappings.set(namespace, pairs);
|
|
146
|
+
})
|
|
147
|
+
},
|
|
148
|
+
cursor: {
|
|
149
|
+
// The committed watermark: what *this* run staged is deliberately not in
|
|
150
|
+
// the answer, exactly as the real store describes it.
|
|
151
|
+
get: op((namespace, partitionKey = "") => cursors.get(namespace)?.get(partitionKey)),
|
|
152
|
+
set: op((namespace, value, partitionKey = "") => {
|
|
153
|
+
const partitions = stagedCursors.get(namespace) ?? /* @__PURE__ */ new Map();
|
|
154
|
+
partitions.set(partitionKey, value);
|
|
155
|
+
stagedCursors.set(namespace, partitions);
|
|
156
|
+
})
|
|
157
|
+
},
|
|
158
|
+
// First caller wins, like the real claim — so a test can drive both the
|
|
159
|
+
// fresh and the duplicate path without reconfiguring the mock. A claim is
|
|
160
|
+
// never handed on here: a TTL is a wall-clock window, and no unit test
|
|
161
|
+
// outlives the shortest one the store accepts.
|
|
162
|
+
claim: op((namespace, key, opts) => {
|
|
163
|
+
assertTtlInRange(opts?.ttlSeconds);
|
|
164
|
+
const held = claims.get(namespace) ?? /* @__PURE__ */ new Set();
|
|
165
|
+
if (held.has(key)) {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
held.add(key);
|
|
169
|
+
claims.set(namespace, held);
|
|
170
|
+
return true;
|
|
171
|
+
}),
|
|
172
|
+
digest: {
|
|
173
|
+
unchanged: op((namespace, entityKey, digest) => digests.get(namespace)?.get(entityKey) === digest),
|
|
174
|
+
set: op((namespace, entityKey, digest) => {
|
|
175
|
+
const entries = stagedDigests.get(namespace) ?? /* @__PURE__ */ new Map();
|
|
176
|
+
entries.set(entityKey, digest);
|
|
177
|
+
stagedDigests.set(namespace, entries);
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
const completeRun = () => {
|
|
182
|
+
for (const [namespace, partitions] of stagedCursors) {
|
|
183
|
+
const committed = cursors.get(namespace) ?? /* @__PURE__ */ new Map();
|
|
184
|
+
for (const [partitionKey, value] of partitions) {
|
|
185
|
+
committed.set(partitionKey, value);
|
|
186
|
+
}
|
|
187
|
+
cursors.set(namespace, committed);
|
|
188
|
+
}
|
|
189
|
+
for (const [namespace, entries] of stagedDigests) {
|
|
190
|
+
const committed = digests.get(namespace) ?? /* @__PURE__ */ new Map();
|
|
191
|
+
for (const [entityKey, digest] of entries) {
|
|
192
|
+
committed.set(entityKey, digest);
|
|
193
|
+
}
|
|
194
|
+
digests.set(namespace, committed);
|
|
195
|
+
}
|
|
196
|
+
stagedCursors.clear();
|
|
197
|
+
stagedDigests.clear();
|
|
69
198
|
};
|
|
199
|
+
return { state, completeRun };
|
|
70
200
|
}
|
|
71
201
|
|
|
72
202
|
// src/testing/author.ts
|
|
@@ -153,7 +283,7 @@ function fakeTokenEndpoint(options = {}) {
|
|
|
153
283
|
}
|
|
154
284
|
|
|
155
285
|
// src/testing/credentials.ts
|
|
156
|
-
var
|
|
286
|
+
var import_integrations_node_sdk2 = require("@revenexx/integrations-node-sdk");
|
|
157
287
|
var import_vitest4 = require("vitest");
|
|
158
288
|
function createCredentialContext(options = {}) {
|
|
159
289
|
const signal = options.signal ?? new AbortController().signal;
|
|
@@ -179,7 +309,7 @@ async function runCredentialResolve(credential, options) {
|
|
|
179
309
|
return { result, persistDurableCreds: ctx.persistDurableCreds, ctx };
|
|
180
310
|
}
|
|
181
311
|
async function runOAuthAuthorizeUrl(credential, options) {
|
|
182
|
-
if (!(0,
|
|
312
|
+
if (!(0, import_integrations_node_sdk2.isOAuthAuthorizeCredential)(credential)) {
|
|
183
313
|
throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);
|
|
184
314
|
}
|
|
185
315
|
const ctx = createCredentialContext({ signal: options.signal });
|
|
@@ -189,7 +319,7 @@ async function runOAuthAuthorizeUrl(credential, options) {
|
|
|
189
319
|
});
|
|
190
320
|
}
|
|
191
321
|
async function runOAuthExchangeCode(credential, options) {
|
|
192
|
-
if (!(0,
|
|
322
|
+
if (!(0, import_integrations_node_sdk2.isOAuthAuthorizeCredential)(credential)) {
|
|
193
323
|
throw new Error(`${credential.description.slug} is not a 3-legged OAuth credential`);
|
|
194
324
|
}
|
|
195
325
|
const ctx = createCredentialContext({ signal: options.signal });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/testing/index.ts","../../src/testing/context.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';\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`, and `credentials.get` so a node's\n * `execute` can be unit-tested in isolation.\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\nexport type MockContext = INodeContext & {\n logger: MockLogger;\n secrets: MockSecrets;\n credentials: MockCredentials;\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}\n\nexport function createMockContext(options: CreateMockContextOptions = {}): MockContext {\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 secrets: {\n get: secretsGet,\n },\n credentials: {\n get: credentialsGet,\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;AA0CZ,SAAS,kBAAkB,UAAoC,CAAC,GAAgB;AACrF,QAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,EAAE;AAEvD,QAAM,aAAa,QAAQ,eACvB,iBAAG,GAAG,YAAY;AAChB,UAAM,QAAQ;AAAA,EAChB,CAAC,IACD,iBAAG,GAAG,OAAO,QAAgB;AAC3B,QAAI,QAAQ,WAAW,OAAO,QAAQ,SAAS;AAC7C,aAAO,QAAQ,QAAQ,GAAG;AAAA,IAC5B;AACA,WAAO,oBAAo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,qBAAqB,YAAyB,SAAgG;AAClK,MAAI,KAAC,yDAA2B,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,kBAAkB,KAAK,QAAQ,QAAQ;AAAA,IACvD,aAAa,QAAQ;AAAA,IACrB,OAAO,QAAQ;AAAA,EACjB,CAAC;AACH;AAWA,eAAsB,qBAAqB,YAAyB,SAA0F;AAC5J,MAAI,KAAC,yDAA2B,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_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';\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,gBAAgB,QAAQ,OAAO,QA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AA,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"]}
|
package/dist/testing/index.d.cts
CHANGED
|
@@ -5,8 +5,22 @@ import { vi } from 'vitest';
|
|
|
5
5
|
* Drop-in replacement for the `createMockContext` helper that was, until this
|
|
6
6
|
* package existed, copy-pasted byte-for-byte into every node repo's
|
|
7
7
|
* `tests/helpers/context.ts`. Builds a full {@link INodeContext} with
|
|
8
|
-
* `vi.fn()`-backed `logger`, `secrets.get`,
|
|
9
|
-
* `execute` can be unit-tested in isolation.
|
|
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.
|
|
10
24
|
*/
|
|
11
25
|
type MockLogger = {
|
|
12
26
|
info: ReturnType<typeof vi.fn>;
|
|
@@ -19,10 +33,48 @@ type MockSecrets = {
|
|
|
19
33
|
type MockCredentials = {
|
|
20
34
|
get: ReturnType<typeof vi.fn>;
|
|
21
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
|
+
}
|
|
22
66
|
type MockContext = INodeContext & {
|
|
23
67
|
logger: MockLogger;
|
|
24
68
|
secrets: MockSecrets;
|
|
25
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;
|
|
26
78
|
};
|
|
27
79
|
interface CreateMockContextOptions {
|
|
28
80
|
signal?: AbortSignal;
|
|
@@ -34,6 +86,13 @@ interface CreateMockContextOptions {
|
|
|
34
86
|
credentials?: Record<string, Record<string, unknown>>;
|
|
35
87
|
/** When set, `credentials.get` rejects with this error instead of resolving. */
|
|
36
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;
|
|
37
96
|
}
|
|
38
97
|
declare function createMockContext(options?: CreateMockContextOptions): MockContext;
|
|
39
98
|
|
|
@@ -191,4 +250,4 @@ declare function runOAuthExchangeCode(credential: ICredential, options: RunOAuth
|
|
|
191
250
|
durableCreds: Record<string, unknown>;
|
|
192
251
|
}>;
|
|
193
252
|
|
|
194
|
-
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 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 };
|
|
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 };
|