@pikku/inspector 0.12.75 → 0.12.82

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 (223) hide show
  1. package/CHANGELOG.md +357 -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-middleware.js +66 -42
  8. package/dist/add/add-wire-addon.js +7 -4
  9. package/dist/add/add-wire-remote-addon.js +1 -0
  10. package/dist/error-codes.d.ts +1 -0
  11. package/dist/error-codes.js +1 -0
  12. package/dist/index.d.ts +3 -1
  13. package/dist/index.js +3 -1
  14. package/dist/inspector.js +5 -0
  15. package/dist/surface/collect-surface.d.ts +58 -0
  16. package/dist/surface/collect-surface.js +613 -0
  17. package/dist/types.d.ts +36 -12
  18. package/dist/utils/filter-inspector-state.js +14 -0
  19. package/dist/utils/load-addon-functions-meta.js +24 -11
  20. package/dist/utils/post-process.js +15 -0
  21. package/dist/utils/read-module-specifiers.d.ts +8 -0
  22. package/dist/utils/read-module-specifiers.js +23 -0
  23. package/dist/utils/read-tsconfig-out-dir.d.ts +5 -0
  24. package/dist/utils/read-tsconfig-out-dir.js +12 -0
  25. package/dist/utils/resolve-deploy-target.d.ts +7 -0
  26. package/dist/utils/resolve-deploy-target.js +15 -7
  27. package/dist/utils/serialize-inspector-state.d.ts +6 -0
  28. package/dist/utils/serialize-inspector-state.js +10 -0
  29. package/dist/visit.js +4 -0
  30. package/package.json +16 -6
  31. package/run-tests.sh +21 -6
  32. package/src/add/add-addon-bans.ts +0 -85
  33. package/src/add/add-agent-scorer.test.ts +0 -197
  34. package/src/add/add-agent-scorer.ts +0 -83
  35. package/src/add/add-agent.test.ts +0 -87
  36. package/src/add/add-agent.ts +0 -638
  37. package/src/add/add-approval-description.ts +0 -76
  38. package/src/add/add-auth.test.ts +0 -791
  39. package/src/add/add-auth.ts +0 -424
  40. package/src/add/add-channel.ts +0 -778
  41. package/src/add/add-cli-renderers.test.ts +0 -74
  42. package/src/add/add-cli.ts +0 -1006
  43. package/src/add/add-credential.ts +0 -186
  44. package/src/add/add-feature.test.ts +0 -306
  45. package/src/add/add-feature.ts +0 -253
  46. package/src/add/add-file-extends-core-type.ts +0 -66
  47. package/src/add/add-file-with-config.ts +0 -45
  48. package/src/add/add-file-with-factory.test.ts +0 -134
  49. package/src/add/add-file-with-factory.ts +0 -288
  50. package/src/add/add-functions.test.ts +0 -743
  51. package/src/add/add-functions.ts +0 -1548
  52. package/src/add/add-gateway.ts +0 -143
  53. package/src/add/add-http-route-ref.test.ts +0 -149
  54. package/src/add/add-http-route.ts +0 -530
  55. package/src/add/add-http-routes.ts +0 -471
  56. package/src/add/add-keyed-wiring.ts +0 -180
  57. package/src/add/add-mcp-prompt.ts +0 -157
  58. package/src/add/add-mcp-resource.ts +0 -175
  59. package/src/add/add-middleware.test.ts +0 -196
  60. package/src/add/add-middleware.ts +0 -879
  61. package/src/add/add-permission-auth.test.ts +0 -59
  62. package/src/add/add-permission.ts +0 -311
  63. package/src/add/add-personas.test.ts +0 -406
  64. package/src/add/add-personas.ts +0 -287
  65. package/src/add/add-queue-worker.ts +0 -117
  66. package/src/add/add-rpc-invocations.test.ts +0 -287
  67. package/src/add/add-rpc-invocations.ts +0 -221
  68. package/src/add/add-scenario-step.test.ts +0 -509
  69. package/src/add/add-schedule.ts +0 -120
  70. package/src/add/add-scope.test.ts +0 -419
  71. package/src/add/add-scope.ts +0 -221
  72. package/src/add/add-secret.ts +0 -10
  73. package/src/add/add-subject-scenario-steps.test.ts +0 -161
  74. package/src/add/add-system-role.test.ts +0 -297
  75. package/src/add/add-system-role.ts +0 -162
  76. package/src/add/add-trigger.ts +0 -165
  77. package/src/add/add-variable.ts +0 -10
  78. package/src/add/add-wire-addon.test.ts +0 -185
  79. package/src/add/add-wire-addon.ts +0 -146
  80. package/src/add/add-wire-remote-addon.ts +0 -80
  81. package/src/add/add-workflow-edge-cases.test.ts +0 -201
  82. package/src/add/add-workflow-fanout.test.ts +0 -166
  83. package/src/add/add-workflow-graph-foreach.test.ts +0 -174
  84. package/src/add/add-workflow-graph-input.test.ts +0 -94
  85. package/src/add/add-workflow-graph-notes.test.ts +0 -74
  86. package/src/add/add-workflow-graph.ts +0 -644
  87. package/src/add/add-workflow-on-error.test.ts +0 -118
  88. package/src/add/add-workflow-return-switch.test.ts +0 -121
  89. package/src/add/add-workflow-silent-drops.test.ts +0 -261
  90. package/src/add/add-workflow-sleep-expression.test.ts +0 -96
  91. package/src/add/add-workflow.test.ts +0 -155
  92. package/src/add/add-workflow.ts +0 -482
  93. package/src/add/addon-bans.test.ts +0 -121
  94. package/src/add/addon-contracts.test.ts +0 -221
  95. package/src/add/allow-escape-hatches.test.ts +0 -144
  96. package/src/add/audit-meta.test.ts +0 -75
  97. package/src/add/classified-sink-check.test.ts +0 -347
  98. package/src/add/config-value-metadata.test.ts +0 -263
  99. package/src/add/dynamic-import-check.test.ts +0 -119
  100. package/src/add/expect-eventually-scenario-only.test.ts +0 -108
  101. package/src/add/function-body-span.test.ts +0 -96
  102. package/src/add/inline-wiring-function.test.ts +0 -104
  103. package/src/add/pii-check.test.ts +0 -258
  104. package/src/add/rpc-type-cast.test.ts +0 -123
  105. package/src/add/scenario-instrumentation.test.ts +0 -89
  106. package/src/add/scenario-instrumentation.ts +0 -42
  107. package/src/add/scenario-marker.test.ts +0 -89
  108. package/src/add/scenario-not-extractable.test.ts +0 -159
  109. package/src/add/scenario-services.test.ts +0 -103
  110. package/src/add/scenario-skip.test.ts +0 -83
  111. package/src/add/validate-workflow-graph-addons.test.ts +0 -102
  112. package/src/add/wire-name-literal.test.ts +0 -117
  113. package/src/error-codes-emitted.test.ts +0 -76
  114. package/src/error-codes.ts +0 -145
  115. package/src/index.ts +0 -66
  116. package/src/inspector.ts +0 -575
  117. package/src/schema-generator.ts +0 -1
  118. package/src/source-file-cache.ts +0 -73
  119. package/src/tsconfig-paths.test.ts +0 -90
  120. package/src/types-map.ts +0 -141
  121. package/src/types.ts +0 -775
  122. package/src/utils/annotate-http-route-auth.test.ts +0 -161
  123. package/src/utils/annotate-http-route-auth.ts +0 -53
  124. package/src/utils/check-classified-sinks.ts +0 -215
  125. package/src/utils/check-pii-output.ts +0 -120
  126. package/src/utils/compute-diagnostics.test.ts +0 -106
  127. package/src/utils/compute-required-schemas.ts +0 -48
  128. package/src/utils/contract-hashes.test.ts +0 -553
  129. package/src/utils/contract-hashes.ts +0 -387
  130. package/src/utils/custom-types-generator.test.ts +0 -124
  131. package/src/utils/custom-types-generator.ts +0 -150
  132. package/src/utils/detect-schema-vendor.test.ts +0 -123
  133. package/src/utils/detect-schema-vendor.ts +0 -120
  134. package/src/utils/does-type-extend-core-type.ts +0 -53
  135. package/src/utils/ensure-function-metadata.ts +0 -385
  136. package/src/utils/extract-function-name.ts +0 -612
  137. package/src/utils/extract-function-node.ts +0 -70
  138. package/src/utils/extract-node-value.test.ts +0 -117
  139. package/src/utils/extract-node-value.ts +0 -172
  140. package/src/utils/extract-secret-usage.test.ts +0 -81
  141. package/src/utils/extract-secret-usage.ts +0 -73
  142. package/src/utils/extract-services.ts +0 -70
  143. package/src/utils/extract-surface-usage.test.ts +0 -147
  144. package/src/utils/extract-surface-usage.ts +0 -121
  145. package/src/utils/filter-inspector-state.test.ts +0 -2232
  146. package/src/utils/filter-inspector-state.ts +0 -1298
  147. package/src/utils/filter-utils.test.ts +0 -843
  148. package/src/utils/filter-utils.ts +0 -161
  149. package/src/utils/find-root-dir.ts +0 -68
  150. package/src/utils/find-zod-transform.test.ts +0 -70
  151. package/src/utils/find-zod-transform.ts +0 -103
  152. package/src/utils/get-exported-variable-name.ts +0 -48
  153. package/src/utils/get-files-and-methods.ts +0 -157
  154. package/src/utils/get-property-value.test.ts +0 -141
  155. package/src/utils/get-property-value.ts +0 -331
  156. package/src/utils/hash.ts +0 -26
  157. package/src/utils/literal-properties.ts +0 -97
  158. package/src/utils/load-addon-functions-meta.test.ts +0 -157
  159. package/src/utils/load-addon-functions-meta.ts +0 -508
  160. package/src/utils/load-addon-scopes.test.ts +0 -138
  161. package/src/utils/middleware.test.ts +0 -204
  162. package/src/utils/middleware.ts +0 -303
  163. package/src/utils/nested-project-filter.test.ts +0 -53
  164. package/src/utils/nested-project-filter.ts +0 -28
  165. package/src/utils/permissions-shorthand.test.ts +0 -79
  166. package/src/utils/permissions.test.ts +0 -125
  167. package/src/utils/permissions.ts +0 -129
  168. package/src/utils/post-process.test.ts +0 -1094
  169. package/src/utils/post-process.ts +0 -1604
  170. package/src/utils/resolve-addon-package.ts +0 -106
  171. package/src/utils/resolve-core-type.test.ts +0 -142
  172. package/src/utils/resolve-core-type.ts +0 -35
  173. package/src/utils/resolve-deploy-target.test.ts +0 -135
  174. package/src/utils/resolve-deploy-target.ts +0 -65
  175. package/src/utils/resolve-function-meta.ts +0 -25
  176. package/src/utils/resolve-function-types.ts +0 -42
  177. package/src/utils/resolve-identifier.ts +0 -46
  178. package/src/utils/resolve-ref-contract.ts +0 -71
  179. package/src/utils/resolve-versions.test.ts +0 -499
  180. package/src/utils/resolve-versions.ts +0 -228
  181. package/src/utils/schema-cache.test.ts +0 -124
  182. package/src/utils/schema-generator.test.ts +0 -272
  183. package/src/utils/schema-generator.ts +0 -780
  184. package/src/utils/secret-alias-services.test.ts +0 -146
  185. package/src/utils/secret-alias-services.ts +0 -58
  186. package/src/utils/serialize-inspector-state.ts +0 -742
  187. package/src/utils/serialize-mcp-json.ts +0 -150
  188. package/src/utils/serialize-middleware-groups-meta.ts +0 -36
  189. package/src/utils/serialize-openapi-json.ts +0 -277
  190. package/src/utils/serialize-permissions-groups-meta.ts +0 -7
  191. package/src/utils/single-declaration.ts +0 -57
  192. package/src/utils/type-utils.ts +0 -145
  193. package/src/utils/validate-auth-sessionless.ts +0 -30
  194. package/src/utils/validate-exposed-functions-gated.test.ts +0 -230
  195. package/src/utils/validate-exposed-functions-gated.ts +0 -103
  196. package/src/utils/validate-tags-resolve-to-middleware.test.ts +0 -108
  197. package/src/utils/validate-tags-resolve-to-middleware.ts +0 -48
  198. package/src/utils/workflow/derive-workflow-plan.test.ts +0 -178
  199. package/src/utils/workflow/derive-workflow-plan.ts +0 -117
  200. package/src/utils/workflow/dsl/deserialize-dsl-workflow.ts +0 -1465
  201. package/src/utils/workflow/dsl/deserialize-fanout-body.test.ts +0 -71
  202. package/src/utils/workflow/dsl/deserialize-fanout-fidelity.test.ts +0 -99
  203. package/src/utils/workflow/dsl/deserialize-graph-next.test.ts +0 -161
  204. package/src/utils/workflow/dsl/deserialize-roundtrip-bindings.test.ts +0 -121
  205. package/src/utils/workflow/dsl/deserialize-roundtrip-values.test.ts +0 -116
  206. package/src/utils/workflow/dsl/deserialize-roundtrip.test.ts +0 -145
  207. package/src/utils/workflow/dsl/extract-approval-policy.test.ts +0 -71
  208. package/src/utils/workflow/dsl/extract-dsl-workflow.ts +0 -2254
  209. package/src/utils/workflow/dsl/index.ts +0 -11
  210. package/src/utils/workflow/dsl/patterns.ts +0 -440
  211. package/src/utils/workflow/dsl/validation.ts +0 -203
  212. package/src/utils/workflow/graph/convert-dsl-to-graph-skip.test.ts +0 -35
  213. package/src/utils/workflow/graph/convert-dsl-to-graph.ts +0 -543
  214. package/src/utils/workflow/graph/fanout-node-identity.test.ts +0 -105
  215. package/src/utils/workflow/graph/finalize-workflow-wires.ts +0 -310
  216. package/src/utils/workflow/graph/finalize-workflows.test.ts +0 -50
  217. package/src/utils/workflow/graph/finalize-workflows.ts +0 -130
  218. package/src/utils/workflow/graph/index.ts +0 -28
  219. package/src/utils/workflow/graph/serialize-workflow-graph.ts +0 -240
  220. package/src/utils/workflow/graph/workflow-graph.types.ts +0 -281
  221. package/src/visit.ts +0 -181
  222. package/tsconfig.json +0 -19
  223. package/tsconfig.tsbuildinfo +0 -1
