@telorun/sdk 0.2.7 → 0.3.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 (41) hide show
  1. package/README.md +54 -0
  2. package/dist/compiled-value.d.ts +2 -0
  3. package/dist/compiled-value.d.ts.map +1 -1
  4. package/dist/evaluation-context.d.ts +16 -102
  5. package/dist/evaluation-context.d.ts.map +1 -1
  6. package/dist/evaluation-context.js +0 -390
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +1 -0
  10. package/dist/invoke-error.d.ts +14 -0
  11. package/dist/invoke-error.d.ts.map +1 -0
  12. package/dist/invoke-error.js +34 -0
  13. package/dist/module-context.d.ts +12 -36
  14. package/dist/module-context.d.ts.map +1 -1
  15. package/dist/module-context.js +1 -177
  16. package/dist/ref.d.ts +1 -1
  17. package/dist/ref.d.ts.map +1 -1
  18. package/dist/ref.js +1 -1
  19. package/dist/resource-context.d.ts +17 -0
  20. package/dist/resource-context.d.ts.map +1 -1
  21. package/dist/types.d.ts +16 -0
  22. package/dist/types.d.ts.map +1 -1
  23. package/package.json +19 -1
  24. package/src/compiled-value.ts +2 -0
  25. package/src/evaluation-context.ts +45 -461
  26. package/src/index.ts +1 -0
  27. package/src/invoke-error.ts +39 -0
  28. package/src/module-context.ts +22 -203
  29. package/src/ref.ts +1 -1
  30. package/src/resource-context.ts +23 -0
  31. package/src/types.ts +18 -0
  32. package/dist/capability-definition.d.ts +0 -8
  33. package/dist/capability-definition.d.ts.map +0 -1
  34. package/dist/capability-definition.js +0 -21
  35. package/dist/cel-environment.d.ts +0 -3
  36. package/dist/cel-environment.d.ts.map +0 -1
  37. package/dist/cel-environment.js +0 -13
  38. package/dist/execution-context.d.ts +0 -13
  39. package/dist/execution-context.d.ts.map +0 -1
  40. package/dist/execution-context.js +0 -13
  41. package/src/execution-context.ts +0 -21
@@ -1,215 +1,34 @@
1
- import { Invocable } from "./capabilities/invokable.js";
2
- import { EmitEvent, EvaluationContext, InstanceFactory } from "./evaluation-context.js";
3
-
4
- /** Wraps process.env so that missing keys return null instead of throwing in CEL.
5
- * cel-js uses Object.hasOwn(obj, key) before accessing obj[key], so we must
6
- * intercept getOwnPropertyDescriptor to report every string key as "own". */
7
- function lenientEnv(env: Record<string, string | undefined>): Record<string, string | null> {
8
- return new Proxy(env as Record<string, string | null>, {
9
- get(target, key) {
10
- if (typeof key !== "string") return (target as any)[key];
11
- return key in target ? (target[key] ?? null) : null;
12
- },
13
- has() {
14
- return true;
15
- },
16
- getOwnPropertyDescriptor(target, key) {
17
- if (typeof key !== "string") return Object.getOwnPropertyDescriptor(target, key);
18
- const value = key in target ? (target[key] ?? null) : null;
19
- return { configurable: true, enumerable: true, writable: true, value };
20
- },
21
- });
22
- }
23
-
24
- function collectSecretValues(secrets: Record<string, unknown>): Set<string> {
25
- const values = new Set<string>();
26
- for (const value of Object.values(secrets)) {
27
- if (typeof value === "string" && value.length > 0) {
28
- values.add(value);
29
- }
30
- }
31
- return values;
32
- }
1
+ import type { Invocable } from "./capabilities/invokable.js";
2
+ import type { EvaluationContext } from "./evaluation-context.js";
33
3
 
