@pikku/core 0.12.0 → 0.12.1

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 (262) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/errors/errors.d.ts +6 -0
  3. package/dist/errors/errors.js +10 -0
  4. package/dist/errors/index.d.ts +1 -0
  5. package/dist/errors/index.js +1 -0
  6. package/dist/function/function-runner.d.ts +3 -3
  7. package/dist/function/function-runner.js +66 -44
  8. package/dist/function/functions.types.d.ts +1 -0
  9. package/dist/handle-error.d.ts +2 -2
  10. package/dist/handle-error.js +2 -2
  11. package/dist/index.d.ts +5 -3
  12. package/dist/index.js +2 -1
  13. package/dist/internal.d.ts +3 -0
  14. package/dist/internal.js +2 -0
  15. package/dist/middleware/auth-bearer.d.ts +1 -1
  16. package/dist/middleware/auth-bearer.js +1 -1
  17. package/dist/middleware/auth-cookie.d.ts +2 -2
  18. package/dist/middleware/auth-cookie.js +1 -1
  19. package/dist/middleware/cors.d.ts +2 -2
  20. package/dist/middleware/cors.js +45 -37
  21. package/dist/middleware-runner.d.ts +1 -1
  22. package/dist/permissions.d.ts +2 -2
  23. package/dist/pikku-state.d.ts +9 -8
  24. package/dist/pikku-state.js +30 -17
  25. package/dist/schema.d.ts +4 -4
  26. package/dist/schema.js +9 -5
  27. package/dist/services/ai-agent-runner-service.d.ts +22 -3
  28. package/dist/services/ai-run-state-service.d.ts +1 -1
  29. package/dist/services/ai-storage-service.d.ts +1 -1
  30. package/dist/services/content-service.d.ts +6 -0
  31. package/dist/services/gopass-secrets.d.ts +1 -1
  32. package/dist/services/gopass-secrets.js +3 -0
  33. package/dist/services/in-memory-ai-run-state-service.d.ts +15 -0
  34. package/dist/services/in-memory-ai-run-state-service.js +44 -0
  35. package/dist/services/in-memory-trigger-service.d.ts +0 -1
  36. package/dist/services/in-memory-trigger-service.js +6 -8
  37. package/dist/services/index.d.ts +3 -2
  38. package/dist/services/index.js +1 -0
  39. package/dist/services/local-content.d.ts +2 -1
  40. package/dist/services/local-content.js +6 -1
  41. package/dist/services/local-secrets.d.ts +2 -2
  42. package/dist/services/local-variables.d.ts +1 -1
  43. package/dist/services/logger-console.d.ts +2 -1
  44. package/dist/services/scheduler-service.d.ts +0 -12
  45. package/dist/services/scheduler-service.js +0 -6
  46. package/dist/services/scoped-secret-service.d.ts +1 -1
  47. package/dist/services/trigger-service.d.ts +0 -7
  48. package/dist/services/user-session-service.d.ts +3 -3
  49. package/dist/services/workflow-service.d.ts +2 -3
  50. package/dist/types/core.types.d.ts +24 -18
  51. package/dist/types/state.types.d.ts +17 -15
  52. package/dist/utils.d.ts +5 -5
  53. package/dist/utils.js +12 -9
  54. package/dist/wirings/ai-agent/ai-agent-assistant-ui.d.ts +5 -0
  55. package/dist/wirings/ai-agent/ai-agent-assistant-ui.js +146 -0
  56. package/dist/wirings/ai-agent/ai-agent-helpers.d.ts +28 -0
  57. package/dist/wirings/ai-agent/ai-agent-helpers.js +40 -0
  58. package/dist/wirings/ai-agent/ai-agent-prepare.d.ts +4 -5
  59. package/dist/wirings/ai-agent/ai-agent-prepare.js +66 -30
  60. package/dist/wirings/ai-agent/ai-agent-registry.d.ts +1 -1
  61. package/dist/wirings/ai-agent/ai-agent-runner.js +107 -8
  62. package/dist/wirings/ai-agent/ai-agent-stream.d.ts +2 -1
  63. package/dist/wirings/ai-agent/ai-agent-stream.js +246 -87
  64. package/dist/wirings/ai-agent/ai-agent.types.d.ts +61 -2
  65. package/dist/wirings/ai-agent/index.d.ts +3 -1
  66. package/dist/wirings/ai-agent/index.js +2 -0
  67. package/dist/wirings/channel/channel-common.d.ts +2 -2
  68. package/dist/wirings/channel/channel-handler.d.ts +3 -3
  69. package/dist/wirings/channel/channel-handler.js +4 -4
  70. package/dist/wirings/channel/channel-runner.d.ts +5 -5
  71. package/dist/wirings/channel/channel-runner.js +3 -2
  72. package/dist/wirings/channel/channel-store.d.ts +1 -1
  73. package/dist/wirings/channel/channel.types.d.ts +4 -6
  74. package/dist/wirings/channel/local/local-channel-runner.d.ts +7 -2
  75. package/dist/wirings/channel/local/local-channel-runner.js +4 -3
  76. package/dist/wirings/channel/local/local-eventhub-service.d.ts +2 -2
  77. package/dist/wirings/channel/log-channels.d.ts +1 -1
  78. package/dist/wirings/channel/pikku-abstract-channel-handler.d.ts +1 -1
  79. package/dist/wirings/channel/serverless/serverless-channel-runner.d.ts +4 -4
  80. package/dist/wirings/channel/serverless/serverless-channel-runner.js +25 -19
  81. package/dist/wirings/cli/channel/cli-channel-runner.d.ts +1 -1
  82. package/dist/wirings/cli/cli-runner.d.ts +2 -2
  83. package/dist/wirings/cli/cli.types.d.ts +3 -3
  84. package/dist/wirings/cli/command-parser.d.ts +1 -1
  85. package/dist/wirings/http/http-runner.d.ts +9 -9
  86. package/dist/wirings/http/http-runner.js +33 -14
  87. package/dist/wirings/http/http.types.d.ts +2 -6
  88. package/dist/wirings/http/log-http-routes.d.ts +1 -1
  89. package/dist/wirings/http/pikku-fetch-http-request.d.ts +1 -1
  90. package/dist/wirings/http/pikku-fetch-http-response.d.ts +2 -2
  91. package/dist/wirings/http/pikku-fetch-http-response.js +6 -1
  92. package/dist/wirings/http/routers/http-router.d.ts +1 -1
  93. package/dist/wirings/http/routers/path-to-regex.d.ts +2 -2
  94. package/dist/wirings/mcp/mcp-endpoint-registry.d.ts +1 -1
  95. package/dist/wirings/mcp/mcp-runner.d.ts +0 -3
  96. package/dist/wirings/mcp/mcp-runner.js +4 -2
  97. package/dist/wirings/mcp/mcp.types.d.ts +2 -2
  98. package/dist/wirings/oauth2/oauth2-client.d.ts +3 -3
  99. package/dist/wirings/oauth2/wire-oauth2-credential.d.ts +1 -1
  100. package/dist/wirings/queue/index.d.ts +1 -1
  101. package/dist/wirings/queue/index.js +1 -1
  102. package/dist/wirings/queue/queue-runner.d.ts +1 -12
  103. package/dist/wirings/queue/queue-runner.js +4 -12
  104. package/dist/wirings/queue/queue.types.d.ts +3 -9
  105. package/dist/wirings/queue/register-queue-helper.d.ts +2 -2
  106. package/dist/wirings/queue/register-queue-helper.js +1 -1
  107. package/dist/wirings/queue/validate-worker-config.d.ts +1 -1
  108. package/dist/wirings/rpc/index.d.ts +2 -0
  109. package/dist/wirings/rpc/index.js +1 -0
  110. package/dist/wirings/rpc/rpc-runner.d.ts +36 -14
  111. package/dist/wirings/rpc/rpc-runner.js +56 -28
  112. package/dist/wirings/rpc/rpc-types.d.ts +14 -2
  113. package/dist/wirings/rpc/wire-addon.d.ts +10 -0
  114. package/dist/wirings/rpc/wire-addon.js +9 -0
  115. package/dist/wirings/scheduler/index.d.ts +1 -1
  116. package/dist/wirings/scheduler/index.js +1 -1
  117. package/dist/wirings/scheduler/log-schedulers.d.ts +1 -1
  118. package/dist/wirings/scheduler/scheduler-runner.d.ts +3 -10
  119. package/dist/wirings/scheduler/scheduler-runner.js +4 -25
  120. package/dist/wirings/scheduler/scheduler.types.d.ts +2 -2
  121. package/dist/wirings/trigger/pikku-trigger-service.d.ts +2 -6
  122. package/dist/wirings/trigger/pikku-trigger-service.js +11 -16
  123. package/dist/wirings/trigger/trigger-runner.d.ts +1 -5
  124. package/dist/wirings/trigger/trigger-runner.js +4 -3
  125. package/dist/wirings/workflow/pikku-workflow-service.d.ts +2 -6
  126. package/dist/wirings/workflow/pikku-workflow-service.js +20 -29
  127. package/dist/wirings/workflow/workflow.types.d.ts +2 -2
  128. package/package.json +2 -1
  129. package/src/crypto-utils.test.ts +116 -0
  130. package/src/errors/error.test.ts +143 -2
  131. package/src/errors/errors.ts +10 -0
  132. package/src/errors/index.ts +1 -0
  133. package/src/function/function-runner.test.ts +2 -2
  134. package/src/function/function-runner.ts +72 -49
  135. package/src/function/functions.types.ts +1 -0
  136. package/src/handle-error.test.ts +361 -0
  137. package/src/handle-error.ts +4 -4
  138. package/src/index.ts +3 -10
  139. package/src/internal.ts +6 -0
  140. package/src/middleware/auth-apikey.test.ts +1 -1
  141. package/src/middleware/auth-bearer.test.ts +1 -1
  142. package/src/middleware/auth-bearer.ts +2 -5
  143. package/src/middleware/auth-cookie.test.ts +1 -1
  144. package/src/middleware/auth-cookie.ts +3 -5
  145. package/src/middleware/cors.test.ts +424 -0
  146. package/src/middleware/cors.ts +14 -6
  147. package/src/middleware/remote-auth.test.ts +488 -0
  148. package/src/middleware-runner.test.ts +1 -1
  149. package/src/middleware-runner.ts +1 -1
  150. package/src/permissions.test.ts +2 -2
  151. package/src/permissions.ts +2 -2
  152. package/src/pikku-state.test.ts +224 -0
  153. package/src/pikku-state.ts +40 -28
  154. package/src/schema.test.ts +198 -6
  155. package/src/schema.ts +11 -7
  156. package/src/services/ai-agent-runner-service.ts +15 -3
  157. package/src/services/ai-run-state-service.ts +1 -1
  158. package/src/services/ai-storage-service.ts +1 -1
  159. package/src/services/content-service.ts +7 -0
  160. package/src/services/gopass-secrets.ts +4 -1
  161. package/src/services/in-memory-ai-run-state-service.ts +73 -0
  162. package/src/services/in-memory-trigger-service.ts +6 -10
  163. package/src/services/in-memory-workflow-service.test.ts +351 -0
  164. package/src/services/index.ts +2 -1
  165. package/src/services/local-content.ts +9 -3
  166. package/src/services/local-secrets.test.ts +80 -0
  167. package/src/services/local-secrets.ts +2 -2
  168. package/src/services/local-variables.test.ts +61 -0
  169. package/src/services/local-variables.ts +1 -1
  170. package/src/services/logger-console.test.ts +118 -0
  171. package/src/services/logger-console.ts +2 -1
  172. package/src/services/scheduler-service.ts +0 -18
  173. package/src/services/scoped-secret-service.test.ts +74 -0
  174. package/src/services/scoped-secret-service.ts +1 -1
  175. package/src/services/trigger-service.ts +0 -21
  176. package/src/services/typed-secret-service.test.ts +93 -0
  177. package/src/services/typed-variables-service.test.ts +73 -0
  178. package/src/services/user-session-service.test.ts +113 -0
  179. package/src/services/user-session-service.ts +3 -3
  180. package/src/services/workflow-service.ts +2 -12
  181. package/src/time-utils.test.ts +1 -1
  182. package/src/types/core.types.ts +25 -19
  183. package/src/types/state.types.ts +24 -15
  184. package/src/utils.test.ts +350 -0
  185. package/src/utils.ts +14 -13
  186. package/src/wirings/ai-agent/ai-agent-assistant-ui.test.ts +363 -0
  187. package/src/wirings/ai-agent/ai-agent-assistant-ui.ts +214 -0
  188. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +152 -0
  189. package/src/wirings/ai-agent/ai-agent-helpers.ts +76 -0
  190. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +115 -0
  191. package/src/wirings/ai-agent/ai-agent-prepare.ts +79 -45
  192. package/src/wirings/ai-agent/ai-agent-registry.ts +1 -1
  193. package/src/wirings/ai-agent/ai-agent-runner.test.ts +245 -3
  194. package/src/wirings/ai-agent/ai-agent-runner.ts +121 -7
  195. package/src/wirings/ai-agent/ai-agent-stream.test.ts +430 -24
  196. package/src/wirings/ai-agent/ai-agent-stream.ts +377 -102
  197. package/src/wirings/ai-agent/ai-agent.types.ts +57 -2
  198. package/src/wirings/ai-agent/index.ts +11 -0
  199. package/src/wirings/channel/channel-common.ts +2 -2
  200. package/src/wirings/channel/channel-handler.ts +13 -9
  201. package/src/wirings/channel/channel-runner.ts +6 -6
  202. package/src/wirings/channel/channel-store.ts +1 -1
  203. package/src/wirings/channel/channel.types.ts +4 -8
  204. package/src/wirings/channel/local/local-channel-runner.test.ts +19 -12
  205. package/src/wirings/channel/local/local-channel-runner.ts +18 -13
  206. package/src/wirings/channel/local/local-eventhub-service.test.ts +2 -2
  207. package/src/wirings/channel/local/local-eventhub-service.ts +2 -2
  208. package/src/wirings/channel/log-channels.ts +1 -1
  209. package/src/wirings/channel/pikku-abstract-channel-handler.ts +1 -1
  210. package/src/wirings/channel/serverless/serverless-channel-runner.ts +37 -32
  211. package/src/wirings/cli/channel/cli-channel-runner.ts +1 -1
  212. package/src/wirings/cli/cli-runner.test.ts +1 -1
  213. package/src/wirings/cli/cli-runner.ts +11 -4
  214. package/src/wirings/cli/cli.types.ts +3 -3
  215. package/src/wirings/cli/command-parser.test.ts +1 -1
  216. package/src/wirings/cli/command-parser.ts +1 -1
  217. package/src/wirings/http/http-routes.test.ts +1 -1
  218. package/src/wirings/http/http-runner.test.ts +9 -17
  219. package/src/wirings/http/http-runner.ts +43 -27
  220. package/src/wirings/http/http.types.ts +1 -14
  221. package/src/wirings/http/log-http-routes.ts +1 -1
  222. package/src/wirings/http/pikku-fetch-http-request.ts +1 -1
  223. package/src/wirings/http/pikku-fetch-http-response.ts +12 -5
  224. package/src/wirings/http/routers/http-router.ts +1 -1
  225. package/src/wirings/http/routers/path-to-regex.test.ts +1 -1
  226. package/src/wirings/http/routers/path-to-regex.ts +4 -3
  227. package/src/wirings/mcp/mcp-endpoint-registry.ts +5 -1
  228. package/src/wirings/mcp/mcp-runner.ts +9 -15
  229. package/src/wirings/mcp/mcp.types.ts +2 -2
  230. package/src/wirings/oauth2/oauth2-client.ts +3 -3
  231. package/src/wirings/oauth2/wire-oauth2-credential.ts +1 -1
  232. package/src/wirings/queue/index.ts +0 -1
  233. package/src/wirings/queue/queue-runner.test.ts +52 -25
  234. package/src/wirings/queue/queue-runner.ts +8 -30
  235. package/src/wirings/queue/queue.types.ts +3 -13
  236. package/src/wirings/queue/register-queue-helper.ts +3 -5
  237. package/src/wirings/queue/validate-worker-config.test.ts +108 -0
  238. package/src/wirings/queue/validate-worker-config.ts +4 -1
  239. package/src/wirings/rpc/index.ts +2 -0
  240. package/src/wirings/rpc/rpc-runner.ts +92 -49
  241. package/src/wirings/rpc/rpc-types.ts +17 -2
  242. package/src/wirings/rpc/wire-addon.ts +20 -0
  243. package/src/wirings/scheduler/index.ts +0 -1
  244. package/src/wirings/scheduler/log-schedulers.ts +1 -1
  245. package/src/wirings/scheduler/scheduler-runner.test.ts +49 -60
  246. package/src/wirings/scheduler/scheduler-runner.ts +9 -56
  247. package/src/wirings/scheduler/scheduler.types.ts +2 -2
  248. package/src/wirings/secret/validate-secret-definitions.test.ts +140 -0
  249. package/src/wirings/trigger/pikku-trigger-service.ts +17 -39
  250. package/src/wirings/trigger/trigger-runner.test.ts +79 -0
  251. package/src/wirings/trigger/trigger-runner.ts +8 -11
  252. package/src/wirings/variable/validate-variable-definitions.test.ts +91 -0
  253. package/src/wirings/workflow/graph/graph-runner.test.ts +14 -22
  254. package/src/wirings/workflow/graph/template.test.ts +49 -0
  255. package/src/wirings/workflow/pikku-workflow-service.test.ts +15 -27
  256. package/src/wirings/workflow/pikku-workflow-service.ts +29 -45
  257. package/src/wirings/workflow/workflow-helpers.test.ts +129 -0
  258. package/src/wirings/workflow/workflow.types.ts +2 -2
  259. package/tsconfig.tsbuildinfo +1 -1
  260. package/dist/wirings/workflow/workflow-utils.d.ts +0 -1
  261. package/dist/wirings/workflow/workflow-utils.js +0 -1
  262. package/src/wirings/workflow/workflow-utils.ts +0 -0
