@abyss-project/runtime 0.0.0-stage → 2.0.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 (132) hide show
  1. package/.eslintrc.js +32 -0
  2. package/.prettierrc +5 -0
  3. package/README.md +28 -3
  4. package/dist/access/access.types.d.ts +14 -0
  5. package/dist/access/access.types.js +9 -0
  6. package/dist/access/access.types.js.map +1 -0
  7. package/dist/access/host-match.d.ts +1 -0
  8. package/dist/access/host-match.js +14 -0
  9. package/dist/access/host-match.js.map +1 -0
  10. package/dist/cost/execution-cost.d.ts +45 -0
  11. package/dist/cost/execution-cost.js +114 -0
  12. package/dist/cost/execution-cost.js.map +1 -0
  13. package/dist/definition/definition.limits.d.ts +4 -0
  14. package/dist/definition/definition.limits.js +8 -0
  15. package/dist/definition/definition.limits.js.map +1 -0
  16. package/dist/definition/definition.schema.d.ts +8 -0
  17. package/dist/definition/definition.schema.js +123 -0
  18. package/dist/definition/definition.schema.js.map +1 -0
  19. package/dist/definition/definition.types.d.ts +117 -0
  20. package/dist/definition/definition.types.js +37 -0
  21. package/dist/definition/definition.types.js.map +1 -0
  22. package/dist/definition/validate-definition.d.ts +9 -0
  23. package/dist/definition/validate-definition.js +163 -0
  24. package/dist/definition/validate-definition.js.map +1 -0
  25. package/dist/definition/walk-steps.d.ts +5 -0
  26. package/dist/definition/walk-steps.js +31 -0
  27. package/dist/definition/walk-steps.js.map +1 -0
  28. package/dist/engine/engine-entry.d.ts +1 -0
  29. package/dist/engine/engine-entry.js +6 -0
  30. package/dist/engine/engine-entry.js.map +1 -0
  31. package/dist/engine/engine-global.d.ts +1 -0
  32. package/dist/engine/engine-global.js +5 -0
  33. package/dist/engine/engine-global.js.map +1 -0
  34. package/dist/engine/engine-source.d.ts +2 -0
  35. package/dist/engine/engine-source.js +3 -0
  36. package/dist/engine/run-in-isolate.d.ts +34 -0
  37. package/dist/engine/run-in-isolate.js +267 -0
  38. package/dist/engine/run-in-isolate.js.map +1 -0
  39. package/dist/errors/runtime-error-code.enum.d.ts +18 -0
  40. package/dist/errors/runtime-error-code.enum.js +19 -0
  41. package/dist/errors/runtime-error-code.enum.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.js +47 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/interpreter/interpreter-error.d.ts +5 -0
  46. package/dist/interpreter/interpreter-error.js +12 -0
  47. package/dist/interpreter/interpreter-error.js.map +1 -0
  48. package/dist/interpreter/interpreter.d.ts +30 -0
  49. package/dist/interpreter/interpreter.js +313 -0
  50. package/dist/interpreter/interpreter.js.map +1 -0
  51. package/dist/interpreter/interpreter.types.d.ts +152 -0
  52. package/dist/interpreter/interpreter.types.js +31 -0
  53. package/dist/interpreter/interpreter.types.js.map +1 -0
  54. package/dist/interpreter/sequence-path.d.ts +6 -0
  55. package/dist/interpreter/sequence-path.js +53 -0
  56. package/dist/interpreter/sequence-path.js.map +1 -0
  57. package/dist/interpreter/test-host.d.ts +18 -0
  58. package/dist/interpreter/test-host.js +43 -0
  59. package/dist/interpreter/test-host.js.map +1 -0
  60. package/dist/runner-protocol/evaluation.types.d.ts +20 -0
  61. package/dist/runner-protocol/evaluation.types.js +10 -0
  62. package/dist/runner-protocol/evaluation.types.js.map +1 -0
  63. package/dist/runner-protocol/execution-protocol.types.d.ts +132 -0
  64. package/dist/runner-protocol/execution-protocol.types.js +48 -0
  65. package/dist/runner-protocol/execution-protocol.types.js.map +1 -0
  66. package/dist/server/code-runner-error.d.ts +5 -0
  67. package/dist/server/code-runner-error.js +12 -0
  68. package/dist/server/code-runner-error.js.map +1 -0
  69. package/dist/server/code-runner-session.d.ts +28 -0
  70. package/dist/server/code-runner-session.js +208 -0
  71. package/dist/server/code-runner-session.js.map +1 -0
  72. package/dist/server/index.d.ts +3 -0
  73. package/dist/server/index.js +10 -0
  74. package/dist/server/index.js.map +1 -0
  75. package/dist/steps/execute-step.d.ts +50 -0
  76. package/dist/steps/execute-step.js +136 -0
  77. package/dist/steps/execute-step.js.map +1 -0
  78. package/dist/steps/global-references.d.ts +2 -0
  79. package/dist/steps/global-references.js +28 -0
  80. package/dist/steps/global-references.js.map +1 -0
  81. package/dist/steps/step-access.d.ts +8 -0
  82. package/dist/steps/step-access.js +39 -0
  83. package/dist/steps/step-access.js.map +1 -0
  84. package/dist/steps/step-fields.d.ts +5 -0
  85. package/dist/steps/step-fields.js +68 -0
  86. package/dist/steps/step-fields.js.map +1 -0
  87. package/dist/steps/value-source.d.ts +6 -0
  88. package/dist/steps/value-source.js +58 -0
  89. package/dist/steps/value-source.js.map +1 -0
  90. package/jest.config.ts +11 -0
  91. package/package.json +68 -3
  92. package/scripts/build-engine.cjs +70 -0
  93. package/src/__tests__/engine-bundle.test.ts +121 -0
  94. package/src/__tests__/surface.test.ts +53 -0
  95. package/src/access/__tests__/host-match.test.ts +24 -0
  96. package/src/access/access.types.ts +25 -0
  97. package/src/access/host-match.ts +13 -0
  98. package/src/cost/__tests__/execution-cost.test.ts +200 -0
  99. package/src/cost/execution-cost.ts +192 -0
  100. package/src/definition/__tests__/validate-definition.test.ts +354 -0
  101. package/src/definition/definition.limits.ts +9 -0
  102. package/src/definition/definition.schema.ts +172 -0
  103. package/src/definition/definition.types.ts +171 -0
  104. package/src/definition/validate-definition.ts +206 -0
  105. package/src/definition/walk-steps.ts +44 -0
  106. package/src/engine/__tests__/run-in-isolate.test.ts +468 -0
  107. package/src/engine/engine-entry.ts +3 -0
  108. package/src/engine/engine-global.ts +2 -0
  109. package/src/engine/run-in-isolate.ts +404 -0
  110. package/src/errors/runtime-error-code.enum.ts +37 -0
  111. package/src/index.ts +30 -0
  112. package/src/interpreter/__tests__/interpreter.test.ts +854 -0
  113. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -0
  114. package/src/interpreter/interpreter-error.ts +12 -0
  115. package/src/interpreter/interpreter.ts +461 -0
  116. package/src/interpreter/interpreter.types.ts +192 -0
  117. package/src/interpreter/sequence-path.ts +67 -0
  118. package/src/interpreter/test-host.ts +85 -0
  119. package/src/runner-protocol/evaluation.types.ts +21 -0
  120. package/src/runner-protocol/execution-protocol.types.ts +221 -0
  121. package/src/server/__tests__/code-runner-session.test.ts +311 -0
  122. package/src/server/code-runner-error.ts +12 -0
  123. package/src/server/code-runner-session.ts +310 -0
  124. package/src/server/index.ts +11 -0
  125. package/src/steps/__tests__/global-references.test.ts +113 -0
  126. package/src/steps/execute-step.ts +186 -0
  127. package/src/steps/global-references.ts +48 -0
  128. package/src/steps/step-access.ts +56 -0
  129. package/src/steps/step-fields.ts +87 -0
  130. package/src/steps/value-source.ts +69 -0
  131. package/tsconfig.check.json +15 -0
  132. package/tsconfig.json +35 -0
