@geekmidas/constructs 10.0.0-alpha.37 → 10.0.0-alpha.39
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.
- package/README.md +156 -155
- package/dist/{Construct-Detz65RA.mjs → Construct-BO1X-kt9.mjs} +3 -6
- package/dist/Construct-BO1X-kt9.mjs.map +1 -0
- package/dist/Construct-BQALFCh2.d.cts +230 -0
- package/dist/Construct-BQALFCh2.d.cts.map +1 -0
- package/dist/{Construct-yG9Sw-5p.cjs → Construct-DmvXceVY.cjs} +3 -6
- package/dist/Construct-DmvXceVY.cjs.map +1 -0
- package/dist/Construct-QXnl3VqT.d.mts +230 -0
- package/dist/Construct-QXnl3VqT.d.mts.map +1 -0
- package/dist/{Cron-CA2oa2nC.d.cts → Cron-CMEGfRs8.d.cts} +7 -5
- package/dist/Cron-CMEGfRs8.d.cts.map +1 -0
- package/dist/{Cron-B_iuyNxr.d.mts → Cron-D6X4-xjB.d.mts} +7 -5
- package/dist/Cron-D6X4-xjB.d.mts.map +1 -0
- package/dist/{CronBuilder-B_KqaodP.d.cts → CronBuilder-CEK7aOqD.d.cts} +21 -16
- package/dist/CronBuilder-CEK7aOqD.d.cts.map +1 -0
- package/dist/{CronBuilder-BbnT7tqo.cjs → CronBuilder-DB35T5dL.cjs} +13 -11
- package/dist/CronBuilder-DB35T5dL.cjs.map +1 -0
- package/dist/{CronBuilder-BRkzUOAs.mjs → CronBuilder-Dv0IlZs0.mjs} +14 -12
- package/dist/CronBuilder-Dv0IlZs0.mjs.map +1 -0
- package/dist/{CronBuilder-BIKCLWu7.d.mts → CronBuilder-O_gvButp.d.mts} +21 -16
- package/dist/CronBuilder-O_gvButp.d.mts.map +1 -0
- package/dist/{Endpoint-DO332Dnm.mjs → Endpoint-CQAeh1Rh.mjs} +5 -5
- package/dist/Endpoint-CQAeh1Rh.mjs.map +1 -0
- package/dist/{Endpoint-QKuFg5gs.cjs → Endpoint-D1L9qu5C.cjs} +5 -5
- package/dist/Endpoint-D1L9qu5C.cjs.map +1 -0
- package/dist/{Endpoint-1-XYQSx0.d.cts → Endpoint-Dp5AKIXl.d.cts} +10 -13
- package/dist/Endpoint-Dp5AKIXl.d.cts.map +1 -0
- package/dist/{Endpoint-GFIxYb9L.d.mts → Endpoint-DtI7heFm.d.mts} +10 -13
- package/dist/Endpoint-DtI7heFm.d.mts.map +1 -0
- package/dist/{EndpointFactory-B9HAjDAP.mjs → EndpointFactory-BBdNeaGJ.mjs} +23 -52
- package/dist/EndpointFactory-BBdNeaGJ.mjs.map +1 -0
- package/dist/{EndpointFactory-BmO0WnXE.cjs → EndpointFactory-BZOCOaK6.cjs} +22 -51
- package/dist/EndpointFactory-BZOCOaK6.cjs.map +1 -0
- package/dist/{EndpointFactory-BCZdh_u3.d.mts → EndpointFactory-CgMDvERK.d.mts} +58 -48
- package/dist/EndpointFactory-CgMDvERK.d.mts.map +1 -0
- package/dist/{EndpointFactory-BnK_YkW1.d.cts → EndpointFactory-FeFRmlDZ.d.cts} +58 -48
- package/dist/EndpointFactory-FeFRmlDZ.d.cts.map +1 -0
- package/dist/{HonoEndpointAdaptor-CiqAZ5Mt.mjs → HonoEndpointAdaptor-Aui-x9Lg.mjs} +4 -3
- package/dist/HonoEndpointAdaptor-Aui-x9Lg.mjs.map +1 -0
- package/dist/{HonoEndpointAdaptor-DoEQdC3r.cjs → HonoEndpointAdaptor-Cq99r9H7.cjs} +5 -4
- package/dist/HonoEndpointAdaptor-Cq99r9H7.cjs.map +1 -0
- package/dist/{Queue-DpKTLl6E.mjs → Queue-C1uDgjxt.mjs} +29 -48
- package/dist/Queue-C1uDgjxt.mjs.map +1 -0
- package/dist/{Queue-B7yRXQmL.cjs → Queue-Ckmudcm8.cjs} +29 -48
- package/dist/Queue-Ckmudcm8.cjs.map +1 -0
- package/dist/{Queue-Bhzi2WQC.d.cts → Queue-CpQIGB_2.d.cts} +22 -33
- package/dist/Queue-CpQIGB_2.d.cts.map +1 -0
- package/dist/{Queue-BoUA-e83.d.mts → Queue-YmvN2vEP.d.mts} +21 -32
- package/dist/Queue-YmvN2vEP.d.mts.map +1 -0
- package/dist/QueueBuilder-CJNcv4dy.cjs +112 -0
- package/dist/QueueBuilder-CJNcv4dy.cjs.map +1 -0
- package/dist/QueueBuilder-CM0WUxfw.d.mts +62 -0
- package/dist/QueueBuilder-CM0WUxfw.d.mts.map +1 -0
- package/dist/QueueBuilder-XEnnOWGe.d.cts +62 -0
- package/dist/QueueBuilder-XEnnOWGe.d.cts.map +1 -0
- package/dist/QueueBuilder-XuPKZwKH.mjs +95 -0
- package/dist/QueueBuilder-XuPKZwKH.mjs.map +1 -0
- package/dist/{Subscriber-DQCaiOXF.d.cts → Subscriber-B91YSkZt.d.cts} +12 -13
- package/dist/Subscriber-B91YSkZt.d.cts.map +1 -0
- package/dist/{Subscriber-CIO3pwji.d.mts → Subscriber-BjHYe5hK.d.mts} +11 -12
- package/dist/Subscriber-BjHYe5hK.d.mts.map +1 -0
- package/dist/{SubscriberBuilder-CjDGSTZc.d.cts → SubscriberBuilder-BSpQX1JT.d.cts} +19 -23
- package/dist/SubscriberBuilder-BSpQX1JT.d.cts.map +1 -0
- package/dist/{SubscriberBuilder-C2FRfd26.d.mts → SubscriberBuilder-BhMphk4z.d.mts} +18 -22
- package/dist/SubscriberBuilder-BhMphk4z.d.mts.map +1 -0
- package/dist/{SubscriberBuilder-C2bCOuPT.cjs → SubscriberBuilder-Duk028pD.cjs} +11 -19
- package/dist/SubscriberBuilder-Duk028pD.cjs.map +1 -0
- package/dist/{SubscriberBuilder-B4YRTBng.mjs → SubscriberBuilder-DzQUWE08.mjs} +11 -19
- package/dist/SubscriberBuilder-DzQUWE08.mjs.map +1 -0
- package/dist/{Topic-D5rlM9wS.cjs → Topic-BBVXC3H4.cjs} +46 -51
- package/dist/Topic-BBVXC3H4.cjs.map +1 -0
- package/dist/Topic-DOw051ch.mjs +98 -0
- package/dist/Topic-DOw051ch.mjs.map +1 -0
- package/dist/adaptors/aws.cjs +5 -5
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts +26 -26
- package/dist/adaptors/aws.d.cts.map +1 -1
- package/dist/adaptors/aws.d.mts +25 -25
- package/dist/adaptors/aws.d.mts.map +1 -1
- package/dist/adaptors/aws.mjs +5 -5
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/hono.cjs +1 -1
- package/dist/adaptors/hono.d.cts +4 -5
- package/dist/adaptors/hono.d.cts.map +1 -1
- package/dist/adaptors/hono.d.mts +4 -5
- package/dist/adaptors/hono.d.mts.map +1 -1
- package/dist/adaptors/hono.mjs +1 -1
- package/dist/adaptors/testing.cjs +59 -23
- package/dist/adaptors/testing.cjs.map +1 -1
- package/dist/adaptors/testing.d.cts +40 -28
- package/dist/adaptors/testing.d.cts.map +1 -1
- package/dist/adaptors/testing.d.mts +40 -28
- package/dist/adaptors/testing.d.mts.map +1 -1
- package/dist/adaptors/testing.mjs +59 -23
- package/dist/adaptors/testing.mjs.map +1 -1
- package/dist/{auth-c6nWnvD8.d.cts → auth-CMwml9QN.d.mts} +4 -4
- package/dist/{auth-c6nWnvD8.d.cts.map → auth-CMwml9QN.d.mts.map} +1 -1
- package/dist/{auth-pS_U1H_X.d.mts → auth-rVRDjIw_.d.cts} +4 -4
- package/dist/{auth-pS_U1H_X.d.mts.map → auth-rVRDjIw_.d.cts.map} +1 -1
- package/dist/auth.d.cts +1 -1
- package/dist/auth.d.mts +1 -1
- package/dist/{cache-B2s0b-ss.d.mts → cache-C9a_hVCc.d.cts} +3 -3
- package/dist/{cache-B2s0b-ss.d.mts.map → cache-C9a_hVCc.d.cts.map} +1 -1
- package/dist/{cache-CYe2Kzjc.d.cts → cache-CeTMI8LR.d.mts} +3 -3
- package/dist/{cache-CYe2Kzjc.d.cts.map → cache-CeTMI8LR.d.mts.map} +1 -1
- package/dist/cache.d.cts +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/{construct-interface-D2gesxos.d.mts → construct-interface-_3zgxzXl.d.mts} +11 -20
- package/dist/{construct-interface-D2gesxos.d.mts.map → construct-interface-_3zgxzXl.d.mts.map} +1 -1
- package/dist/{construct-interface-DPusCUSQ.d.cts → construct-interface-_xi4BPN8.d.cts} +11 -20
- package/dist/{construct-interface-DPusCUSQ.d.cts.map → construct-interface-_xi4BPN8.d.cts.map} +1 -1
- package/dist/construct-interface.cjs +4 -33
- package/dist/construct-interface.cjs.map +1 -1
- package/dist/construct-interface.d.cts +2 -2
- package/dist/construct-interface.d.mts +2 -2
- package/dist/construct-interface.mjs +5 -32
- package/dist/construct-interface.mjs.map +1 -1
- package/dist/credential.cjs +22 -9
- package/dist/credential.cjs.map +1 -1
- package/dist/credential.d.cts +12 -2
- package/dist/credential.d.cts.map +1 -1
- package/dist/credential.d.mts +12 -2
- package/dist/credential.d.mts.map +1 -1
- package/dist/credential.mjs +22 -10
- package/dist/credential.mjs.map +1 -1
- package/dist/crons/index.cjs +1 -1
- package/dist/crons/index.d.cts +2 -2
- package/dist/crons/index.d.mts +2 -2
- package/dist/crons/index.mjs +1 -1
- package/dist/database/kysely.d.cts +1 -1
- package/dist/database/kysely.d.mts +1 -1
- package/dist/email.d.cts +1 -1
- package/dist/email.d.mts +1 -1
- package/dist/endpoints/index.cjs +5 -4
- package/dist/endpoints/index.d.cts +4 -13
- package/dist/endpoints/index.d.cts.map +1 -1
- package/dist/endpoints/index.d.mts +4 -13
- package/dist/endpoints/index.d.mts.map +1 -1
- package/dist/endpoints/index.mjs +4 -3
- package/dist/external-api-DS3mujT5.d.mts +86 -0
- package/dist/external-api-DS3mujT5.d.mts.map +1 -0
- package/dist/external-api-LBfE-q3g.d.cts +86 -0
- package/dist/external-api-LBfE-q3g.d.cts.map +1 -0
- package/dist/external-api.cjs +124 -0
- package/dist/external-api.cjs.map +1 -0
- package/dist/external-api.d.cts +2 -0
- package/dist/external-api.d.mts +2 -0
- package/dist/external-api.mjs +121 -0
- package/dist/external-api.mjs.map +1 -0
- package/dist/file-server.d.cts +1 -1
- package/dist/file-server.d.mts +1 -1
- package/dist/functions/index.cjs +1 -1
- package/dist/functions/index.d.cts +1 -1
- package/dist/functions/index.d.mts +1 -1
- package/dist/functions/index.mjs +1 -1
- package/dist/{functions-DlFm8HmH.mjs → functions-DCIfCRR-.mjs} +94 -23
- package/dist/functions-DCIfCRR-.mjs.map +1 -0
- package/dist/{functions-DKN6aQWJ.cjs → functions-ZH60FE7H.cjs} +99 -19
- package/dist/functions-ZH60FE7H.cjs.map +1 -0
- package/dist/{index-BI23K3wy.d.cts → index-B0kxstwf.d.cts} +36 -24
- package/dist/index-B0kxstwf.d.cts.map +1 -0
- package/dist/{index-yb3fXNyH.d.mts → index-CjVEjOw0.d.mts} +36 -24
- package/dist/index-CjVEjOw0.d.mts.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{kysely-CEVXacPN.d.cts → kysely-BJ8IQ_1P.d.mts} +4 -4
- package/dist/{kysely-CEVXacPN.d.cts.map → kysely-BJ8IQ_1P.d.mts.map} +1 -1
- package/dist/{kysely-mcTdPNhl.d.mts → kysely-DVF8wOT4.d.cts} +4 -4
- package/dist/{kysely-mcTdPNhl.d.mts.map → kysely-DVF8wOT4.d.cts.map} +1 -1
- package/dist/{lazyAccessors-BHtcqgz2.mjs → lazyAccessors-CFanua0O.mjs} +2 -39
- package/dist/lazyAccessors-CFanua0O.mjs.map +1 -0
- package/dist/{lazyAccessors-Dx9NLwJZ.cjs → lazyAccessors-hJKGv8Ay.cjs} +1 -50
- package/dist/lazyAccessors-hJKGv8Ay.cjs.map +1 -0
- package/dist/mobile-app.d.cts +1 -1
- package/dist/mobile-app.d.mts +1 -1
- package/dist/object-storage.d.cts +1 -1
- package/dist/object-storage.d.mts +1 -1
- package/dist/processAudits-BpRlPQMW.mjs.map +1 -1
- package/dist/processAudits-D_2W5x8k.cjs.map +1 -1
- package/dist/queue/index.cjs +4 -78
- package/dist/queue/index.d.cts +3 -53
- package/dist/queue/index.d.mts +3 -53
- package/dist/queue/index.mjs +3 -77
- package/dist/rest-api.cjs +2 -4
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +4 -5
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +4 -5
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +2 -4
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.d.cts +1 -1
- package/dist/site.d.mts +1 -1
- package/dist/subscribers/index.cjs +1 -1
- package/dist/subscribers/index.d.cts +2 -2
- package/dist/subscribers/index.d.mts +2 -2
- package/dist/subscribers/index.mjs +1 -1
- package/dist/topic/index.cjs +1 -36
- package/dist/topic/index.d.cts +2 -3
- package/dist/topic/index.d.mts +2 -3
- package/dist/topic/index.mjs +2 -35
- package/dist/worker.cjs +26 -17
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +37 -29
- package/dist/worker.d.cts.map +1 -1
- package/dist/worker.d.mts +37 -29
- package/dist/worker.d.mts.map +1 -1
- package/dist/worker.mjs +26 -17
- package/dist/worker.mjs.map +1 -1
- package/package.json +41 -31
- package/dist/Construct-DTqYvkPG.d.cts +0 -115
- package/dist/Construct-DTqYvkPG.d.cts.map +0 -1
- package/dist/Construct-Detz65RA.mjs.map +0 -1
- package/dist/Construct-pVadmURD.d.mts +0 -115
- package/dist/Construct-pVadmURD.d.mts.map +0 -1
- package/dist/Construct-yG9Sw-5p.cjs.map +0 -1
- package/dist/Cron-B_iuyNxr.d.mts.map +0 -1
- package/dist/Cron-CA2oa2nC.d.cts.map +0 -1
- package/dist/CronBuilder-BIKCLWu7.d.mts.map +0 -1
- package/dist/CronBuilder-BRkzUOAs.mjs.map +0 -1
- package/dist/CronBuilder-B_KqaodP.d.cts.map +0 -1
- package/dist/CronBuilder-BbnT7tqo.cjs.map +0 -1
- package/dist/Endpoint-1-XYQSx0.d.cts.map +0 -1
- package/dist/Endpoint-DO332Dnm.mjs.map +0 -1
- package/dist/Endpoint-GFIxYb9L.d.mts.map +0 -1
- package/dist/Endpoint-QKuFg5gs.cjs.map +0 -1
- package/dist/EndpointFactory-B9HAjDAP.mjs.map +0 -1
- package/dist/EndpointFactory-BCZdh_u3.d.mts.map +0 -1
- package/dist/EndpointFactory-BmO0WnXE.cjs.map +0 -1
- package/dist/EndpointFactory-BnK_YkW1.d.cts.map +0 -1
- package/dist/HonoEndpointAdaptor-CiqAZ5Mt.mjs.map +0 -1
- package/dist/HonoEndpointAdaptor-DoEQdC3r.cjs.map +0 -1
- package/dist/Queue-B7yRXQmL.cjs.map +0 -1
- package/dist/Queue-Bhzi2WQC.d.cts.map +0 -1
- package/dist/Queue-BoUA-e83.d.mts.map +0 -1
- package/dist/Queue-DpKTLl6E.mjs.map +0 -1
- package/dist/Subscriber-CIO3pwji.d.mts.map +0 -1
- package/dist/Subscriber-DQCaiOXF.d.cts.map +0 -1
- package/dist/SubscriberBuilder-B4YRTBng.mjs.map +0 -1
- package/dist/SubscriberBuilder-C2FRfd26.d.mts.map +0 -1
- package/dist/SubscriberBuilder-C2bCOuPT.cjs.map +0 -1
- package/dist/SubscriberBuilder-CjDGSTZc.d.cts.map +0 -1
- package/dist/Topic-Ct3Le8Wt.mjs +0 -103
- package/dist/Topic-Ct3Le8Wt.mjs.map +0 -1
- package/dist/Topic-D5rlM9wS.cjs.map +0 -1
- package/dist/Topic-D6blllEn.d.cts +0 -89
- package/dist/Topic-D6blllEn.d.cts.map +0 -1
- package/dist/Topic-DVvheJ_-.d.mts +0 -89
- package/dist/Topic-DVvheJ_-.d.mts.map +0 -1
- package/dist/functions-DKN6aQWJ.cjs.map +0 -1
- package/dist/functions-DlFm8HmH.mjs.map +0 -1
- package/dist/index-BI23K3wy.d.cts.map +0 -1
- package/dist/index-fnpjXiA-.d.mts +0 -26
- package/dist/index-fnpjXiA-.d.mts.map +0 -1
- package/dist/index-tE_119SX.d.cts +0 -26
- package/dist/index-tE_119SX.d.cts.map +0 -1
- package/dist/index-yb3fXNyH.d.mts.map +0 -1
- package/dist/lazyAccessors-BHtcqgz2.mjs.map +0 -1
- package/dist/lazyAccessors-Dx9NLwJZ.cjs.map +0 -1
- package/dist/queue/index.cjs.map +0 -1
- package/dist/queue/index.d.cts.map +0 -1
- package/dist/queue/index.d.mts.map +0 -1
- package/dist/queue/index.mjs.map +0 -1
- package/dist/topic/index.cjs.map +0 -1
- package/dist/topic/index.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processAudits-BpRlPQMW.mjs","names":[],"sources":["../src/endpoints/processAudits.ts"],"sourcesContent":["import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditor,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type { CookieFn, Endpoint, HeaderFn } from './Endpoint';\n\n/**\n * Process declarative audit definitions after successful endpoint execution.\n * Similar to publishConstructEvents for events.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param response - The handler response to generate audit payloads from\n * @param serviceDiscovery - Service discovery for registering audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context (session, headers, cookies, services)\n * @param existingAuditor - Optional existing auditor instance (e.g., from handler context).\n * If provided, uses this auditor (with its stored transaction).\n * If not provided, creates a new auditor.\n */\nexport async function processEndpointAudits<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tany,\n\t\tany,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction\n\t>,\n\tresponse: InferStandardSchema<OutSchema>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n\texistingAuditor?: Auditor<TAuditAction>,\n): Promise<void> {\n\ttry {\n\t\tconst audits = endpoint.audits as MappedAudit<TAuditAction, OutSchema>[];\n\n\t\t// If we have an existing auditor (from handler context), we need to flush\n\t\t// any manual audits it collected, even if there are no declarative audits\n\t\tconst hasExistingRecords =\n\t\t\texistingAuditor && existingAuditor.getRecords().length > 0;\n\n\t\t// Skip if no declarative audits and no existing records to flush\n\t\tif (!audits?.length && !hasExistingRecords) {\n\t\t\tlogger.debug('No audits to process');\n\t\t\treturn;\n\t\t}\n\n\t\t// If no auditor storage service and we have things to process, warn\n\t\tif (!endpoint.auditorStorageService) {\n\t\t\tif (hasExistingRecords || audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Get or create auditor\n\t\tlet auditor: Auditor<TAuditAction>;\n\n\t\tif (existingAuditor) {\n\t\t\t// Use existing auditor (preserves stored transaction and manual audits)\n\t\t\tauditor = existingAuditor;\n\t\t\tlogger.debug('Using existing auditor from handler context');\n\t\t} else {\n\t\t\t// Create new auditor (backward compatibility)\n\t\t\tconst services = await serviceDiscovery.register([\n\t\t\t\tendpoint.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = services[\n\t\t\t\tendpoint.auditorStorageService.serviceName\n\t\t\t] as AuditStorage;\n\n\t\t\t// Extract actor if configured\n\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\tif (endpoint.actorExtractor) {\n\t\t\t\ttry {\n\t\t\t\t\tactor = await (\n\t\t\t\t\t\tendpoint.actorExtractor as ActorExtractor<\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\tTLogger\n\t\t\t\t\t\t>\n\t\t\t\t\t)({\n\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\theader: ctx.header,\n\t\t\t\t\t\tcookie: ctx.cookie,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t// Continue with system actor\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor,\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tendpoint: endpoint.route,\n\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Process each declarative audit\n\t\tif (audits?.length) {\n\t\t\tfor (const audit of audits) {\n\t\t\t\tlogger.debug({ audit: audit.type }, 'Processing declarative audit');\n\n\t\t\t\t// Check when condition\n\t\t\t\tif (audit.when && !audit.when(response as any)) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ audit: audit.type },\n\t\t\t\t\t\t'Audit skipped due to when condition',\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Extract payload\n\t\t\t\tconst payload = audit.payload(response as any);\n\n\t\t\t\t// Extract entityId if configured\n\t\t\t\tconst entityId = audit.entityId?.(response as any);\n\n\t\t\t\t// Record the audit\n\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\ttable: audit.table,\n\t\t\t\t\tentityId,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush audits to storage\n\t\t// Note: If existingAuditor has a stored transaction (via setTransaction),\n\t\t// flush() will use it automatically\n\t\tconst recordCount = auditor.getRecords().length;\n\t\tif (recordCount > 0) {\n\t\t\t// Check if auditor has a stored transaction (for logging purposes)\n\t\t\tconst trx =\n\t\t\t\t'getTransaction' in auditor\n\t\t\t\t\t? (auditor as { getTransaction(): unknown }).getTransaction()\n\t\t\t\t\t: undefined;\n\t\t\tlogger.debug(\n\t\t\t\t{ auditCount: recordCount, hasTransaction: !!trx },\n\t\t\t\t'Flushing audits',\n\t\t\t);\n\t\t\tawait auditor.flush();\n\t\t}\n\t} catch (error) {\n\t\tlogger.error(error as Error, 'Failed to process audits');\n\t\t// Don't rethrow - audit failures shouldn't fail the request\n\t}\n}\n\n/**\n * Context for audit-aware handler execution.\n */\nexport interface AuditExecutionContext<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\t/** The auditor instance for recording audits */\n\tauditor: Auditor<TAuditAction>;\n\t/** The audit storage instance */\n\tstorage: AuditStorage;\n}\n\n/**\n * Create audit context for handler execution.\n * Returns the auditor and storage for use in the handler.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param serviceDiscovery - Service discovery for getting audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context for actor extraction\n * @returns Audit context with auditor and storage, or undefined if not configured\n */\nexport async function createAuditContext<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tany,\n\t\tany,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n): Promise<AuditExecutionContext<TAuditAction> | undefined> {\n\tif (!endpoint.auditorStorageService) {\n\t\treturn undefined;\n\t}\n\n\tconst services = await serviceDiscovery.register([\n\t\tendpoint.auditorStorageService,\n\t]);\n\tconst storage = services[\n\t\tendpoint.auditorStorageService.serviceName\n\t] as AuditStorage;\n\n\t// Extract actor if configured\n\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\tif (endpoint.actorExtractor) {\n\t\ttry {\n\t\t\tactor = await (\n\t\t\t\tendpoint.actorExtractor as ActorExtractor<TServices, TSession, TLogger>\n\t\t\t)({\n\t\t\t\tservices: ctx.services as any,\n\t\t\t\tsession: ctx.session,\n\t\t\t\theader: ctx.header,\n\t\t\t\tcookie: ctx.cookie,\n\t\t\t\tlogger,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t}\n\t}\n\n\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\tactor,\n\t\tstorage,\n\t\tmetadata: {\n\t\t\tendpoint: endpoint.route,\n\t\t\tmethod: endpoint.method,\n\t\t},\n\t});\n\n\treturn { auditor, storage };\n}\n\n/**\n * Options for executeWithAuditTransaction.\n */\nexport interface ExecuteWithAuditTransactionOptions {\n\t/**\n\t * Database connection to use for the transaction.\n\t * If this is already a transaction, it will be reused instead of creating a nested one.\n\t * If not provided, the storage's internal database is used.\n\t */\n\tdb?: unknown;\n}\n\n/**\n * Execute a handler with automatic audit transaction support.\n * If the audit storage provides a withTransaction method, wraps execution\n * in a transaction so audits are atomic with handler's database operations.\n *\n * This is database-agnostic - each storage implementation provides its own\n * transaction handling based on the underlying database (Kysely, Drizzle, etc.).\n *\n * If the db parameter is provided and is already a transaction, the storage\n * will reuse it instead of creating a nested transaction (similar to\n * packages/db/src/kysely.ts#withTransaction).\n *\n * @param auditContext - The audit context from createAuditContext\n * @param handler - The handler function to execute (receives auditor)\n * @param onComplete - Called after handler with response, to process declarative audits\n * @param options - Optional configuration including database connection\n * @returns The handler result\n */\nexport async function executeWithAuditTransaction<\n\tT,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tauditContext: AuditExecutionContext<TAuditAction> | undefined,\n\thandler: (auditor?: Auditor<TAuditAction>) => Promise<T>,\n\tonComplete?: (response: T, auditor: Auditor<TAuditAction>) => Promise<void>,\n\toptions?: ExecuteWithAuditTransactionOptions,\n): Promise<T> {\n\t// No audit context - just run handler\n\tif (!auditContext) {\n\t\treturn handler(undefined);\n\t}\n\n\tconst { auditor, storage } = auditContext;\n\n\t// Check if storage provides a transaction wrapper\n\tif (storage.withTransaction) {\n\t\t// Wrap in transaction - audits are atomic with handler operations\n\t\t// The storage's withTransaction handles setTransaction and flush\n\t\t// Pass db so existing transactions are reused\n\t\treturn storage.withTransaction(\n\t\t\tauditor,\n\t\t\tasync () => {\n\t\t\t\tconst response = await handler(auditor);\n\n\t\t\t\t// Process declarative audits within the transaction\n\t\t\t\tif (onComplete) {\n\t\t\t\t\tawait onComplete(response, auditor);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t},\n\t\t\toptions?.db,\n\t\t);\n\t}\n\n\t// No transaction support - run handler and flush audits after\n\tconst response = await handler(auditor);\n\n\tif (onComplete) {\n\t\tawait onComplete(response, auditor);\n\t}\n\n\t// Flush audits (no transaction)\n\tawait auditor.flush();\n\n\treturn response;\n}\n"],"mappings":";;;;;;;;;;;;AAkNA,eAAsB,mBAarB,UAgBA,kBACA,QACA,KAM2D;CAC3D,IAAI,CAAC,SAAS,uBACb;CAMD,MAAM,WAAU,MAHO,iBAAiB,SAAS,CAChD,SAAS,qBACV,CAAC,EAAA,CAEA,SAAS,sBAAsB;CAIhC,IAAI,QAAoB;EAAE,IAAI;EAAU,MAAM;CAAS;CACvD,IAAI,SAAS,gBACZ,IAAI;EACH,QAAQ,MACP,SAAS,eACR;GACD,UAAU,IAAI;GACd,SAAS,IAAI;GACb,QAAQ,IAAI;GACZ,QAAQ,IAAI;GACZ;EACD,CAAC;CACF,SAAS,OAAO;EACf,OAAO,MAAM,OAAgB,oCAAoC;CAClE;CAYD,OAAO;EAAE,SAAA,IATW,eAA6B;GAChD;GACA;GACA,UAAU;IACT,UAAU,SAAS;IACnB,QAAQ,SAAS;GAClB;EACD,CAEe;EAAG;CAAQ;AAC3B;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,4BAOrB,cACA,SACA,YACA,SACa;CAEb,IAAI,CAAC,cACJ,OAAO,QAAQ,KAAA,CAAS;CAGzB,MAAM,EAAE,SAAS,YAAY;CAG7B,IAAI,QAAQ,iBAIX,OAAO,QAAQ,gBACd,SACA,YAAY;EACX,MAAM,WAAW,MAAM,QAAQ,OAAO;EAGtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;EAGnC,OAAO;CACR,GACA,SAAS,EACV;CAID,MAAM,WAAW,MAAM,QAAQ,OAAO;CAEtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;CAInC,MAAM,QAAQ,MAAM;CAEpB,OAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"processAudits-BpRlPQMW.mjs","names":[],"sources":["../src/endpoints/processAudits.ts"],"sourcesContent":["import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditor,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type { CookieFn, Endpoint, HeaderFn } from './Endpoint';\n\n/**\n * Process declarative audit definitions after successful endpoint execution.\n * Similar to publishConstructEvents for events.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param response - The handler response to generate audit payloads from\n * @param serviceDiscovery - Service discovery for registering audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context (session, headers, cookies, services)\n * @param existingAuditor - Optional existing auditor instance (e.g., from handler context).\n * If provided, uses this auditor (with its stored transaction).\n * If not provided, creates a new auditor.\n */\nexport async function processEndpointAudits<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction\n\t>,\n\tresponse: InferStandardSchema<OutSchema>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n\texistingAuditor?: Auditor<TAuditAction>,\n): Promise<void> {\n\ttry {\n\t\tconst audits = endpoint.audits as MappedAudit<TAuditAction, OutSchema>[];\n\n\t\t// If we have an existing auditor (from handler context), we need to flush\n\t\t// any manual audits it collected, even if there are no declarative audits\n\t\tconst hasExistingRecords =\n\t\t\texistingAuditor && existingAuditor.getRecords().length > 0;\n\n\t\t// Skip if no declarative audits and no existing records to flush\n\t\tif (!audits?.length && !hasExistingRecords) {\n\t\t\tlogger.debug('No audits to process');\n\t\t\treturn;\n\t\t}\n\n\t\t// If no auditor storage service and we have things to process, warn\n\t\tif (!endpoint.auditorStorageService) {\n\t\t\tif (hasExistingRecords || audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Get or create auditor\n\t\tlet auditor: Auditor<TAuditAction>;\n\n\t\tif (existingAuditor) {\n\t\t\t// Use existing auditor (preserves stored transaction and manual audits)\n\t\t\tauditor = existingAuditor;\n\t\t\tlogger.debug('Using existing auditor from handler context');\n\t\t} else {\n\t\t\t// Create new auditor (backward compatibility)\n\t\t\tconst services = await serviceDiscovery.register([\n\t\t\t\tendpoint.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = services[\n\t\t\t\tendpoint.auditorStorageService.serviceName\n\t\t\t] as AuditStorage;\n\n\t\t\t// Extract actor if configured\n\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\tif (endpoint.actorExtractor) {\n\t\t\t\ttry {\n\t\t\t\t\tactor = await (\n\t\t\t\t\t\tendpoint.actorExtractor as ActorExtractor<\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\tTLogger\n\t\t\t\t\t\t>\n\t\t\t\t\t)({\n\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\theader: ctx.header,\n\t\t\t\t\t\tcookie: ctx.cookie,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t// Continue with system actor\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor,\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tendpoint: endpoint.route,\n\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Process each declarative audit\n\t\tif (audits?.length) {\n\t\t\tfor (const audit of audits) {\n\t\t\t\tlogger.debug({ audit: audit.type }, 'Processing declarative audit');\n\n\t\t\t\t// Check when condition\n\t\t\t\tif (audit.when && !audit.when(response as any)) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ audit: audit.type },\n\t\t\t\t\t\t'Audit skipped due to when condition',\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Extract payload\n\t\t\t\tconst payload = audit.payload(response as any);\n\n\t\t\t\t// Extract entityId if configured\n\t\t\t\tconst entityId = audit.entityId?.(response as any);\n\n\t\t\t\t// Record the audit\n\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\ttable: audit.table,\n\t\t\t\t\tentityId,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush audits to storage\n\t\t// Note: If existingAuditor has a stored transaction (via setTransaction),\n\t\t// flush() will use it automatically\n\t\tconst recordCount = auditor.getRecords().length;\n\t\tif (recordCount > 0) {\n\t\t\t// Check if auditor has a stored transaction (for logging purposes)\n\t\t\tconst trx =\n\t\t\t\t'getTransaction' in auditor\n\t\t\t\t\t? (auditor as { getTransaction(): unknown }).getTransaction()\n\t\t\t\t\t: undefined;\n\t\t\tlogger.debug(\n\t\t\t\t{ auditCount: recordCount, hasTransaction: !!trx },\n\t\t\t\t'Flushing audits',\n\t\t\t);\n\t\t\tawait auditor.flush();\n\t\t}\n\t} catch (error) {\n\t\tlogger.error(error as Error, 'Failed to process audits');\n\t\t// Don't rethrow - audit failures shouldn't fail the request\n\t}\n}\n\n/**\n * Context for audit-aware handler execution.\n */\nexport interface AuditExecutionContext<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\t/** The auditor instance for recording audits */\n\tauditor: Auditor<TAuditAction>;\n\t/** The audit storage instance */\n\tstorage: AuditStorage;\n}\n\n/**\n * Create audit context for handler execution.\n * Returns the auditor and storage for use in the handler.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param serviceDiscovery - Service discovery for getting audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context for actor extraction\n * @returns Audit context with auditor and storage, or undefined if not configured\n */\nexport async function createAuditContext<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n): Promise<AuditExecutionContext<TAuditAction> | undefined> {\n\tif (!endpoint.auditorStorageService) {\n\t\treturn undefined;\n\t}\n\n\tconst services = await serviceDiscovery.register([\n\t\tendpoint.auditorStorageService,\n\t]);\n\tconst storage = services[\n\t\tendpoint.auditorStorageService.serviceName\n\t] as AuditStorage;\n\n\t// Extract actor if configured\n\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\tif (endpoint.actorExtractor) {\n\t\ttry {\n\t\t\tactor = await (\n\t\t\t\tendpoint.actorExtractor as ActorExtractor<TServices, TSession, TLogger>\n\t\t\t)({\n\t\t\t\tservices: ctx.services as any,\n\t\t\t\tsession: ctx.session,\n\t\t\t\theader: ctx.header,\n\t\t\t\tcookie: ctx.cookie,\n\t\t\t\tlogger,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t}\n\t}\n\n\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\tactor,\n\t\tstorage,\n\t\tmetadata: {\n\t\t\tendpoint: endpoint.route,\n\t\t\tmethod: endpoint.method,\n\t\t},\n\t});\n\n\treturn { auditor, storage };\n}\n\n/**\n * Options for executeWithAuditTransaction.\n */\nexport interface ExecuteWithAuditTransactionOptions {\n\t/**\n\t * Database connection to use for the transaction.\n\t * If this is already a transaction, it will be reused instead of creating a nested one.\n\t * If not provided, the storage's internal database is used.\n\t */\n\tdb?: unknown;\n}\n\n/**\n * Execute a handler with automatic audit transaction support.\n * If the audit storage provides a withTransaction method, wraps execution\n * in a transaction so audits are atomic with handler's database operations.\n *\n * This is database-agnostic - each storage implementation provides its own\n * transaction handling based on the underlying database (Kysely, Drizzle, etc.).\n *\n * If the db parameter is provided and is already a transaction, the storage\n * will reuse it instead of creating a nested transaction (similar to\n * packages/db/src/kysely.ts#withTransaction).\n *\n * @param auditContext - The audit context from createAuditContext\n * @param handler - The handler function to execute (receives auditor)\n * @param onComplete - Called after handler with response, to process declarative audits\n * @param options - Optional configuration including database connection\n * @returns The handler result\n */\nexport async function executeWithAuditTransaction<\n\tT,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tauditContext: AuditExecutionContext<TAuditAction> | undefined,\n\thandler: (auditor?: Auditor<TAuditAction>) => Promise<T>,\n\tonComplete?: (response: T, auditor: Auditor<TAuditAction>) => Promise<void>,\n\toptions?: ExecuteWithAuditTransactionOptions,\n): Promise<T> {\n\t// No audit context - just run handler\n\tif (!auditContext) {\n\t\treturn handler(undefined);\n\t}\n\n\tconst { auditor, storage } = auditContext;\n\n\t// Check if storage provides a transaction wrapper\n\tif (storage.withTransaction) {\n\t\t// Wrap in transaction - audits are atomic with handler operations\n\t\t// The storage's withTransaction handles setTransaction and flush\n\t\t// Pass db so existing transactions are reused\n\t\treturn storage.withTransaction(\n\t\t\tauditor,\n\t\t\tasync () => {\n\t\t\t\tconst response = await handler(auditor);\n\n\t\t\t\t// Process declarative audits within the transaction\n\t\t\t\tif (onComplete) {\n\t\t\t\t\tawait onComplete(response, auditor);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t},\n\t\t\toptions?.db,\n\t\t);\n\t}\n\n\t// No transaction support - run handler and flush audits after\n\tconst response = await handler(auditor);\n\n\tif (onComplete) {\n\t\tawait onComplete(response, auditor);\n\t}\n\n\t// Flush audits (no transaction)\n\tawait auditor.flush();\n\n\treturn response;\n}\n"],"mappings":";;;;;;;;;;;;AAgNA,eAAsB,mBAarB,UAcA,kBACA,QACA,KAM2D;CAC3D,IAAI,CAAC,SAAS,uBACb;CAMD,MAAM,WAAU,MAHO,iBAAiB,SAAS,CAChD,SAAS,qBACV,CAAC,EAAA,CAEA,SAAS,sBAAsB;CAIhC,IAAI,QAAoB;EAAE,IAAI;EAAU,MAAM;CAAS;CACvD,IAAI,SAAS,gBACZ,IAAI;EACH,QAAQ,MACP,SAAS,eACR;GACD,UAAU,IAAI;GACd,SAAS,IAAI;GACb,QAAQ,IAAI;GACZ,QAAQ,IAAI;GACZ;EACD,CAAC;CACF,SAAS,OAAO;EACf,OAAO,MAAM,OAAgB,oCAAoC;CAClE;CAYD,OAAO;EAAE,SAAA,IATW,eAA6B;GAChD;GACA;GACA,UAAU;IACT,UAAU,SAAS;IACnB,QAAQ,SAAS;GAClB;EACD,CAEe;EAAG;CAAQ;AAC3B;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,4BAOrB,cACA,SACA,YACA,SACa;CAEb,IAAI,CAAC,cACJ,OAAO,QAAQ,KAAA,CAAS;CAGzB,MAAM,EAAE,SAAS,YAAY;CAG7B,IAAI,QAAQ,iBAIX,OAAO,QAAQ,gBACd,SACA,YAAY;EACX,MAAM,WAAW,MAAM,QAAQ,OAAO;EAGtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;EAGnC,OAAO;CACR,GACA,SAAS,EACV;CAID,MAAM,WAAW,MAAM,QAAQ,OAAO;CAEtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;CAInC,MAAM,QAAQ,MAAM;CAEpB,OAAO;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processAudits-D_2W5x8k.cjs","names":["DefaultAuditor"],"sources":["../src/endpoints/processAudits.ts"],"sourcesContent":["import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditor,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type { CookieFn, Endpoint, HeaderFn } from './Endpoint';\n\n/**\n * Process declarative audit definitions after successful endpoint execution.\n * Similar to publishConstructEvents for events.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param response - The handler response to generate audit payloads from\n * @param serviceDiscovery - Service discovery for registering audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context (session, headers, cookies, services)\n * @param existingAuditor - Optional existing auditor instance (e.g., from handler context).\n * If provided, uses this auditor (with its stored transaction).\n * If not provided, creates a new auditor.\n */\nexport async function processEndpointAudits<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tany,\n\t\tany,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction\n\t>,\n\tresponse: InferStandardSchema<OutSchema>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n\texistingAuditor?: Auditor<TAuditAction>,\n): Promise<void> {\n\ttry {\n\t\tconst audits = endpoint.audits as MappedAudit<TAuditAction, OutSchema>[];\n\n\t\t// If we have an existing auditor (from handler context), we need to flush\n\t\t// any manual audits it collected, even if there are no declarative audits\n\t\tconst hasExistingRecords =\n\t\t\texistingAuditor && existingAuditor.getRecords().length > 0;\n\n\t\t// Skip if no declarative audits and no existing records to flush\n\t\tif (!audits?.length && !hasExistingRecords) {\n\t\t\tlogger.debug('No audits to process');\n\t\t\treturn;\n\t\t}\n\n\t\t// If no auditor storage service and we have things to process, warn\n\t\tif (!endpoint.auditorStorageService) {\n\t\t\tif (hasExistingRecords || audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Get or create auditor\n\t\tlet auditor: Auditor<TAuditAction>;\n\n\t\tif (existingAuditor) {\n\t\t\t// Use existing auditor (preserves stored transaction and manual audits)\n\t\t\tauditor = existingAuditor;\n\t\t\tlogger.debug('Using existing auditor from handler context');\n\t\t} else {\n\t\t\t// Create new auditor (backward compatibility)\n\t\t\tconst services = await serviceDiscovery.register([\n\t\t\t\tendpoint.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = services[\n\t\t\t\tendpoint.auditorStorageService.serviceName\n\t\t\t] as AuditStorage;\n\n\t\t\t// Extract actor if configured\n\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\tif (endpoint.actorExtractor) {\n\t\t\t\ttry {\n\t\t\t\t\tactor = await (\n\t\t\t\t\t\tendpoint.actorExtractor as ActorExtractor<\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\tTLogger\n\t\t\t\t\t\t>\n\t\t\t\t\t)({\n\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\theader: ctx.header,\n\t\t\t\t\t\tcookie: ctx.cookie,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t// Continue with system actor\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor,\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tendpoint: endpoint.route,\n\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Process each declarative audit\n\t\tif (audits?.length) {\n\t\t\tfor (const audit of audits) {\n\t\t\t\tlogger.debug({ audit: audit.type }, 'Processing declarative audit');\n\n\t\t\t\t// Check when condition\n\t\t\t\tif (audit.when && !audit.when(response as any)) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ audit: audit.type },\n\t\t\t\t\t\t'Audit skipped due to when condition',\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Extract payload\n\t\t\t\tconst payload = audit.payload(response as any);\n\n\t\t\t\t// Extract entityId if configured\n\t\t\t\tconst entityId = audit.entityId?.(response as any);\n\n\t\t\t\t// Record the audit\n\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\ttable: audit.table,\n\t\t\t\t\tentityId,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush audits to storage\n\t\t// Note: If existingAuditor has a stored transaction (via setTransaction),\n\t\t// flush() will use it automatically\n\t\tconst recordCount = auditor.getRecords().length;\n\t\tif (recordCount > 0) {\n\t\t\t// Check if auditor has a stored transaction (for logging purposes)\n\t\t\tconst trx =\n\t\t\t\t'getTransaction' in auditor\n\t\t\t\t\t? (auditor as { getTransaction(): unknown }).getTransaction()\n\t\t\t\t\t: undefined;\n\t\t\tlogger.debug(\n\t\t\t\t{ auditCount: recordCount, hasTransaction: !!trx },\n\t\t\t\t'Flushing audits',\n\t\t\t);\n\t\t\tawait auditor.flush();\n\t\t}\n\t} catch (error) {\n\t\tlogger.error(error as Error, 'Failed to process audits');\n\t\t// Don't rethrow - audit failures shouldn't fail the request\n\t}\n}\n\n/**\n * Context for audit-aware handler execution.\n */\nexport interface AuditExecutionContext<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\t/** The auditor instance for recording audits */\n\tauditor: Auditor<TAuditAction>;\n\t/** The audit storage instance */\n\tstorage: AuditStorage;\n}\n\n/**\n * Create audit context for handler execution.\n * Returns the auditor and storage for use in the handler.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param serviceDiscovery - Service discovery for getting audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context for actor extraction\n * @returns Audit context with auditor and storage, or undefined if not configured\n */\nexport async function createAuditContext<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tany,\n\t\tany,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n): Promise<AuditExecutionContext<TAuditAction> | undefined> {\n\tif (!endpoint.auditorStorageService) {\n\t\treturn undefined;\n\t}\n\n\tconst services = await serviceDiscovery.register([\n\t\tendpoint.auditorStorageService,\n\t]);\n\tconst storage = services[\n\t\tendpoint.auditorStorageService.serviceName\n\t] as AuditStorage;\n\n\t// Extract actor if configured\n\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\tif (endpoint.actorExtractor) {\n\t\ttry {\n\t\t\tactor = await (\n\t\t\t\tendpoint.actorExtractor as ActorExtractor<TServices, TSession, TLogger>\n\t\t\t)({\n\t\t\t\tservices: ctx.services as any,\n\t\t\t\tsession: ctx.session,\n\t\t\t\theader: ctx.header,\n\t\t\t\tcookie: ctx.cookie,\n\t\t\t\tlogger,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t}\n\t}\n\n\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\tactor,\n\t\tstorage,\n\t\tmetadata: {\n\t\t\tendpoint: endpoint.route,\n\t\t\tmethod: endpoint.method,\n\t\t},\n\t});\n\n\treturn { auditor, storage };\n}\n\n/**\n * Options for executeWithAuditTransaction.\n */\nexport interface ExecuteWithAuditTransactionOptions {\n\t/**\n\t * Database connection to use for the transaction.\n\t * If this is already a transaction, it will be reused instead of creating a nested one.\n\t * If not provided, the storage's internal database is used.\n\t */\n\tdb?: unknown;\n}\n\n/**\n * Execute a handler with automatic audit transaction support.\n * If the audit storage provides a withTransaction method, wraps execution\n * in a transaction so audits are atomic with handler's database operations.\n *\n * This is database-agnostic - each storage implementation provides its own\n * transaction handling based on the underlying database (Kysely, Drizzle, etc.).\n *\n * If the db parameter is provided and is already a transaction, the storage\n * will reuse it instead of creating a nested transaction (similar to\n * packages/db/src/kysely.ts#withTransaction).\n *\n * @param auditContext - The audit context from createAuditContext\n * @param handler - The handler function to execute (receives auditor)\n * @param onComplete - Called after handler with response, to process declarative audits\n * @param options - Optional configuration including database connection\n * @returns The handler result\n */\nexport async function executeWithAuditTransaction<\n\tT,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tauditContext: AuditExecutionContext<TAuditAction> | undefined,\n\thandler: (auditor?: Auditor<TAuditAction>) => Promise<T>,\n\tonComplete?: (response: T, auditor: Auditor<TAuditAction>) => Promise<void>,\n\toptions?: ExecuteWithAuditTransactionOptions,\n): Promise<T> {\n\t// No audit context - just run handler\n\tif (!auditContext) {\n\t\treturn handler(undefined);\n\t}\n\n\tconst { auditor, storage } = auditContext;\n\n\t// Check if storage provides a transaction wrapper\n\tif (storage.withTransaction) {\n\t\t// Wrap in transaction - audits are atomic with handler operations\n\t\t// The storage's withTransaction handles setTransaction and flush\n\t\t// Pass db so existing transactions are reused\n\t\treturn storage.withTransaction(\n\t\t\tauditor,\n\t\t\tasync () => {\n\t\t\t\tconst response = await handler(auditor);\n\n\t\t\t\t// Process declarative audits within the transaction\n\t\t\t\tif (onComplete) {\n\t\t\t\t\tawait onComplete(response, auditor);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t},\n\t\t\toptions?.db,\n\t\t);\n\t}\n\n\t// No transaction support - run handler and flush audits after\n\tconst response = await handler(auditor);\n\n\tif (onComplete) {\n\t\tawait onComplete(response, auditor);\n\t}\n\n\t// Flush audits (no transaction)\n\tawait auditor.flush();\n\n\treturn response;\n}\n"],"mappings":";;;;;;;;;;;;AAkNA,eAAsB,mBAarB,UAgBA,kBACA,QACA,KAM2D;CAC3D,IAAI,CAAC,SAAS,uBACb;CAMD,MAAM,WAAU,MAHO,iBAAiB,SAAS,CAChD,SAAS,qBACV,CAAC,EAAA,CAEA,SAAS,sBAAsB;CAIhC,IAAI,QAAoB;EAAE,IAAI;EAAU,MAAM;CAAS;CACvD,IAAI,SAAS,gBACZ,IAAI;EACH,QAAQ,MACP,SAAS,eACR;GACD,UAAU,IAAI;GACd,SAAS,IAAI;GACb,QAAQ,IAAI;GACZ,QAAQ,IAAI;GACZ;EACD,CAAC;CACF,SAAS,OAAO;EACf,OAAO,MAAM,OAAgB,oCAAoC;CAClE;CAYD,OAAO;EAAE,SAAA,IATWA,iBAAAA,eAA6B;GAChD;GACA;GACA,UAAU;IACT,UAAU,SAAS;IACnB,QAAQ,SAAS;GAClB;EACD,CAEe;EAAG;CAAQ;AAC3B;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,4BAOrB,cACA,SACA,YACA,SACa;CAEb,IAAI,CAAC,cACJ,OAAO,QAAQ,KAAA,CAAS;CAGzB,MAAM,EAAE,SAAS,YAAY;CAG7B,IAAI,QAAQ,iBAIX,OAAO,QAAQ,gBACd,SACA,YAAY;EACX,MAAM,WAAW,MAAM,QAAQ,OAAO;EAGtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;EAGnC,OAAO;CACR,GACA,SAAS,EACV;CAID,MAAM,WAAW,MAAM,QAAQ,OAAO;CAEtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;CAInC,MAAM,QAAQ,MAAM;CAEpB,OAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"processAudits-D_2W5x8k.cjs","names":["DefaultAuditor"],"sources":["../src/endpoints/processAudits.ts"],"sourcesContent":["import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditor,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport { DefaultAuditor } from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type { CookieFn, Endpoint, HeaderFn } from './Endpoint';\n\n/**\n * Process declarative audit definitions after successful endpoint execution.\n * Similar to publishConstructEvents for events.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param response - The handler response to generate audit payloads from\n * @param serviceDiscovery - Service discovery for registering audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context (session, headers, cookies, services)\n * @param existingAuditor - Optional existing auditor instance (e.g., from handler context).\n * If provided, uses this auditor (with its stored transaction).\n * If not provided, creates a new auditor.\n */\nexport async function processEndpointAudits<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction\n\t>,\n\tresponse: InferStandardSchema<OutSchema>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n\texistingAuditor?: Auditor<TAuditAction>,\n): Promise<void> {\n\ttry {\n\t\tconst audits = endpoint.audits as MappedAudit<TAuditAction, OutSchema>[];\n\n\t\t// If we have an existing auditor (from handler context), we need to flush\n\t\t// any manual audits it collected, even if there are no declarative audits\n\t\tconst hasExistingRecords =\n\t\t\texistingAuditor && existingAuditor.getRecords().length > 0;\n\n\t\t// Skip if no declarative audits and no existing records to flush\n\t\tif (!audits?.length && !hasExistingRecords) {\n\t\t\tlogger.debug('No audits to process');\n\t\t\treturn;\n\t\t}\n\n\t\t// If no auditor storage service and we have things to process, warn\n\t\tif (!endpoint.auditorStorageService) {\n\t\t\tif (hasExistingRecords || audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Get or create auditor\n\t\tlet auditor: Auditor<TAuditAction>;\n\n\t\tif (existingAuditor) {\n\t\t\t// Use existing auditor (preserves stored transaction and manual audits)\n\t\t\tauditor = existingAuditor;\n\t\t\tlogger.debug('Using existing auditor from handler context');\n\t\t} else {\n\t\t\t// Create new auditor (backward compatibility)\n\t\t\tconst services = await serviceDiscovery.register([\n\t\t\t\tendpoint.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = services[\n\t\t\t\tendpoint.auditorStorageService.serviceName\n\t\t\t] as AuditStorage;\n\n\t\t\t// Extract actor if configured\n\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\tif (endpoint.actorExtractor) {\n\t\t\t\ttry {\n\t\t\t\t\tactor = await (\n\t\t\t\t\t\tendpoint.actorExtractor as ActorExtractor<\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\tTLogger\n\t\t\t\t\t\t>\n\t\t\t\t\t)({\n\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\theader: ctx.header,\n\t\t\t\t\t\tcookie: ctx.cookie,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t// Continue with system actor\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor,\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tendpoint: endpoint.route,\n\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Process each declarative audit\n\t\tif (audits?.length) {\n\t\t\tfor (const audit of audits) {\n\t\t\t\tlogger.debug({ audit: audit.type }, 'Processing declarative audit');\n\n\t\t\t\t// Check when condition\n\t\t\t\tif (audit.when && !audit.when(response as any)) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ audit: audit.type },\n\t\t\t\t\t\t'Audit skipped due to when condition',\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Extract payload\n\t\t\t\tconst payload = audit.payload(response as any);\n\n\t\t\t\t// Extract entityId if configured\n\t\t\t\tconst entityId = audit.entityId?.(response as any);\n\n\t\t\t\t// Record the audit\n\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\ttable: audit.table,\n\t\t\t\t\tentityId,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush audits to storage\n\t\t// Note: If existingAuditor has a stored transaction (via setTransaction),\n\t\t// flush() will use it automatically\n\t\tconst recordCount = auditor.getRecords().length;\n\t\tif (recordCount > 0) {\n\t\t\t// Check if auditor has a stored transaction (for logging purposes)\n\t\t\tconst trx =\n\t\t\t\t'getTransaction' in auditor\n\t\t\t\t\t? (auditor as { getTransaction(): unknown }).getTransaction()\n\t\t\t\t\t: undefined;\n\t\t\tlogger.debug(\n\t\t\t\t{ auditCount: recordCount, hasTransaction: !!trx },\n\t\t\t\t'Flushing audits',\n\t\t\t);\n\t\t\tawait auditor.flush();\n\t\t}\n\t} catch (error) {\n\t\tlogger.error(error as Error, 'Failed to process audits');\n\t\t// Don't rethrow - audit failures shouldn't fail the request\n\t}\n}\n\n/**\n * Context for audit-aware handler execution.\n */\nexport interface AuditExecutionContext<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\t/** The auditor instance for recording audits */\n\tauditor: Auditor<TAuditAction>;\n\t/** The audit storage instance */\n\tstorage: AuditStorage;\n}\n\n/**\n * Create audit context for handler execution.\n * Returns the auditor and storage for use in the handler.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param serviceDiscovery - Service discovery for getting audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context for actor extraction\n * @returns Audit context with auditor and storage, or undefined if not configured\n */\nexport async function createAuditContext<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n): Promise<AuditExecutionContext<TAuditAction> | undefined> {\n\tif (!endpoint.auditorStorageService) {\n\t\treturn undefined;\n\t}\n\n\tconst services = await serviceDiscovery.register([\n\t\tendpoint.auditorStorageService,\n\t]);\n\tconst storage = services[\n\t\tendpoint.auditorStorageService.serviceName\n\t] as AuditStorage;\n\n\t// Extract actor if configured\n\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\tif (endpoint.actorExtractor) {\n\t\ttry {\n\t\t\tactor = await (\n\t\t\t\tendpoint.actorExtractor as ActorExtractor<TServices, TSession, TLogger>\n\t\t\t)({\n\t\t\t\tservices: ctx.services as any,\n\t\t\t\tsession: ctx.session,\n\t\t\t\theader: ctx.header,\n\t\t\t\tcookie: ctx.cookie,\n\t\t\t\tlogger,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t}\n\t}\n\n\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\tactor,\n\t\tstorage,\n\t\tmetadata: {\n\t\t\tendpoint: endpoint.route,\n\t\t\tmethod: endpoint.method,\n\t\t},\n\t});\n\n\treturn { auditor, storage };\n}\n\n/**\n * Options for executeWithAuditTransaction.\n */\nexport interface ExecuteWithAuditTransactionOptions {\n\t/**\n\t * Database connection to use for the transaction.\n\t * If this is already a transaction, it will be reused instead of creating a nested one.\n\t * If not provided, the storage's internal database is used.\n\t */\n\tdb?: unknown;\n}\n\n/**\n * Execute a handler with automatic audit transaction support.\n * If the audit storage provides a withTransaction method, wraps execution\n * in a transaction so audits are atomic with handler's database operations.\n *\n * This is database-agnostic - each storage implementation provides its own\n * transaction handling based on the underlying database (Kysely, Drizzle, etc.).\n *\n * If the db parameter is provided and is already a transaction, the storage\n * will reuse it instead of creating a nested transaction (similar to\n * packages/db/src/kysely.ts#withTransaction).\n *\n * @param auditContext - The audit context from createAuditContext\n * @param handler - The handler function to execute (receives auditor)\n * @param onComplete - Called after handler with response, to process declarative audits\n * @param options - Optional configuration including database connection\n * @returns The handler result\n */\nexport async function executeWithAuditTransaction<\n\tT,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tauditContext: AuditExecutionContext<TAuditAction> | undefined,\n\thandler: (auditor?: Auditor<TAuditAction>) => Promise<T>,\n\tonComplete?: (response: T, auditor: Auditor<TAuditAction>) => Promise<void>,\n\toptions?: ExecuteWithAuditTransactionOptions,\n): Promise<T> {\n\t// No audit context - just run handler\n\tif (!auditContext) {\n\t\treturn handler(undefined);\n\t}\n\n\tconst { auditor, storage } = auditContext;\n\n\t// Check if storage provides a transaction wrapper\n\tif (storage.withTransaction) {\n\t\t// Wrap in transaction - audits are atomic with handler operations\n\t\t// The storage's withTransaction handles setTransaction and flush\n\t\t// Pass db so existing transactions are reused\n\t\treturn storage.withTransaction(\n\t\t\tauditor,\n\t\t\tasync () => {\n\t\t\t\tconst response = await handler(auditor);\n\n\t\t\t\t// Process declarative audits within the transaction\n\t\t\t\tif (onComplete) {\n\t\t\t\t\tawait onComplete(response, auditor);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t},\n\t\t\toptions?.db,\n\t\t);\n\t}\n\n\t// No transaction support - run handler and flush audits after\n\tconst response = await handler(auditor);\n\n\tif (onComplete) {\n\t\tawait onComplete(response, auditor);\n\t}\n\n\t// Flush audits (no transaction)\n\tawait auditor.flush();\n\n\treturn response;\n}\n"],"mappings":";;;;;;;;;;;;AAgNA,eAAsB,mBAarB,UAcA,kBACA,QACA,KAM2D;CAC3D,IAAI,CAAC,SAAS,uBACb;CAMD,MAAM,WAAU,MAHO,iBAAiB,SAAS,CAChD,SAAS,qBACV,CAAC,EAAA,CAEA,SAAS,sBAAsB;CAIhC,IAAI,QAAoB;EAAE,IAAI;EAAU,MAAM;CAAS;CACvD,IAAI,SAAS,gBACZ,IAAI;EACH,QAAQ,MACP,SAAS,eACR;GACD,UAAU,IAAI;GACd,SAAS,IAAI;GACb,QAAQ,IAAI;GACZ,QAAQ,IAAI;GACZ;EACD,CAAC;CACF,SAAS,OAAO;EACf,OAAO,MAAM,OAAgB,oCAAoC;CAClE;CAYD,OAAO;EAAE,SAAA,IATWA,iBAAAA,eAA6B;GAChD;GACA;GACA,UAAU;IACT,UAAU,SAAS;IACnB,QAAQ,SAAS;GAClB;EACD,CAEe;EAAG;CAAQ;AAC3B;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,4BAOrB,cACA,SACA,YACA,SACa;CAEb,IAAI,CAAC,cACJ,OAAO,QAAQ,KAAA,CAAS;CAGzB,MAAM,EAAE,SAAS,YAAY;CAG7B,IAAI,QAAQ,iBAIX,OAAO,QAAQ,gBACd,SACA,YAAY;EACX,MAAM,WAAW,MAAM,QAAQ,OAAO;EAGtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;EAGnC,OAAO;CACR,GACA,SAAS,EACV;CAID,MAAM,WAAW,MAAM,QAAQ,OAAO;CAEtC,IAAI,YACH,MAAM,WAAW,UAAU,OAAO;CAInC,MAAM,QAAQ,MAAM;CAEpB,OAAO;AACR"}
|
package/dist/queue/index.cjs
CHANGED
|
@@ -1,80 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
const
|
|
4
|
-
const require_Queue = require("../Queue-B7yRXQmL.cjs");
|
|
5
|
-
let _geekmidas_logger_console = require("@geekmidas/logger/console");
|
|
6
|
-
//#region src/queue/QueueBuilder.ts
|
|
7
|
-
/**
|
|
8
|
-
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
|
9
|
-
* Services are an array (sniffed for required env vars); `message` is the typed
|
|
10
|
-
* job payload; `handle` is the single consumer. The queue name is captured as a
|
|
11
|
-
* literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.
|
|
12
|
-
*/
|
|
13
|
-
var QueueBuilder = class {
|
|
14
|
-
_name;
|
|
15
|
-
_messageSchema;
|
|
16
|
-
_timeout = 3e4;
|
|
17
|
-
_batchSize;
|
|
18
|
-
_fifo;
|
|
19
|
-
_services = [];
|
|
20
|
-
/** The construct ids `.dependsOn()` named — what the manifest records. */
|
|
21
|
-
_constructs = [];
|
|
22
|
-
_logger = _geekmidas_logger_console.DEFAULT_LOGGER;
|
|
23
|
-
/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */
|
|
24
|
-
queue(name) {
|
|
25
|
-
return require_clone.cloneWith(this, { _name: name });
|
|
26
|
-
}
|
|
27
|
-
timeout(timeout) {
|
|
28
|
-
return require_clone.cloneWith(this, { _timeout: timeout });
|
|
29
|
-
}
|
|
30
|
-
/** SQS event-source batch size (deployed). */
|
|
31
|
-
batchSize(batchSize) {
|
|
32
|
-
return require_clone.cloneWith(this, { _batchSize: batchSize });
|
|
33
|
-
}
|
|
34
|
-
/** Mark the queue as FIFO (deployed). */
|
|
35
|
-
fifo(fifo = true) {
|
|
36
|
-
return require_clone.cloneWith(this, { _fifo: fifo });
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Depend on constructs — a database, a bucket, a mail sender, a queue, a
|
|
40
|
-
* topic.
|
|
41
|
-
*
|
|
42
|
-
* It records the edge and dissolves each construct's client into the
|
|
43
|
-
* handler's service record under the construct's own id, so
|
|
44
|
-
* `.dependsOn([uploads])` is what makes `services.uploads` exist and type.
|
|
45
|
-
*
|
|
46
|
-
* Constructs only. A `Service` does not match the shape, which is what keeps
|
|
47
|
-
* env sniffing confined to `.services()` and the explicit lift.
|
|
48
|
-
*/
|
|
49
|
-
dependsOn(constructs) {
|
|
50
|
-
const services = require_construct_interface.servicesOf(constructs);
|
|
51
|
-
return require_clone.cloneWith(this, {
|
|
52
|
-
_services: [...this._services, ...services],
|
|
53
|
-
_constructs: require_construct_interface.idsOf(constructs, this._constructs)
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
services(services) {
|
|
57
|
-
return require_clone.cloneWith(this, { _services: [...this._services, ...services] });
|
|
58
|
-
}
|
|
59
|
-
logger(logger) {
|
|
60
|
-
return require_clone.cloneWith(this, { _logger: logger });
|
|
61
|
-
}
|
|
62
|
-
/** The typed message (job) payload the queue carries. */
|
|
63
|
-
message(schema) {
|
|
64
|
-
return require_clone.cloneWith(this, { _messageSchema: schema });
|
|
65
|
-
}
|
|
66
|
-
handle(fn) {
|
|
67
|
-
if (!this._name) throw new Error("Queue requires a name — call .queue(name) before .handle().");
|
|
68
|
-
if (!this._messageSchema) throw new Error("Queue requires a message schema — call .message(schema) before .handle().");
|
|
69
|
-
return new require_Queue.Queue(this._name, fn, this._messageSchema, this._timeout, this._services, this._logger, this._batchSize, this._fifo, this._constructs);
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
//#endregion
|
|
73
|
-
//#region src/queue/index.ts
|
|
74
|
-
const q = new QueueBuilder();
|
|
75
|
-
//#endregion
|
|
2
|
+
const require_Queue = require("../Queue-Ckmudcm8.cjs");
|
|
3
|
+
const require_QueueBuilder = require("../QueueBuilder-CJNcv4dy.cjs");
|
|
76
4
|
exports.Queue = require_Queue.Queue;
|
|
77
|
-
exports.
|
|
78
|
-
exports.
|
|
79
|
-
|
|
80
|
-
//# sourceMappingURL=index.cjs.map
|
|
5
|
+
exports.QueueNeedsMessage = require_QueueBuilder.QueueNeedsMessage;
|
|
6
|
+
exports.QueueNeedsName = require_QueueBuilder.QueueNeedsName;
|
package/dist/queue/index.d.cts
CHANGED
|
@@ -1,53 +1,3 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { Logger as Logger$1 } from "@geekmidas/logger";
|
|
5
|
-
import { Service } from "@geekmidas/services";
|
|
6
|
-
//#region src/queue/QueueBuilder.d.ts
|
|
7
|
-
/**
|
|
8
|
-
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
|
9
|
-
* Services are an array (sniffed for required env vars); `message` is the typed
|
|
10
|
-
* job payload; `handle` is the single consumer. The queue name is captured as a
|
|
11
|
-
* literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.
|
|
12
|
-
*/
|
|
13
|
-
export declare class QueueBuilder<TName extends string = string, TMessage extends StandardSchemaV1 | undefined = undefined, TServices extends Service[] = [], TLogger extends Logger$1 = Logger$1> {
|
|
14
|
-
private _name?;
|
|
15
|
-
private _messageSchema?;
|
|
16
|
-
private _timeout;
|
|
17
|
-
private _batchSize?;
|
|
18
|
-
private _fifo?;
|
|
19
|
-
private _services;
|
|
20
|
-
/** The construct ids `.dependsOn()` named — what the manifest records. */
|
|
21
|
-
_constructs: string[];
|
|
22
|
-
private _logger;
|
|
23
|
-
/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */
|
|
24
|
-
queue<T extends string>(name: T): QueueBuilder<T, TMessage, TServices, TLogger>;
|
|
25
|
-
timeout(timeout: number): this;
|
|
26
|
-
/** SQS event-source batch size (deployed). */
|
|
27
|
-
batchSize(batchSize: number): this;
|
|
28
|
-
/** Mark the queue as FIFO (deployed). */
|
|
29
|
-
fifo(fifo?: boolean): this;
|
|
30
|
-
/**
|
|
31
|
-
* Depend on constructs — a database, a bucket, a mail sender, a queue, a
|
|
32
|
-
* topic.
|
|
33
|
-
*
|
|
34
|
-
* It records the edge and dissolves each construct's client into the
|
|
35
|
-
* handler's service record under the construct's own id, so
|
|
36
|
-
* `.dependsOn([uploads])` is what makes `services.uploads` exist and type.
|
|
37
|
-
*
|
|
38
|
-
* Constructs only. A `Service` does not match the shape, which is what keeps
|
|
39
|
-
* env sniffing confined to `.services()` and the explicit lift.
|
|
40
|
-
*/
|
|
41
|
-
dependsOn<const T extends readonly Consumable[]>(constructs: T): QueueBuilder<TName, TMessage, [...TServices, ...ServicesOf<T>], TLogger>;
|
|
42
|
-
services<T extends Service[]>(services: T): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger>;
|
|
43
|
-
logger<T extends Logger$1>(logger: T): QueueBuilder<TName, TMessage, TServices, T>;
|
|
44
|
-
/** The typed message (job) payload the queue carries. */
|
|
45
|
-
message<T extends StandardSchemaV1>(schema: T): QueueBuilder<TName, T, TServices, TLogger>;
|
|
46
|
-
handle(fn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>): Queue<TName, NonNullable<TMessage>, TServices, TLogger>;
|
|
47
|
-
}
|
|
48
|
-
//#endregion
|
|
49
|
-
//#region src/queue/index.d.ts
|
|
50
|
-
export declare const q: QueueBuilder<string, undefined, [], Logger>;
|
|
51
|
-
//#endregion
|
|
52
|
-
export { Queue, type QueueContext, type QueueHandler, type QueueMessage };
|
|
53
|
-
//# sourceMappingURL=index.d.cts.map
|
|
1
|
+
import { i as QueueMessage, n as QueueContext, r as QueueHandler, t as Queue } from "../Queue-CpQIGB_2.cjs";
|
|
2
|
+
import { n as QueueNeedsMessage, r as QueueNeedsName } from "../QueueBuilder-XEnnOWGe.cjs";
|
|
3
|
+
export { Queue, type QueueContext, type QueueHandler, type QueueMessage, QueueNeedsMessage, QueueNeedsName };
|
package/dist/queue/index.d.mts
CHANGED
|
@@ -1,53 +1,3 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { Service } from "@geekmidas/services";
|
|
5
|
-
import { Logger as Logger$1 } from "@geekmidas/logger";
|
|
6
|
-
//#region src/queue/QueueBuilder.d.ts
|
|
7
|
-
/**
|
|
8
|
-
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
|
9
|
-
* Services are an array (sniffed for required env vars); `message` is the typed
|
|
10
|
-
* job payload; `handle` is the single consumer. The queue name is captured as a
|
|
11
|
-
* literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.
|
|
12
|
-
*/
|
|
13
|
-
export declare class QueueBuilder<TName extends string = string, TMessage extends StandardSchemaV1 | undefined = undefined, TServices extends Service[] = [], TLogger extends Logger$1 = Logger$1> {
|
|
14
|
-
private _name?;
|
|
15
|
-
private _messageSchema?;
|
|
16
|
-
private _timeout;
|
|
17
|
-
private _batchSize?;
|
|
18
|
-
private _fifo?;
|
|
19
|
-
private _services;
|
|
20
|
-
/** The construct ids `.dependsOn()` named — what the manifest records. */
|
|
21
|
-
_constructs: string[];
|
|
22
|
-
private _logger;
|
|
23
|
-
/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */
|
|
24
|
-
queue<T extends string>(name: T): QueueBuilder<T, TMessage, TServices, TLogger>;
|
|
25
|
-
timeout(timeout: number): this;
|
|
26
|
-
/** SQS event-source batch size (deployed). */
|
|
27
|
-
batchSize(batchSize: number): this;
|
|
28
|
-
/** Mark the queue as FIFO (deployed). */
|
|
29
|
-
fifo(fifo?: boolean): this;
|
|
30
|
-
/**
|
|
31
|
-
* Depend on constructs — a database, a bucket, a mail sender, a queue, a
|
|
32
|
-
* topic.
|
|
33
|
-
*
|
|
34
|
-
* It records the edge and dissolves each construct's client into the
|
|
35
|
-
* handler's service record under the construct's own id, so
|
|
36
|
-
* `.dependsOn([uploads])` is what makes `services.uploads` exist and type.
|
|
37
|
-
*
|
|
38
|
-
* Constructs only. A `Service` does not match the shape, which is what keeps
|
|
39
|
-
* env sniffing confined to `.services()` and the explicit lift.
|
|
40
|
-
*/
|
|
41
|
-
dependsOn<const T extends readonly Consumable[]>(constructs: T): QueueBuilder<TName, TMessage, [...TServices, ...ServicesOf<T>], TLogger>;
|
|
42
|
-
services<T extends Service[]>(services: T): QueueBuilder<TName, TMessage, [...TServices, ...T], TLogger>;
|
|
43
|
-
logger<T extends Logger$1>(logger: T): QueueBuilder<TName, TMessage, TServices, T>;
|
|
44
|
-
/** The typed message (job) payload the queue carries. */
|
|
45
|
-
message<T extends StandardSchemaV1>(schema: T): QueueBuilder<TName, T, TServices, TLogger>;
|
|
46
|
-
handle(fn: QueueHandler<NonNullable<TMessage>, TServices, TLogger>): Queue<TName, NonNullable<TMessage>, TServices, TLogger>;
|
|
47
|
-
}
|
|
48
|
-
//#endregion
|
|
49
|
-
//#region src/queue/index.d.ts
|
|
50
|
-
export declare const q: QueueBuilder<string, undefined, [], Logger>;
|
|
51
|
-
//#endregion
|
|
52
|
-
export { Queue, type QueueContext, type QueueHandler, type QueueMessage };
|
|
53
|
-
//# sourceMappingURL=index.d.mts.map
|
|
1
|
+
import { i as QueueMessage, n as QueueContext, r as QueueHandler, t as Queue } from "../Queue-YmvN2vEP.mjs";
|
|
2
|
+
import { n as QueueNeedsMessage, r as QueueNeedsName } from "../QueueBuilder-CM0WUxfw.mjs";
|
|
3
|
+
export { Queue, type QueueContext, type QueueHandler, type QueueMessage, QueueNeedsMessage, QueueNeedsName };
|
package/dist/queue/index.mjs
CHANGED
|
@@ -1,77 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { DEFAULT_LOGGER } from "@geekmidas/logger/console";
|
|
5
|
-
//#region src/queue/QueueBuilder.ts
|
|
6
|
-
/**
|
|
7
|
-
* Builds a {@link Queue} worker — `q.queue('orders').services([db]).message(schema).handle(fn)`.
|
|
8
|
-
* Services are an array (sniffed for required env vars); `message` is the typed
|
|
9
|
-
* job payload; `handle` is the single consumer. The queue name is captured as a
|
|
10
|
-
* literal so `queue.publisher` is typed to `{ type: '<name>', payload }`.
|
|
11
|
-
*/
|
|
12
|
-
var QueueBuilder = class {
|
|
13
|
-
_name;
|
|
14
|
-
_messageSchema;
|
|
15
|
-
_timeout = 3e4;
|
|
16
|
-
_batchSize;
|
|
17
|
-
_fifo;
|
|
18
|
-
_services = [];
|
|
19
|
-
/** The construct ids `.dependsOn()` named — what the manifest records. */
|
|
20
|
-
_constructs = [];
|
|
21
|
-
_logger = DEFAULT_LOGGER;
|
|
22
|
-
/** The queue name — drives the infra queue and its `<NAME>_*` env vars. */
|
|
23
|
-
queue(name) {
|
|
24
|
-
return cloneWith(this, { _name: name });
|
|
25
|
-
}
|
|
26
|
-
timeout(timeout) {
|
|
27
|
-
return cloneWith(this, { _timeout: timeout });
|
|
28
|
-
}
|
|
29
|
-
/** SQS event-source batch size (deployed). */
|
|
30
|
-
batchSize(batchSize) {
|
|
31
|
-
return cloneWith(this, { _batchSize: batchSize });
|
|
32
|
-
}
|
|
33
|
-
/** Mark the queue as FIFO (deployed). */
|
|
34
|
-
fifo(fifo = true) {
|
|
35
|
-
return cloneWith(this, { _fifo: fifo });
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Depend on constructs — a database, a bucket, a mail sender, a queue, a
|
|
39
|
-
* topic.
|
|
40
|
-
*
|
|
41
|
-
* It records the edge and dissolves each construct's client into the
|
|
42
|
-
* handler's service record under the construct's own id, so
|
|
43
|
-
* `.dependsOn([uploads])` is what makes `services.uploads` exist and type.
|
|
44
|
-
*
|
|
45
|
-
* Constructs only. A `Service` does not match the shape, which is what keeps
|
|
46
|
-
* env sniffing confined to `.services()` and the explicit lift.
|
|
47
|
-
*/
|
|
48
|
-
dependsOn(constructs) {
|
|
49
|
-
const services = servicesOf(constructs);
|
|
50
|
-
return cloneWith(this, {
|
|
51
|
-
_services: [...this._services, ...services],
|
|
52
|
-
_constructs: idsOf(constructs, this._constructs)
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
services(services) {
|
|
56
|
-
return cloneWith(this, { _services: [...this._services, ...services] });
|
|
57
|
-
}
|
|
58
|
-
logger(logger) {
|
|
59
|
-
return cloneWith(this, { _logger: logger });
|
|
60
|
-
}
|
|
61
|
-
/** The typed message (job) payload the queue carries. */
|
|
62
|
-
message(schema) {
|
|
63
|
-
return cloneWith(this, { _messageSchema: schema });
|
|
64
|
-
}
|
|
65
|
-
handle(fn) {
|
|
66
|
-
if (!this._name) throw new Error("Queue requires a name — call .queue(name) before .handle().");
|
|
67
|
-
if (!this._messageSchema) throw new Error("Queue requires a message schema — call .message(schema) before .handle().");
|
|
68
|
-
return new Queue(this._name, fn, this._messageSchema, this._timeout, this._services, this._logger, this._batchSize, this._fifo, this._constructs);
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
//#endregion
|
|
72
|
-
//#region src/queue/index.ts
|
|
73
|
-
const q = new QueueBuilder();
|
|
74
|
-
//#endregion
|
|
75
|
-
export { Queue, QueueBuilder, q };
|
|
76
|
-
|
|
77
|
-
//# sourceMappingURL=index.mjs.map
|
|
1
|
+
import { t as Queue } from "../Queue-C1uDgjxt.mjs";
|
|
2
|
+
import { n as QueueNeedsMessage, r as QueueNeedsName } from "../QueueBuilder-XuPKZwKH.mjs";
|
|
3
|
+
export { Queue, QueueNeedsMessage, QueueNeedsName };
|
package/dist/rest-api.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_construct_interface = require("./construct-interface.cjs");
|
|
3
|
-
const require_EndpointFactory = require("./EndpointFactory-
|
|
3
|
+
const require_EndpointFactory = require("./EndpointFactory-BZOCOaK6.cjs");
|
|
4
4
|
const require_surfaceEnv = require("./surfaceEnv-CNimK76p.cjs");
|
|
5
5
|
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
6
6
|
let _geekmidas_logger_console = require("@geekmidas/logger/console");
|
|
@@ -8,7 +8,7 @@ let _geekmidas_logger_console = require("@geekmidas/logger/console");
|
|
|
8
8
|
/**
|
|
9
9
|
* What is *not* here, and why.
|
|
10
10
|
*
|
|
11
|
-
* `dependsOn`, `database`, `auditor` and `
|
|
11
|
+
* `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability
|
|
12
12
|
* into a handler. Putting one on the surface hands it to every route the
|
|
13
13
|
* surface serves — a health check gets the database because a report needed it
|
|
14
14
|
* — which is the thing least privilege forbids and the reason `.calls()` is not
|
|
@@ -95,7 +95,6 @@ var RestApi = class RestApi {
|
|
|
95
95
|
this.session = endpoints.session.bind(endpoints);
|
|
96
96
|
this.auditor = endpoints.auditor.bind(endpoints);
|
|
97
97
|
this.actor = endpoints.actor.bind(endpoints);
|
|
98
|
-
this.publisher = endpoints.publisher.bind(endpoints);
|
|
99
98
|
this.authorizer = endpoints.authorizer.bind(endpoints);
|
|
100
99
|
this.authorize = endpoints.authorize.bind(endpoints);
|
|
101
100
|
this.rls = endpoints.rls.bind(endpoints);
|
|
@@ -138,7 +137,6 @@ var RestApi = class RestApi {
|
|
|
138
137
|
session;
|
|
139
138
|
auditor;
|
|
140
139
|
actor;
|
|
141
|
-
publisher;
|
|
142
140
|
authorizer;
|
|
143
141
|
authorize;
|
|
144
142
|
rls;
|
package/dist/rest-api.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest-api.cjs","names":["canonicalId","provideKey","DEFAULT_LOGGER","envParserFor","EndpointFactory","getSecurityScheme","edgeTo"],"sources":["../src/rest-api.ts"],"sourcesContent":["/**\n * `RestApi` — the application's own HTTP surface, declared.\n *\n * Everything an app serves already existed; what did not exist was a *node* for\n * it. Without one, three things that are properties of the graph had to be\n * written down somewhere else: which origins the API accepts, which origins the\n * auth server trusts, and which URL a frontend is built against. All three were\n * being derived by walking the workspace config for ports — a second mechanism,\n * running beside the graph and answering the same question worse, since it can\n * only ever describe what this repo happens to run.\n *\n * With the surface declared, all three become one edge read backwards: a\n * consumer depends on the API, and *that* is the CORS entry, the trusted origin,\n * and the build-time URL. Nothing enumerates its own callers.\n *\n * ```ts\n * export const api = new RestApi('Api', {\n * authorizers: ['session'],\n * defaultAuthorizer: 'session',\n * });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n} from '@geekmidas/manifest';\nimport type { Telescope } from '@geekmidas/telescope';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\n\nexport type { Authenticator } from './construct-interface';\n\nimport {\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n} from './endpoints/Authorizer';\nimport { EndpointFactory } from './endpoints/EndpointFactory';\nimport { envParserFor } from './endpoints/surfaceEnv';\n\n/** The factory a surface builds its endpoints from. */\ntype Endpoints = EndpointFactory<[], '', Logger>;\n\nexport interface RestApiConfig<\n\t// `readonly []` rather than `readonly string[]`: a surface that declares no\n\t// authorizers of its own should narrow `defaultAuthorizer` to the built-ins\n\t// and `'none'`, not widen it back to any string.\n\tTAuthorizers extends readonly string[] = readonly [],\n> {\n\t/**\n\t * The app that serves this surface, relative to the workspace root —\n\t * `'apps/api'`, or `'.'` in a single-app project.\n\t *\n\t * Required. It was inferred from the id (`apps/<kebab-id>`, or the root\n\t * when no such directory existed), which meant a surface's home was\n\t * whatever happened to be on disk. It is where the app's `package.json`\n\t * and base `tsconfig.json` are, and which build serves this surface. It\n\t * does not change discovery: constructs still load from the workspace's\n\t * `constructs` glob.\n\t */\n\tpath: string;\n\t/**\n\t * CORS tunables. The *origins* are never here — they are read off the\n\t * constructs that declared an edge to this surface, which is the whole point\n\t * of declaring one. These are the parts a graph cannot answer.\n\t */\n\tcors?: {\n\t\tmaxAge?: number;\n\t\tcredentials?: boolean;\n\t\tallowHeaders?: readonly string[];\n\t\texposeHeaders?: readonly string[];\n\t};\n\t/**\n\t * The authorizer names this surface exposes. Names only — what verifies a\n\t * request legitimately differs between local and deployed, so the mechanism\n\t * belongs to the target and never to portable code.\n\t */\n\tauthorizers?: TAuthorizers;\n\t/**\n\t * The authorizer applied to an endpoint that names none.\n\t *\n\t * Required, and `'none'` is a valid answer that has to be typed out. The\n\t * alternative is an API that ships open because a field was left off, which\n\t * is the one default worth refusing to have.\n\t *\n\t * It was called `default`, which said what it was to the type and nothing\n\t * to the reader: next to `authorizers: ['iam']`, a bare `default: 'none'`\n\t * could be defaulting the runtime or the target. The manifest has always\n\t * called it `defaultAuthorizer` and the factory `defaultAuthorizerName`;\n\t * this is the same fact under the same name.\n\t *\n\t * Typed from `authorizers`, so it can only name one this surface exposes —\n\t * plus a built-in scheme, and `'none'`. It was a bare `string`, which let\n\t * `defaultAuthorizer: 'jwtt'` compile and every endpoint on the surface\n\t * default to an authorizer that does not exist.\n\t */\n\tdefaultAuthorizer: TAuthorizers[number] | BuiltInSecuritySchemeId | 'none';\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * The actual logger, not a path to one. It used to be named in config as\n\t * `logger: './config/logger'`, because the build wrote an import into each\n\t * generated handler and a generator can print a specifier but not an object.\n\t * Endpoints built from the surface carry it, so there is nothing to print\n\t * and nothing to keep in step with a moved file.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Same reason as `logger`, and the same field it replaces —\n\t * `envParser: './config/env#envParser'`, a module path with an export name\n\t * appended, parsed by us, checked by nothing.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * The Telescope instance this surface's entry mounts.\n\t *\n\t * The actual instance, for the reason `logger` is: it used to be named as\n\t * `telescope: './config/telescope#telescope'`, a module path the build\n\t * printed an import for. The entry already imports the surface.\n\t */\n\ttelescope?: Telescope;\n}\n\n/**\n * What is *not* here, and why.\n *\n * `dependsOn`, `database`, `auditor` and `publisher` all inject a capability\n * into a handler. Putting one on the surface hands it to every route the\n * surface serves — a health check gets the database because a report needed it\n * — which is the thing least privilege forbids and the reason `.calls()` is not\n * spelled `dependsOn`. They belong to the endpoint, or to a branch —\n * `api.database(db)` — for a group of endpoints that genuinely share them. A\n * branch is a new factory; the surface config stays free of grants.\n *\n * `auth` is not here either: `.auth(construct)` already declares it, and a\n * second way to say the same thing is the duplication this whole model removes.\n *\n * What is left is what the *process* is rather than what a route may reach.\n */\n\nexport class RestApi<\n\tTName extends string = string,\n\tconst TAuthorizers extends readonly string[] = readonly [],\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/**\n\t * Declared once and read by both `declare()` and anything that consumes this\n\t * surface, so what the target publishes and what a consumer reads cannot\n\t * drift.\n\t */\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * Always defined — the surface's own if it was given one, the console\n\t * logger otherwise — so nothing downstream has to decide what to do about a\n\t * missing one. The generated entry reads it from here.\n\t */\n\treadonly logger: Logger;\n\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Always defined, and normally the default: `process.env` merged with the\n\t * credentials `gkm dev`/`gkm exec` injected. That is what every\n\t * application's own `config/env.ts` was — boilerplate identical in every\n\t * project, and mandatory, which is a poor combination.\n\t */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/** The Telescope instance, when this surface was given one. */\n\treadonly telescope?: Telescope;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: RestApiConfig<TAuthorizers>,\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\tprivate readonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telescope = config.telescope;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tthis.#endpoints = new EndpointFactory({\n\t\t\tdefaultLogger: this.logger,\n\t\t\t...(config.authorizers\n\t\t\t\t? {\n\t\t\t\t\t\t// With the scheme a built-in name stands for, as the factory's own\n\t\t\t\t\t\t// `.authorizers()` resolves it. Bare names reached the OpenAPI\n\t\t\t\t\t\t// document with no scheme, so a guarded endpoint read as public.\n\t\t\t\t\t\tavailableAuthorizers: config.authorizers.map((name) => {\n\t\t\t\t\t\t\tconst securityScheme = getSecurityScheme(name);\n\t\t\t\t\t\t\treturn securityScheme ? { name, securityScheme } : { name };\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// `'none'` reaches the factory as no default at all, which is what\n\t\t\t// public means to an endpoint that names no authorizer.\n\t\t\t...(config.defaultAuthorizer && config.defaultAuthorizer !== 'none'\n\t\t\t\t? { defaultAuthorizerName: config.defaultAuthorizer }\n\t\t\t\t: {}),\n\t\t\tsurface: {\n\t\t\t\tid: this.id,\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\t...(authenticator ? { auth: authenticator } : {}),\n\t\t\t},\n\t\t});\n\n\t\tconst endpoints = this.#endpoints;\n\t\tthis.get = endpoints.get.bind(endpoints);\n\t\tthis.post = endpoints.post.bind(endpoints);\n\t\tthis.put = endpoints.put.bind(endpoints);\n\t\tthis.patch = endpoints.patch.bind(endpoints);\n\t\tthis.delete = endpoints.delete.bind(endpoints);\n\t\tthis.options = endpoints.options.bind(endpoints);\n\t\tthis.database = endpoints.database.bind(endpoints);\n\t\tthis.session = endpoints.session.bind(endpoints);\n\t\tthis.auditor = endpoints.auditor.bind(endpoints);\n\t\tthis.actor = endpoints.actor.bind(endpoints);\n\t\tthis.publisher = endpoints.publisher.bind(endpoints);\n\t\tthis.authorizer = endpoints.authorizer.bind(endpoints);\n\t\tthis.authorize = endpoints.authorize.bind(endpoints);\n\t\tthis.rls = endpoints.rls.bind(endpoints);\n\t\tthis.route = endpoints.route.bind(endpoints);\n\t}\n\n\t/**\n\t * This surface's endpoint factory, which every method below starts from.\n\t *\n\t * Private: a surface *is* where endpoints are built, so there is no second\n\t * object to reach through first. `api.database(db)` said the same\n\t * thing as `api.database(db)` with one more word to learn.\n\t */\n\treadonly #endpoints: Endpoints;\n\n\t/** `api.get('/users')` — one route on this surface. */\n\treadonly get: Endpoints['get'];\n\treadonly post: Endpoints['post'];\n\treadonly put: Endpoints['put'];\n\treadonly patch: Endpoints['patch'];\n\treadonly delete: Endpoints['delete'];\n\treadonly options: Endpoints['options'];\n\n\t/**\n\t * A branch for a *group* of endpoints that shares what a single route would\n\t * otherwise repeat — a database, an auditor, a publisher, a session:\n\t *\n\t * ```ts\n\t * export const router = api.database(database);\n\t * export const createUser = router.post('/users').handle(({ db }) => …);\n\t * ```\n\t *\n\t * Each returns a new factory and leaves the surface as it was. That is the\n\t * whole difference from putting the same thing in the surface's config: a\n\t * group opts in, where the surface would grant it to every route it serves —\n\t * a health check handed the database because a profile endpoint needed it.\n\t *\n\t * `dependsOn` is deliberately not here. It is per endpoint, and on the\n\t * surface it would read as the API depending on something, which is what\n\t * `.calls()` and `.auth()` say instead.\n\t */\n\treadonly database: Endpoints['database'];\n\treadonly session: Endpoints['session'];\n\treadonly auditor: Endpoints['auditor'];\n\treadonly actor: Endpoints['actor'];\n\treadonly publisher: Endpoints['publisher'];\n\treadonly authorizer: Endpoints['authorizer'];\n\treadonly authorize: Endpoints['authorize'];\n\treadonly rls: Endpoints['rls'];\n\treadonly route: Endpoints['route'];\n\n\t/**\n\t * What authenticates this surface.\n\t *\n\t * An edge like `.calls()` — the auth server learns this origin, and the two\n\t * share a cookie domain — but a named one, because *who authenticates me* is\n\t * a different fact from *who I happen to call*, and only one of them decides\n\t * what a request is allowed to be. A surface with two of the first is a\n\t * mistake; two of the second is Tuesday.\n\t *\n\t * It declares the id, and keeps the construct: a session callback reads from\n\t * it as `auth` — `session(async ({ auth }) => auth.getSession())` — which\n\t * calls the construct's `verify(headers)`. That is the one thing every\n\t * provider shares, whether the server is mounted in this process, deployed\n\t * beside it, or an OIDC issuer somebody else runs.\n\t */\n\tauth(construct: Authenticator): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(construct)],\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Other surfaces this one calls.\n\t *\n\t * **Not `.dependsOn()`, and the difference matters.** An endpoint's\n\t * `.dependsOn()` injects a client into that handler and grants it exactly\n\t * what it named. This grants nothing and injects nothing: it records that\n\t * this API calls another surface, which is what puts this API's origin on\n\t * that surface's trusted-origin list.\n\t *\n\t * Spelling it `dependsOn` would invite the thing least privilege forbids —\n\t * every route on the surface receiving whatever the surface named.\n\t *\n\t * Immutable, like every other builder here.\n\t */\n\tcalls(constructs: readonly Declarable[]): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.authenticator,\n\t\t);\n\t}\n\n\t/**\n\t * One surface node, with its endpoints left to the build.\n\t *\n\t * The three provided keys are one fact about this surface and two about its\n\t * callers. Declaring the caller-derived pair here rather than having the\n\t * target invent them is what makes the contract checkable: a target that\n\t * resolves no origins is caught against this list instead of being noticed\n\t * when a browser is refused in production.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\t...(this.config.telescope ? { telescope: true } : {}),\n\t\t\t\t...(this.config.cors ? { cors: this.config.cors } : {}),\n\t\t\t\t...(this.authenticator ? { auth: this.authenticator.id } : {}),\n\t\t\t\t// Filled by the build, which already generates one handler per\n\t\t\t\t// endpoint and knows the path it wrote it to. A surface that\n\t\t\t\t// enumerates its own routes statically — an auth server's single\n\t\t\t\t// wildcard — puts them here instead.\n\t\t\t\tendpoints: [],\n\t\t\t\t...(this.dependencies.length ? { calls: this.dependencies } : {}),\n\t\t\t\t...(this.config.authorizers?.length\n\t\t\t\t\t? { authorizers: this.config.authorizers }\n\t\t\t\t\t: {}),\n\t\t\t\tdefaultAuthorizer: this.config.defaultAuthorizer,\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuJA,IAAa,UAAb,MAAa,QAIb;CAsCmB;CAEA;CAEA;CAzClB;;;;;;CAOA;;;;;;;;CAaA;;;;;;;;;CAUA;;CAGA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GAExD,eACC;EALgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEA,KAAA,gBAAA;EAEjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EAEV,KAAK,OAAO;GACX,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;GAChC,iBAAA,GAAgBA,oBAAAA,WAAAA,CAAW,WAAW,gBAAgB;GACtD,eAAA,GAAcA,oBAAAA,WAAAA,CAAW,WAAW,cAAc;EACnD;EAEA,KAAK,SAAS,OAAO,UAAUC,0BAAAA;EAC/B,KAAK,YAAY,OAAO;EACxB,KAAK,YAAYC,mBAAAA,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EAEA,KAAK,aAAa,IAAIC,wBAAAA,gBAAgB;GACrC,eAAe,KAAK;GACpB,GAAI,OAAO,cACR,EAIA,sBAAsB,OAAO,YAAY,KAAK,SAAS;IACtD,MAAM,iBAAiBC,wBAAAA,kBAAkB,IAAI;IAC7C,OAAO,iBAAiB;KAAE;KAAM;IAAe,IAAI,EAAE,KAAK;GAC3D,CAAC,EACF,IACC,CAAC;GAGJ,GAAI,OAAO,qBAAqB,OAAO,sBAAsB,SAC1D,EAAE,uBAAuB,OAAO,kBAAkB,IAClD,CAAC;GACJ,SAAS;IACR,IAAI,KAAK;IACT,WAAW,KAAK;IAChB,GAAI,gBAAgB,EAAE,MAAM,cAAc,IAAI,CAAC;GAChD;EACD,CAAC;EAED,MAAM,YAAY,KAAK;EACvB,KAAK,MAAM,UAAU,IAAI,KAAK,SAAS;EACvC,KAAK,OAAO,UAAU,KAAK,KAAK,SAAS;EACzC,KAAK,MAAM,UAAU,IAAI,KAAK,SAAS;EACvC,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS;EAC3C,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS;EAC7C,KAAK,UAAU,UAAU,QAAQ,KAAK,SAAS;EAC/C,KAAK,WAAW,UAAU,SAAS,KAAK,SAAS;EACjD,KAAK,UAAU,UAAU,QAAQ,KAAK,SAAS;EAC/C,KAAK,UAAU,UAAU,QAAQ,KAAK,SAAS;EAC/C,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS;EAC3C,KAAK,YAAY,UAAU,UAAU,KAAK,SAAS;EACnD,KAAK,aAAa,UAAU,WAAW,KAAK,SAAS;EACrD,KAAK,YAAY,UAAU,UAAU,KAAK,SAAS;EACnD,KAAK,MAAM,UAAU,IAAI,KAAK,SAAS;EACvC,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS;CAC5C;;;;;;;;CASA;;CAGA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;;;;CAoBA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;CAiBA,KAAK,WAAwD;EAC5D,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAcC,4BAAAA,OAAO,SAAS,CAAC,GACxC,SACD;CACD;;;;;;;;;;;;;;;CAgBA,MAAM,YAAiE;EACtE,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,GAAG,WAAW,IAAIA,4BAAAA,MAAM,CAAC,GAChD,KAAK,aACN;CACD;;;;;;;;;;CAWA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,MAAM,KAAK,OAAO;GAClB,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACnD,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,gBAAgB,EAAE,MAAM,KAAK,cAAc,GAAG,IAAI,CAAC;GAK5D,WAAW,CAAC;GACZ,GAAI,KAAK,aAAa,SAAS,EAAE,OAAO,KAAK,aAAa,IAAI,CAAC;GAC/D,GAAI,KAAK,OAAO,aAAa,SAC1B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;GACJ,mBAAmB,KAAK,OAAO;GAC/B,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"rest-api.cjs","names":["canonicalId","provideKey","DEFAULT_LOGGER","envParserFor","EndpointFactory","getSecurityScheme","edgeTo"],"sources":["../src/rest-api.ts"],"sourcesContent":["/**\n * `RestApi` — the application's own HTTP surface, declared.\n *\n * Everything an app serves already existed; what did not exist was a *node* for\n * it. Without one, three things that are properties of the graph had to be\n * written down somewhere else: which origins the API accepts, which origins the\n * auth server trusts, and which URL a frontend is built against. All three were\n * being derived by walking the workspace config for ports — a second mechanism,\n * running beside the graph and answering the same question worse, since it can\n * only ever describe what this repo happens to run.\n *\n * With the surface declared, all three become one edge read backwards: a\n * consumer depends on the API, and *that* is the CORS entry, the trusted origin,\n * and the build-time URL. Nothing enumerates its own callers.\n *\n * ```ts\n * export const api = new RestApi('Api', {\n * authorizers: ['session'],\n * defaultAuthorizer: 'session',\n * });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n\tprovideKey,\n} from '@geekmidas/manifest';\nimport type { Telescope } from '@geekmidas/telescope';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\n\nexport type { Authenticator } from './construct-interface';\n\nimport {\n\ttype BuiltInSecuritySchemeId,\n\tgetSecurityScheme,\n} from './endpoints/Authorizer';\nimport { EndpointFactory } from './endpoints/EndpointFactory';\nimport { envParserFor } from './endpoints/surfaceEnv';\n\n/** The factory a surface builds its endpoints from. */\ntype Endpoints = EndpointFactory<[], '', Logger>;\n\nexport interface RestApiConfig<\n\t// `readonly []` rather than `readonly string[]`: a surface that declares no\n\t// authorizers of its own should narrow `defaultAuthorizer` to the built-ins\n\t// and `'none'`, not widen it back to any string.\n\tTAuthorizers extends readonly string[] = readonly [],\n> {\n\t/**\n\t * The app that serves this surface, relative to the workspace root —\n\t * `'apps/api'`, or `'.'` in a single-app project.\n\t *\n\t * Required. It was inferred from the id (`apps/<kebab-id>`, or the root\n\t * when no such directory existed), which meant a surface's home was\n\t * whatever happened to be on disk. It is where the app's `package.json`\n\t * and base `tsconfig.json` are, and which build serves this surface. It\n\t * does not change discovery: constructs still load from the workspace's\n\t * `constructs` glob.\n\t */\n\tpath: string;\n\t/**\n\t * CORS tunables. The *origins* are never here — they are read off the\n\t * constructs that declared an edge to this surface, which is the whole point\n\t * of declaring one. These are the parts a graph cannot answer.\n\t */\n\tcors?: {\n\t\tmaxAge?: number;\n\t\tcredentials?: boolean;\n\t\tallowHeaders?: readonly string[];\n\t\texposeHeaders?: readonly string[];\n\t};\n\t/**\n\t * The authorizer names this surface exposes. Names only — what verifies a\n\t * request legitimately differs between local and deployed, so the mechanism\n\t * belongs to the target and never to portable code.\n\t */\n\tauthorizers?: TAuthorizers;\n\t/**\n\t * The authorizer applied to an endpoint that names none.\n\t *\n\t * Required, and `'none'` is a valid answer that has to be typed out. The\n\t * alternative is an API that ships open because a field was left off, which\n\t * is the one default worth refusing to have.\n\t *\n\t * It was called `default`, which said what it was to the type and nothing\n\t * to the reader: next to `authorizers: ['iam']`, a bare `default: 'none'`\n\t * could be defaulting the runtime or the target. The manifest has always\n\t * called it `defaultAuthorizer` and the factory `defaultAuthorizerName`;\n\t * this is the same fact under the same name.\n\t *\n\t * Typed from `authorizers`, so it can only name one this surface exposes —\n\t * plus a built-in scheme, and `'none'`. It was a bare `string`, which let\n\t * `defaultAuthorizer: 'jwtt'` compile and every endpoint on the surface\n\t * default to an authorizer that does not exist.\n\t */\n\tdefaultAuthorizer: TAuthorizers[number] | BuiltInSecuritySchemeId | 'none';\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * The actual logger, not a path to one. It used to be named in config as\n\t * `logger: './config/logger'`, because the build wrote an import into each\n\t * generated handler and a generator can print a specifier but not an object.\n\t * Endpoints built from the surface carry it, so there is nothing to print\n\t * and nothing to keep in step with a moved file.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Same reason as `logger`, and the same field it replaces —\n\t * `envParser: './config/env#envParser'`, a module path with an export name\n\t * appended, parsed by us, checked by nothing.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * The Telescope instance this surface's entry mounts.\n\t *\n\t * The actual instance, for the reason `logger` is: it used to be named as\n\t * `telescope: './config/telescope#telescope'`, a module path the build\n\t * printed an import for. The entry already imports the surface.\n\t */\n\ttelescope?: Telescope;\n}\n\n/**\n * What is *not* here, and why.\n *\n * `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability\n * into a handler. Putting one on the surface hands it to every route the\n * surface serves — a health check gets the database because a report needed it\n * — which is the thing least privilege forbids and the reason `.calls()` is not\n * spelled `dependsOn`. They belong to the endpoint, or to a branch —\n * `api.database(db)` — for a group of endpoints that genuinely share them. A\n * branch is a new factory; the surface config stays free of grants.\n *\n * `auth` is not here either: `.auth(construct)` already declares it, and a\n * second way to say the same thing is the duplication this whole model removes.\n *\n * What is left is what the *process* is rather than what a route may reach.\n */\n\nexport class RestApi<\n\tTName extends string = string,\n\tconst TAuthorizers extends readonly string[] = readonly [],\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/**\n\t * Declared once and read by both `declare()` and anything that consumes this\n\t * surface, so what the target publishes and what a consumer reads cannot\n\t * drift.\n\t */\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tcookieDomain: string;\n\t};\n\n\t/**\n\t * The logger every endpoint on this surface runs with.\n\t *\n\t * Always defined — the surface's own if it was given one, the console\n\t * logger otherwise — so nothing downstream has to decide what to do about a\n\t * missing one. The generated entry reads it from here.\n\t */\n\treadonly logger: Logger;\n\n\t/**\n\t * The environment parser every endpoint on this surface runs with.\n\t *\n\t * Always defined, and normally the default: `process.env` merged with the\n\t * credentials `gkm dev`/`gkm exec` injected. That is what every\n\t * application's own `config/env.ts` was — boilerplate identical in every\n\t * project, and mandatory, which is a poor combination.\n\t */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/** The Telescope instance, when this surface was given one. */\n\treadonly telescope?: Telescope;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: RestApiConfig<TAuthorizers>,\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\tprivate readonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tcookieDomain: provideKey(canonical, 'cookieDomain'),\n\t\t};\n\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telescope = config.telescope;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tthis.#endpoints = new EndpointFactory({\n\t\t\tdefaultLogger: this.logger,\n\t\t\t...(config.authorizers\n\t\t\t\t? {\n\t\t\t\t\t\t// With the scheme a built-in name stands for, as the factory's own\n\t\t\t\t\t\t// `.authorizers()` resolves it. Bare names reached the OpenAPI\n\t\t\t\t\t\t// document with no scheme, so a guarded endpoint read as public.\n\t\t\t\t\t\tavailableAuthorizers: config.authorizers.map((name) => {\n\t\t\t\t\t\t\tconst securityScheme = getSecurityScheme(name);\n\t\t\t\t\t\t\treturn securityScheme ? { name, securityScheme } : { name };\n\t\t\t\t\t\t}),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t// `'none'` reaches the factory as no default at all, which is what\n\t\t\t// public means to an endpoint that names no authorizer.\n\t\t\t...(config.defaultAuthorizer && config.defaultAuthorizer !== 'none'\n\t\t\t\t? { defaultAuthorizerName: config.defaultAuthorizer }\n\t\t\t\t: {}),\n\t\t\tsurface: {\n\t\t\t\tid: this.id,\n\t\t\t\tenvParser: this.envParser,\n\t\t\t\t...(authenticator ? { auth: authenticator } : {}),\n\t\t\t},\n\t\t});\n\n\t\tconst endpoints = this.#endpoints;\n\t\tthis.get = endpoints.get.bind(endpoints);\n\t\tthis.post = endpoints.post.bind(endpoints);\n\t\tthis.put = endpoints.put.bind(endpoints);\n\t\tthis.patch = endpoints.patch.bind(endpoints);\n\t\tthis.delete = endpoints.delete.bind(endpoints);\n\t\tthis.options = endpoints.options.bind(endpoints);\n\t\tthis.database = endpoints.database.bind(endpoints);\n\t\tthis.session = endpoints.session.bind(endpoints);\n\t\tthis.auditor = endpoints.auditor.bind(endpoints);\n\t\tthis.actor = endpoints.actor.bind(endpoints);\n\t\tthis.authorizer = endpoints.authorizer.bind(endpoints);\n\t\tthis.authorize = endpoints.authorize.bind(endpoints);\n\t\tthis.rls = endpoints.rls.bind(endpoints);\n\t\tthis.route = endpoints.route.bind(endpoints);\n\t}\n\n\t/**\n\t * This surface's endpoint factory, which every method below starts from.\n\t *\n\t * Private: a surface *is* where endpoints are built, so there is no second\n\t * object to reach through first. `api.database(db)` said the same\n\t * thing as `api.database(db)` with one more word to learn.\n\t */\n\treadonly #endpoints: Endpoints;\n\n\t/** `api.get('/users')` — one route on this surface. */\n\treadonly get: Endpoints['get'];\n\treadonly post: Endpoints['post'];\n\treadonly put: Endpoints['put'];\n\treadonly patch: Endpoints['patch'];\n\treadonly delete: Endpoints['delete'];\n\treadonly options: Endpoints['options'];\n\n\t/**\n\t * A branch for a *group* of endpoints that shares what a single route would\n\t * otherwise repeat — a database, an auditor, a publisher, a session:\n\t *\n\t * ```ts\n\t * export const router = api.database(database);\n\t * export const createUser = router.post('/users').handle(({ db }) => …);\n\t * ```\n\t *\n\t * Each returns a new factory and leaves the surface as it was. That is the\n\t * whole difference from putting the same thing in the surface's config: a\n\t * group opts in, where the surface would grant it to every route it serves —\n\t * a health check handed the database because a profile endpoint needed it.\n\t *\n\t * `dependsOn` is deliberately not here. It is per endpoint, and on the\n\t * surface it would read as the API depending on something, which is what\n\t * `.calls()` and `.auth()` say instead.\n\t */\n\treadonly database: Endpoints['database'];\n\treadonly session: Endpoints['session'];\n\treadonly auditor: Endpoints['auditor'];\n\treadonly actor: Endpoints['actor'];\n\treadonly authorizer: Endpoints['authorizer'];\n\treadonly authorize: Endpoints['authorize'];\n\treadonly rls: Endpoints['rls'];\n\treadonly route: Endpoints['route'];\n\n\t/**\n\t * What authenticates this surface.\n\t *\n\t * An edge like `.calls()` — the auth server learns this origin, and the two\n\t * share a cookie domain — but a named one, because *who authenticates me* is\n\t * a different fact from *who I happen to call*, and only one of them decides\n\t * what a request is allowed to be. A surface with two of the first is a\n\t * mistake; two of the second is Tuesday.\n\t *\n\t * It declares the id, and keeps the construct: a session callback reads from\n\t * it as `auth` — `session(async ({ auth }) => auth.getSession())` — which\n\t * calls the construct's `verify(headers)`. That is the one thing every\n\t * provider shares, whether the server is mounted in this process, deployed\n\t * beside it, or an OIDC issuer somebody else runs.\n\t */\n\tauth(construct: Authenticator): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(construct)],\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Other surfaces this one calls.\n\t *\n\t * **Not `.dependsOn()`, and the difference matters.** An endpoint's\n\t * `.dependsOn()` injects a client into that handler and grants it exactly\n\t * what it named. This grants nothing and injects nothing: it records that\n\t * this API calls another surface, which is what puts this API's origin on\n\t * that surface's trusted-origin list.\n\t *\n\t * Spelling it `dependsOn` would invite the thing least privilege forbids —\n\t * every route on the surface receiving whatever the surface named.\n\t *\n\t * Immutable, like every other builder here.\n\t */\n\tcalls(constructs: readonly Declarable[]): RestApi<TName, TAuthorizers> {\n\t\treturn new RestApi<TName, TAuthorizers>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.authenticator,\n\t\t);\n\t}\n\n\t/**\n\t * One surface node, with its endpoints left to the build.\n\t *\n\t * The three provided keys are one fact about this surface and two about its\n\t * callers. Declaring the caller-derived pair here rather than having the\n\t * target invent them is what makes the contract checkable: a target that\n\t * resolves no origins is caught against this list instead of being noticed\n\t * when a browser is refused in production.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'rest-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\t...(this.config.telescope ? { telescope: true } : {}),\n\t\t\t\t...(this.config.cors ? { cors: this.config.cors } : {}),\n\t\t\t\t...(this.authenticator ? { auth: this.authenticator.id } : {}),\n\t\t\t\t// Filled by the build, which already generates one handler per\n\t\t\t\t// endpoint and knows the path it wrote it to. A surface that\n\t\t\t\t// enumerates its own routes statically — an auth server's single\n\t\t\t\t// wildcard — puts them here instead.\n\t\t\t\tendpoints: [],\n\t\t\t\t...(this.dependencies.length ? { calls: this.dependencies } : {}),\n\t\t\t\t...(this.config.authorizers?.length\n\t\t\t\t\t? { authorizers: this.config.authorizers }\n\t\t\t\t\t: {}),\n\t\t\t\tdefaultAuthorizer: this.config.defaultAuthorizer,\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.cookieDomain,\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuJA,IAAa,UAAb,MAAa,QAIb;CAsCmB;CAEA;CAEA;CAzClB;;;;;;CAOA;;;;;;;;CAaA;;;;;;;;;CAUA;;CAGA;CAEA,YACC,IACA,QAEA,eAAuD,CAAC,GAExD,eACC;EALgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAEA,KAAA,gBAAA;EAEjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EAEV,KAAK,OAAO;GACX,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;GAChC,iBAAA,GAAgBA,oBAAAA,WAAAA,CAAW,WAAW,gBAAgB;GACtD,eAAA,GAAcA,oBAAAA,WAAAA,CAAW,WAAW,cAAc;EACnD;EAEA,KAAK,SAAS,OAAO,UAAUC,0BAAAA;EAC/B,KAAK,YAAY,OAAO;EACxB,KAAK,YAAYC,mBAAAA,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EAEA,KAAK,aAAa,IAAIC,wBAAAA,gBAAgB;GACrC,eAAe,KAAK;GACpB,GAAI,OAAO,cACR,EAIA,sBAAsB,OAAO,YAAY,KAAK,SAAS;IACtD,MAAM,iBAAiBC,wBAAAA,kBAAkB,IAAI;IAC7C,OAAO,iBAAiB;KAAE;KAAM;IAAe,IAAI,EAAE,KAAK;GAC3D,CAAC,EACF,IACC,CAAC;GAGJ,GAAI,OAAO,qBAAqB,OAAO,sBAAsB,SAC1D,EAAE,uBAAuB,OAAO,kBAAkB,IAClD,CAAC;GACJ,SAAS;IACR,IAAI,KAAK;IACT,WAAW,KAAK;IAChB,GAAI,gBAAgB,EAAE,MAAM,cAAc,IAAI,CAAC;GAChD;EACD,CAAC;EAED,MAAM,YAAY,KAAK;EACvB,KAAK,MAAM,UAAU,IAAI,KAAK,SAAS;EACvC,KAAK,OAAO,UAAU,KAAK,KAAK,SAAS;EACzC,KAAK,MAAM,UAAU,IAAI,KAAK,SAAS;EACvC,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS;EAC3C,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS;EAC7C,KAAK,UAAU,UAAU,QAAQ,KAAK,SAAS;EAC/C,KAAK,WAAW,UAAU,SAAS,KAAK,SAAS;EACjD,KAAK,UAAU,UAAU,QAAQ,KAAK,SAAS;EAC/C,KAAK,UAAU,UAAU,QAAQ,KAAK,SAAS;EAC/C,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS;EAC3C,KAAK,aAAa,UAAU,WAAW,KAAK,SAAS;EACrD,KAAK,YAAY,UAAU,UAAU,KAAK,SAAS;EACnD,KAAK,MAAM,UAAU,IAAI,KAAK,SAAS;EACvC,KAAK,QAAQ,UAAU,MAAM,KAAK,SAAS;CAC5C;;;;;;;;CASA;;CAGA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;;;;CAoBA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;;;;;;;;CAiBA,KAAK,WAAwD;EAC5D,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAcC,4BAAAA,OAAO,SAAS,CAAC,GACxC,SACD;CACD;;;;;;;;;;;;;;;CAgBA,MAAM,YAAiE;EACtE,OAAO,IAAI,QACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,GAAG,WAAW,IAAIA,4BAAAA,MAAM,CAAC,GAChD,KAAK,aACN;CACD;;;;;;;;;;CAWA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,MAAM,KAAK,OAAO;GAClB,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,IAAI,CAAC;GACnD,GAAI,KAAK,OAAO,OAAO,EAAE,MAAM,KAAK,OAAO,KAAK,IAAI,CAAC;GACrD,GAAI,KAAK,gBAAgB,EAAE,MAAM,KAAK,cAAc,GAAG,IAAI,CAAC;GAK5D,WAAW,CAAC;GACZ,GAAI,KAAK,aAAa,SAAS,EAAE,OAAO,KAAK,aAAa,IAAI,CAAC;GAC/D,GAAI,KAAK,OAAO,aAAa,SAC1B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;GACJ,mBAAmB,KAAK,OAAO;GAC/B,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD"}
|
package/dist/rest-api.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as Declarable, t as Authenticator } from "./construct-interface-
|
|
2
|
-
import { T as BuiltInSecuritySchemeId } from "./Endpoint-
|
|
3
|
-
import { t as EndpointFactory } from "./EndpointFactory-
|
|
1
|
+
import { i as Declarable, t as Authenticator } from "./construct-interface-_xi4BPN8.cjs";
|
|
2
|
+
import { T as BuiltInSecuritySchemeId } from "./Endpoint-Dp5AKIXl.cjs";
|
|
3
|
+
import { t as EndpointFactory } from "./EndpointFactory-FeFRmlDZ.cjs";
|
|
4
4
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
5
5
|
import { Logger } from "@geekmidas/logger";
|
|
6
6
|
import { ConstructName, Declaration, Dependency } from "@geekmidas/manifest";
|
|
@@ -87,7 +87,7 @@ export interface RestApiConfig<TAuthorizers extends readonly string[] = readonly
|
|
|
87
87
|
/**
|
|
88
88
|
* What is *not* here, and why.
|
|
89
89
|
*
|
|
90
|
-
* `dependsOn`, `database`, `auditor` and `
|
|
90
|
+
* `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability
|
|
91
91
|
* into a handler. Putting one on the surface hands it to every route the
|
|
92
92
|
* surface serves — a health check gets the database because a report needed it
|
|
93
93
|
* — which is the thing least privilege forbids and the reason `.calls()` is not
|
|
@@ -171,7 +171,6 @@ export declare class RestApi<TName extends string = string, const TAuthorizers e
|
|
|
171
171
|
readonly session: Endpoints['session'];
|
|
172
172
|
readonly auditor: Endpoints['auditor'];
|
|
173
173
|
readonly actor: Endpoints['actor'];
|
|
174
|
-
readonly publisher: Endpoints['publisher'];
|
|
175
174
|
readonly authorizer: Endpoints['authorizer'];
|
|
176
175
|
readonly authorize: Endpoints['authorize'];
|
|
177
176
|
readonly rls: Endpoints['rls'];
|
package/dist/rest-api.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest-api.d.cts","names":[],"sources":["../src/rest-api.ts"],"mappings":";;;;;;;;;KAkDK,YAAY,wBAAwB;iBAExB,cAIhB;;;;;;;;;;;;EAaA;;;;;;EAMA;IACC;IACA;IACA;IACA;;;;;;;EAOD,cAAc;;;;;;;;;;;;;;;;;;;EAmBd,mBAAmB,uBAAuB;;;;;;;;;;EAU1C,SAAS;;;;;;;;EAQT,YAAY;;;;;;;;EAQZ,YAAY;;;;;;;;;;;;;;;;;;qBAoBA,QACZ,qCACM,iEACM,WAAW;;mBAuCL;;mBAEA;;mBAEA;WAzCT,IAAI;;;;;;WAOJ;IACR;IACA;IACA;;;;;;;;;WAUQ,QAAQ;;;;;;;;;WAUR,WAAW;;WAGX,YAAY;EAErB,YACC,IAAI,cAAc,QACD,QAAQ,cAAc,eAEtB;;EAAA,wBAAuB,cAEvB;;EAAA,gBAAgB;;
|
|
1
|
+
{"version":3,"file":"rest-api.d.cts","names":[],"sources":["../src/rest-api.ts"],"mappings":";;;;;;;;;KAkDK,YAAY,wBAAwB;iBAExB,cAIhB;;;;;;;;;;;;EAaA;;;;;;EAMA;IACC;IACA;IACA;IACA;;;;;;;EAOD,cAAc;;;;;;;;;;;;;;;;;;;EAmBd,mBAAmB,uBAAuB;;;;;;;;;;EAU1C,SAAS;;;;;;;;EAQT,YAAY;;;;;;;;EAQZ,YAAY;;;;;;;;;;;;;;;;;;qBAoBA,QACZ,qCACM,iEACM,WAAW;;mBAuCL;;mBAEA;;mBAEA;WAzCT,IAAI;;;;;;WAOJ;IACR;IACA;IACA;;;;;;;;;WAUQ,QAAQ;;;;;;;;;WAUR,WAAW;;WAGX,YAAY;EAErB,YACC,IAAI,cAAc,QACD,QAAQ,cAAc,eAEtB;;EAAA,wBAAuB,cAEvB;;EAAA,gBAAgB;;WAwEzB,KAAK;WACL,MAAM;WACN,KAAK;WACL,OAAO;WACP,QAAQ;WACR,SAAS;;;;;;;;;;;;;;;;;;;WAoBT,UAAU;WACV,SAAS;WACT,SAAS;WACT,OAAO;WACP,YAAY;WACZ,WAAW;WACX,KAAK;WACL,OAAO;;;;;;;;;;;;;;;;EAiBhB,KAAK,WAAW,gBAAgB,QAAQ,OAAO;;;;;;;;;;;;;;;EAuB/C,MAAM,qBAAqB,eAAe,QAAQ,OAAO;;;;;;;;;;EAkBzD,WAAW"}
|
package/dist/rest-api.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { i as Declarable, t as Authenticator } from "./construct-interface-
|
|
2
|
-
import { T as BuiltInSecuritySchemeId } from "./Endpoint-
|
|
3
|
-
import { t as EndpointFactory } from "./EndpointFactory-
|
|
1
|
+
import { i as Declarable, t as Authenticator } from "./construct-interface-_3zgxzXl.mjs";
|
|
2
|
+
import { T as BuiltInSecuritySchemeId } from "./Endpoint-DtI7heFm.mjs";
|
|
3
|
+
import { t as EndpointFactory } from "./EndpointFactory-CgMDvERK.mjs";
|
|
4
4
|
import { ConstructName, Declaration, Dependency } from "@geekmidas/manifest";
|
|
5
5
|
import { EnvironmentParser } from "@geekmidas/envkit";
|
|
6
6
|
import { Logger } from "@geekmidas/logger";
|
|
@@ -87,7 +87,7 @@ export interface RestApiConfig<TAuthorizers extends readonly string[] = readonly
|
|
|
87
87
|
/**
|
|
88
88
|
* What is *not* here, and why.
|
|
89
89
|
*
|
|
90
|
-
* `dependsOn`, `database`, `auditor` and `
|
|
90
|
+
* `dependsOn`, `database`, `auditor` and `.event(topic, …)` all inject a capability
|
|
91
91
|
* into a handler. Putting one on the surface hands it to every route the
|
|
92
92
|
* surface serves — a health check gets the database because a report needed it
|
|
93
93
|
* — which is the thing least privilege forbids and the reason `.calls()` is not
|
|
@@ -171,7 +171,6 @@ export declare class RestApi<TName extends string = string, const TAuthorizers e
|
|
|
171
171
|
readonly session: Endpoints['session'];
|
|
172
172
|
readonly auditor: Endpoints['auditor'];
|
|
173
173
|
readonly actor: Endpoints['actor'];
|
|
174
|
-
readonly publisher: Endpoints['publisher'];
|
|
175
174
|
readonly authorizer: Endpoints['authorizer'];
|
|
176
175
|
readonly authorize: Endpoints['authorize'];
|
|
177
176
|
readonly rls: Endpoints['rls'];
|
package/dist/rest-api.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rest-api.d.mts","names":[],"sources":["../src/rest-api.ts"],"mappings":";;;;;;;;;KAkDK,YAAY,wBAAwB;iBAExB,cAIhB;;;;;;;;;;;;EAaA;;;;;;EAMA;IACC;IACA;IACA;IACA;;;;;;;EAOD,cAAc;;;;;;;;;;;;;;;;;;;EAmBd,mBAAmB,uBAAuB;;;;;;;;;;EAU1C,SAAS;;;;;;;;EAQT,YAAY;;;;;;;;EAQZ,YAAY;;;;;;;;;;;;;;;;;;qBAoBA,QACZ,qCACM,iEACM,WAAW;;mBAuCL;;mBAEA;;mBAEA;WAzCT,IAAI;;;;;;WAOJ;IACR;IACA;IACA;;;;;;;;;WAUQ,QAAQ;;;;;;;;;WAUR,WAAW;;WAGX,YAAY;EAErB,YACC,IAAI,cAAc,QACD,QAAQ,cAAc,eAEtB;;EAAA,wBAAuB,cAEvB;;EAAA,gBAAgB;;
|
|
1
|
+
{"version":3,"file":"rest-api.d.mts","names":[],"sources":["../src/rest-api.ts"],"mappings":";;;;;;;;;KAkDK,YAAY,wBAAwB;iBAExB,cAIhB;;;;;;;;;;;;EAaA;;;;;;EAMA;IACC;IACA;IACA;IACA;;;;;;;EAOD,cAAc;;;;;;;;;;;;;;;;;;;EAmBd,mBAAmB,uBAAuB;;;;;;;;;;EAU1C,SAAS;;;;;;;;EAQT,YAAY;;;;;;;;EAQZ,YAAY;;;;;;;;;;;;;;;;;;qBAoBA,QACZ,qCACM,iEACM,WAAW;;mBAuCL;;mBAEA;;mBAEA;WAzCT,IAAI;;;;;;WAOJ;IACR;IACA;IACA;;;;;;;;;WAUQ,QAAQ;;;;;;;;;WAUR,WAAW;;WAGX,YAAY;EAErB,YACC,IAAI,cAAc,QACD,QAAQ,cAAc,eAEtB;;EAAA,wBAAuB,cAEvB;;EAAA,gBAAgB;;WAwEzB,KAAK;WACL,MAAM;WACN,KAAK;WACL,OAAO;WACP,QAAQ;WACR,SAAS;;;;;;;;;;;;;;;;;;;WAoBT,UAAU;WACV,SAAS;WACT,SAAS;WACT,OAAO;WACP,YAAY;WACZ,WAAW;WACX,KAAK;WACL,OAAO;;;;;;;;;;;;;;;;EAiBhB,KAAK,WAAW,gBAAgB,QAAQ,OAAO;;;;;;;;;;;;;;;EAuB/C,MAAM,qBAAqB,eAAe,QAAQ,OAAO;;;;;;;;;;EAkBzD,WAAW"}
|