@ontemper/sdk 0.11.0 → 0.12.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 (72) hide show
  1. package/README.md +134 -12
  2. package/dist/Contract/Manifest.d.ts +3 -2
  3. package/dist/Contract/Manifest.d.ts.map +1 -1
  4. package/dist/Contract/Manifest.js +2 -0
  5. package/dist/Contract/Manifest.js.map +1 -1
  6. package/dist/Contract/RuntimeApi.d.ts +8 -33
  7. package/dist/Contract/RuntimeApi.d.ts.map +1 -1
  8. package/dist/Contract/RuntimeApi.js +8 -32
  9. package/dist/Contract/RuntimeApi.js.map +1 -1
  10. package/dist/Contract/StaticGraph.d.ts +96 -0
  11. package/dist/Contract/StaticGraph.d.ts.map +1 -0
  12. package/dist/Contract/StaticGraph.js +92 -0
  13. package/dist/Contract/StaticGraph.js.map +1 -0
  14. package/dist/Contract/index.d.ts +1 -0
  15. package/dist/Contract/index.d.ts.map +1 -1
  16. package/dist/Contract/index.js +1 -0
  17. package/dist/Contract/index.js.map +1 -1
  18. package/dist/Manifest.d.ts +1 -1
  19. package/dist/Manifest.d.ts.map +1 -1
  20. package/dist/Manifest.js +17 -75
  21. package/dist/Manifest.js.map +1 -1
  22. package/dist/ResourcesToken.js +2 -2
  23. package/dist/ResourcesToken.js.map +1 -1
  24. package/dist/RuntimeResources.d.ts +3 -9
  25. package/dist/RuntimeResources.d.ts.map +1 -1
  26. package/dist/RuntimeResources.js +13 -53
  27. package/dist/RuntimeResources.js.map +1 -1
  28. package/dist/StaticGraph.d.ts +87 -0
  29. package/dist/StaticGraph.d.ts.map +1 -0
  30. package/dist/StaticGraph.js +237 -0
  31. package/dist/StaticGraph.js.map +1 -0
  32. package/dist/StaticGraphAnalyzer.d.ts +7 -0
  33. package/dist/StaticGraphAnalyzer.d.ts.map +1 -0
  34. package/dist/StaticGraphAnalyzer.js +162 -0
  35. package/dist/StaticGraphAnalyzer.js.map +1 -0
  36. package/dist/StaticGraphCalls.d.ts +15 -0
  37. package/dist/StaticGraphCalls.d.ts.map +1 -0
  38. package/dist/StaticGraphCalls.js +1028 -0
  39. package/dist/StaticGraphCalls.js.map +1 -0
  40. package/dist/StaticGraphDeclarations.d.ts +43 -0
  41. package/dist/StaticGraphDeclarations.d.ts.map +1 -0
  42. package/dist/StaticGraphDeclarations.js +443 -0
  43. package/dist/StaticGraphDeclarations.js.map +1 -0
  44. package/dist/StaticGraphProcess.d.ts +2 -0
  45. package/dist/StaticGraphProcess.d.ts.map +1 -0
  46. package/dist/StaticGraphProcess.js +55 -0
  47. package/dist/StaticGraphProcess.js.map +1 -0
  48. package/dist/StaticGraphProject.d.ts +65 -0
  49. package/dist/StaticGraphProject.d.ts.map +1 -0
  50. package/dist/StaticGraphProject.js +303 -0
  51. package/dist/StaticGraphProject.js.map +1 -0
  52. package/dist/StaticGraphProtocol.d.ts +82 -0
  53. package/dist/StaticGraphProtocol.d.ts.map +1 -0
  54. package/dist/StaticGraphProtocol.js +36 -0
  55. package/dist/StaticGraphProtocol.js.map +1 -0
  56. package/dist/StaticGraphRuntime.d.ts +25 -0
  57. package/dist/StaticGraphRuntime.d.ts.map +1 -0
  58. package/dist/StaticGraphRuntime.js +60 -0
  59. package/dist/StaticGraphRuntime.js.map +1 -0
  60. package/dist/StaticGraphValues.d.ts +243 -0
  61. package/dist/StaticGraphValues.d.ts.map +1 -0
  62. package/dist/StaticGraphValues.js +845 -0
  63. package/dist/StaticGraphValues.js.map +1 -0
  64. package/dist/StepCatalogRules.d.ts +33 -0
  65. package/dist/StepCatalogRules.d.ts.map +1 -0
  66. package/dist/StepCatalogRules.js +64 -0
  67. package/dist/StepCatalogRules.js.map +1 -0
  68. package/dist/cli.d.ts +1 -1
  69. package/dist/cli.d.ts.map +1 -1
  70. package/dist/cli.js +67 -9
  71. package/dist/cli.js.map +1 -1
  72. package/package.json +13 -4
