@abyss-project/runtime 3.5.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.eslintrc.js +32 -32
  2. package/.prettierrc +5 -5
  3. package/README.md +88 -88
  4. package/dist/engine/engine-source.js +1 -1
  5. package/dist/interpreter/interpreter.js +18 -4
  6. package/dist/interpreter/interpreter.js.map +1 -1
  7. package/dist/interpreter/interpreter.types.d.ts +2 -0
  8. package/dist/interpreter/interpreter.types.js.map +1 -1
  9. package/dist/runner-protocol/execution-protocol.types.d.ts +11 -0
  10. package/dist/runner-protocol/execution-protocol.types.js +2 -1
  11. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  12. package/jest.config.ts +11 -11
  13. package/package.json +15 -10
  14. package/scripts/build-engine.cjs +70 -70
  15. package/src/__tests__/engine-bundle.test.ts +121 -121
  16. package/src/__tests__/surface.test.ts +70 -66
  17. package/src/access/__tests__/host-match.test.ts +24 -24
  18. package/src/access/access.types.ts +25 -25
  19. package/src/access/host-match.ts +13 -13
  20. package/src/cost/__tests__/execution-cost.test.ts +196 -196
  21. package/src/cost/execution-cost.ts +186 -186
  22. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  23. package/src/definition/definition.limits.ts +9 -9
  24. package/src/definition/definition.schema.ts +172 -172
  25. package/src/definition/definition.types.ts +171 -171
  26. package/src/definition/validate-definition.ts +206 -206
  27. package/src/definition/walk-steps.ts +44 -44
  28. package/src/discord/__tests__/discord-event-input.test.ts +89 -89
  29. package/src/discord/discord.types.ts +639 -639
  30. package/src/engine/__tests__/run-in-isolate.test.ts +468 -468
  31. package/src/engine/engine-entry.ts +3 -3
  32. package/src/engine/engine-global.ts +2 -2
  33. package/src/engine/run-in-isolate.ts +404 -404
  34. package/src/errors/runtime-error-code.enum.ts +37 -37
  35. package/src/index.ts +32 -32
  36. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  37. package/src/interpreter/__tests__/log-respond-resume.test.ts +270 -223
  38. package/src/interpreter/interpreter-error.ts +12 -12
  39. package/src/interpreter/interpreter.ts +482 -461
  40. package/src/interpreter/interpreter.types.ts +202 -192
  41. package/src/interpreter/sequence-path.ts +67 -67
  42. package/src/interpreter/test-host.ts +85 -85
  43. package/src/runner-protocol/evaluation.types.ts +21 -21
  44. package/src/runner-protocol/execution-protocol.types.ts +254 -231
  45. package/src/schedule/schedule.types.ts +100 -100
  46. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  47. package/src/server/code-runner-error.ts +12 -12
  48. package/src/server/code-runner-session.ts +310 -310
  49. package/src/server/index.ts +11 -11
  50. package/src/steps/__tests__/global-references.test.ts +133 -133
  51. package/src/steps/execute-step.ts +186 -186
  52. package/src/steps/global-references.ts +48 -48
  53. package/src/steps/step-access.ts +56 -56
  54. package/src/steps/step-fields.ts +87 -87
  55. package/src/steps/value-source.ts +69 -69
  56. package/tsconfig.check.json +15 -15
  57. package/tsconfig.json +35 -35
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ExecutionStatus = exports.StepStatus = exports.StepPhase = exports.RESERVED_GLOBAL_NAMES = exports.ExecutionMessageType = exports.CoreCapability = exports.MAX_PROGRESS_OUTPUT_CHARS = exports.MAX_CALL_PAYLOAD_BYTES = exports.EXECUTION_PROTOCOL = void 0;
3
+ exports.ExecutionStatus = exports.StepStatus = exports.StepPhase = exports.RESERVED_GLOBAL_NAMES = exports.ExecutionMessageType = exports.CoreCapability = exports.MAX_ERROR_STACK_CHARS = exports.MAX_PROGRESS_OUTPUT_CHARS = exports.MAX_CALL_PAYLOAD_BYTES = exports.EXECUTION_PROTOCOL = void 0;
4
4
  exports.EXECUTION_PROTOCOL = 'abyss-runtime.v2';
5
5
  exports.MAX_CALL_PAYLOAD_BYTES = 1_048_576;