@@ -1,743 +0,0 @@
1
- import { strict as assert } from 'assert'
2
- import { describe, test } from 'node:test'
3
- import { mkdir, 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 { ErrorCode } from '../error-codes.js'
8
- import type { InspectorLogger } from '../types.js'
9
-
10
- describe('addFunctions duplicate name handling', () => {
11
- test('logs a critical error when function name is duplicated across files', async () => {
12
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-duplicate-function-'))
13
- const fileA = join(rootDir, 'a.ts')
14
- const fileB = join(rootDir, 'b.ts')
15
-
16
- await writeFile(
17
- fileA,
18
- [
19
- "import { pikkuFunc } from '@pikku/core'",
20
- 'export const createUser = pikkuFunc({',
21
- ' func: async () => ({ ok: true })',
22
- '})',
23
- ].join('\n')
24
- )
25
-
26
- await writeFile(
27
- fileB,
28
- [
29
- "import { pikkuFunc } from '@pikku/core'",
30
- 'export const createUser = pikkuFunc({',
31
- ' func: async () => ({ ok: true })',
32
- '})',
33
- ].join('\n')
34
- )
35
-
36
- const criticals: Array<{ code: ErrorCode; message: string }> = []
37
- const logger: InspectorLogger = {
38
- debug: () => {},
39
- info: () => {},
40
- warn: () => {},
41
- error: () => {},
42
- diagnostic: ({ code, message }) => {
43
- criticals.push({ code, message })
44
- },
45
- critical: (code: ErrorCode, message: string) => {
46
- criticals.push({ code, message })
47
- },
48
- hasCriticalErrors: () => criticals.length > 0,
49
- }
50
-
51
- try {
52
- const state = await inspect(logger, [fileA, fileB], { rootDir })
53
- const nameCollision = criticals.find(
54
- (entry) => entry.code === ErrorCode.DUPLICATE_FUNCTION_NAME
55
- )
56
- assert.ok(nameCollision)
57
- assert.match(nameCollision!.message, /createUser/)
58
- assert.strictEqual(state.rpc.internalMeta['createUser'], 'createUser')
59
- } finally {
60
- await rm(rootDir, { recursive: true, force: true })
61
- }
62
- })
63
-
64
- test('allows same base function name across files when versions differ', async () => {
65
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-versioned-function-'))
66
- const fileA = join(rootDir, 'a.ts')
67
- const fileB = join(rootDir, 'b.ts')
68
-
69
- await writeFile(
70
- fileA,
71
- [
72
- "import { pikkuFunc } from '@pikku/core'",
73
- 'export const createUser = pikkuFunc({',
74
- ' version: 1,',
75
- ' func: async () => ({ ok: true })',
76
- '})',
77
- ].join('\n')
78
- )
79
-
80
- await writeFile(
81
- fileB,
82
- [
83
- "import { pikkuFunc } from '@pikku/core'",
84
- 'export const createUser = pikkuFunc({',
85
- ' version: 2,',
86
- ' func: async () => ({ ok: true })',
87
- '})',
88
- ].join('\n')
89
- )
90
-
91
- const criticals: Array<{ code: ErrorCode; message: string }> = []
92
- const logger: InspectorLogger = {
93
- debug: () => {},
94
- info: () => {},
95
- warn: () => {},
96
- error: () => {},
97
- diagnostic: ({ code, message }) => {
98
- criticals.push({ code, message })
99
- },
100
- critical: (code: ErrorCode, message: string) => {
101
- criticals.push({ code, message })
102
- },
103
- hasCriticalErrors: () => criticals.length > 0,
104
- }
105
-
106
- try {
107
- const state = await inspect(logger, [fileA, fileB], { rootDir })
108
- const nameCollision = criticals.find(
109
- (entry) => entry.code === ErrorCode.DUPLICATE_FUNCTION_NAME
110
- )
111
- assert.equal(nameCollision, undefined)
112
- assert.strictEqual(state.rpc.internalMeta['createUser'], 'createUser@v2')
113
- assert.ok(state.functions.meta['createUser@v1'])
114
- assert.ok(state.functions.meta['createUser@v2'])
115
- } finally {
116
- await rm(rootDir, { recursive: true, force: true })
117
- }
118
- })
119
-
120
- test('strips VN suffix so createUserV1 + version:1 groups with createUser as createUser@v1', async () => {
121
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-vn-suffix-'))
122
- const fileV1 = join(rootDir, 'create-user-v1.ts')
123
- const fileLatest = join(rootDir, 'create-user.ts')
124
-
125
- await writeFile(
126
- fileV1,
127
- [
128
- "import { pikkuFunc } from '@pikku/core'",
129
- 'export const createUserV1 = pikkuFunc({',
130
- ' version: 1,',
131
- ' func: async () => ({ ok: true })',
132
- '})',
133
- ].join('\n')
134
- )
135
-
136
- await writeFile(
137
- fileLatest,
138
- [
139
- "import { pikkuFunc } from '@pikku/core'",
140
- 'export const createUser = pikkuFunc({',
141
- ' func: async () => ({ ok: true })',
142
- '})',
143
- ].join('\n')
144
- )
145
-
146
- const logger: InspectorLogger = {
147
- debug: () => {},
148
- info: () => {},
149
- warn: () => {},
150
- error: () => {},
151
- diagnostic: () => {},
152
- critical: () => {},
153
- hasCriticalErrors: () => false,
154
- }
155
-
156
- try {
157
- const state = await inspect(logger, [fileV1, fileLatest], { rootDir })
158
- // V1 suffix stripped: createUserV1 + version:1 → createUser@v1
159
- assert.ok(
160
- state.functions.meta['createUser@v1'],
161
- 'createUser@v1 should exist'
162
- )
163
- assert.strictEqual(state.functions.meta['createUser@v1']!.version, 1)
164
- // Unversioned createUser auto-promoted to createUser@v2
165
- assert.ok(
166
- state.functions.meta['createUser@v2'],
167
- 'createUser@v2 should exist'
168
- )
169
- assert.strictEqual(state.functions.meta['createUser@v2']!.version, 2)
170
- // No stale createUserV1@v1 entry
171
- assert.strictEqual(state.functions.meta['createUserV1@v1'], undefined)
172
- // Latest alias points to v2
173
- assert.strictEqual(state.rpc.internalMeta['createUser'], 'createUser@v2')
174
- } finally {
175
- await rm(rootDir, { recursive: true, force: true })
176
- }
177
- })
178
-
179
- test('logs a critical error when exposed function name is duplicated across files', async () => {
180
- const rootDir = await mkdtemp(
181
- join(tmpdir(), 'pikku-exposed-duplicate-function-')
182
- )
183
- const fileA = join(rootDir, 'a.ts')
184
- const fileB = join(rootDir, 'b.ts')
185
-
186
- await writeFile(
187
- fileA,
188
- [
189
- "import { pikkuFunc } from '@pikku/core'",
190
- 'export const createUser = pikkuFunc({',
191
- ' expose: true,',
192
- ' func: async () => ({ ok: true })',
193
- '})',
194
- ].join('\n')
195
- )
196
-
197
- await writeFile(
198
- fileB,
199
- [
200
- "import { pikkuFunc } from '@pikku/core'",
201
- 'export const createUser = pikkuFunc({',
202
- ' expose: true,',
203
- ' func: async () => ({ ok: true })',
204
- '})',
205
- ].join('\n')
206
- )
207
-
208
- const criticals: Array<{ code: ErrorCode; message: string }> = []
209
- const logger: InspectorLogger = {
210
- debug: () => {},
211
- info: () => {},
212
- warn: () => {},
213
- error: () => {},
214
- diagnostic: ({ code, message }) => {
215
- criticals.push({ code, message })
216
- },
217
- critical: (code: ErrorCode, message: string) => {
218
- criticals.push({ code, message })
219
- },
220
- hasCriticalErrors: () => criticals.length > 0,
221
- }
222
-
223
- try {
224
- await inspect(logger, [fileA, fileB], { rootDir })
225
- const nameCollision = criticals.find(
226
- (entry) => entry.code === ErrorCode.DUPLICATE_FUNCTION_NAME
227
- )
228
- assert.ok(nameCollision)
229
- assert.match(
230
- nameCollision!.message,
231
- /Function name 'createUser' is not unique/
232
- )
233
- } finally {
234
- await rm(rootDir, { recursive: true, force: true })
235
- }
236
- })
237
- })
238
-
239
- describe('addFunctions implementationHash', () => {
240
- test('records a stable implementation hash for an inline function', async () => {
241
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-function-hash-inline-'))
242
- const file = join(rootDir, 'inline.ts')
243
-
244
- await writeFile(
245
- file,
246
- [
247
- "import { pikkuFunc } from '@pikku/core'",
248
- 'export const createUser = pikkuFunc({',
249
- ' expose: true,',
250
- ' func: async ({ logger }, input: { name: string }) => {',
251
- " logger.info('create user')",
252
- ' return { ok: true, name: input.name }',
253
- ' }',
254
- '})',
255
- ].join('\n')
256
- )
257
-
258
- const logger: InspectorLogger = {
259
- debug: () => {},
260
- info: () => {},
261
- warn: () => {},
262
- error: () => {},
263
- diagnostic: () => {},
264
- critical: () => {},
265
- hasCriticalErrors: () => false,
266
- }
267
-
268
- try {
269
- const first = await inspect(logger, [file], { rootDir })
270
- const second = await inspect(logger, [file], { rootDir })
271
- const firstHash = first.functions.meta['createUser']?.implementationHash
272
- const secondHash = second.functions.meta['createUser']?.implementationHash
273
-
274
- assert.match(firstHash ?? '', /^[0-9a-f]{16}$/)
275
- assert.strictEqual(firstHash, secondHash)
276
- } finally {
277
- await rm(rootDir, { recursive: true, force: true })
278
- }
279
- })
280
-
281
- test('changes when a referenced handler implementation changes', async () => {
282
- const rootDir = await mkdtemp(
283
- join(tmpdir(), 'pikku-function-hash-referenced-')
284
- )
285
- const file = join(rootDir, 'referenced.ts')
286
-
287
- const writeSource = async (bodyLine: string) => {
288
- await writeFile(
289
- file,
290
- [
291
- "import { pikkuFunc } from '@pikku/core'",
292
- '',
293
- 'const handler = async () => {',
294
- ` ${bodyLine}`,
295
- ' return { ok: true }',
296
- '}',
297
- '',
298
- 'export const createUser = pikkuFunc({',
299
- ' func: handler,',
300
- '})',
301
- ].join('\n')
302
- )
303
- }
304
-
305
- const logger: InspectorLogger = {
306
- debug: () => {},
307
- info: () => {},
308
- warn: () => {},
309
- error: () => {},
310
- diagnostic: () => {},
311
- critical: () => {},
312
- hasCriticalErrors: () => false,
313
- }
314
-
315
- try {
316
- await writeSource("console.log('first')")
317
- const first = await inspect(logger, [file], { rootDir })
318
-
319
- await writeSource("console.log('second')")
320
- const second = await inspect(logger, [file], { rootDir })
321
-
322
- assert.notStrictEqual(
323
- first.functions.meta['createUser']?.implementationHash,
324
- second.functions.meta['createUser']?.implementationHash
325
- )
326
- } finally {
327
- await rm(rootDir, { recursive: true, force: true })
328
- }
329
- })
330
- })
331
-
332
- describe('pikkuChannelConnectionFunc generic mapping', () => {
333
- // Regression: pikkuChannelConnectionFunc<Out> has a single generic that is the
334
- // OUTPUT type (input is always void). The inspector must NOT record that generic
335
- // as inputSchemaName — otherwise the empty WS handshake is validated against an
336
- // input schema requiring the send-payload shape and the connect is rejected 403.
337
- test('does not map the output generic to inputSchemaName', async () => {
338
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-channel-connect-'))
339
- const file = join(rootDir, 'channel.ts')
340
-
341
- await writeFile(
342
- file,
343
- [
344
- 'type Sessionless<In, Out> = (',
345
- ' services: any,',
346
- ' data: In,',
347
- ' interaction: any',
348
- ') => Promise<Out>',
349
- 'export const pikkuChannelConnectionFunc = <Out = unknown>(',
350
- ' func: Sessionless<void, Out>',
351
- ') => ({ func })',
352
- 'export const onCardsConnect = pikkuChannelConnectionFunc<{',
353
- " type: 'hello'",
354
- ' count: number',
355
- '}>(async (_services, _data, _interaction) => {})',
356
- ].join('\n')
357
- )
358
-
359
- const logger: InspectorLogger = {
360
- debug: () => {},
361
- info: () => {},
362
- warn: () => {},
363
- error: () => {},
364
- diagnostic: () => {},
365
- critical: () => {},
366
- hasCriticalErrors: () => false,
367
- }
368
-
369
- try {
370
- const state = await inspect(logger, [file], { rootDir })
371
- const meta = state.functions.meta['onCardsConnect']
372
- assert.ok(meta, 'onCardsConnect meta should exist')
373
- assert.strictEqual(
374
- meta!.inputSchemaName,
375
- null,
376
- 'connect input must be void (no input schema), not the output generic'
377
- )
378
- assert.deepStrictEqual(meta!.inputs, [])
379
- } finally {
380
- await rm(rootDir, { recursive: true, force: true })
381
- }
382
- })
383
- })
384
-
385
- describe('pikkuRemoteChannelFunc', () => {
386
- const quietLogger = (): InspectorLogger & {
387
- errors: string[]
388
- criticals: Array<{ code: ErrorCode; message: string }>
389
- } => {
390
- const errors: string[] = []
391
- const criticals: Array<{ code: ErrorCode; message: string }> = []
392
- return {
393
- debug: () => {},
394
- info: () => {},
395
- warn: () => {},
396
- error: (message: string) => {
397
- errors.push(message)
398
- },
399
- diagnostic: ({ code, message }) => {
400
- criticals.push({ code, message })
401
- },
402
- critical: (code: ErrorCode, message: string) => {
403
- criticals.push({ code, message })
404
- },
405
- hasCriticalErrors: () => criticals.length > 0,
406
- errors,
407
- criticals,
408
- } as any
409
- }
410
-
411
- /**
412
- * The vendor check keys off the declaration file's path, so a stub under
413
- * `node_modules/zod` is indistinguishable from the real thing and costs this
414
- * suite no dependency.
415
- */
416
- const writeZodStub = async (rootDir: string) => {
417
- const dir = join(rootDir, 'node_modules', 'zod')
418
- await mkdir(dir, { recursive: true })
419
- await writeFile(
420
- join(dir, 'package.json'),
421
- JSON.stringify({ name: 'zod', version: '3.0.0', types: 'index.d.ts' })
422
- )
423
- await writeFile(
424
- join(dir, 'index.d.ts'),
425
- [
426
- 'export interface ZodType<Output = unknown> {',
427
- ' _output: Output',
428
- '}',
429
- 'export declare const z: {',
430
- ' object(shape: Record<string, ZodType>): ZodType<Record<string, unknown>>',
431
- ' string(): ZodType<string>',
432
- '}',
433
- '',
434
- ].join('\n')
435
- )
436
- }
437
-
438
- const DECLARE_WRAPPER = [
439
- "import { z } from 'zod'",
440
- 'declare function pikkuRemoteChannelFunc(config: any): any',
441
- 'declare function pikkuSessionlessFunc(config: any): any',
442
- ]
443
-
444
- const withProject = async (
445
- label: string,
446
- files: Record<string, string[]>,
447
- assertions: (
448
- state: Awaited<ReturnType<typeof inspect>>,
449
- logger: ReturnType<typeof quietLogger>
450
- ) => void
451
- ) => {
452
- const rootDir = await mkdtemp(join(tmpdir(), `pikku-${label}-`))
453
- await writeZodStub(rootDir)
454
- const paths: string[] = []
455
- for (const [name, lines] of Object.entries(files)) {
456
- const path = join(rootDir, name)
457
- await writeFile(path, [...DECLARE_WRAPPER, ...lines, ''].join('\n'))
458
- paths.push(path)
459
- }
460
- const logger = quietLogger()
461
- try {
462
- assertions(await inspect(logger, paths, { rootDir }), logger)
463
- } finally {
464
- await rm(rootDir, { recursive: true, force: true })
465
- }
466
- }
467
-
468
- test('a declaration with no func is registered rather than rejected', async () => {
469
- await withProject(
470
- 'remote-channel-registers',
471
- {
472
- 'capabilities.ts': [
473
- 'export const localCheckoutOutput = z.object({ sha: z.string() })',
474
- 'export const localCheckout = pikkuRemoteChannelFunc({',
475
- " title: 'localCheckout',",
476
- " description: 'Read the current commit of your working tree',",
477
- ' output: localCheckoutOutput,',
478
- '})',
479
- ],
480
- },
481
- (state, logger) => {
482
- // The ordinary path logs "No valid 'func' property" for a config with
483
- // no callable func, which is what a contract-only declaration is.
484
- assert.deepStrictEqual(logger.errors, [])
485
- assert.deepStrictEqual(logger.criticals, [])
486
-
487
- const meta = state.functions.meta['localCheckout']
488
- assert.ok(meta, 'the declaration should be registered')
489
- assert.strictEqual(meta!.functionType, 'remote')
490
- assert.strictEqual(meta!.funcWrapper, 'pikkuRemoteChannelFunc')
491
- assert.strictEqual(
492
- meta!.description,
493
- 'Read the current commit of your working tree'
494
- )
495
- }
496
- )
497
- })
498
-
499
- test('the declared schemas are what each side gets checked against', async () => {
500
- await withProject(
501
- 'remote-channel-schemas',
502
- {
503
- 'capabilities.ts': [
504
- 'export const runCommandInput = z.object({ argv: z.string() })',
505
- 'export const runCommandOutput = z.object({ stdout: z.string() })',
506
- 'export const runCommand = pikkuRemoteChannelFunc({',
507
- ' input: runCommandInput,',
508
- ' output: runCommandOutput,',
509
- '})',
510
- ],
511
- },
512
- (state) => {
513
- const meta = state.functions.meta['runCommand']
514
- assert.strictEqual(meta!.inputSchemaName, 'RunCommandInput')
515
- assert.strictEqual(meta!.outputSchemaName, 'RunCommandOutput')
516
- assert.deepStrictEqual(meta!.outputs, ['RunCommandOutput'])
517
- assert.strictEqual(
518
- state.schemaLookup.get('RunCommandOutput')?.variableName,
519
- 'runCommandOutput'
520
- )
521
- }
522
- )
523
- })
524
-
525
- test('the name resolves through the RPC map, which is what channel.remote reads', async () => {
526
- await withProject(
527
- 'remote-channel-rpc-map',
528
- {
529
- 'capabilities.ts': [
530
- 'export const localCheckoutOutput = z.object({ sha: z.string() })',
531
- 'export const localCheckout = pikkuRemoteChannelFunc({',
532
- ' output: localCheckoutOutput,',
533
- '})',
534
- ],
535
- },
536
- (state) => {
537
- // Both validators look the name up here and skip validation on a miss,
538
- // so an unregistered name silently disables the schema check.
539
- assert.strictEqual(
540
- state.rpc.internalMeta['localCheckout'],
541
- 'localCheckout'
542
- )
543
- // Imported, so a local call reaches the factory's thrower rather than
544
- // missing the registry.
545
- assert.strictEqual(
546
- state.rpc.internalFiles.get('localCheckout')?.exportedName,
547
- 'localCheckout'
548
- )
549
- }
550
- )
551
- })
552
-
553
- test('an unexported declaration is skipped, the way any unexported function is', async () => {
554
- await withProject(
555
- 'remote-channel-unexported',
556
- {
557
- 'capabilities.ts': [
558
- 'const localCheckoutOutput = z.object({ sha: z.string() })',
559
- 'const localCheckout = pikkuRemoteChannelFunc({',
560
- ' output: localCheckoutOutput,',
561
- '})',
562
- 'void localCheckout',
563
- ],
564
- },
565
- (state) => {
566
- // No export and no `override` leaves nothing to name it by, so it is
567
- // dropped upstream and never reaches the remote-channel path.
568
- assert.strictEqual(state.rpc.internalMeta['localCheckout'], undefined)
569
- assert.strictEqual(state.functions.meta['localCheckout'], undefined)
570
- }
571
- )
572
- })
573
-
574
- test('a name claimed by override still has to be exported for the server to import it', async () => {
575
- await withProject(
576
- 'remote-channel-override-unexported',
577
- {
578
- 'capabilities.ts': [
579
- 'const localCheckoutOutput = z.object({ sha: z.string() })',
580
- 'const localCheckout = pikkuRemoteChannelFunc({',
581
- " override: 'localCheckout',",
582
- ' output: localCheckoutOutput,',
583
- '})',
584
- 'void localCheckout',
585
- ],
586
- },
587
- (state, logger) => {
588
- assert.strictEqual(
589
- logger.errors.length,
590
- 1,
591
- `expected one error, got ${JSON.stringify(logger.errors)}`
592
- )
593
- assert.match(logger.errors[0]!, /not exported/)
594
- assert.strictEqual(state.rpc.internalMeta['localCheckout'], undefined)
595
- }
596
- )
597
- })
598
-
599
- test('two capabilities cannot share a name', async () => {
600
- await withProject(
601
- 'remote-channel-duplicate',
602
- {
603
- 'a.ts': [
604
- 'export const aOutput = z.object({ sha: z.string() })',
605
- 'export const localCheckout = pikkuRemoteChannelFunc({',
606
- ' output: aOutput,',
607
- '})',
608
- ],
609
- 'b.ts': [
610
- 'export const bOutput = z.object({ sha: z.string() })',
611
- 'export const localCheckout = pikkuRemoteChannelFunc({',
612
- ' output: bOutput,',
613
- '})',
614
- ],
615
- },
616
- (_state, logger) => {
617
- const collision = logger.criticals.find(
618
- (entry) => entry.code === ErrorCode.DUPLICATE_FUNCTION_NAME
619
- )
620
- assert.ok(collision, 'a name collision should be reported')
621
- assert.match(collision!.message, /not unique/)
622
- }
623
- )
624
- })
625
-
626
- test('the ordinary path still rejects a config with no callable func', async () => {
627
- await withProject(
628
- 'remote-channel-ordinary-path',
629
- {
630
- 'capabilities.ts': [
631
- 'export const broken = pikkuSessionlessFunc({ auth: false })',
632
- ],
633
- },
634
- (state, logger) => {
635
- assert.strictEqual(
636
- logger.errors.length,
637
- 1,
638
- `expected one error, got ${JSON.stringify(logger.errors)}`
639
- )
640
- assert.match(logger.errors[0]!, /No valid 'func' property/)
641
- assert.strictEqual(state.functions.meta['broken']?.functionType, 'user')
642
- }
643
- )
644
- })
645
- })
646
-
647
- describe('MCP tool naming', () => {
648
- const quietLogger = (): InspectorLogger => ({
649
- debug: () => {},
650
- info: () => {},
651
- warn: () => {},
652
- error: () => {},
653
- diagnostic: () => {},
654
- critical: () => {},
655
- hasCriticalErrors: () => false,
656
- })
657
-
658
- test('a declared name is what the tool is published as', async () => {
659
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-mcp-tool-name-'))
660
- const file = join(rootDir, 'tool.ts')
661
- await writeFile(
662
- file,
663
- [
664
- "import { pikkuMCPToolFunc } from '@pikku/core'",
665
- 'export const createUnansweredCountTool = pikkuMCPToolFunc({',
666
- " name: 'getUnansweredConversationCount',",
667
- " description: 'How many conversations are unanswered.',",
668
- ' func: async () => ({ ok: true })',
669
- '})',
670
- ].join('\n')
671
- )
672
-
673
- try {
674
- const state = await inspect(quietLogger(), [file], { rootDir })
675
- const tools = state.mcpEndpoints.toolsMeta
676
- assert.ok(
677
- tools['getUnansweredConversationCount'],
678
- `expected the declared name, got: ${Object.keys(tools).join(', ')}`
679
- )
680
- assert.strictEqual(tools['createUnansweredCountTool'], undefined)
681
- assert.strictEqual(
682
- tools['getUnansweredConversationCount']!.pikkuFuncId,
683
- 'createUnansweredCountTool'
684
- )
685
- } finally {
686
- await rm(rootDir, { recursive: true, force: true })
687
- }
688
- })
689
-
690
- test('with no declared name the export still names the tool', async () => {
691
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-mcp-tool-export-'))
692
- const file = join(rootDir, 'tool.ts')
693
- await writeFile(
694
- file,
695
- [
696
- "import { pikkuMCPToolFunc } from '@pikku/core'",
697
- 'export const listOpenTickets = pikkuMCPToolFunc({',
698
- " description: 'Tickets still open.',",
699
- ' func: async () => ({ ok: true })',
700
- '})',
701
- ].join('\n')
702
- )
703
-
704
- try {
705
- const state = await inspect(quietLogger(), [file], { rootDir })
706
- assert.ok(state.mcpEndpoints.toolsMeta['listOpenTickets'])
707
- } finally {
708
- await rm(rootDir, { recursive: true, force: true })
709
- }
710
- })
711
- test('a plain func with mcp: true is published under its declared name', async () => {
712
- const rootDir = await mkdtemp(join(tmpdir(), 'pikku-mcp-flag-name-'))
713
- const file = join(rootDir, 'tool.ts')
714
- await writeFile(
715
- file,
716
- [
717
- "import { pikkuFunc } from '@pikku/core'",
718
- 'export const countUnanswered = pikkuFunc({',
719
- ' mcp: true,',
720
- " name: 'getUnansweredConversationCount',",
721
- " description: 'How many conversations are unanswered.',",
722
- ' func: async () => ({ ok: true })',
723
- '})',
724
- ].join('\n')
725
- )
726
-
727
- try {
728
- const state = await inspect(quietLogger(), [file], { rootDir })
729
- const tools = state.mcpEndpoints.toolsMeta
730
- assert.ok(
731
- tools['getUnansweredConversationCount'],
732
- `expected the declared name, got: ${Object.keys(tools).join(', ')}`
733
- )
734
- assert.strictEqual(tools['countUnanswered'], undefined)
735
- assert.strictEqual(
736
- tools['getUnansweredConversationCount']!.pikkuFuncId,
737
- 'countUnanswered'
738
- )
739
- } finally {
740
- await rm(rootDir, { recursive: true, force: true })
741
- }
742
- })
743
- })