@pikku/core 0.12.4 → 0.12.5

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 (229) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/dist/dev/hot-reload.d.ts +10 -0
  3. package/dist/dev/hot-reload.js +158 -0
  4. package/dist/middleware-runner.d.ts +1 -0
  5. package/dist/middleware-runner.js +5 -0
  6. package/dist/permissions.d.ts +1 -0
  7. package/dist/permissions.js +5 -0
  8. package/dist/services/in-memory-workflow-service.js +7 -11
  9. package/dist/wirings/ai-agent/ai-agent-prepare.js +16 -1
  10. package/dist/wirings/channel/channel-middleware-runner.d.ts +1 -0
  11. package/dist/wirings/channel/channel-middleware-runner.js +5 -0
  12. package/dist/wirings/workflow/pikku-workflow-service.js +7 -8
  13. package/package.json +3 -2
  14. package/src/crypto-utils.test.ts +214 -0
  15. package/src/crypto-utils.ts +213 -0
  16. package/src/dev/hot-reload.test.ts +484 -0
  17. package/src/dev/hot-reload.ts +212 -0
  18. package/src/errors/error-handler.ts +62 -0
  19. package/src/errors/error.test.ts +195 -0
  20. package/src/errors/errors.ts +374 -0
  21. package/src/errors/index.ts +2 -0
  22. package/src/factory-functions.test.ts +109 -0
  23. package/src/function/function-runner.test.ts +536 -0
  24. package/src/function/function-runner.ts +365 -0
  25. package/src/function/functions.types.ts +304 -0
  26. package/src/function/index.ts +5 -0
  27. package/src/handle-error.test.ts +424 -0
  28. package/src/handle-error.ts +69 -0
  29. package/src/index.ts +118 -0
  30. package/src/internal.ts +6 -0
  31. package/src/middleware/auth-apikey.test.ts +363 -0
  32. package/src/middleware/auth-apikey.ts +47 -0
  33. package/src/middleware/auth-bearer.test.ts +450 -0
  34. package/src/middleware/auth-bearer.ts +72 -0
  35. package/src/middleware/auth-cookie.test.ts +528 -0
  36. package/src/middleware/auth-cookie.ts +80 -0
  37. package/src/middleware/cors.test.ts +424 -0
  38. package/src/middleware/cors.ts +104 -0
  39. package/src/middleware/index.ts +5 -0
  40. package/src/middleware/remote-auth.test.ts +488 -0
  41. package/src/middleware/remote-auth.ts +68 -0
  42. package/src/middleware/timeout.ts +15 -0
  43. package/src/middleware-runner.test.ts +418 -0
  44. package/src/middleware-runner.ts +240 -0
  45. package/src/permissions.test.ts +434 -0
  46. package/src/permissions.ts +327 -0
  47. package/src/pikku-request.ts +23 -0
  48. package/src/pikku-response.ts +5 -0
  49. package/src/pikku-state.test.ts +224 -0
  50. package/src/pikku-state.ts +216 -0
  51. package/src/run-tests-script.test.ts +49 -0
  52. package/src/schema.test.ts +249 -0
  53. package/src/schema.ts +151 -0
  54. package/src/services/ai-agent-runner-service.ts +41 -0
  55. package/src/services/ai-run-state-service.ts +20 -0
  56. package/src/services/ai-storage-service.ts +39 -0
  57. package/src/services/content-service.ts +76 -0
  58. package/src/services/deployment-service.ts +22 -0
  59. package/src/services/gateway-service.ts +20 -0
  60. package/src/services/gopass-secrets.ts +98 -0
  61. package/src/services/in-memory-ai-run-state-service.ts +73 -0
  62. package/src/services/in-memory-trigger-service.ts +64 -0
  63. package/src/services/in-memory-workflow-service.test.ts +351 -0
  64. package/src/services/in-memory-workflow-service.ts +502 -0
  65. package/src/services/index.ts +56 -0
  66. package/src/services/jwt-service.ts +30 -0
  67. package/src/services/local-content.ts +120 -0
  68. package/src/services/local-gateway-service.ts +62 -0
  69. package/src/services/local-secrets.test.ts +80 -0
  70. package/src/services/local-secrets.ts +94 -0
  71. package/src/services/local-variables.test.ts +61 -0
  72. package/src/services/local-variables.ts +39 -0
  73. package/src/services/logger-console.test.ts +118 -0
  74. package/src/services/logger-console.ts +98 -0
  75. package/src/services/logger.ts +57 -0
  76. package/src/services/scheduler-service.ts +86 -0
  77. package/src/services/schema-service.ts +33 -0
  78. package/src/services/scoped-secret-service.test.ts +74 -0
  79. package/src/services/scoped-secret-service.ts +41 -0
  80. package/src/services/secret-service.ts +38 -0
  81. package/src/services/trigger-service.ts +17 -0
  82. package/src/services/typed-secret-service.test.ts +93 -0
  83. package/src/services/typed-secret-service.ts +70 -0
  84. package/src/services/typed-variables-service.test.ts +73 -0
  85. package/src/services/typed-variables-service.ts +81 -0
  86. package/src/services/user-session-service.test.ts +113 -0
  87. package/src/services/user-session-service.ts +86 -0
  88. package/src/services/variables-service.ts +11 -0
  89. package/src/services/workflow-service.ts +95 -0
  90. package/src/testing/index.ts +2 -0
  91. package/src/testing/service-tests.ts +873 -0
  92. package/src/time-utils.test.ts +56 -0
  93. package/src/time-utils.ts +107 -0
  94. package/src/types/core.types.ts +478 -0
  95. package/src/types/state.types.ts +188 -0
  96. package/src/utils/hash.test.ts +68 -0
  97. package/src/utils/hash.ts +26 -0
  98. package/src/utils.test.ts +350 -0
  99. package/src/utils.ts +129 -0
  100. package/src/version.test.ts +80 -0
  101. package/src/version.ts +25 -0
  102. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +469 -0
  103. package/src/wirings/ai-agent/ai-agent-helpers.test.ts +152 -0
  104. package/src/wirings/ai-agent/ai-agent-helpers.ts +76 -0
  105. package/src/wirings/ai-agent/ai-agent-memory.ts +310 -0
  106. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +115 -0
  107. package/src/wirings/ai-agent/ai-agent-model-config.ts +43 -0
  108. package/src/wirings/ai-agent/ai-agent-prepare.ts +659 -0
  109. package/src/wirings/ai-agent/ai-agent-registry.test.ts +37 -0
  110. package/src/wirings/ai-agent/ai-agent-registry.ts +82 -0
  111. package/src/wirings/ai-agent/ai-agent-runner.test.ts +319 -0
  112. package/src/wirings/ai-agent/ai-agent-runner.ts +773 -0
  113. package/src/wirings/ai-agent/ai-agent-stream.test.ts +859 -0
  114. package/src/wirings/ai-agent/ai-agent-stream.ts +1153 -0
  115. package/src/wirings/ai-agent/ai-agent.types.ts +382 -0
  116. package/src/wirings/ai-agent/index.ts +37 -0
  117. package/src/wirings/channel/channel-common.ts +90 -0
  118. package/src/wirings/channel/channel-handler.ts +250 -0
  119. package/src/wirings/channel/channel-middleware-runner.ts +126 -0
  120. package/src/wirings/channel/channel-runner.ts +166 -0
  121. package/src/wirings/channel/channel-store.ts +29 -0
  122. package/src/wirings/channel/channel.types.ts +172 -0
  123. package/src/wirings/channel/define-channel-routes.ts +25 -0
  124. package/src/wirings/channel/eventhub-service.ts +34 -0
  125. package/src/wirings/channel/eventhub-store.ts +13 -0
  126. package/src/wirings/channel/index.ts +24 -0
  127. package/src/wirings/channel/local/index.ts +3 -0
  128. package/src/wirings/channel/local/local-channel-handler.ts +81 -0
  129. package/src/wirings/channel/local/local-channel-runner.test.ts +215 -0
  130. package/src/wirings/channel/local/local-channel-runner.ts +210 -0
  131. package/src/wirings/channel/local/local-eventhub-service.test.ts +95 -0
  132. package/src/wirings/channel/local/local-eventhub-service.ts +101 -0
  133. package/src/wirings/channel/log-channels.ts +20 -0
  134. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +54 -0
  135. package/src/wirings/channel/pikku-abstract-channel-handler.ts +45 -0
  136. package/src/wirings/channel/serverless/index.ts +5 -0
  137. package/src/wirings/channel/serverless/serverless-channel-runner.ts +289 -0
  138. package/src/wirings/cli/channel/cli-channel-runner.ts +136 -0
  139. package/src/wirings/cli/channel/index.ts +1 -0
  140. package/src/wirings/cli/cli-runner.test.ts +403 -0
  141. package/src/wirings/cli/cli-runner.ts +529 -0
  142. package/src/wirings/cli/cli.types.ts +358 -0
  143. package/src/wirings/cli/command-parser.test.ts +445 -0
  144. package/src/wirings/cli/command-parser.ts +504 -0
  145. package/src/wirings/cli/define-cli-commands.ts +24 -0
  146. package/src/wirings/cli/index.ts +19 -0
  147. package/src/wirings/gateway/gateway-runner.test.ts +474 -0
  148. package/src/wirings/gateway/gateway-runner.ts +411 -0
  149. package/src/wirings/gateway/gateway.types.ts +149 -0
  150. package/src/wirings/gateway/index.ts +13 -0
  151. package/src/wirings/http/http-routes.test.ts +322 -0
  152. package/src/wirings/http/http-routes.ts +197 -0
  153. package/src/wirings/http/http-runner.test.ts +144 -0
  154. package/src/wirings/http/http-runner.ts +588 -0
  155. package/src/wirings/http/http.types.ts +369 -0
  156. package/src/wirings/http/index.ts +28 -0
  157. package/src/wirings/http/log-http-routes.ts +22 -0
  158. package/src/wirings/http/pikku-fetch-http-request.test.ts +237 -0
  159. package/src/wirings/http/pikku-fetch-http-request.ts +170 -0
  160. package/src/wirings/http/pikku-fetch-http-response.test.ts +82 -0
  161. package/src/wirings/http/pikku-fetch-http-response.ts +147 -0
  162. package/src/wirings/http/routers/http-router.ts +13 -0
  163. package/src/wirings/http/routers/path-to-regex.test.ts +319 -0
  164. package/src/wirings/http/routers/path-to-regex.ts +126 -0
  165. package/src/wirings/http/web-request.test.ts +236 -0
  166. package/src/wirings/http/web-request.ts +104 -0
  167. package/src/wirings/mcp/index.ts +27 -0
  168. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +389 -0
  169. package/src/wirings/mcp/mcp-endpoint-registry.ts +159 -0
  170. package/src/wirings/mcp/mcp-runner.ts +323 -0
  171. package/src/wirings/mcp/mcp.types.ts +216 -0
  172. package/src/wirings/node/index.ts +2 -0
  173. package/src/wirings/node/node.types.ts +23 -0
  174. package/src/wirings/oauth2/index.ts +3 -0
  175. package/src/wirings/oauth2/oauth2-client.test.ts +929 -0
  176. package/src/wirings/oauth2/oauth2-client.ts +335 -0
  177. package/src/wirings/oauth2/oauth2.types.ts +69 -0
  178. package/src/wirings/oauth2/wire-oauth2-credential.ts +23 -0
  179. package/src/wirings/queue/index.ts +31 -0
  180. package/src/wirings/queue/queue-runner.test.ts +710 -0
  181. package/src/wirings/queue/queue-runner.ts +192 -0
  182. package/src/wirings/queue/queue.types.ts +189 -0
  183. package/src/wirings/queue/register-queue-helper.ts +60 -0
  184. package/src/wirings/queue/validate-worker-config.test.ts +108 -0
  185. package/src/wirings/queue/validate-worker-config.ts +116 -0
  186. package/src/wirings/rpc/index.ts +4 -0
  187. package/src/wirings/rpc/rpc-runner.ts +460 -0
  188. package/src/wirings/rpc/rpc-types.ts +56 -0
  189. package/src/wirings/rpc/wire-addon.ts +21 -0
  190. package/src/wirings/scheduler/index.ts +11 -0
  191. package/src/wirings/scheduler/log-schedulers.ts +20 -0
  192. package/src/wirings/scheduler/scheduler-runner.test.ts +660 -0
  193. package/src/wirings/scheduler/scheduler-runner.ts +133 -0
  194. package/src/wirings/scheduler/scheduler.types.ts +53 -0
  195. package/src/wirings/secret/index.ts +9 -0
  196. package/src/wirings/secret/secret.types.ts +32 -0
  197. package/src/wirings/secret/validate-secret-definitions.test.ts +140 -0
  198. package/src/wirings/secret/validate-secret-definitions.ts +82 -0
  199. package/src/wirings/trigger/index.ts +10 -0
  200. package/src/wirings/trigger/pikku-trigger-service.ts +112 -0
  201. package/src/wirings/trigger/trigger-runner.test.ts +79 -0
  202. package/src/wirings/trigger/trigger-runner.ts +135 -0
  203. package/src/wirings/trigger/trigger.types.ts +178 -0
  204. package/src/wirings/variable/index.ts +8 -0
  205. package/src/wirings/variable/validate-variable-definitions.test.ts +91 -0
  206. package/src/wirings/variable/validate-variable-definitions.ts +69 -0
  207. package/src/wirings/variable/variable.types.ts +22 -0
  208. package/src/wirings/workflow/dsl/index.ts +31 -0
  209. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +320 -0
  210. package/src/wirings/workflow/dsl/workflow-runner.ts +28 -0
  211. package/src/wirings/workflow/graph/graph-node.ts +222 -0
  212. package/src/wirings/workflow/graph/graph-runner.test.ts +487 -0
  213. package/src/wirings/workflow/graph/graph-runner.ts +816 -0
  214. package/src/wirings/workflow/graph/graph-validation.test.ts +170 -0
  215. package/src/wirings/workflow/graph/graph-validation.ts +237 -0
  216. package/src/wirings/workflow/graph/index.ts +19 -0
  217. package/src/wirings/workflow/graph/template.test.ts +49 -0
  218. package/src/wirings/workflow/graph/template.ts +42 -0
  219. package/src/wirings/workflow/graph/wire-workflow-graph.ts +29 -0
  220. package/src/wirings/workflow/graph/workflow-graph.types.ts +104 -0
  221. package/src/wirings/workflow/index.ts +82 -0
  222. package/src/wirings/workflow/pikku-workflow-service.test.ts +200 -0
  223. package/src/wirings/workflow/pikku-workflow-service.ts +1179 -0
  224. package/src/wirings/workflow/workflow-helpers.test.ts +129 -0
  225. package/src/wirings/workflow/workflow-helpers.ts +79 -0
  226. package/src/wirings/workflow/workflow.types.ts +274 -0
  227. package/tsconfig.json +14 -0
  228. package/tsconfig.tsbuildinfo +1 -0
  229. package/lcov.info +0 -18891
