@venizia/ignis-worker 0.4.6 → 0.4.7-0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../../src/applications/worker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAGxC,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AAE1D;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IAClC,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC,GAAG,IAAI,CAAC;IACjF,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACjF,mBAAmB,CAAC,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACrF,KAAK,CAAC,IAAI,IAAI,CAAC;CAChB;AAED;;;;;GAKG;AACH,8BAAsB,iBAAiB,CACrC,MAAM,SAAS,GAAG,GAAG,GAAG,EACxB,SAAS,SAAS,MAAM,GAAG,EAAE,EAC7B,QAAQ,SAAS,MAAM,GAAG,GAAG,CAC7B,SAAQ,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC;IACpD,qMAAqM;IACrM,UAAkB,OAAO,EAAE,yBAAyB,CAAC;IAErD,iGAAiG;IACjG,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,+FAA+F;IAC/F,OAAO,CAAC,aAAa,CAAC,CAAgB;IACtC,OAAO,CAAC,eAAe,CAAC,CAAa;IACrC,OAAO,CAA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AS,MAAM,GAAG,GAAG,CAC7B,SAAQ,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC;IACpD,qMAAqM;IACrM,UAAkB,OAAO,EAAE,yBAAyB,CAAC;IAErD,iGAAiG;IACjG,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,+FAA+F;IAC/F,OAAO,CAAC,aAAa,CAAC,CAAgB;IACtC,OAAO,CAAC,eAAe,CAAC,CAAa;IACrC,OAAO,CAAC,SAAS,CAAS;IAE1B;;;;;;;OAOG;IACM,cAAc,IAAI,MAAM;IASjC;;;OAGG;YACW,aAAa;IAqC3B,kKAAkK;IAClK,OAAO,CAAC,iBAAiB;IAgBzB,kIAAkI;YACpH,YAAY;IAW1B;;;;;OAKG;YACW,eAAe;IAqC7B,OAAO,CAAC,QAAQ;IAsChB;;;;;;OAMG;IACG,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,WAAW,GAAG,mBAAmB,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBjF;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAW5B"}
@@ -39,7 +39,8 @@ export class WorkerApplication extends RestApplication {
39
39
  try {
40
40
  const request = BffEnvelope.decodeRequest({ envelope });
41
41
  const response = await this.getServer().fetch(request);
42
- responseEnvelope = await BffEnvelope.encodeResponse({ response, id: envelope.id });
42
+ const result = await BffEnvelope.encodeResponse({ response, id: envelope.id });
43
+ responseEnvelope = result;
43
44
  }
44
45
  catch (error) {
45
46
  logger.error('Failed to handle worker message | id: %s | error: %s', envelope.id, error);
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../../src/applications/worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,YA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AI,CAAC,kEAAkE,CAAC,CAAC;YAC5E,OAAO,IAAI,CAAC,aAAa,CAAC;QAC5B,CAAC;QAED,+FAA+F;QAC/F,+DAA+D;QAC/D,MAAM,KAAK,GACT,IAAI,EAAE,KAAK,IAAK,UAAkC,CAAC;QAErD,IAAI,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEzB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAC1C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC;QAElF,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,IAAI;QACR,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QAEjC,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAClC,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAE9B,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import { getError, ProjectRootRegistry } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { CoreBindings, RestApplication } from '@venizia/ignis-kernel';\nimport type { Env, Schema } from 'hono';\nimport { BffEnvelope } from '@/envelope/encode';\nimport type { IBffRequestEnvelope, IBffResponseEnvelope } from '@/envelope/common';\nimport type { IWorkerApplicationConfigs } from './common';\n\n/**\n * Structural shape of the two globals `listen()` can attach to. Never `DedicatedWorkerGlobalScope`:\n * naming it emits it into the published `.d.ts` and forces every consumer to compile with\n * `lib.webworker`. `start` is optional because a `MessagePort`s queue starts disabled and only\n * `start()` enables it, while a worker global scope has no such method at all.\n */\nexport interface IWorkerMessageScope {\n postMessage(message: unknown, transfer?: Array<ArrayBuffer | MessagePort>): void;\n addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;\n removeEventListener?(type: 'message', listener: (event: MessageEvent) => void): void;\n start?(): void;\n}\n\n/**\n * Runs an IGNIS application inside a browser Web Worker: `listen()` replaces what\n * `ServerApplication.start()` does with a socket, attaching `onmessage` instead. Gets REST\n * controller registration by inheritance - `RestApplication.registerControllers()` - the whole\n * reason the DI helpers and `RestComponent` sit in the kernel.\n */\nexport abstract class WorkerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n> extends RestApplication<AppEnv, AppSchema, BasePath> {\n /** Widened by this layer, the only one with an optional `projectRoot` to read. Assigned by the base constructor - `declare` so no field initializer runs here and overwrites it with `undefined`. */\n declare protected configs: IWorkerApplicationConfigs;\n\n /** Resolves once the router tree is mounted - what an envelope arriving during boot waits on. */\n private servingPromise?: Promise<void>;\n /** The whole `listen()` call, kept so a second one is a no-op instead of a second listener. */\n private listenPromise?: Promise<void>;\n private detachFromScope?: () => void;\n private isStopped = false;\n\n /**\n * `configs.projectRoot` wins, else the host's own working directory - read as\n * `globalThis.process?.cwd?.()`, never a bare `process.cwd()`, because a real browser Worker has no\n * such global and this class ships there. Bound AND shared with `ModuleUtility` (through the\n * purity-safe `ProjectRootRegistry`), the same seam `ServerApplication` gives a socket host. No\n * `node_modules` check here, unlike that host: a browser has no filesystem to check, and `node:fs`\n * would bundle a Node builtin straight into a Worker.\n */\n override getProjectRoot(): string {\n const projectRoot = this.configs.projectRoot ?? globalThis.process?.cwd?.() ?? '';\n\n this.bind<string>({ key: CoreBindings.APPLICATION_PROJECT_ROOT }).toValue(projectRoot);\n ProjectRootRegistry.set({ projectRoot });\n\n return projectRoot;\n }\n\n /**\n * Every failure here is posted back as an `IBffErrorEnvelope`, the failed `postMessage` included:\n * an exception nobody posts leaves the UI waiting out the transport timeout.\n */\n private async handleMessage(opts: {\n scope: MessagePort | IWorkerMessageScope;\n envelope: IBffRequestEnvelope;\n }): Promise<void> {\n const { scope, envelope } = opts;\n const logger = this.logger.for(this.handleMessage.name);\n\n let responseEnvelope: IBffResponseEnvelope | undefined;\n let failure: unknown;\n\n try {\n const request = BffEnvelope.decodeRequest({ envelope });\n const response = await this.getServer().fetch(request);\n responseEnvelope = await BffEnvelope.encodeResponse({ response, id: envelope.id });\n } catch (error) {\n logger.error('Failed to handle worker message | id: %s | error: %s', envelope.id, error);\n failure = error;\n }\n\n if (responseEnvelope) {\n try {\n scope.postMessage(responseEnvelope, responseEnvelope.body ? [responseEnvelope.body] : []);\n return;\n } catch (postError) {\n logger.error(\n 'Failed to post response back to scope, falling back to an error envelope | id: %s | error: %s',\n envelope.id,\n postError,\n );\n failure = postError;\n }\n }\n\n this.postErrorEnvelope({ scope, id: envelope.id, error: failure });\n }\n\n /** No transfer list: an error envelope carries no `ArrayBuffer` body, and this is already the fallback path - nothing left to hand off if this post fails too. */\n private postErrorEnvelope(opts: {\n scope: MessagePort | IWorkerMessageScope;\n id: string;\n error: unknown;\n }): void {\n const { scope, id, error } = opts;\n\n try {\n scope.postMessage(BffEnvelope.encodeError({ id, error }));\n } catch (postError) {\n this.logger\n .for(this.postErrorEnvelope.name)\n .error('Failed to post error envelope back to scope | id: %s | error: %s', id, postError);\n }\n }\n\n /** Everything `ServerApplication.start()` does short of binding a socket. Once this resolves the application answers requests. */\n private async startServing(): Promise<void> {\n // The stack itself is `RestApplication.registerDefaultMiddlewares()` - a BFF must answer with\n // the framework's envelope exactly as the server does, so it adds nothing and overrides nothing.\n await this.registerDefaultMiddlewares();\n\n await this.initialize();\n await this.setupMiddlewares();\n\n this.getServer().route(this.configs.path.base, this.rootRouter);\n }\n\n /**\n * Holds an envelope until the application is serving. A dedicated worker's queue is enabled when\n * its module script is evaluated, so anything posted during boot - PGlite takes ~350ms - reaches\n * this listener and would otherwise be dropped. One shared promise also hands them on in arrival\n * order.\n */\n private async dispatchMessage(opts: {\n scope: MessagePort | IWorkerMessageScope;\n envelope: IBffRequestEnvelope;\n }): Promise<void> {\n const { scope, envelope } = opts;\n const logger = this.logger.for(this.dispatchMessage.name);\n\n try {\n await this.servingPromise;\n } catch (error) {\n logger.error(\n 'The application failed to start, answering with an error envelope | id: %s | error: %s',\n envelope.id,\n error,\n );\n this.postErrorEnvelope({ scope, id: envelope.id, error });\n return;\n }\n\n // Answered, not dropped: a request admitted before `stop()` and still waiting on the boot has\n // a caller holding a promise, and silence there is the timeout this whole path exists to avoid.\n if (this.isStopped) {\n logger.warn('Refusing a request that arrived after stop() | id: %s', envelope.id);\n this.postErrorEnvelope({\n scope,\n id: envelope.id,\n error: getError({\n statusCode: HTTP.ResultCodes.RS_5.ServiceUnavailable,\n message: `[WorkerApplication] The application was stopped before this request could run | id: ${envelope.id}`,\n }),\n });\n return;\n }\n\n await this.handleMessage({ scope, envelope });\n }\n\n private attachTo(opts: { scope: MessagePort | IWorkerMessageScope }): void {\n const { scope } = opts;\n const logger = this.logger.for(this.attachTo.name);\n\n // Typed as the broader `Event`, not `MessageEvent`: Node's ambient `worker_threads.MessagePort`\n // (the fallback this package's DOM-less tsconfig resolves `MessagePort` to) declares\n // `addEventListener` over `Event | MessageEvent`, and a handler narrower than that is not\n // assignable to it.\n const listener = (event: Event): void => {\n const envelope = (event as MessageEvent).data as IBffRequestEnvelope | undefined;\n\n // A worker scope receives every `postMessage` sent to it, not only ours - a dev-server ping,\n // a devtools/extension probe, a library's own init handshake. None of those carry an `id`;\n // silently dropping them (rather than dereferencing `envelope.id` inside `handleMessage`'s\n // own catch block) is what keeps a foreign message from throwing a bare `TypeError` that\n // would otherwise escape this listener entirely, unlogged and unposted.\n if (!envelope?.id) {\n logger.debug('Ignoring worker message with no request id | data: %j', envelope);\n return;\n }\n\n // `dispatchMessage` never rejects - every failure inside it, including a failed post, is\n // caught and handled internally. This `.catch` only guards the sliver of code before its own\n // try block ever runs.\n this.dispatchMessage({ scope, envelope }).catch((error) => {\n logger.error('Unexpected failure handling worker message | error: %s', error);\n });\n };\n\n scope.addEventListener('message', listener);\n\n scope.start?.();\n\n this.detachFromScope = () => {\n scope.removeEventListener?.('message', listener);\n };\n }\n\n /**\n * `ServerApplication.start()` minus the socket. `opts.scope` defaults to `globalThis`, never a\n * bare `self`, which would tie the published types to `lib.webworker`. Idempotent: without the\n * guard one envelope runs its handler once per call - a POST inserting two rows - and Vite HMR\n * re-evaluating the worker module is the everyday trigger. A boot failure keeps the listener\n * attached so every request hears the failure instead of waiting out the transport timeout.\n */\n async listen(opts?: { scope?: MessagePort | IWorkerMessageScope }): Promise<void> {\n if (this.listenPromise) {\n this.logger\n .for(this.listen.name)\n .warn('Already listening - ignoring this call | one scope, one listener');\n return this.listenPromise;\n }\n\n // Everything down to the first `await` runs synchronously with the caller, which is what makes\n // the listener observable to anything posted in the same turn.\n const scope: MessagePort | IWorkerMessageScope =\n opts?.scope ?? (globalThis as IWorkerMessageScope);\n\n this.attachTo({ scope });\n\n this.servingPromise = this.startServing();\n this.listenPromise = this.servingPromise.then(() => this.executePostStartHooks());\n\n return this.listenPromise;\n }\n\n /**\n * The counterpart to `listen()`, and to `ServerApplication.stop()`: runs the post-stop hooks, then\n * closes every datasource the boot configured. Without it the OPFS exclusive lock a PGlite holds\n * is never released - the next Worker then fails with `NoModificationAllowedError` until a full\n * page reload. The Vite recipe is `import.meta.hot?.dispose(() => application.stop())`.\n *\n * Detaches BEFORE draining, unlike the server: here the listener IS the socket, and a request\n * admitted while a datasource is closing has nothing left to run against. A stopped application\n * is not restartable - build a new one.\n */\n async stop(): Promise<void> {\n this.isStopped = true;\n\n this.detachFromScope?.();\n this.detachFromScope = undefined;\n\n await this.executePostStopHooks();\n await this.closeDataSources();\n\n this.logger.for(this.stop.name).info('Worker application STOPPED');\n }\n}\n"]}
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../../src/applications/worker.ts"],"names":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C;IAED;;;;;;OAMG;IACH,KAAK,CAAC,MAAM,CAAC,IAAoD;QAC/D,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;iBACrB,IAAI,CAAC,kEAAkE,CAAC,CAAC;YAC5E,OAAO,IAAI,CAAC,aAAa,CAAC;QAC5B,CAAC;QAED,+FAA+F;QAC/F,+DAA+D;QAC/D,MAAM,KAAK,GACT,IAAI,EAAE,KAAK,IAAK,UAAkC,CAAC;QAErD,IAAI,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEzB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAC1C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC;QAElF,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,IAAI;QACR,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QAEjC,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAClC,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAE9B,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import { getError, ProjectRootRegistry } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { CoreBindings, RestApplication } from '@venizia/ignis-kernel';\nimport type { Env, Schema } from 'hono';\nimport { BffEnvelope } from '@/envelope/encode';\nimport type { IBffRequestEnvelope, IBffResponseEnvelope } from '@/envelope/common';\nimport type { IWorkerApplicationConfigs } from './common';\n\n/**\n * Structural shape of the two globals `listen()` can attach to. Never `DedicatedWorkerGlobalScope`:\n * naming it emits it into the published `.d.ts` and forces every consumer to compile with\n * `lib.webworker`. `start` is optional because a `MessagePort`s queue starts disabled and only\n * `start()` enables it, while a worker global scope has no such method at all.\n */\nexport interface IWorkerMessageScope {\n postMessage(message: unknown, transfer?: Array<ArrayBuffer | MessagePort>): void;\n addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;\n removeEventListener?(type: 'message', listener: (event: MessageEvent) => void): void;\n start?(): void;\n}\n\n/**\n * Runs an IGNIS application inside a browser Web Worker: `listen()` replaces what\n * `ServerApplication.start()` does with a socket, attaching `onmessage` instead. Gets REST\n * controller registration by inheritance - `RestApplication.registerControllers()` - the whole\n * reason the DI helpers and `RestComponent` sit in the kernel.\n */\nexport abstract class WorkerApplication<\n AppEnv extends Env = Env,\n AppSchema extends Schema = {},\n BasePath extends string = '/',\n> extends RestApplication<AppEnv, AppSchema, BasePath> {\n /** Widened by this layer, the only one with an optional `projectRoot` to read. Assigned by the base constructor - `declare` so no field initializer runs here and overwrites it with `undefined`. */\n declare protected configs: IWorkerApplicationConfigs;\n\n /** Resolves once the router tree is mounted - what an envelope arriving during boot waits on. */\n private servingPromise?: Promise<void>;\n /** The whole `listen()` call, kept so a second one is a no-op instead of a second listener. */\n private listenPromise?: Promise<void>;\n private detachFromScope?: () => void;\n private isStopped = false;\n\n /**\n * `configs.projectRoot` wins, else the host's own working directory - read as\n * `globalThis.process?.cwd?.()`, never a bare `process.cwd()`, because a real browser Worker has no\n * such global and this class ships there. Bound AND shared with `ModuleUtility` (through the\n * purity-safe `ProjectRootRegistry`), the same seam `ServerApplication` gives a socket host. No\n * `node_modules` check here, unlike that host: a browser has no filesystem to check, and `node:fs`\n * would bundle a Node builtin straight into a Worker.\n */\n override getProjectRoot(): string {\n const projectRoot = this.configs.projectRoot ?? globalThis.process?.cwd?.() ?? '';\n\n this.bind<string>({ key: CoreBindings.APPLICATION_PROJECT_ROOT }).toValue(projectRoot);\n ProjectRootRegistry.set({ projectRoot });\n\n return projectRoot;\n }\n\n /**\n * Every failure here is posted back as an `IBffErrorEnvelope`, the failed `postMessage` included:\n * an exception nobody posts leaves the UI waiting out the transport timeout.\n */\n private async handleMessage(opts: {\n scope: MessagePort | IWorkerMessageScope;\n envelope: IBffRequestEnvelope;\n }): Promise<void> {\n const { scope, envelope } = opts;\n const logger = this.logger.for(this.handleMessage.name);\n\n let responseEnvelope: IBffResponseEnvelope | undefined;\n let failure: unknown;\n\n try {\n const request = BffEnvelope.decodeRequest({ envelope });\n const response = await this.getServer().fetch(request);\n const result = await BffEnvelope.encodeResponse({ response, id: envelope.id });\n responseEnvelope = result;\n } catch (error) {\n logger.error('Failed to handle worker message | id: %s | error: %s', envelope.id, error);\n failure = error;\n }\n\n if (responseEnvelope) {\n try {\n scope.postMessage(responseEnvelope, responseEnvelope.body ? [responseEnvelope.body] : []);\n return;\n } catch (postError) {\n logger.error(\n 'Failed to post response back to scope, falling back to an error envelope | id: %s | error: %s',\n envelope.id,\n postError,\n );\n failure = postError;\n }\n }\n\n this.postErrorEnvelope({ scope, id: envelope.id, error: failure });\n }\n\n /** No transfer list: an error envelope carries no `ArrayBuffer` body, and this is already the fallback path - nothing left to hand off if this post fails too. */\n private postErrorEnvelope(opts: {\n scope: MessagePort | IWorkerMessageScope;\n id: string;\n error: unknown;\n }): void {\n const { scope, id, error } = opts;\n\n try {\n scope.postMessage(BffEnvelope.encodeError({ id, error }));\n } catch (postError) {\n this.logger\n .for(this.postErrorEnvelope.name)\n .error('Failed to post error envelope back to scope | id: %s | error: %s', id, postError);\n }\n }\n\n /** Everything `ServerApplication.start()` does short of binding a socket. Once this resolves the application answers requests. */\n private async startServing(): Promise<void> {\n // The stack itself is `RestApplication.registerDefaultMiddlewares()` - a BFF must answer with\n // the framework's envelope exactly as the server does, so it adds nothing and overrides nothing.\n await this.registerDefaultMiddlewares();\n\n await this.initialize();\n await this.setupMiddlewares();\n\n this.getServer().route(this.configs.path.base, this.rootRouter);\n }\n\n /**\n * Holds an envelope until the application is serving. A dedicated worker's queue is enabled when\n * its module script is evaluated, so anything posted during boot - PGlite takes ~350ms - reaches\n * this listener and would otherwise be dropped. One shared promise also hands them on in arrival\n * order.\n */\n private async dispatchMessage(opts: {\n scope: MessagePort | IWorkerMessageScope;\n envelope: IBffRequestEnvelope;\n }): Promise<void> {\n const { scope, envelope } = opts;\n const logger = this.logger.for(this.dispatchMessage.name);\n\n try {\n await this.servingPromise;\n } catch (error) {\n logger.error(\n 'The application failed to start, answering with an error envelope | id: %s | error: %s',\n envelope.id,\n error,\n );\n this.postErrorEnvelope({ scope, id: envelope.id, error });\n return;\n }\n\n // Answered, not dropped: a request admitted before `stop()` and still waiting on the boot has\n // a caller holding a promise, and silence there is the timeout this whole path exists to avoid.\n if (this.isStopped) {\n logger.warn('Refusing a request that arrived after stop() | id: %s', envelope.id);\n this.postErrorEnvelope({\n scope,\n id: envelope.id,\n error: getError({\n statusCode: HTTP.ResultCodes.RS_5.ServiceUnavailable,\n message: `[WorkerApplication] The application was stopped before this request could run | id: ${envelope.id}`,\n }),\n });\n return;\n }\n\n await this.handleMessage({ scope, envelope });\n }\n\n private attachTo(opts: { scope: MessagePort | IWorkerMessageScope }): void {\n const { scope } = opts;\n const logger = this.logger.for(this.attachTo.name);\n\n // Typed as the broader `Event`, not `MessageEvent`: Node's ambient `worker_threads.MessagePort`\n // (the fallback this package's DOM-less tsconfig resolves `MessagePort` to) declares\n // `addEventListener` over `Event | MessageEvent`, and a handler narrower than that is not\n // assignable to it.\n const listener = (event: Event): void => {\n const envelope = (event as MessageEvent).data as IBffRequestEnvelope | undefined;\n\n // A worker scope receives every `postMessage` sent to it, not only ours - a dev-server ping,\n // a devtools/extension probe, a library's own init handshake. None of those carry an `id`;\n // silently dropping them (rather than dereferencing `envelope.id` inside `handleMessage`'s\n // own catch block) is what keeps a foreign message from throwing a bare `TypeError` that\n // would otherwise escape this listener entirely, unlogged and unposted.\n if (!envelope?.id) {\n logger.debug('Ignoring worker message with no request id | data: %j', envelope);\n return;\n }\n\n // `dispatchMessage` never rejects - every failure inside it, including a failed post, is\n // caught and handled internally. This `.catch` only guards the sliver of code before its own\n // try block ever runs.\n this.dispatchMessage({ scope, envelope }).catch((error) => {\n logger.error('Unexpected failure handling worker message | error: %s', error);\n });\n };\n\n scope.addEventListener('message', listener);\n\n scope.start?.();\n\n this.detachFromScope = () => {\n scope.removeEventListener?.('message', listener);\n };\n }\n\n /**\n * `ServerApplication.start()` minus the socket. `opts.scope` defaults to `globalThis`, never a\n * bare `self`, which would tie the published types to `lib.webworker`. Idempotent: without the\n * guard one envelope runs its handler once per call - a POST inserting two rows - and Vite HMR\n * re-evaluating the worker module is the everyday trigger. A boot failure keeps the listener\n * attached so every request hears the failure instead of waiting out the transport timeout.\n */\n async listen(opts?: { scope?: MessagePort | IWorkerMessageScope }): Promise<void> {\n if (this.listenPromise) {\n this.logger\n .for(this.listen.name)\n .warn('Already listening - ignoring this call | one scope, one listener');\n return this.listenPromise;\n }\n\n // Everything down to the first `await` runs synchronously with the caller, which is what makes\n // the listener observable to anything posted in the same turn.\n const scope: MessagePort | IWorkerMessageScope =\n opts?.scope ?? (globalThis as IWorkerMessageScope);\n\n this.attachTo({ scope });\n\n this.servingPromise = this.startServing();\n this.listenPromise = this.servingPromise.then(() => this.executePostStartHooks());\n\n return this.listenPromise;\n }\n\n /**\n * The counterpart to `listen()`, and to `ServerApplication.stop()`: runs the post-stop hooks, then\n * closes every datasource the boot configured. Without it the OPFS exclusive lock a PGlite holds\n * is never released - the next Worker then fails with `NoModificationAllowedError` until a full\n * page reload. The Vite recipe is `import.meta.hot?.dispose(() => application.stop())`.\n *\n * Detaches BEFORE draining, unlike the server: here the listener IS the socket, and a request\n * admitted while a datasource is closing has nothing left to run against. A stopped application\n * is not restartable - build a new one.\n */\n async stop(): Promise<void> {\n this.isStopped = true;\n\n this.detachFromScope?.();\n this.detachFromScope = undefined;\n\n await this.executePostStopHooks();\n await this.closeDataSources();\n\n this.logger.for(this.stop.name).info('Worker application STOPPED');\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../../../src/envelope/encode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAGpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAE7F;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,0BAA0B,CAAC;AAE5D,+IAA+I;AAC/I,qBAAa,WAAW;IACtB;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAA4B;IAEtE;;;;OAIG;IACH,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM;IAKpD;;;;;OAKG;WACU,aAAa,CAAC,IAAI,EAAE;QAC/B,OAAO,EAAE,OAAO,CAAC;QACjB,EAAE,EAAE,MAAM,CAAC;QACX,GAAG,CAAC,EAAE,MAAM,CAAC;KACd,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAahC,MAAM,CAAC,aAAa,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,mBAAmB,CAAA;KAAE,GAAG,OAAO;WAUzD,cAAc,CAAC,IAAI,EAAE;QAChC,QAAQ,EAAE,QAAQ,CAAC;QACnB,EAAE,EAAE,MAAM,CAAC;KACZ,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAajC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,oBAAoB,CAAA;KAAE,GAAG,QAAQ;IAazE;;;;;;;OAOG;IACH,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;Q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,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,GAAG,iBAAiB;IAoB3E,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE;QAAE,QAAQ,EAAE,iBAAiB,CAAA;KAAE,GAAG,gBAAgB;CAc5E"}
@@ -31,12 +31,17 @@ export class BffEnvelope {
31
31
  static async encodeRequest(opts) {
32
32
  const { request, id, url } = opts;
33
33
  const hasBody = request.method !== 'GET' && request.method !== 'HEAD';
34
+ let body;
35
+ if (hasBody) {
36
+ const buffer = await request.arrayBuffer();
37
+ body = buffer;
38
+ }
34
39
  return {
35
40
  id,
36
41
  method: request.method,
37
42
  url: url ?? request.url,
38
43
  headers: [...request.headers.entries()],
39
- body: hasBody ? await request.arrayBuffer() : undefined,
44
+ body,
40
45
  };
41
46
  }
42
47
  static decodeRequest(opts) {
@@ -50,12 +55,17 @@ export class BffEnvelope {
50
55
  static async encodeResponse(opts) {
51
56
  const { response, id } = opts;
52
57
  const hasBody = !BffEnvelope.NULL_BODY_STATUSES.has(response.status);
58
+ let body;
59
+ if (hasBody) {
60
+ const buffer = await response.arrayBuffer();
61
+ body = buffer;
62
+ }
53
63
  return {
54
64
  id,
55
65
  status: response.status,
56
66
  statusText: response.statusText,
57
67
  headers: [...response.headers.entries()],
58
- body: hasBody ? await response.arrayBuffer() : undefined,
68
+ body,
59
69
  };
60
70
  }
61
71
  static decodeResponse(opts) {
@@ -1 +1 @@
1
- {"version":3,"file":"encode.js","sourceRoot":"","sources":["../../../src/envelope/encode.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,uBAAuB,CAAC;AAE5D,+IAA+I;AAC/I,MAAM,OAAO,WAAW;IACtB;;;OAGG;aACqB,uBAAkB,GAAG,IAA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AAC,MAAM,CAAC,KAAK,CAAC;aAChE,CAAC,CAAC;QAEP,OAAO;YACL,EAAE;YACF,UAAU,EAAE,gBAAgB,CAAC,UAAU;YACvC,KAAK,EAAE;gBACL,IAAI,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI;gBACtC,IAAI,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI;gBACtC,IAAI,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI;aACvC;SACF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,IAAqC;QACtD,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;QAE1B,OAAO,SAAS,CAAC;YACf,KAAK,EAAE;gBACL,UAAU,EAAE,QAAQ,CAAC,UAAU;gBAC/B,UAAU,EAAE;oBACV,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI;oBACzB,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI;oBACzB,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,IAA2C;iBACjE;aACF;SACF,CAAC,CAAC;IACL,CAAC","sourcesContent":["import type { ApplicationError } from '@venizia/ignis-helpers/core';\nimport { fromError, getError, isApplicationError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IBffErrorEnvelope, IBffRequestEnvelope, IBffResponseEnvelope } from './common';\n\n/**\n * Every request built inside the Worker uses this origin. Never `self.location.href`: a `blob:`\n * worker origin is opaque and `new URL(path, blobUrl)` throws, and Hono's `getPath()` mis-parses\n * `file://`. Hono never resolves the host - it string-scans from `indexOf(':') + 4`.\n */\nexport const BFF_SYNTHETIC_ORIGIN = 'http://ignis.internal';\n\n/** Turns `Request`/`Response`/`Error` into plain structured-cloneable shapes and back - none of the three survives `postMessage` as itself. */\nexport class BffEnvelope {\n /**\n * Statuses the Fetch spec forbids a body on - `new Response(body, { status })` throws if `body`\n * is anything but `null` for one of these, even an empty `ArrayBuffer`.\n */\n private static readonly NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\n /**\n * Moves a URL onto the synthetic origin, keeping everything below it. A caller builds a request\n * against the page's real origin (or a relative path resolved against it); `decodeRequest` on the\n * far side always reconstructs on `BFF_SYNTHETIC_ORIGIN`.\n */\n static toSyntheticUrl(opts: { url: string }): string {\n const url = new URL(opts.url);\n return `${BFF_SYNTHETIC_ORIGIN}${url.pathname}${url.search}${url.hash}`;\n }\n\n /**\n * `url` overrides the request's own, so the origin rewrite costs nothing: rebuilding the `Request`\n * to change its URL would read the body a second time, and a 10 MB upload would hold 20 MB on the\n * UI thread. Reading the body here disturbs the caller's request exactly as `globalThis.fetch`\n * does with the one it is handed.\n */\n static async encodeRequest(opts: {\n request: Request;\n id: string;\n url?: string;\n }): Promise<IBffRequestEnvelope> {\n const { request, id, url } = opts;\n const hasBody = request.method !== 'GET' && request.method !== 'HEAD';\n\n return {\n id,\n method: request.method,\n url: url ?? request.url,\n headers: [...request.headers.entries()],\n body: hasBody ? await request.arrayBuffer() : undefined,\n };\n }\n\n static decodeRequest(opts: { envelope: IBffRequestEnvelope }): Request {\n const { envelope } = opts;\n\n return new Request(envelope.url, {\n method: envelope.method,\n headers: envelope.headers,\n body: envelope.body,\n });\n }\n\n static async encodeResponse(opts: {\n response: Response;\n id: string;\n }): Promise<IBffResponseEnvelope> {\n const { response, id } = opts;\n const hasBody = !BffEnvelope.NULL_BODY_STATUSES.has(response.status);\n\n return {\n id,\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers.entries()],\n body: hasBody ? await response.arrayBuffer() : undefined,\n };\n }\n\n static decodeResponse(opts: { envelope: IBffResponseEnvelope }): Response {\n const { envelope } = opts;\n const body = BffEnvelope.NULL_BODY_STATUSES.has(envelope.status)\n ? null\n : (envelope.body ?? null);\n\n return new Response(body, {\n status: envelope.status,\n statusText: envelope.statusText,\n headers: envelope.headers,\n });\n }\n\n /**\n * Builds the shape an error crosses `postMessage` as. An `ApplicationError` cannot cross as itself\n * - a custom `Error` subclass loses its name, its own properties and its prototype through\n * structured clone - so it crosses normalised and `decodeError` rebuilds it on the far side.\n *\n * A foreign error gets `500`, matching what the framework's error middleware gives an UNEXPECTED\n * one on the server. Anything reaching here already escaped the whole HTTP layer.\n */\n static encodeError(opts: { id: string; error: unknown }): IBffErrorEnvelope {\n const { id, error } = opts;\n const applicationError = isApplicationError(error)\n ? error\n : getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: error instanceof Error ? error.message : String(error),\n });\n\n return {\n id,\n statusCode: applicationError.statusCode,\n error: {\n text: applicationError.normalized.text,\n code: applicationError.normalized.code,\n args: applicationError.normalized.args,\n },\n };\n }\n\n static decodeError(opts: { envelope: IBffErrorEnvelope }): ApplicationError {\n const { envelope } = opts;\n\n return fromError({\n error: {\n statusCode: envelope.statusCode,\n normalized: {\n text: envelope.error.text,\n code: envelope.error.code,\n args: envelope.error.args as Record<string, unknown> | undefined,\n },\n },\n });\n }\n}\n"]}
1
+ {"version":3,"file":"encode.js","sourceRoot":"","sources":["../../../src/envelope/encode.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD;;;;GAIG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,uBAAuB,CAAC;AAE5D,+IAA+I;AAC/I,MAAM,OAAO,WAAW;IACtB;;;OAGG;aACqB,uBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;IAEtE;;;;OAIG;IACH,MAAM,CAAC,cAAc,CAAC,IAAqB;QACzC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC9B,OAAO,GAAG,oBAAoB,GAAG,GAAG,CAAC,QAAQ,GAAG,GAAG,CAAC,MAAM,GAAG,GAAG,CA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E,gBAAgB,CAAC,UAAU,CAAC,IAAI;gBACtC,IAAI,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI;gBACtC,IAAI,EAAE,gBAAgB,CAAC,UAAU,CAAC,IAAI;aACvC;SACF,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,WAAW,CAAC,IAAqC;QACtD,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;QAE1B,OAAO,SAAS,CAAC;YACf,KAAK,EAAE;gBACL,UAAU,EAAE,QAAQ,CAAC,UAAU;gBAC/B,UAAU,EAAE;oBACV,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI;oBACzB,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,IAAI;oBACzB,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,IAA2C;iBACjE;aACF;SACF,CAAC,CAAC;IACL,CAAC","sourcesContent":["import type { ApplicationError } from '@venizia/ignis-helpers/core';\nimport { fromError, getError, isApplicationError } from '@venizia/ignis-helpers/core';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { IBffErrorEnvelope, IBffRequestEnvelope, IBffResponseEnvelope } from './common';\n\n/**\n * Every request built inside the Worker uses this origin. Never `self.location.href`: a `blob:`\n * worker origin is opaque and `new URL(path, blobUrl)` throws, and Hono's `getPath()` mis-parses\n * `file://`. Hono never resolves the host - it string-scans from `indexOf(':') + 4`.\n */\nexport const BFF_SYNTHETIC_ORIGIN = 'http://ignis.internal';\n\n/** Turns `Request`/`Response`/`Error` into plain structured-cloneable shapes and back - none of the three survives `postMessage` as itself. */\nexport class BffEnvelope {\n /**\n * Statuses the Fetch spec forbids a body on - `new Response(body, { status })` throws if `body`\n * is anything but `null` for one of these, even an empty `ArrayBuffer`.\n */\n private static readonly NULL_BODY_STATUSES = new Set([204, 205, 304]);\n\n /**\n * Moves a URL onto the synthetic origin, keeping everything below it. A caller builds a request\n * against the page's real origin (or a relative path resolved against it); `decodeRequest` on the\n * far side always reconstructs on `BFF_SYNTHETIC_ORIGIN`.\n */\n static toSyntheticUrl(opts: { url: string }): string {\n const url = new URL(opts.url);\n return `${BFF_SYNTHETIC_ORIGIN}${url.pathname}${url.search}${url.hash}`;\n }\n\n /**\n * `url` overrides the request's own, so the origin rewrite costs nothing: rebuilding the `Request`\n * to change its URL would read the body a second time, and a 10 MB upload would hold 20 MB on the\n * UI thread. Reading the body here disturbs the caller's request exactly as `globalThis.fetch`\n * does with the one it is handed.\n */\n static async encodeRequest(opts: {\n request: Request;\n id: string;\n url?: string;\n }): Promise<IBffRequestEnvelope> {\n const { request, id, url } = opts;\n const hasBody = request.method !== 'GET' && request.method !== 'HEAD';\n\n let body: ArrayBuffer | undefined;\n if (hasBody) {\n const buffer = await request.arrayBuffer();\n body = buffer;\n }\n\n return {\n id,\n method: request.method,\n url: url ?? request.url,\n headers: [...request.headers.entries()],\n body,\n };\n }\n\n static decodeRequest(opts: { envelope: IBffRequestEnvelope }): Request {\n const { envelope } = opts;\n\n return new Request(envelope.url, {\n method: envelope.method,\n headers: envelope.headers,\n body: envelope.body,\n });\n }\n\n static async encodeResponse(opts: {\n response: Response;\n id: string;\n }): Promise<IBffResponseEnvelope> {\n const { response, id } = opts;\n const hasBody = !BffEnvelope.NULL_BODY_STATUSES.has(response.status);\n\n let body: ArrayBuffer | undefined;\n if (hasBody) {\n const buffer = await response.arrayBuffer();\n body = buffer;\n }\n\n return {\n id,\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers.entries()],\n body,\n };\n }\n\n static decodeResponse(opts: { envelope: IBffResponseEnvelope }): Response {\n const { envelope } = opts;\n const body = BffEnvelope.NULL_BODY_STATUSES.has(envelope.status)\n ? null\n : (envelope.body ?? null);\n\n return new Response(body, {\n status: envelope.status,\n statusText: envelope.statusText,\n headers: envelope.headers,\n });\n }\n\n /**\n * Builds the shape an error crosses `postMessage` as. An `ApplicationError` cannot cross as itself\n * - a custom `Error` subclass loses its name, its own properties and its prototype through\n * structured clone - so it crosses normalised and `decodeError` rebuilds it on the far side.\n *\n * A foreign error gets `500`, matching what the framework's error middleware gives an UNEXPECTED\n * one on the server. Anything reaching here already escaped the whole HTTP layer.\n */\n static encodeError(opts: { id: string; error: unknown }): IBffErrorEnvelope {\n const { id, error } = opts;\n const applicationError = isApplicationError(error)\n ? error\n : getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: error instanceof Error ? error.message : String(error),\n });\n\n return {\n id,\n statusCode: applicationError.statusCode,\n error: {\n text: applicationError.normalized.text,\n code: applicationError.normalized.code,\n args: applicationError.normalized.args,\n },\n };\n }\n\n static decodeError(opts: { envelope: IBffErrorEnvelope }): ApplicationError {\n const { envelope } = opts;\n\n return fromError({\n error: {\n statusCode: envelope.statusCode,\n normalized: {\n text: envelope.error.text,\n code: envelope.error.code,\n args: envelope.error.args as Record<string, unknown> | undefined,\n },\n },\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"in-process.d.ts","sourceRoot":"","sources":["../../../src/transport/in-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAsB,MAAM,6BAA6B,CAAC;AAG7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;GASG;AACH,qBAAa,qBAAsB,SAAQ,UAAW,YAAW,aAAa;IAC5E,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0C;IAClE,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAEhC;gBAES,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;KAAE;IAMhE,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;CAyB3D"}
1
+ {"version":3,"file":"in-process.d.ts","sourceRoot":"","sources":["../../../src/transport/in-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAsB,MAAM,6BAA6B,CAAC;AAG7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAEpD;;;;;;;;;GASG;AACH,qBAAa,qBAAsB,SAAQ,UAAW,YAAW,aAAa;IAC5E,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0C;IAClE,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAEhC;gBAES,IAAI,EAAE;QAAE,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;KAAE;IAMhE,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;CA0B3D"}
@@ -28,7 +28,8 @@ export class InProcessBffTransport extends BaseHelper {
28
28
  let responseEnvelope;
29
29
  try {
30
30
  const response = await this.handler(BffEnvelope.decodeRequest({ envelope: requestEnvelope }));
31
- responseEnvelope = await BffEnvelope.encodeResponse({ response, id });
31
+ const result = await BffEnvelope.encodeResponse({ response, id });
32
+ responseEnvelope = result;
32
33
  }
33
34
  catch (error) {
34
35
  this.logger.for(this.fetch.name).error('Handler failed | id: %s | error: %s', id, error);
@@ -1 +1 @@
1
- {"version":3,"file":"in-process.js","sourceRoot":"","sources":["../../../src/transport/in-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIhD;;;;;;;;;GASG;AACH,MAAM,OAAO,qBAAsB,SAAQ,UAAU;IAMnD,YAAY,IAA0D;QACpE,KAAK,CAAC,EAAE,KAAK,EAAE,qBAAqB,CAAC,IAAI,EAAE,CAAC,CAAC;QAL9B,uBAAkB,GAAG,IAAI,kBAAkB,CAAC;YAC3D,KAAK,EAAE,qBAAqB,CAAC,IAAI;SAClC,CAAC,CAAC;QAKD,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,IAA0B;QACpC,MAAM,EAAE,GAAG,IAAI,CAAC,kBAAkB,CAAC,MAAM,EAAE,CAAC;QAE5C,MAAM,eAAe,GAAG,MAAM,WAAW,CAAC,aAAa,CAAC;YACtD,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,EAAE;YACF,GAAG,EAAE,WAAW,CAAC,cAAc,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;SAC3D,CAAC,CAAC;QAEH,IAAI,gBAAsC,CAAC;QAE3C,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,aAAa,CAAC,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC;YAC9F,gBAAgB,GAAG,MAAM,WAAW,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,qCAAqC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;YAEzF,uFAAuF;YACvF,6FAA6F;YAC7F,4BAA4B;YAC5B,MAAM,WAAW,CAAC,WAAW,CAAC,EAAE,QAAQ,EAAE,WAAW,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QACtF,CAAC;QAED,OAAO,WAAW,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { BaseHelper, RequestIdGenerator } from '@venizia/ignis-helpers/core';\nimport { BffEnvelope } from '@/envelope/encode';\nimport type { IBffResponseEnvelope } from '@/envelope/common';\nimport type { IBffTransport } from './common/types';\n\n/**\n * No worker, no browser - the seam that makes a BFF testable in-process. It still runs the full\n * envelope round trip, and that is the whole point: a bare pass-through lets a route pass here and\n * hang over a real Worker, because only the envelope applies the synthetic origin, buffers a\n * streaming body, and reduces a thrown error to `{ text, code, args }`. A test is worth what its\n * differences from production are worth.\n *\n * What it deliberately does NOT mirror is the timeout: in-process there is no message that can be\n * lost, so a handler either settles or the caller's own test timeout fires.\n */\nexport class InProcessBffTransport extends BaseHelper implements IBffTransport {\n private readonly handler: (request: Request) => Promise<Response>;\n private readonly requestIdGenerator = new RequestIdGenerator({\n scope: InProcessBffTransport.name,\n });\n\n constructor(opts: { handler: (request: Request) => Promise<Response> }) {\n super({ scope: InProcessBffTransport.name });\n\n this.handler = opts.handler;\n }\n\n async fetch(opts: { request: Request }): Promise<Response> {\n const id = this.requestIdGenerator.nextId();\n\n const requestEnvelope = await BffEnvelope.encodeRequest({\n request: opts.request,\n id,\n url: BffEnvelope.toSyntheticUrl({ url: opts.request.url }),\n });\n\n let responseEnvelope: IBffResponseEnvelope;\n\n try {\n const response = await this.handler(BffEnvelope.decodeRequest({ envelope: requestEnvelope }));\n responseEnvelope = await BffEnvelope.encodeResponse({ response, id });\n } catch (error) {\n this.logger.for(this.fetch.name).error('Handler failed | id: %s | error: %s', id, error);\n\n // Encoded and decoded rather than rethrown: what a UI receives over a real Worker is a\n // rebuilt `ApplicationError` carrying only the normalised shape - never the original object,\n // its stack or its `extra`.\n throw BffEnvelope.decodeError({ envelope: BffEnvelope.encodeError({ id, error }) });\n }\n\n return BffEnvelope.decodeResponse({ envelope: responseEnvelope });\n }\n}\n"]}
1
+ {"version":3,"file":"in-process.js","sourceRoot":"","sources":["../../../src/transport/in-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAIhD;;;;;;;;;GASG;AACH,MAAM,OAAO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,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QACtF,CAAC;QAED,OAAO,WAAW,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { BaseHelper, RequestIdGenerator } from '@venizia/ignis-helpers/core';\nimport { BffEnvelope } from '@/envelope/encode';\nimport type { IBffResponseEnvelope } from '@/envelope/common';\nimport type { IBffTransport } from './common/types';\n\n/**\n * No worker, no browser - the seam that makes a BFF testable in-process. It still runs the full\n * envelope round trip, and that is the whole point: a bare pass-through lets a route pass here and\n * hang over a real Worker, because only the envelope applies the synthetic origin, buffers a\n * streaming body, and reduces a thrown error to `{ text, code, args }`. A test is worth what its\n * differences from production are worth.\n *\n * What it deliberately does NOT mirror is the timeout: in-process there is no message that can be\n * lost, so a handler either settles or the caller's own test timeout fires.\n */\nexport class InProcessBffTransport extends BaseHelper implements IBffTransport {\n private readonly handler: (request: Request) => Promise<Response>;\n private readonly requestIdGenerator = new RequestIdGenerator({\n scope: InProcessBffTransport.name,\n });\n\n constructor(opts: { handler: (request: Request) => Promise<Response> }) {\n super({ scope: InProcessBffTransport.name });\n\n this.handler = opts.handler;\n }\n\n async fetch(opts: { request: Request }): Promise<Response> {\n const id = this.requestIdGenerator.nextId();\n\n const requestEnvelope = await BffEnvelope.encodeRequest({\n request: opts.request,\n id,\n url: BffEnvelope.toSyntheticUrl({ url: opts.request.url }),\n });\n\n let responseEnvelope: IBffResponseEnvelope;\n\n try {\n const response = await this.handler(BffEnvelope.decodeRequest({ envelope: requestEnvelope }));\n const result = await BffEnvelope.encodeResponse({ response, id });\n responseEnvelope = result;\n } catch (error) {\n this.logger.for(this.fetch.name).error('Handler failed | id: %s | error: %s', id, error);\n\n // Encoded and decoded rather than rethrown: what a UI receives over a real Worker is a\n // rebuilt `ApplicationError` carrying only the normalised shape - never the original object,\n // its stack or its `extra`.\n throw BffEnvelope.decodeError({ envelope: BffEnvelope.encodeError({ id, error }) });\n }\n\n return BffEnvelope.decodeResponse({ envelope: responseEnvelope });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../../src/transport/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAgC,MAAM,6BAA6B,CAAC;AAGvF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGrD,OAAO,KAAK,EAEV,0BAA0B,EAC1B,QAAQ,EAET,MAAM,UAAU,CAAC;AAElB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,kBAAmB,SAAQ,UAAW,YAAW,aAAa;IACzE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAe;IAC5C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAmB;IAC3C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAqB;IACxD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAsC;IAEtE,OAAO,CAAC,IAAI,CAA+B;IAC3C,OAAO,CAAC,eAAe,CAAC,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAS;IAEzB;;;;;OAKG;IACH,OAAO,CAAC,YAAY,CAAC,CAAS;IAE9B,gGAAgG;IAChG,OAAO,CAAC,kBAAkB,CAAC,CAAU;IAErC,+EAA+E;IAC/E,OAAO,CAAC,iBAAiB,CAAC,CAAa;IAEvC,+FAA+F;IAC/F,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAyB;IAE9D,uEAAuE;IACvE,OAAO,CAAC,WAAW,CAAyB;gBAEhC,IAAI,EAAE,0BAA0B;IAkC5C,OAAO,IAAI,QAAQ;IAIb,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;IAk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AAC,iBAAiB,CAAC,CAAa;IAEvC,+FAA+F;IAC/F,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAyB;IAE9D,uEAAuE;IACvE,OAAO,CAAC,WAAW,CAAyB;gBAEhC,IAAI,EAAE,0BAA0B;IAkC5C,OAAO,IAAI,QAAQ;IAIb,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;IAkC1D,KAAK,IAAI,IAAI;YA+BC,KAAK;IA4DnB,OAAO,CAAC,YAAY;IA6BpB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,iBAAiB;IASzB;;;;;;;;OAQG;YACW,cAAc;IAoD5B,oGAAoG;IACpG,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,gBAAgB;IAWxB;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CA4EnC;YAEY,aAAa;CA0B5B"}
@@ -359,9 +359,10 @@ export class SharedBffTransport extends BaseHelper {
359
359
  const response = await this.leaderTransport.fetch({
360
360
  request: BffEnvelope.decodeRequest({ envelope }),
361
361
  });
362
+ const result = await BffEnvelope.encodeResponse({ response, id: envelope.id });
362
363
  this.channel.postMessage({
363
364
  kind: ChannelMessageKinds.RESPONSE,
364
- envelope: await BffEnvelope.encodeResponse({ response, id: envelope.id }),
365
+ envelope: result,
365
366
  });
366
367
  }
367
368
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transport/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,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AO,EAAE,WAAW,CAAC,aAAa,CAAC,EAAE,QAAQ,EAAE,CAAC;aACjD,CAAC,CAAC;YAEH,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC;gBACvB,IAAI,EAAE,mBAAmB,CAAC,QAAQ;gBAClC,QAAQ,EAAE,MAAM,WAAW,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,CAAC;aAChD,CAAC,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,2FAA2F;YAC3F,yCAAyC;YACzC,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC;iBAC5B,KAAK,CAAC,yDAAyD,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;YAExF,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC;gBACvB,IAAI,EAAE,mBAAmB,CAAC,KAAK;gBAC/B,QAAQ,EAAE,WAAW,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC;aACpC,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseHelper, getError, RequestIdGenerator } from '@venizia/ignis-helpers/core';\nimport { BffEnvelope } from '@/envelope/encode';\nimport type { IBffRequestEnvelope } from '@/envelope/common';\nimport type { IBffTransport } from '../common/types';\nimport { WorkerBffTransport } from '../worker';\nimport { BffRoles, ChannelMessageKinds, DEFAULT_CHANNEL_NAME, DEFAULT_TIMEOUT_MS } from './common';\nimport type {\n IPendingRequest,\n ISharedBffTransportOptions,\n TBffRole,\n TChannelMessage,\n} from './common';\n\n/**\n * One BFF for every tab of an origin, instead of one per tab.\n *\n * The problem it solves is not a framework limitation, it is a storage one. PGlite in\n * `opfs-ahp://` mode holds an exclusive access handle on the database file, and OPFS access handles\n * are exclusive PER ORIGIN. Measured in Chromium with two tabs of the same page: the first tab\n * works, and the second never boots its database -\n * `Failed to execute 'createSyncAccessHandle' on 'FileSystemFileHandle': Access Handles cannot be\n * created if there is another open Access Handle or Writable stream associated with the same file`.\n * The first tab is unaffected, and closing it lets the second recover on reload - so the failure is\n * contained and self-healing, but the second tab is simply dead until then.\n *\n * So exactly one tab may own the database. This transport elects that tab with the Web Locks API,\n * gives it the Worker, and forwards every other tab's request to it over a `BroadcastChannel`,\n * carried in the same envelope the Worker itself speaks. When the leader's tab closes, the lock is\n * released by the browser and a follower is promoted automatically - no heartbeat, no timeout, no\n * stale-leader window to reason about.\n *\n * A host with no `navigator.locks` runs single-tab, exactly as before. That is not a compromise:\n * measured on a plain-http origin, `navigator.locks` and `navigator.storage.getDirectory` are BOTH\n * undefined, because both are secure-context only. Wherever OPFS works the lock exists, and where it\n * does not the database could not have started either.\n */\nexport class SharedBffTransport extends BaseHelper implements IBffTransport {\n private readonly createWorker: () => Worker;\n private readonly channel: BroadcastChannel;\n private readonly lockName: string;\n private readonly timeoutMs: number;\n private readonly requestIdGenerator: RequestIdGenerator;\n private readonly pendingRequests = new Map<string, IPendingRequest>();\n\n private role: TBffRole = BffRoles.ELECTING;\n private leaderTransport?: WorkerBffTransport;\n private isClosed = false;\n\n /**\n * Held because THIS class created it. `WorkerBffTransport.close()` deliberately leaves a worker\n * running - it did not create the one it was handed - so without this reference the worker would\n * outlive `close()` still holding the exclusive OPFS access handle, while the lock has already\n * gone to another tab that opens the same database.\n */\n private leaderWorker?: Worker;\n\n /** Set when `createWorker()` throws, so callers get that failure instead of parking forever. */\n private leaderStartupError?: unknown;\n\n /** Resolving this releases the Web Lock, which is what promotes a follower. */\n private releaseLeadership?: () => void;\n\n /** Drops this tab out of the lock QUEUE on close, so a closed transport cannot be promoted. */\n private readonly leadershipQueueAbort = new AbortController();\n\n /** Callers parked in `fetch()` while the election is still running. */\n private roleWaiters: Array<() => void> = [];\n\n constructor(opts: ISharedBffTransportOptions) {\n super({ scope: opts.scope ?? SharedBffTransport.name });\n\n const channelName = opts.channelName ?? DEFAULT_CHANNEL_NAME;\n\n this.createWorker = opts.createWorker;\n this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.lockName = `${channelName}.leader`;\n this.requestIdGenerator = new RequestIdGenerator({ scope: SharedBffTransport.name });\n\n // Attached BEFORE the election starts: a tab that becomes leader a moment later must not miss a\n // request a follower posted while it was still deciding.\n this.channel = new BroadcastChannel(channelName);\n this.channel.addEventListener('message', this.handleChannelMessage);\n\n // A failed election must not leave `fetch()` parked forever waiting for a role that never\n // arrives: this tab falls back to serving itself, which is the pre-election behaviour.\n this.elect().catch((error: unknown) => {\n // `close()` aborts the queued lock request, and the rejection that produces is the expected\n // end of the election - not a failure to report.\n if (this.isClosed) {\n return;\n }\n\n this.logger\n .for(this.elect.name)\n .error('Leader election failed, falling back to single-tab | error: %s', error);\n\n if (this.role === BffRoles.ELECTING) {\n this.becomeLeader();\n }\n });\n }\n\n getRole(): TBffRole {\n return this.role;\n }\n\n async fetch(opts: { request: Request }): Promise<Response> {\n if (this.isClosed) {\n throw getError({\n message: '[SharedBffTransport] The transport is closed | open a new one to make requests',\n });\n }\n\n await this.whenRoleSettled();\n\n // Re-checked AFTER the await: `close()` can land while the election is still running, and\n // posting then reaches a channel that is already closed - the caller would get a raw\n // `DOMException` instead of this error, and a pending entry plus a live timer would be left\n // behind on a transport nothing can settle.\n if (this.isClosed) {\n throw getError({\n message: '[SharedBffTransport] The transport is closed | open a new one to make requests',\n });\n }\n\n if (this.leaderStartupError) {\n throw getError({\n message:\n '[SharedBffTransport] This tab leads but its BFF worker never started | reload the page',\n cause: this.leaderStartupError,\n });\n }\n\n if (this.role === BffRoles.LEADER && this.leaderTransport) {\n return this.leaderTransport.fetch(opts);\n }\n\n return this.fetchViaLeader(opts);\n }\n\n close(): void {\n this.isClosed = true;\n\n // A follower is parked in the lock QUEUE rather than holding anything. Without this it stays\n // queued after close, and the browser would eventually hand leadership to a dead transport -\n // which returns straight away, but only after the tab that could have served was skipped.\n this.leadershipQueueAbort.abort();\n\n // ORDER IS THE POINT, and it is the opposite of the obvious one. The worker has to be GONE\n // before the lock is released: releasing first promotes another tab, which opens the same OPFS\n // database while this worker still holds the exclusive access handle - the exact failure this\n // transport exists to prevent, reintroduced by its own teardown.\n //\n // `terminate()` is abrupt by design. It is no worse than the tab-close path the browser already\n // takes on every leader, and leaving the worker alive is strictly worse than an abrupt stop.\n this.leaderTransport?.close();\n this.leaderTransport = undefined;\n this.leaderWorker?.terminate();\n this.leaderWorker = undefined;\n\n // Only now: the next tab may open the database.\n this.releaseLeadership?.();\n this.releaseLeadership = undefined;\n\n this.channel.removeEventListener('message', this.handleChannelMessage);\n this.channel.close();\n\n this.rejectAllPending({ reason: 'the transport was closed' });\n this.settleRoleWaiters();\n }\n\n private async elect(): Promise<void> {\n const locks = globalThis.navigator?.locks;\n\n if (!locks) {\n this.logger\n .for(this.elect.name)\n .warn(\n 'navigator.locks is unavailable - running single-tab | a second tab cannot open the same OPFS database',\n );\n this.becomeLeader();\n return;\n }\n\n // `ifAvailable` answers NOW instead of queueing, which is what lets this tab find out it is a\n // follower rather than hanging until the current leader goes away.\n const hasWon = await locks.request(this.lockName, { ifAvailable: true }, async (lock) => {\n if (!lock) {\n return false;\n }\n\n // Symmetric with the queued branch below, and not defensive padding. A real `LockManager`\n // grants from a queued task - it never runs this callback synchronously inside `request()` -\n // so `close()` can land between the constructor and this line. Without the guard a CLOSED\n // transport starts a worker, reports itself leader, and then holds the lock for the lifetime\n // of the page: `close()` has already read and cleared `releaseLeadership`, so the assignment\n // `heldUntilClosed()` makes below can never be resolved by anything. No other tab is ever\n // promoted, and this one answers nobody - its channel listener is already detached.\n //\n // Returning true, not false: this tab DID hold the lock. Returning releases it immediately,\n // which is exactly what a closed transport should do with it.\n if (this.isClosed) {\n return true;\n }\n\n this.becomeLeader();\n await this.heldUntilClosed();\n return true;\n });\n\n if (hasWon || this.isClosed) {\n return;\n }\n\n this.becomeFollower();\n\n // Queues behind the current leader. The browser releases its lock when that tab goes away - a\n // crash included - so this resolves without anything having to detect the death.\n await locks.request(this.lockName, { signal: this.leadershipQueueAbort.signal }, async () => {\n if (this.isClosed) {\n return;\n }\n\n this.logger\n .for(this.elect.name)\n .info('Promoted to leader | previous leader released the lock');\n this.becomeLeader();\n await this.heldUntilClosed();\n });\n }\n\n private becomeLeader(): void {\n // Anything this tab had in flight was addressed to the leader that just went away. It cannot be\n // replayed - a write may well have been applied - so it is failed explicitly rather than left\n // to run out its timeout under a leader that will never answer it.\n this.rejectAllPending({\n reason: 'the leader serving it went away before this tab was promoted',\n });\n\n try {\n this.leaderWorker = this.createWorker();\n this.leaderTransport = new WorkerBffTransport({\n worker: this.leaderWorker,\n timeoutMs: this.timeoutMs,\n });\n } catch (error) {\n // A CSP refusal or a bad worker URL must still SETTLE the role. `whenRoleSettled()` has no\n // timeout of its own and the per-request timer is armed only inside `fetchViaLeader()`, which\n // this tab never reaches - so leaving the role unsettled hangs every caller forever, with no\n // error and no log per request.\n this.leaderStartupError = error;\n this.logger\n .for(this.becomeLeader.name)\n .error('Could not start the BFF worker | error: %s', error);\n }\n\n this.role = BffRoles.LEADER;\n this.settleRoleWaiters();\n }\n\n private becomeFollower(): void {\n this.role = BffRoles.FOLLOWER;\n this.settleRoleWaiters();\n }\n\n private heldUntilClosed(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.releaseLeadership = resolve;\n });\n }\n\n private whenRoleSettled(): Promise<void> {\n if (this.role !== BffRoles.ELECTING) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n this.roleWaiters.push(resolve);\n });\n }\n\n private settleRoleWaiters(): void {\n const waiters = this.roleWaiters;\n this.roleWaiters = [];\n\n for (const waiter of waiters) {\n waiter();\n }\n }\n\n /**\n * The caller's `AbortSignal` is honoured HERE as well as in `WorkerBffTransport`. Without it the\n * same page code behaves differently depending on which tab won the lock: abort works in the\n * leader and silently does nothing in every follower, so a data provider that aborts on unmount\n * leaves promises pending for the full timeout in every tab but one.\n *\n * Aborting settles the CALLER. It does not cancel the leader's work - there is no cancel message,\n * and a write already dispatched cannot be taken back.\n */\n private async fetchViaLeader(opts: { request: Request }): Promise<Response> {\n const { signal } = opts.request;\n\n if (signal?.aborted) {\n throw this.toAbortError({ signal });\n }\n\n const id = this.requestIdGenerator.nextId();\n\n const envelope = await BffEnvelope.encodeRequest({\n request: opts.request,\n id,\n url: BffEnvelope.toSyntheticUrl({ url: opts.request.url }),\n });\n\n return new Promise<Response>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.takePending({ id })?.reject(\n getError({\n message: `[SharedBffTransport] Timed out waiting for the leader tab | id: ${id} | timeoutMs: ${this.timeoutMs}`,\n }),\n );\n }, this.timeoutMs);\n\n const handleAbort = (): void => {\n this.takePending({ id })?.reject(this.toAbortError({ signal }));\n };\n signal?.addEventListener('abort', handleAbort);\n\n this.pendingRequests.set(id, {\n resolve,\n reject,\n release: () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', handleAbort);\n },\n });\n\n // Buffering the body took an await, and `addEventListener('abort')` never fires on a signal\n // that aborted before it was attached - without this re-read that window loses the abort.\n if (signal?.aborted) {\n handleAbort();\n return;\n }\n\n this.channel.postMessage({\n kind: ChannelMessageKinds.REQUEST,\n envelope,\n } satisfies TChannelMessage);\n });\n }\n\n /** `signal.reason` first, the way `globalThis.fetch` rejects, so a custom abort reason survives. */\n private toAbortError(opts: { signal?: AbortSignal }): unknown {\n return (\n opts.signal?.reason ??\n getError({ message: '[SharedBffTransport] The request was aborted by its caller' })\n );\n }\n\n private takePending(opts: { id: string }): IPendingRequest | undefined {\n const pending = this.pendingRequests.get(opts.id);\n if (!pending) {\n return undefined;\n }\n\n this.pendingRequests.delete(opts.id);\n pending.release();\n return pending;\n }\n\n private rejectAllPending(opts: { reason: string }): void {\n const pendingRequestsKeys = [...this.pendingRequests.keys()];\n for (const id of pendingRequestsKeys) {\n this.takePending({ id })?.reject(\n getError({\n message: `[SharedBffTransport] Request abandoned | id: ${id} | reason: ${opts.reason}`,\n }),\n );\n }\n }\n\n /**\n * A `BroadcastChannel` never delivers a message to the instance that sent it, so a leader does not\n * hear its own answers and a follower does not hear its own requests. Every tab does hear every\n * OTHER tab, which is why a response is matched by id and silently ignored when it belongs to\n * someone else.\n */\n private readonly handleChannelMessage = (event: MessageEvent): void => {\n const message = event.data as TChannelMessage | undefined;\n\n switch (message?.kind) {\n case ChannelMessageKinds.REQUEST: {\n if (this.role !== BffRoles.LEADER) {\n return;\n }\n\n // `serveAsLeader` answers its own failures on the channel; this catch is for the one case\n // it cannot - the channel itself refusing the message, e.g. a body that will not clone.\n this.serveAsLeader({ envelope: message.envelope }).catch((error: unknown) => {\n this.logger\n .for(this.serveAsLeader.name)\n .error(\n 'Could not answer a follower at all | id: %s | error: %s',\n message.envelope.id,\n error,\n );\n });\n return;\n }\n\n // Both decodes are guarded. The channel is origin-wide and its name is the application's, not\n // a secret, and version skew is the realistic trigger: a long-lived tab on v1 and a new tab\n // on v2 share the same channel and lock BY DESIGN. An envelope this build cannot read must\n // fail its caller, never leave the promise unsettled for the full timeout.\n case ChannelMessageKinds.RESPONSE: {\n const pending = this.takePending({ id: message.envelope.id });\n if (!pending) {\n return;\n }\n\n try {\n pending.resolve(BffEnvelope.decodeResponse({ envelope: message.envelope }));\n } catch (error) {\n this.logger\n .for(this.handleChannelMessage.name)\n .error(\n 'Undecodable response envelope | id: %s | error: %s',\n message.envelope.id,\n error,\n );\n pending.reject(\n getError({\n message: `[SharedBffTransport] The leader's response could not be decoded | id: ${message.envelope.id}`,\n cause: error,\n }),\n );\n }\n return;\n }\n\n case ChannelMessageKinds.ERROR: {\n const pending = this.takePending({ id: message.envelope.id });\n if (!pending) {\n return;\n }\n\n try {\n pending.reject(BffEnvelope.decodeError({ envelope: message.envelope }));\n } catch (error) {\n pending.reject(\n getError({\n message: `[SharedBffTransport] The leader's error envelope could not be decoded | id: ${message.envelope.id}`,\n cause: error,\n }),\n );\n }\n return;\n }\n\n default: {\n return;\n }\n }\n };\n\n private async serveAsLeader(opts: { envelope: IBffRequestEnvelope }): Promise<void> {\n const { envelope } = opts;\n\n try {\n const response = await this.leaderTransport!.fetch({\n request: BffEnvelope.decodeRequest({ envelope }),\n });\n\n this.channel.postMessage({\n kind: ChannelMessageKinds.RESPONSE,\n envelope: await BffEnvelope.encodeResponse({ response, id: envelope.id }),\n } satisfies TChannelMessage);\n } catch (error) {\n // The follower gets the failure as a failure, rather than waiting out a timeout that would\n // tell it nothing about what went wrong.\n this.logger\n .for(this.serveAsLeader.name)\n .error('Failed to serve a follower request | id: %s | error: %s', envelope.id, error);\n\n this.channel.postMessage({\n kind: ChannelMessageKinds.ERROR,\n envelope: BffEnvelope.encodeError({ id: envelope.id, error }),\n } satisfies TChannelMessage);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../../src/transport/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAQnG;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,kBAAmB,SAAQ,UAAU;IAgChD,YAAY,IAAgC;QAC1C,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,kBAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;QA3BzC,oBAAe,GAAG,IAAI,GAAG,EAA2B,CAAC;QAE9D,SAAI,GAAa,QAAQ,CAAC,QAAQ,CAAC;QAEnC,aAAQ,GAAG,KAAK,CAAC;QAgBzB,+FAA+F;QAC9E,yBAAoB,GAAG,IAAI,eAAe,EAAE,CA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5B,KAAK,CAAC,yDAAyD,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;YAExF,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC;gBACvB,IAAI,EAAE,mBAAmB,CAAC,KAAK;gBAC/B,QAAQ,EAAE,WAAW,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC;aACpC,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;CACF","sourcesContent":["import { BaseHelper, getError, RequestIdGenerator } from '@venizia/ignis-helpers/core';\nimport { BffEnvelope } from '@/envelope/encode';\nimport type { IBffRequestEnvelope } from '@/envelope/common';\nimport type { IBffTransport } from '../common/types';\nimport { WorkerBffTransport } from '../worker';\nimport { BffRoles, ChannelMessageKinds, DEFAULT_CHANNEL_NAME, DEFAULT_TIMEOUT_MS } from './common';\nimport type {\n IPendingRequest,\n ISharedBffTransportOptions,\n TBffRole,\n TChannelMessage,\n} from './common';\n\n/**\n * One BFF for every tab of an origin, instead of one per tab.\n *\n * The problem it solves is not a framework limitation, it is a storage one. PGlite in\n * `opfs-ahp://` mode holds an exclusive access handle on the database file, and OPFS access handles\n * are exclusive PER ORIGIN. Measured in Chromium with two tabs of the same page: the first tab\n * works, and the second never boots its database -\n * `Failed to execute 'createSyncAccessHandle' on 'FileSystemFileHandle': Access Handles cannot be\n * created if there is another open Access Handle or Writable stream associated with the same file`.\n * The first tab is unaffected, and closing it lets the second recover on reload - so the failure is\n * contained and self-healing, but the second tab is simply dead until then.\n *\n * So exactly one tab may own the database. This transport elects that tab with the Web Locks API,\n * gives it the Worker, and forwards every other tab's request to it over a `BroadcastChannel`,\n * carried in the same envelope the Worker itself speaks. When the leader's tab closes, the lock is\n * released by the browser and a follower is promoted automatically - no heartbeat, no timeout, no\n * stale-leader window to reason about.\n *\n * A host with no `navigator.locks` runs single-tab, exactly as before. That is not a compromise:\n * measured on a plain-http origin, `navigator.locks` and `navigator.storage.getDirectory` are BOTH\n * undefined, because both are secure-context only. Wherever OPFS works the lock exists, and where it\n * does not the database could not have started either.\n */\nexport class SharedBffTransport extends BaseHelper implements IBffTransport {\n private readonly createWorker: () => Worker;\n private readonly channel: BroadcastChannel;\n private readonly lockName: string;\n private readonly timeoutMs: number;\n private readonly requestIdGenerator: RequestIdGenerator;\n private readonly pendingRequests = new Map<string, IPendingRequest>();\n\n private role: TBffRole = BffRoles.ELECTING;\n private leaderTransport?: WorkerBffTransport;\n private isClosed = false;\n\n /**\n * Held because THIS class created it. `WorkerBffTransport.close()` deliberately leaves a worker\n * running - it did not create the one it was handed - so without this reference the worker would\n * outlive `close()` still holding the exclusive OPFS access handle, while the lock has already\n * gone to another tab that opens the same database.\n */\n private leaderWorker?: Worker;\n\n /** Set when `createWorker()` throws, so callers get that failure instead of parking forever. */\n private leaderStartupError?: unknown;\n\n /** Resolving this releases the Web Lock, which is what promotes a follower. */\n private releaseLeadership?: () => void;\n\n /** Drops this tab out of the lock QUEUE on close, so a closed transport cannot be promoted. */\n private readonly leadershipQueueAbort = new AbortController();\n\n /** Callers parked in `fetch()` while the election is still running. */\n private roleWaiters: Array<() => void> = [];\n\n constructor(opts: ISharedBffTransportOptions) {\n super({ scope: opts.scope ?? SharedBffTransport.name });\n\n const channelName = opts.channelName ?? DEFAULT_CHANNEL_NAME;\n\n this.createWorker = opts.createWorker;\n this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.lockName = `${channelName}.leader`;\n this.requestIdGenerator = new RequestIdGenerator({ scope: SharedBffTransport.name });\n\n // Attached BEFORE the election starts: a tab that becomes leader a moment later must not miss a\n // request a follower posted while it was still deciding.\n this.channel = new BroadcastChannel(channelName);\n this.channel.addEventListener('message', this.handleChannelMessage);\n\n // A failed election must not leave `fetch()` parked forever waiting for a role that never\n // arrives: this tab falls back to serving itself, which is the pre-election behaviour.\n this.elect().catch((error: unknown) => {\n // `close()` aborts the queued lock request, and the rejection that produces is the expected\n // end of the election - not a failure to report.\n if (this.isClosed) {\n return;\n }\n\n this.logger\n .for(this.elect.name)\n .error('Leader election failed, falling back to single-tab | error: %s', error);\n\n if (this.role === BffRoles.ELECTING) {\n this.becomeLeader();\n }\n });\n }\n\n getRole(): TBffRole {\n return this.role;\n }\n\n async fetch(opts: { request: Request }): Promise<Response> {\n if (this.isClosed) {\n throw getError({\n message: '[SharedBffTransport] The transport is closed | open a new one to make requests',\n });\n }\n\n await this.whenRoleSettled();\n\n // Re-checked AFTER the await: `close()` can land while the election is still running, and\n // posting then reaches a channel that is already closed - the caller would get a raw\n // `DOMException` instead of this error, and a pending entry plus a live timer would be left\n // behind on a transport nothing can settle.\n if (this.isClosed) {\n throw getError({\n message: '[SharedBffTransport] The transport is closed | open a new one to make requests',\n });\n }\n\n if (this.leaderStartupError) {\n throw getError({\n message:\n '[SharedBffTransport] This tab leads but its BFF worker never started | reload the page',\n cause: this.leaderStartupError,\n });\n }\n\n if (this.role === BffRoles.LEADER && this.leaderTransport) {\n return this.leaderTransport.fetch(opts);\n }\n\n return this.fetchViaLeader(opts);\n }\n\n close(): void {\n this.isClosed = true;\n\n // A follower is parked in the lock QUEUE rather than holding anything. Without this it stays\n // queued after close, and the browser would eventually hand leadership to a dead transport -\n // which returns straight away, but only after the tab that could have served was skipped.\n this.leadershipQueueAbort.abort();\n\n // ORDER IS THE POINT, and it is the opposite of the obvious one. The worker has to be GONE\n // before the lock is released: releasing first promotes another tab, which opens the same OPFS\n // database while this worker still holds the exclusive access handle - the exact failure this\n // transport exists to prevent, reintroduced by its own teardown.\n //\n // `terminate()` is abrupt by design. It is no worse than the tab-close path the browser already\n // takes on every leader, and leaving the worker alive is strictly worse than an abrupt stop.\n this.leaderTransport?.close();\n this.leaderTransport = undefined;\n this.leaderWorker?.terminate();\n this.leaderWorker = undefined;\n\n // Only now: the next tab may open the database.\n this.releaseLeadership?.();\n this.releaseLeadership = undefined;\n\n this.channel.removeEventListener('message', this.handleChannelMessage);\n this.channel.close();\n\n this.rejectAllPending({ reason: 'the transport was closed' });\n this.settleRoleWaiters();\n }\n\n private async elect(): Promise<void> {\n const locks = globalThis.navigator?.locks;\n\n if (!locks) {\n this.logger\n .for(this.elect.name)\n .warn(\n 'navigator.locks is unavailable - running single-tab | a second tab cannot open the same OPFS database',\n );\n this.becomeLeader();\n return;\n }\n\n // `ifAvailable` answers NOW instead of queueing, which is what lets this tab find out it is a\n // follower rather than hanging until the current leader goes away.\n const hasWon = await locks.request(this.lockName, { ifAvailable: true }, async (lock) => {\n if (!lock) {\n return false;\n }\n\n // Symmetric with the queued branch below, and not defensive padding. A real `LockManager`\n // grants from a queued task - it never runs this callback synchronously inside `request()` -\n // so `close()` can land between the constructor and this line. Without the guard a CLOSED\n // transport starts a worker, reports itself leader, and then holds the lock for the lifetime\n // of the page: `close()` has already read and cleared `releaseLeadership`, so the assignment\n // `heldUntilClosed()` makes below can never be resolved by anything. No other tab is ever\n // promoted, and this one answers nobody - its channel listener is already detached.\n //\n // Returning true, not false: this tab DID hold the lock. Returning releases it immediately,\n // which is exactly what a closed transport should do with it.\n if (this.isClosed) {\n return true;\n }\n\n this.becomeLeader();\n await this.heldUntilClosed();\n return true;\n });\n\n if (hasWon || this.isClosed) {\n return;\n }\n\n this.becomeFollower();\n\n // Queues behind the current leader. The browser releases its lock when that tab goes away - a\n // crash included - so this resolves without anything having to detect the death.\n await locks.request(this.lockName, { signal: this.leadershipQueueAbort.signal }, async () => {\n if (this.isClosed) {\n return;\n }\n\n this.logger\n .for(this.elect.name)\n .info('Promoted to leader | previous leader released the lock');\n this.becomeLeader();\n await this.heldUntilClosed();\n });\n }\n\n private becomeLeader(): void {\n // Anything this tab had in flight was addressed to the leader that just went away. It cannot be\n // replayed - a write may well have been applied - so it is failed explicitly rather than left\n // to run out its timeout under a leader that will never answer it.\n this.rejectAllPending({\n reason: 'the leader serving it went away before this tab was promoted',\n });\n\n try {\n this.leaderWorker = this.createWorker();\n this.leaderTransport = new WorkerBffTransport({\n worker: this.leaderWorker,\n timeoutMs: this.timeoutMs,\n });\n } catch (error) {\n // A CSP refusal or a bad worker URL must still SETTLE the role. `whenRoleSettled()` has no\n // timeout of its own and the per-request timer is armed only inside `fetchViaLeader()`, which\n // this tab never reaches - so leaving the role unsettled hangs every caller forever, with no\n // error and no log per request.\n this.leaderStartupError = error;\n this.logger\n .for(this.becomeLeader.name)\n .error('Could not start the BFF worker | error: %s', error);\n }\n\n this.role = BffRoles.LEADER;\n this.settleRoleWaiters();\n }\n\n private becomeFollower(): void {\n this.role = BffRoles.FOLLOWER;\n this.settleRoleWaiters();\n }\n\n private heldUntilClosed(): Promise<void> {\n return new Promise<void>((resolve) => {\n this.releaseLeadership = resolve;\n });\n }\n\n private whenRoleSettled(): Promise<void> {\n if (this.role !== BffRoles.ELECTING) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n this.roleWaiters.push(resolve);\n });\n }\n\n private settleRoleWaiters(): void {\n const waiters = this.roleWaiters;\n this.roleWaiters = [];\n\n for (const waiter of waiters) {\n waiter();\n }\n }\n\n /**\n * The caller's `AbortSignal` is honoured HERE as well as in `WorkerBffTransport`. Without it the\n * same page code behaves differently depending on which tab won the lock: abort works in the\n * leader and silently does nothing in every follower, so a data provider that aborts on unmount\n * leaves promises pending for the full timeout in every tab but one.\n *\n * Aborting settles the CALLER. It does not cancel the leader's work - there is no cancel message,\n * and a write already dispatched cannot be taken back.\n */\n private async fetchViaLeader(opts: { request: Request }): Promise<Response> {\n const { signal } = opts.request;\n\n if (signal?.aborted) {\n throw this.toAbortError({ signal });\n }\n\n const id = this.requestIdGenerator.nextId();\n\n const envelope = await BffEnvelope.encodeRequest({\n request: opts.request,\n id,\n url: BffEnvelope.toSyntheticUrl({ url: opts.request.url }),\n });\n\n return new Promise<Response>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.takePending({ id })?.reject(\n getError({\n message: `[SharedBffTransport] Timed out waiting for the leader tab | id: ${id} | timeoutMs: ${this.timeoutMs}`,\n }),\n );\n }, this.timeoutMs);\n\n const handleAbort = (): void => {\n this.takePending({ id })?.reject(this.toAbortError({ signal }));\n };\n signal?.addEventListener('abort', handleAbort);\n\n this.pendingRequests.set(id, {\n resolve,\n reject,\n release: () => {\n clearTimeout(timer);\n signal?.removeEventListener('abort', handleAbort);\n },\n });\n\n // Buffering the body took an await, and `addEventListener('abort')` never fires on a signal\n // that aborted before it was attached - without this re-read that window loses the abort.\n if (signal?.aborted) {\n handleAbort();\n return;\n }\n\n this.channel.postMessage({\n kind: ChannelMessageKinds.REQUEST,\n envelope,\n } satisfies TChannelMessage);\n });\n }\n\n /** `signal.reason` first, the way `globalThis.fetch` rejects, so a custom abort reason survives. */\n private toAbortError(opts: { signal?: AbortSignal }): unknown {\n return (\n opts.signal?.reason ??\n getError({ message: '[SharedBffTransport] The request was aborted by its caller' })\n );\n }\n\n private takePending(opts: { id: string }): IPendingRequest | undefined {\n const pending = this.pendingRequests.get(opts.id);\n if (!pending) {\n return undefined;\n }\n\n this.pendingRequests.delete(opts.id);\n pending.release();\n return pending;\n }\n\n private rejectAllPending(opts: { reason: string }): void {\n const pendingRequestsKeys = [...this.pendingRequests.keys()];\n for (const id of pendingRequestsKeys) {\n this.takePending({ id })?.reject(\n getError({\n message: `[SharedBffTransport] Request abandoned | id: ${id} | reason: ${opts.reason}`,\n }),\n );\n }\n }\n\n /**\n * A `BroadcastChannel` never delivers a message to the instance that sent it, so a leader does not\n * hear its own answers and a follower does not hear its own requests. Every tab does hear every\n * OTHER tab, which is why a response is matched by id and silently ignored when it belongs to\n * someone else.\n */\n private readonly handleChannelMessage = (event: MessageEvent): void => {\n const message = event.data as TChannelMessage | undefined;\n\n switch (message?.kind) {\n case ChannelMessageKinds.REQUEST: {\n if (this.role !== BffRoles.LEADER) {\n return;\n }\n\n // `serveAsLeader` answers its own failures on the channel; this catch is for the one case\n // it cannot - the channel itself refusing the message, e.g. a body that will not clone.\n this.serveAsLeader({ envelope: message.envelope }).catch((error: unknown) => {\n this.logger\n .for(this.serveAsLeader.name)\n .error(\n 'Could not answer a follower at all | id: %s | error: %s',\n message.envelope.id,\n error,\n );\n });\n return;\n }\n\n // Both decodes are guarded. The channel is origin-wide and its name is the application's, not\n // a secret, and version skew is the realistic trigger: a long-lived tab on v1 and a new tab\n // on v2 share the same channel and lock BY DESIGN. An envelope this build cannot read must\n // fail its caller, never leave the promise unsettled for the full timeout.\n case ChannelMessageKinds.RESPONSE: {\n const pending = this.takePending({ id: message.envelope.id });\n if (!pending) {\n return;\n }\n\n try {\n pending.resolve(BffEnvelope.decodeResponse({ envelope: message.envelope }));\n } catch (error) {\n this.logger\n .for(this.handleChannelMessage.name)\n .error(\n 'Undecodable response envelope | id: %s | error: %s',\n message.envelope.id,\n error,\n );\n pending.reject(\n getError({\n message: `[SharedBffTransport] The leader's response could not be decoded | id: ${message.envelope.id}`,\n cause: error,\n }),\n );\n }\n return;\n }\n\n case ChannelMessageKinds.ERROR: {\n const pending = this.takePending({ id: message.envelope.id });\n if (!pending) {\n return;\n }\n\n try {\n pending.reject(BffEnvelope.decodeError({ envelope: message.envelope }));\n } catch (error) {\n pending.reject(\n getError({\n message: `[SharedBffTransport] The leader's error envelope could not be decoded | id: ${message.envelope.id}`,\n cause: error,\n }),\n );\n }\n return;\n }\n\n default: {\n return;\n }\n }\n };\n\n private async serveAsLeader(opts: { envelope: IBffRequestEnvelope }): Promise<void> {\n const { envelope } = opts;\n\n try {\n const response = await this.leaderTransport!.fetch({\n request: BffEnvelope.decodeRequest({ envelope }),\n });\n\n const result = await BffEnvelope.encodeResponse({ response, id: envelope.id });\n this.channel.postMessage({\n kind: ChannelMessageKinds.RESPONSE,\n envelope: result,\n } satisfies TChannelMessage);\n } catch (error) {\n // The follower gets the failure as a failure, rather than waiting out a timeout that would\n // tell it nothing about what went wrong.\n this.logger\n .for(this.serveAsLeader.name)\n .error('Failed to serve a follower request | id: %s | error: %s', envelope.id, error);\n\n this.channel.postMessage({\n kind: ChannelMessageKinds.ERROR,\n envelope: BffEnvelope.encodeError({ id: envelope.id, error }),\n } satisfies TChannelMessage);\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-worker",
3
- "version": "0.4.6",
3
+ "version": "0.4.7-0",
4
4
  "description": "Browser Web Worker host for the IGNIS framework: the request/response envelope, the transport contract, and WorkerApplication - the layer that listens on `onmessage` instead of a socket, so a RestApplication can serve its controllers with no server anywhere.",
5
5
  "keywords": [
6
6
  "browser",
@@ -56,14 +56,14 @@
56
56
  "prepublishOnly": "make rebuild"
57
57
  },
58
58
  "dependencies": {
59
- "@venizia/ignis-helpers": "0.4.6",
60
- "@venizia/ignis-inversion": "0.4.5",
61
- "@venizia/ignis-kernel": "0.4.6",
59
+ "@venizia/ignis-helpers": "0.4.7-0",
60
+ "@venizia/ignis-inversion": "0.4.6-0",
61
+ "@venizia/ignis-kernel": "0.4.7-0",
62
62
  "reflect-metadata": "^0.2.2"
63
63
  },
64
64
  "devDependencies": {
65
65
  "@types/bun": "^1.4.3",
66
- "@venizia/dev-configs": "0.4.6",
66
+ "@venizia/dev-configs": "0.4.7-0",
67
67
  "eslint": "^10.13.0",
68
68
  "oxlint": "1.89.0",
69
69
  "oxlint-tsgolint": "7.0.2004",