@pikku/core 0.7.0 → 0.7.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 (94) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/channel/channel-runner.js +1 -1
  3. package/dist/channel/serverless/serverless-channel-runner.js +1 -1
  4. package/dist/http/http-runner.js +4 -2
  5. package/dist/http/log-http-routes.js +1 -1
  6. package/lcov.info +4585 -0
  7. package/package.json +1 -1
  8. package/src/channel/channel-handler.ts +165 -0
  9. package/src/channel/channel-runner.ts +153 -0
  10. package/src/channel/channel-store.ts +29 -0
  11. package/src/channel/channel.types.ts +133 -0
  12. package/src/channel/eventhub-service.ts +30 -0
  13. package/src/channel/eventhub-store.ts +8 -0
  14. package/src/channel/index.ts +8 -0
  15. package/src/channel/local/index.ts +3 -0
  16. package/src/channel/local/local-channel-handler.ts +50 -0
  17. package/src/channel/local/local-channel-runner.test.ts +157 -0
  18. package/src/channel/local/local-channel-runner.ts +139 -0
  19. package/src/channel/local/local-eventhub-service.test.ts +95 -0
  20. package/src/channel/local/local-eventhub-service.ts +95 -0
  21. package/src/channel/log-channels.ts +20 -0
  22. package/src/channel/pikku-abstract-channel-handler.test.ts +52 -0
  23. package/src/channel/pikku-abstract-channel-handler.ts +38 -0
  24. package/src/channel/serverless/index.ts +1 -0
  25. package/src/channel/serverless/serverless-channel-runner.ts +220 -0
  26. package/src/errors/error-handler.ts +61 -0
  27. package/src/errors/error.test.ts +54 -0
  28. package/src/errors/errors.ts +339 -0
  29. package/src/errors/index.ts +2 -0
  30. package/src/function/function-runner.ts +91 -0
  31. package/src/function/functions.types.ts +77 -0
  32. package/src/function/index.ts +2 -0
  33. package/src/handle-error.ts +73 -0
  34. package/src/http/http-runner.test.ts +140 -0
  35. package/src/http/http-runner.ts +493 -0
  36. package/src/http/http.types.ts +250 -0
  37. package/src/http/incomingmessage-to-request-convertor.ts +0 -0
  38. package/src/http/index.ts +8 -0
  39. package/src/http/log-http-routes.ts +22 -0
  40. package/src/http/pikku-fetch-http-request.test.ts +237 -0
  41. package/src/http/pikku-fetch-http-request.ts +163 -0
  42. package/src/http/pikku-fetch-http-response.test.ts +82 -0
  43. package/src/http/pikku-fetch-http-response.ts +138 -0
  44. package/src/index.ts +20 -0
  45. package/src/middleware/auth-apikey.ts +66 -0
  46. package/src/middleware/auth-bearer.ts +66 -0
  47. package/src/middleware/auth-cookie.ts +103 -0
  48. package/src/middleware/index.ts +3 -0
  49. package/src/middleware/timeout.ts +13 -0
  50. package/src/middleware-runner.ts +43 -0
  51. package/src/permissions.test.ts +58 -0
  52. package/src/permissions.ts +43 -0
  53. package/src/pikku-function.ts +1 -0
  54. package/src/pikku-request.ts +23 -0
  55. package/src/pikku-response.ts +5 -0
  56. package/src/pikku-state.ts +87 -0
  57. package/src/scheduler/index.ts +5 -0
  58. package/src/scheduler/log-schedulers.ts +20 -0
  59. package/src/scheduler/scheduler-runner.ts +105 -0
  60. package/src/scheduler/scheduler.types.ts +33 -0
  61. package/src/schema.test.ts +57 -0
  62. package/src/schema.ts +99 -0
  63. package/src/services/content-service.ts +68 -0
  64. package/src/services/index.ts +18 -0
  65. package/src/services/jwt-service.ts +30 -0
  66. package/src/services/local-content.ts +105 -0
  67. package/src/services/local-secrets.ts +43 -0
  68. package/src/services/local-variables.ts +17 -0
  69. package/src/services/logger-console.ts +97 -0
  70. package/src/services/logger.ts +57 -0
  71. package/src/services/schema-service.ts +26 -0
  72. package/src/services/secret-service.ts +17 -0
  73. package/src/services/user-session-service.ts +53 -0
  74. package/src/services/variables-service.ts +6 -0
  75. package/src/time-utils.test.ts +56 -0
  76. package/src/time-utils.ts +32 -0
  77. package/src/types/core.types.ts +178 -0
  78. package/src/utils.ts +40 -0
  79. package/tsconfig.json +13 -0
  80. package/tsconfig.tsbuildinfo +1 -0
  81. package/dist/http/http-route-runner.d.ts +0 -90
  82. package/dist/http/http-route-runner.js +0 -325
  83. package/dist/http/http-routes.types.d.ts +0 -179
  84. package/dist/http/http-routes.types.js +0 -1
  85. package/dist/http/pikku-http-request.d.ts +0 -56
  86. package/dist/http/pikku-http-request.js +0 -95
  87. package/dist/http/pikku-http-response.d.ts +0 -13
  88. package/dist/http/pikku-http-response.js +0 -60
  89. package/dist/parse-relative-time-offset.d.ts +0 -12
  90. package/dist/parse-relative-time-offset.js +0 -20
  91. package/dist/pikku-func.d.ts +0 -12
  92. package/dist/pikku-func.js +0 -39
  93. package/dist/types/functions.types.d.ts +0 -37
  94. package/dist/types/functions.types.js +0 -1