@@ -0,0 +1,188 @@
1
+ import type { PikkuError, ErrorDetails } from '../errors/error-handler.js'
2
+ import type {
3
+ CorePikkuFunctionConfig,
4
+ CorePermissionGroup,
5
+ CorePikkuPermission,
6
+ } from '../function/functions.types.js'
7
+ import type { CorePikkuTriggerFunctionConfig } from '../wirings/trigger/trigger.types.js'
8
+ import type {
9
+ CoreChannel,
10
+ ChannelsMeta,
11
+ } from '../wirings/channel/channel.types.js'
12
+ import type { CLIMeta, CLIProgramState } from '../wirings/cli/cli.types.js'
13
+ import type {
14
+ HTTPMethod,
15
+ CoreHTTPFunctionWiring,
16
+ HTTPWiringsMeta,
17
+ } from '../wirings/http/http.types.js'
18
+ import type {
19
+ CoreMCPResource,
20
+ MCPResourceMeta,
21
+ MCPToolMeta,
22
+ CoreMCPPrompt,
23
+ MCPPromptMeta,
24
+ } from '../wirings/mcp/mcp.types.js'
25
+ import type {
26
+ CoreAIAgent,
27
+ AIAgentMeta,
28
+ } from '../wirings/ai-agent/ai-agent.types.js'
29
+ import type {
30
+ CoreGateway,
31
+ GatewaysMeta,
32
+ } from '../wirings/gateway/gateway.types.js'
33
+ import type {
34
+ CoreQueueWorker,
35
+ QueueWorkersMeta,
36
+ } from '../wirings/queue/queue.types.js'
37
+ import type {
38
+ CoreScheduledTask,
39
+ ScheduledTasksMeta,
40
+ } from '../wirings/scheduler/scheduler.types.js'
41
+ import type {
42
+ CoreWorkflow,
43
+ WorkflowsRuntimeMeta,
44
+ } from '../wirings/workflow/workflow.types.js'
45
+ import type {
46
+ CoreTrigger,
47
+ CoreTriggerSource,
48
+ TriggerMeta,
49
+ TriggerSourceMeta,
50
+ } from '../wirings/trigger/trigger.types.js'
51
+ import type {
52
+ FunctionsMeta,
53
+ CorePikkuMiddleware,
54
+ CorePikkuMiddlewareGroup,
55
+ CreateConfig,
56
+ CreateSingletonServices,
57
+ CreateWireServices,
58
+ CoreConfig,
59
+ CoreSingletonServices,
60
+ CoreServices,
61
+ CoreUserSession,
62
+ } from './core.types.js'
63
+ import type { CorePikkuChannelMiddleware } from '../wirings/channel/channel.types.js'
64
+
65
+ /**
66
+ * State structure for an individual package
67
+ */
68
+ export interface PikkuPackageState {
69
+ function: {
70
+ meta: FunctionsMeta
71
+ functions: Map<string, CorePikkuFunctionConfig<any, any>>
72
+ }
73
+ rpc: {
74
+ meta: Record<string, string>
75
+ files: Map<
76
+ string,
77
+ {
78
+ exportedName: string
79
+ path: string
80
+ }
81
+ >
82
+ }
83
+ /** Maps namespace aliases to package config (e.g., 'console' -> { package: '@pikku/console', ... }) */
84
+ addons: {
85
+ packages: Map<
86
+ string,
87
+ { package: string; rpcEndpoint?: string; auth?: boolean; tags?: string[] }
88
+ >
89
+ }
90
+ http: {
91
+ middleware: Map<string, CorePikkuMiddleware<any, any>[]>
92
+ permissions: Map<string, CorePermissionGroup | CorePikkuPermission[]>
93
+ routes: Map<HTTPMethod, Map<string, CoreHTTPFunctionWiring<any, any, any>>>
94
+ meta: HTTPWiringsMeta
95
+ }
96
+ channel: {
97
+ channels: Map<string, CoreChannel<any, any>>
98
+ meta: ChannelsMeta
99
+ }
100
+ scheduler: {
101
+ tasks: Map<string, CoreScheduledTask>
102
+ meta: ScheduledTasksMeta
103
+ }
104
+ queue: {
105
+ registrations: Map<string, CoreQueueWorker>
106
+ meta: QueueWorkersMeta
107
+ }
108
+ workflows: {
109
+ registrations: Map<string, CoreWorkflow>
110
+ meta: WorkflowsRuntimeMeta
111
+ }
112
+ trigger: {
113
+ functions: Map<string, CorePikkuTriggerFunctionConfig<any, any>>
114
+ triggers: Map<string, CoreTrigger>
115
+ triggerSources: Map<string, CoreTriggerSource>
116
+ meta: TriggerMeta
117
+ sourceMeta: TriggerSourceMeta
118
+ }
119
+ mcp: {
120
+ resources: Map<string, CoreMCPResource>
121
+ resourcesMeta: MCPResourceMeta
122
+ toolsMeta: MCPToolMeta
123
+ prompts: Map<string, CoreMCPPrompt>
124
+ promptsMeta: MCPPromptMeta
125
+ }
126
+ agent: {
127
+ agents: Map<string, CoreAIAgent>
128
+ agentsMeta: AIAgentMeta
129
+ }
130
+ gateway: {
131
+ gateways: Map<string, CoreGateway>
132
+ meta: GatewaysMeta
133
+ }
134
+ cli: {
135
+ meta: CLIMeta | Record<string, any> // Backward compatible with old published CLI format
136
+ programs: Record<string, CLIProgramState>
137
+ }
138
+ middleware: {
139
+ tagGroup: Record<string, CorePikkuMiddlewareGroup>
140
+ httpGroup: Record<string, CorePikkuMiddlewareGroup>
141
+ }
142
+ channelMiddleware: {
143
+ tagGroup: Record<string, CorePikkuChannelMiddleware[]>
144
+ }
145
+ permissions: {
146
+ tagGroup: Record<string, CorePermissionGroup | CorePikkuPermission[]>
147
+ httpGroup: Record<string, CorePermissionGroup | CorePikkuPermission[]>
148
+ }
149
+ misc: {
150
+ errors: Map<PikkuError, ErrorDetails>
151
+ schemas: Map<string, any>
152
+ middleware: Record<string, CorePikkuMiddleware[]>
153
+ channelMiddleware: Record<string, CorePikkuChannelMiddleware[]>
154
+ permissions: Record<string, CorePermissionGroup | CorePikkuPermission[]>
155
+ }
156
+ models: {
157
+ config: {
158
+ models?: Record<
159
+ string,
160
+ string | { model: string; temperature?: number; maxSteps?: number }
161
+ >
162
+ agentDefaults?: { temperature?: number; maxSteps?: number }
163
+ agentOverrides?: Record<
164
+ string,
165
+ { model?: string; temperature?: number; maxSteps?: number }
166
+ >
167
+ } | null
168
+ }
169
+ package: {
170
+ /** Service factory functions for addon packages */
171
+ factories: {
172
+ createConfig?: CreateConfig<CoreConfig>
173
+ createSingletonServices?: CreateSingletonServices<
174
+ CoreConfig,
175
+ CoreSingletonServices
176
+ >
177
+ createWireServices?: CreateWireServices<
178
+ CoreSingletonServices,
179
+ CoreServices,
180
+ CoreUserSession
181
+ >
182
+ } | null
183
+ /** Cached singleton services for this package */
184
+ singletonServices: CoreSingletonServices | null
185
+ /** Absolute path to this package's .pikku directory */
186
+ metaDir: string | null
187
+ }
188
+ }
@@ -0,0 +1,68 @@
1
+ import { describe, it } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { canonicalJSON, hashString } from './hash.js'
5
+
6
+ describe('canonicalJSON', () => {
7
+ it('sorts object keys alphabetically', () => {
8
+ const result = canonicalJSON({ b: 1, a: 2, c: 3 })
9
+ assert.equal(result, '{"a":2,"b":1,"c":3}')
10
+ })
11
+
12
+ it('sorts nested object keys', () => {
13
+ const result = canonicalJSON({ z: { b: 1, a: 2 }, a: 1 })
14
+ assert.equal(result, '{"a":1,"z":{"a":2,"b":1}}')
15
+ })
16
+
17
+ it('preserves array order', () => {
18
+ const result = canonicalJSON([3, 1, 2])
19
+ assert.equal(result, '[3,1,2]')
20
+ })
21
+
22
+ it('sorts objects inside arrays', () => {
23
+ const result = canonicalJSON([{ b: 1, a: 2 }])
24
+ assert.equal(result, '[{"a":2,"b":1}]')
25
+ })
26
+
27
+ it('handles null and undefined', () => {
28
+ assert.equal(canonicalJSON(null), 'null')
29
+ assert.equal(canonicalJSON(undefined), undefined)
30
+ })
31
+
32
+ it('handles primitives', () => {
33
+ assert.equal(canonicalJSON('hello'), '"hello"')
34
+ assert.equal(canonicalJSON(42), '42')
35
+ assert.equal(canonicalJSON(true), 'true')
36
+ })
37
+
38
+ it('produces deterministic output for same input regardless of key order', () => {
39
+ const a = canonicalJSON({ x: 1, y: 2, z: 3 })
40
+ const b = canonicalJSON({ z: 3, x: 1, y: 2 })
41
+ assert.equal(a, b)
42
+ })
43
+ })
44
+
45
+ describe('hashString', () => {
46
+ it('returns a hex string of default length 16', () => {
47
+ const result = hashString('test')
48
+ assert.equal(result.length, 16)
49
+ assert.match(result, /^[0-9a-f]+$/)
50
+ })
51
+
52
+ it('returns consistent hash for same input', () => {
53
+ const a = hashString('hello world')
54
+ const b = hashString('hello world')
55
+ assert.equal(a, b)
56
+ })
57
+
58
+ it('returns different hashes for different inputs', () => {
59
+ const a = hashString('hello')
60
+ const b = hashString('world')
61
+ assert.notEqual(a, b)
62
+ })
63
+
64
+ it('respects custom length parameter', () => {
65
+ const result = hashString('test', 8)
66
+ assert.equal(result.length, 8)
67
+ })
68
+ })
@@ -0,0 +1,26 @@
1
+ import { createHash } from 'crypto'
2
+
3
+ export function canonicalJSON(obj: unknown): string {
4
+ return JSON.stringify(sortDeep(obj))
5
+ }
6
+
7
+ function sortDeep(value: unknown): unknown {
8
+ if (value === null || value === undefined) {
9
+ return value
10
+ }
11
+ if (Array.isArray(value)) {
12
+ return value.map(sortDeep)
13
+ }
14
+ if (typeof value === 'object') {
15
+ const sorted: Record<string, unknown> = {}
16
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
17
+ sorted[key] = sortDeep((value as Record<string, unknown>)[key])
18
+ }
19
+ return sorted
20
+ }
21
+ return value
22
+ }
23
+
24
+ export function hashString(input: string, length: number = 16): string {
25
+ return createHash('sha256').update(input).digest('hex').slice(0, length)
26
+ }
@@ -0,0 +1,350 @@
1
+ import { describe, test, beforeEach } from 'node:test'
2
+ import assert from 'node:assert'
3
+ import {
4
+ closeWireServices,
5
+ createWeakUID,
6
+ isSerializable,
7
+ getTagGroups,
8
+ freezeDedupe,
9
+ stopSingletonServices,
10
+ } from './utils.js'
11
+ import {
12
+ resetPikkuState,
13
+ pikkuState,
14
+ initializePikkuState,
15
+ } from './pikku-state.js'
16
+
17
+ beforeEach(() => {
18
+ resetPikkuState()
19
+ })
20
+
21
+ describe('createWeakUID', () => {
22
+ test('should return a string', () => {
23
+ const uid = createWeakUID()
24
+ assert.strictEqual(typeof uid, 'string')
25
+ })
26
+
27
+ test('should return unique values', () => {
28
+ const uid1 = createWeakUID()
29
+ const uid2 = createWeakUID()
30
+ assert.notStrictEqual(uid1, uid2)
31
+ })
32
+
33
+ test('should contain a dash separator', () => {
34
+ const uid = createWeakUID()
35
+ assert.ok(uid.includes('-'))
36
+ })
37
+ })
38
+
39
+ describe('isSerializable', () => {
40
+ test('should return true for objects', () => {
41
+ assert.strictEqual(isSerializable({ key: 'value' }), true)
42
+ })
43
+
44
+ test('should return true for arrays', () => {
45
+ assert.strictEqual(isSerializable([1, 2, 3]), true)
46
+ })
47
+
48
+ test('should return true for numbers', () => {
49
+ assert.strictEqual(isSerializable(42), true)
50
+ })
51
+
52
+ test('should return true for booleans', () => {
53
+ assert.strictEqual(isSerializable(true), true)
54
+ })
55
+
56
+ test('should return true for null', () => {
57
+ assert.strictEqual(isSerializable(null), true)
58
+ })
59
+
60
+ test('should return false for strings', () => {
61
+ assert.strictEqual(isSerializable('hello'), false)
62
+ })
63
+
64
+ test('should return false for ArrayBuffer', () => {
65
+ assert.strictEqual(isSerializable(new ArrayBuffer(8)), false)
66
+ })
67
+
68
+ test('should return false for Uint8Array', () => {
69
+ assert.strictEqual(isSerializable(new Uint8Array(8)), false)
70
+ })
71
+
72
+ test('should return false for Int8Array', () => {
73
+ assert.strictEqual(isSerializable(new Int8Array(8)), false)
74
+ })
75
+
76
+ test('should return false for Uint16Array', () => {
77
+ assert.strictEqual(isSerializable(new Uint16Array(8)), false)
78
+ })
79
+
80
+ test('should return false for Float64Array', () => {
81
+ assert.strictEqual(isSerializable(new Float64Array(8)), false)
82
+ })
83
+ })
84
+
85
+ describe('getTagGroups', () => {
86
+ test('should return exact match', () => {
87
+ const groups = { billing: 'billing-middleware' as any }
88
+ const result = getTagGroups(groups, 'billing')
89
+ assert.deepStrictEqual(result, ['billing-middleware'])
90
+ })
91
+
92
+ test('should return parent tag for namespaced tag', () => {
93
+ const groups = { billing: 'billing-middleware' as any }
94
+ const result = getTagGroups(groups, 'billing:read')
95
+ assert.deepStrictEqual(result, ['billing-middleware'])
96
+ })
97
+
98
+ test('should return both exact and parent matches', () => {
99
+ const groups = {
100
+ billing: 'billing-middleware' as any,
101
+ 'billing:read': 'billing-read-middleware' as any,
102
+ }
103
+ const result = getTagGroups(groups, 'billing:read')
104
+ assert.deepStrictEqual(result, [
105
+ 'billing-read-middleware',
106
+ 'billing-middleware',
107
+ ])
108
+ })
109
+
110
+ test('should resolve multi-level namespace', () => {
111
+ const groups = {
112
+ billing: 'b' as any,
113
+ 'billing:read': 'br' as any,
114
+ 'billing:read:admin': 'bra' as any,
115
+ }
116
+ const result = getTagGroups(groups, 'billing:read:admin')
117
+ assert.deepStrictEqual(result, ['bra', 'br', 'b'])
118
+ })
119
+
120
+ test('should return empty array for unmatched tag', () => {
121
+ const groups = { billing: 'b' as any }
122
+ const result = getTagGroups(groups, 'other')
123
+ assert.deepStrictEqual(result, [])
124
+ })
125
+
126
+ test('should skip missing intermediate groups', () => {
127
+ const groups = {
128
+ billing: 'b' as any,
129
+ // no billing:read
130
+ 'billing:read:admin': 'bra' as any,
131
+ }
132
+ const result = getTagGroups(groups, 'billing:read:admin')
133
+ assert.deepStrictEqual(result, ['bra', 'b'])
134
+ })
135
+ })
136
+
137
+ describe('freezeDedupe', () => {
138
+ test('should return frozen empty array for undefined', () => {
139
+ const result = freezeDedupe(undefined)
140
+ assert.strictEqual(result.length, 0)
141
+ assert.ok(Object.isFrozen(result))
142
+ })
143
+
144
+ test('should return frozen empty array for empty array', () => {
145
+ const result = freezeDedupe([])
146
+ assert.strictEqual(result.length, 0)
147
+ assert.ok(Object.isFrozen(result))
148
+ })
149
+
150
+ test('should return same frozen reference for empty arrays', () => {
151
+ const result1 = freezeDedupe([])
152
+ const result2 = freezeDedupe(undefined)
153
+ assert.strictEqual(result1, result2)
154
+ })
155
+
156
+ test('should return frozen single element array', () => {
157
+ const result = freezeDedupe(['a'])
158
+ assert.deepStrictEqual([...result], ['a'])
159
+ assert.ok(Object.isFrozen(result))
160
+ })
161
+
162
+ test('should deduplicate array', () => {
163
+ const a = () => {}
164
+ const b = () => {}
165
+ const result = freezeDedupe([a, b, a, b])
166
+ assert.strictEqual(result.length, 2)
167
+ assert.strictEqual(result[0], a)
168
+ assert.strictEqual(result[1], b)
169
+ })
170
+
171
+ test('should freeze the result', () => {
172
+ const result = freezeDedupe([1, 2, 3])
173
+ assert.ok(Object.isFrozen(result))
174
+ })
175
+
176
+ test('should preserve order (first occurrence)', () => {
177
+ const result = freezeDedupe([3, 1, 2, 1, 3])
178
+ assert.deepStrictEqual([...result], [3, 1, 2])
179
+ })
180
+ })
181
+
182
+ describe('closeWireServices', () => {
183
+ test('should call close on services that have it', async () => {
184
+ let closeCalled = false
185
+ const mockLogger = {
186
+ info: () => {},
187
+ warn: () => {},
188
+ error: () => {},
189
+ debug: () => {},
190
+ }
191
+ const wireServices = {
192
+ serviceA: {
193
+ close: async () => {
194
+ closeCalled = true
195
+ },
196
+ },
197
+ serviceB: {},
198
+ }
199
+
200
+ await closeWireServices(mockLogger as any, wireServices as any)
201
+
202
+ assert.strictEqual(closeCalled, true)
203
+ })
204
+
205
+ test('should handle errors during close gracefully', async () => {
206
+ let errorLogged = false
207
+ const mockLogger = {
208
+ info: () => {},
209
+ warn: () => {},
210
+ error: () => {
211
+ errorLogged = true
212
+ },
213
+ debug: () => {},
214
+ }
215
+ const wireServices = {
216
+ serviceA: {
217
+ close: async () => {
218
+ throw new Error('close failed')
219
+ },
220
+ },
221
+ }
222
+
223
+ await closeWireServices(mockLogger as any, wireServices as any)
224
+
225
+ assert.strictEqual(errorLogged, true)
226
+ })
227
+
228
+ test('should skip services without close method', async () => {
229
+ const mockLogger = {
230
+ info: () => {},
231
+ warn: () => {},
232
+ error: () => {},
233
+ debug: () => {},
234
+ }
235
+ const wireServices = {
236
+ serviceA: { doStuff: () => {} },
237
+ serviceB: null,
238
+ }
239
+
240
+ await closeWireServices(mockLogger as any, wireServices as any)
241
+ // Should not throw
242
+ })
243
+ })
244
+
245
+ describe('stopSingletonServices', () => {
246
+ test('should stop addon services first, then parent services', async () => {
247
+ const order: string[] = []
248
+ const mockServices = {
249
+ logger: {
250
+ info: () => {},
251
+ warn: () => {},
252
+ error: () => {},
253
+ debug: () => {},
254
+ },
255
+ serviceA: {
256
+ stop: async () => {
257
+ order.push('parent-serviceA')
258
+ },
259
+ },
260
+ }
261
+ pikkuState(null, 'package', 'singletonServices', mockServices as any)
262
+
263
+ initializePikkuState('@addon/pkg')
264
+ const addonServices = {
265
+ addonService: {
266
+ stop: async () => {
267
+ order.push('addon-addonService')
268
+ },
269
+ },
270
+ }
271
+ pikkuState(
272
+ '@addon/pkg',
273
+ 'package',
274
+ 'singletonServices',
275
+ addonServices as any
276
+ )
277
+
278
+ await stopSingletonServices()
279
+
280
+ assert.ok(
281
+ order.indexOf('addon-addonService') < order.indexOf('parent-serviceA')
282
+ )
283
+ })
284
+
285
+ test('should handle services without stop method', async () => {
286
+ const mockServices = {
287
+ logger: {
288
+ info: () => {},
289
+ warn: () => {},
290
+ error: () => {},
291
+ debug: () => {},
292
+ },
293
+ noStop: {},
294
+ }
295
+ pikkuState(null, 'package', 'singletonServices', mockServices as any)
296
+
297
+ await stopSingletonServices()
298
+ // Should not throw
299
+ })
300
+
301
+ test('should handle errors during stop gracefully', async () => {
302
+ let errorLogged = false
303
+ const mockServices = {
304
+ logger: {
305
+ info: () => {},
306
+ warn: () => {},
307
+ error: () => {
308
+ errorLogged = true
309
+ },
310
+ debug: () => {},
311
+ },
312
+ failing: {
313
+ stop: async () => {
314
+ throw new Error('stop failed')
315
+ },
316
+ },
317
+ }
318
+ pikkuState(null, 'package', 'singletonServices', mockServices as any)
319
+
320
+ await stopSingletonServices()
321
+
322
+ assert.strictEqual(errorLogged, true)
323
+ })
324
+
325
+ test('should clear addon singleton services after stopping', async () => {
326
+ const mockServices = {
327
+ logger: {
328
+ info: () => {},
329
+ warn: () => {},
330
+ error: () => {},
331
+ debug: () => {},
332
+ },
333
+ }
334
+ pikkuState(null, 'package', 'singletonServices', mockServices as any)
335
+
336
+ initializePikkuState('@addon/pkg')
337
+ pikkuState('@addon/pkg', 'package', 'singletonServices', {
338
+ s: { stop: async () => {} },
339
+ } as any)
340
+
341
+ await stopSingletonServices()
342
+
343
+ const addonServices = pikkuState(
344
+ '@addon/pkg',
345
+ 'package',
346
+ 'singletonServices'
347
+ )
348
+ assert.strictEqual(addonServices, null)
349
+ })
350
+ })