@@ -0,0 +1,845 @@
1
+ import ts from 'typescript';
2
+ import { LimitReached, SDK_PACKAGE, STEP_CAPABLE_PACKAGE, } from './StaticGraphProject.js';
3
+ export const ROOT_ENV = { parent: undefined, bindings: new Map() };
4
+ export const UNKNOWN = { t: 'unknown' };
5
+ export const LIB_VALUE = { t: 'libValue' };
6
+ // One of `options`; options that all say nothing, or all name a package value, are that one value.
7
+ const choiceOf = (options) => {
8
+ const [first] = options;
9
+ if (first === undefined)
10
+ return UNKNOWN;
11
+ if (options.length === 1)
12
+ return first;
13
+ if (options.every((option) => option.t === 'unknown'))
14
+ return UNKNOWN;
15
+ return options.every((option) => option.t === 'libValue') ? LIB_VALUE : { t: 'choice', options };
16
+ };
17
+ export const tick = (ctx) => {
18
+ ctx.work += 1;
19
+ if (ctx.work > ctx.limits.maxWork)
20
+ throw new LimitReached('the code is too large to analyze within the work budget');
21
+ };
22
+ export const propertyName = (name) => name !== undefined &&
23
+ (ts.isIdentifier(name) ||
24
+ ts.isStringLiteral(name) ||
25
+ ts.isNoSubstitutionTemplateLiteral(name) ||
26
+ ts.isNumericLiteral(name))
27
+ ? name.text
28
+ : undefined;
29
+ /** The name the source gives a function, a class, or the value of a call, such as the `const` that holds it. */
30
+ export const declaredName = (node) => {
31
+ if ((ts.isClassLike(node) || ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)) &&
32
+ node.name !== undefined) {
33
+ return node.name.text;
34
+ }
35
+ if (ts.isMethodDeclaration(node))
36
+ return propertyName(node.name);
37
+ const parent = node.parent;
38
+ if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name))
39
+ return parent.name.text;
40
+ if (ts.isPropertyAssignment(parent))
41
+ return propertyName(parent.name);
42
+ // `const f = Effect.fn('name')(function* () {})`: the function is an argument of the call the variable holds.
43
+ return ts.isCallExpression(parent) && parent.expression !== node ? declaredName(parent) : undefined;
44
+ };
45
+ /**
46
+ * Walks inside `node`. Past the call depth budget the graph is withheld, never cut (FLOW-10): every reader of a
47
+ * named function enters it here, so none answers at the budget with a value that only looks unknown.
48
+ */
49
+ export const within = (ctx, node, walk) => {
50
+ const counts = declaredName(node) !== undefined;
51
+ if (counts && ctx.depth >= ctx.limits.maxDepth) {
52
+ throw new LimitReached(`the calls nest deeper than ${ctx.limits.maxDepth} functions`);
53
+ }
54
+ ctx.stack.push(node);
55
+ ctx.dependent.push(false);
56
+ if (counts)
57
+ ctx.depth += 1;
58
+ try {
59
+ return walk();
60
+ }
61
+ finally {
62
+ ctx.stack.pop();
63
+ ctx.lastDependent = ctx.dependent.pop() ?? false;
64
+ if (counts)
65
+ ctx.depth -= 1;
66
+ }
67
+ };
68
+ /**
69
+ * Marks the walks from `owner` inward as dependent on their caller: `owner` and the walks inside it for a
70
+ * parameter of `owner`, only the walks inside it for a recursion into `owner`. An owner that already
71
+ * returned, such as the maker of a closure, marks every walk.
72
+ */
73
+ export const markDependent = (ctx, owner, includeOwner) => {
74
+ const index = ctx.stack.lastIndexOf(owner);
75
+ const from = index === -1 ? 0 : includeOwner ? index : index + 1;
76
+ ctx.dependent.fill(true, from);
77
+ };
78
+ export const unwrap = (expression) => {
79
+ let current = expression;
80
+ while (ts.isParenthesizedExpression(current) ||
81
+ ts.isAsExpression(current) ||
82
+ ts.isSatisfiesExpression(current) ||
83
+ ts.isNonNullExpression(current) ||
84
+ ts.isTypeAssertionExpression(current)) {
85
+ current = current.expression;
86
+ }
87
+ return current;
88
+ };
89
+ export const isGenerator = (node) => !ts.isArrowFunction(node) && node.asteriskToken !== undefined;
90
+ const bindNames = (table, name, path, declare) => {
91
+ if (ts.isIdentifier(name)) {
92
+ table.set(name.text, declare(path));
93
+ return;
94
+ }
95
+ for (const element of name.elements) {
96
+ if (ts.isOmittedExpression(element))
97
+ continue;
98
+ const key = ts.isObjectBindingPattern(name) && element.dotDotDotToken === undefined
99
+ ? propertyName(element.propertyName ?? element.name)
100
+ : undefined;
101
+ bindNames(table, element.name, path === undefined || key === undefined ? undefined : [...path, key], declare);
102
+ }
103
+ };
104
+ const declareImport = (table, node) => {
105
+ const clause = node.importClause;
106
+ if (clause === undefined || clause.isTypeOnly)
107
+ return;
108
+ if (clause.name !== undefined)
109
+ table.set(clause.name.text, { kind: 'import', node, name: 'default' });
110
+ const named = clause.namedBindings;
111
+ if (named === undefined)
112
+ return;
113
+ if (ts.isNamespaceImport(named)) {
114
+ table.set(named.name.text, { kind: 'import', node, name: '*' });
115
+ return;
116
+ }
117
+ for (const element of named.elements) {
118
+ if (!element.isTypeOnly) {
119
+ table.set(element.name.text, { kind: 'import', node, name: (element.propertyName ?? element.name).text });
120
+ }
121
+ }
122
+ };
123
+ const declareStatements = (table, statements) => {
124
+ for (const statement of statements) {
125
+ if (ts.isVariableStatement(statement)) {
126
+ const constant = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0;
127
+ for (const node of statement.declarationList.declarations) {
128
+ bindNames(table, node.name, [], (path) => ({ kind: 'variable', node, path, constant }));
129
+ }
130
+ }
131
+ else if (ts.isFunctionDeclaration(statement) && statement.name !== undefined) {
132
+ table.set(statement.name.text, { kind: 'function', node: statement });
133
+ }
134
+ else if (ts.isClassDeclaration(statement) && statement.name !== undefined) {
135
+ table.set(statement.name.text, { kind: 'class', node: statement });
136
+ }
137
+ else if (ts.isImportDeclaration(statement)) {
138
+ declareImport(table, statement);
139
+ }
140
+ else if (ts.isEnumDeclaration(statement)) {
141
+ table.set(statement.name.text, { kind: 'opaque' });
142
+ }
143
+ }
144
+ };
145
+ // The names a node declares for the code inside it, or `undefined` when the node is no scope.
146
+ const scopeTable = (ctx, node) => {
147
+ const known = ctx.scopes.get(node);
148
+ if (known !== undefined)
149
+ return known;
150
+ const table = new Map();
151
+ if (ts.isSourceFile(node) || ts.isBlock(node) || ts.isModuleBlock(node)) {
152
+ declareStatements(table, node.statements);
153
+ }
154
+ else if (ts.isCaseBlock(node)) {
155
+ for (const clause of node.clauses)
156
+ declareStatements(table, clause.statements);
157
+ }
158
+ else if (ts.isFunctionLike(node)) {
159
+ if (ts.isFunctionExpression(node) && node.name !== undefined)
160
+ table.set(node.name.text, { kind: 'function', node });
161
+ for (const parameter of node.parameters) {
162
+ bindNames(table, parameter.name, [], (path) => ({ kind: 'parameter', node: parameter, path }));
163
+ }
164
+ }
165
+ else if (ts.isForStatement(node) || ts.isForOfStatement(node) || ts.isForInStatement(node)) {
166
+ const initializer = node.initializer;
167
+ if (initializer !== undefined && ts.isVariableDeclarationList(initializer)) {
168
+ for (const declaration of initializer.declarations) {
169
+ bindNames(table, declaration.name, undefined, () => ({ kind: 'opaque' }));
170
+ }
171
+ }
172
+ }
173
+ else if (ts.isCatchClause(node)) {
174
+ if (node.variableDeclaration !== undefined) {
175
+ bindNames(table, node.variableDeclaration.name, undefined, () => ({ kind: 'opaque' }));
176
+ }
177
+ }
178
+ else {
179
+ return undefined;
180
+ }
181
+ ctx.scopes.set(node, table);
182
+ return table;
183
+ };
184
+ export const lookup = (ctx, identifier) => {
185
+ let scope = identifier.parent;
186
+ while (scope !== undefined) {
187
+ const found = scopeTable(ctx, scope)?.get(identifier.text);
188
+ if (found !== undefined)
189
+ return found;
190
+ scope = scope.parent;
191
+ }
192
+ return undefined;
193
+ };
194
+ export const functionValue = (node, env) => ({
195
+ t: 'function',
196
+ node,
197
+ env,
198
+ step: undefined,
199
+ lazy: false,
200
+ pipes: [],
201
+ pipesEnv: env,
202
+ });
203
+ export const bindingOf = (env, parameter) => {
204
+ let current = env;
205
+ while (current !== undefined) {
206
+ const found = current.bindings.get(parameter);
207
+ if (found !== undefined)
208
+ return found;
209
+ current = current.parent;
210
+ }
211
+ return undefined;
212
+ };
213
+ /** The Env of one call of `fn`: each parameter holds its argument, unevaluated until the body reads it. */
214
+ export const bindArguments = (fn, bindings) => {
215
+ const bound = new Map();
216
+ for (const [index, parameter] of fn.node.parameters.entries()) {
217
+ const binding = bindings[index];
218
+ if (binding !== undefined && parameter.dotDotDotToken === undefined)
219
+ bound.set(parameter, binding);
220
+ }
221
+ return { parent: fn.env, bindings: bound };
222
+ };
223
+ export const argumentBindings = (expressions, env) => expressions.map((expression) => ({ expression, env }));
224
+ // Return statements of a function body itself, not of a function inside it.
225
+ const returnsOf = (body) => {
226
+ const found = [];
227
+ const visit = (node) => {
228
+ if (ts.isFunctionLike(node) || ts.isClassLike(node))
229
+ return;
230
+ if (ts.isReturnStatement(node))
231
+ found.push(node);
232
+ else
233
+ ts.forEachChild(node, visit);
234
+ };
235
+ ts.forEachChild(body, visit);
236
+ return found;
237
+ };
238
+ /** The one expression a function returns: its expression body, or the expression of its only `return`. */
239
+ export const resultExpression = (node) => {
240
+ if (node.body === undefined)
241
+ return undefined;
242
+ if (!ts.isBlock(node.body))
243
+ return node.body;
244
+ const returns = returnsOf(node.body);
245
+ return returns.length === 1 ? returns[0]?.expression : undefined;
246
+ };
247
+ /** The namespace and name of a package export: `import { Effect } from 'effect'` and `import * as Effect from 'effect/Effect'` name one. */
248
+ export const apiOf = (value) => {
249
+ const { module, path } = value;
250
+ const effect = module === 'effect' || module.startsWith('effect/') || module.startsWith('@effect/');
251
+ const sdk = module === SDK_PACKAGE || module.startsWith(`${SDK_PACKAGE}/`);
252
+ if (path.length >= 2)
253
+ return { effect, sdk, ns: path[0] ?? '', name: path[1] ?? '' };
254
+ const deep = module.startsWith('effect/') ? module.slice(module.lastIndexOf('/') + 1) : '';
255
+ return { effect, sdk, ns: deep, name: path[0] ?? '' };
256
+ };
257
+ export const isEffectApi = (value, ns, names) => {
258
+ if (value.t !== 'lib')
259
+ return false;
260
+ const api = apiOf(value);
261
+ return api.effect && api.ns === ns && names.includes(api.name);
262
+ };
263
+ const packageValue = (name, path) => STEP_CAPABLE_PACKAGE.test(name) ? { t: 'external', module: name } : { t: 'lib', module: name, path };
264
+ const targetExport = (ctx, target, name, seen) => {
265
+ if (target === undefined)
266
+ return UNKNOWN;
267
+ if (target.kind === 'unread')
268
+ return { t: 'external', module: target.specifier };
269
+ if (target.kind === 'package')
270
+ return packageValue(target.name, name === '*' ? [] : [name]);
271
+ return name === '*' ? { t: 'module', file: target.file } : exported(ctx, target.file, name, seen);
272
+ };
273
+ const targetOf = (ctx, file, specifier) => specifier !== undefined && ts.isStringLiteral(specifier)
274
+ ? ctx.project.targets.get(file)?.get(specifier.text)
275
+ : undefined;
276
+ /** The value a module exports under `name`, through re-exports; `seen` stops a re-export cycle. */
277
+ export function exported(ctx, file, name, seen) {
278
+ const key = `${file.fileName}\u0000${name}`;
279
+ if (seen.has(key))
280
+ return UNKNOWN;
281
+ seen.add(key);
282
+ for (const statement of file.statements) {
283
+ if (ts.isExportAssignment(statement)) {
284
+ if (name === 'default' && statement.isExportEquals !== true)
285
+ return evaluate(ctx, statement.expression, ROOT_ENV);
286
+ continue;
287
+ }
288
+ if (!ts.isExportDeclaration(statement) || statement.isTypeOnly)
289
+ continue;
290
+ const target = targetOf(ctx, file, statement.moduleSpecifier);
291
+ const clause = statement.exportClause;
292
+ if (clause === undefined) {
293
+ if (name === 'default' || target?.kind !== 'file')
294
+ continue;
295
+ const found = exported(ctx, target.file, name, seen);
296
+ if (found.t !== 'unknown')
297
+ return found;
298
+ }
299
+ else if (ts.isNamespaceExport(clause)) {
300
+ if (clause.name.text === name)
301
+ return targetExport(ctx, target, '*', seen);
302
+ }
303
+ else {
304
+ const element = clause.elements.find((candidate) => !candidate.isTypeOnly && candidate.name.text === name);
305
+ if (element === undefined)
306
+ continue;
307
+ const source = (element.propertyName ?? element.name).text;
308
+ if (statement.moduleSpecifier !== undefined)
309
+ return targetExport(ctx, target, source, seen);
310
+ const local = scopeTable(ctx, file)?.get(source);
311
+ return local === undefined ? UNKNOWN : valueOfDeclaration(ctx, local, ROOT_ENV, seen);
312
+ }
313
+ }
314
+ if (name === 'default') {
315
+ const statement = file.statements.find((candidate) => (ts.isFunctionDeclaration(candidate) || ts.isClassDeclaration(candidate)) &&
316
+ (ts.getCombinedModifierFlags(candidate) & ts.ModifierFlags.Default) !== 0);
317
+ if (statement !== undefined && ts.isFunctionDeclaration(statement))
318
+ return functionValue(statement, ROOT_ENV);
319
+ if (statement !== undefined && ts.isClassDeclaration(statement))
320
+ return { t: 'class', node: statement, env: ROOT_ENV };
321
+ return UNKNOWN;
322
+ }
323
+ const local = scopeTable(ctx, file)?.get(name);
324
+ return local === undefined ? UNKNOWN : valueOfDeclaration(ctx, local, ROOT_ENV, seen);
325
+ }
326
+ // `seen` holds the exports already followed to this declaration, so two modules that re-export each other's import end.
327
+ function valueOfDeclaration(ctx, declaration, env, seen = new Set()) {
328
+ switch (declaration.kind) {
329
+ case 'variable': {
330
+ const { node, path } = declaration;
331
+ // A `let` can change after its initializer, so only a `const` names one value.
332
+ if (!declaration.constant || node.initializer === undefined || path === undefined)
333
+ return UNKNOWN;
334
+ if (ctx.evaluating.has(node))
335
+ return UNKNOWN;
336
+ ctx.evaluating.add(node);
337
+ try {
338
+ let value = evaluate(ctx, node.initializer, env);
339
+ for (const name of path)
340
+ value = member(ctx, value, name);
341
+ return value;
342
+ }
343
+ finally {
344
+ ctx.evaluating.delete(node);
345
+ }
346
+ }
347
+ case 'function':
348
+ return functionValue(declaration.node, env);
349
+ case 'class':
350
+ return { t: 'class', node: declaration.node, env };
351
+ case 'parameter': {
352
+ markDependent(ctx, declaration.node.parent, true);
353
+ const binding = bindingOf(env, declaration.node);
354
+ if (binding === undefined || declaration.path === undefined)
355
+ return UNKNOWN;
356
+ let value = 'value' in binding ? binding.value : evaluate(ctx, binding.expression, binding.env);
357
+ for (const name of declaration.path)
358
+ value = member(ctx, value, name);
359
+ return value;
360
+ }
361
+ case 'import': {
362
+ const file = declaration.node.getSourceFile();
363
+ return targetExport(ctx, targetOf(ctx, file, declaration.node.moduleSpecifier), declaration.name, seen);
364
+ }
365
+ case 'opaque':
366
+ return UNKNOWN;
367
+ }
368
+ }
369
+ export const words = (text) => new Set(text.split(/\s+/));
370
+ // The globals of JavaScript and of the runtimes that a call can read as a package: the call takes and returns data.
371
+ // The list leaves out `globalThis`, `eval`, `Function`, `Reflect`, and `Proxy`, which reach code of the workflow.
372
+ const PLATFORM_GLOBALS = words(`AbortController AbortSignal AggregateError Array ArrayBuffer Atomics BigInt BigInt64Array BigUint64Array Blob
373
+ Boolean BroadcastChannel Buffer Bun CompressionStream DOMException DataView Date DecompressionStream Error
374
+ EvalError Event EventTarget File Float32Array Float64Array FormData Headers Infinity Int16Array Int32Array
375
+ Int8Array Intl Iterator JSON Map Math NaN Number Object Promise RangeError ReadableStream ReferenceError RegExp
376
+ Request Response Set SharedArrayBuffer String Symbol SyntaxError TextDecoder TextEncoder TransformStream TypeError
377
+ URIError URL URLSearchParams Uint16Array Uint32Array Uint8Array Uint8ClampedArray WeakMap WeakRef WeakSet
378
+ WebSocket WritableStream atob btoa clearImmediate clearInterval clearTimeout console crypto decodeURI
379
+ decodeURIComponent encodeURI encodeURIComponent fetch isFinite isNaN navigator parseFloat parseInt performance
380
+ process queueMicrotask setImmediate setInterval setTimeout structuredClone`);
381
+ export function evaluate(ctx, expression, env) {
382
+ tick(ctx);
383
+ const node = unwrap(expression);
384
+ if (ts.isIdentifier(node)) {
385
+ if (node.text === 'undefined')
386
+ return UNKNOWN;
387
+ const declaration = lookup(ctx, node);
388
+ if (declaration !== undefined)
389
+ return valueOfDeclaration(ctx, declaration, env);
390
+ // A name that no scope declares is a package value only when the platform defines it, such as JSON or Promise.
391
+ // Any other one is declared in a form that the scopes do not record, such as `import x = require()`, a
392
+ // namespace, or a `var` in a block, so it can hold workflow code.
393
+ return PLATFORM_GLOBALS.has(node.text) ? { t: 'lib', module: 'global', path: [node.text] } : UNKNOWN;
394
+ }
395
+ if (node.kind === ts.SyntaxKind.ThisKeyword)
396
+ return staticThis(node, env);
397
+ if (ts.isPropertyAccessExpression(node))
398
+ return member(ctx, evaluate(ctx, node.expression, env), node.name.text);
399
+ if (ts.isElementAccessExpression(node))
400
+ return computedMember(ctx, node, env);
401
+ if (ts.isCallExpression(node))
402
+ return evaluateCall(ctx, node, env);
403
+ if (ts.isYieldExpression(node)) {
404
+ return node.asteriskToken !== undefined && node.expression !== undefined
405
+ ? resultOf(ctx, evaluate(ctx, node.expression, env))
406
+ : UNKNOWN;
407
+ }
408
+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node))
409
+ return functionValue(node, env);
410
+ if (ts.isObjectLiteralExpression(node))
411
+ return { t: 'object', node, env };
412
+ if (ts.isArrayLiteralExpression(node))
413
+ return { t: 'array', node, env };
414
+ if (ts.isClassExpression(node))
415
+ return { t: 'class', node, env };
416
+ if (ts.isNewExpression(node)) {
417
+ const constructed = evaluate(ctx, node.expression, env);
418
+ if (constructed.t === 'class')
419
+ return { t: 'instance', class: constructed };
420
+ return constructed.t === 'lib' || constructed.t === 'libValue' ? LIB_VALUE : UNKNOWN;
421
+ }
422
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
423
+ return { t: 'text', value: node.text };
424
+ if (ts.isNumericLiteral(node))
425
+ return { t: 'number', value: Number(node.text) };
426
+ if (node.kind === ts.SyntaxKind.TrueKeyword)
427
+ return { t: 'literal', value: true };
428
+ if (node.kind === ts.SyntaxKind.FalseKeyword)
429
+ return { t: 'literal', value: false };
430
+ if (node.kind === ts.SyntaxKind.NullKeyword)
431
+ return { t: 'literal', value: null };
432
+ if (ts.isConditionalExpression(node) || ts.isBinaryExpression(node))
433
+ return { t: 'expression', node, env, lib: false };
434
+ return UNKNOWN;
435
+ }
436
+ // `this` in a static member of a class is the class, as in `static layer = Layer.effect(this, make)`.
437
+ const staticThis = (node, env) => {
438
+ let current = node.parent;
439
+ while (!ts.isSourceFile(current)) {
440
+ const owner = current.parent;
441
+ if (ts.isClassElement(current)) {
442
+ const isStatic = (ts.getCombinedModifierFlags(current) & ts.ModifierFlags.Static) !== 0;
443
+ const names = ts.isClassStaticBlockDeclaration(current) || isStatic;
444
+ return names && ts.isClassLike(owner) ? { t: 'class', node: owner, env } : UNKNOWN;
445
+ }
446
+ // An arrow function keeps the `this` of the code around it; any other function has its own.
447
+ if (ts.isFunctionLike(current) && !ts.isArrowFunction(current))
448
+ return UNKNOWN;
449
+ current = owner;
450
+ }
451
+ return UNKNOWN;
452
+ };
453
+ // `record[key]`: the member a literal key names. A computed key can name any member, so the value is known only
454
+ // when every member is a package function, such as a record of `Effect.log*` by level.
455
+ const computedMember = (ctx, node, env) => {
456
+ const base = evaluate(ctx, node.expression, env);
457
+ const key = evaluate(ctx, node.argumentExpression, env);
458
+ if (key.t === 'text')
459
+ return member(ctx, base, key.value);
460
+ if (base.t === 'lib' || base.t === 'libValue')
461
+ return LIB_VALUE;
462
+ if (base.t !== 'object')
463
+ return UNKNOWN;
464
+ const packaged = base.node.properties.every((property) => {
465
+ if (!ts.isPropertyAssignment(property))
466
+ return false;
467
+ const value = evaluate(ctx, property.initializer, base.env);
468
+ return value.t === 'lib' || value.t === 'libValue';
469
+ });
470
+ return packaged ? LIB_VALUE : UNKNOWN;
471
+ };
472
+ export const FUNCTION_BUILDERS = ['fn', 'fnUntraced', 'fnUntracedEager'];
473
+ // A function that `Effect.fn` or `step.fn` builds from the body in the first argument, or the builder that still waits for it.
474
+ const builtFunction = (ctx, call, env, step) => {
475
+ const first = call.arguments[0];
476
+ const body = first === undefined ? UNKNOWN : evaluate(ctx, first, env);
477
+ if (body.t !== 'function')
478
+ return { t: 'builder', step };
479
+ return { ...body, step, lazy: true, pipes: call.arguments.slice(1), pipesEnv: env };
480
+ };
481
+ // What a call of a plain function returns, when the source says it: a closure, an object, or another value
482
+ // with a structure. An Effect stays a call, which the walker inlines where the effect runs.
483
+ const returnValue = (ctx, fn, call, env) => {
484
+ const deferred = { t: 'expression', node: call, env, lib: false };
485
+ const result = fn.lazy || isGenerator(fn.node) ? undefined : resultExpression(fn.node);
486
+ if (result === undefined || ctx.stack.includes(fn.node))
487
+ return deferred;
488
+ const value = within(ctx, fn.node, () => evaluate(ctx, result, bindArguments(fn, argumentBindings(call.arguments, env))));
489
+ const plain = value.t === 'unknown' || value.t === 'text' || value.t === 'number' || value.t === 'literal';
490
+ return value.t === 'expression' || plain ? deferred : value;
491
+ };
492
+ function evaluateCall(ctx, call, env) {
493
+ const callee = evaluate(ctx, call.expression, env);
494
+ const target = unwrap(call.expression);
495
+ const [given] = call.arguments;
496
+ if (callee.t === 'unknown' &&
497
+ ts.isPropertyAccessExpression(target) &&
498
+ target.name.text === 'of' &&
499
+ given !== undefined) {
500
+ // `Service.of(record)` only types the record a service implementation returns.
501
+ const owner = evaluate(ctx, target.expression, env);
502
+ if (owner.t === 'class' && isServiceClass(ctx, owner))
503
+ return evaluate(ctx, given, env);
504
+ }
505
+ switch (callee.t) {
506
+ case 'lib': {
507
+ const api = apiOf(callee);
508
+ if (api.sdk && api.ns === 'Step' && api.name === 'make')
509
+ return { t: 'step', id: ctx.stepIds.get(call) ?? null };
510
+ if (api.effect && api.ns === 'Effect' && FUNCTION_BUILDERS.includes(api.name)) {
511
+ return builtFunction(ctx, call, env, undefined);
512
+ }
513
+ return { t: 'expression', node: call, env, lib: true };
514
+ }
515
+ case 'builder':
516
+ return builtFunction(ctx, call, env, callee.step);
517
+ case 'stepFn':
518
+ return builtFunction(ctx, call, env, callee.id);
519
+ case 'function':
520
+ return returnValue(ctx, callee, call, env);
521
+ case 'libValue':
522
+ return { t: 'expression', node: call, env, lib: true };
523
+ case 'expression':
524
+ return { t: 'expression', node: call, env, lib: callee.lib };
525
+ case 'external':
526
+ case 'ambiguous':
527
+ return callee;
528
+ default:
529
+ return { t: 'expression', node: call, env, lib: false };
530
+ }
531
+ }
532
+ // The options object of `class X extends Context.Service<X, …>()('id', { make })`, which holds members the class body does not.
533
+ const heritageOptions = (cls) => {
534
+ const base = cls.node.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
535
+ const call = base === undefined ? undefined : unwrap(base.expression);
536
+ if (call === undefined || !ts.isCallExpression(call))
537
+ return undefined;
538
+ const options = call.arguments.map(unwrap).find(ts.isObjectLiteralExpression);
539
+ return options === undefined ? undefined : { t: 'object', node: options, env: cls.env };
540
+ };
541
+ const classMember = (ctx, cls, name, statics) => {
542
+ for (const element of cls.node.members) {
543
+ if (propertyName(element.name) !== name)
544
+ continue;
545
+ const isStatic = (ts.getCombinedModifierFlags(element) & ts.ModifierFlags.Static) !== 0;
546
+ if (ts.isMethodDeclaration(element) && isStatic === statics)
547
+ return functionValue(element, cls.env);
548
+ if (ts.isPropertyDeclaration(element) && isStatic === statics) {
549
+ return element.initializer === undefined ? UNKNOWN : evaluate(ctx, element.initializer, cls.env);
550
+ }
551
+ }
552
+ const options = statics ? heritageOptions(cls) : undefined;
553
+ return options === undefined ? UNKNOWN : objectMember(ctx, options, name);
554
+ };
555
+ function objectMember(ctx, object, name) {
556
+ // A later property replaces an earlier one with the same name.
557
+ for (const property of object.node.properties.toReversed()) {
558
+ if (ts.isSpreadAssignment(property)) {
559
+ const found = member(ctx, evaluate(ctx, property.expression, object.env), name);
560
+ if (found.t !== 'unknown')
561
+ return found;
562
+ }
563
+ else if (propertyName(property.name) === name) {
564
+ if (ts.isPropertyAssignment(property))
565
+ return evaluate(ctx, property.initializer, object.env);
566
+ if (ts.isShorthandPropertyAssignment(property))
567
+ return evaluate(ctx, property.name, object.env);
568
+ return ts.isMethodDeclaration(property) ? functionValue(property, object.env) : UNKNOWN;
569
+ }
570
+ }
571
+ return UNKNOWN;
572
+ }
573
+ export const lastFunction = (ctx, given, env) => {
574
+ for (const argument of given.toReversed()) {
575
+ const value = evaluate(ctx, argument, env);
576
+ if (value.t === 'function')
577
+ return value;
578
+ }
579
+ return undefined;
580
+ };
581
+ // The name of an export of the `Effect` module, such as `flatMap`; `undefined` for any other value.
582
+ export const effectName = (value) => {
583
+ const api = value.t === 'lib' ? apiOf(value) : undefined;
584
+ return api !== undefined && api.effect && api.ns === 'Effect' ? api.name : undefined;
585
+ };
586
+ // The `pipe` function of Effect, from `effect` or `effect/Function`, also as `Function.pipe`; it takes the base first.
587
+ export const isPipeFunction = (value) => {
588
+ if (value.t !== 'lib')
589
+ return false;
590
+ const api = apiOf(value);
591
+ return api.effect && api.name === 'pipe' && (api.ns === '' || api.ns === 'Function');
592
+ };
593
+ // Combinators whose callback decides what the effect succeeds with.
594
+ const MAPPERS = ['flatMap', 'andThen', 'map'];
595
+ // Combinators that succeed with what the effect before them succeeds with.
596
+ const KEEPS = words(`orDie mapError withSpan withLogSpan annotateLogs annotateSpans provide provideContext provideService
597
+ provideServiceEffect updateService delay timeout interruptible uninterruptible scoped filterOrFail tap tapError
598
+ tapErrorTag tapCause tapDefect onError onExit onInterrupt ensuring retry acquireRelease`);
599
+ // `Effect.cached(effect)` succeeds with `effect` itself, which runs where the code yields that result.
600
+ export const DEFERRED = ['cached', 'cachedWithTTL'];
601
+ // Combinators that succeed with a record of Effect around what the effect before them succeeds with.
602
+ const WRAPPERS = ['result', 'exit', 'option'];
603
+ // Effects that fail, or that succeed with nothing or with a value that Effect makes itself, such as a fiber.
604
+ const OWN_VALUE = words(`fail failCause failSync failCauseSync die log logTrace logDebug logInfo logWarning logError
605
+ logFatal sleep asVoid ignore ignoreCause context makeSpan makeSpanScoped forkChild forkDetach forkIn forkScoped`);
606
+ // What an effect succeeds with after the combinator `name`, given what it succeeds with before. A combinator in no
607
+ // list can pass on a value that the workflow made, so its result is unknown, never a package value (FLOW-10).
608
+ const resultThrough = (name, before) => {
609
+ if (KEEPS.has(name))
610
+ return before();
611
+ if (WRAPPERS.includes(name))
612
+ return { t: 'wrapped', inner: before() };
613
+ return OWN_VALUE.has(name) ? LIB_VALUE : UNKNOWN;
614
+ };
615
+ // What `base.pipe(...steps)` succeeds with: what its last step makes of the effect before that step.
616
+ const pipedResult = (ctx, base, steps, env, hops) => {
617
+ const last = steps.at(-1);
618
+ if (last === undefined)
619
+ return effectResult(ctx, base, env, hops + 1);
620
+ const step = unwrap(last);
621
+ const applied = evaluate(ctx, ts.isCallExpression(step) ? step.expression : step, env);
622
+ const before = () => pipedResult(ctx, base, steps.slice(0, -1), env, hops);
623
+ if (applied.t === 'stepRun')
624
+ return before();
625
+ const name = effectName(applied);
626
+ if (name === undefined)
627
+ return UNKNOWN;
628
+ if (MAPPERS.includes(name))
629
+ return ts.isCallExpression(step) ? effectResult(ctx, step, env, hops + 1) : UNKNOWN;
630
+ return resultThrough(name, before);
631
+ };
632
+ // What a workflow function or the callback of a mapper gives: a generator returns the value, a plain function its effect.
633
+ const returnedResult = (ctx, fn, env, returnsValue, hops) => {
634
+ const result = resultExpression(fn.node);
635
+ if (result === undefined || ctx.stack.includes(fn.node))
636
+ return UNKNOWN;
637
+ return within(ctx, fn.node, () => returnsValue || fn.lazy || isGenerator(fn.node)
638
+ ? evaluate(ctx, result, env)
639
+ : effectResult(ctx, result, env, hops + 1));
640
+ };
641
+ // What an effect succeeds with, through calls of workflow functions, mappers, and the combinators of `resultThrough`.
642
+ function effectResult(ctx, expression, env, hops) {
643
+ const node = unwrap(expression);
644
+ if (hops > 8)
645
+ return UNKNOWN;
646
+ if (!ts.isCallExpression(node)) {
647
+ const held = evaluate(ctx, node, env);
648
+ if (held.t !== 'expression')
649
+ return resultOf(ctx, held);
650
+ return held.node === node ? UNKNOWN : effectResult(ctx, held.node, held.env, hops + 1);
651
+ }
652
+ const callee = unwrap(node.expression);
653
+ const value = evaluate(ctx, callee, env);
654
+ const [first, ...rest] = node.arguments;
655
+ if (isPipeFunction(value) && first !== undefined)
656
+ return pipedResult(ctx, first, rest, env, hops);
657
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'pipe') {
658
+ return pipedResult(ctx, callee.expression, node.arguments, env, hops);
659
+ }
660
+ if (value.t === 'function') {
661
+ return returnedResult(ctx, value, bindArguments(value, argumentBindings(node.arguments, env)), false, hops);
662
+ }
663
+ if (value.t === 'stepRun')
664
+ return first === undefined ? UNKNOWN : effectResult(ctx, first, env, hops + 1);
665
+ if (value.t === 'external' || value.t === 'ambiguous')
666
+ return value;
667
+ const name = effectName(value);
668
+ // A call of any other package makes its own value.
669
+ const packaged = value.t === 'lib' || value.t === 'libValue' || (value.t === 'expression' && value.lib);
670
+ if (name === undefined)
671
+ return packaged ? LIB_VALUE : UNKNOWN;
672
+ if (MAPPERS.includes(name)) {
673
+ const mapper = node.arguments.at(-1);
674
+ const mapped = mapper === undefined ? UNKNOWN : evaluate(ctx, mapper, env);
675
+ return mapped.t === 'function' ? returnedResult(ctx, mapped, mapped.env, name === 'map', hops) : UNKNOWN;
676
+ }
677
+ if (name === 'gen' || name === 'sync') {
678
+ const made = lastFunction(ctx, node.arguments, env);
679
+ if (made === undefined || made.node.body === undefined)
680
+ return UNKNOWN;
681
+ if (!ts.isBlock(made.node.body))
682
+ return evaluate(ctx, made.node.body, made.env);
683
+ // A body with several returns succeeds with one of them, such as a fallback record without configuration.
684
+ const returned = returnsOf(made.node.body).flatMap((statement) => statement.expression === undefined ? [] : [statement.expression]);
685
+ return choiceOf(returned.map((returnedExpression) => evaluate(ctx, returnedExpression, made.env)));
686
+ }
687
+ if (first !== undefined && (name === 'succeed' || DEFERRED.includes(name)))
688
+ return evaluate(ctx, first, env);
689
+ return resultThrough(name, () => (first === undefined ? UNKNOWN : effectResult(ctx, first, env, hops + 1)));
690
+ }
691
+ const implementationOf = (ctx, provider) => {
692
+ if (provider.kind === 'effect')
693
+ return effectResult(ctx, provider.expression, provider.env, 0);
694
+ const value = evaluate(ctx, provider.expression, provider.env);
695
+ if (provider.kind === 'value')
696
+ return value;
697
+ const result = value.t === 'function' ? resultExpression(value.node) : undefined;
698
+ return value.t !== 'function' || result === undefined ? UNKNOWN : evaluate(ctx, result, value.env);
699
+ };
700
+ // A member of a service, read from its one production implementation (FLOW-10). No implementation, several,
701
+ // or a wired layer that the analyzer cannot read leaves the member ambiguous.
702
+ const serviceMember = (ctx, service, name) => {
703
+ const providers = ctx.providers.get(service.tag) ?? [];
704
+ const provider = providers.length === 1 && !ctx.unknownLayer ? providers[0] : undefined;
705
+ const implementation = provider === undefined ? UNKNOWN : implementationOf(ctx, provider);
706
+ const records = implementation.t === 'choice' ? implementation.options : [implementation];
707
+ if (!records.every((record) => record.t === 'object' || record.t === 'instance')) {
708
+ return { t: 'ambiguous', label: `${service.name}.${name}` };
709
+ }
710
+ return choiceOf(records.map((record) => member(ctx, record, name)));
711
+ };
712
+ export function member(ctx, base, name) {
713
+ switch (base.t) {
714
+ case 'module':
715
+ return exported(ctx, base.file, name, new Set());
716
+ case 'lib':
717
+ return { t: 'lib', module: base.module, path: [...base.path, name] };
718
+ case 'libValue':
719
+ case 'external':
720
+ case 'ambiguous':
721
+ return base;
722
+ case 'step':
723
+ return name === 'run' ? { t: 'stepRun', id: base.id } : name === 'fn' ? { t: 'stepFn', id: base.id } : UNKNOWN;
724
+ case 'class':
725
+ return classMember(ctx, base, name, true);
726
+ case 'instance':
727
+ return classMember(ctx, base.class, name, false);
728
+ case 'object':
729
+ return objectMember(ctx, base, name);
730
+ case 'service':
731
+ return serviceMember(ctx, base, name);
732
+ case 'expression':
733
+ return base.lib ? LIB_VALUE : UNKNOWN;
734
+ case 'choice':
735
+ return choiceOf(base.options.map((option) => member(ctx, option, name)));
736
+ // The failure side holds an error or a cause, which is data: a yield of it fails and runs no step.
737
+ case 'wrapped':
738
+ return name === 'success' || name === 'value' ? base.inner : LIB_VALUE;
739
+ default:
740
+ return UNKNOWN;
741
+ }
742
+ }
743
+ /** The package export at the root of `X<…>()(…)` call chains, such as `Context.Service` or `Variable`. */
744
+ export const rootCallee = (ctx, expression, env) => {
745
+ let current = unwrap(expression);
746
+ while (ts.isCallExpression(current))
747
+ current = unwrap(current.expression);
748
+ return evaluate(ctx, current, env);
749
+ };
750
+ const SERVICE_KEYS = ['Service', 'Reference'];
751
+ export const extendsExpression = (node) => node.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;
752
+ const isServiceClass = (ctx, cls) => {
753
+ if (ctx.providers.has(cls.node))
754
+ return true;
755
+ const base = extendsExpression(cls.node);
756
+ if (base === undefined)
757
+ return false;
758
+ return isEffectApi(rootCallee(ctx, base, cls.env), 'Context', SERVICE_KEYS);
759
+ };
760
+ /** What `yield*` of a value gives: the service of a service key, or a package value. */
761
+ export function resultOf(ctx, value) {
762
+ switch (value.t) {
763
+ case 'class':
764
+ return isServiceClass(ctx, value)
765
+ ? { t: 'service', tag: value.node, name: value.node.name?.text ?? 'service' }
766
+ : UNKNOWN;
767
+ case 'expression': {
768
+ const isKey = value.lib &&
769
+ (ctx.providers.has(value.node) || isEffectApi(rootCallee(ctx, value.node, value.env), 'Context', SERVICE_KEYS));
770
+ return isKey
771
+ ? { t: 'service', tag: value.node, name: declaredName(value.node) ?? 'service' }
772
+ : effectResult(ctx, value.node, value.env, 0);
773
+ }
774
+ case 'lib':
775
+ case 'libValue':
776
+ return LIB_VALUE;
777
+ case 'external':
778
+ case 'ambiguous':
779
+ return value;
780
+ case 'choice':
781
+ return choiceOf(value.options.map((option) => resultOf(ctx, option)));
782
+ default:
783
+ return UNKNOWN;
784
+ }
785
+ }
786
+ /** A value the source writes as literals, through `const` names; `undefined` when a part is computed. */
787
+ export const literalOf = (ctx, expression, env, depth) => {
788
+ const node = unwrap(expression);
789
+ if (depth > 16)
790
+ return undefined;
791
+ if (ts.isPrefixUnaryExpression(node) &&
792
+ node.operator === ts.SyntaxKind.MinusToken &&
793
+ ts.isNumericLiteral(node.operand)) {
794
+ return { value: -Number(node.operand.text) };
795
+ }
796
+ if (ts.isArrayLiteralExpression(node)) {
797
+ const values = [];
798
+ for (const element of node.elements) {
799
+ const literal = ts.isSpreadElement(element) ? undefined : literalOf(ctx, element, env, depth + 1);
800
+ if (literal === undefined)
801
+ return undefined;
802
+ values.push(literal.value);
803
+ }
804
+ return { value: values };
805
+ }
806
+ if (ts.isObjectLiteralExpression(node)) {
807
+ const entries = [];
808
+ for (const property of node.properties) {
809
+ const name = propertyName(property.name);
810
+ const value = ts.isPropertyAssignment(property)
811
+ ? property.initializer
812
+ : ts.isShorthandPropertyAssignment(property)
813
+ ? property.name
814
+ : undefined;
815
+ const literal = name === undefined || value === undefined ? undefined : literalOf(ctx, value, env, depth + 1);
816
+ if (name === undefined || literal === undefined)
817
+ return undefined;
818
+ entries.push([name, literal.value]);
819
+ }
820
+ return { value: Object.fromEntries(entries) };
821
+ }
822
+ const value = evaluate(ctx, node, env);
823
+ if (value.t === 'text' || value.t === 'number' || value.t === 'literal')
824
+ return { value: value.value };
825
+ const held = (value.t === 'object' || value.t === 'array') && value.node !== node;
826
+ return held ? literalOf(ctx, value.node, value.env, depth + 1) : undefined;
827
+ };
828
+ /** The text an expression is written as, through `const` names; only text names a step, an endpoint, or a path. */
829
+ export const textOf = (ctx, expression, env) => {
830
+ const value = expression === undefined ? UNKNOWN : evaluate(ctx, expression, env);
831
+ return value.t === 'text' ? value.value : undefined;
832
+ };
833
+ /** The expression an object literal gives `name`; the last property with the name wins. */
834
+ export const propertyExpression = (node, name) => {
835
+ for (const property of node.properties.toReversed()) {
836
+ if (propertyName(property.name) !== name)
837
+ continue;
838
+ if (ts.isPropertyAssignment(property))
839
+ return property.initializer;
840
+ if (ts.isShorthandPropertyAssignment(property))
841
+ return property.name;
842
+ }
843
+ return undefined;
844
+ };
845
+ //# sourceMappingURL=StaticGraphValues.js.map