@pikku/core 0.12.2 → 0.12.4

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 (282) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/crypto-utils.d.ts +10 -0
  3. package/dist/crypto-utils.js +62 -0
  4. package/dist/function/function-runner.js +4 -4
  5. package/dist/function/functions.types.d.ts +26 -1
  6. package/dist/function/functions.types.js +16 -0
  7. package/dist/handle-error.d.ts +1 -1
  8. package/dist/handle-error.js +7 -3
  9. package/dist/index.d.ts +14 -2
  10. package/dist/index.js +1 -1
  11. package/dist/pikku-state.js +3 -1
  12. package/dist/schema.js +1 -1
  13. package/dist/services/in-memory-workflow-service.d.ts +22 -3
  14. package/dist/services/in-memory-workflow-service.js +77 -1
  15. package/dist/services/workflow-service.d.ts +8 -2
  16. package/dist/testing/index.d.ts +2 -0
  17. package/dist/testing/index.js +1 -0
  18. package/dist/testing/service-tests.d.ts +31 -0
  19. package/dist/testing/service-tests.js +598 -0
  20. package/dist/types/core.types.d.ts +9 -1
  21. package/dist/types/state.types.d.ts +4 -2
  22. package/dist/utils/hash.d.ts +2 -0
  23. package/dist/utils/hash.js +23 -0
  24. package/dist/wirings/ai-agent/agent-dynamic-workflow.d.ts +6 -0
  25. package/dist/wirings/ai-agent/agent-dynamic-workflow.js +348 -0
  26. package/dist/wirings/ai-agent/ai-agent-memory.d.ts +1 -1
  27. package/dist/wirings/ai-agent/ai-agent-memory.js +6 -5
  28. package/dist/wirings/ai-agent/ai-agent-prepare.d.ts +10 -7
  29. package/dist/wirings/ai-agent/ai-agent-prepare.js +127 -47
  30. package/dist/wirings/ai-agent/ai-agent-runner.d.ts +4 -0
  31. package/dist/wirings/ai-agent/ai-agent-runner.js +381 -27
  32. package/dist/wirings/ai-agent/ai-agent-stream.d.ts +7 -2
  33. package/dist/wirings/ai-agent/ai-agent-stream.js +109 -46
  34. package/dist/wirings/ai-agent/ai-agent.types.d.ts +22 -1
  35. package/dist/wirings/ai-agent/index.d.ts +1 -2
  36. package/dist/wirings/ai-agent/index.js +1 -2
  37. package/dist/wirings/channel/channel-handler.js +5 -1
  38. package/dist/wirings/channel/channel.types.d.ts +1 -7
  39. package/dist/wirings/channel/local/local-channel-handler.d.ts +1 -1
  40. package/dist/wirings/channel/local/local-channel-handler.js +5 -3
  41. package/dist/wirings/channel/local/local-channel-runner.js +14 -4
  42. package/dist/wirings/channel/serverless/serverless-channel-runner.js +4 -1
  43. package/dist/wirings/cli/cli-runner.js +10 -2
  44. package/dist/wirings/cli/cli.types.d.ts +1 -0
  45. package/dist/wirings/http/http-routes.js +0 -1
  46. package/dist/wirings/http/http-runner.d.ts +1 -1
  47. package/dist/wirings/http/http-runner.js +25 -3
  48. package/dist/wirings/http/http.types.d.ts +3 -11
  49. package/dist/wirings/http/index.d.ts +2 -1
  50. package/dist/wirings/http/index.js +1 -0
  51. package/dist/wirings/http/pikku-fetch-http-request.d.ts +1 -0
  52. package/dist/wirings/http/pikku-fetch-http-request.js +3 -0
  53. package/dist/wirings/http/pikku-fetch-http-response.d.ts +1 -0
  54. package/dist/wirings/http/pikku-fetch-http-response.js +4 -4
  55. package/dist/wirings/http/web-request.d.ts +12 -0
  56. package/dist/wirings/http/web-request.js +85 -0
  57. package/dist/wirings/mcp/mcp-endpoint-registry.js +1 -1
  58. package/dist/wirings/mcp/mcp-runner.js +13 -1
  59. package/dist/wirings/rpc/rpc-runner.d.ts +30 -6
  60. package/dist/wirings/rpc/rpc-runner.js +36 -14
  61. package/dist/wirings/rpc/rpc-types.d.ts +6 -1
  62. package/dist/wirings/rpc/wire-addon.d.ts +1 -0
  63. package/dist/wirings/rpc/wire-addon.js +1 -1
  64. package/dist/wirings/scheduler/scheduler-runner.js +1 -0
  65. package/dist/wirings/workflow/graph/graph-validation.d.ts +3 -0
  66. package/dist/wirings/workflow/graph/graph-validation.js +175 -0
  67. package/dist/wirings/workflow/graph/index.d.ts +1 -0
  68. package/dist/wirings/workflow/graph/index.js +1 -0
  69. package/dist/wirings/workflow/index.d.ts +1 -1
  70. package/dist/wirings/workflow/pikku-workflow-service.d.ts +8 -2
  71. package/dist/wirings/workflow/pikku-workflow-service.js +1 -2
  72. package/dist/wirings/workflow/workflow.types.d.ts +10 -1
  73. package/lcov.info +18891 -0
  74. package/package.json +4 -2
  75. package/dist/wirings/ai-agent/ai-agent-assistant-ui.d.ts +0 -5
  76. package/dist/wirings/ai-agent/ai-agent-assistant-ui.js +0 -168
  77. package/src/crypto-utils.test.ts +0 -116
  78. package/src/crypto-utils.ts +0 -99
  79. package/src/errors/error-handler.ts +0 -62
  80. package/src/errors/error.test.ts +0 -195
  81. package/src/errors/errors.ts +0 -374
  82. package/src/errors/index.ts +0 -2
  83. package/src/factory-functions.test.ts +0 -109
  84. package/src/function/function-runner.test.ts +0 -536
  85. package/src/function/function-runner.ts +0 -365
  86. package/src/function/functions.types.ts +0 -267
  87. package/src/function/index.ts +0 -5
  88. package/src/handle-error.test.ts +0 -361
  89. package/src/handle-error.ts +0 -65
  90. package/src/index.ts +0 -104
  91. package/src/internal.ts +0 -6
  92. package/src/middleware/auth-apikey.test.ts +0 -363
  93. package/src/middleware/auth-apikey.ts +0 -47
  94. package/src/middleware/auth-bearer.test.ts +0 -450
  95. package/src/middleware/auth-bearer.ts +0 -72
  96. package/src/middleware/auth-cookie.test.ts +0 -528
  97. package/src/middleware/auth-cookie.ts +0 -80
  98. package/src/middleware/cors.test.ts +0 -424
  99. package/src/middleware/cors.ts +0 -104
  100. package/src/middleware/index.ts +0 -5
  101. package/src/middleware/remote-auth.test.ts +0 -488
  102. package/src/middleware/remote-auth.ts +0 -68
  103. package/src/middleware/timeout.ts +0 -15
  104. package/src/middleware-runner.test.ts +0 -418
  105. package/src/middleware-runner.ts +0 -234
  106. package/src/permissions.test.ts +0 -434
  107. package/src/permissions.ts +0 -319
  108. package/src/pikku-request.ts +0 -23
  109. package/src/pikku-response.ts +0 -5
  110. package/src/pikku-state.test.ts +0 -224
  111. package/src/pikku-state.ts +0 -214
  112. package/src/run-tests-script.test.ts +0 -49
  113. package/src/schema.test.ts +0 -249
  114. package/src/schema.ts +0 -151
  115. package/src/services/ai-agent-runner-service.ts +0 -41
  116. package/src/services/ai-run-state-service.ts +0 -20
  117. package/src/services/ai-storage-service.ts +0 -39
  118. package/src/services/content-service.ts +0 -76
  119. package/src/services/deployment-service.ts +0 -22
  120. package/src/services/gateway-service.ts +0 -20
  121. package/src/services/gopass-secrets.ts +0 -98
  122. package/src/services/in-memory-ai-run-state-service.ts +0 -73
  123. package/src/services/in-memory-trigger-service.ts +0 -64
  124. package/src/services/in-memory-workflow-service.test.ts +0 -351
  125. package/src/services/in-memory-workflow-service.ts +0 -395
  126. package/src/services/index.ts +0 -56
  127. package/src/services/jwt-service.ts +0 -30
  128. package/src/services/local-content.ts +0 -120
  129. package/src/services/local-gateway-service.ts +0 -62
  130. package/src/services/local-secrets.test.ts +0 -80
  131. package/src/services/local-secrets.ts +0 -94
  132. package/src/services/local-variables.test.ts +0 -61
  133. package/src/services/local-variables.ts +0 -39
  134. package/src/services/logger-console.test.ts +0 -118
  135. package/src/services/logger-console.ts +0 -98
  136. package/src/services/logger.ts +0 -57
  137. package/src/services/scheduler-service.ts +0 -86
  138. package/src/services/schema-service.ts +0 -33
  139. package/src/services/scoped-secret-service.test.ts +0 -74
  140. package/src/services/scoped-secret-service.ts +0 -41
  141. package/src/services/secret-service.ts +0 -38
  142. package/src/services/trigger-service.ts +0 -17
  143. package/src/services/typed-secret-service.test.ts +0 -93
  144. package/src/services/typed-secret-service.ts +0 -70
  145. package/src/services/typed-variables-service.test.ts +0 -73
  146. package/src/services/typed-variables-service.ts +0 -81
  147. package/src/services/user-session-service.test.ts +0 -113
  148. package/src/services/user-session-service.ts +0 -86
  149. package/src/services/variables-service.ts +0 -11
  150. package/src/services/workflow-service.ts +0 -84
  151. package/src/time-utils.test.ts +0 -56
  152. package/src/time-utils.ts +0 -107
  153. package/src/types/core.types.ts +0 -470
  154. package/src/types/state.types.ts +0 -186
  155. package/src/utils.test.ts +0 -350
  156. package/src/utils.ts +0 -129
  157. package/src/version.test.ts +0 -80
  158. package/src/version.ts +0 -25
  159. package/src/wirings/ai-agent/ai-agent-assistant-ui.test.ts +0 -363
  160. package/src/wirings/ai-agent/ai-agent-assistant-ui.ts +0 -238
  161. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +0 -152
  162. package/src/wirings/ai-agent/ai-agent-helpers.ts +0 -76
  163. package/src/wirings/ai-agent/ai-agent-memory.ts +0 -309
  164. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +0 -115
  165. package/src/wirings/ai-agent/ai-agent-model-config.ts +0 -43
  166. package/src/wirings/ai-agent/ai-agent-prepare.ts +0 -522
  167. package/src/wirings/ai-agent/ai-agent-registry.test.ts +0 -37
  168. package/src/wirings/ai-agent/ai-agent-registry.ts +0 -82
  169. package/src/wirings/ai-agent/ai-agent-runner.test.ts +0 -317
  170. package/src/wirings/ai-agent/ai-agent-runner.ts +0 -251
  171. package/src/wirings/ai-agent/ai-agent-stream.test.ts +0 -652
  172. package/src/wirings/ai-agent/ai-agent-stream.ts +0 -1060
  173. package/src/wirings/ai-agent/ai-agent.types.ts +0 -360
  174. package/src/wirings/ai-agent/index.ts +0 -41
  175. package/src/wirings/channel/channel-common.ts +0 -90
  176. package/src/wirings/channel/channel-handler.ts +0 -241
  177. package/src/wirings/channel/channel-middleware-runner.ts +0 -120
  178. package/src/wirings/channel/channel-runner.ts +0 -166
  179. package/src/wirings/channel/channel-store.ts +0 -29
  180. package/src/wirings/channel/channel.types.ts +0 -178
  181. package/src/wirings/channel/define-channel-routes.ts +0 -25
  182. package/src/wirings/channel/eventhub-service.ts +0 -34
  183. package/src/wirings/channel/eventhub-store.ts +0 -13
  184. package/src/wirings/channel/index.ts +0 -24
  185. package/src/wirings/channel/local/index.ts +0 -3
  186. package/src/wirings/channel/local/local-channel-handler.ts +0 -79
  187. package/src/wirings/channel/local/local-channel-runner.test.ts +0 -215
  188. package/src/wirings/channel/local/local-channel-runner.ts +0 -200
  189. package/src/wirings/channel/local/local-eventhub-service.test.ts +0 -95
  190. package/src/wirings/channel/local/local-eventhub-service.ts +0 -101
  191. package/src/wirings/channel/log-channels.ts +0 -20
  192. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +0 -54
  193. package/src/wirings/channel/pikku-abstract-channel-handler.ts +0 -45
  194. package/src/wirings/channel/serverless/index.ts +0 -5
  195. package/src/wirings/channel/serverless/serverless-channel-runner.ts +0 -286
  196. package/src/wirings/cli/channel/cli-channel-runner.ts +0 -136
  197. package/src/wirings/cli/channel/index.ts +0 -1
  198. package/src/wirings/cli/cli-runner.test.ts +0 -403
  199. package/src/wirings/cli/cli-runner.ts +0 -519
  200. package/src/wirings/cli/cli.types.ts +0 -357
  201. package/src/wirings/cli/command-parser.test.ts +0 -445
  202. package/src/wirings/cli/command-parser.ts +0 -504
  203. package/src/wirings/cli/define-cli-commands.ts +0 -24
  204. package/src/wirings/cli/index.ts +0 -19
  205. package/src/wirings/gateway/gateway-runner.test.ts +0 -474
  206. package/src/wirings/gateway/gateway-runner.ts +0 -411
  207. package/src/wirings/gateway/gateway.types.ts +0 -149
  208. package/src/wirings/gateway/index.ts +0 -13
  209. package/src/wirings/http/http-routes.test.ts +0 -322
  210. package/src/wirings/http/http-routes.ts +0 -198
  211. package/src/wirings/http/http-runner.test.ts +0 -144
  212. package/src/wirings/http/http-runner.ts +0 -563
  213. package/src/wirings/http/http.types.ts +0 -378
  214. package/src/wirings/http/index.ts +0 -25
  215. package/src/wirings/http/log-http-routes.ts +0 -22
  216. package/src/wirings/http/pikku-fetch-http-request.test.ts +0 -237
  217. package/src/wirings/http/pikku-fetch-http-request.ts +0 -166
  218. package/src/wirings/http/pikku-fetch-http-response.test.ts +0 -82
  219. package/src/wirings/http/pikku-fetch-http-response.ts +0 -147
  220. package/src/wirings/http/routers/http-router.ts +0 -13
  221. package/src/wirings/http/routers/path-to-regex.test.ts +0 -319
  222. package/src/wirings/http/routers/path-to-regex.ts +0 -126
  223. package/src/wirings/mcp/index.ts +0 -27
  224. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +0 -389
  225. package/src/wirings/mcp/mcp-endpoint-registry.ts +0 -159
  226. package/src/wirings/mcp/mcp-runner.ts +0 -305
  227. package/src/wirings/mcp/mcp.types.ts +0 -216
  228. package/src/wirings/node/index.ts +0 -2
  229. package/src/wirings/node/node.types.ts +0 -23
  230. package/src/wirings/oauth2/index.ts +0 -3
  231. package/src/wirings/oauth2/oauth2-client.test.ts +0 -929
  232. package/src/wirings/oauth2/oauth2-client.ts +0 -335
  233. package/src/wirings/oauth2/oauth2.types.ts +0 -69
  234. package/src/wirings/oauth2/wire-oauth2-credential.ts +0 -23
  235. package/src/wirings/queue/index.ts +0 -31
  236. package/src/wirings/queue/queue-runner.test.ts +0 -710
  237. package/src/wirings/queue/queue-runner.ts +0 -192
  238. package/src/wirings/queue/queue.types.ts +0 -189
  239. package/src/wirings/queue/register-queue-helper.ts +0 -60
  240. package/src/wirings/queue/validate-worker-config.test.ts +0 -108
  241. package/src/wirings/queue/validate-worker-config.ts +0 -116
  242. package/src/wirings/rpc/index.ts +0 -4
  243. package/src/wirings/rpc/rpc-runner.ts +0 -439
  244. package/src/wirings/rpc/rpc-types.ts +0 -51
  245. package/src/wirings/rpc/wire-addon.ts +0 -20
  246. package/src/wirings/scheduler/index.ts +0 -11
  247. package/src/wirings/scheduler/log-schedulers.ts +0 -20
  248. package/src/wirings/scheduler/scheduler-runner.test.ts +0 -660
  249. package/src/wirings/scheduler/scheduler-runner.ts +0 -132
  250. package/src/wirings/scheduler/scheduler.types.ts +0 -53
  251. package/src/wirings/secret/index.ts +0 -9
  252. package/src/wirings/secret/secret.types.ts +0 -32
  253. package/src/wirings/secret/validate-secret-definitions.test.ts +0 -140
  254. package/src/wirings/secret/validate-secret-definitions.ts +0 -82
  255. package/src/wirings/trigger/index.ts +0 -10
  256. package/src/wirings/trigger/pikku-trigger-service.ts +0 -112
  257. package/src/wirings/trigger/trigger-runner.test.ts +0 -79
  258. package/src/wirings/trigger/trigger-runner.ts +0 -135
  259. package/src/wirings/trigger/trigger.types.ts +0 -178
  260. package/src/wirings/variable/index.ts +0 -8
  261. package/src/wirings/variable/validate-variable-definitions.test.ts +0 -91
  262. package/src/wirings/variable/validate-variable-definitions.ts +0 -69
  263. package/src/wirings/variable/variable.types.ts +0 -22
  264. package/src/wirings/workflow/dsl/index.ts +0 -31
  265. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +0 -320
  266. package/src/wirings/workflow/dsl/workflow-runner.ts +0 -28
  267. package/src/wirings/workflow/graph/graph-node.ts +0 -222
  268. package/src/wirings/workflow/graph/graph-runner.test.ts +0 -487
  269. package/src/wirings/workflow/graph/graph-runner.ts +0 -816
  270. package/src/wirings/workflow/graph/index.ts +0 -14
  271. package/src/wirings/workflow/graph/template.test.ts +0 -49
  272. package/src/wirings/workflow/graph/template.ts +0 -42
  273. package/src/wirings/workflow/graph/wire-workflow-graph.ts +0 -29
  274. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -104
  275. package/src/wirings/workflow/index.ts +0 -81
  276. package/src/wirings/workflow/pikku-workflow-service.test.ts +0 -200
  277. package/src/wirings/workflow/pikku-workflow-service.ts +0 -1165
  278. package/src/wirings/workflow/workflow-helpers.test.ts +0 -129
  279. package/src/wirings/workflow/workflow-helpers.ts +0 -79
  280. package/src/wirings/workflow/workflow.types.ts +0 -266
  281. package/tsconfig.json +0 -14
  282. package/tsconfig.tsbuildinfo +0 -1