6
6
  exports.MAX_PROGRESS_OUTPUT_CHARS = 4_096;
7
+ exports.MAX_ERROR_STACK_CHARS = 4_096;
7
8
  var CoreCapability;
8
9
  (function (CoreCapability) {
9
10
  CoreCapability["HTTP_FETCH"] = "http.fetch";
@@ -1 +1 @@
1
- {"version":3,"file":"execution-protocol.types.js","sourceRoot":"","sources":["../../src/runner-protocol/execution-protocol.types.ts"],"names":[],"mappings":";;;AAQa,QAAA,kBAAkB,GAAG,kBAAkB,CAAC;AAGxC,QAAA,sBAAsB,GAAG,SAAS,CAAC;AAGnC,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAM/C,IAAY,cASX;AATD,WAAY,cAAc;IAExB,2CAAyB,CAAA;IAEzB,+BAAa,CAAA;IAEb,yCAAuB,CAAA;IAEvB,+CAA6B,CAAA;AAC/B,CAAC,EATW,cAAc,8BAAd,cAAc,QASzB;AAED,IAAY,oBAOX;AAPD,WAAY,oBAAoB;IAC9B,2CAAmB,CAAA;IACnB,qCAAa,CAAA;IACb,kDAA0B,CAAA;IAC1B,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;AACvB,CAAC,EAPW,oBAAoB,oCAApB,oBAAoB,QAO/B;AAcY,QAAA,qBAAqB,GAAsB;IACtD,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,SAAS;CACV,CAAC;AA+FF,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,gCAAmB,CAAA;IACnB,kCAAqB,CAAA;AACvB,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAED,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,qCAAuB,CAAA;IACvB,+BAAiB,CAAA;IAEjB,qCAAuB,CAAA;AACzB,CAAC,EALW,UAAU,0BAAV,UAAU,QAKrB;AAuBD,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,oCAAiB,CAAA;IACjB,0CAAuB,CAAA;AACzB,CAAC,EAJW,eAAe,+BAAf,eAAe,QAI1B"}
1
+ {"version":3,"file":"execution-protocol.types.js","sourceRoot":"","sources":["../../src/runner-protocol/execution-protocol.types.ts"],"names":[],"mappings":";;;AAQa,QAAA,kBAAkB,GAAG,kBAAkB,CAAC;AAGxC,QAAA,sBAAsB,GAAG,SAAS,CAAC;AAGnC,QAAA,yBAAyB,GAAG,KAAK,CAAC;AAGlC,QAAA,qBAAqB,GAAG,KAAK,CAAC;AAM3C,IAAY,cASX;AATD,WAAY,cAAc;IAExB,2CAAyB,CAAA;IAEzB,+BAAa,CAAA;IAEb,yCAAuB,CAAA;IAEvB,+CAA6B,CAAA;AAC/B,CAAC,EATW,cAAc,8BAAd,cAAc,QASzB;AAED,IAAY,oBAOX;AAPD,WAAY,oBAAoB;IAC9B,2CAAmB,CAAA;IACnB,qCAAa,CAAA;IACb,kDAA0B,CAAA;IAC1B,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;IACrB,6CAAqB,CAAA;AACvB,CAAC,EAPW,oBAAoB,oCAApB,oBAAoB,QAO/B;AAcY,QAAA,qBAAqB,GAAsB;IACtD,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,OAAO;IACP,SAAS;CACV,CAAC;AA2GF,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,gCAAmB,CAAA;IACnB,kCAAqB,CAAA;AACvB,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAED,IAAY,UAKX;AALD,WAAY,UAAU;IACpB,qCAAuB,CAAA;IACvB,+BAAiB,CAAA;IAEjB,qCAAuB,CAAA;AACzB,CAAC,EALW,UAAU,0BAAV,UAAU,QAKrB;AA2BD,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,oCAAiB,CAAA;IACjB,0CAAuB,CAAA;AACzB,CAAC,EAJW,eAAe,+BAAf,eAAe,QAI1B"}
package/jest.config.ts CHANGED
@@ -1,11 +1,11 @@
1
- import type { Config } from '@jest/types';
2
-
3
- const config: Config.InitialOptions = {
4
- testEnvironment: 'node',
5
- transform: {
6
- '^.+\\.tsx?$': ['ts-jest', { isolatedModules: true }],
7
- },
8
- modulePathIgnorePatterns: ['dist'],
9
- };
10
-
11
- export default config;
1
+ import type { Config } from '@jest/types';
2
+
3
+ const config: Config.InitialOptions = {
4
+ testEnvironment: 'node',
5
+ transform: {
6
+ '^.+\\.tsx?$': ['ts-jest', { isolatedModules: true }],
7
+ },
8
+ modulePathIgnorePatterns: ['dist'],
9
+ };
10
+
11
+ export default config;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abyss-project/runtime",
3
- "version": "3.5.0",
3
+ "version": "3.6.0",
4
4
  "description": "Abyss automation core: definitions, interpreter, runner protocol",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -28,6 +28,19 @@
28
28
  ]
29
29
  }