34
4
  /**
35
- * Persistent, module-scoped context. Three reserved CEL namespaces:
36
- * variables, secrets, resources.
5
+ * Public contract for a persistent, module-scoped context.
37
6
  *
7
+ * Three reserved CEL namespaces: variables, secrets, resources.
38
8
  * Unlike the base EvaluationContext, ModuleContext is stateful and mutable:
39
- * variables/secrets/resources accumulate during multi-pass initialization and
40
- * the context record is rebuilt on each mutation. Import aliases are tracked
41
- * here for alias-prefixed kind resolution (e.g. MyImport.Http.Route).
9
+ * variables/secrets/resources accumulate during multi-pass initialization.
10
+ * Import aliases are tracked here for alias-prefixed kind resolution.
42
11
  *
43
- * Imported modules are surfaced under resources.<alias> alongside local
44
- * resources — no separate imports namespace needed.
12
+ * The class implementation lives in `@telorun/kernel`.
45
13
  */
46
- export class ModuleContext extends EvaluationContext {
47
- private _variables: Record<string, unknown>;
48
- private _secrets: Record<string, unknown>;
49
- private _resources: Record<string, unknown>;
50
-
51
- /** Maps import alias → real module name for kind resolution. */
52
- readonly importAliases = new Map<string, string>();
53
-
54
- /** Maps import alias → allowed kind names. Absent entry = unrestricted (e.g. Kernel). */
55
- private readonly importedKinds = new Map<string, Set<string>>();
56
-
57
- constructor(
58
- source: string,
59
- variables: Record<string, unknown> = {},
60
- secrets: Record<string, unknown> = {},
61
- resources: Record<string, unknown> = {},
62
- private targets: string[] = [],
63
- createInstance: InstanceFactory = async () => null,
64
- emit: EmitEvent,
65
- private readonly _hostEnv?: Record<string, string | undefined>,
66
- ) {
67
- super(source, {}, createInstance, new Set(), emit);
68
- this._variables = variables;
69
- this._secrets = secrets;
70
- this._resources = resources;
71
- this._rebuildContext();
72
- }
73
-
74
- get variables(): Record<string, unknown> {
75
- return this._variables;
76
- }
77
-
78
- get secrets(): Record<string, unknown> {
79
- return this._secrets;
80
- }
81
-
82
- get resources(): Record<string, unknown> {
83
- return this._resources;
84
- }
85
-
86
- setVariables(vars: Record<string, unknown>): void {
87
- this._variables = vars;
88
- this._rebuildContext();
89
- }
14
+ export interface ModuleContext extends EvaluationContext {
15
+ readonly variables: Record<string, unknown>;
16
+ readonly secrets: Record<string, unknown>;
17
+ readonly resources: Record<string, unknown>;
90
18
 
91
- setTargets(vars: string[]): void {
92
- this.targets = vars;
93
- }
19
+ /** Maps import alias -> real module name for kind resolution. */
20
+ readonly importAliases: Map<string, string>;
94
21
 
95
- setSecrets(secrets: Record<string, unknown>): void {
96
- this._secrets = secrets;
97
- this._rebuildContext();
98
- }
99
-
100
- setResource(name: string, props: Record<string, unknown>): void {
101
- this._resources = { ...this._resources, [name]: props };
102
- this._rebuildContext();
103
- }
104
-
105
- protected override onResourceSnapshotted(name: string, snap: Record<string, unknown>): void {
106
- this.setResource(name, snap);
107
- }
108
-
109
- /**
110
- * Register an imported module under the given alias, with the list of kind names
111
- * it exports. An empty kinds array means no restriction (used for built-ins like Kernel).
112
- */
113
- registerImport(alias: string, targetModule: string, kinds: string[]): void {
114
- this.importAliases.set(alias, targetModule);
115
- if (kinds.length > 0) {
116
- this.importedKinds.set(alias, new Set(kinds));
117
- }
118
- }
119
-
120
- getInstance(name: string): unknown {
121
- const entry = this.resourceInstances.get(name);
122
- if (!entry) {
123
- throw new Error(
124
- `Resource '${name}' not found in module context. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
125
- );
126
- }
127
- return entry?.instance;
128
- }
22
+ setVariables(vars: Record<string, unknown>): void;
23
+ setTargets(vars: string[]): void;
24
+ setSecrets(secrets: Record<string, unknown>): void;
25
+ setResource(name: string, props: Record<string, unknown>): void;
129
26
 
27
+ registerImport(alias: string, targetModule: string, kinds: string[]): void;
28
+ getInstance(name: string): unknown;
130
29
  getInvocable<TInput = Record<string, any>, TOutput = any>(
131
30
  name: string,
132
- ): Invocable<TInput, TOutput> {
133
- const instance = this.getInstance(name);
134
-
135
- if (
136
- instance &&
137
- typeof instance === "object" &&
138
- "invoke" in instance &&
139
- typeof instance.invoke !== "function"
140
- ) {
141
- throw new Error(`Resource '${name}' does not have an invoke() method.`);
142
- }
143
- return instance as Invocable<TInput, TOutput>;
144
- }
145
-
146
- /**
147
- * Resolve a fully-qualified kind like "Http.Server" to its real kind "http-server.Server".
148
- * Splits on the first dot, looks up the prefix in importAliases, validates against
149
- * importedKinds (if set), and reconstructs the resolved kind.
150
- * Throws with a clear message if the alias is unknown or the kind is not exported.
151
- */
152
- resolveKind(kind: string): string {
153
- const dot = kind.indexOf(".");
154
- if (dot === -1) {
155
- throw new Error(`Kind '${kind}' must be fully qualified (e.g. 'Module.KindName')`);
156
- }
157
- const prefix = kind.slice(0, dot);
158
- const suffix = kind.slice(dot + 1);
159
- const realModule = this.importAliases.get(prefix);
160
- if (!realModule) {
161
- const known = [...this.importAliases.keys()].join(", ") || "(none)";
162
- throw new Error(
163
- `Kind '${kind}': no module imported with alias '${prefix}'. Known aliases: ${known}`,
164
- );
165
- }
166
- const allowed = this.importedKinds.get(prefix);
167
- if (allowed !== undefined && !allowed.has(suffix)) {
168
- throw new Error(
169
- `Kind '${suffix}' is not exported by module '${realModule}' (imported as '${prefix}'). ` +
170
- `Exported kinds: ${[...allowed].join(", ")}`,
171
- );
172
- }
173
- return `${realModule}.${suffix}`;
174
- }
175
-
176
- private _rebuildContext(): void {
177
- this._context = {
178
- variables: this._variables,
179
- secrets: this._secrets,
180
- resources: this._resources,
181
- ...(this._hostEnv ? { env: lenientEnv(this._hostEnv) } : {}),
182
- };
183
- this._secretValues = collectSecretValues(this._secrets);
184
- }
185
-
186
- override async invoke<TInputs>(kind: string, name: string, inputs: TInputs): Promise<any> {
187
- const result = await super.invoke(kind, name, inputs);
188
- const entry = this.resourceInstances.get(name);
189
- if (entry && typeof (entry.instance as any).snapshot === "function") {
190
- const snap = await Promise.resolve((entry.instance as any).snapshot());
191
- this.setResource(name, snap as Record<string, unknown>);
192
- }
193
- return result;
194
- }
195
-
196
- async run(name: string) {
197
- const resource = this.resourceInstances.get(name);
198
- if (!resource) {
199
- throw new Error(
200
- `Target resource ${name} not found in module context. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
201
- );
202
- }
203
- if (typeof resource.instance.run === "function") {
204
- await resource.instance.run();
205
- } else {
206
- throw new Error(`Target resource ${name} does not have a run() method.`);
207
- }
208
- }
209
-
210
- async runTargets() {
211
- for (const target of this.targets) {
212
- await this.run(target);
213
- }
214
- }
31
+ ): Invocable<TInput, TOutput>;
32
+ resolveKind(kind: string): string;
33
+ runTargets(): Promise<void>;
215
34
  }