@@ -1,519 +0,0 @@
1
- import { NotFoundError, PikkuMissingMetaError } from '../../errors/errors.js'
2
- import { addFunction, runPikkuFunc } from '../../function/function-runner.js'
3
- import { pikkuState } from '../../pikku-state.js'
4
- import type {
5
- CorePikkuMiddleware,
6
- CoreUserSession,
7
- } from '../../types/core.types.js'
8
- import type {
9
- CoreCLI,
10
- CLICommandMeta,
11
- CLIOption,
12
- CLIProgramState,
13
- CorePikkuCLIRender,
14
- CoreCLICommandConfig,
15
- CLIMeta,
16
- } from './cli.types.js'
17
- import type {
18
- CoreSingletonServices,
19
- CoreServices,
20
- CreateWireServices,
21
- PikkuWire,
22
- CreateConfig,
23
- CreateSingletonServices,
24
- } from '../../types/core.types.js'
25
- import type { PikkuChannel } from '../channel/channel.types.js'
26
- import {
27
- PikkuSessionService,
28
- createMiddlewareSessionWireProps,
29
- } from '../../services/user-session-service.js'
30
- import { LocalVariablesService } from '../../services/local-variables.js'
31
- import { generateCommandHelp, parseCLIArguments } from './command-parser.js'
32
-
33
- /**
34
- * CLI command execution error - thrown when CLI execution fails
35
- * Should be caught by the wrapper to call process.exit()
36
- */
37
- export class CLIError extends Error {
38
- constructor(
39
- message: string,
40
- public exitCode: number = 1
41
- ) {
42
- super(message)
43
- this.name = 'CLIError'
44
- }
45
- }
46
-
47
- /**
48
- * Default JSON renderer for CLI output
49
- */
50
- const defaultJSONRenderer: CorePikkuCLIRender<any> = (_services, data) => {
51
- console.log(JSON.stringify(data, null, 2))
52
- }
53
-
54
- /**
55
- * Registers a CLI command tree and all its functions
56
- */
57
- export const wireCLI = <
58
- Commands extends Record<string, CoreCLICommandConfig<any, any, any>>,
59
- GlobalOptions,
60
- PikkuMiddleware extends CorePikkuMiddleware,
61
- GlobalOutput,
62
- >(
63
- cli: CoreCLI<Commands, GlobalOptions, PikkuMiddleware, GlobalOutput>
64
- ) => {
65
- // Get the existing metadata that was generated during inspection
66
- const cliMeta = pikkuState(null, 'cli', 'meta') || {}
67
-
68
- if (!cliMeta.programs?.[cli.program]) {
69
- throw new PikkuMissingMetaError(
70
- `CLI metadata not found for program '${cli.program}'`
71
- )
72
- }
73
-
74
- // Get existing programs state and add this program
75
- const programs: Record<string, CLIProgramState> =
76
- pikkuState(null, 'cli', 'programs') || {}
77
- programs[cli.program] = {
78
- defaultRenderer: (cli.render ||
79
- defaultJSONRenderer) as CorePikkuCLIRender<any>,
80
- middleware: cli.middleware || [],
81
- renderers: {},
82
- tags: cli.tags,
83
- }
84
- pikkuState(null, 'cli', 'programs', programs)
85
-
86
- // Register all command functions recursively
87
- registerCLICommands(
88
- cli.commands as Record<string, any>,
89
- [],
90
- cli.options || {},
91
- cli.program
92
- )
93
- }
94
-
95
- /**
96
- * Unwraps a function from pikku wrappers (pikkuFunc, pikkuSessionlessFunc, etc.)
97
- * These wrappers return { func, middleware, ... } but we need the actual function
98
- */
99
- function unwrapFunc(command: any): {
100
- func: Function
101
- middleware?: any[]
102
- auth?: boolean
103
- permissions?: any
104
- tags?: string[]
105
- } {
106
- if (typeof command === 'function') {
107
- return { func: command }
108
- }
109
-
110
- // If command has a func property that's an object with func, unwrap it
111
- if (
112
- command.func &&
113
- typeof command.func === 'object' &&
114
- 'func' in command.func
115
- ) {
116
- return {
117
- func: command.func.func,
118
- middleware: command.func.middleware,
119
- auth: command.func.auth,
120
- permissions: command.func.permissions,
121
- tags: command.func.tags,
122
- }
123
- }
124
-
125
- // Otherwise return as-is
126
- return command
127
- }
128
-
129
- /**
130
- * Registers CLI commands and their functions recursively
131
- */
132
- function registerCLICommands(
133
- commands: Record<string, any>,
134
- path: string[] = [],
135
- inheritedOptions: Record<string, CLIOption> = {},
136
- program: string
137
- ) {
138
- // Get the CLI metadata to find actual function names
139
- const cliMeta = pikkuState(null, 'cli', 'meta').programs[program]
140
-
141
- for (const [name, command] of Object.entries(commands)) {
142
- const fullPath = [...path, name]
143
- const commandId = fullPath.join('.')
144
-
145
- // Navigate metadata to find the actual function name
146
- let currentMeta: CLICommandMeta | undefined = cliMeta?.commands[fullPath[0]]
147
- for (let i = 1; i < fullPath.length; i++) {
148
- currentMeta = currentMeta?.subcommands?.[fullPath[i]]
149
- }
150
- const funcName = currentMeta?.pikkuFuncId
151
-
152
- // Skip if no function name (could be a command group)
153
- if (!funcName) {
154
- // Recursively register subcommands if they exist
155
- if (typeof command === 'object' && command.subcommands) {
156
- const commandOptions = command.options || {}
157
- const mergedOptions = { ...inheritedOptions, ...commandOptions }
158
- registerCLICommands(
159
- command.subcommands,
160
- fullPath,
161
- mergedOptions,
162
- program
163
- )
164
- }
165
- continue
166
- }
167
-
168
- // Merge options (inherited + local)
169
- const commandOptions =
170
- typeof command === 'object' ? command.options || {} : {}
171
- const mergedOptions = { ...inheritedOptions, ...commandOptions }
172
-
173
- // Store the options and middleware in program state for use during execution
174
- const programs: Record<string, CLIProgramState> = pikkuState(
175
- null,
176
- 'cli',
177
- 'programs'
178
- )
179
- if (programs[program]) {
180
- if (!programs[program].commandOptions) {
181
- programs[program].commandOptions = {}
182
- }
183
- programs[program].commandOptions![commandId] = mergedOptions
184
-
185
- // Store command middleware from the wire config
186
- if (typeof command === 'object' && command.middleware) {
187
- if (!programs[program].commandMiddleware) {
188
- programs[program].commandMiddleware = {}
189
- }
190
- programs[program].commandMiddleware![commandId] = command.middleware
191
- }
192
- }
193
-
194
- addFunction(funcName, unwrapFunc(command))
195
-
196
- // Register renderer if provided
197
- if (typeof command === 'object' && command.render) {
198
- if (programs[program]) {
199
- programs[program].renderers[commandId] = command.render
200
- }
201
- }
202
-
203
- // Recursively register subcommands
204
- if (typeof command === 'object' && command.subcommands) {
205
- registerCLICommands(command.subcommands, fullPath, mergedOptions, program)
206
- }
207
- }
208
- }
209
-
210
- /**
211
- * Plucks only the data that the function expects based on its schema
212
- */
213
- function pluckCLIData(
214
- mergedData: Record<string, any>,
215
- funcName: string,
216
- availableOptions: Record<string, CLIOption>
217
- ): Record<string, any> {
218
- const funcMeta = pikkuState(null, 'function', 'meta')[funcName]
219
- const schemaName = funcMeta?.inputSchemaName
220
- const schema = schemaName
221
- ? pikkuState(null, 'misc', 'schemas').get(schemaName)
222
- : null
223
-
224
- if (schema && schema.properties) {
225
- // If we have a schema, only include fields that are in the schema
226
- const result: Record<string, any> = {}
227
- for (const key of Object.keys(schema.properties)) {
228
- if (key in mergedData) {
229
- result[key] = mergedData[key]
230
- } else if (availableOptions[key]?.default !== undefined) {
231
- // Apply default if not provided
232
- result[key] = availableOptions[key].default
233
- }
234
- }
235
- return result
236
- } else {
237
- // No schema, include all data
238
- return { ...mergedData }
239
- }
240
- }
241
-
242
- /**
243
- * Executes a CLI command for a specific program
244
- */
245
- export async function runCLICommand({
246
- program,
247
- commandPath,
248
- data,
249
- singletonServices,
250
- createWireServices,
251
- }: {
252
- program: string
253
- commandPath: string[]
254
- data: Record<string, any>
255
- singletonServices: CoreSingletonServices
256
- createWireServices?: CreateWireServices
257
- }): Promise<any> {
258
- // Get the command metadata to find the function name
259
- const cliMeta = pikkuState(null, 'cli', 'meta')
260
- const programMeta = cliMeta.programs?.[program]
261
- if (!programMeta) {
262
- throw new NotFoundError(`Program not found: ${program}`)
263
- }
264
-
265
- // Navigate command tree to find the function name
266
- let currentCommand = programMeta.commands[commandPath[0]]
267
- if (!currentCommand) {
268
- throw new NotFoundError(`Command not found: ${commandPath.join(' ')}`)
269
- }
270
-
271
- for (let i = 1; i < commandPath.length; i++) {
272
- if (
273
- !currentCommand.subcommands ||
274
- !currentCommand.subcommands[commandPath[i]]
275
- ) {
276
- throw new NotFoundError(`Command not found: ${commandPath.join(' ')}`)
277
- }
278
- currentCommand = currentCommand.subcommands[commandPath[i]]
279
- }
280
-
281
- const funcName = currentCommand.pikkuFuncId
282
-
283
- // Get program-specific data
284
- const programs: Record<string, CLIProgramState> =
285
- pikkuState(null, 'cli', 'programs') || {}
286
- const programData = programs[program]
287
-
288
- // Combine program middleware + command middleware from the hierarchy
289
- const allWireMiddleware: CorePikkuMiddleware[] = [
290
- ...(programData?.middleware || []),
291
- ]
292
-
293
- // Walk through the command path and collect middleware from the runtime config
294
- const commandParts: string[] = []
295
- for (const part of commandPath) {
296
- commandParts.push(part)
297
- const commandId = commandParts.join('.')
298
- const middleware = programData?.commandMiddleware?.[commandId]
299
- if (middleware) {
300
- allWireMiddleware.push(...middleware)
301
- }
302
- }
303
-
304
- // Get command ID and options
305
- const commandId = commandPath.join('.')
306
- const availableOptions = programData?.commandOptions?.[commandId] || {}
307
-
308
- // Pluck only the fields the function expects
309
- const pluckedData = () => pluckCLIData(data, funcName, availableOptions)
310
-
311
- // Get the renderer
312
- const renderer =
313
- programData?.renderers[commandId] || programData?.defaultRenderer
314
-
315
- // Create a CLI channel for progressive output
316
- const channel: PikkuChannel<unknown, unknown> = {
317
- channelId: `cli:${program}:${commandId}`,
318
- openingData: pluckedData,
319
- send: async (data: any) => {
320
- if (renderer) {
321
- await Promise.resolve(renderer(singletonServices, data, undefined))
322
- }
323
- },
324
- sendBinary: () => {
325
- throw new Error('Binary data is not supported on CLI channels')
326
- },
327
- close: () => {
328
- if (channel) {
329
- channel.state = 'closed'
330
- }
331
- },
332
- state: 'open',
333
- }
334
-
335
- const userSession = new PikkuSessionService<CoreUserSession>()
336
-
337
- const wire: PikkuWire = {
338
- cli: {
339
- program,
340
- command: commandPath,
341
- data: pluckedData,
342
- channel,
343
- },
344
- ...createMiddlewareSessionWireProps(userSession),
345
- }
346
-
347
- try {
348
- const result = await runPikkuFunc('cli', commandId, funcName, {
349
- singletonServices,
350
- createWireServices,
351
- data: pluckedData,
352
- auth: false,
353
- inheritedMiddleware: currentCommand.middleware,
354
- wireMiddleware: allWireMiddleware,
355
- inheritedPermissions: currentCommand.permissions,
356
- wirePermissions: undefined,
357
- tags: programData?.tags,
358
- wire,
359
- sessionService: userSession,
360
- })
361
-
362
- // Apply renderer one final time with the final output (if renderer exists)
363
- // Skip if result is undefined (void functions handle their own output)
364
- if (renderer && result !== undefined) {
365
- await Promise.resolve(
366
- renderer(
367
- singletonServices,
368
- result,
369
- userSession.get() as CoreUserSession | undefined
370
- )
371
- )
372
- }
373
-
374
- return result
375
- } finally {
376
- // Close the channel
377
- channel.close()
378
- }
379
- }
380
-
381
- /**
382
- * Factory function for CLI-specific renderers
383
- */
384
- export const pikkuCLIRender = <
385
- Data,
386
- Services extends CoreSingletonServices = CoreServices,
387
- Session extends CoreUserSession = CoreUserSession,
388
- >(
389
- renderer: (
390
- services: Services,
391
- data: Data,
392
- session?: Session
393
- ) => void | Promise<void>
394
- ): CorePikkuCLIRender<Data, Services, Session> => {
395
- return renderer
396
- }
397
-
398
- /**
399
- * Execute a CLI program with the given arguments
400
- * This is the main entry point for CLI programs
401
- *
402
- * @throws {CLIError} When CLI execution fails - should be caught by wrapper to call process.exit()
403
- */
404
- export async function executeCLI({
405
- programName,
406
- args,
407
- createConfig,
408
- createSingletonServices,
409
- createWireServices,
410
- }: {
411
- programName: string
412
- args?: string[]
413
- createConfig?: CreateConfig<any, any>
414
- createSingletonServices: CreateSingletonServices<any, any>
415
- createWireServices?: CreateWireServices<any, any, any>
416
- }): Promise<void> {
417
- if (!args) {
418
- throw new Error(
419
- 'CLI arguments are required, this is to satisfy release diffs'
420
- )
421
- }
422
-
423
- try {
424
- // Get CLI metadata from state
425
- const allCLIMeta = pikkuState(null, 'cli', 'meta') as unknown as
426
- | CLIMeta
427
- | undefined
428
- if (!allCLIMeta) {
429
- throw new Error(
430
- '[PKU342] CLI metadata not found. No CLI wirings were registered. See https://pikku.dev/docs/pikku-cli/errors/pku342 for more information.'
431
- )
432
- }
433
- const programMeta = allCLIMeta.programs[programName]
434
-
435
- if (!programMeta) {
436
- throw new CLIError(`CLI program "${programName}" not found`, 1)
437
- }
438
-
439
- // Parse arguments for this specific program
440
- const parsed = parseCLIArguments(args, programName, allCLIMeta)
441
-
442
- // Handle help (check after parsing to support subcommand help)
443
- // Show help if --help/-h is present, or if no args AND no default command
444
- const shouldShowHelp =
445
- args.includes('--help') ||
446
- args.includes('-h') ||
447
- (args.length === 0 && parsed.commandPath.length === 0)
448
-
449
- if (shouldShowHelp) {
450
- const helpText = generateCommandHelp(
451
- programName,
452
- allCLIMeta,
453
- parsed.commandPath
454
- )
455
- console.log(helpText)
456
- return
457
- }
458
-
459
- if (parsed.errors.length > 0) {
460
- // Check if any error is about an unknown command
461
- const hasUnknownCommand = parsed.errors.some(
462
- (error) =>
463
- error.startsWith('Unknown command:') ||
464
- error.startsWith('Command not found:')
465
- )
466
-
467
- if (hasUnknownCommand) {
468
- // Show help instead of error for unknown commands
469
- const helpText = generateCommandHelp(
470
- programName,
471
- allCLIMeta,
472
- parsed.commandPath
473
- )
474
- console.log(helpText)
475
- throw new CLIError('Unknown command', 1)
476
- } else {
477
- // Show errors for other types of errors
478
- console.error('Errors:')
479
- parsed.errors.forEach((error) => console.error(` ${error}`))
480
- throw new CLIError(parsed.errors.join('\n'), 1)
481
- }
482
- }
483
-
484
- // Merge positionals and options into single data object
485
- const data = { ...parsed.positionals, ...parsed.options }
486
-
487
- // Create config (pass data in case it needs to use any parsed options)
488
- const config = createConfig
489
- ? await createConfig(new LocalVariablesService(), data)
490
- : ({} as any)
491
-
492
- // Create services with config
493
- const singletonServices = await createSingletonServices(config)
494
-
495
- // Execute the command
496
- await runCLICommand({
497
- program: programName,
498
- commandPath: parsed.commandPath,
499
- data,
500
- singletonServices,
501
- createWireServices,
502
- })
503
- } catch (error: any) {
504
- // Re-throw CLIError as-is
505
- if (error instanceof CLIError) {
506
- throw error
507
- }
508
-
509
- // Wrap other errors in CLIError
510
- console.error('Error:', error)
511
-
512
- // Show stack trace in verbose mode
513
- if (args.includes('--verbose') || args.includes('-v')) {
514
- console.error('Stack trace:', error.stack)
515
- }
516
-
517
- throw new CLIError(error.message || String(error), 1)
518
- }
519
- }