30
30
  },
31
+ "publishConfig": {
32
+ "main": "dist/index.js",
33
+ "types": "dist/index.d.ts"
34
+ },
35
+ "scripts": {
36
+ "lint": "eslint \"{src,apps,libs,test,core}/**/*.ts\" --fix",
37
+ "lint:check": "eslint \"{src,apps,libs,test,core}/**/*.ts\" --max-warnings 0",
38
+ "tsc": "tsc",
39
+ "build": "tsc && node scripts/build-engine.cjs",
40
+ "test": "jest",
41
+ "prepublishOnly": "tsc && node scripts/build-engine.cjs && node ../../scripts/check-sdk-surface.cjs",
42
+ "dev": "tsc --watch"
43
+ },
31
44
  "repository": {
32
45
  "type": "git",
33
46
  "url": "https://gitlab.com/abyss-group/abyss-runtime.git"
@@ -59,13 +72,5 @@
59
72
  "ts-jest": "^29.1.0",
60
73
  "ts-node": "^10.4.0",
61
74
  "typescript": "5.9.3"
62
- },
63
- "scripts": {
64
- "lint": "eslint \"{src,apps,libs,test,core}/**/*.ts\" --fix",
65
- "lint:check": "eslint \"{src,apps,libs,test,core}/**/*.ts\" --max-warnings 0",
66
- "tsc": "tsc",
67
- "build": "tsc && node scripts/build-engine.cjs",
68
- "test": "jest",
69
- "dev": "tsc --watch"
70
75
  }
