@pikku/inspector 0.12.75 → 0.12.81

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 (219) hide show
  1. package/CHANGELOG.md +330 -0
  2. package/dist/add/add-analytics.d.ts +9 -0
  3. package/dist/add/add-analytics.js +178 -0
  4. package/dist/add/add-auth.js +0 -54
  5. package/dist/add/add-feature-flag.d.ts +2 -0
  6. package/dist/add/add-feature-flag.js +162 -0
  7. package/dist/add/add-wire-addon.js +1 -0
  8. package/dist/add/add-wire-remote-addon.js +1 -0
  9. package/dist/index.d.ts +3 -1
  10. package/dist/index.js +3 -1
  11. package/dist/inspector.js +4 -0
  12. package/dist/surface/collect-surface.d.ts +58 -0
  13. package/dist/surface/collect-surface.js +613 -0
  14. package/dist/types.d.ts +20 -11
  15. package/dist/utils/filter-inspector-state.js +14 -0
  16. package/dist/utils/post-process.js +15 -0
  17. package/dist/utils/read-module-specifiers.d.ts +8 -0
  18. package/dist/utils/read-module-specifiers.js +23 -0
  19. package/dist/utils/read-tsconfig-out-dir.d.ts +5 -0
  20. package/dist/utils/read-tsconfig-out-dir.js +12 -0
  21. package/dist/utils/resolve-deploy-target.d.ts +7 -0
  22. package/dist/utils/resolve-deploy-target.js +15 -7
  23. package/dist/utils/serialize-inspector-state.d.ts +5 -0
  24. package/dist/utils/serialize-inspector-state.js +8 -0
  25. package/dist/visit.js +4 -0
  26. package/package.json +16 -6
  27. package/run-tests.sh +21 -6
  28. package/src/add/add-addon-bans.ts +0 -85
  29. package/src/add/add-agent-scorer.test.ts +0 -197
  30. package/src/add/add-agent-scorer.ts +0 -83
  31. package/src/add/add-agent.test.ts +0 -87
  32. package/src/add/add-agent.ts +0 -638
  33. package/src/add/add-approval-description.ts +0 -76
  34. package/src/add/add-auth.test.ts +0 -791
  35. package/src/add/add-auth.ts +0 -424
  36. package/src/add/add-channel.ts +0 -778
  37. package/src/add/add-cli-renderers.test.ts +0 -74
  38. package/src/add/add-cli.ts +0 -1006
  39. package/src/add/add-credential.ts +0 -186
  40. package/src/add/add-feature.test.ts +0 -306
  41. package/src/add/add-feature.ts +0 -253
  42. package/src/add/add-file-extends-core-type.ts +0 -66
  43. package/src/add/add-file-with-config.ts +0 -45
  44. package/src/add/add-file-with-factory.test.ts +0 -134
  45. package/src/add/add-file-with-factory.ts +0 -288
  46. package/src/add/add-functions.test.ts +0 -743
  47. package/src/add/add-functions.ts +0 -1548
  48. package/src/add/add-gateway.ts +0 -143
  49. package/src/add/add-http-route-ref.test.ts +0 -149
  50. package/src/add/add-http-route.ts +0 -530
  51. package/src/add/add-http-routes.ts +0 -471
  52. package/src/add/add-keyed-wiring.ts +0 -180
  53. package/src/add/add-mcp-prompt.ts +0 -157
  54. package/src/add/add-mcp-resource.ts +0 -175
  55. package/src/add/add-middleware.test.ts +0 -196
  56. package/src/add/add-middleware.ts +0 -879
  57. package/src/add/add-permission-auth.test.ts +0 -59
  58. package/src/add/add-permission.ts +0 -311
  59. package/src/add/add-personas.test.ts +0 -406
  60. package/src/add/add-personas.ts +0 -287
  61. package/src/add/add-queue-worker.ts +0 -117
  62. package/src/add/add-rpc-invocations.test.ts +0 -287
  63. package/src/add/add-rpc-invocations.ts +0 -221
  64. package/src/add/add-scenario-step.test.ts +0 -509
  65. package/src/add/add-schedule.ts +0 -120
  66. package/src/add/add-scope.test.ts +0 -419
  67. package/src/add/add-scope.ts +0 -221
  68. package/src/add/add-secret.ts +0 -10
  69. package/src/add/add-subject-scenario-steps.test.ts +0 -161
  70. package/src/add/add-system-role.test.ts +0 -297
  71. package/src/add/add-system-role.ts +0 -162
  72. package/src/add/add-trigger.ts +0 -165
  73. package/src/add/add-variable.ts +0 -10
  74. package/src/add/add-wire-addon.test.ts +0 -185
  75. package/src/add/add-wire-addon.ts +0 -146
  76. package/src/add/add-wire-remote-addon.ts +0 -80
  77. package/src/add/add-workflow-edge-cases.test.ts +0 -201
  78. package/src/add/add-workflow-fanout.test.ts +0 -166
  79. package/src/add/add-workflow-graph-foreach.test.ts +0 -174
  80. package/src/add/add-workflow-graph-input.test.ts +0 -94
  81. package/src/add/add-workflow-graph-notes.test.ts +0 -74
  82. package/src/add/add-workflow-graph.ts +0 -644
  83. package/src/add/add-workflow-on-error.test.ts +0 -118
  84. package/src/add/add-workflow-return-switch.test.ts +0 -121
  85. package/src/add/add-workflow-silent-drops.test.ts +0 -261
  86. package/src/add/add-workflow-sleep-expression.test.ts +0 -96
  87. package/src/add/add-workflow.test.ts +0 -155
  88. package/src/add/add-workflow.ts +0 -482
  89. package/src/add/addon-bans.test.ts +0 -121
  90. package/src/add/addon-contracts.test.ts +0 -221
  91. package/src/add/allow-escape-hatches.test.ts +0 -144
  92. package/src/add/audit-meta.test.ts +0 -75
  93. package/src/add/classified-sink-check.test.ts +0 -347
  94. package/src/add/config-value-metadata.test.ts +0 -263
  95. package/src/add/dynamic-import-check.test.ts +0 -119
  96. package/src/add/expect-eventually-scenario-only.test.ts +0 -108
  97. package/src/add/function-body-span.test.ts +0 -96
  98. package/src/add/inline-wiring-function.test.ts +0 -104
  99. package/src/add/pii-check.test.ts +0 -258
  100. package/src/add/rpc-type-cast.test.ts +0 -123
  101. package/src/add/scenario-instrumentation.test.ts +0 -89
  102. package/src/add/scenario-instrumentation.ts +0 -42
  103. package/src/add/scenario-marker.test.ts +0 -89
  104. package/src/add/scenario-not-extractable.test.ts +0 -159
  105. package/src/add/scenario-services.test.ts +0 -103
  106. package/src/add/scenario-skip.test.ts +0 -83
  107. package/src/add/validate-workflow-graph-addons.test.ts +0 -102
  108. package/src/add/wire-name-literal.test.ts +0 -117
  109. package/src/error-codes-emitted.test.ts +0 -76
  110. package/src/error-codes.ts +0 -145
  111. package/src/index.ts +0 -66
  112. package/src/inspector.ts +0 -575
  113. package/src/schema-generator.ts +0 -1
  114. package/src/source-file-cache.ts +0 -73
  115. package/src/tsconfig-paths.test.ts +0 -90
  116. package/src/types-map.ts +0 -141
  117. package/src/types.ts +0 -775
  118. package/src/utils/annotate-http-route-auth.test.ts +0 -161
  119. package/src/utils/annotate-http-route-auth.ts +0 -53
  120. package/src/utils/check-classified-sinks.ts +0 -215
  121. package/src/utils/check-pii-output.ts +0 -120
  122. package/src/utils/compute-diagnostics.test.ts +0 -106
  123. package/src/utils/compute-required-schemas.ts +0 -48
  124. package/src/utils/contract-hashes.test.ts +0 -553
  125. package/src/utils/contract-hashes.ts +0 -387
  126. package/src/utils/custom-types-generator.test.ts +0 -124
  127. package/src/utils/custom-types-generator.ts +0 -150
  128. package/src/utils/detect-schema-vendor.test.ts +0 -123
  129. package/src/utils/detect-schema-vendor.ts +0 -120
  130. package/src/utils/does-type-extend-core-type.ts +0 -53
  131. package/src/utils/ensure-function-metadata.ts +0 -385
  132. package/src/utils/extract-function-name.ts +0 -612
  133. package/src/utils/extract-function-node.ts +0 -70
  134. package/src/utils/extract-node-value.test.ts +0 -117
  135. package/src/utils/extract-node-value.ts +0 -172
  136. package/src/utils/extract-secret-usage.test.ts +0 -81
  137. package/src/utils/extract-secret-usage.ts +0 -73
  138. package/src/utils/extract-services.ts +0 -70
  139. package/src/utils/extract-surface-usage.test.ts +0 -147
  140. package/src/utils/extract-surface-usage.ts +0 -121
  141. package/src/utils/filter-inspector-state.test.ts +0 -2232
  142. package/src/utils/filter-inspector-state.ts +0 -1298
  143. package/src/utils/filter-utils.test.ts +0 -843
  144. package/src/utils/filter-utils.ts +0 -161
  145. package/src/utils/find-root-dir.ts +0 -68
  146. package/src/utils/find-zod-transform.test.ts +0 -70
  147. package/src/utils/find-zod-transform.ts +0 -103
  148. package/src/utils/get-exported-variable-name.ts +0 -48
  149. package/src/utils/get-files-and-methods.ts +0 -157
  150. package/src/utils/get-property-value.test.ts +0 -141
  151. package/src/utils/get-property-value.ts +0 -331
  152. package/src/utils/hash.ts +0 -26
  153. package/src/utils/literal-properties.ts +0 -97
  154. package/src/utils/load-addon-functions-meta.test.ts +0 -157
  155. package/src/utils/load-addon-functions-meta.ts +0 -508
  156. package/src/utils/load-addon-scopes.test.ts +0 -138
  157. package/src/utils/middleware.test.ts +0 -204
  158. package/src/utils/middleware.ts +0 -303
  159. package/src/utils/nested-project-filter.test.ts +0 -53
  160. package/src/utils/nested-project-filter.ts +0 -28
  161. package/src/utils/permissions-shorthand.test.ts +0 -79
  162. package/src/utils/permissions.test.ts +0 -125
  163. package/src/utils/permissions.ts +0 -129
  164. package/src/utils/post-process.test.ts +0 -1094
  165. package/src/utils/post-process.ts +0 -1604
  166. package/src/utils/resolve-addon-package.ts +0 -106
  167. package/src/utils/resolve-core-type.test.ts +0 -142
  168. package/src/utils/resolve-core-type.ts +0 -35
  169. package/src/utils/resolve-deploy-target.test.ts +0 -135
  170. package/src/utils/resolve-deploy-target.ts +0 -65
  171. package/src/utils/resolve-function-meta.ts +0 -25
  172. package/src/utils/resolve-function-types.ts +0 -42
  173. package/src/utils/resolve-identifier.ts +0 -46
  174. package/src/utils/resolve-ref-contract.ts +0 -71
  175. package/src/utils/resolve-versions.test.ts +0 -499
  176. package/src/utils/resolve-versions.ts +0 -228
  177. package/src/utils/schema-cache.test.ts +0 -124
  178. package/src/utils/schema-generator.test.ts +0 -272
  179. package/src/utils/schema-generator.ts +0 -780
  180. package/src/utils/secret-alias-services.test.ts +0 -146
  181. package/src/utils/secret-alias-services.ts +0 -58
  182. package/src/utils/serialize-inspector-state.ts +0 -742
  183. package/src/utils/serialize-mcp-json.ts +0 -150
  184. package/src/utils/serialize-middleware-groups-meta.ts +0 -36
  185. package/src/utils/serialize-openapi-json.ts +0 -277
  186. package/src/utils/serialize-permissions-groups-meta.ts +0 -7
  187. package/src/utils/single-declaration.ts +0 -57
  188. package/src/utils/type-utils.ts +0 -145
  189. package/src/utils/validate-auth-sessionless.ts +0 -30
  190. package/src/utils/validate-exposed-functions-gated.test.ts +0 -230
  191. package/src/utils/validate-exposed-functions-gated.ts +0 -103
  192. package/src/utils/validate-tags-resolve-to-middleware.test.ts +0 -108
  193. package/src/utils/validate-tags-resolve-to-middleware.ts +0 -48
  194. package/src/utils/workflow/derive-workflow-plan.test.ts +0 -178
  195. package/src/utils/workflow/derive-workflow-plan.ts +0 -117
  196. package/src/utils/workflow/dsl/deserialize-dsl-workflow.ts +0 -1465
  197. package/src/utils/workflow/dsl/deserialize-fanout-body.test.ts +0 -71
  198. package/src/utils/workflow/dsl/deserialize-fanout-fidelity.test.ts +0 -99
  199. package/src/utils/workflow/dsl/deserialize-graph-next.test.ts +0 -161
  200. package/src/utils/workflow/dsl/deserialize-roundtrip-bindings.test.ts +0 -121
  201. package/src/utils/workflow/dsl/deserialize-roundtrip-values.test.ts +0 -116
  202. package/src/utils/workflow/dsl/deserialize-roundtrip.test.ts +0 -145
  203. package/src/utils/workflow/dsl/extract-approval-policy.test.ts +0 -71
  204. package/src/utils/workflow/dsl/extract-dsl-workflow.ts +0 -2254
  205. package/src/utils/workflow/dsl/index.ts +0 -11
  206. package/src/utils/workflow/dsl/patterns.ts +0 -440
  207. package/src/utils/workflow/dsl/validation.ts +0 -203
  208. package/src/utils/workflow/graph/convert-dsl-to-graph-skip.test.ts +0 -35
  209. package/src/utils/workflow/graph/convert-dsl-to-graph.ts +0 -543
  210. package/src/utils/workflow/graph/fanout-node-identity.test.ts +0 -105
  211. package/src/utils/workflow/graph/finalize-workflow-wires.ts +0 -310
  212. package/src/utils/workflow/graph/finalize-workflows.test.ts +0 -50
  213. package/src/utils/workflow/graph/finalize-workflows.ts +0 -130
  214. package/src/utils/workflow/graph/index.ts +0 -28
  215. package/src/utils/workflow/graph/serialize-workflow-graph.ts +0 -240
  216. package/src/utils/workflow/graph/workflow-graph.types.ts +0 -281
  217. package/src/visit.ts +0 -181
  218. package/tsconfig.json +0 -19
  219. package/tsconfig.tsbuildinfo +0 -1