@@ -1,5 +1,5 @@
1
- import { CorePermissionGroup, CorePikkuPermission } from '../../function/functions.types.js';
2
- import { CorePikkuMiddleware, MiddlewareMetadata, PermissionMetadata } from '../../types/core.types.js';
1
+ import type { CorePermissionGroup, CorePikkuPermission } from '../../function/functions.types.js';
2
+ import type { CorePikkuMiddleware, MiddlewareMetadata, PermissionMetadata } from '../../types/core.types.js';
3
3
  import type { PikkuChannel } from '../channel/channel.types.js';
4
4
  import type { CorePikkuChannelMiddleware } from '../channel/channel.types.js';
5
5
  export interface AIThread {
@@ -60,6 +60,7 @@ export interface AIAgentToolDef {
60
60
  description: string;
61
61
  inputSchema: Record<string, unknown>;
62
62
  execute: (input: unknown) => Promise<unknown>;
63
+ needsApproval?: boolean;
63
64
  }
64
65
  export interface PikkuAIMiddlewareHooks<State extends Record<string, unknown> = Record<string, unknown>, Services = any> {
65
66
  modifyInput?: (services: Services, ctx: {
@@ -91,6 +92,50 @@ export interface PikkuAIMiddlewareHooks<State extends Record<string, unknown> =
91
92
  text: string;
92
93
  messages: AIMessage[];
93
94
  };
95
+ beforeToolCall?: (services: Services, ctx: {
96
+ toolName: string;
97
+ toolCallId: string;
98
+ args: Record<string, unknown>;
99
+ }) => Promise<{
100
+ args: Record<string, unknown>;
101
+ } | void> | {
102
+ args: Record<string, unknown>;
103
+ } | void;
104
+ afterToolCall?: (services: Services, ctx: {
105
+ toolName: string;
106
+ toolCallId: string;
107
+ args: Record<string, unknown>;
108
+ result: unknown;
109
+ durationMs: number;
110
+ }) => Promise<{
111
+ result: unknown;
112
+ } | void> | {
113
+ result: unknown;
114
+ } | void;
115
+ afterStep?: (services: Services, ctx: {
116
+ stepNumber: number;
117
+ text: string;
118
+ toolCalls: {
119
+ toolCallId: string;
120
+ toolName: string;
121
+ args: unknown;
122
+ }[];
123
+ toolResults: {
124
+ toolCallId: string;
125
+ toolName: string;
126
+ result: unknown;
127
+ }[];
128
+ usage: {
129
+ inputTokens: number;
130
+ outputTokens: number;
131
+ };
132
+ finishReason: string;
133
+ }) => Promise<void> | void;
134
+ onError?: (services: Services, ctx: {
135
+ error: Error;
136
+ stepNumber: number;
137
+ messages: AIMessage[];
138
+ }) => Promise<void> | void;
94
139
  }
95
140
  export type AIAgentMemoryConfig = {
96
141
  storage?: string;
@@ -115,12 +160,26 @@ export type CoreAIAgent<PikkuPermission = CorePikkuPermission<any, any>, PikkuMi
115
160
  input?: unknown;
116
161
  output?: unknown;
117
162
  tags?: string[];
163
+ protocol?: 'ui-message-stream';
164
+ prepareStep?: (ctx: {
165
+ stepNumber: number;
166
+ messages: AIMessage[];
167
+ tools: AIAgentToolDef[];
168
+ toolChoice: 'auto' | 'required' | 'none';
169
+ model: string;
170
+ stop: () => void;
171
+ }) => void | Promise<void>;
118
172
  middleware?: PikkuMiddleware[];
119
173
  channelMiddleware?: CorePikkuChannelMiddleware<any, any>[];
120
174
  aiMiddleware?: PikkuAIMiddlewareHooks<any, any>[];
121
175
  permissions?: CorePermissionGroup<PikkuPermission>;
122
176
  };
123
177
  export type AIStreamEvent = {
178
+ type: 'step-start';
179
+ stepNumber: number;
180
+ agent?: string;
181
+ session?: string;
182
+ } | {
124
183
  type: 'text-delta';
125
184
  text: string;
126
185
  agent?: string;
@@ -1,5 +1,7 @@
1
+ export { agent, agentStream, agentResume, agentApprove, } from './ai-agent-helpers.js';
1
2
  export { runAIAgent } from './ai-agent-runner.js';
2
3
  export { streamAIAgent, resumeAIAgent } from './ai-agent-stream.js';
4
+ export { createAssistantUIChannel, parseAssistantUIInput, } from './ai-agent-assistant-ui.js';
3
5
  export { type RunAIAgentParams, type StreamAIAgentOptions, ToolApprovalRequired, } from './ai-agent-prepare.js';
4
6
  export { addAIAgent, approveAIAgent, getAIAgents, getAIAgentsMeta, } from './ai-agent-registry.js';
5
- export type { AIAgentMeta, AIAgentMemoryConfig, AIAgentStep, AgentRunRow, AgentRunService, AgentRunState, AIMessage, AIStreamChannel, AIStreamEvent, AIThread, CoreAIAgent, PendingApproval, PikkuAIMiddlewareHooks, } from './ai-agent.types.js';
7
+ export type { AIAgentInput, AIAgentMeta, AIAgentMemoryConfig, AIAgentStep, AgentRunRow, AgentRunService, AgentRunState, AIMessage, AIStreamChannel, AIStreamEvent, AIThread, CoreAIAgent, PendingApproval, PikkuAIMiddlewareHooks, } from './ai-agent.types.js';
@@ -1,4 +1,6 @@
1
+ export { agent, agentStream, agentResume, agentApprove, } from './ai-agent-helpers.js';
1
2
  export { runAIAgent } from './ai-agent-runner.js';
2
3
  export { streamAIAgent, resumeAIAgent } from './ai-agent-stream.js';
4
+ export { createAssistantUIChannel, parseAssistantUIInput, } from './ai-agent-assistant-ui.js';
3
5
  export { ToolApprovalRequired, } from './ai-agent-prepare.js';
4
6
  export { addAIAgent, approveAIAgent, getAIAgents, getAIAgentsMeta, } from './ai-agent-registry.js';
@@ -1,5 +1,5 @@
1
- import { CoreSingletonServices, MiddlewareMetadata } from '../../types/core.types.js';
2
- import { CoreChannel, ChannelMessageMeta } from './channel.types.js';
1
+ import type { CoreSingletonServices, MiddlewareMetadata } from '../../types/core.types.js';
2
+ import type { CoreChannel, ChannelMessageMeta } from './channel.types.js';
3
3
  /**
4
4
  * Runs a channel lifecycle function (onConnect or onDisconnect) with proper middleware handling.
5
5
  *
@@ -1,4 +1,4 @@
1
- import { CoreServices, CoreUserSession } from '../../types/core.types.js';
2
- import { CoreChannel, PikkuChannelHandler } from './channel.types.js';
3
- import { SessionService } from '../../services/user-session-service.js';
1
+ import type { CoreServices, CoreUserSession } from '../../types/core.types.js';
2
+ import type { CoreChannel, PikkuChannelHandler } from './channel.types.js';
3
+ import type { SessionService } from '../../services/user-session-service.js';
4
4
  export declare const processMessageHandlers: (services: CoreServices, channelConfig: CoreChannel<any, any>, channelHandler: PikkuChannelHandler, userSession?: SessionService<CoreUserSession>) => (rawData: any) => Promise<unknown>;
@@ -1,6 +1,6 @@
1
1
  import { pikkuState } from '../../pikku-state.js';
2
2
  import { runPikkuFunc } from '../../function/function-runner.js';
3
- import { createMiddlewareSessionWireProps, } from '../../services/user-session-service.js';
3
+ import { createMiddlewareSessionWireProps } from '../../services/user-session-service.js';
4
4
  const getChannelMeta = (channelName) => {
5
5
  return pikkuState(null, 'channel', 'meta')[channelName];
6
6
  };
@@ -39,7 +39,7 @@ export const processMessageHandlers = (services, channelConfig, channelHandler,
39
39
  const logger = services.logger;
40
40
  const requiresSession = channelConfig.auth !== false;
41
41
  const processMessage = async (data, onMessage, routingProperty, routerValue) => {
42
- if (!validateAuth(requiresSession, channelHandler, onMessage)) {
42
+ if (!validateAuth(requiresSession, userSession?.get(), onMessage)) {
43
43
  const routeMessage = routingProperty
44
44
  ? `route '${routingProperty}:${routerValue}'`
45
45
  : 'the default message route';
@@ -100,7 +100,7 @@ export const processMessageHandlers = (services, channelConfig, channelHandler,
100
100
  try {
101
101
  messageData = JSON.parse(rawData);
102
102
  }
103
- catch (error) {
103
+ catch {
104
104
  // Most likely a json error.. ignore
105
105
  }
106
106
  if (messageData) {
@@ -130,7 +130,7 @@ export const processMessageHandlers = (services, channelConfig, channelHandler,
130
130
  }
131
131
  if (!processed) {
132
132
  logger.error(`No handler found for message in channel ${channelConfig.name} for ${JSON.stringify(rawData)}`);
133
- logger.error(`Channel ${JSON.stringify(channelConfig)}`);
133
+ logger.error(`Channel config name: ${channelConfig.name}`);
134
134
  }
135
135
  return result;
136
136
  };
@@ -1,13 +1,13 @@
1
- import { CorePikkuPermission } from '../../function/functions.types.js';
2
- import { SessionService } from '../../services/user-session-service.js';
3
- import { CorePikkuMiddleware } from '../../types/core.types.js';
4
- import { ChannelMeta, CoreChannel, RunChannelOptions, RunChannelParams } from './channel.types.js';
1
+ import type { CorePikkuPermission } from '../../function/functions.types.js';
2
+ import type { SessionService } from '../../services/user-session-service.js';
3
+ import type { CorePikkuMiddleware } from '../../types/core.types.js';
4
+ import type { ChannelMeta, CoreChannel, RunChannelOptions, RunChannelParams } from './channel.types.js';
5
5
  /**
6
6
  * Adds a channel and registers all functions referenced in it using the
7
7
  * function names already stored in the channel metadata
8
8
  */
9
9
  export declare const wireChannel: <In, Channel extends string, PikkuPermission extends CorePikkuPermission<In>, PikkuMiddleware extends CorePikkuMiddleware, ChannelFunction>(channel: CoreChannel<In, Channel, PikkuPermission, PikkuMiddleware, ChannelFunction>) => void;
10
- export declare const openChannel: ({ route, singletonServices, coerceDataFromSchema, request, }: Pick<CoreChannel<unknown, string>, "route"> & RunChannelParams<unknown> & {
10
+ export declare const openChannel: ({ route, coerceDataFromSchema, request, }: Pick<CoreChannel<unknown, string>, "route"> & RunChannelParams<unknown> & {
11
11
  userSession: SessionService<any>;
12
12
  } & RunChannelOptions) => Promise<{
13
13
  openingData: unknown;
@@ -1,6 +1,6 @@
1
1
  import { NotFoundError, PikkuMissingMetaError } from '../../errors/errors.js';
2
2
  import { addFunction } from '../../function/function-runner.js';
3
- import { pikkuState } from '../../pikku-state.js';
3
+ import { pikkuState, getSingletonServices } from '../../pikku-state.js';
4
4
  import { coerceTopLevelDataFromSchema, validateSchema } from '../../schema.js';
5
5
  import { httpRouter } from '../http/routers/http-router.js';
6
6
  /**
@@ -75,7 +75,8 @@ const getMatchingChannelConfig = (path) => {
75
75
  meta: channelMeta,
76
76
  };
77
77
  };
78
- export const openChannel = async ({ route, singletonServices, coerceDataFromSchema = true, request, }) => {
78
+ export const openChannel = async ({ route, coerceDataFromSchema = true, request, }) => {
79
+ const singletonServices = getSingletonServices();
79
80
  const matchingChannel = getMatchingChannelConfig(route);
80
81
  if (!matchingChannel) {
81
82
  singletonServices.logger.info(`Channel not found: ${route}`);
@@ -1,4 +1,4 @@
1
- import { CoreUserSession } from '../../types/core.types.js';
1
+ import type { CoreUserSession } from '../../types/core.types.js';
2
2
  export type Channel<ChannelType = unknown, OpeningData = unknown> = {
3
3
  channelId: string;
4
4
  channelName: string;
@@ -1,9 +1,9 @@
1
- import { PikkuError } from '../../errors/error-handler.js';
2
- import { HTTPFunctionMetaInputTypes, PikkuHTTPRequest, PikkuHTTPResponse } from '../http/http.types.js';
3
- import { CoreSingletonServices, CreateWireServices, CorePikkuMiddleware, MiddlewareMetadata, PermissionMetadata } from '../../types/core.types.js';
1
+ import type { PikkuError } from '../../errors/error-handler.js';
2
+ import type { HTTPFunctionMetaInputTypes, PikkuHTTPRequest, PikkuHTTPResponse } from '../http/http.types.js';
3
+ import type { CorePikkuMiddleware, MiddlewareMetadata, PermissionMetadata } from '../../types/core.types.js';
4
4
  export type CorePikkuChannelMiddleware<Services = any, Event = unknown> = (services: Services, event: Event, next: (event: Event | Event[] | null) => Promise<void> | void) => Promise<void> | void;
5
5
  export type CorePikkuChannelMiddlewareFactory<In = any, Services = any, Event = unknown> = (input: In) => CorePikkuChannelMiddleware<Services, Event>;
6
- import { CorePermissionGroup, CorePikkuFunction, CorePikkuFunctionConfig, CorePikkuFunctionSessionless, CorePikkuPermission } from '../../function/functions.types.js';
6
+ import type { CorePermissionGroup, CorePikkuFunction, CorePikkuFunctionConfig, CorePikkuFunctionSessionless, CorePikkuPermission } from '../../function/functions.types.js';
7
7
  export type RunChannelOptions = Partial<{
8
8
  skipUserSession: boolean;
9
9
  respondWith404: boolean;
@@ -13,10 +13,8 @@ export type RunChannelOptions = Partial<{
13
13
  }>;
14
14
  export type RunChannelParams<ChannelData> = {
15
15
  channelId: string;
16
- singletonServices: CoreSingletonServices;
17
16
  request?: PikkuHTTPRequest<ChannelData>;
18
17
  response?: PikkuHTTPResponse;
19
- createWireServices?: CreateWireServices;
20
18
  };
21
19
  export interface ChannelMessageMeta {
22
20
  pikkuFuncId: string;
@@ -1,3 +1,8 @@
1
- import { CoreChannel, RunChannelOptions, RunChannelParams } from '../channel.types.js';
1
+ import type { CoreChannel, RunChannelOptions } from '../channel.types.js';
2
2
  import { PikkuLocalChannelHandler } from './local-channel-handler.js';
3
- export declare const runLocalChannel: ({ singletonServices, channelId, request, response, route, createWireServices, skipUserSession, respondWith404, coerceDataFromSchema, logWarningsForStatusCodes, bubbleErrors, }: Partial<Pick<CoreChannel<unknown, any>, "route">> & RunChannelOptions & RunChannelParams<unknown>) => Promise<PikkuLocalChannelHandler | void>;
3
+ import type { PikkuHTTPRequest, PikkuHTTPResponse } from '../../http/http.types.js';
4
+ export declare const runLocalChannel: ({ channelId, request, response, route, skipUserSession, respondWith404, coerceDataFromSchema, logWarningsForStatusCodes, bubbleErrors, }: Partial<Pick<CoreChannel<unknown, any>, "route">> & RunChannelOptions & {
5
+ channelId: string;
6
+ request?: PikkuHTTPRequest;
7
+ response?: PikkuHTTPResponse;
8
+ }) => Promise<PikkuLocalChannelHandler | void>;
@@ -6,7 +6,10 @@ import { PikkuLocalChannelHandler } from './local-channel-handler.js';
6
6
  import { handleHTTPError } from '../../../handle-error.js';
7
7
  import { PikkuSessionService, createMiddlewareSessionWireProps, } from '../../../services/user-session-service.js';
8
8
  import { runChannelLifecycleWithMiddleware } from '../channel-common.js';
9
- export const runLocalChannel = async ({ singletonServices, channelId, request, response, route, createWireServices, skipUserSession = false, respondWith404 = true, coerceDataFromSchema = true, logWarningsForStatusCodes = [], bubbleErrors = false, }) => {
9
+ import { getSingletonServices, getCreateWireServices, } from '../../../pikku-state.js';
10
+ export const runLocalChannel = async ({ channelId, request, response, route, skipUserSession = false, respondWith404 = true, coerceDataFromSchema = true, logWarningsForStatusCodes = [], bubbleErrors = false, }) => {
11
+ const singletonServices = getSingletonServices();
12
+ const createWireServices = getCreateWireServices();
10
13
  let wireServices;
11
14
  let closedWireServices = false;
12
15
  let channelHandler;
@@ -21,12 +24,10 @@ export const runLocalChannel = async ({ singletonServices, channelId, request, r
21
24
  ;
22
25
  ({ openingData, channelConfig, meta } = await openChannel({
23
26
  channelId,
24
- createWireServices,
25
27
  respondWith404,
26
28
  request,
27
29
  response,
28
30
  route,
29
- singletonServices,
30
31
  skipUserSession,
31
32
  coerceDataFromSchema,
32
33
  userSession,
@@ -1,5 +1,5 @@
1
- import { PikkuChannelHandler } from '../channel.types.js';
2
- import { EventHubService } from '../eventhub-service.js';
1
+ import type { PikkuChannelHandler } from '../channel.types.js';
2
+ import type { EventHubService } from '../eventhub-service.js';
3
3
  /**
4
4
  * Implementation of the SubscriptionService interface.
5
5
  * Manages subscriptions and publishes messages to subscribers.
@@ -1,4 +1,4 @@
1
- import { Logger } from '../../services/index.js';
1
+ import type { Logger } from '../../services/index.js';
2
2
  /**
3
3
  * Logs all the loaded channels.
4
4
  * @param logger - A logger for logging information.
@@ -1,4 +1,4 @@
1
- import { PikkuChannel, PikkuChannelHandler } from './channel.types.js';
1
+ import type { PikkuChannel, PikkuChannelHandler } from './channel.types.js';
2
2
  export declare abstract class PikkuAbstractChannelHandler<OpeningData = unknown, Out = unknown> implements PikkuChannelHandler<OpeningData, Out> {
3
3
  channelId: string;
4
4
  channelName: string;
@@ -1,10 +1,10 @@
1
1
  import type { CoreChannel, RunChannelOptions, RunChannelParams, PikkuChannelHandlerFactory } from '../channel.types.js';
2
- import { ChannelStore } from '../channel-store.js';
2
+ import type { ChannelStore } from '../channel-store.js';
3
3
  export interface RunServerlessChannelParams<ChannelData> extends RunChannelParams<ChannelData> {
4
4
  channelStore: ChannelStore;
5
5
  channelHandlerFactory: PikkuChannelHandlerFactory;
6
6
  channelObject?: unknown;
7
7
  }
8
- export declare const runChannelConnect: ({ singletonServices, channelId, channelObject, request, response, route, createWireServices, channelStore, channelHandlerFactory, coerceDataFromSchema, logWarningsForStatusCodes, respondWith404, bubbleErrors, }: Pick<CoreChannel<unknown, any>, "route"> & RunChannelOptions & RunServerlessChannelParams<unknown>) => Promise<void>;
9
- export declare const runChannelDisconnect: ({ singletonServices, ...params }: RunServerlessChannelParams<unknown>) => Promise<void>;
10
- export declare const runChannelMessage: ({ singletonServices, ...params }: RunServerlessChannelParams<unknown>, data: unknown) => Promise<unknown>;
8
+ export declare const runChannelConnect: ({ channelId, channelObject, request, response, route, channelStore, channelHandlerFactory, coerceDataFromSchema, logWarningsForStatusCodes, respondWith404, bubbleErrors, }: Pick<CoreChannel<unknown, any>, "route"> & RunChannelOptions & RunServerlessChannelParams<unknown>) => Promise<void>;
9
+ export declare const runChannelDisconnect: ({ channelId, channelStore, channelHandlerFactory, }: RunServerlessChannelParams<unknown>) => Promise<void>;
10
+ export declare const runChannelMessage: ({ channelId, channelStore, channelHandlerFactory, }: RunServerlessChannelParams<unknown>, data: unknown) => Promise<unknown>;
@@ -4,7 +4,7 @@ import { openChannel } from '../channel-runner.js';
4
4
  import { createHTTPWire } from '../../http/http-runner.js';
5
5
  import { handleHTTPError } from '../../../handle-error.js';
6
6
  import { PikkuSessionService, createMiddlewareSessionWireProps, } from '../../../services/user-session-service.js';
7
- import { pikkuState } from '../../../pikku-state.js';
7
+ import { getSingletonServices, getCreateWireServices, pikkuState, } from '../../../pikku-state.js';
8
8
  import { PikkuFetchHTTPRequest } from '../../http/pikku-fetch-http-request.js';
9
9
  import { runChannelLifecycleWithMiddleware } from '../channel-common.js';
10
10
  const getVariablesForChannel = ({ channelId, channelName, channelHandlerFactory, openingData, }) => {
@@ -26,7 +26,9 @@ const getVariablesForChannel = ({ channelId, channelName, channelHandlerFactory,
26
26
  meta,
27
27
  };
28
28
  };
29
- export const runChannelConnect = async ({ singletonServices, channelId, channelObject, request, response, route, createWireServices, channelStore, channelHandlerFactory, coerceDataFromSchema = true, logWarningsForStatusCodes = [], respondWith404 = true, bubbleErrors = false, }) => {
29
+ export const runChannelConnect = async ({ channelId, channelObject, request, response, route, channelStore, channelHandlerFactory, coerceDataFromSchema = true, logWarningsForStatusCodes = [], respondWith404 = true, bubbleErrors = false, }) => {
30
+ const singletonServices = getSingletonServices();
31
+ const createWireServices = getCreateWireServices();
30
32
  let wireServices;
31
33
  let http;
32
34
  if (request instanceof Request) {
@@ -35,10 +37,8 @@ export const runChannelConnect = async ({ singletonServices, channelId, channelO
35
37
  const userSession = new PikkuSessionService(channelStore, channelId);
36
38
  const { channelConfig, openingData, meta } = await openChannel({
37
39
  channelId,
38
- createWireServices,
39
40
  request,
40
41
  route,
41
- singletonServices,
42
42
  coerceDataFromSchema,
43
43
  userSession,
44
44
  });
@@ -88,7 +88,9 @@ export const runChannelConnect = async ({ singletonServices, channelId, channelO
88
88
  }
89
89
  }
90
90
  };
91
- export const runChannelDisconnect = async ({ singletonServices, ...params }) => {
91
+ export const runChannelDisconnect = async ({ channelId, channelStore, channelHandlerFactory, }) => {
92
+ const singletonServices = getSingletonServices();
93
+ const createWireServices = getCreateWireServices();
92
94
  let wireServices;
93
95
  // Try to get channel from store. In serverless environments (especially with
94
96
  // serverless-offline or worker threads), disconnect can be called multiple times
@@ -96,26 +98,27 @@ export const runChannelDisconnect = async ({ singletonServices, ...params }) =>
96
98
  // there's nothing to disconnect, so we can return early.
97
99
  let channelData;
98
100
  try {
99
- channelData = await params.channelStore.getChannelAndSession(params.channelId);
101
+ channelData = await channelStore.getChannelAndSession(channelId);
100
102
  }
101
- catch (error) {
102
- singletonServices.logger.info(`Channel ${params.channelId} not found during disconnect - already cleaned up`);
103
+ catch {
104
+ singletonServices.logger.info(`Channel ${channelId} not found during disconnect - already cleaned up`);
103
105
  return;
104
106
  }
105
107
  const { openingData, channelName, session } = channelData;
106
108
  const { channel, channelConfig, meta } = getVariablesForChannel({
107
- ...params,
109
+ channelId,
110
+ channelHandlerFactory,
108
111
  openingData,
109
112
  channelName,
110
113
  });
111
- const userSession = new PikkuSessionService(params.channelStore, params.channelId);
114
+ const userSession = new PikkuSessionService(channelStore, channelId);
112
115
  userSession.setInitial(session);
113
116
  const wire = {
114
117
  channel,
115
118
  ...createMiddlewareSessionWireProps(userSession),
116
119
  };
117
- if (!wireServices && params.createWireServices) {
118
- wireServices = await params.createWireServices(singletonServices, wire);
120
+ if (createWireServices) {
121
+ wireServices = await createWireServices(singletonServices, wire);
119
122
  }
120
123
  const services = {
121
124
  ...singletonServices,
@@ -137,27 +140,30 @@ export const runChannelDisconnect = async ({ singletonServices, ...params }) =>
137
140
  singletonServices.logger.error(`Error handling onDisconnect: ${e.message || e}`);
138
141
  }
139
142
  }
140
- await params.channelStore.removeChannels([channel.channelId]);
143
+ await channelStore.removeChannels([channel.channelId]);
141
144
  if (wireServices) {
142
145
  await closeWireServices(singletonServices.logger, wireServices);
143
146
  }
144
147
  };
145
- export const runChannelMessage = async ({ singletonServices, ...params }, data) => {
148
+ export const runChannelMessage = async ({ channelId, channelStore, channelHandlerFactory, }, data) => {
149
+ const singletonServices = getSingletonServices();
150
+ const createWireServices = getCreateWireServices();
146
151
  let wireServices;
147
- const { openingData, channelName, session } = await params.channelStore.getChannelAndSession(params.channelId);
152
+ const { openingData, channelName, session } = await channelStore.getChannelAndSession(channelId);
148
153
  const { channel, channelHandler, channelConfig } = getVariablesForChannel({
149
- ...params,
154
+ channelId,
155
+ channelHandlerFactory,
150
156
  openingData,
151
157
  channelName,
152
158
  });
153
- const userSession = new PikkuSessionService(params.channelStore, params.channelId);
159
+ const userSession = new PikkuSessionService(channelStore, channelId);
154
160
  userSession.setInitial(session);
155
161
  const wire = {
156
162
  channel,
157
163
  ...createMiddlewareSessionWireProps(userSession),
158
164
  };
159
- if (params.createWireServices) {
160
- wireServices = await params.createWireServices(singletonServices, wire);
165
+ if (createWireServices) {
166
+ wireServices = await createWireServices(singletonServices, wire);
161
167
  }
162
168
  const services = {
163
169
  ...singletonServices,
@@ -1,4 +1,4 @@
1
- import { CorePikkuCLIRender } from '../cli.types.js';
1
+ import type { CorePikkuCLIRender } from '../cli.types.js';
2
2
  /**
3
3
  * Execute a CLI program via WebSocket channel
4
4
  * This is the main entry point for CLI-over-Channel clients
@@ -1,5 +1,5 @@
1
- import { CorePikkuMiddleware, CoreUserSession } from '../../types/core.types.js';
2
- import { CoreCLI, CorePikkuCLIRender, CoreCLICommandConfig } from './cli.types.js';
1
+ import type { CorePikkuMiddleware, CoreUserSession } from '../../types/core.types.js';
2
+ import type { CoreCLI, CorePikkuCLIRender, CoreCLICommandConfig } from './cli.types.js';
3
3
  import type { CoreSingletonServices, CoreServices, CreateWireServices, CreateConfig, CreateSingletonServices } from '../../types/core.types.js';
4
4
  /**
5
5
  * CLI command execution error - thrown when CLI execution fails
@@ -1,6 +1,6 @@
1
- import { CorePikkuMiddleware, CoreSingletonServices, CoreUserSession, CoreServices, MiddlewareMetadata, PermissionMetadata } from '../../types/core.types.js';
2
- import { CorePikkuFunctionConfig, CorePikkuPermission, CorePikkuFunction, CorePikkuFunctionSessionless } from '../../function/functions.types.js';
3
- import { PikkuChannel } from '../channel/channel.types.js';
1
+ import type { CorePikkuMiddleware, CoreSingletonServices, CoreUserSession, CoreServices, MiddlewareMetadata, PermissionMetadata } from '../../types/core.types.js';
2
+ import type { CorePikkuFunctionConfig, CorePikkuPermission, CorePikkuFunction, CorePikkuFunctionSessionless } from '../../function/functions.types.js';
3
+ import type { PikkuChannel } from '../channel/channel.types.js';
4
4
  /**
5
5
  * CLI option definition
6
6
  */
@@ -1,4 +1,4 @@
1
- import { CLIMeta } from './cli.types.js';
1
+ import type { CLIMeta } from './cli.types.js';
2
2
  /**
3
3
  * Result of parsing CLI arguments
4
4
  */
@@ -1,6 +1,6 @@
1
- import { CoreHTTPFunctionWiring, RunHTTPWiringOptions, RunHTTPWiringParams, PikkuHTTP, PikkuHTTPRequest, PikkuHTTPResponse } from './http.types.js';
2
- import { CorePikkuFunction, CorePikkuFunctionSessionless, CorePikkuPermission, CorePermissionGroup } from '../../function/functions.types.js';
3
- import { CorePikkuMiddleware, CorePikkuMiddlewareGroup } from '../../types/core.types.js';
1
+ import type { CoreHTTPFunctionWiring, RunHTTPWiringOptions, PikkuHTTP, PikkuHTTPRequest, PikkuHTTPResponse } from './http.types.js';
2
+ import type { CorePikkuFunction, CorePikkuFunctionSessionless, CorePikkuPermission, CorePermissionGroup } from '../../function/functions.types.js';
3
+ import type { CorePikkuMiddleware, CorePikkuMiddlewareGroup } from '../../types/core.types.js';
4
4
  import { PikkuFetchHTTPResponse } from './pikku-fetch-http-response.js';
5
5
  /**
6
6
  * Registers HTTP middleware for a specific route pattern.
@@ -101,10 +101,10 @@ export declare const createHTTPWire: (request: PikkuHTTPRequest | undefined, res
101
101
  * @template In Expected input data type.
102
102
  * @template Out Expected output data type.
103
103
  * @param {Request} request - The native Fetch API Request object.
104
- * @param {RunHTTPWiringOptions & RunHTTPWiringParams} params - Additional options including services and session management.
104
+ * @param {RunHTTPWiringOptions} params - Additional options including services and session management.
105
105
  * @returns {Promise<Response>} A promise that resolves to a Fetch API Response object.
106
106
  */
107
- export declare const fetch: <In, Out>(request: Request, params: RunHTTPWiringOptions & RunHTTPWiringParams) => Promise<Response>;
107
+ export declare const fetch: <In, Out>(request: Request, params?: RunHTTPWiringOptions) => Promise<Response>;
108
108
  /**
109
109
  * Executes an HTTP route using a Pikku-specific request wrapper.
110
110
  *
@@ -114,10 +114,10 @@ export declare const fetch: <In, Out>(request: Request, params: RunHTTPWiringOpt
114
114
  * @template In Expected input data type.
115
115
  * @template Out Expected output data type.
116
116
  * @param {Request | PikkuHTTPRequest} request - The request object.
117
- * @param {RunHTTPWiringOptions & RunHTTPWiringParams} params - Execution options including services and session configuration.
117
+ * @param {RunHTTPWiringOptions} params - Execution options including services and session configuration.
118
118
  * @returns {Promise<PikkuFetchHTTPResponse>} A promise that resolves to a PikkuFetchHTTPResponse object.
119
119
  */
120
- export declare const pikkuFetch: <In, Out>(request: Request | PikkuHTTPRequest, params: RunHTTPWiringOptions & RunHTTPWiringParams) => Promise<PikkuFetchHTTPResponse>;
120
+ export declare const pikkuFetch: <In, Out>(request: Request | PikkuHTTPRequest, params?: RunHTTPWiringOptions) => Promise<PikkuFetchHTTPResponse>;
121
121
  /**
122
122
  * Core function to process an HTTP request through route matching, validation,
123
123
  * middleware execution, error handling, and session service cleanup.
@@ -133,7 +133,7 @@ export declare const pikkuFetch: <In, Out>(request: Request | PikkuHTTPRequest,
133
133
  * @template Out Expected output data type.
134
134
  * @param {Request | PikkuHTTPRequest} request - The incoming HTTP request.
135
135
  * @param {PikkuHTTPResponse} response - The response object to be populated.
136
- * @param {RunHTTPWiringOptions & RunHTTPWiringParams} options - Options such as singleton services, session handling, and error configuration.
136
+ * @param {RunHTTPWiringOptions} options - Options such as singleton services, session handling, and error configuration.
137
137
  * @returns {Promise<Out | void>} The output from the route handler or void if an error occurred.
138
138
  */
139
- export declare const fetchData: <In, Out>(request: Request | PikkuHTTPRequest, response: PikkuHTTPResponse, { singletonServices, createWireServices, skipUserSession, respondWith404, logWarningsForStatusCodes, coerceDataFromSchema, bubbleErrors, generateRequestId, }: RunHTTPWiringOptions & RunHTTPWiringParams) => Promise<Out | void>;
139
+ export declare const fetchData: <In, Out>(request: Request | PikkuHTTPRequest, response: PikkuHTTPResponse, { skipUserSession, respondWith404, logWarningsForStatusCodes, coerceDataFromSchema, bubbleErrors, generateRequestId, }?: RunHTTPWiringOptions) => Promise<Out | void>;
@@ -1,6 +1,7 @@
1
1
  import { NotFoundError, PikkuMissingMetaError } from '../../errors/errors.js';
2
2
  import { closeWireServices, createWeakUID, isSerializable, } from '../../utils.js';
3
- import { PikkuSessionService, createMiddlewareSessionWireProps, } from '../../services/user-session-service.js';
3
+ import { getSingletonServices, getCreateWireServices, } from '../../pikku-state.js';
4
+ import { PikkuSessionService } from '../../services/user-session-service.js';
4
5
  import { handleHTTPError } from '../../handle-error.js';
5
6
  import { pikkuState } from '../../pikku-state.js';
6
7
  import { PikkuFetchHTTPResponse } from './pikku-fetch-http-response.js';
@@ -8,6 +9,7 @@ import { PikkuFetchHTTPRequest } from './pikku-fetch-http-request.js';
8
9
  import { addFunction, runPikkuFunc } from '../../function/function-runner.js';
9
10
  import { httpRouter } from './routers/http-router.js';
10
11
  import { validateSchema } from '../../schema.js';
12
+ import { runMiddleware } from '../../middleware-runner.js';
11
13
  /**
12
14
  * Extract headers from a PikkuHTTPRequest based on the schema keys
13
15
  */
@@ -248,7 +250,10 @@ const executeRoute = async (services, matchedRoute, http, options) => {
248
250
  const wire = {
249
251
  http,
250
252
  channel,
251
- ...createMiddlewareSessionWireProps(userSession),
253
+ session: userSession.get(),
254
+ setSession: (s) => userSession.setInitial(s),
255
+ getSession: () => userSession.get(),
256
+ hasSessionChanged: () => userSession.sessionChanged,
252
257
  };
253
258
  result = await runPikkuFunc('http', `${meta.method}:${meta.route}`, meta.pikkuFuncId, {
254
259
  singletonServices,
@@ -290,10 +295,10 @@ const executeRoute = async (services, matchedRoute, http, options) => {
290
295
  * @template In Expected input data type.
291
296
  * @template Out Expected output data type.
292
297
  * @param {Request} request - The native Fetch API Request object.
293
- * @param {RunHTTPWiringOptions & RunHTTPWiringParams} params - Additional options including services and session management.
298
+ * @param {RunHTTPWiringOptions} params - Additional options including services and session management.
294
299
  * @returns {Promise<Response>} A promise that resolves to a Fetch API Response object.
295
300
  */
296
- export const fetch = async (request, params) => {
301
+ export const fetch = async (request, params = {}) => {
297
302
  const pikkuResponse = new PikkuFetchHTTPResponse();
298
303
  await fetchData(request, pikkuResponse, params);
299
304
  return pikkuResponse.toResponse();
@@ -307,10 +312,10 @@ export const fetch = async (request, params) => {
307
312
  * @template In Expected input data type.
308
313
  * @template Out Expected output data type.
309
314
  * @param {Request | PikkuHTTPRequest} request - The request object.
310
- * @param {RunHTTPWiringOptions & RunHTTPWiringParams} params - Execution options including services and session configuration.
315
+ * @param {RunHTTPWiringOptions} params - Execution options including services and session configuration.
311
316
  * @returns {Promise<PikkuFetchHTTPResponse>} A promise that resolves to a PikkuFetchHTTPResponse object.
312
317
  */
313
- export const pikkuFetch = async (request, params) => {
318
+ export const pikkuFetch = async (request, params = {}) => {
314
319
  const pikkuResponse = new PikkuFetchHTTPResponse();
315
320
  await fetchData(request, pikkuResponse, params);
316
321
  return pikkuResponse;
@@ -330,24 +335,39 @@ export const pikkuFetch = async (request, params) => {
330
335
  * @template Out Expected output data type.
331
336
  * @param {Request | PikkuHTTPRequest} request - The incoming HTTP request.
332
337
  * @param {PikkuHTTPResponse} response - The response object to be populated.
333
- * @param {RunHTTPWiringOptions & RunHTTPWiringParams} options - Options such as singleton services, session handling, and error configuration.
338
+ * @param {RunHTTPWiringOptions} options - Options such as singleton services, session handling, and error configuration.
334
339
  * @returns {Promise<Out | void>} The output from the route handler or void if an error occurred.
335
340
  */
336
- export const fetchData = async (request, response, { singletonServices, createWireServices, skipUserSession = false, respondWith404 = true, logWarningsForStatusCodes = [], coerceDataFromSchema = true, bubbleErrors = false, generateRequestId, }) => {
337
- const requestId = request.getHeader?.('x-request-id') ||
338
- generateRequestId?.() ||
339
- createWeakUID();
341
+ export const fetchData = async (request, response, { skipUserSession = false, respondWith404 = true, logWarningsForStatusCodes = [], coerceDataFromSchema = true, bubbleErrors = false, generateRequestId, } = {}) => {
342
+ const singletonServices = getSingletonServices();
343
+ const createWireServices = getCreateWireServices();
340
344
  let wireServices;
341
345
  let result;
342
346
  // Combine the request and response into one wire object
343
- const http = createHTTPWire(request instanceof Request ? new PikkuFetchHTTPRequest(request) : request, response);
347
+ const pikkuRequest = request instanceof Request ? new PikkuFetchHTTPRequest(request) : request;
348
+ let requestId = null;
349
+ try {
350
+ requestId = pikkuRequest.header('x-request-id');
351
+ }
352
+ catch { }
353
+ requestId = requestId || generateRequestId?.() || createWeakUID();
354
+ const http = createHTTPWire(pikkuRequest, response);
344
355
  const apiType = http.request.method();
345
356
  const apiRoute = http.request.path();
346
357
  // Locate the matching route based on the HTTP method and path
347
358
  const matchedRoute = getMatchingRoute(apiType, apiRoute);
348
359
  try {
349
- // If no route matches, log the occurrence and throw a NotFoundError
350
360
  if (!matchedRoute) {
361
+ if (apiType.toLowerCase() === 'options') {
362
+ const httpGroups = pikkuState(null, 'middleware', 'httpGroup');
363
+ const globalMiddleware = httpGroups['*'];
364
+ const wire = { http: http };
365
+ if (globalMiddleware) {
366
+ await runMiddleware(singletonServices, wire, globalMiddleware);
367
+ }
368
+ response.status(204).json(undefined);
369
+ return;
370
+ }
351
371
  singletonServices.logger.info({
352
372
  message: 'Route not found',
353
373
  apiRoute,
@@ -366,7 +386,6 @@ export const fetchData = async (request, response, { singletonServices, createWi
366
386
  return result;
367
387
  }
368
388
  catch (e) {
369
- // Handle errors and, depending on configuration, bubble them up or respond with an error
370
389
  handleHTTPError(e, http, requestId, singletonServices.logger, logWarningsForStatusCodes, respondWith404, bubbleErrors);
371
390
  }
372
391
  finally {