@@ -0,0 +1,493 @@
1
+ import {
2
+ CoreHTTPFunctionRoute,
3
+ RunRouteOptions,
4
+ RunRouteParams,
5
+ PikkuHTTP,
6
+ PikkuHTTPRequest,
7
+ PikkuHTTPResponse,
8
+ HTTPRouteMeta,
9
+ HTTPMethod,
10
+ } from './http.types.js'
11
+ import {
12
+ CoreUserSession,
13
+ PikkuMiddleware,
14
+ SessionServices,
15
+ } from '../types/core.types.js'
16
+ import { match } from 'path-to-regexp'
17
+ import { MissingSessionError, NotFoundError } from '../errors/errors.js'
18
+ import {
19
+ closeSessionServices,
20
+ createWeakUID,
21
+ isSerializable,
22
+ } from '../utils.js'
23
+ import {
24
+ PikkuUserSessionService,
25
+ UserSessionService,
26
+ } from '../services/user-session-service.js'
27
+ import { runMiddleware } from '../middleware-runner.js'
28
+ import { handleError } from '../handle-error.js'
29
+ import { pikkuState } from '../pikku-state.js'
30
+ import { PikkuFetchHTTPResponse } from './pikku-fetch-http-response.js'
31
+ import { PikkuFetchHTTPRequest } from './pikku-fetch-http-request.js'
32
+ import { PikkuChannel } from '../channel/channel.types.js'
33
+ import { addFunction, runPikkuFunc } from '../function/function-runner.js'
34
+
35
+ /**
36
+ * Registers middleware either globally or for a specific route.
37
+ *
38
+ * When a string route pattern is provided along with middleware, the middleware
39
+ * is applied only to that route. Otherwise, if an array is provided, it is treated
40
+ * as global middleware (applied to all routes).
41
+ *
42
+ * @template APIMiddleware The middleware type.
43
+ * @param {APIMiddleware[] | string} routeOrMiddleware - Either a global middleware array or a route pattern string.
44
+ * @param {APIMiddleware[]} [middleware] - The middleware array to apply when a route pattern is specified.
45
+ */
46
+ export const addMiddleware = <APIMiddleware extends PikkuMiddleware>(
47
+ routeOrMiddleware: APIMiddleware[] | string,
48
+ middleware?: APIMiddleware[]
49
+ ) => {
50
+ if (typeof routeOrMiddleware === 'string' && middleware) {
51
+ pikkuState('http', 'middleware').push({
52
+ route: routeOrMiddleware,
53
+ middleware,
54
+ })
55
+ } else {
56
+ pikkuState('http', 'middleware').push({
57
+ route: '*',
58
+ middleware: routeOrMiddleware as any,
59
+ })
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Adds a new route to the global HTTP route registry.
65
+ *
66
+ * The route configuration includes the HTTP method, route path, permissions,
67
+ * middleware, and the handler function that implements the route's logic.
68
+ *
69
+ * @template In Expected input type.
70
+ * @template Out Expected output type.
71
+ * @template Route Route pattern as a string.
72
+ * @template APIFunction Type for the route handler function.
73
+ * @template APIFunctionSessionless Type for a sessionless handler.
74
+ * @template APIPermissionGroup Type representing required permissions.
75
+ * @template APIMiddleware Middleware type to be used with the route.
76
+ * @param {CoreHTTPFunctionRoute<In, Out, Route, APIFunction, APIFunctionSessionless, APIPermission, APIMiddleware>} route - The route configuration object.
77
+ */
78
+ export const addHTTPRoute = <
79
+ In,
80
+ Out,
81
+ Route extends string,
82
+ APIFunction,
83
+ APIFunctionSessionless,
84
+ APIPermissionGroup,
85
+ APIMiddleware,
86
+ >(
87
+ httpRoute: CoreHTTPFunctionRoute<
88
+ In,
89
+ Out,
90
+ Route,
91
+ APIFunction,
92
+ APIFunctionSessionless,
93
+ APIPermissionGroup,
94
+ APIMiddleware
95
+ >
96
+ ) => {
97
+ const httpMeta = pikkuState('http', 'meta')
98
+ const routeMeta = httpMeta.find(
99
+ (meta) => meta.route === httpRoute.route && meta.method === httpRoute.method
100
+ )
101
+ if (!routeMeta) {
102
+ throw new Error('Route metadata not found')
103
+ }
104
+ addFunction(routeMeta.pikkuFuncName, httpRoute.func as any)
105
+ const routes = pikkuState('http', 'routes')
106
+ if (!routes.has(httpRoute.method)) {
107
+ routes.set(httpRoute.method, new Map())
108
+ }
109
+ pikkuState('http', 'routes')
110
+ .get(httpRoute.method)
111
+ ?.set(httpRoute.route, httpRoute as any)
112
+ }
113
+
114
+ /**
115
+ * Finds a matching route based on the HTTP method and URL path.
116
+ *
117
+ * Iterates over all registered routes, skipping those with a mismatched method.
118
+ * When a route pattern matches the incoming request path, this function aggregates
119
+ * any global middleware along with route-specific middleware and identifies any input schema.
120
+ *
121
+ * @param {string} requestType - The HTTP method (e.g., GET, POST).
122
+ * @param {string} requestPath - The URL path of the incoming request.
123
+ * @returns {Object | undefined} An object with matched route details or undefined if no match.
124
+ */
125
+ const getMatchingRoute = (requestType: string, requestPath: string) => {
126
+ const allRoutes = pikkuState('http', 'routes')
127
+ const middleware = pikkuState('http', 'middleware')
128
+ const routes = allRoutes.get(requestType.toLowerCase() as HTTPMethod)
129
+ if (!routes) {
130
+ return undefined
131
+ }
132
+ for (const route of routes.values()) {
133
+ // Generate a matching function from the route pattern
134
+ const matchFunc = match(`/${route.route}`.replace(/^\/\//, '/'), {
135
+ decode: decodeURIComponent,
136
+ })
137
+
138
+ // Attempt to match the request path
139
+ const matchedPath = matchFunc(requestPath.replace(/^\/\//, '/'))
140
+
141
+ if (matchedPath) {
142
+ // Aggregate global and route-specific middleware
143
+ const globalMiddleware = middleware
144
+ .filter((m) => m.route === '*' || new RegExp(m.route).test(route.route))
145
+ .map((m) => m.middleware)
146
+ .flat()
147
+
148
+ const meta = pikkuState('http', 'meta').find(
149
+ (meta) => meta.route === route.route && meta.method === route.method
150
+ )
151
+
152
+ return {
153
+ matchedPath,
154
+ params: matchedPath.params,
155
+ route,
156
+ permissions: route.permissions,
157
+ middleware: [...globalMiddleware, ...(route.middleware || [])],
158
+ meta: meta!,
159
+ }
160
+ }
161
+ }
162
+ return undefined
163
+ }
164
+
165
+ /**
166
+ * Combines the request and response objects into a single HTTP interaction object.
167
+ *
168
+ * This utility function creates an object that holds both the HTTP request and response,
169
+ * which simplifies passing these around through middleware and route execution.
170
+ *
171
+ * @param {PikkuHTTPRequest | undefined} request - The HTTP request object.
172
+ * @param {PikkuHTTPResponse | undefined} response - The HTTP response object.
173
+ * @returns {PikkuHTTP | undefined} The combined HTTP interaction object or undefined if none provided.
174
+ */
175
+ export const createHTTPInteraction = (
176
+ request: PikkuHTTPRequest | undefined,
177
+ response: PikkuHTTPResponse | undefined
178
+ ): PikkuHTTP | undefined => {
179
+ let http: PikkuHTTP | undefined = undefined
180
+
181
+ if (request || response) {
182
+ http = {}
183
+ if (request) {
184
+ http.request = request
185
+ }
186
+ if (response) {
187
+ http.response = response
188
+ }
189
+ }
190
+
191
+ return http
192
+ }
193
+
194
+ /**
195
+ * Validates the input data and executes the route handler with associated middleware.
196
+ *
197
+ * This function is the central execution point for a route. It performs these steps:
198
+ * 1. Sets URL parameters on the request.
199
+ * 2. Validates the user session if required.
200
+ * 3. Creates session-specific services.
201
+ * 4. Validates the incoming data against a schema.
202
+ * 5. Optionally coerces query string values to arrays.
203
+ * 6. Checks route-specific permissions.
204
+ * 7. Executes the route handler.
205
+ * 8. Sends the appropriate response.
206
+ *
207
+ * @param {Object} services - A collection of shared services and utilities.
208
+ * @param {Object} matchedRoute - Contains route details, URL parameters, middleware, and optional schema.
209
+ * @param {PikkuHTTP | undefined} http - The HTTP interaction object.
210
+ * @param {Object} options - Options for route execution (e.g., whether to coerce query strings to arrays).
211
+ * @returns {Promise<any>} An object containing the route handler result and session services (if any).
212
+ * @throws Throws errors like MissingSessionError or ForbiddenError on validation failures.
213
+ */
214
+ const executeRouteWithMiddleware = async (
215
+ services: {
216
+ singletonServices: any
217
+ userSession: UserSessionService<CoreUserSession>
218
+ createSessionServices: Function
219
+ skipUserSession: boolean
220
+ requestId: string
221
+ },
222
+ matchedRoute: {
223
+ matchedPath: any
224
+ params: any
225
+ route: CoreHTTPFunctionRoute<any, any, any>
226
+ middleware: any[]
227
+ meta: HTTPRouteMeta
228
+ },
229
+ http: PikkuHTTP,
230
+ options: {
231
+ coerceDataFromSchema: boolean
232
+ }
233
+ ) => {
234
+ const { matchedPath, params, route, middleware, meta } = matchedRoute
235
+ const {
236
+ singletonServices,
237
+ userSession,
238
+ createSessionServices,
239
+ skipUserSession,
240
+ requestId,
241
+ } = services
242
+
243
+ const requiresSession = route.auth !== false
244
+ let sessionServices: any
245
+ let result: any
246
+
247
+ // Attach URL parameters to the request object
248
+ http?.request?.setParams(params)
249
+
250
+ singletonServices.logger.info(
251
+ `Matched route: ${route.route} | method: ${route.method.toUpperCase()} | auth: ${requiresSession.toString()}`
252
+ )
253
+
254
+ // Main route execution logic wrapped for middleware handling
255
+ const runMain = async () => {
256
+ const session = userSession.get()
257
+
258
+ // Ensure session is available when required
259
+ if (skipUserSession && requiresSession) {
260
+ throw new Error(
261
+ "Can't skip trying to get user session if auth is required"
262
+ )
263
+ }
264
+
265
+ if (requiresSession && !session) {
266
+ singletonServices.logger.info({
267
+ action: 'Rejecting route (invalid session)',
268
+ path: matchedPath,
269
+ })
270
+ throw new MissingSessionError()
271
+ }
272
+
273
+ const data = http.request!.data()
274
+
275
+ const getAllServices = async () => {
276
+ let channel: PikkuChannel<unknown, unknown> | undefined
277
+ if (matchedRoute.route.sse) {
278
+ const response = http?.response
279
+ if (!response) {
280
+ throw new Error('SSE requires a valid HTTP response object')
281
+ }
282
+ if (!response.setMode) {
283
+ throw new Error('Response object does not support SSE mode')
284
+ }
285
+ response.setMode('stream')
286
+ response.header('Content-Type', 'text/event-stream')
287
+ response.header('Cache-Control', 'no-cache')
288
+ response.header('Connection', 'keep-alive')
289
+ response.header('Transfer-Encoding', 'chunked')
290
+ channel = {
291
+ channelId: requestId,
292
+ openingData: data,
293
+ send: (data: any) => {
294
+ response.arrayBuffer(
295
+ isSerializable(data) ? JSON.stringify(data) : data
296
+ )
297
+ },
298
+ close: () => {
299
+ channel!.state = 'closed'
300
+ response.close?.()
301
+ },
302
+ state: 'open',
303
+ }
304
+ }
305
+
306
+ // Create session-specific services for handling the request
307
+ sessionServices = await createSessionServices(
308
+ { ...singletonServices, userSession, channel },
309
+ { http },
310
+ session
311
+ )
312
+ return {
313
+ ...singletonServices,
314
+ ...sessionServices,
315
+ http,
316
+ userSession,
317
+ channel,
318
+ }
319
+ }
320
+
321
+ const result = await runPikkuFunc(meta.pikkuFuncName, {
322
+ singletonServices,
323
+ getAllServices,
324
+ session,
325
+ data,
326
+ permissions: route.permissions,
327
+ coerceDataFromSchema: options.coerceDataFromSchema,
328
+ })
329
+
330
+ // Respond with either a binary or JSON response based on configuration
331
+ if (route.returnsJSON === false) {
332
+ http?.response?.arrayBuffer(result)
333
+ } else {
334
+ http?.response?.json(result)
335
+ }
336
+
337
+ http?.response?.status(200)
338
+ // TODO: Evaluate if the response stream should be explicitly ended.
339
+ // http?.response?.end()
340
+
341
+ return result
342
+ }
343
+
344
+ // Execute middleware, then run the main logic
345
+ await runMiddleware(
346
+ { ...singletonServices, userSession },
347
+ { http },
348
+ middleware,
349
+ runMain
350
+ )
351
+
352
+ return sessionServices ? { result, sessionServices } : { result }
353
+ }
354
+
355
+ /**
356
+ * Executes an HTTP route for a given Fetch API request.
357
+ *
358
+ * This function wraps the entire lifecycle of handling an HTTP request:
359
+ * - Matching the request to a registered route.
360
+ * - Validating input and session state.
361
+ * - Running middleware and the route handler.
362
+ * - Handling errors and forming the response.
363
+ *
364
+ * @template In Expected input data type.
365
+ * @template Out Expected output data type.
366
+ * @param {Request} request - The native Fetch API Request object.
367
+ * @param {RunRouteOptions & RunRouteParams} params - Additional options including services and session management.
368
+ * @returns {Promise<Response>} A promise that resolves to a Fetch API Response object.
369
+ */
370
+ export const fetch = async <In, Out>(
371
+ request: Request,
372
+ params: RunRouteOptions & RunRouteParams
373
+ ): Promise<Response> => {
374
+ const pikkuResponse = new PikkuFetchHTTPResponse()
375
+ await fetchData<In, Out>(request, pikkuResponse, params)
376
+ return pikkuResponse.toResponse()
377
+ }
378
+
379
+ /**
380
+ * Executes an HTTP route using a Pikku-specific request wrapper.
381
+ *
382
+ * This variant accepts either a native Request or a PikkuHTTPRequest object and returns
383
+ * a PikkuFetchHTTPResponse for further manipulation if needed.
384
+ *
385
+ * @template In Expected input data type.
386
+ * @template Out Expected output data type.
387
+ * @param {Request | PikkuHTTPRequest} request - The request object.
388
+ * @param {RunRouteOptions & RunRouteParams} params - Execution options including services and session configuration.
389
+ * @returns {Promise<PikkuFetchHTTPResponse>} A promise that resolves to a PikkuFetchHTTPResponse object.
390
+ */
391
+ export const pikkuFetch = async <In, Out>(
392
+ request: Request | PikkuHTTPRequest,
393
+ params: RunRouteOptions & RunRouteParams
394
+ ): Promise<PikkuFetchHTTPResponse> => {
395
+ const pikkuResponse = new PikkuFetchHTTPResponse()
396
+ await fetchData<In, Out>(request, pikkuResponse, params)
397
+ return pikkuResponse
398
+ }
399
+
400
+ /**
401
+ * Core function to process an HTTP request through route matching, validation,
402
+ * middleware execution, error handling, and session service cleanup.
403
+ *
404
+ * This function does the following:
405
+ * - Wraps the incoming request and response into an HTTP interaction object.
406
+ * - Determines the correct route based on HTTP method and path.
407
+ * - Executes middleware and the route handler.
408
+ * - Catches and handles errors, optionally bubbling them if configured.
409
+ * - Cleans up any session services created during processing.
410
+ *
411
+ * @template In Expected input data type.
412
+ * @template Out Expected output data type.
413
+ * @param {Request | PikkuHTTPRequest} request - The incoming HTTP request.
414
+ * @param {PikkuHTTPResponse} response - The response object to be populated.
415
+ * @param {RunRouteOptions & RunRouteParams} options - Options such as singleton services, session handling, and error configuration.
416
+ * @returns {Promise<Out | void>} The output from the route handler or void if an error occurred.
417
+ */
418
+ export const fetchData = async <In, Out>(
419
+ request: Request | PikkuHTTPRequest,
420
+ response: PikkuHTTPResponse,
421
+ {
422
+ singletonServices,
423
+ createSessionServices,
424
+ skipUserSession = false,
425
+ respondWith404 = true,
426
+ logWarningsForStatusCodes = [],
427
+ coerceDataFromSchema = true,
428
+ bubbleErrors = false,
429
+ generateRequestId,
430
+ }: RunRouteOptions & RunRouteParams
431
+ ): Promise<Out | void> => {
432
+ const requestId =
433
+ (request as any).getHeader?.('x-request-id') ||
434
+ generateRequestId?.() ||
435
+ createWeakUID()
436
+ const userSession = new PikkuUserSessionService()
437
+ let sessionServices: SessionServices<typeof singletonServices> | undefined
438
+ let result: Out
439
+
440
+ // Combine the request and response into one interaction object
441
+ const http = createHTTPInteraction(
442
+ request instanceof Request ? new PikkuFetchHTTPRequest(request) : request,
443
+ response
444
+ )
445
+ const apiType = http!.request!.method()
446
+ const apiRoute = http!.request!.path()
447
+
448
+ // Locate the matching route based on the HTTP method and path
449
+ const matchedRoute = getMatchingRoute(apiType, apiRoute)
450
+ try {
451
+ // If no route matches, log the occurrence and throw a NotFoundError
452
+ if (!matchedRoute) {
453
+ singletonServices.logger.info({
454
+ message: 'Route not found',
455
+ apiRoute,
456
+ apiType,
457
+ })
458
+ throw new NotFoundError(`Route not found: ${apiRoute}`)
459
+ }
460
+
461
+ // Execute the matched route along with its middleware and session management
462
+ ;({ result, sessionServices } = await executeRouteWithMiddleware(
463
+ {
464
+ singletonServices,
465
+ userSession,
466
+ createSessionServices,
467
+ skipUserSession,
468
+ requestId,
469
+ },
470
+ matchedRoute,
471
+ http!,
472
+ { coerceDataFromSchema }
473
+ ))
474
+
475
+ return result
476
+ } catch (e: any) {
477
+ // Handle errors and, depending on configuration, bubble them up or respond with an error
478
+ handleError(
479
+ e,
480
+ http,
481
+ requestId,
482
+ singletonServices.logger,
483
+ logWarningsForStatusCodes,
484
+ respondWith404,
485
+ bubbleErrors
486
+ )
487
+ } finally {
488
+ // Clean up any session-specific services created during processing
489
+ if (sessionServices) {
490
+ await closeSessionServices(singletonServices.logger, sessionServices)
491
+ }
492
+ }
493
+ }