@@ -1,74 +0,0 @@
1
- import { strict as assert } from 'assert'
2
- import { describe, test } from 'node:test'
3
- import { mkdtemp, rm, writeFile } from 'node:fs/promises'
4
- import { tmpdir } from 'node:os'
5
- import { join } from 'node:path'
6
- import { inspect } from '../inspector.js'
7
- import type { InspectorLogger } from '../types.js'
8
-
9
- function makeLogger(): InspectorLogger {
10
- return {
11
- debug: () => {},
12
- info: () => {},
13
- warn: () => {},
14
- error: () => {},
15
- diagnostic: () => {},
16
- critical: () => {},
17
- hasCriticalErrors: () => false,
18
- }
19
- }
20
-
21
- describe('addWorkflowGraph — notes extraction', () => {
22
- test('node-level and graph-level notes are carried into the serialized graph', async () => {
23
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-graph-notes-'))
24
- const stepFile = join(rootDir, 'my.steps.ts')
25
- const graphFile = join(rootDir, 'my.graph.ts')
26
-
27
- await writeFile(
28
- stepFile,
29
- [
30
- "import { pikkuSessionlessFunc } from '@pikku/core'",
31
- 'export const assess = pikkuSessionlessFunc({ func: async () => ({ ok: true }) })',
32
- 'export const notify = pikkuSessionlessFunc({ func: async () => ({ sent: true }) })',
33
- ].join('\n')
34
- )
35
-
36
- await writeFile(
37
- graphFile,
38
- [
39
- "import { pikkuWorkflowGraph } from '@pikku/core/workflow'",
40
- 'export const myGraph = pikkuWorkflowGraph({',
41
- " name: 'my-graph',",
42
- " notes: ['imported sticky note'],",
43
- ' nodes: {',
44
- " assess: 'assess',",
45
- " notify: 'notify',",
46
- ' },',
47
- ' config: {',
48
- " assess: { next: 'notify', notes: 'STUB — generated from node \"Assess\"' },",
49
- ' notify: {},',
50
- ' },',
51
- '})',
52
- ].join('\n')
53
- )
54
-
55
- try {
56
- const state = await inspect(makeLogger(), [stepFile, graphFile], {
57
- rootDir,
58
- })
59
- const graph = state.workflows.graphMeta['my-graph']
60
- assert.ok(graph, 'graph meta should be registered')
61
- assert.deepEqual(graph.notes, ['imported sticky note'])
62
- assert.equal(
63
- (graph.nodes['assess'] as { notes?: string }).notes,
64
- 'STUB — generated from node "Assess"'
65
- )
66
- assert.equal(
67
- (graph.nodes['notify'] as { notes?: string }).notes,
68
- undefined
69
- )
70
- } finally {
71
- await rm(rootDir, { recursive: true, force: true })
72
- }
73
- })
74
- })
@@ -1,644 +0,0 @@
1
- import * as ts from 'typescript'
2
- import type { AddWiring } from '../types.js'
3
- import { ErrorCode } from '../error-codes.js'
4
- import { extractStringLiteral } from '../utils/extract-node-value.js'
5
- import type {
6
- SerializedWorkflowGraph,
7
- DataRef,
8
- } from '../utils/workflow/graph/workflow-graph.types.js'
9
-
10
- function extractAstValue(
11
- expr: ts.Expression,
12
- refParamName: string,
13
- templateParamName: string | undefined,
14
- itemParamName?: string
15
- ): unknown {
16
- // `'GET' as const` / parenthesised values wrap the real initializer — see
17
- // through them or the whole property is silently dropped from the meta.
18
- while (ts.isAsExpression(expr) || ts.isParenthesizedExpression(expr)) {
19
- expr = expr.expression
20
- }
21
- if (ts.isStringLiteral(expr)) {
22
- return expr.text
23
- }
24
- if (ts.isNumericLiteral(expr)) {
25
- return Number(expr.text)
26
- }
27
- if (expr.kind === ts.SyntaxKind.TrueKeyword) {
28
- return true
29
- }
30
- if (expr.kind === ts.SyntaxKind.FalseKeyword) {
31
- return false
32
- }
33
- if (expr.kind === ts.SyntaxKind.NullKeyword) {
34
- return null
35
- }
36
- if (ts.isCallExpression(expr)) {
37
- const callee = expr.expression
38
- if (ts.isIdentifier(callee)) {
39
- if (callee.text === refParamName) {
40
- const args = expr.arguments
41
- const nodeId =
42
- args[0] && ts.isStringLiteral(args[0]) ? args[0].text : 'unknown'
43
- const path =
44
- args[1] && ts.isStringLiteral(args[1]) ? args[1].text : undefined
45
- return { $ref: nodeId, path } as DataRef
46
- }
47
- if (itemParamName && callee.text === itemParamName) {
48
- const pathArg = expr.arguments[0]
49
- const path =
50
- pathArg && ts.isStringLiteral(pathArg) ? pathArg.text : undefined
51
- return { $ref: '$item', path } as DataRef
52
- }
53
- if (templateParamName && callee.text === templateParamName) {
54
- const templateStr =
55
- expr.arguments[0] && ts.isStringLiteral(expr.arguments[0])
56
- ? expr.arguments[0].text
57
- : ''
58
- const refsArg = expr.arguments[1]
59
- const refs: Array<{ $ref: string; path?: string }> = []
60
- if (refsArg && ts.isArrayLiteralExpression(refsArg)) {
61
- for (const el of refsArg.elements) {
62
- const resolved = extractAstValue(
63
- el,
64
- refParamName,
65
- templateParamName,
66
- itemParamName
67
- )
68
- if (
69
- typeof resolved === 'object' &&
70
- resolved !== null &&
71
- '$ref' in resolved
72
- ) {
73
- refs.push(resolved as { $ref: string; path?: string })
74
- }
75
- }
76
- }
77
- const parts: string[] = []
78
- const expressions: Array<{ $ref: string; path?: string }> = []
79
- const regex = /\$(\d+)/g
80
- let lastIndex = 0
81
- let match
82
- while ((match = regex.exec(templateStr)) !== null) {
83
- parts.push(templateStr.slice(lastIndex, match.index))
84
- const refIndex = parseInt(match[1]!, 10)
85
- expressions.push(refs[refIndex] ?? { $ref: 'unknown' })
86
- lastIndex = regex.lastIndex
87
- }
88
- parts.push(templateStr.slice(lastIndex))
89
- return { $template: { parts, expressions } }
90
- }
91
- }
92
- }
93
- if (ts.isArrayLiteralExpression(expr)) {
94
- return expr.elements.map((el) =>
95
- extractAstValue(el, refParamName, templateParamName, itemParamName)
96
- )
97
- }
98
- if (ts.isObjectLiteralExpression(expr)) {
99
- const obj: Record<string, unknown> = {}
100
- for (const prop of expr.properties) {
101
- if (!ts.isPropertyAssignment(prop)) continue
102
- const key = ts.isIdentifier(prop.name)
103
- ? prop.name.text
104
- : ts.isStringLiteral(prop.name)
105
- ? prop.name.text
106
- : null
107
- if (!key) continue
108
- obj[key] = extractAstValue(
109
- prop.initializer,
110
- refParamName,
111
- templateParamName,
112
- itemParamName
113
- )
114
- }
115
- return obj
116
- }
117
- if (ts.isPrefixUnaryExpression(expr)) {
118
- if (
119
- expr.operator === ts.SyntaxKind.MinusToken &&
120
- ts.isNumericLiteral(expr.operand)
121
- ) {
122
- return -Number(expr.operand.text)
123
- }
124
- }
125
- return undefined
126
- }
127
-
128
- function extractInputMapping(
129
- node: ts.Node,
130
- _checker: ts.TypeChecker
131
- ): Record<string, unknown | DataRef> {
132
- if (!ts.isArrowFunction(node)) {
133
- return {}
134
- }
135
-
136
- let bodyObj: ts.ObjectLiteralExpression | undefined
137
-
138
- if (ts.isObjectLiteralExpression(node.body)) {
139
- bodyObj = node.body
140
- } else if (ts.isParenthesizedExpression(node.body)) {
141
- if (ts.isObjectLiteralExpression(node.body.expression)) {
142
- bodyObj = node.body.expression
143
- }
144
- } else if (ts.isBlock(node.body)) {
145
- for (const stmt of node.body.statements) {
146
- if (ts.isReturnStatement(stmt) && stmt.expression) {
147
- if (ts.isObjectLiteralExpression(stmt.expression)) {
148
- bodyObj = stmt.expression
149
- }
150
- }
151
- }
152
- }
153
-
154
- if (!bodyObj) {
155
- return {}
156
- }
157
-
158
- const refParamName =
159
- node.parameters.length > 0 && ts.isIdentifier(node.parameters[0].name)
160
- ? node.parameters[0].name.text
161
- : 'ref'
162
-
163
- // The canonical form imports `template` from '@pikku/core/workflow' and calls
164
- // it inside a single-param `(ref) => (...)` arrow; the older form passes it as
165
- // a second arrow parameter. Support both — default to the imported name so a
166
- // `template(...)` value is never dropped just because it isn't a 2nd param.
167
- const templateParamName =
168
- node.parameters.length > 1 && ts.isIdentifier(node.parameters[1].name)
169
- ? node.parameters[1].name.text
170
- : 'template'
171
-
172
- // `$item` is appended after `template` so neither existing arrow shape —
173
- // `(ref) => ...` nor `(ref, template) => ...` — shifts a parameter.
174
- const itemParamName =
175
- node.parameters.length > 2 && ts.isIdentifier(node.parameters[2].name)
176
- ? node.parameters[2].name.text
177
- : undefined
178
-
179
- const input: Record<string, unknown | DataRef> = {}
180
-
181
- for (const prop of bodyObj.properties) {
182
- if (!ts.isPropertyAssignment(prop)) continue
183
-
184
- const key = ts.isIdentifier(prop.name)
185
- ? prop.name.text
186
- : ts.isStringLiteral(prop.name)
187
- ? prop.name.text
188
- : null
189
-
190
- if (!key) continue
191
-
192
- const value = extractAstValue(
193
- prop.initializer,
194
- refParamName,
195
- templateParamName,
196
- itemParamName
197
- )
198
- if (value !== undefined) {
199
- input[key] = value
200
- }
201
- }
202
-
203
- return input
204
- }
205
-
206
- /**
207
- * Extract a `forEach` source, authored either as a bare node id (`'listRows'`)
208
- * or as a callback returning a ref (`(ref) => ref('listRows', 'rows')`).
209
- */
210
- function extractForEachConfig(node: ts.Node): DataRef | undefined {
211
- while (ts.isAsExpression(node) || ts.isParenthesizedExpression(node)) {
212
- node = node.expression
213
- }
214
-
215
- if (ts.isStringLiteral(node)) {
216
- return { $ref: node.text }
217
- }
218
-
219
- if (ts.isArrowFunction(node)) {
220
- const refParamName =
221
- node.parameters.length > 0 && ts.isIdentifier(node.parameters[0].name)
222
- ? node.parameters[0].name.text
223
- : 'ref'
224
-
225
- let body: ts.Node = node.body
226
- if (ts.isBlock(body)) {
227
- for (const stmt of body.statements) {
228
- if (ts.isReturnStatement(stmt) && stmt.expression) {
229
- body = stmt.expression
230
- }
231
- }
232
- }
233
- if (!ts.isExpression(body)) return undefined
234
-
235
- const value = extractAstValue(body, refParamName, undefined)
236
- if (
237
- typeof value === 'object' &&
238
- value !== null &&
239
- '$ref' in value &&
240
- typeof (value as DataRef).$ref === 'string'
241
- ) {
242
- return value as DataRef
243
- }
244
- }
245
-
246
- return undefined
247
- }
248
-
249
- /**
250
- * Extract next config (string, array, or record)
251
- */
252
- function extractNextConfig(
253
- node: ts.Node,
254
- _checker: ts.TypeChecker
255
- ): string | string[] | Record<string, string | string[]> | undefined {
256
- // Key-based branch `next` (`{ key: [targets] }`) is authored with an `as any`
257
- // cast because the graph's NextConfig can't narrow record targets to node-id
258
- // literals; see through that (and parens) so the routing survives into the meta.
259
- while (ts.isAsExpression(node) || ts.isParenthesizedExpression(node)) {
260
- node = node.expression
261
- }
262
-
263
- if (ts.isStringLiteral(node)) {
264
- return node.text
265
- }
266
-
267
- if (ts.isArrayLiteralExpression(node)) {
268
- return node.elements
269
- .filter(ts.isStringLiteral)
270
- .map((el) => (el as ts.StringLiteral).text)
271
- }
272
-
273
- if (ts.isObjectLiteralExpression(node)) {
274
- const result: Record<string, string | string[]> = {}
275
- for (const prop of node.properties) {
276
- if (!ts.isPropertyAssignment(prop)) continue
277
-
278
- const key = ts.isIdentifier(prop.name)
279
- ? prop.name.text
280
- : ts.isStringLiteral(prop.name)
281
- ? prop.name.text
282
- : null
283
-
284
- if (!key) continue
285
-
286
- if (ts.isStringLiteral(prop.initializer)) {
287
- result[key] = prop.initializer.text
288
- } else if (ts.isArrayLiteralExpression(prop.initializer)) {
289
- result[key] = prop.initializer.elements
290
- .filter(ts.isStringLiteral)
291
- .map((el) => (el as ts.StringLiteral).text)
292
- }
293
- }
294
- return result
295
- }
296
-
297
- return undefined
298
- }
299
-
300
- /**
301
- * Compute entry node IDs from graph nodes
302
- */
303
- function computeEntryNodeIds(graphNodes: Record<string, any>): string[] {
304
- const hasIncomingEdge = new Set<string>()
305
- for (const node of Object.values(graphNodes)) {
306
- const next = node.next
307
- if (!next) continue
308
-
309
- if (typeof next === 'string') {
310
- hasIncomingEdge.add(next)
311
- } else if (Array.isArray(next)) {
312
- next.forEach((n: string) => hasIncomingEdge.add(n))
313
- } else if (typeof next === 'object') {
314
- for (const targets of Object.values(next)) {
315
- if (typeof targets === 'string') {
316
- hasIncomingEdge.add(targets)
317
- } else if (Array.isArray(targets)) {
318
- ;(targets as string[]).forEach((n) => hasIncomingEdge.add(n))
319
- }
320
- }
321
- }
322
- }
323
-
324
- return Object.keys(graphNodes).filter(
325
- (nodeId) => !hasIncomingEdge.has(nodeId)
326
- )
327
- }
328
-
329
- interface PikkuWorkflowGraphExtract {
330
- name?: string
331
- description?: string
332
- tags?: string[]
333
- notes?: string[]
334
- disabled?: true
335
- nodesNode?: ts.ObjectLiteralExpression
336
- configNode?: ts.ObjectLiteralExpression
337
- exportedName?: string
338
- }
339
-
340
- /**
341
- * Extract pikkuWorkflowGraph config from an object literal argument
342
- */
343
- function extractWorkflowGraphConfig(
344
- configArg: ts.ObjectLiteralExpression,
345
- checker: ts.TypeChecker
346
- ): PikkuWorkflowGraphExtract | undefined {
347
- let name: string | undefined
348
- let description: string | undefined
349
- let tags: string[] | undefined
350
- let notes: string[] | undefined
351
- let disabled: true | undefined
352
- let nodesNode: ts.ObjectLiteralExpression | undefined
353
- let configNode: ts.ObjectLiteralExpression | undefined
354
-
355
- for (const prop of configArg.properties) {
356
- if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue
357
-
358
- const propName = prop.name.text
359
- if (propName === 'name') {
360
- name = extractStringLiteral(prop.initializer, checker)
361
- } else if (propName === 'description') {
362
- description = extractStringLiteral(prop.initializer, checker)
363
- } else if (propName === 'disabled') {
364
- if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
365
- disabled = true
366
- }
367
- } else if (
368
- propName === 'tags' &&
369
- ts.isArrayLiteralExpression(prop.initializer)
370
- ) {
371
- tags = prop.initializer.elements
372
- .filter(ts.isStringLiteral)
373
- .map((el) => (el as ts.StringLiteral).text)
374
- } else if (
375
- propName === 'notes' &&
376
- ts.isArrayLiteralExpression(prop.initializer)
377
- ) {
378
- notes = prop.initializer.elements
379
- .filter(ts.isStringLiteral)
380
- .map((el) => (el as ts.StringLiteral).text)
381
- } else if (
382
- propName === 'nodes' &&
383
- ts.isObjectLiteralExpression(prop.initializer)
384
- ) {
385
- nodesNode = prop.initializer
386
- } else if (
387
- propName === 'config' &&
388
- ts.isObjectLiteralExpression(prop.initializer)
389
- ) {
390
- configNode = prop.initializer
391
- }
392
- }
393
-
394
- return { name, description, tags, notes, disabled, nodesNode, configNode }
395
- }
396
-
397
- /**
398
- * Extract graph nodes from the new pikkuWorkflowGraph format
399
- * New format: { nodes: { entry: 'rpcName', ... }, config: { entry: { next: 'sendWelcome', ... }, ... } }
400
- */
401
- function extractGraphFromNewFormat(
402
- nodesNode: ts.ObjectLiteralExpression | undefined,
403
- configNode: ts.ObjectLiteralExpression | undefined,
404
- checker: ts.TypeChecker,
405
- state: any
406
- ): Record<string, any> {
407
- const nodes: Record<string, any> = {}
408
-
409
- if (!nodesNode) {
410
- return nodes
411
- }
412
-
413
- // Extract node ID to RPC name mapping from 'nodes' property
414
- const nodeRpcMap: Record<string, string> = {}
415
- for (const prop of nodesNode.properties) {
416
- if (!ts.isPropertyAssignment(prop)) continue
417
-
418
- const nodeId = ts.isIdentifier(prop.name)
419
- ? prop.name.text
420
- : ts.isStringLiteral(prop.name)
421
- ? prop.name.text
422
- : null
423
-
424
- if (!nodeId) continue
425
-
426
- const rpcName = extractStringLiteral(prop.initializer, checker)
427
- if (rpcName) {
428
- nodeRpcMap[nodeId] = rpcName
429
- state.rpc.invokedFunctions.add(rpcName)
430
- const funcFile = state.functions.files.get(rpcName)
431
- if (funcFile && !state.rpc.internalFiles.has(rpcName)) {
432
- state.rpc.internalFiles.set(rpcName, funcFile)
433
- }
434
- }
435
- }
436
-
437
- // Initialize nodes with their RPC names
438
- for (const [nodeId, rpcName] of Object.entries(nodeRpcMap)) {
439
- nodes[nodeId] = {
440
- nodeId,
441
- rpcName,
442
- input: {},
443
- forEach: undefined,
444
- mode: undefined,
445
- next: undefined,
446
- onError: undefined,
447
- retries: undefined,
448
- retryDelay: undefined,
449
- notes: undefined,
450
- }
451
- }
452
-
453
- // Extract config for each node from 'config' property
454
- if (configNode) {
455
- for (const prop of configNode.properties) {
456
- if (!ts.isPropertyAssignment(prop)) continue
457
-
458
- const nodeId = ts.isIdentifier(prop.name)
459
- ? prop.name.text
460
- : ts.isStringLiteral(prop.name)
461
- ? prop.name.text
462
- : null
463
-
464
- if (!nodeId || !nodes[nodeId]) continue
465
-
466
- if (ts.isObjectLiteralExpression(prop.initializer)) {
467
- const nodeConfig = extractNodeConfigFromObject(
468
- prop.initializer,
469
- checker
470
- )
471
- if (nodeConfig) {
472
- nodes[nodeId].next = nodeConfig.next
473
- nodes[nodeId].onError = nodeConfig.onError
474
- nodes[nodeId].input = nodeConfig.input
475
- nodes[nodeId].forEach = nodeConfig.forEach
476
- nodes[nodeId].mode = nodeConfig.mode
477
- nodes[nodeId].retries = nodeConfig.retries
478
- nodes[nodeId].retryDelay = nodeConfig.retryDelay
479
- nodes[nodeId].notes = nodeConfig.notes
480
- }
481
- }
482
- }
483
- }
484
-
485
- return nodes
486
- }
487
-
488
- /**
489
- * Extract node config (next, onError, input) from object literal
490
- */
491
- function extractNodeConfigFromObject(
492
- obj: ts.ObjectLiteralExpression,
493
- checker: ts.TypeChecker
494
- ): {
495
- next: any
496
- onError: any
497
- input: Record<string, any>
498
- forEach: DataRef | undefined
499
- mode: string | undefined
500
- retries: number | undefined
501
- retryDelay: string | number | undefined
502
- notes: string | undefined
503
- } {
504
- let next: any = undefined
505
- let onError: any = undefined
506
- let input: Record<string, any> = {}
507
- let forEach: DataRef | undefined = undefined
508
- let mode: string | undefined = undefined
509
- let retries: number | undefined = undefined
510
- let retryDelay: string | number | undefined = undefined
511
- let notes: string | undefined = undefined
512
-
513
- for (const prop of obj.properties) {
514
- if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) continue
515
-
516
- const propName = prop.name.text
517
-
518
- if (propName === 'next') {
519
- next = extractNextConfig(prop.initializer, checker)
520
- } else if (propName === 'onError') {
521
- onError = extractNextConfig(prop.initializer, checker)
522
- } else if (propName === 'input') {
523
- input = extractInputMapping(prop.initializer, checker)
524
- } else if (propName === 'forEach') {
525
- forEach = extractForEachConfig(prop.initializer)
526
- } else if (propName === 'mode') {
527
- mode = extractStringLiteral(prop.initializer, checker)
528
- } else if (propName === 'retries') {
529
- if (ts.isNumericLiteral(prop.initializer)) {
530
- retries = Number(prop.initializer.text)
531
- }
532
- } else if (propName === 'retryDelay') {
533
- if (ts.isNumericLiteral(prop.initializer)) {
534
- retryDelay = Number(prop.initializer.text)
535
- } else if (ts.isStringLiteral(prop.initializer)) {
536
- retryDelay = prop.initializer.text
537
- }
538
- } else if (propName === 'notes') {
539
- notes = extractStringLiteral(prop.initializer, checker)
540
- }
541
- }
542
-
543
- return { next, onError, input, forEach, mode, retries, retryDelay, notes }
544
- }
545
-
546
- /**
547
- * Inspector for pikkuWorkflowGraph() calls
548
- * Detects: pikkuWorkflowGraph({ nodes: {...}, config: {...} })
549
- * or: export const x = pikkuWorkflowGraph({...}) where the call is found via variable declaration
550
- */
551
- export const addWorkflowGraph: AddWiring = (logger, node, checker, state) => {
552
- if (!ts.isCallExpression(node)) {
553
- return
554
- }
555
-
556
- const expression = node.expression
557
- if (
558
- !ts.isIdentifier(expression) ||
559
- expression.text !== 'pikkuWorkflowGraph'
560
- ) {
561
- return
562
- }
563
-
564
- const args = node.arguments
565
- const firstArg = args[0]
566
-
567
- if (!firstArg) {
568
- logger.critical(
569
- ErrorCode.MISSING_FUNC,
570
- 'pikkuWorkflowGraph requires an argument'
571
- )
572
- return
573
- }
574
-
575
- if (!ts.isObjectLiteralExpression(firstArg)) {
576
- logger.critical(
577
- ErrorCode.MISSING_FUNC,
578
- 'pikkuWorkflowGraph requires an object argument'
579
- )
580
- return
581
- }
582
-
583
- const graphConfig = extractWorkflowGraphConfig(firstArg, checker)
584
-
585
- if (!graphConfig) {
586
- logger.critical(
587
- ErrorCode.MISSING_NAME,
588
- 'pikkuWorkflowGraph: failed to extract config'
589
- )
590
- return
591
- }
592
-
593
- // Resolve exportedName from variable declaration if this is `export const x = pikkuWorkflowGraph({...})`
594
- const parent = node.parent
595
- if (
596
- !graphConfig.exportedName &&
597
- parent &&
598
- ts.isVariableDeclaration(parent) &&
599
- ts.isIdentifier(parent.name)
600
- ) {
601
- graphConfig.exportedName = parent.name.text
602
- }
603
-
604
- const workflowName = graphConfig.name || graphConfig.exportedName
605
-
606
- if (!workflowName) {
607
- logger.critical(
608
- ErrorCode.MISSING_NAME,
609
- 'pikkuWorkflowGraph requires a name property or exported variable name'
610
- )
611
- return
612
- }
613
-
614
- let graphNodes: Record<string, any> = {}
615
- if (graphConfig.nodesNode) {
616
- graphNodes = extractGraphFromNewFormat(
617
- graphConfig.nodesNode,
618
- graphConfig.configNode,
619
- checker,
620
- state
621
- )
622
- }
623
-
624
- const entryNodeIds = computeEntryNodeIds(graphNodes)
625
-
626
- const serialized: SerializedWorkflowGraph = {
627
- name: workflowName,
628
- pikkuFuncId: workflowName,
629
- source: 'graph',
630
- description: graphConfig.description,
631
- tags: graphConfig.tags,
632
- notes: graphConfig.notes,
633
- nodes: graphNodes,
634
- entryNodeIds,
635
- }
636
-
637
- if (graphConfig.disabled) return
638
-
639
- state.workflows.graphMeta[workflowName] = serialized
640
- state.workflows.graphFiles.set(workflowName, {
641
- path: node.getSourceFile().fileName,
642
- exportedName: graphConfig.exportedName || workflowName,
643
- })
644
- }