@telorun/sdk 0.2.4 → 0.2.5
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 +3 -3
- package/dist/capabilities/invokable.d.ts +4 -0
- package/dist/capabilities/invokable.d.ts.map +1 -0
- package/dist/capabilities/invokable.js +1 -0
- package/dist/capabilities/provider.d.ts +4 -0
- package/dist/capabilities/provider.d.ts.map +1 -0
- package/dist/capabilities/provider.js +1 -0
- package/dist/capabilities/runnable.d.ts +4 -0
- package/dist/capabilities/runnable.d.ts.map +1 -0
- package/dist/capabilities/runnable.js +1 -0
- package/dist/context-provider.d.ts +1 -0
- package/dist/context-provider.d.ts.map +1 -0
- package/dist/controller-context.d.ts +2 -2
- package/dist/controller-context.d.ts.map +1 -0
- package/dist/evaluation-context.d.ts +103 -0
- package/dist/evaluation-context.d.ts.map +1 -0
- package/dist/evaluation-context.js +256 -0
- package/dist/execution-context.d.ts +13 -0
- package/dist/execution-context.d.ts.map +1 -0
- package/dist/execution-context.js +13 -0
- package/dist/index.d.ts +15 -8
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -8
- package/dist/module-context.d.ts +51 -0
- package/dist/module-context.d.ts.map +1 -0
- package/dist/module-context.js +150 -0
- package/dist/resource-context.d.ts +11 -0
- package/dist/resource-context.d.ts.map +1 -0
- package/dist/resource-instance.d.ts +1 -0
- package/dist/resource-instance.d.ts.map +1 -0
- package/dist/resource-manifest.d.ts +2 -1
- package/dist/resource-manifest.d.ts.map +1 -0
- package/dist/runtime-error.d.ts +2 -1
- package/dist/runtime-error.d.ts.map +1 -0
- package/dist/runtime-event.d.ts +1 -0
- package/dist/runtime-event.d.ts.map +1 -0
- package/dist/runtime-resource.d.ts +1 -0
- package/dist/runtime-resource.d.ts.map +1 -0
- package/dist/types.d.ts +62 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +8 -0
- package/package.json +5 -1
- package/src/capabilities/invokable.ts +3 -0
- package/src/capabilities/provider.ts +3 -0
- package/src/capabilities/runnable.ts +3 -0
- package/src/controller-context.ts +4 -14
- package/src/evaluation-context.ts +337 -0
- package/src/execution-context.ts +21 -0
- package/src/index.ts +14 -8
- package/src/module-context.ts +187 -0
- package/src/resource-context.ts +11 -5
- package/src/resource-manifest.ts +1 -1
- package/src/runtime-error.ts +11 -8
- package/src/types.ts +83 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { evaluate } from "cel-js";
|
|
2
|
+
import { ModuleContext } from "./module-context.js";
|
|
3
|
+
import { ResourceInstance } from "./resource-instance.js";
|
|
4
|
+
import { ResourceManifest } from "./resource-manifest.js";
|
|
5
|
+
import { RuntimeError } from "./types.js";
|
|
6
|
+
|
|
7
|
+
export type EmitEvent = (event: string, payload?: any) => void | Promise<void>;
|
|
8
|
+
|
|
9
|
+
const TEMPLATE_REGEX = /\$\{\{\s*([^}]+?)\s*\}\}/g;
|
|
10
|
+
const EXACT_TEMPLATE_REGEX = /^\s*\$\{\{\s*([^}]+?)\s*\}\}\s*$/;
|
|
11
|
+
|
|
12
|
+
/** Four-stage resource lifecycle defined in resource-lifecycle.md */
|
|
13
|
+
export type LifecycleState = "Pending" | "Validated" | "Initialized" | "Draining" | "Teardown";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Creates a ResourceInstance for the given manifest, or returns null if not yet
|
|
17
|
+
* ready (e.g. a dependency is still initializing). Injected at construction so
|
|
18
|
+
* every EvaluationContext node owns its full resource lifecycle.
|
|
19
|
+
*/
|
|
20
|
+
export type InstanceFactory = (
|
|
21
|
+
moduleContext: ModuleContext,
|
|
22
|
+
resource: ResourceManifest,
|
|
23
|
+
) => Promise<ResourceInstance | null>;
|
|
24
|
+
|
|
25
|
+
/** Canonical key for a resource instance: "<module>.<kind>.<name>" */
|
|
26
|
+
export function resourceKey(r: ResourceManifest): string {
|
|
27
|
+
return `${r.kind}.${r.metadata.name}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function redactSecrets(message: string, secretValues: Set<string>): string {
|
|
31
|
+
if (secretValues.size === 0) return message;
|
|
32
|
+
const sorted = Array.from(secretValues).sort((a, b) => b.length - a.length);
|
|
33
|
+
let result = message;
|
|
34
|
+
for (const secret of sorted) {
|
|
35
|
+
result = result.split(secret).join("[REDACTED]");
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Base class for all evaluation contexts. Owns CEL evaluation, template
|
|
42
|
+
* expansion, secrets redaction, and the generic resource lifecycle tree.
|
|
43
|
+
*
|
|
44
|
+
* Every EvaluationContext node can:
|
|
45
|
+
* - Hold its own resource instances (resourceInstances)
|
|
46
|
+
* - Queue resources for initialization (pendingResources)
|
|
47
|
+
* - Spawn child contexts (spawnChild) forming a lifecycle tree
|
|
48
|
+
* - Run a multi-pass initialization loop (initializeResources)
|
|
49
|
+
* - Cascade teardown depth-first through the tree (teardownResources)
|
|
50
|
+
*/
|
|
51
|
+
export class EvaluationContext {
|
|
52
|
+
readonly id = Math.random().toString(16).slice(2, 8);
|
|
53
|
+
protected _context: Record<string, unknown>;
|
|
54
|
+
protected _secretValues: Set<string>;
|
|
55
|
+
protected _createInstance: InstanceFactory;
|
|
56
|
+
readonly emit: EmitEvent;
|
|
57
|
+
|
|
58
|
+
/** Position in the lifecycle tree. */
|
|
59
|
+
parent: EvaluationContext | undefined = undefined;
|
|
60
|
+
readonly children: EvaluationContext[] = [];
|
|
61
|
+
|
|
62
|
+
/** Current lifecycle state of this context node. */
|
|
63
|
+
state: LifecycleState = "Pending";
|
|
64
|
+
|
|
65
|
+
/** Resource instances owned by this context node, keyed by resourceKey(). */
|
|
66
|
+
readonly resourceInstances = new Map<
|
|
67
|
+
string,
|
|
68
|
+
{ resource: ResourceManifest; instance: ResourceInstance }
|
|
69
|
+
>();
|
|
70
|
+
|
|
71
|
+
/** Resources queued for initialization on this context node. */
|
|
72
|
+
private pendingResources: ResourceManifest[] = [];
|
|
73
|
+
|
|
74
|
+
constructor(
|
|
75
|
+
readonly source: string,
|
|
76
|
+
context: Record<string, unknown>,
|
|
77
|
+
createInstance: InstanceFactory = async () => null,
|
|
78
|
+
secretValues: Set<string>,
|
|
79
|
+
emit: EmitEvent,
|
|
80
|
+
) {
|
|
81
|
+
this._context = context;
|
|
82
|
+
this._createInstance = createInstance;
|
|
83
|
+
this._secretValues = secretValues ?? new Set();
|
|
84
|
+
this.emit = emit;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get createInstance(): InstanceFactory {
|
|
88
|
+
return this._createInstance;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get context(): Record<string, unknown> {
|
|
92
|
+
return this._context;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
get secretValues(): Set<string> {
|
|
96
|
+
return this._secretValues;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Queue a resource manifest for initialization on this context.
|
|
101
|
+
*/
|
|
102
|
+
registerManifest(resource: ResourceManifest): void {
|
|
103
|
+
if (!resource.metadata) {
|
|
104
|
+
resource.metadata = { name: `__unnamed_${Math.random().toString(16).slice(2, 8)}` };
|
|
105
|
+
}
|
|
106
|
+
this.pendingResources.push(resource);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Attach a child context to this node. The child's parent is set to this
|
|
111
|
+
* context and the child is registered under the given name.
|
|
112
|
+
*/
|
|
113
|
+
spawnChild<T extends EvaluationContext>(child: T): T {
|
|
114
|
+
child.parent = this;
|
|
115
|
+
this.children.push(child);
|
|
116
|
+
return child;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Multi-pass initialization loop. Processes pendingResources by calling the
|
|
121
|
+
* supplied instantiator for each resource, retrying failures across up to 10
|
|
122
|
+
* passes (handles dependency ordering without explicit topological sort).
|
|
123
|
+
*
|
|
124
|
+
* ERR_VISIBILITY_DENIED errors are fatal and re-thrown immediately.
|
|
125
|
+
* All other errors are tracked and retried until no progress is made.
|
|
126
|
+
*/
|
|
127
|
+
async initializeResources(): Promise<void> {
|
|
128
|
+
const MAX_PASSES = 10;
|
|
129
|
+
let pass = 1;
|
|
130
|
+
const errors = new Map<string, string>();
|
|
131
|
+
|
|
132
|
+
do {
|
|
133
|
+
const handled: string[] = [];
|
|
134
|
+
|
|
135
|
+
for (const resource of [...this.pendingResources]) {
|
|
136
|
+
// const rkey = resourceKey(resource);
|
|
137
|
+
// const displayKey = rkey;
|
|
138
|
+
const name = resource.metadata.name;
|
|
139
|
+
if (this.resourceInstances.has(name)) continue;
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
const instance = await this._createInstance(this as any, resource);
|
|
143
|
+
if (instance) {
|
|
144
|
+
this.resourceInstances.set(name, { resource, instance });
|
|
145
|
+
handled.push(name);
|
|
146
|
+
errors.delete(name);
|
|
147
|
+
}
|
|
148
|
+
} catch (error) {
|
|
149
|
+
if (error instanceof RuntimeError && error.code === "ERR_VISIBILITY_DENIED") throw error;
|
|
150
|
+
errors.set(name, error instanceof Error ? (error.stack ?? error.message) : String(error));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
for (const name of handled) {
|
|
155
|
+
const resource = this.pendingResources.find((m) => m.metadata.name === name)!;
|
|
156
|
+
const idx = this.pendingResources.indexOf(resource);
|
|
157
|
+
if (idx >= 0) this.pendingResources.splice(idx, 1);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
pass++;
|
|
161
|
+
if (handled.length === 0) break;
|
|
162
|
+
} while (pass <= MAX_PASSES);
|
|
163
|
+
|
|
164
|
+
if (this.pendingResources.length > 0) {
|
|
165
|
+
const unhandledList = this.pendingResources
|
|
166
|
+
.reverse()
|
|
167
|
+
.map((r) => `- ${r.metadata.name}: ${errors.get(r.metadata.name) ?? "Unknown error"}`)
|
|
168
|
+
.join("\n");
|
|
169
|
+
|
|
170
|
+
throw new RuntimeError(
|
|
171
|
+
"ERR_RESOURCE_INITIALIZATION_FAILED",
|
|
172
|
+
`Unable to process resources:\n\n${unhandledList}`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
this.state = "Initialized";
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
withManifests<T>(manifests: any[], fn: () => T): T {
|
|
180
|
+
const child = this.spawnChild(
|
|
181
|
+
new EvaluationContext(
|
|
182
|
+
this.source,
|
|
183
|
+
this._context,
|
|
184
|
+
this._createInstance,
|
|
185
|
+
this._secretValues,
|
|
186
|
+
this.emit,
|
|
187
|
+
),
|
|
188
|
+
);
|
|
189
|
+
try {
|
|
190
|
+
for (const manifest of manifests) {
|
|
191
|
+
child.registerManifest(manifest);
|
|
192
|
+
}
|
|
193
|
+
return fn();
|
|
194
|
+
} finally {
|
|
195
|
+
// Tear down child context and its resources immediately after fn() completes.
|
|
196
|
+
// Note that this does NOT emit Kernel-level events (e.g. Teardown events) —
|
|
197
|
+
// they remain the Kernel's responsibility.
|
|
198
|
+
child.teardownResources();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Cascade teardown depth-first through the tree:
|
|
204
|
+
* 1. Tear down child contexts in reverse registration order.
|
|
205
|
+
* 2. Tear down own resource instances in reverse registration order.
|
|
206
|
+
*
|
|
207
|
+
* Note: Kernel-level events (e.g. Teardown events) are NOT emitted here —
|
|
208
|
+
* they remain the Kernel's responsibility.
|
|
209
|
+
*/
|
|
210
|
+
async teardownResources(): Promise<void> {
|
|
211
|
+
this.state = "Draining";
|
|
212
|
+
for (const child of [...this.children].reverse()) {
|
|
213
|
+
await child.teardownResources();
|
|
214
|
+
}
|
|
215
|
+
const entries = [...this.resourceInstances.entries()].reverse();
|
|
216
|
+
for (const [key, { instance }] of entries) {
|
|
217
|
+
if (instance.teardown) await instance.teardown();
|
|
218
|
+
this.resourceInstances.delete(key);
|
|
219
|
+
}
|
|
220
|
+
this.state = "Teardown";
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Invoke a resource by kind and name within this context's resourceInstances.
|
|
225
|
+
* Emits a scoped Invoked event via the injected emit callback after invocation.
|
|
226
|
+
*/
|
|
227
|
+
async invoke(kind: string, name: string, ...args: any[]): Promise<any> {
|
|
228
|
+
const entry = this.resourceInstances.get(name);
|
|
229
|
+
|
|
230
|
+
if (entry) {
|
|
231
|
+
if (typeof entry.instance.invoke !== "function") {
|
|
232
|
+
throw new RuntimeError(
|
|
233
|
+
"ERR_RESOURCE_NOT_INVOKABLE",
|
|
234
|
+
`Resource ${kind}.${name} does not have an invoke method`,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
const outputs = await entry.instance.invoke(args[0]);
|
|
238
|
+
await this.emit(`${kind}.${name}.Invoked`, { outputs });
|
|
239
|
+
return outputs;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
throw new RuntimeError(
|
|
243
|
+
"ERR_RESOURCE_NOT_FOUND",
|
|
244
|
+
`Resource not found for invocation: ${kind}.${name}. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async run(name: string): Promise<void> {
|
|
249
|
+
const entry = this.resourceInstances.get(name);
|
|
250
|
+
if (entry && typeof entry.instance.run === "function") {
|
|
251
|
+
return entry.instance.run();
|
|
252
|
+
}
|
|
253
|
+
throw new RuntimeError(
|
|
254
|
+
"ERR_RESOURCE_NOT_RUNNABLE",
|
|
255
|
+
`Resource ${name} is not runnable or not found. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Evaluate a single CEL expression string against the context.
|
|
261
|
+
* Secret values are redacted from any thrown error message.
|
|
262
|
+
*/
|
|
263
|
+
evaluate(expression: string): unknown {
|
|
264
|
+
try {
|
|
265
|
+
return evaluate(expression, this._context);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
268
|
+
const safe = redactSecrets(raw, this._secretValues);
|
|
269
|
+
throw new Error(`CEL evaluation failed: "${expression}": ${safe}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Expand a value that may contain ${{ }} templates.
|
|
275
|
+
* Works recursively over strings, arrays, and objects.
|
|
276
|
+
* Templates whose identifiers are not present in the context are left
|
|
277
|
+
* unchanged (deferred) — they will be resolved at execution time when a
|
|
278
|
+
* richer ExecutionContext is available. All other CEL errors are propagated.
|
|
279
|
+
*/
|
|
280
|
+
expand(value: unknown): unknown {
|
|
281
|
+
if (typeof value === "string") {
|
|
282
|
+
return this.expandString(value);
|
|
283
|
+
}
|
|
284
|
+
if (Array.isArray(value)) {
|
|
285
|
+
return value.map((entry) => this.expand(entry));
|
|
286
|
+
}
|
|
287
|
+
if (value !== null && typeof value === "object") {
|
|
288
|
+
const resolved: Record<string, unknown> = {};
|
|
289
|
+
for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
|
|
290
|
+
resolved[key] = this.expand(entry);
|
|
291
|
+
}
|
|
292
|
+
return resolved;
|
|
293
|
+
}
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Merge another context on top of this one.
|
|
299
|
+
* Returns a new base EvaluationContext — 'other' wins on key conflict.
|
|
300
|
+
*/
|
|
301
|
+
merge(other: EvaluationContext | Record<string, unknown>): EvaluationContext {
|
|
302
|
+
const otherCtx = other instanceof EvaluationContext ? other.context : other;
|
|
303
|
+
const otherSecrets =
|
|
304
|
+
other instanceof EvaluationContext ? other.secretValues : new Set<string>();
|
|
305
|
+
const merged = Object.assign(Object.create(null), this._context, otherCtx) as Record<
|
|
306
|
+
string,
|
|
307
|
+
unknown
|
|
308
|
+
>;
|
|
309
|
+
const mergedSecrets = new Set<string>([...this._secretValues, ...otherSecrets]);
|
|
310
|
+
return new EvaluationContext(
|
|
311
|
+
this.source,
|
|
312
|
+
merged,
|
|
313
|
+
this._createInstance,
|
|
314
|
+
mergedSecrets,
|
|
315
|
+
this.emit,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private expandString(value: string): unknown {
|
|
320
|
+
if (!value.includes("${{")) {
|
|
321
|
+
return value;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const exact = value.match(EXACT_TEMPLATE_REGEX);
|
|
325
|
+
if (exact) {
|
|
326
|
+
return this.evaluate(exact[1]);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return value.replace(TEMPLATE_REGEX, (_match, expr: string) => {
|
|
330
|
+
const resolved = this.evaluate(expr);
|
|
331
|
+
if (resolved === null || resolved === undefined) {
|
|
332
|
+
return "";
|
|
333
|
+
}
|
|
334
|
+
return String(resolved);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { EvaluationContext } from "./evaluation-context.js";
|
|
2
|
+
import { ModuleContext } from "./module-context.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The ephemeral, per-trigger context layer. Merges a ModuleContext with
|
|
6
|
+
* arbitrary execution-time properties (e.g. { request, inputs } for HTTP;
|
|
7
|
+
* any shape is valid — determined by the trigger type).
|
|
8
|
+
*
|
|
9
|
+
* Execution props overlay the module namespaces on key conflict.
|
|
10
|
+
*/
|
|
11
|
+
export class ExecutionContext extends EvaluationContext {
|
|
12
|
+
constructor(moduleCtx: ModuleContext, execProps: Record<string, unknown>) {
|
|
13
|
+
super(
|
|
14
|
+
moduleCtx.source,
|
|
15
|
+
Object.assign(Object.create(null), moduleCtx.context, execProps) as Record<string, unknown>,
|
|
16
|
+
moduleCtx.createInstance,
|
|
17
|
+
moduleCtx.secretValues,
|
|
18
|
+
moduleCtx.emit,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
-
export * from
|
|
2
|
-
export * from
|
|
3
|
-
export * from
|
|
4
|
-
export * from
|
|
5
|
-
export * from
|
|
6
|
-
export * from
|
|
7
|
-
export * from
|
|
8
|
-
export * from
|
|
1
|
+
export * from "./capabilities/invokable.js";
|
|
2
|
+
export * from "./capabilities/provider.js";
|
|
3
|
+
export * from "./capabilities/runnable.js";
|
|
4
|
+
export * from "./context-provider.js";
|
|
5
|
+
export * from "./controller-context.js";
|
|
6
|
+
export * from "./evaluation-context.js";
|
|
7
|
+
export * from "./module-context.js";
|
|
8
|
+
export * from "./resource-context.js";
|
|
9
|
+
export * from "./resource-instance.js";
|
|
10
|
+
export * from "./resource-manifest.js";
|
|
11
|
+
export * from "./runtime-error.js";
|
|
12
|
+
export * from "./runtime-event.js";
|
|
13
|
+
export * from "./runtime-resource.js";
|
|
14
|
+
export * from "./types.js";
|
|
9
15
|
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { Invokable } from "./capabilities/invokable.js";
|
|
2
|
+
import { EmitEvent, EvaluationContext, InstanceFactory } from "./evaluation-context.js";
|
|
3
|
+
|
|
4
|
+
function collectSecretValues(secrets: Record<string, unknown>): Set<string> {
|
|
5
|
+
const values = new Set<string>();
|
|
6
|
+
for (const value of Object.values(secrets)) {
|
|
7
|
+
if (typeof value === "string" && value.length > 0) {
|
|
8
|
+
values.add(value);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return values;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Persistent, module-scoped context. Three reserved CEL namespaces:
|
|
16
|
+
* variables, secrets, resources.
|
|
17
|
+
*
|
|
18
|
+
* Unlike the base EvaluationContext, ModuleContext is stateful and mutable:
|
|
19
|
+
* variables/secrets/resources accumulate during multi-pass initialization and
|
|
20
|
+
* the context record is rebuilt on each mutation. Import aliases are tracked
|
|
21
|
+
* here for alias-prefixed kind resolution (e.g. MyImport.Http.Route).
|
|
22
|
+
*
|
|
23
|
+
* Imported modules are surfaced under resources.<alias> alongside local
|
|
24
|
+
* resources — no separate imports namespace needed.
|
|
25
|
+
*/
|
|
26
|
+
export class ModuleContext extends EvaluationContext {
|
|
27
|
+
private _variables: Record<string, unknown>;
|
|
28
|
+
private _secrets: Record<string, unknown>;
|
|
29
|
+
private _resources: Record<string, unknown>;
|
|
30
|
+
|
|
31
|
+
/** Maps import alias → real module name for kind resolution. */
|
|
32
|
+
readonly importAliases = new Map<string, string>();
|
|
33
|
+
|
|
34
|
+
/** Maps import alias → allowed kind names. Absent entry = unrestricted (e.g. Kernel). */
|
|
35
|
+
private readonly importedKinds = new Map<string, Set<string>>();
|
|
36
|
+
|
|
37
|
+
constructor(
|
|
38
|
+
source: string,
|
|
39
|
+
variables: Record<string, unknown> = {},
|
|
40
|
+
secrets: Record<string, unknown> = {},
|
|
41
|
+
resources: Record<string, unknown> = {},
|
|
42
|
+
private targets: string[] = [],
|
|
43
|
+
createInstance: InstanceFactory = async () => null,
|
|
44
|
+
emit: EmitEvent,
|
|
45
|
+
) {
|
|
46
|
+
super(source, {}, createInstance, new Set(), emit);
|
|
47
|
+
this._variables = variables;
|
|
48
|
+
this._secrets = secrets;
|
|
49
|
+
this._resources = resources;
|
|
50
|
+
this._rebuildContext();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
get variables(): Record<string, unknown> {
|
|
54
|
+
return this._variables;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
get secrets(): Record<string, unknown> {
|
|
58
|
+
return this._secrets;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
get resources(): Record<string, unknown> {
|
|
62
|
+
return this._resources;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
setVariables(vars: Record<string, unknown>): void {
|
|
66
|
+
this._variables = vars;
|
|
67
|
+
this._rebuildContext();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
setTargets(vars: string[]): void {
|
|
71
|
+
this.targets = vars;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
setSecrets(secrets: Record<string, unknown>): void {
|
|
75
|
+
this._secrets = secrets;
|
|
76
|
+
this._rebuildContext();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
setResource(name: string, props: Record<string, unknown>): void {
|
|
80
|
+
this._resources = { ...this._resources, [name]: props };
|
|
81
|
+
this._rebuildContext();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Register an imported module under the given alias, with the list of kind names
|
|
86
|
+
* it exports. An empty kinds array means no restriction (used for built-ins like Kernel).
|
|
87
|
+
*/
|
|
88
|
+
registerImport(alias: string, targetModule: string, kinds: string[]): void {
|
|
89
|
+
this.importAliases.set(alias, targetModule);
|
|
90
|
+
if (kinds.length > 0) {
|
|
91
|
+
this.importedKinds.set(alias, new Set(kinds));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
getInstance(name: string): unknown {
|
|
96
|
+
const entry = this.resourceInstances.get(name);
|
|
97
|
+
if (!entry) {
|
|
98
|
+
throw new Error(
|
|
99
|
+
`Resource '${name}' not found in module context. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
return entry?.instance;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
getInvokable(name: string): Invokable {
|
|
106
|
+
const instance = this.getInstance(name);
|
|
107
|
+
|
|
108
|
+
if (
|
|
109
|
+
instance &&
|
|
110
|
+
typeof instance === "object" &&
|
|
111
|
+
"invoke" in instance &&
|
|
112
|
+
typeof instance.invoke !== "function"
|
|
113
|
+
) {
|
|
114
|
+
throw new Error(`Resource '${name}' does not have an invoke() method.`);
|
|
115
|
+
}
|
|
116
|
+
return instance as Invokable;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Resolve a fully-qualified kind like "Http.Server" to its real kind "http-server.Server".
|
|
121
|
+
* Splits on the first dot, looks up the prefix in importAliases, validates against
|
|
122
|
+
* importedKinds (if set), and reconstructs the resolved kind.
|
|
123
|
+
* Throws with a clear message if the alias is unknown or the kind is not exported.
|
|
124
|
+
*/
|
|
125
|
+
resolveKind(kind: string): string {
|
|
126
|
+
const dot = kind.indexOf(".");
|
|
127
|
+
if (dot === -1) {
|
|
128
|
+
throw new Error(`Kind '${kind}' must be fully qualified (e.g. 'Module.KindName')`);
|
|
129
|
+
}
|
|
130
|
+
const prefix = kind.slice(0, dot);
|
|
131
|
+
const suffix = kind.slice(dot + 1);
|
|
132
|
+
const realModule = this.importAliases.get(prefix);
|
|
133
|
+
if (!realModule) {
|
|
134
|
+
const known = [...this.importAliases.keys()].join(", ") || "(none)";
|
|
135
|
+
throw new Error(
|
|
136
|
+
`Kind '${kind}': no module imported with alias '${prefix}'. Known aliases: ${known}`,
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const allowed = this.importedKinds.get(prefix);
|
|
140
|
+
if (allowed !== undefined && !allowed.has(suffix)) {
|
|
141
|
+
throw new Error(
|
|
142
|
+
`Kind '${suffix}' is not exported by module '${realModule}' (imported as '${prefix}'). ` +
|
|
143
|
+
`Exported kinds: ${[...allowed].join(", ")}`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
return `${realModule}.${suffix}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private _rebuildContext(): void {
|
|
150
|
+
this._context = {
|
|
151
|
+
variables: this._variables,
|
|
152
|
+
secrets: this._secrets,
|
|
153
|
+
resources: this._resources,
|
|
154
|
+
};
|
|
155
|
+
this._secretValues = collectSecretValues(this._secrets);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
override async invoke(kind: string, name: string, ...args: any[]): Promise<any> {
|
|
159
|
+
const result = await super.invoke(kind, name, ...args);
|
|
160
|
+
const entry = this.resourceInstances.get(name);
|
|
161
|
+
if (entry && typeof (entry.instance as any).snapshot === "function") {
|
|
162
|
+
const snap = await Promise.resolve((entry.instance as any).snapshot());
|
|
163
|
+
this.setResource(name, snap as Record<string, unknown>);
|
|
164
|
+
}
|
|
165
|
+
return result;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async run(name: string) {
|
|
169
|
+
const resource = this.resourceInstances.get(name);
|
|
170
|
+
if (!resource) {
|
|
171
|
+
throw new Error(
|
|
172
|
+
`Target resource ${name} not found in module context. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (typeof resource.instance.run === "function") {
|
|
176
|
+
await resource.instance.run();
|
|
177
|
+
} else {
|
|
178
|
+
throw new Error(`Target resource ${name} does not have a run() method.`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async runTargets() {
|
|
183
|
+
for (const target of this.targets) {
|
|
184
|
+
await this.run(target);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
package/src/resource-context.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { ControllerContext } from "./controller-context.js";
|
|
2
|
+
import { EvaluationContext } from "./evaluation-context.js";
|
|
3
|
+
import { ModuleContext } from "./module-context.js";
|
|
2
4
|
import { RuntimeResource } from "./runtime-resource.js";
|
|
3
5
|
|
|
4
6
|
export interface DataValidator {
|
|
@@ -20,22 +22,26 @@ export interface ResourceContext extends ControllerContext {
|
|
|
20
22
|
acquireHold(reason?: string): () => void;
|
|
21
23
|
emitEvent(event: string, payload?: any): Promise<void>;
|
|
22
24
|
invoke(kind: string, name: string, ...args: any[]): Promise<any>;
|
|
25
|
+
run(kind: string, name: string): Promise<void>;
|
|
23
26
|
getResources(kind: string): RuntimeResource[];
|
|
24
27
|
getResourcesByName(kind: string, name: string): RuntimeResource | null;
|
|
25
28
|
registerManifest(resource: any): void;
|
|
29
|
+
spawnChildContext(): EvaluationContext;
|
|
30
|
+
withManifests<T>(manifests: any[], fn: () => T): T;
|
|
26
31
|
resolveChildren(resource: any, resourceName?: string): { kind: string; name: string };
|
|
27
32
|
validateSchema(value: any, schema: any): void;
|
|
28
33
|
createSchemaValidator(schema: any): DataValidator;
|
|
29
34
|
registerSchema(name: string, schema: object): void;
|
|
30
35
|
lookupSchema(name: string): object | undefined;
|
|
31
|
-
registerController(
|
|
32
|
-
moduleName: string,
|
|
33
|
-
kindName: string,
|
|
34
|
-
controllerInstance: any,
|
|
35
|
-
): Promise<void>;
|
|
36
|
+
registerController(moduleName: string, kindName: string, controllerInstance: any): Promise<void>;
|
|
36
37
|
registerDefinition(definition: any): void;
|
|
38
|
+
registerModuleImport(alias: string, targetModule: string, kinds: string[]): void;
|
|
37
39
|
registerCapability(name: string, schema?: Record<string, any>): void;
|
|
38
40
|
isCapabilityRegistered(name: string): boolean;
|
|
39
41
|
getCapabilitySchema(name: string): Record<string, any> | null | undefined;
|
|
40
42
|
teardownResource(kind: string, name: string): Promise<void>;
|
|
43
|
+
moduleContext: ModuleContext;
|
|
44
|
+
stdin: NodeJS.ReadableStream;
|
|
45
|
+
stdout: NodeJS.WritableStream;
|
|
46
|
+
stderr: NodeJS.WritableStream;
|
|
41
47
|
}
|
package/src/resource-manifest.ts
CHANGED
package/src/runtime-error.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
export type RuntimeErrorCode =
|
|
2
|
-
|
|
|
3
|
-
|
|
|
4
|
-
|
|
|
5
|
-
|
|
|
6
|
-
|
|
|
7
|
-
|
|
|
8
|
-
|
|
|
9
|
-
|
|
|
2
|
+
| "ERR_RESOURCE_NOT_FOUND"
|
|
3
|
+
| "ERR_RESOURCE_NOT_RUNNABLE"
|
|
4
|
+
| "ERR_CONTROLLER_NOT_FOUND"
|
|
5
|
+
| "ERR_CONTROLLER_INVALID"
|
|
6
|
+
| "ERR_RESOURCE_INITIALIZATION_FAILED"
|
|
7
|
+
| "ERR_RESOURCE_NOT_INVOKABLE"
|
|
8
|
+
| "ERR_RESOURCE_SCHEMA_VALIDATION_FAILED"
|
|
9
|
+
| "ERR_DUPLICATE_RESOURCE"
|
|
10
|
+
| "ERR_EXECUTION_FAILED"
|
|
11
|
+
| "ERR_INVALID_VALUE"
|
|
12
|
+
| "ERR_VISIBILITY_DENIED";
|