71
- }
76
+ }
@@ -1,70 +1,70 @@
1
- #!/usr/bin/env node
2
- /**
3
- * build-engine.cjs — bundles the isolate engine (ADR-0238) into one self-contained script and
4
- * ships it as a string: `@abyss-project/runtime/engine` exports `ENGINE_SOURCE`.
5
- *
6
- * The script is an IIFE that defines one global (`ENGINE_GLOBAL_NAME`, `{ runInIsolate }`).
7
- * `platform: 'neutral'` resolves no Node built-in: an import of `fs`, `net`... fails the build
8
- * instead of slipping into the isolate. Runs after `tsc`, which emits the rest of `dist`.
9
- *
10
- * USAGE (from the package directory, what `build` does)
11
- * node scripts/build-engine.cjs
12
- */
13
-
14
- /* eslint-disable no-console */
15
- 'use strict';
16
-
17
- const fs = require('fs');
18
- const path = require('path');
19
- const esbuild = require('esbuild');
20
-
21
- const PACKAGE_DIR = path.resolve(__dirname, '..');
22
- const ENTRY = path.join(PACKAGE_DIR, 'src', 'engine', 'engine-entry.ts');
23
- const OUT_DIR = path.join(PACKAGE_DIR, 'dist', 'engine');
24
-
25
- /** The engine script, as a string; `globalName` is the global it defines. */
26
- function bundleEngine(globalName) {
27
- const result = esbuild.buildSync({
28
- entryPoints: [ENTRY],
29
- bundle: true,
30
- format: 'iife',
31
- globalName,
32
- platform: 'neutral',
33
- target: 'es2021',
34
- write: false,
35
- legalComments: 'none',
36
- logLevel: 'silent',
37
- });
38
- return result.outputFiles[0].text;
39
- }
40
-
41
- function main() {
42
- const globalPath = path.join(OUT_DIR, 'engine-global.js');
43
- if (!fs.existsSync(globalPath)) {
44
- throw new Error(`${globalPath} is missing: run tsc before this script`);
45
- }
46
- const { ENGINE_GLOBAL_NAME } = require(globalPath);
47
- const source = bundleEngine(ENGINE_GLOBAL_NAME);
48
- fs.writeFileSync(
49
- path.join(OUT_DIR, 'engine-source.js'),
50
- `"use strict";\nObject.defineProperty(exports, "__esModule", { value: true });\n` +
51
- `exports.ENGINE_SOURCE = ${JSON.stringify(source)};\n`,
52
- );
53
- fs.writeFileSync(
54
- path.join(OUT_DIR, 'engine-source.d.ts'),
55
- '/** The isolate engine script: evaluating it defines the global `ENGINE_GLOBAL_NAME`. */\n' +
56
- 'export declare const ENGINE_SOURCE: string;\n',
57
- );
58
- console.log(`engine bundle: ${source.length} characters in dist/engine/engine-source.js`);
59
- }
60
-
61
- if (require.main === module) {
62
- try {
63
- main();
64
- } catch (error) {
65
- console.error(error instanceof Error ? error.message : error);
66
- process.exit(1);
67
- }
68
- }
69
-
70
- module.exports = { bundleEngine };
1
+ #!/usr/bin/env node
2
+ /**
3
+ * build-engine.cjs — bundles the isolate engine (ADR-0238) into one self-contained script and
4
+ * ships it as a string: `@abyss-project/runtime/engine` exports `ENGINE_SOURCE`.
5
+ *
6
+ * The script is an IIFE that defines one global (`ENGINE_GLOBAL_NAME`, `{ runInIsolate }`).
7
+ * `platform: 'neutral'` resolves no Node built-in: an import of `fs`, `net`... fails the build
8
+ * instead of slipping into the isolate. Runs after `tsc`, which emits the rest of `dist`.
9
+ *
10
+ * USAGE (from the package directory, what `build` does)
11
+ * node scripts/build-engine.cjs
12
+ */
13
+
14
+ /* eslint-disable no-console */
15
+ 'use strict';
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const esbuild = require('esbuild');
20
+
21
+ const PACKAGE_DIR = path.resolve(__dirname, '..');
22
+ const ENTRY = path.join(PACKAGE_DIR, 'src', 'engine', 'engine-entry.ts');
23
+ const OUT_DIR = path.join(PACKAGE_DIR, 'dist', 'engine');
24
+
25
+ /** The engine script, as a string; `globalName` is the global it defines. */
26
+ function bundleEngine(globalName) {
27
+ const result = esbuild.buildSync({
28
+ entryPoints: [ENTRY],
29
+ bundle: true,
30
+ format: 'iife',
31
+ globalName,
32
+ platform: 'neutral',
33
+ target: 'es2021',
34
+ write: false,
35
+ legalComments: 'none',
36
+ logLevel: 'silent',
37
+ });
38
+ return result.outputFiles[0].text;
39
+ }
40
+
41
+ function main() {
42
+ const globalPath = path.join(OUT_DIR, 'engine-global.js');
43
+ if (!fs.existsSync(globalPath)) {
44
+ throw new Error(`${globalPath} is missing: run tsc before this script`);
45
+ }
46
+ const { ENGINE_GLOBAL_NAME } = require(globalPath);
47
+ const source = bundleEngine(ENGINE_GLOBAL_NAME);
48
+ fs.writeFileSync(
49
+ path.join(OUT_DIR, 'engine-source.js'),
50
+ `"use strict";\nObject.defineProperty(exports, "__esModule", { value: true });\n` +
51
+ `exports.ENGINE_SOURCE = ${JSON.stringify(source)};\n`,
52
+ );
53
+ fs.writeFileSync(
54
+ path.join(OUT_DIR, 'engine-source.d.ts'),
55
+ '/** The isolate engine script: evaluating it defines the global `ENGINE_GLOBAL_NAME`. */\n' +
56
+ 'export declare const ENGINE_SOURCE: string;\n',
57
+ );
58
+ console.log(`engine bundle: ${source.length} characters in dist/engine/engine-source.js`);
59
+ }
60
+
61
+ if (require.main === module) {
62
+ try {
63
+ main();
64
+ } catch (error) {
65
+ console.error(error instanceof Error ? error.message : error);
66
+ process.exit(1);
67
+ }
68
+ }
69
+
70
+ module.exports = { bundleEngine };
@@ -1,121 +1,121 @@
1
- import * as vm from 'vm';
2
- import { AccessKind } from '../access/access.types';
3
- import {
4
- CURRENT_FORMAT_VERSION,
5
- HttpMethod,
6
- LogLevel,
7
- StepType,
8
- StopStatus,
9
- } from '../definition/definition.types';
10
- import type { RuntimeDefinition } from '../definition/definition.types';
11
- import { ENGINE_GLOBAL_NAME } from '../engine/engine-global';
12
- import { EngineResultKind } from '../engine/run-in-isolate';
13
- import type { EngineHost, EngineRequest, EngineResult } from '../engine/run-in-isolate';
14
- import type { EvaluationItem } from '../runner-protocol/evaluation.types';
15
- import { CoreCapability, ExecutionStatus } from '../runner-protocol/execution-protocol.types';
16
-
17
- // The build script is plain CommonJS, shared with `build`: the test bundles exactly what ships.
18
- // eslint-disable-next-line @typescript-eslint/no-require-imports
19
- const { bundleEngine } = require('../../scripts/build-engine.cjs') as {
20
- bundleEngine: (globalName: string) => string;
21
- };
22
-
23
- type Engine = { runInIsolate: (request: EngineRequest, host: EngineHost) => Promise<EngineResult> };
24
-
25
- const definition: RuntimeDefinition = {
26
- formatVersion: CURRENT_FORMAT_VERSION,
27
- accesses: [{ kind: AccessKind.HTTP, hosts: ['api.example.com'] }],
28
- steps: [
29
- { id: 'double', type: StepType.SET, variable: 'n', value: { $expression: 'input.n * 2' } },
30
- {
31
- id: 'fetch',
32
- type: StepType.HTTP,
33
- method: HttpMethod.GET,
34
- url: 'https://api.example.com/{{ vars.n }}',
35
- },
36
- { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'fetched' },
37
- {
38
- id: 'end',
39
- type: StepType.STOP,
40
- status: StopStatus.SUCCEEDED,
41
- output: { $expression: 'vars.n' },
42
- },
43
- ],
44
- };
45
-
46
- describe('isolate engine bundle', () => {
47
- let source: string;
48
-
49
- beforeAll(() => {
50
- source = bundleEngine(ENGINE_GLOBAL_NAME);
51
- });
52
-
53
- it('carries no module loader and no Joi', () => {
54
- expect(source).not.toMatch(/\brequire\s*\(/);
55
- expect(source).not.toMatch(/joi/i);
56
- });
57
-
58
- it('loads in a bare context and runs a definition with a fake evaluate and callHost', async () => {
59
- // No `require`, `process`, `URL`, timers nor console: only the language built-ins.
60
- const context = vm.createContext({});
61
- vm.runInContext(source, context);
62
- expect(vm.runInContext('typeof require + typeof process + typeof URL', context)).toBe(
63
- 'undefinedundefinedundefined',
64
- );
65
- const engine = (context as Record<string, unknown>)[ENGINE_GLOBAL_NAME] as Engine;
66
- expect(typeof engine.runInIsolate).toBe('function');
67
-
68
- const values: Record<string, unknown> = {
69
- 'input.n * 2': 42,
70
- 'https://api.example.com/{{ vars.n }}': 'https://api.example.com/42',
71
- 'vars.n': 42,
72
- };
73
- const calls: Array<{ stepId: string; capability: string; args: unknown }> = [];
74
- const progress: string[] = [];
75
- const host: EngineHost = {
76
- evaluate: async (items: EvaluationItem[]) =>
77
- items.map((item) => ({ id: item.id, ok: true as const, value: values[item.source] })),
78
- callHost: async (stepId, capability, args) => {
79
- calls.push({ stepId, capability, args });
80
- return {
81
- ok: true,
82
- value:
83
- capability === CoreCapability.HTTP_FETCH
84
- ? { status: 200, headers: {}, body: null }
85
- : null,
86
- };
87
- },
88
- onProgress: (p) => progress.push(`${p.stepId}:${p.phase}`),
89
- now: () => 0,
90
- };
91
-
92
- const result = await engine.runInIsolate(
93
- {
94
- definition,
95
- input: { n: 21 },
96
- capabilities: [CoreCapability.HTTP_FETCH, CoreCapability.LOG_WRITE],
97
- budget: { maxSteps: 10, maxEffects: 10 },
98
- },
99
- host,
100
- );
101
-
102
- // Values built in the other realm: compare their JSON.
103
- expect(JSON.parse(JSON.stringify(result))).toEqual({
104
- kind: EngineResultKind.FINISHED,
105
- outcome: { status: ExecutionStatus.SUCCEEDED, output: 42 },
106
- });
107
- expect(JSON.parse(JSON.stringify(calls))).toEqual([
108
- {
109
- stepId: 'fetch',
110
- capability: CoreCapability.HTTP_FETCH,
111
- args: { method: 'GET', url: 'https://api.example.com/42', headers: {} },
112
- },
113
- {
114
- stepId: 'note',
115
- capability: CoreCapability.LOG_WRITE,
116
- args: { level: LogLevel.INFO, message: 'fetched' },
117
- },
118
- ]);
119
- expect(progress).toHaveLength(8);
120
- });
121
- });
1
+ import * as vm from 'vm';
2
+ import { AccessKind } from '../access/access.types';
3
+ import {
4
+ CURRENT_FORMAT_VERSION,
5
+ HttpMethod,
6
+ LogLevel,
7
+ StepType,
8
+ StopStatus,
9
+ } from '../definition/definition.types';
10
+ import type { RuntimeDefinition } from '../definition/definition.types';
11
+ import { ENGINE_GLOBAL_NAME } from '../engine/engine-global';
12
+ import { EngineResultKind } from '../engine/run-in-isolate';
13
+ import type { EngineHost, EngineRequest, EngineResult } from '../engine/run-in-isolate';
14
+ import type { EvaluationItem } from '../runner-protocol/evaluation.types';
15
+ import { CoreCapability, ExecutionStatus } from '../runner-protocol/execution-protocol.types';
16
+
17
+ // The build script is plain CommonJS, shared with `build`: the test bundles exactly what ships.
18
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
19
+ const { bundleEngine } = require('../../scripts/build-engine.cjs') as {
20
+ bundleEngine: (globalName: string) => string;
21
+ };
22
+
23
+ type Engine = { runInIsolate: (request: EngineRequest, host: EngineHost) => Promise<EngineResult> };
24
+
25
+ const definition: RuntimeDefinition = {
26
+ formatVersion: CURRENT_FORMAT_VERSION,
27
+ accesses: [{ kind: AccessKind.HTTP, hosts: ['api.example.com'] }],
28
+ steps: [
29
+ { id: 'double', type: StepType.SET, variable: 'n', value: { $expression: 'input.n * 2' } },
30
+ {
31
+ id: 'fetch',
32
+ type: StepType.HTTP,
33
+ method: HttpMethod.GET,
34
+ url: 'https://api.example.com/{{ vars.n }}',
35
+ },
36
+ { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'fetched' },
37
+ {
38
+ id: 'end',
39
+ type: StepType.STOP,
40
+ status: StopStatus.SUCCEEDED,
41
+ output: { $expression: 'vars.n' },
42
+ },
43
+ ],
44
+ };
45
+
46
+ describe('isolate engine bundle', () => {
47
+ let source: string;
48
+
49
+ beforeAll(() => {
50
+ source = bundleEngine(ENGINE_GLOBAL_NAME);
51
+ });
52
+
53
+ it('carries no module loader and no Joi', () => {
54
+ expect(source).not.toMatch(/\brequire\s*\(/);
55
+ expect(source).not.toMatch(/joi/i);
56
+ });
57
+
58
+ it('loads in a bare context and runs a definition with a fake evaluate and callHost', async () => {
59
+ // No `require`, `process`, `URL`, timers nor console: only the language built-ins.
60
+ const context = vm.createContext({});
61
+ vm.runInContext(source, context);
62
+ expect(vm.runInContext('typeof require + typeof process + typeof URL', context)).toBe(
63
+ 'undefinedundefinedundefined',
64
+ );
65
+ const engine = (context as Record<string, unknown>)[ENGINE_GLOBAL_NAME] as Engine;
66
+ expect(typeof engine.runInIsolate).toBe('function');
67
+
68
+ const values: Record<string, unknown> = {
69
+ 'input.n * 2': 42,
70
+ 'https://api.example.com/{{ vars.n }}': 'https://api.example.com/42',
71
+ 'vars.n': 42,
72
+ };
73
+ const calls: Array<{ stepId: string; capability: string; args: unknown }> = [];
74
+ const progress: string[] = [];
75
+ const host: EngineHost = {
76
+ evaluate: async (items: EvaluationItem[]) =>
77
+ items.map((item) => ({ id: item.id, ok: true as const, value: values[item.source] })),
78
+ callHost: async (stepId, capability, args) => {
79
+ calls.push({ stepId, capability, args });
80
+ return {
81
+ ok: true,
82
+ value:
83
+ capability === CoreCapability.HTTP_FETCH
84
+ ? { status: 200, headers: {}, body: null }
85
+ : null,
86
+ };
87
+ },
88
+ onProgress: (p) => progress.push(`${p.stepId}:${p.phase}`),
89
+ now: () => 0,
90
+ };
91
+
92
+ const result = await engine.runInIsolate(
93
+ {
94
+ definition,
95
+ input: { n: 21 },
96
+ capabilities: [CoreCapability.HTTP_FETCH, CoreCapability.LOG_WRITE],
97
+ budget: { maxSteps: 10, maxEffects: 10 },
98
+ },
99
+ host,
100
+ );
101
+
102
+ // Values built in the other realm: compare their JSON.
103
+ expect(JSON.parse(JSON.stringify(result))).toEqual({
104
+ kind: EngineResultKind.FINISHED,
105
+ outcome: { status: ExecutionStatus.SUCCEEDED, output: 42 },
106
+ });
107
+ expect(JSON.parse(JSON.stringify(calls))).toEqual([
108
+ {
109
+ stepId: 'fetch',
110
+ capability: CoreCapability.HTTP_FETCH,
111
+ args: { method: 'GET', url: 'https://api.example.com/42', headers: {} },
112
+ },
113
+ {
114
+ stepId: 'note',
115
+ capability: CoreCapability.LOG_WRITE,
116
+ args: { level: LogLevel.INFO, message: 'fetched' },
117
+ },
118
+ ]);
119
+ expect(progress).toHaveLength(8);
120
+ });
121
+ });
@@ -1,66 +1,70 @@
1
- import { builtinModules } from 'module';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
-
5
- import { DiscordEventType, isDiscordEventInput } from '../index';
6
- const SRC_DIR = path.resolve(__dirname, '..');
7
- const SERVER_DIR = path.join(SRC_DIR, 'server');
8
- const TESTS_DIR = path.join(SRC_DIR, '__tests__');
9
-
10
- // `ws` and every Node built-in module (`fs`, `net`, `http`, `node:*`...) are forbidden outside
11
- // `src/server`, so that the package root stays usable in a browser.
12
- const FORBIDDEN = new Set<string>(['ws', ...builtinModules]);
13
-
14
- const walkTsFiles = (dir: string): string[] =>
15
- fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
16
- const full = path.join(dir, entry.name);
17
- if (entry.isDirectory()) {
18
- return full === SERVER_DIR || full === TESTS_DIR ? [] : walkTsFiles(full);
19
- }
20
- return entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') ? [full] : [];
21
- });
22
-
23
- const IMPORT_PATTERNS = [
24
- /\bfrom\s*['"]([^'"]+)['"]/g,
25
- /\bimport\s*['"]([^'"]+)['"]/g,
26
- /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
27
- /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
28
- ];
29
-
30
- const importedSpecifiers = (text: string): string[] =>
31
- IMPORT_PATTERNS.flatMap((pattern) => [...text.matchAll(pattern)].map((match) => match[1]));
32
-
33
- const isForbidden = (specifier: string): boolean => {
34
- const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;
35
- return FORBIDDEN.has(bare) || FORBIDDEN.has(bare.split('/')[0]);
36
- };
37
-
38
- describe('browser-compatible package root', () => {
39
- it('imports no Node built-in nor ws outside src/server', () => {
40
- const offenders = walkTsFiles(SRC_DIR).flatMap((file) =>
41
- importedSpecifiers(fs.readFileSync(file, 'utf8'))
42
- .filter(isForbidden)
43
- .map((specifier) => `${path.relative(SRC_DIR, file)} imports ${specifier}`),
44
- );
45
- expect(offenders).toEqual([]);
46
- });
47
-
48
- it('detects forbidden imports (guard sanity)', () => {
49
- const source = "import { WebSocket } from 'ws';\nconst n = require('node:net');";
50
- expect(importedSpecifiers(source)).toEqual(['ws', 'node:net']);
51
- expect(['ws', 'node:net', 'fs/promises', 'http'].every(isForbidden)).toBe(true);
52
- expect(['joi', './steps', '../access'].some(isForbidden)).toBe(false);
53
- });
54
- });
55
-
56
- describe('public surface of the package root', () => {
57
- it('exports the Discord event input contract', () => {
58
- expect(Object.values(DiscordEventType)).toEqual([
59
- 'GUILD_MEMBER_ADD',
60
- 'GUILD_MEMBER_REMOVE',
61
- 'MESSAGE_CREATE',
62
- 'MESSAGE_REACTION_ADD',
63
- ]);
64
- expect(typeof isDiscordEventInput).toBe('function');
65
- });
66
- });
1
+ import { builtinModules } from 'module';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+
5
+ import { DiscordEventType, MAX_ERROR_STACK_CHARS, isDiscordEventInput } from '../index';
6
+ const SRC_DIR = path.resolve(__dirname, '..');
7
+ const SERVER_DIR = path.join(SRC_DIR, 'server');
8
+ const TESTS_DIR = path.join(SRC_DIR, '__tests__');
9
+
10
+ // `ws` and every Node built-in module (`fs`, `net`, `http`, `node:*`...) are forbidden outside
11
+ // `src/server`, so that the package root stays usable in a browser.
12
+ const FORBIDDEN = new Set<string>(['ws', ...builtinModules]);
13
+
14
+ const walkTsFiles = (dir: string): string[] =>
15
+ fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
16
+ const full = path.join(dir, entry.name);
17
+ if (entry.isDirectory()) {
18
+ return full === SERVER_DIR || full === TESTS_DIR ? [] : walkTsFiles(full);
19
+ }
20
+ return entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') ? [full] : [];
21
+ });
22
+
23
+ const IMPORT_PATTERNS = [
24
+ /\bfrom\s*['"]([^'"]+)['"]/g,
25
+ /\bimport\s*['"]([^'"]+)['"]/g,
26
+ /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
27
+ /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
28
+ ];
29
+
30
+ const importedSpecifiers = (text: string): string[] =>
31
+ IMPORT_PATTERNS.flatMap((pattern) => [...text.matchAll(pattern)].map((match) => match[1]));
32
+
33
+ const isForbidden = (specifier: string): boolean => {
34
+ const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;
35
+ return FORBIDDEN.has(bare) || FORBIDDEN.has(bare.split('/')[0]);
36
+ };
37
+
38
+ describe('browser-compatible package root', () => {
39
+ it('imports no Node built-in nor ws outside src/server', () => {
40
+ const offenders = walkTsFiles(SRC_DIR).flatMap((file) =>
41
+ importedSpecifiers(fs.readFileSync(file, 'utf8'))
42
+ .filter(isForbidden)
43
+ .map((specifier) => `${path.relative(SRC_DIR, file)} imports ${specifier}`),
44
+ );
45
+ expect(offenders).toEqual([]);
46
+ });
47
+
48
+ it('detects forbidden imports (guard sanity)', () => {
49
+ const source = "import { WebSocket } from 'ws';\nconst n = require('node:net');";
50
+ expect(importedSpecifiers(source)).toEqual(['ws', 'node:net']);
51
+ expect(['ws', 'node:net', 'fs/promises', 'http'].every(isForbidden)).toBe(true);
52
+ expect(['joi', './steps', '../access'].some(isForbidden)).toBe(false);
53
+ });
54
+ });
55
+
56
+ describe('public surface of the package root', () => {
57
+ it('exports the Discord event input contract', () => {
58
+ expect(Object.values(DiscordEventType)).toEqual([
59
+ 'GUILD_MEMBER_ADD',
60
+ 'GUILD_MEMBER_REMOVE',
61
+ 'MESSAGE_CREATE',
62
+ 'MESSAGE_REACTION_ADD',
63
+ ]);
64
+ expect(typeof isDiscordEventInput).toBe('function');
65
+ });
66
+
67
+ it('exports the error stack bound of the execution protocol', () => {
68
+ expect(MAX_ERROR_STACK_CHARS).toBe(4096);
69
+ });
70
+ });