package/src/ref.ts CHANGED
@@ -48,7 +48,7 @@ export type Injected<T> = {
48
48
  /** Returns a schema node that emits `x-telo-ref` for buildReferenceFieldMap and carries
49
49
  * KindRef<T> as its TypeScript type. For TypeBox schemas use Type.Unsafe<KindRef<T>>(Ref(...)).
50
50
  *
51
- * @param ref Canonical ref string: "namespace/module-name#TypeName" or "kernel#TypeName" */
51
+ * @param ref Canonical ref string: "namespace/module-name#TypeName" or "telo#TypeName" */
52
52
  export const Ref = <T = ResourceInstance>(ref: string): KindRef<T> =>
53
53
  ({ "x-telo-ref": ref } as unknown as KindRef<T>);
54
54
 
@@ -1,8 +1,16 @@
1
1
  import { ControllerContext } from "./controller-context.js";
2
2
  import { EvaluationContext } from "./evaluation-context.js";
3
3
  import { ModuleContext } from "./module-context.js";
4
+ import { ResourceInstance } from "./resource-instance.js";
5
+ import { ResourceManifest } from "./resource-manifest.js";
4
6
  import { RuntimeResource } from "./runtime-resource.js";
5
7
 
8
+ export interface LoadOptions {
9
+ /** When true, `${{ }}` templates are replaced with CompiledValue wrappers
10
+ * so they can be evaluated at runtime. Leave unset for static analysis. */
11
+ compile?: boolean;
12
+ }
13
+
6
14
  export interface DataValidator {
7
15
  validate(data: any): void;
8
16
  isValid(data: any): boolean;
@@ -31,6 +39,12 @@ export interface ResourceContext extends ControllerContext {
31
39
  acquireHold(reason?: string): () => void;
32
40
  emitEvent(event: string, payload?: any): Promise<void>;
33
41
  invoke<TInputs>(kind: string, name: string, inputs: TInputs, options?: any): Promise<any>;
42
+ invokeResolved<TInputs>(
43
+ kind: string,
44
+ name: string,
45
+ instance: ResourceInstance,
46
+ inputs: TInputs,
47
+ ): Promise<any>;
34
48
  run(kind: string, name: string): Promise<void>;
35
49
  getResources(kind: string): RuntimeResource[];
36
50
  getResourcesByName(kind: string, name: string): RuntimeResource | null;
@@ -51,7 +65,16 @@ export interface ResourceContext extends ControllerContext {
51
65
  registerDefinition(definition: any): void;
52
66
  registerModuleImport(alias: string, targetModule: string, kinds: string[]): void;
53
67
  teardownResource(kind: string, name: string): Promise<void>;
68
+ /** Load a single module (its own file + `include`d partials). Use this when
69
+ * you need just the declaring file's manifests. */
70
+ loadModule(url: string, options?: LoadOptions): Promise<ResourceManifest[]>;
71
+ /** Load a module and follow its Telo.Import chain, returning the union of
72
+ * the module's manifests plus all transitively-imported Telo.Definition
73
+ * manifests. Use this when you need the full kind surface area visible from
74
+ * the module. */
75
+ loadManifests(url: string): Promise<ResourceManifest[]>;
54
76
  readonly moduleContext: ModuleContext;
77
+ readonly env: Record<string, string | undefined>;
55
78
  readonly stdin: NodeJS.ReadableStream;
56
79
  readonly stdout: NodeJS.WritableStream;
57
80
  readonly stderr: NodeJS.WritableStream;
package/src/types.ts CHANGED
@@ -14,6 +14,22 @@ export interface ExecContext {
14
14
  [key: string]: any;
15
15
  }
16
16
 
17
+ export interface ThrowCodeSpec {
18
+ description: string;
19
+ data?: Record<string, any>;
20
+ }
21
+
22
+ /**
23
+ * Declared throw contract for a Telo.Invocable or Telo.Runnable definition.
24
+ * Codes-only (explicit contract) in Phase 1; `inherit` and `passthrough` land
25
+ * in Phase 2 together with the analyzer dataflow pass.
26
+ */
27
+ export interface ThrowsSpec {
28
+ codes?: Record<string, ThrowCodeSpec>;
29
+ inherit?: boolean;
30
+ passthrough?: boolean;
31
+ }
32
+
17
33
  export interface ResourceDefinition {
18
34
  kind: string;
19
35
  metadata: {
@@ -27,6 +43,8 @@ export interface ResourceDefinition {
27
43
  runtime: string;
28
44
  entry: string;
29
45
  }>;
46
+ /** Declared throw contract — only valid on Telo.Invocable / Telo.Runnable. */
47
+ throws?: ThrowsSpec;
30
48
  }
31
49
 
32
50
  /**
@@ -1,8 +0,0 @@
1
- import type { CapabilityDefinition } from "./types.js";
2
- /**
3
- * Factory that wires the declarative `expand` config on a CapabilityDefinition
4
- * into the `onManifest` and `onInvoke` lifecycle hooks. The kernel only ever
5
- * calls these hooks — it has no knowledge of the `expand` config.
6
- */
7
- export declare function createCapability(def: CapabilityDefinition): CapabilityDefinition;
8
- //# sourceMappingURL=capability-definition.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"capability-definition.d.ts","sourceRoot":"","sources":["../src/capability-definition.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAGvD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,oBAAoB,GAAG,oBAAoB,CAwBhF"}
@@ -1,21 +0,0 @@
1
- /**
2
- * Factory that wires the declarative `expand` config on a CapabilityDefinition
3
- * into the `onManifest` and `onInvoke` lifecycle hooks. The kernel only ever
4
- * calls these hooks — it has no knowledge of the `expand` config.
5
- */
6
- export function createCapability(def) {
7
- const compile = def.expand?.compile ?? [];
8
- const runtime = def.expand?.runtime ?? [];
9
- return {
10
- ...def,
11
- onManifest: compile.length
12
- ? (manifest, ctx) => ctx.expandPaths(manifest, compile, runtime)
13
- : def.onManifest,
14
- onInvoke: runtime.length
15
- ? async (instance, inputs, ctx) => {
16
- const expanded = ctx.moduleContext.expandPaths(inputs, runtime);
17
- return instance.invoke(expanded);
18
- }
19
- : def.onInvoke,
20
- };
21
- }
@@ -1,3 +0,0 @@
1
- import { Environment } from "@marcbachmann/cel-js";
2
- export declare const celEnvironment: Environment;
3
- //# sourceMappingURL=cel-environment.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"cel-environment.d.ts","sourceRoot":"","sources":["../src/cel-environment.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAEnD,eAAO,MAAM,cAAc,aAWvB,CAAC"}
@@ -1,13 +0,0 @@
1
- import { Environment } from "@marcbachmann/cel-js";
2
- export const celEnvironment = new Environment({ unlistedVariablesAreDyn: true })
3
- .registerFunction("join(list, string): string", (list, sep) => list.map(String).join(sep))
4
- .registerFunction("keys(map): list", (map) => {
5
- if (map instanceof Map)
6
- return [...map.keys()];
7
- return Object.keys(map);
8
- })
9
- .registerFunction("values(map): list", (map) => {
10
- if (map instanceof Map)
11
- return [...map.values()];
12
- return Object.values(map);
13
- });
@@ -1,13 +0,0 @@
1
- import { EvaluationContext } from "./evaluation-context.js";
2
- import { ModuleContext } from "./module-context.js";
3
- /**
4
- * The ephemeral, per-trigger context layer. Merges a ModuleContext with
5
- * arbitrary execution-time properties (e.g. { request, inputs } for HTTP;
6
- * any shape is valid — determined by the trigger type).
7
- *
8
- * Execution props overlay the module namespaces on key conflict.
9
- */
10
- export declare class ExecutionContext extends EvaluationContext {
11
- constructor(moduleCtx: ModuleContext, execProps: Record<string, unknown>);
12
- }
13
- //# sourceMappingURL=execution-context.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"execution-context.d.ts","sourceRoot":"","sources":["../src/execution-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD;;;;;;GAMG;AACH,qBAAa,gBAAiB,SAAQ,iBAAiB;gBACzC,SAAS,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;CASzE"}
@@ -1,13 +0,0 @@
1
- import { EvaluationContext } from "./evaluation-context.js";
2
- /**
3
- * The ephemeral, per-trigger context layer. Merges a ModuleContext with
4
- * arbitrary execution-time properties (e.g. { request, inputs } for HTTP;
5
- * any shape is valid — determined by the trigger type).
6
- *
7
- * Execution props overlay the module namespaces on key conflict.
8
- */
9
- export class ExecutionContext extends EvaluationContext {
10
- constructor(moduleCtx, execProps) {
11
- super(moduleCtx.source, Object.assign(Object.create(null), moduleCtx.context, execProps), moduleCtx.createInstance, moduleCtx.secretValues, moduleCtx.emit);
12
- }
13
- }
@@ -1,21 +0,0 @@
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
- }