@@ -0,0 +1,192 @@
1
+ // Metered cost of an execution, shared by Flow and Reflex (ADR-0239). Prices are in
2
+ // millicredits (thousandths of a credit). Every part is computed exactly, in integer
3
+ // sub-millicredit units, and rounded half-up once, at the end.
4
+
5
+ export enum ResourceProfile {
6
+ S = 'S',
7
+ M = 'M',
8
+ L = 'L',
9
+ XL = 'XL',
10
+ XXL = 'XXL',
11
+ }
12
+
13
+ export interface ResourceProfileSpec {
14
+ /** Memory of the execution's isolate. */
15
+ memoryMb: number;
16
+ /** Multiplies the CPU part. */
17
+ cpuCoefficient: number;
18
+ }
19
+
20
+ export const RESOURCE_PROFILES: Readonly<Record<ResourceProfile, ResourceProfileSpec>> = {
21
+ [ResourceProfile.S]: { memoryMb: 128, cpuCoefficient: 1 },
22
+ [ResourceProfile.M]: { memoryMb: 256, cpuCoefficient: 1.05 },
23
+ [ResourceProfile.L]: { memoryMb: 512, cpuCoefficient: 1.1 },
24
+ [ResourceProfile.XL]: { memoryMb: 1024, cpuCoefficient: 1.2 },
25
+ [ResourceProfile.XXL]: { memoryMb: 2048, cpuCoefficient: 1.35 },
26
+ };
27
+
28
+ /** The ADR-0239 price list, in millicredits. */
29
+ export const COST_RATES = {
30
+ /** Once per execution, whatever its number of segments. */
31
+ executionMillicredits: 10,
32
+ cpuMillicreditsPerSecond: 500,
33
+ /** Multiplies the CPU part of an execution with a guaranteed core. */
34
+ guaranteedCpuCoefficient: 1.5,
35
+ /** Per GB-second of ALLOCATED memory (the profile's), GB = 1024 MB. */
36
+ memoryMillicreditsPerGbSecond: 100,
37
+ /** Per MB sent out, MB = 1024 × 1024 bytes. */
38
+ networkOutMillicreditsPerMb: 1000,
39
+ httpCallMillicredits: 10,
40
+ storeWriteMillicredits: 10,
41
+ } as const;
42
+
43
+ export enum CostedExecutionStatus {
44
+ /** Ran (succeeded, failed or suspended): billed at the measure. */
45
+ RAN = 'RAN',
46
+ /** Stopped by a pod shutdown: free (ADR-0239 §6). */
47
+ INTERRUPTED = 'INTERRUPTED',
48
+ /** Refused before any step (401, 404, 429, paused, invalid input): free. */
49
+ REFUSED = 'REFUSED',
50
+ }
51
+
52
+ /** What one step consumed. A refused host call is not counted in `httpCalls` nor `storeWrites`. */
53
+ export interface StepUsage {
54
+ cpuMs: number;
55
+ wallMs: number;
56
+ netOutBytes: number;
57
+ httpCalls: number;
58
+ storeWrites: number;
59
+ }
60
+
61
+ export interface ExecutionCostInput extends StepUsage {
62
+ status: CostedExecutionStatus;
63
+ profile: ResourceProfile;
64
+ guaranteedCpu: boolean;
65
+ /**
66
+ * True for the second and later segments of a suspended execution: they add their measure
67
+ * but not the execution price, paid once by the first segment.
68
+ */
69
+ resumedSegment?: boolean;
70
+ }
71
+
72
+ export interface StepCostInput {
73
+ /** The execution (segment) the steps belong to; its totals are what is billed. */
74
+ execution: ExecutionCostInput;
75
+ /** In execution order. */
76
+ steps: StepUsage[];
77
+ }
78
+
79
+ // Exact unit: 1 / UNITS_PER_MILLICREDIT of a millicredit. Durations are taken in microseconds
80
+ // (cpuMs and wallMs may carry fractions of a millisecond), coefficients in hundredths or
81
+ // thousandths. Each part is a product divided by a fixed denominator; UNITS_PER_MILLICREDIT is
82
+ // their least common multiple, 2^20 × 5^11, so that every part is an exact integer of units.
83
+ const MICROS_PER_SECOND = BigInt(1_000_000);
84
+ const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100) * BigInt(1000);
85
+ const MEMORY_DENOMINATOR = BigInt(1024) * MICROS_PER_SECOND;
86
+ const NETWORK_DENOMINATOR = BigInt(1024 * 1024);
87
+ const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(48_828_125);
88
+ const ZERO = BigInt(0);
89
+ const ONE = BigInt(1);
90
+ const TWO = BigInt(2);
91
+
92
+ const assertUsage = (usage: StepUsage, subject: string): void => {
93
+ (['cpuMs', 'wallMs', 'netOutBytes', 'httpCalls', 'storeWrites'] as const).forEach((key) => {
94
+ const value = usage[key];
95
+ if (!Number.isFinite(value) || value < 0) {
96
+ throw new RangeError(`${subject}.${key} must be a finite number >= 0, got ${value}`);
97
+ }
98
+ });
99
+ };
100
+
101
+ const micros = (ms: number): bigint => BigInt(Math.round(ms * 1000));
102
+ const whole = (count: number): bigint => BigInt(Math.round(count));
103
+ /** Coefficients have at most two decimals (1.05) or one (1.5): exact as integers. */
104
+ const hundredths = (coefficient: number): bigint => BigInt(Math.round(coefficient * 100));
105
+ const thousandths = (coefficient: number): bigint => BigInt(Math.round(coefficient * 1000));
106
+
107
+ /** Variable cost (everything but the execution price) of a usage, in exact units. */
108
+ const variableUnits = (usage: StepUsage, execution: ExecutionCostInput): bigint => {
109
+ const profile = RESOURCE_PROFILES[execution.profile];
110
+ const guaranteed = execution.guaranteedCpu ? COST_RATES.guaranteedCpuCoefficient : 1;
111
+ // cpuUs / 10^6 s × rate × coefficient% / 100 × guaranteed‰ / 1000
112
+ const cpu =
113
+ (micros(usage.cpuMs) *
114
+ BigInt(COST_RATES.cpuMillicreditsPerSecond) *
115
+ hundredths(profile.cpuCoefficient) *
116
+ thousandths(guaranteed) *
117
+ UNITS_PER_MILLICREDIT) /
118
+ CPU_DENOMINATOR;
119
+ // memoryMb / 1024 GB × wallUs / 10^6 s × rate
120
+ const memory =
121
+ (BigInt(profile.memoryMb) *
122
+ micros(usage.wallMs) *
123
+ BigInt(COST_RATES.memoryMillicreditsPerGbSecond) *
124
+ UNITS_PER_MILLICREDIT) /
125
+ MEMORY_DENOMINATOR;
126
+ // bytes / (1024 × 1024) MB × rate
127
+ const network =
128
+ (whole(usage.netOutBytes) *
129
+ BigInt(COST_RATES.networkOutMillicreditsPerMb) *
130
+ UNITS_PER_MILLICREDIT) /
131
+ NETWORK_DENOMINATOR;
132
+ const effects =
133
+ (whole(usage.httpCalls) * BigInt(COST_RATES.httpCallMillicredits) +
134
+ whole(usage.storeWrites) * BigInt(COST_RATES.storeWriteMillicredits)) *
135
+ UNITS_PER_MILLICREDIT;
136
+ return cpu + memory + network + effects;
137
+ };
138
+
139
+ /** Floor division, also for a negative numerator. */
140
+ const floorDiv = (numerator: bigint, denominator: bigint): bigint => {
141
+ const quotient = numerator / denominator;
142
+ return numerator % denominator !== ZERO && numerator < ZERO ? quotient - ONE : quotient;
143
+ };
144
+
145
+ /** Exact units to whole millicredits, half-up. */
146
+ const roundHalfUp = (units: bigint): number =>
147
+ Number(floorDiv(units * TWO + UNITS_PER_MILLICREDIT, UNITS_PER_MILLICREDIT * TWO));
148
+
149
+ const isFree = (execution: ExecutionCostInput): boolean =>
150
+ execution.status !== CostedExecutionStatus.RAN;
151
+
152
+ const executionPrice = (execution: ExecutionCostInput): number =>
153
+ isFree(execution) || execution.resumedSegment ? 0 : COST_RATES.executionMillicredits;
154
+
155
+ /** Cost of an execution (or of one segment of it), in whole millicredits. */
156
+ export const computeExecutionCost = (input: ExecutionCostInput): number => {
157
+ assertUsage(input, 'execution');
158
+ if (isFree(input)) {
159
+ return 0;
160
+ }
161
+ return executionPrice(input) + roundHalfUp(variableUnits(input, input));
162
+ };
163
+
164
+ /**
165
+ * Spreads the variable cost of an execution over its steps, one whole number of millicredits
166
+ * per step, in the order given. Each step gets its CPU, its memory (allocated memory × its
167
+ * duration), its network and its effects; what the execution measured outside any step (the
168
+ * engine between two steps) goes to the last step. Rounding is cumulative, so that
169
+ * `sum(steps) + execution price = computeExecutionCost(execution)` holds exactly. An execution
170
+ * that ran no step has nothing to spread: the result is empty.
171
+ */
172
+ export const computeStepCost = (input: StepCostInput): number[] => {
173
+ const { execution, steps } = input;
174
+ assertUsage(execution, 'execution');
175
+ steps.forEach((step, index) => assertUsage(step, `steps[${index}]`));
176
+ if (steps.length === 0) {
177
+ return [];
178
+ }
179
+ if (isFree(execution)) {
180
+ return steps.map(() => 0);
181
+ }
182
+ const total = variableUnits(execution, execution);
183
+ let cumulative = ZERO;
184
+ let assigned = 0;
185
+ return steps.map((step, index) => {
186
+ cumulative = index === steps.length - 1 ? total : cumulative + variableUnits(step, execution);
187
+ const rounded = roundHalfUp(cumulative);
188
+ const cost = rounded - assigned;
189
+ assigned = rounded;
190
+ return cost;
191
+ });
192
+ };
@@ -0,0 +1,354 @@
1
+ import Joi from 'joi';
2
+ import { AccessKind } from '../../access/access.types';
3
+ import {
4
+ CURRENT_FORMAT_VERSION,
5
+ HttpMethod,
6
+ LogLevel,
7
+ StepType,
8
+ StopStatus,
9
+ } from '../definition.types';
10
+ import type { HostActionCatalog } from '../definition.types';
11
+ import { MAX_WAIT_DURATION_MS } from '../definition.schema';
12
+ import { validateDefinition } from '../validate-definition';
13
+ import { walkSteps } from '../walk-steps';
14
+
15
+ const catalog: HostActionCatalog = new Map([
16
+ [
17
+ 'send-email',
18
+ {
19
+ name: 'send-email',
20
+ inputSchema: Joi.object({ to: Joi.string().required(), subject: Joi.string() }),
21
+ },
22
+ ],
23
+ ]);
24
+
25
+ const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
26
+
27
+ const validDefinition = () => ({
28
+ formatVersion: CURRENT_FORMAT_VERSION,
29
+ accesses: [
30
+ { kind: AccessKind.HTTP, hosts: ['api.example.com', '*.hooks.example.com'] },
31
+ { kind: AccessKind.HOST_ACTION, action: 'send-email' },
32
+ ],
33
+ steps: [
34
+ { id: 'init', type: StepType.SET, variable: 'count', value: 0 },
35
+ {
36
+ id: 'check',
37
+ type: StepType.CONDITION,
38
+ if: { $expression: 'input.amount > 10' },
39
+ then: [
40
+ {
41
+ id: 'fetch',
42
+ type: StepType.HTTP,
43
+ method: HttpMethod.POST,
44
+ url: 'https://api.example.com/v1/items',
45
+ headers: { Authorization: 'Bearer {{ input.token }}', 'X-List': ['a', { b: 1 }] },
46
+ body: { items: [1, 2, { $expression: 'input.items' }] },
47
+ timeoutMs: 5000,
48
+ },
49
+ {
50
+ id: 'mail',
51
+ type: StepType.HOST,
52
+ action: 'send-email',
53
+ input: { to: '{{ input.email }}', subject: 'Hello' },
54
+ },
55
+ ],
56
+ else: [
57
+ { id: 'pause', type: StepType.WAIT, durationMs: 1000 },
58
+ {
59
+ id: 'note',
60
+ type: StepType.LOG,
61
+ level: LogLevel.WARN,
62
+ message: 'small amount: {{ input.amount }}',
63
+ data: { amount: { $expression: 'input.amount' } },
64
+ },
65
+ {
66
+ id: 'reply',
67
+ type: StepType.RESPOND,
68
+ status: 202,
69
+ headers: { 'Content-Type': 'application/json' },
70
+ body: { accepted: true },
71
+ },
72
+ ],
73
+ },
74
+ {
75
+ id: 'route',
76
+ type: StepType.SWITCH,
77
+ value: '{{ input.kind }}',
78
+ cases: [
79
+ {
80
+ match: 'a',
81
+ steps: [
82
+ { id: 'compute', type: StepType.CODE, source: 'return input.n * 2;' },
83
+ { id: 'later', type: StepType.WAIT, until: '2026-12-31T00:00:00Z' },
84
+ ],
85
+ },
86
+ {
87
+ match: null,
88
+ steps: [
89
+ {
90
+ id: 'hook',
91
+ type: StepType.HTTP,
92
+ method: HttpMethod.GET,
93
+ url: 'https://x.hooks.example.com/ping',
94
+ },
95
+ ],
96
+ },
97
+ ],
98
+ default: [{ id: 'fail', type: StepType.STOP, status: StopStatus.FAILED, output: 'unknown' }],
99
+ },
100
+ { id: 'done', type: StepType.STOP, status: StopStatus.SUCCEEDED },
101
+ ],
102
+ });
103
+
104
+ const errorsOf = (raw: unknown) => {
105
+ const result = validateDefinition(raw, catalog);
106
+ if (result.ok) {
107
+ throw new Error('expected a refusal');
108
+ }
109
+ return result.errors;
110
+ };
111
+
112
+ const pathsOf = (raw: unknown) => errorsOf(raw).map((error) => error.path);
113
+
114
+ describe('validateDefinition', () => {
115
+ it('accepts a complete definition with the 10 step types and nested branches', () => {
116
+ const raw = validDefinition();
117
+ const result = validateDefinition(raw, catalog);
118
+ expect(result).toEqual({ ok: true, definition: raw });
119
+ const types = new Set<string>();
120
+ walkSteps(raw.steps as never, (step) => types.add(step.type));
121
+ expect([...types].sort()).toEqual(Object.values(StepType).sort());
122
+ });
123
+
124
+ it('rejects an unknown formatVersion at "formatVersion"', () => {
125
+ const raw = { ...validDefinition(), formatVersion: 2 };
126
+ expect(pathsOf(raw)).toEqual(['formatVersion']);
127
+ });
128
+
129
+ it('rejects a duplicated id on the second occurrence', () => {
130
+ const raw = validDefinition();
131
+ (raw.steps[1] as any).then[0].id = 'init';
132
+ expect(pathsOf(raw)).toEqual(['steps[1].then[0].id']);
133
+ });
134
+
135
+ it('rejects __proto__, constructor and prototype as step id and as SET variable', () => {
136
+ for (const name of ['__proto__', 'constructor', 'prototype']) {
137
+ const asId = validDefinition();
138
+ (asId.steps[0] as any).id = name;
139
+ expect(pathsOf(asId)).toEqual(['steps[0].id']);
140
+ const asVariable = validDefinition();
141
+ (asVariable.steps[0] as any).variable = name;
142
+ expect(pathsOf(asVariable)).toEqual(['steps[0].variable']);
143
+ }
144
+ });
145
+
146
+ it('bounds a literal WAIT duration to MAX_WAIT_DURATION_MS', () => {
147
+ expect(MAX_WAIT_DURATION_MS).toBe(30 * 24 * 60 * 60 * 1000);
148
+ const at = (durationMs: unknown) => ({
149
+ ...validDefinition(),
150
+ steps: [{ id: 'w', type: StepType.WAIT, durationMs }],
151
+ });
152
+ expect(validateDefinition(at(MAX_WAIT_DURATION_MS), catalog).ok).toBe(true);
153
+ expect(validateDefinition(at({ $expression: 'input.d' }), catalog).ok).toBe(true);
154
+ expect(validateDefinition(at('{{ input.d }}'), catalog).ok).toBe(true);
155
+ for (const bad of [MAX_WAIT_DURATION_MS + 1, -1, 1.5]) {
156
+ expect(pathsOf(at(bad))).toEqual(['steps[0].durationMs']);
157
+ }
158
+ });
159
+
160
+ it('requires a literal WAIT until to be an ISO 8601 date', () => {
161
+ const at = (until: unknown) => ({
162
+ ...validDefinition(),
163
+ steps: [{ id: 'w', type: StepType.WAIT, until }],
164
+ });
165
+ expect(validateDefinition(at('2030-01-01T00:00:00.000Z'), catalog).ok).toBe(true);
166
+ expect(validateDefinition(at('{{ input.when }}'), catalog).ok).toBe(true);
167
+ expect(validateDefinition(at({ $expression: 'input.when' }), catalog).ok).toBe(true);
168
+ expect(pathsOf(at('tomorrow'))).toEqual(['steps[0].until']);
169
+ expect(pathsOf(at(12))).toEqual(['steps[0].until']);
170
+ });
171
+
172
+ it('requires a LOG level among info, warn, error and a message', () => {
173
+ const at = (step: Record<string, unknown>) => ({
174
+ ...validDefinition(),
175
+ steps: [{ id: 'l', type: StepType.LOG, ...step }],
176
+ });
177
+ expect(
178
+ validateDefinition(at({ level: 'info', message: { $expression: 'input' } }), catalog).ok,
179
+ ).toBe(true);
180
+ expect(pathsOf(at({ level: 'debug', message: 'x' }))).toEqual(['steps[0].level']);
181
+ expect(pathsOf(at({ level: 'error' }))).toEqual(['steps[0].message']);
182
+ });
183
+
184
+ it('requires a RESPOND status, a literal one being an HTTP status', () => {
185
+ const at = (status: unknown) => ({
186
+ ...validDefinition(),
187
+ steps: [{ id: 'r', type: StepType.RESPOND, status }],
188
+ });
189
+ for (const good of [100, 200, 599, '{{ input.status }}', { $expression: 'input.status' }]) {
190
+ expect(validateDefinition(at(good), catalog).ok).toBe(true);
191
+ }
192
+ for (const bad of [99, 600, 200.5, 'ok']) {
193
+ expect(pathsOf(at(bad))).toEqual(['steps[0].status']);
194
+ }
195
+ const missing = { ...validDefinition(), steps: [{ id: 'r', type: StepType.RESPOND }] };
196
+ expect(pathsOf(missing)).toEqual(['steps[0].status']);
197
+ });
198
+
199
+ it('rejects an action absent from the catalog at the path of "action"', () => {
200
+ const raw = validDefinition();
201
+ (raw.steps[1] as any).then[1].action = 'send-sms';
202
+ const paths = pathsOf(raw);
203
+ expect(paths).toContain('steps[1].then[1].action');
204
+ });
205
+
206
+ it('rejects an input key outside the action schema', () => {
207
+ const raw = validDefinition();
208
+ (raw.steps[1] as any).then[1].input.cc = 'x@y.z';
209
+ expect(pathsOf(raw)).toEqual(['steps[1].then[1].input.cc']);
210
+ });
211
+
212
+ it('rejects an HTTP step towards an undeclared host', () => {
213
+ const raw = validDefinition();
214
+ (raw.steps[1] as any).then[0].url = 'https://evil.example.org/x';
215
+ expect(pathsOf(raw)).toEqual(['steps[1].then[0]']);
216
+ });
217
+
218
+ it('does not let a wildcard declaration cover the apex host', () => {
219
+ const raw = validDefinition();
220
+ (raw.steps[2] as any).cases[1].steps[0].url = 'https://hooks.example.com/ping';
221
+ expect(pathsOf(raw)).toEqual(['steps[2].cases[1].steps[0]']);
222
+ });
223
+
224
+ it('skips the host check when the URL is a template', () => {
225
+ const raw = validDefinition();
226
+ (raw.steps[1] as any).then[0].url = 'https://{{ input.host }}/x';
227
+ expect(validateDefinition(raw, catalog).ok).toBe(true);
228
+ });
229
+
230
+ it('requires an HTTP declaration for any HTTP step', () => {
231
+ const raw = validDefinition();
232
+ raw.accesses = raw.accesses.filter((access) => access.kind !== AccessKind.HTTP);
233
+ (raw.steps[1] as any).then[0].url = '{{ input.url }}';
234
+ expect(pathsOf(raw)).toContain('steps[1].then[0]');
235
+ });
236
+
237
+ it('rejects a HOST step whose action is not declared', () => {
238
+ const raw = validDefinition();
239
+ raw.accesses = raw.accesses.filter((access) => access.kind !== AccessKind.HOST_ACTION);
240
+ expect(pathsOf(raw)).toEqual(['steps[1].then[1]']);
241
+ });
242
+
243
+ it('rejects a WAIT with both durationMs and until', () => {
244
+ const raw = validDefinition();
245
+ (raw.steps[1] as any).else[0].until = '2026-12-31T00:00:00Z';
246
+ expect(pathsOf(raw)).toEqual(['steps[1].else[0]']);
247
+ });
248
+
249
+ it('rejects a WAIT with neither durationMs nor until', () => {
250
+ const raw = validDefinition();
251
+ delete (raw.steps[1] as any).else[0].durationMs;
252
+ expect(pathsOf(raw)).toEqual(['steps[1].else[0]']);
253
+ });
254
+
255
+ it('rejects an object carrying $expression and another key', () => {
256
+ const raw = validDefinition();
257
+ (raw.steps[0] as any).value = { $expression: '1 + 1', other: 2 };
258
+ expect(pathsOf(raw)).toEqual(['steps[0].value']);
259
+ });
260
+
261
+ it('rejects a $expression that is not a string', () => {
262
+ const raw = validDefinition();
263
+ (raw.steps[0] as any).value = { $expression: 3 };
264
+ expect(pathsOf(raw)).toEqual(['steps[0].value']);
265
+ });
266
+
267
+ it('rejects an invalid SET variable, an empty id and an unknown STOP status', () => {
268
+ const raw = validDefinition();
269
+ (raw.steps[0] as any).variable = 'not valid';
270
+ (raw.steps[3] as any).id = '';
271
+ (raw.steps[2] as any).default[0].status = 'MAYBE';
272
+ expect(pathsOf(raw).sort()).toEqual(
273
+ ['steps[0].variable', 'steps[2].default[0].status', 'steps[3].id'].sort(),
274
+ );
275
+ });
276
+
277
+ it('rejects a SWITCH without case', () => {
278
+ const raw = validDefinition();
279
+ (raw.steps[2] as any).cases = [];
280
+ expect(pathsOf(raw)).toEqual(['steps[2].cases']);
281
+ });
282
+
283
+ it('bounds the HTTP timeout to a positive integer of at most 30000', () => {
284
+ const tooLong = validDefinition();
285
+ (tooLong.steps[1] as any).then[0].timeoutMs = 30001;
286
+ expect(pathsOf(tooLong)).toEqual(['steps[1].then[0].timeoutMs']);
287
+ const fractional = validDefinition();
288
+ (fractional.steps[1] as any).then[0].timeoutMs = 1.5;
289
+ expect(pathsOf(fractional)).toEqual(['steps[1].then[0].timeoutMs']);
290
+ });
291
+
292
+ it('rejects HTTP headers that are not value sources', () => {
293
+ const raw = validDefinition();
294
+ (raw.steps[1] as any).then[0].headers = { 'X-Bad': { $expression: 'a', extra: 1 } };
295
+ expect(pathsOf(raw)).toEqual(['steps[1].then[0].headers.X-Bad']);
296
+ });
297
+
298
+ it('rejects a malformed access declaration', () => {
299
+ const raw = validDefinition();
300
+ (raw.accesses[0] as any).hosts = ['https://api.example.com/'];
301
+ (raw.accesses as any[]).push({ kind: 'FTP' });
302
+ const paths = pathsOf(raw);
303
+ expect(paths).toContain('accesses[0].hosts[0]');
304
+ expect(paths).toContain('accesses[2].kind');
305
+ });
306
+
307
+ it('rejects an unknown step type and a non-object step', () => {
308
+ const raw = validDefinition();
309
+ (raw.steps as any[]).push({ id: 'x', type: 'LOOP' }, 'oops');
310
+ expect(pathsOf(raw)).toEqual(['steps[4].type', 'steps[5]']);
311
+ });
312
+
313
+ it('collects every error instead of stopping at the first', () => {
314
+ const raw = validDefinition();
315
+ (raw.steps[1] as any).then[1].action = 'send-sms';
316
+ (raw.steps[1] as any).then[0].url = 'https://evil.example.org/x';
317
+ (raw.steps[0] as any).variable = '1x';
318
+ expect(errorsOf(raw).length).toBeGreaterThanOrEqual(3);
319
+ });
320
+
321
+ it('rejects a document that is not an object', () => {
322
+ expect(pathsOf('nope')).toEqual(['']);
323
+ expect(pathsOf(null)).toEqual(['']);
324
+ });
325
+
326
+ it('does not mutate its input', () => {
327
+ const raw = validDefinition();
328
+ const copy = clone(raw);
329
+ validateDefinition(raw, catalog);
330
+ expect(raw).toEqual(copy);
331
+ });
332
+ });
333
+
334
+ describe('walkSteps', () => {
335
+ it('visits steps in document order with their JSON path', () => {
336
+ const visited: string[] = [];
337
+ walkSteps(validDefinition().steps as never, (step, path) => visited.push(`${path}:${step.id}`));
338
+ expect(visited).toEqual([
339
+ 'steps[0]:init',
340
+ 'steps[1]:check',
341
+ 'steps[1].then[0]:fetch',
342
+ 'steps[1].then[1]:mail',
343
+ 'steps[1].else[0]:pause',
344
+ 'steps[1].else[1]:note',
345
+ 'steps[1].else[2]:reply',
346
+ 'steps[2]:route',
347
+ 'steps[2].cases[0].steps[0]:compute',
348
+ 'steps[2].cases[0].steps[1]:later',
349
+ 'steps[2].cases[1].steps[0]:hook',
350
+ 'steps[2].default[0]:fail',
351
+ 'steps[3]:done',
352
+ ]);
353
+ });
354
+ });
@@ -0,0 +1,9 @@
1
+ // Bounds of the definition format, without Joi: the interpreter and the isolate engine bundle
2
+ // read them, and neither may pull Joi in (see `engine/run-in-isolate.ts`).
3
+
4
+ export const MAX_HTTP_TIMEOUT_MS = 30_000;
5
+ export const MAX_WAIT_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
6
+
7
+ /** HTTP status range a RESPOND step may send. */
8
+ export const MIN_RESPONSE_STATUS = 100;
9
+ export const MAX_RESPONSE_STATUS = 599;