ras-stack 3.1.1 → 4.0.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.
Files changed (98) hide show
  1. package/README.md +10 -10
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/auth/index.js +1 -1
  4. package/dist/auth/index.js.map +1 -1
  5. package/dist/auth/origins.d.ts +2 -0
  6. package/dist/auth/origins.js +6 -0
  7. package/dist/auth/origins.js.map +1 -1
  8. package/dist/conformance/index.d.ts +0 -57
  9. package/dist/conformance/index.js +1 -257
  10. package/dist/conformance/index.js.map +1 -1
  11. package/dist/database/libsql.d.ts +14 -0
  12. package/dist/database/libsql.js +31 -0
  13. package/dist/database/libsql.js.map +1 -0
  14. package/dist/database/postgres.d.ts +0 -5
  15. package/dist/database/postgres.js +0 -34
  16. package/dist/database/postgres.js.map +1 -1
  17. package/dist/database/pragmas.d.ts +7 -0
  18. package/dist/database/pragmas.js +12 -0
  19. package/dist/database/pragmas.js.map +1 -0
  20. package/dist/database/sqlite.d.ts +2 -9
  21. package/dist/database/sqlite.js +3 -28
  22. package/dist/database/sqlite.js.map +1 -1
  23. package/dist/email/index.d.ts +0 -11
  24. package/dist/email/index.js +6 -9
  25. package/dist/email/index.js.map +1 -1
  26. package/dist/posthog/client.d.ts +0 -6
  27. package/dist/posthog/client.js +4 -13
  28. package/dist/posthog/client.js.map +1 -1
  29. package/dist/posthog/config.d.ts +1 -0
  30. package/dist/posthog/config.js +2 -0
  31. package/dist/posthog/config.js.map +1 -1
  32. package/dist/posthog/index.d.ts +2 -2
  33. package/dist/posthog/index.js +2 -2
  34. package/dist/posthog/index.js.map +1 -1
  35. package/dist/posthog/proxy.d.ts +0 -1
  36. package/dist/posthog/proxy.js +1 -3
  37. package/dist/posthog/proxy.js.map +1 -1
  38. package/dist/posthog/react.d.ts +1 -2
  39. package/dist/posthog/react.js +1 -2
  40. package/dist/posthog/react.js.map +1 -1
  41. package/dist/posthog/request.d.ts +0 -3
  42. package/dist/posthog/request.js +3 -3
  43. package/dist/posthog/request.js.map +1 -1
  44. package/dist/posthog/server.d.ts +1 -3
  45. package/dist/posthog/server.js +2 -2
  46. package/dist/posthog/server.js.map +1 -1
  47. package/dist/preview/cloudflare.js +1 -1
  48. package/dist/preview/cloudflare.js.map +1 -1
  49. package/dist/preview/dokploy-cli.js +1 -1
  50. package/dist/preview/dokploy-cli.js.map +1 -1
  51. package/dist/preview/dokploy-preview.d.ts +102 -0
  52. package/dist/preview/dokploy-preview.js +377 -0
  53. package/dist/preview/dokploy-preview.js.map +1 -0
  54. package/dist/preview/dokploy.d.ts +2 -102
  55. package/dist/preview/dokploy.js +1 -376
  56. package/dist/preview/dokploy.js.map +1 -1
  57. package/dist/preview/github.js +1 -1
  58. package/dist/preview/github.js.map +1 -1
  59. package/dist/realtime/client.d.ts +1 -11
  60. package/dist/realtime/client.js +2 -98
  61. package/dist/realtime/client.js.map +1 -1
  62. package/dist/realtime/index.d.ts +0 -2
  63. package/dist/realtime/index.js +0 -1
  64. package/dist/realtime/index.js.map +1 -1
  65. package/dist/realtime/react.d.ts +1 -4
  66. package/dist/realtime/react.js +22 -26
  67. package/dist/realtime/react.js.map +1 -1
  68. package/dist/runtime/index.d.ts +2 -64
  69. package/dist/runtime/index.js +1 -255
  70. package/dist/runtime/index.js.map +1 -1
  71. package/dist/runtime/stack.d.ts +64 -0
  72. package/dist/runtime/stack.js +252 -0
  73. package/dist/runtime/stack.js.map +1 -0
  74. package/dist/server/errors.d.ts +0 -22
  75. package/dist/server/errors.js +0 -44
  76. package/dist/server/errors.js.map +1 -1
  77. package/dist/server/health.d.ts +7 -4
  78. package/dist/server/health.js +3 -7
  79. package/dist/server/health.js.map +1 -1
  80. package/dist/server/index.d.ts +2 -10
  81. package/dist/server/index.js +1 -5
  82. package/dist/server/index.js.map +1 -1
  83. package/dist/tanstack/client.d.ts +11 -0
  84. package/dist/tanstack/client.js +33 -0
  85. package/dist/tanstack/client.js.map +1 -0
  86. package/dist/tanstack/middleware.d.ts +5 -1
  87. package/dist/tanstack/middleware.js +20 -5
  88. package/dist/tanstack/middleware.js.map +1 -1
  89. package/dist/tanstack/server.d.ts +2 -11
  90. package/dist/tanstack/server.js +2 -6
  91. package/dist/tanstack/server.js.map +1 -1
  92. package/dist/uploads/index.d.ts +0 -6
  93. package/dist/uploads/index.js +0 -25
  94. package/dist/uploads/index.js.map +1 -1
  95. package/package.json +15 -18
  96. package/dist/server/rate-limit.d.ts +0 -30
  97. package/dist/server/rate-limit.js +0 -73
  98. package/dist/server/rate-limit.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAEnD,OAAO,EAAE,cAAc,EAA2B,MAAM,UAAU,CAAA;AAmBlE,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,SAAoC,EAAE,OAAO,GAAsB,EAAE;IAC5G,OAAO,aAAa,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;AAC1C,CAAC;AAED,KAAK,UAAU,aAAa,CAAC,SAAoC,EAAE,OAA0B,EAAE,aAAiC;IAC9H,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;IACvF,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAA;IAC/B,KAAK,MAAM,OAAO,IAAI,SAAS,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAA;QACpF,IAAI,CAAC,OAAO,CAAC,O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AAK,CAAA;AACd,CAAC;AAED,SAAS,YAAY,CAAC,KAAa,EAAE,IAAY;IAC/C,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,2BAA2B,CAAC,CAAA;IAChF,OAAO,KAAK,CAAA;AACd,CAAC;AAID,kHAAkH;AAClH,MAAM,UAAU,uBAAuB,CAAC,WAAW,GAAsB,OAAO,CAAC,GAAG,EAAE,OAAO,GAAmC,EAAE;IAChI,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,EAAE,CAAA;IACnC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,MAAM,sBAAsB,CAAC,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC,WAAW,IAAI,uBAAuB,CAAA;IACnH,MAAM,MAAM,GAAG,eAAe,CAAC;QAC7B,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QAC7B,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QAC7B,WAAW;QACX,cAAc,EAAE,GAAG,MAAM,iBAAiB;QAC1C,KAAK,EAAE,EAAE;KACV,CAAC,CAAA;IACF,WAAW,CAAC,GAAG,MAAM,iBAAiB,CAAC,GAAG,MAAM,CAAA;IAChD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { spawn, type ChildProcess } from 'node:child_process'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { persistedSecret } from '../auth/secret.js'\n\nexport { runRealtimeDev, type RealtimeDevOptions } from './dev.js'\n\nexport type RuntimeProcess = {\n name: string\n command: string\n args?: readonly string[]\n cwd?: string\n env?: NodeJS.ProcessEnv\n}\n\ntype SignalSource = Pick<NodeJS.Process, 'off' | 'once'>\ntype SpawnProcess = (process: RuntimeProcess) => ChildProcess\n\nexport type SupervisorOptions = {\n shutdownTimeoutMs?: number\n signalSource?: SignalSource\n spawn?: SpawnProcess\n}\n\nexport async function superviseProcesses(processes: readonly RuntimeProcess[], options: SupervisorOptions = {}) {\n return runSupervisor(processes, options)\n}\n\nasync function runSupervisor(processes: readonly RuntimeProcess[], options: SupervisorOptions, shutdownOrder?: readonly string[]) {\n if (processes.length === 0) throw new Error('at least one runtime process is required')\n const names = new Set<string>()\n for (const process of processes) {\n if (!process.name.trim()) throw new Error('runtime process names must not be empty')\n if (!process.command.trim()) throw new Error(`runtime process ${process.name} must have a command`)\n if (names.has(process.name)) throw new Error(`duplicate runtime process name: ${process.name}`)\n names.add(process.name)\n }\n\n const signalSource = options.signalSource ?? process\n const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000\n if (!Number.isSafeInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 0) {\n throw new Error('shutdownTimeoutMs must be a non-negative integer')\n }\n const spawnProcess =\n options.spawn ??\n ((specification: RuntimeProcess) =>\n spawn(specification.command, [...(specification.args ?? [])], {\n cwd: specification.cwd,\n env: specification.env ?? process.env,\n stdio: 'inherit',\n }))\n const children = new Map<ChildProcess, string>()\n const exits = new Map<ChildProcess, Promise<void>>()\n let settled = false\n let phasedShutdown = false\n let expectedExit: ChildProcess | undefined\n let resolveResult!: (value: number) => void\n const result = new Promise<number>((resolve) => {\n resolveResult = resolve\n })\n\n const finishImmediately = async (status: number) => {\n if (settled) return\n settled = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n await stopChildren([...children.keys()], shutdownTimeoutMs)\n resolveResult(status)\n }\n const finishInPhases = async () => {\n if (settled || phasedShutdown) return\n phasedShutdown = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n const deadline = Date.now() + shutdownTimeoutMs\n for (const name of shutdownOrder ?? []) {\n if (settled) return\n const child = [...children].find(([, childName]) => childName === name)?.[0]\n if (!child || !running(child)) continue\n expectedExit = child\n child.kill('SIGTERM')\n // oxlint-disable-next-line no-await-in-loop -- Shutdown phases must remain dependency-ordered.\n const exited = await beforeDeadline(exits.get(child)!, Math.max(0, deadline - Date.now()))\n expectedExit = undefined\n if (settled) return\n if (!exited) {\n settled = true\n for (const runningChild of children.keys()) if (running(runningChild)) runningChild.kill('SIGKILL')\n resolveResult(0)\n return\n }\n }\n settled = true\n resolveResult(0)\n }\n const onSignal = () => {\n if (shutdownOrder) void finishInPhases()\n else void finishImmediately(0)\n }\n signalSource.once('SIGINT', onSignal)\n signalSource.once('SIGTERM', onSignal)\n\n try {\n for (const specification of processes) {\n const child = spawnProcess(specification)\n children.set(child, specification.name)\n let resolveExit!: () => void\n exits.set(\n child,\n new Promise<void>((resolve) => {\n resolveExit = resolve\n }),\n )\n child.once('error', () => void finishImmediately(1))\n child.once('exit', (code) => {\n resolveExit()\n if (!phasedShutdown || child !== expectedExit) void finishImmediately(code && code > 0 ? code : 1)\n })\n }\n } catch (error) {\n await finishImmediately(1)\n throw error\n }\n return result\n}\n\nasync function beforeDeadline(exited: Promise<void>, timeoutMs: number) {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs)\n })\n const result = await Promise.race([exited.then(() => true as const), timeout])\n if (timer) clearTimeout(timer)\n return result\n}\n\nfunction running(child: ChildProcess) {\n return child.exitCode === null && child.signalCode === null\n}\n\nasync function stopChildren(children: ChildProcess[], timeoutMs: number) {\n const active = children.filter(running)\n if (active.length === 0) return\n const exited = Promise.all(active.map((child) => new Promise<void>((resolve) => child.once('exit', () => resolve())))).then(\n () => 'exited' as const,\n )\n for (const child of active) child.kill('SIGTERM')\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n })\n const outcome = await Promise.race([exited, timeout])\n if (timer) clearTimeout(timer)\n if (outcome === 'timeout') {\n for (const child of active) if (running(child)) child.kill('SIGKILL')\n }\n}\n\nexport type CentrifugoEnvironmentOptions = {\n apiKey: string\n clientTokenSecret?: string\n subscriptionTokenSecret?: string\n allowedOrigins?: string\n redisUrl?: string\n}\n\nexport type RealtimeStackOptions = {\n app: Omit<RuntimeProcess, 'name'>\n centrifugo: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n environment: CentrifugoEnvironmentOptions\n }\n caddy: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n proxy?: CaddyRealtimeProxyOptions\n runtime?: CaddyRuntimeEnvironmentOptions\n }\n supervisor?: SupervisorOptions\n}\n\nexport async function runRealtimeStack(options: RealtimeStackOptions) {\n const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath')\n const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath')\n await mkdir(path.dirname(configPath), { recursive: true })\n await writeFile(configPath, caddyRealtimeProxy(options.caddy.proxy), 'utf8')\n return runSupervisor(\n [\n { name: 'app', ...options.app },\n {\n name: 'realtime',\n command: options.centrifugo.command ?? 'centrifugo',\n args: [`--config=${centrifugoConfigPath}`],\n ...(options.centrifugo.cwd ? { cwd: options.centrifugo.cwd } : {}),\n env: { ...options.centrifugo.env, ...centrifugoEnvironment(options.centrifugo.environment) },\n },\n {\n name: 'proxy',\n command: options.caddy.command ?? 'caddy',\n args: ['run', '--config', configPath, '--adapter', 'caddyfile'],\n ...(options.caddy.cwd ? { cwd: options.caddy.cwd } : {}),\n env: { ...options.caddy.env, ...caddyRuntimeEnvironment(options.caddy.runtime) },\n },\n ],\n options.supervisor ?? {},\n ['proxy', 'app', 'realtime'],\n )\n}\n\nexport function centrifugoEnvironment(options: CentrifugoEnvironmentOptions): NodeJS.ProcessEnv {\n const apiKey = requiredValue(options.apiKey, 'apiKey')\n const clientTokenSecret = options.clientTokenSecret?.trim()\n const subscriptionTokenSecret = options.subscriptionTokenSecret?.trim()\n return {\n CENTRIFUGO_HTTP_API_KEY: apiKey,\n CENTRIFUGO_CLIENT_ALLOWED_ORIGINS: options.allowedOrigins?.trim() || '*',\n CENTRIFUGO_HTTP_SERVER_ADDRESS: '127.0.0.1',\n CENTRIFUGO_HEALTH_ENABLED: 'true',\n ...(clientTokenSecret ? { CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY: clientTokenSecret } : {}),\n ...(subscriptionTokenSecret\n ? {\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED: 'true',\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY: subscriptionTokenSecret,\n }\n : {}),\n ...(options.redisUrl\n ? { CENTRIFUGO_ENGINE_TYPE: 'redis', CENTRIFUGO_ENGINE_REDIS_ADDRESS: requiredValue(options.redisUrl, 'redisUrl') }\n : {}),\n }\n}\n\nexport type CaddyRuntimeEnvironmentOptions = { configHome?: string; dataHome?: string }\n\nexport function caddyRuntimeEnvironment(options: CaddyRuntimeEnvironmentOptions = {}): NodeJS.ProcessEnv {\n const configHome = absolutePath(options.configHome ?? '/tmp/caddy-config', 'configHome')\n const dataHome = absolutePath(options.dataHome ?? '/tmp/caddy-data', 'dataHome')\n return { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome }\n}\n\nexport type CaddyRealtimeProxyOptions = {\n publicPort?: number\n appPort?: number\n realtimePort?: number\n websocketPath?: string\n /** Compress responses with zstd and gzip. On unless turned off: Caddy already skips upgrades and incompressible content. */\n encode?: boolean\n}\n\nexport function caddyRealtimeProxy(options: CaddyRealtimeProxyOptions = {}) {\n const publicPort = port(options.publicPort ?? 3000, 'publicPort')\n const appPort = port(options.appPort ?? 3001, 'appPort')\n const realtimePort = port(options.realtimePort ?? 8000, 'realtimePort')\n const websocketPath = options.websocketPath ?? '/connection/'\n if (!/^\\/[A-Za-z0-9._~/-]+\\/$/.test(websocketPath) || websocketPath.includes('//')) {\n throw new Error('websocketPath must be a normalized absolute directory path')\n }\n return `{\n\\tservers {\n\\t\\ttrusted_proxies static private_ranges\n\\t\\ttrusted_proxies_strict\n\\t}\n}\n\n:${publicPort} {\n${options.encode === false ? '' : '\\tencode zstd gzip\\n'}\\troute {\n\\t\\t@foreignWebSocketOrigin \\`{path}.startsWith('${websocketPath}') && {http.request.header.Origin} != '' && {http.request.header.Origin} != 'http://' + {http.request.hostport} && {http.request.header.Origin} != 'https://' + {http.request.hostport}\\`\n\\t\\trespond @foreignWebSocketOrigin 403\n\n\\t\\thandle ${websocketPath}* {\n\\t\\t\\treverse_proxy 127.0.0.1:${realtimePort}\n\\t\\t}\n\n\\t\\thandle {\n\\t\\t\\treverse_proxy 127.0.0.1:${appPort}\n\\t\\t}\n\\t}\n}\n`\n}\n\nfunction requiredValue(value: string, name: string) {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${name} is required`)\n return normalized\n}\n\nfunction port(value: number, name: string) {\n if (!Number.isInteger(value) || value < 1 || value > 65_535) throw new Error(`${name} must be a valid TCP port`)\n return value\n}\n\nfunction absolutePath(value: string, name: string) {\n if (!path.isAbsolute(value)) throw new Error(`${name} must be an absolute path`)\n return value\n}\n\nexport type PersistedRealtimeSecretOptions = { prefix?: string; defaultFile?: string }\n\n// The secret lands back in the environment so the supervised application inherits the value Centrifugo was given.\nexport function persistedRealtimeSecret(environment: NodeJS.ProcessEnv = process.env, options: PersistedRealtimeSecretOptions = {}) {\n const prefix = options.prefix ?? ''\n const file = environment[`${prefix}REALTIME_SECRET_FILE`]?.trim() || options.defaultFile || '/data/realtime-secret'\n const secret = persistedSecret({\n directory: path.dirname(file),\n filename: path.basename(file),\n environment,\n environmentKey: `${prefix}REALTIME_SECRET`,\n bytes: 48,\n })\n environment[`${prefix}REALTIME_SECRET`] = secret\n return secret\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA","sourcesContent":["export { caddyRealtimeProxy, persistedRealtimeSecret, runRealtimeStack } from './stack.js'\nexport type {\n CaddyRealtimeProxyOptions,\n CaddyRuntimeEnvironmentOptions,\n CentrifugoEnvironmentOptions,\n PersistedRealtimeSecretOptions,\n RealtimeStackOptions,\n RuntimeProcess,\n SupervisorOptions,\n} from './stack.js'\n"]}
@@ -0,0 +1,64 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ export type RuntimeProcess = {
3
+ name: string;
4
+ command: string;
5
+ args?: readonly string[];
6
+ cwd?: string;
7
+ env?: NodeJS.ProcessEnv;
8
+ };
9
+ type SignalSource = Pick<NodeJS.Process, 'off' | 'once'>;
10
+ type SpawnProcess = (process: RuntimeProcess) => ChildProcess;
11
+ export type SupervisorOptions = {
12
+ shutdownTimeoutMs?: number;
13
+ signalSource?: SignalSource;
14
+ spawn?: SpawnProcess;
15
+ };
16
+ export declare function superviseProcesses(processes: readonly RuntimeProcess[], options?: SupervisorOptions, shutdownOrder?: readonly string[]): Promise<number>;
17
+ export type CentrifugoEnvironmentOptions = {
18
+ apiKey: string;
19
+ clientTokenSecret?: string;
20
+ subscriptionTokenSecret?: string;
21
+ allowedOrigins?: string;
22
+ redisUrl?: string;
23
+ };
24
+ export type RealtimeStackOptions = {
25
+ app: Omit<RuntimeProcess, 'name'>;
26
+ centrifugo: {
27
+ command?: string;
28
+ configPath: string;
29
+ cwd?: string;
30
+ env?: NodeJS.ProcessEnv;
31
+ environment: CentrifugoEnvironmentOptions;
32
+ };
33
+ caddy: {
34
+ command?: string;
35
+ configPath: string;
36
+ cwd?: string;
37
+ env?: NodeJS.ProcessEnv;
38
+ proxy?: CaddyRealtimeProxyOptions;
39
+ runtime?: CaddyRuntimeEnvironmentOptions;
40
+ };
41
+ supervisor?: SupervisorOptions;
42
+ };
43
+ export declare function runRealtimeStack(options: RealtimeStackOptions): Promise<number>;
44
+ export declare function centrifugoEnvironment(options: CentrifugoEnvironmentOptions): NodeJS.ProcessEnv;
45
+ export type CaddyRuntimeEnvironmentOptions = {
46
+ configHome?: string;
47
+ dataHome?: string;
48
+ };
49
+ export declare function caddyRuntimeEnvironment(options?: CaddyRuntimeEnvironmentOptions): NodeJS.ProcessEnv;
50
+ export type CaddyRealtimeProxyOptions = {
51
+ publicPort?: number;
52
+ appPort?: number;
53
+ realtimePort?: number;
54
+ websocketPath?: string;
55
+ /** Compress responses with zstd and gzip. On unless turned off: Caddy already skips upgrades and incompressible content. */
56
+ encode?: boolean;
57
+ };
58
+ export declare function caddyRealtimeProxy(options?: CaddyRealtimeProxyOptions): string;
59
+ export type PersistedRealtimeSecretOptions = {
60
+ prefix?: string;
61
+ defaultFile?: string;
62
+ };
63
+ export declare function persistedRealtimeSecret(environment?: NodeJS.ProcessEnv, options?: PersistedRealtimeSecretOptions): string;
64
+ export {};
@@ -0,0 +1,252 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { persistedSecret } from '../auth/secret.js';
5
+ export async function superviseProcesses(processes, options = {}, shutdownOrder) {
6
+ if (processes.length === 0)
7
+ throw new Error('at least one runtime process is required');
8
+ const names = new Set();
9
+ for (const process of processes) {
10
+ if (!process.name.trim())
11
+ throw new Error('runtime process names must not be empty');
12
+ if (!process.command.trim())
13
+ throw new Error(`runtime process ${process.name} must have a command`);
14
+ if (names.has(process.name))
15
+ throw new Error(`duplicate runtime process name: ${process.name}`);
16
+ names.add(process.name);
17
+ }
18
+ const signalSource = options.signalSource ?? process;
19
+ const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000;
20
+ if (!Number.isSafeInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 0) {
21
+ throw new Error('shutdownTimeoutMs must be a non-negative integer');
22
+ }
23
+ const spawnProcess = options.spawn ??
24
+ ((specification) => spawn(specification.command, [...(specification.args ?? [])], {
25
+ cwd: specification.cwd,
26
+ env: specification.env ?? process.env,
27
+ stdio: 'inherit',
28
+ }));
29
+ const children = new Map();
30
+ const exits = new Map();
31
+ let settled = false;
32
+ let phasedShutdown = false;
33
+ let expectedExit;
34
+ let resolveResult;
35
+ const result = new Promise((resolve) => {
36
+ resolveResult = resolve;
37
+ });
38
+ const finishImmediately = async (status) => {
39
+ if (settled)
40
+ return;
41
+ settled = true;
42
+ signalSource.off('SIGINT', onSignal);
43
+ signalSource.off('SIGTERM', onSignal);
44
+ await stopChildren([...children.keys()], shutdownTimeoutMs);
45
+ resolveResult(status);
46
+ };
47
+ const finishInPhases = async () => {
48
+ if (settled || phasedShutdown)
49
+ return;
50
+ phasedShutdown = true;
51
+ signalSource.off('SIGINT', onSignal);
52
+ signalSource.off('SIGTERM', onSignal);
53
+ const deadline = Date.now() + shutdownTimeoutMs;
54
+ for (const name of shutdownOrder ?? []) {
55
+ if (settled)
56
+ return;
57
+ const child = [...children].find(([, childName]) => childName === name)?.[0];
58
+ if (!child || !running(child))
59
+ continue;
60
+ expectedExit = child;
61
+ child.kill('SIGTERM');
62
+ // oxlint-disable-next-line no-await-in-loop -- Shutdown phases must remain dependency-ordered.
63
+ const exited = await beforeDeadline(exits.get(child), Math.max(0, deadline - Date.now()));
64
+ expectedExit = undefined;
65
+ if (settled)
66
+ return;
67
+ if (!exited) {
68
+ settled = true;
69
+ for (const runningChild of children.keys())
70
+ if (running(runningChild))
71
+ runningChild.kill('SIGKILL');
72
+ resolveResult(0);
73
+ return;
74
+ }
75
+ }
76
+ settled = true;
77
+ resolveResult(0);
78
+ };
79
+ const onSignal = () => {
80
+ if (shutdownOrder)
81
+ void finishInPhases();
82
+ else
83
+ void finishImmediately(0);
84
+ };
85
+ signalSource.once('SIGINT', onSignal);
86
+ signalSource.once('SIGTERM', onSignal);
87
+ try {
88
+ for (const specification of processes) {
89
+ const child = spawnProcess(specification);
90
+ children.set(child, specification.name);
91
+ let resolveExit;
92
+ exits.set(child, new Promise((resolve) => {
93
+ resolveExit = resolve;
94
+ }));
95
+ child.once('error', () => void finishImmediately(1));
96
+ child.once('exit', (code) => {
97
+ resolveExit();
98
+ if (!phasedShutdown || child !== expectedExit)
99
+ void finishImmediately(code && code > 0 ? code : 1);
100
+ });
101
+ }
102
+ }
103
+ catch (error) {
104
+ await finishImmediately(1);
105
+ throw error;
106
+ }
107
+ return result;
108
+ }
109
+ async function beforeDeadline(exited, timeoutMs) {
110
+ let timer;
111
+ const timeout = new Promise((resolve) => {
112
+ timer = setTimeout(() => resolve(false), timeoutMs);
113
+ });
114
+ const result = await Promise.race([exited.then(() => true), timeout]);
115
+ if (timer)
116
+ clearTimeout(timer);
117
+ return result;
118
+ }
119
+ function running(child) {
120
+ return child.exitCode === null && child.signalCode === null;
121
+ }
122
+ async function stopChildren(children, timeoutMs) {
123
+ const active = children.filter(running);
124
+ if (active.length === 0)
125
+ return;
126
+ const exited = Promise.all(active.map((child) => new Promise((resolve) => child.once('exit', () => resolve())))).then(() => 'exited');
127
+ for (const child of active)
128
+ child.kill('SIGTERM');
129
+ let timer;
130
+ const timeout = new Promise((resolve) => {
131
+ timer = setTimeout(() => resolve('timeout'), timeoutMs);
132
+ });
133
+ const outcome = await Promise.race([exited, timeout]);
134
+ if (timer)
135
+ clearTimeout(timer);
136
+ if (outcome === 'timeout') {
137
+ for (const child of active)
138
+ if (running(child))
139
+ child.kill('SIGKILL');
140
+ }
141
+ }
142
+ export async function runRealtimeStack(options) {
143
+ const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath');
144
+ const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath');
145
+ await mkdir(path.dirname(configPath), { recursive: true });
146
+ await writeFile(configPath, caddyRealtimeProxy(options.caddy.proxy), 'utf8');
147
+ return superviseProcesses([
148
+ { name: 'app', ...options.app },
149
+ {
150
+ name: 'realtime',
151
+ command: options.centrifugo.command ?? 'centrifugo',
152
+ args: [`--config=${centrifugoConfigPath}`],
153
+ ...(options.centrifugo.cwd ? { cwd: options.centrifugo.cwd } : {}),
154
+ env: { ...options.centrifugo.env, ...centrifugoEnvironment(options.centrifugo.environment) },
155
+ },
156
+ {
157
+ name: 'proxy',
158
+ command: options.caddy.command ?? 'caddy',
159
+ args: ['run', '--config', configPath, '--adapter', 'caddyfile'],
160
+ ...(options.caddy.cwd ? { cwd: options.caddy.cwd } : {}),
161
+ env: { ...options.caddy.env, ...caddyRuntimeEnvironment(options.caddy.runtime) },
162
+ },
163
+ ], options.supervisor ?? {}, ['proxy', 'app', 'realtime']);
164
+ }
165
+ export function centrifugoEnvironment(options) {
166
+ const apiKey = requiredValue(options.apiKey, 'apiKey');
167
+ const clientTokenSecret = options.clientTokenSecret?.trim();
168
+ const subscriptionTokenSecret = options.subscriptionTokenSecret?.trim();
169
+ return {
170
+ CENTRIFUGO_HTTP_API_KEY: apiKey,
171
+ CENTRIFUGO_CLIENT_ALLOWED_ORIGINS: options.allowedOrigins?.trim() || '*',
172
+ CENTRIFUGO_HTTP_SERVER_ADDRESS: '127.0.0.1',
173
+ CENTRIFUGO_HEALTH_ENABLED: 'true',
174
+ ...(clientTokenSecret ? { CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY: clientTokenSecret } : {}),
175
+ ...(subscriptionTokenSecret
176
+ ? {
177
+ CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED: 'true',
178
+ CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY: subscriptionTokenSecret,
179
+ }
180
+ : {}),
181
+ ...(options.redisUrl
182
+ ? { CENTRIFUGO_ENGINE_TYPE: 'redis', CENTRIFUGO_ENGINE_REDIS_ADDRESS: requiredValue(options.redisUrl, 'redisUrl') }
183
+ : {}),
184
+ };
185
+ }
186
+ export function caddyRuntimeEnvironment(options = {}) {
187
+ const configHome = absolutePath(options.configHome ?? '/tmp/caddy-config', 'configHome');
188
+ const dataHome = absolutePath(options.dataHome ?? '/tmp/caddy-data', 'dataHome');
189
+ return { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome };
190
+ }
191
+ export function caddyRealtimeProxy(options = {}) {
192
+ const publicPort = port(options.publicPort ?? 3000, 'publicPort');
193
+ const appPort = port(options.appPort ?? 3001, 'appPort');
194
+ const realtimePort = port(options.realtimePort ?? 8000, 'realtimePort');
195
+ const websocketPath = options.websocketPath ?? '/connection/';
196
+ if (!/^\/[A-Za-z0-9._~/-]+\/$/.test(websocketPath) || websocketPath.includes('//')) {
197
+ throw new Error('websocketPath must be a normalized absolute directory path');
198
+ }
199
+ return `{
200
+ \tservers {
201
+ \t\ttrusted_proxies static private_ranges
202
+ \t\ttrusted_proxies_strict
203
+ \t}
204
+ }
205
+
206
+ :${publicPort} {
207
+ ${options.encode === false ? '' : '\tencode zstd gzip\n'}\troute {
208
+ \t\t@foreignWebSocketOrigin \`{path}.startsWith('${websocketPath}') && {http.request.header.Origin} != '' && {http.request.header.Origin} != 'http://' + {http.request.hostport} && {http.request.header.Origin} != 'https://' + {http.request.hostport}\`
209
+ \t\trespond @foreignWebSocketOrigin 403
210
+
211
+ \t\thandle ${websocketPath}* {
212
+ \t\t\treverse_proxy 127.0.0.1:${realtimePort}
213
+ \t\t}
214
+
215
+ \t\thandle {
216
+ \t\t\treverse_proxy 127.0.0.1:${appPort}
217
+ \t\t}
218
+ \t}
219
+ }
220
+ `;
221
+ }
222
+ function requiredValue(value, name) {
223
+ const normalized = value.trim();
224
+ if (!normalized)
225
+ throw new Error(`${name} is required`);
226
+ return normalized;
227
+ }
228
+ function port(value, name) {
229
+ if (!Number.isInteger(value) || value < 1 || value > 65_535)
230
+ throw new Error(`${name} must be a valid TCP port`);
231
+ return value;
232
+ }
233
+ function absolutePath(value, name) {
234
+ if (!path.isAbsolute(value))
235
+ throw new Error(`${name} must be an absolute path`);
236
+ return value;
237
+ }
238
+ // The secret lands back in the environment so the supervised application inherits the value Centrifugo was given.
239
+ export function persistedRealtimeSecret(environment = process.env, options = {}) {
240
+ const prefix = options.prefix ?? '';
241
+ const file = environment[`${prefix}REALTIME_SECRET_FILE`]?.trim() || options.defaultFile || '/data/realtime-secret';
242
+ const secret = persistedSecret({
243
+ directory: path.dirname(file),
244
+ filename: path.basename(file),
245
+ environment,
246
+ environmentKey: `${prefix}REALTIME_SECRET`,
247
+ bytes: 48,
248
+ });
249
+ environment[`${prefix}REALTIME_SECRET`] = secret;
250
+ return secret;
251
+ }
252
+ //# sourceMappingURL=stack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stack.js","sourceRoot":"","sources":["../../src/runtime/stack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAmBnD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,SAAoC,EACpC,OAAO,GAAsB,EAAE,EAC/B,aAAiC;IAEjC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAA;IACvF,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAA;IAC/B,KAAK,MAAM,OAAO,IAAI,SAAS,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAA;QACpF,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,OAAO,CAAC,IAAI,sBAAsB,CAAC,CAAA;QACnG,IAAI,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;QAC/F,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IACzB,CAAC;IAED,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,OAAO,CAAA;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,EAAE,CAAA;IACnC,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,MAAM,sBAAsB,CAAC,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC,WAAW,IAAI,uBAAuB,CAAA;IACnH,MAAM,MAAM,GAAG,eAAe,CAAC;QAC7B,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QAC7B,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;QAC7B,WAAW;QACX,cAAc,EAAE,GAAG,MAAM,iBAAiB;QAC1C,KAAK,EAAE,EAAE;KACV,CAAC,CAAA;IACF,WAAW,CAAC,GAAG,MAAM,iBAAiB,CAAC,GAAG,MAAM,CAAA;IAChD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { spawn, type ChildProcess } from 'node:child_process'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { persistedSecret } from '../auth/secret.js'\n\nexport type RuntimeProcess = {\n name: string\n command: string\n args?: readonly string[]\n cwd?: string\n env?: NodeJS.ProcessEnv\n}\n\ntype SignalSource = Pick<NodeJS.Process, 'off' | 'once'>\ntype SpawnProcess = (process: RuntimeProcess) => ChildProcess\n\nexport type SupervisorOptions = {\n shutdownTimeoutMs?: number\n signalSource?: SignalSource\n spawn?: SpawnProcess\n}\n\nexport async function superviseProcesses(\n processes: readonly RuntimeProcess[],\n options: SupervisorOptions = {},\n shutdownOrder?: readonly string[],\n) {\n if (processes.length === 0) throw new Error('at least one runtime process is required')\n const names = new Set<string>()\n for (const process of processes) {\n if (!process.name.trim()) throw new Error('runtime process names must not be empty')\n if (!process.command.trim()) throw new Error(`runtime process ${process.name} must have a command`)\n if (names.has(process.name)) throw new Error(`duplicate runtime process name: ${process.name}`)\n names.add(process.name)\n }\n\n const signalSource = options.signalSource ?? process\n const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000\n if (!Number.isSafeInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 0) {\n throw new Error('shutdownTimeoutMs must be a non-negative integer')\n }\n const spawnProcess =\n options.spawn ??\n ((specification: RuntimeProcess) =>\n spawn(specification.command, [...(specification.args ?? [])], {\n cwd: specification.cwd,\n env: specification.env ?? process.env,\n stdio: 'inherit',\n }))\n const children = new Map<ChildProcess, string>()\n const exits = new Map<ChildProcess, Promise<void>>()\n let settled = false\n let phasedShutdown = false\n let expectedExit: ChildProcess | undefined\n let resolveResult!: (value: number) => void\n const result = new Promise<number>((resolve) => {\n resolveResult = resolve\n })\n\n const finishImmediately = async (status: number) => {\n if (settled) return\n settled = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n await stopChildren([...children.keys()], shutdownTimeoutMs)\n resolveResult(status)\n }\n const finishInPhases = async () => {\n if (settled || phasedShutdown) return\n phasedShutdown = true\n signalSource.off('SIGINT', onSignal)\n signalSource.off('SIGTERM', onSignal)\n const deadline = Date.now() + shutdownTimeoutMs\n for (const name of shutdownOrder ?? []) {\n if (settled) return\n const child = [...children].find(([, childName]) => childName === name)?.[0]\n if (!child || !running(child)) continue\n expectedExit = child\n child.kill('SIGTERM')\n // oxlint-disable-next-line no-await-in-loop -- Shutdown phases must remain dependency-ordered.\n const exited = await beforeDeadline(exits.get(child)!, Math.max(0, deadline - Date.now()))\n expectedExit = undefined\n if (settled) return\n if (!exited) {\n settled = true\n for (const runningChild of children.keys()) if (running(runningChild)) runningChild.kill('SIGKILL')\n resolveResult(0)\n return\n }\n }\n settled = true\n resolveResult(0)\n }\n const onSignal = () => {\n if (shutdownOrder) void finishInPhases()\n else void finishImmediately(0)\n }\n signalSource.once('SIGINT', onSignal)\n signalSource.once('SIGTERM', onSignal)\n\n try {\n for (const specification of processes) {\n const child = spawnProcess(specification)\n children.set(child, specification.name)\n let resolveExit!: () => void\n exits.set(\n child,\n new Promise<void>((resolve) => {\n resolveExit = resolve\n }),\n )\n child.once('error', () => void finishImmediately(1))\n child.once('exit', (code) => {\n resolveExit()\n if (!phasedShutdown || child !== expectedExit) void finishImmediately(code && code > 0 ? code : 1)\n })\n }\n } catch (error) {\n await finishImmediately(1)\n throw error\n }\n return result\n}\n\nasync function beforeDeadline(exited: Promise<void>, timeoutMs: number) {\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), timeoutMs)\n })\n const result = await Promise.race([exited.then(() => true as const), timeout])\n if (timer) clearTimeout(timer)\n return result\n}\n\nfunction running(child: ChildProcess) {\n return child.exitCode === null && child.signalCode === null\n}\n\nasync function stopChildren(children: ChildProcess[], timeoutMs: number) {\n const active = children.filter(running)\n if (active.length === 0) return\n const exited = Promise.all(active.map((child) => new Promise<void>((resolve) => child.once('exit', () => resolve())))).then(\n () => 'exited' as const,\n )\n for (const child of active) child.kill('SIGTERM')\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), timeoutMs)\n })\n const outcome = await Promise.race([exited, timeout])\n if (timer) clearTimeout(timer)\n if (outcome === 'timeout') {\n for (const child of active) if (running(child)) child.kill('SIGKILL')\n }\n}\n\nexport type CentrifugoEnvironmentOptions = {\n apiKey: string\n clientTokenSecret?: string\n subscriptionTokenSecret?: string\n allowedOrigins?: string\n redisUrl?: string\n}\n\nexport type RealtimeStackOptions = {\n app: Omit<RuntimeProcess, 'name'>\n centrifugo: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n environment: CentrifugoEnvironmentOptions\n }\n caddy: {\n command?: string\n configPath: string\n cwd?: string\n env?: NodeJS.ProcessEnv\n proxy?: CaddyRealtimeProxyOptions\n runtime?: CaddyRuntimeEnvironmentOptions\n }\n supervisor?: SupervisorOptions\n}\n\nexport async function runRealtimeStack(options: RealtimeStackOptions) {\n const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath')\n const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath')\n await mkdir(path.dirname(configPath), { recursive: true })\n await writeFile(configPath, caddyRealtimeProxy(options.caddy.proxy), 'utf8')\n return superviseProcesses(\n [\n { name: 'app', ...options.app },\n {\n name: 'realtime',\n command: options.centrifugo.command ?? 'centrifugo',\n args: [`--config=${centrifugoConfigPath}`],\n ...(options.centrifugo.cwd ? { cwd: options.centrifugo.cwd } : {}),\n env: { ...options.centrifugo.env, ...centrifugoEnvironment(options.centrifugo.environment) },\n },\n {\n name: 'proxy',\n command: options.caddy.command ?? 'caddy',\n args: ['run', '--config', configPath, '--adapter', 'caddyfile'],\n ...(options.caddy.cwd ? { cwd: options.caddy.cwd } : {}),\n env: { ...options.caddy.env, ...caddyRuntimeEnvironment(options.caddy.runtime) },\n },\n ],\n options.supervisor ?? {},\n ['proxy', 'app', 'realtime'],\n )\n}\n\nexport function centrifugoEnvironment(options: CentrifugoEnvironmentOptions): NodeJS.ProcessEnv {\n const apiKey = requiredValue(options.apiKey, 'apiKey')\n const clientTokenSecret = options.clientTokenSecret?.trim()\n const subscriptionTokenSecret = options.subscriptionTokenSecret?.trim()\n return {\n CENTRIFUGO_HTTP_API_KEY: apiKey,\n CENTRIFUGO_CLIENT_ALLOWED_ORIGINS: options.allowedOrigins?.trim() || '*',\n CENTRIFUGO_HTTP_SERVER_ADDRESS: '127.0.0.1',\n CENTRIFUGO_HEALTH_ENABLED: 'true',\n ...(clientTokenSecret ? { CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY: clientTokenSecret } : {}),\n ...(subscriptionTokenSecret\n ? {\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED: 'true',\n CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY: subscriptionTokenSecret,\n }\n : {}),\n ...(options.redisUrl\n ? { CENTRIFUGO_ENGINE_TYPE: 'redis', CENTRIFUGO_ENGINE_REDIS_ADDRESS: requiredValue(options.redisUrl, 'redisUrl') }\n : {}),\n }\n}\n\nexport type CaddyRuntimeEnvironmentOptions = { configHome?: string; dataHome?: string }\n\nexport function caddyRuntimeEnvironment(options: CaddyRuntimeEnvironmentOptions = {}): NodeJS.ProcessEnv {\n const configHome = absolutePath(options.configHome ?? '/tmp/caddy-config', 'configHome')\n const dataHome = absolutePath(options.dataHome ?? '/tmp/caddy-data', 'dataHome')\n return { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome }\n}\n\nexport type CaddyRealtimeProxyOptions = {\n publicPort?: number\n appPort?: number\n realtimePort?: number\n websocketPath?: string\n /** Compress responses with zstd and gzip. On unless turned off: Caddy already skips upgrades and incompressible content. */\n encode?: boolean\n}\n\nexport function caddyRealtimeProxy(options: CaddyRealtimeProxyOptions = {}) {\n const publicPort = port(options.publicPort ?? 3000, 'publicPort')\n const appPort = port(options.appPort ?? 3001, 'appPort')\n const realtimePort = port(options.realtimePort ?? 8000, 'realtimePort')\n const websocketPath = options.websocketPath ?? '/connection/'\n if (!/^\\/[A-Za-z0-9._~/-]+\\/$/.test(websocketPath) || websocketPath.includes('//')) {\n throw new Error('websocketPath must be a normalized absolute directory path')\n }\n return `{\n\\tservers {\n\\t\\ttrusted_proxies static private_ranges\n\\t\\ttrusted_proxies_strict\n\\t}\n}\n\n:${publicPort} {\n${options.encode === false ? '' : '\\tencode zstd gzip\\n'}\\troute {\n\\t\\t@foreignWebSocketOrigin \\`{path}.startsWith('${websocketPath}') && {http.request.header.Origin} != '' && {http.request.header.Origin} != 'http://' + {http.request.hostport} && {http.request.header.Origin} != 'https://' + {http.request.hostport}\\`\n\\t\\trespond @foreignWebSocketOrigin 403\n\n\\t\\thandle ${websocketPath}* {\n\\t\\t\\treverse_proxy 127.0.0.1:${realtimePort}\n\\t\\t}\n\n\\t\\thandle {\n\\t\\t\\treverse_proxy 127.0.0.1:${appPort}\n\\t\\t}\n\\t}\n}\n`\n}\n\nfunction requiredValue(value: string, name: string) {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${name} is required`)\n return normalized\n}\n\nfunction port(value: number, name: string) {\n if (!Number.isInteger(value) || value < 1 || value > 65_535) throw new Error(`${name} must be a valid TCP port`)\n return value\n}\n\nfunction absolutePath(value: string, name: string) {\n if (!path.isAbsolute(value)) throw new Error(`${name} must be an absolute path`)\n return value\n}\n\nexport type PersistedRealtimeSecretOptions = { prefix?: string; defaultFile?: string }\n\n// The secret lands back in the environment so the supervised application inherits the value Centrifugo was given.\nexport function persistedRealtimeSecret(environment: NodeJS.ProcessEnv = process.env, options: PersistedRealtimeSecretOptions = {}) {\n const prefix = options.prefix ?? ''\n const file = environment[`${prefix}REALTIME_SECRET_FILE`]?.trim() || options.defaultFile || '/data/realtime-secret'\n const secret = persistedSecret({\n directory: path.dirname(file),\n filename: path.basename(file),\n environment,\n environmentKey: `${prefix}REALTIME_SECRET`,\n bytes: 48,\n })\n environment[`${prefix}REALTIME_SECRET`] = secret\n return secret\n}\n"]}
@@ -1,23 +1 @@
1
- export type InfrastructureFailure = {
2
- code: string;
3
- message: string;
4
- retryable: boolean;
5
- };
6
- export declare class InfrastructureError extends Error {
7
- readonly code: string;
8
- readonly publicMessage: string;
9
- readonly retryable: boolean;
10
- constructor(code: string, publicMessage: string, options?: {
11
- cause?: unknown;
12
- retryable?: boolean;
13
- });
14
- }
15
- export declare function infrastructureFailure(error: unknown, fallback: InfrastructureFailure): InfrastructureFailure;
16
- export declare function safeInfrastructureError(error: unknown, fallback: InfrastructureFailure): InfrastructureError;
17
- export declare function infrastructureDiagnostic(error: unknown): {
18
- name: string;
19
- message: string;
20
- code?: string | number;
21
- status?: number;
22
- };
23
1
  export declare function errorHasCode(error: unknown, code: string | number): boolean;
@@ -1,50 +1,6 @@
1
- export class InfrastructureError extends Error {
2
- code;
3
- publicMessage;
4
- retryable;
5
- constructor(code, publicMessage, options = {}) {
6
- super(publicMessage, options.cause === undefined ? undefined : { cause: options.cause });
7
- this.name = 'InfrastructureError';
8
- this.code = code;
9
- this.publicMessage = publicMessage;
10
- this.retryable = options.retryable ?? false;
11
- }
12
- }
13
- export function infrastructureFailure(error, fallback) {
14
- const known = findCause(error, (candidate) => candidate instanceof InfrastructureError);
15
- return known ? { code: known.code, message: known.publicMessage, retryable: known.retryable } : fallback;
16
- }
17
- export function safeInfrastructureError(error, fallback) {
18
- const failure = infrastructureFailure(error, fallback);
19
- return new InfrastructureError(failure.code, failure.message, { cause: error, retryable: failure.retryable });
20
- }
21
- export function infrastructureDiagnostic(error) {
22
- const found = findCause(error, (candidate) => candidate instanceof Error);
23
- if (!found)
24
- return { name: 'UnknownError', message: String(error) };
25
- const code = findProperty(error, 'code', (value) => typeof value === 'string' || typeof value === 'number');
26
- const status = findProperty(error, 'status', (value) => typeof value === 'number');
27
- return {
28
- name: found.name,
29
- message: found.message,
30
- ...(code === undefined ? {} : { code }),
31
- ...(status === undefined ? {} : { status }),
32
- };
33
- }
34
1
  export function errorHasCode(error, code) {
35
2
  return findProperty(error, 'code', (value) => typeof value === 'string' || typeof value === 'number') === code;
36
3
  }
37
- function findCause(error, matches) {
38
- let current = error;
39
- const seen = new Set();
40
- while (current && !seen.has(current)) {
41
- if (matches(current))
42
- return current;
43
- seen.add(current);
44
- current = typeof current === 'object' && 'cause' in current ? current.cause : undefined;
45
- }
46
- return undefined;
47
- }
48
4
  function findProperty(error, property, matches) {
49
5
  let current = error;
50
6
  const seen = new Set();
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/server/errors.ts"],"names":[],"mappings":"AAMA,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACnC,IAAI,CAAQ;IACZ,aAAa,CAAQ;IACrB,SAAS,CAAS;IAE3B,YAAY,IAAY,EAAE,aAAqB,EAAE,OAAO,GAA6C,EAAE;QACrG,KAAK,CAAC,aAAa,EAAE,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAA;QACxF,IAAI,CAAC,IAAI,GAAG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AuC;IAChG,IAAI,OAAO,GAAG,KAAK,CAAA;IACnB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAW,CAAA;IAC/B,OAAO,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QACjB,IAAI,OAAO,OAAO,KAAK,QAAQ;YAAE,OAAO,SAAS,CAAA;QACjD,IAAI,QAAQ,IAAI,OAAO,EAAE,CAAC;YACxB,MAAM,KAAK,GAAG,OAAO,CAAC,QAAgC,CAAC,CAAA;YACvD,IAAI,OAAO,CAAC,KAAK,CAAC;gBAAE,OAAO,KAAK,CAAA;QAClC,CAAC;QACD,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;IAC1D,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC","sourcesContent":["export type InfrastructureFailure = {\n code: string\n message: string\n retryable: boolean\n}\n\nexport class InfrastructureError extends Error {\n readonly code: string\n readonly publicMessage: string\n readonly retryable: boolean\n\n constructor(code: string, publicMessage: string, options: { cause?: unknown; retryable?: boolean } = {}) {\n super(publicMessage, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'InfrastructureError'\n this.code = code\n this.publicMessage = publicMessage\n this.retryable = options.retryable ?? false\n }\n}\n\nexport function infrastructureFailure(error: unknown, fallback: InfrastructureFailure): InfrastructureFailure {\n const known = findCause(error, (candidate): candidate is InfrastructureError => candidate instanceof InfrastructureError)\n return known ? { code: known.code, message: known.publicMessage, retryable: known.retryable } : fallback\n}\n\nexport function safeInfrastructureError(error: unknown, fallback: InfrastructureFailure) {\n const failure = infrastructureFailure(error, fallback)\n return new InfrastructureError(failure.code, failure.message, { cause: error, retryable: failure.retryable })\n}\n\nexport function infrastructureDiagnostic(error: unknown) {\n const found = findCause(error, (candidate): candidate is Error => candidate instanceof Error)\n if (!found) return { name: 'UnknownError', message: String(error) }\n const code = findProperty(error, 'code', (value): value is string | number => typeof value === 'string' || typeof value === 'number')\n const status = findProperty(error, 'status', (value): value is number => typeof value === 'number')\n return {\n name: found.name,\n message: found.message,\n ...(code === undefined ? {} : { code }),\n ...(status === undefined ? {} : { status }),\n }\n}\n\nexport function errorHasCode(error: unknown, code: string | number) {\n return findProperty(error, 'code', (value): value is string | number => typeof value === 'string' || typeof value === 'number') === code\n}\n\nfunction findCause<T>(error: unknown, matches: (candidate: unknown) => candidate is T): T | undefined {\n let current = error\n const seen = new Set<unknown>()\n while (current && !seen.has(current)) {\n if (matches(current)) return current\n seen.add(current)\n current = typeof current === 'object' && 'cause' in current ? current.cause : undefined\n }\n return undefined\n}\n\nfunction findProperty<T>(error: unknown, property: string, matches: (value: unknown) => value is T): T | undefined {\n let current = error\n const seen = new Set<unknown>()\n while (current && !seen.has(current)) {\n seen.add(current)\n if (typeof current !== 'object') return undefined\n if (property in current) {\n const value = current[property as keyof typeof current]\n if (matches(value)) return value\n }\n current = 'cause' in current ? current.cause : undefined\n }\n return undefined\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/server/errors.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,YAAY,CAAC,KAAc,EAAE,IAAqB;IAChE,OAAO,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC,KAAK,EAA4B,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,KAAK,IAAI,CAAA;AAC1I,CAAC;AAED,SAAS,YAAY,CAAI,KAAc,EAAE,QAAgB,EAAE,OAAuC;IAChG,IAAI,OAAO,GAAG,KAAK,CAAA;IACnB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAW,CAAA;IAC/B,OAAO,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QACjB,IAAI,OAAO,OAAO,KAAK,QAAQ;YAAE,OAAO,SAAS,CAAA;QACjD,IAAI,QAAQ,IAAI,OAAO,EAAE,CAAC;YACxB,MAAM,KAAK,GAAG,OAAO,CAAC,QAAgC,CAAC,CAAA;YACvD,IAAI,OAAO,CAAC,KAAK,CAAC;gBAAE,OAAO,KAAK,CAAA;QAClC,CAAC;QACD,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;IAC1D,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC","sourcesContent":["export function errorHasCode(error: unknown, code: string | number) {\n return findProperty(error, 'code', (value): value is string | number => typeof value === 'string' || typeof value === 'number') === code\n}\n\nfunction findProperty<T>(error: unknown, property: string, matches: (value: unknown) => value is T): T | undefined {\n let current = error\n const seen = new Set<unknown>()\n while (current && !seen.has(current)) {\n seen.add(current)\n if (typeof current !== 'object') return undefined\n if (property in current) {\n const value = current[property as keyof typeof current]\n if (matches(value)) return value\n }\n current = 'cause' in current ? current.cause : undefined\n }\n return undefined\n}\n"]}
@@ -1,7 +1,10 @@
1
- import { type InfrastructureFailure } from './errors.js';
1
+ export type HealthFailure = {
2
+ code: string;
3
+ message: string;
4
+ };
2
5
  export type HealthResponseOptions = {
3
- errorMessage?: (error: unknown) => string;
4
- failure?: (error: unknown) => InfrastructureFailure;
6
+ /** Maps a failed check to the code and message the response may expose; the cause itself never leaves the server. */
7
+ failure?: (error: unknown) => HealthFailure;
5
8
  };
6
9
  export declare function healthResponse(check: () => Promise<void> | void, options?: HealthResponseOptions): Promise<Response>;
7
- export declare const databaseHealthFailure: (error: unknown) => InfrastructureFailure;
10
+ export declare const databaseHealthFailure: () => HealthFailure;
@@ -1,16 +1,12 @@
1
- import { infrastructureFailure } from './errors.js';
2
1
  export async function healthResponse(check, options = {}) {
3
2
  try {
4
3
  await check();
5
4
  return Response.json({ ok: true });
6
5
  }
7
6
  catch (error) {
8
- if (options.failure) {
9
- const failure = options.failure(error);
10
- return Response.json({ ok: false, error: failure.message, code: failure.code }, { status: 503 });
11
- }
12
- return Response.json({ ok: false, error: options.errorMessage?.(error) ?? 'health check failed' }, { status: 503 });
7
+ const failure = options.failure?.(error);
8
+ return Response.json(failure ? { ok: false, error: failure.message, code: failure.code } : { ok: false, error: 'health check failed' }, { status: 503 });
13
9
  }
14
10
  }
15
- export const databaseHealthFailure = (error) => infrastructureFailure(error, { code: 'database_unavailable', message: 'database unavailable', retryable: true });
11
+ export const databaseHealthFailure = () => ({ code: 'database_unavailable', message: 'database unavailable' });
16
12
  //# sourceMappingURL=health.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"health.js","sourceRoot":"","sources":["../../src/server/health.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAA8B,MAAM,aAAa,CAAA;AAO/E,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,KAAiC,EAAE,OAAO,GAA0B,EAAE;IACzG,IAAI,CAAC;QACH,MAAM,KAAK,EAAE,CAAA;QACb,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAA;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;YACpB,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;YACtC,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;QAClG,CAAC;QACD,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC,KAAK,CAAC,IAAI,qBAAqB,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,CAAA;IACrH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,KAAc,EAAE,EAAE,CACtD,qBAAqB,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,sBAAsB,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAA","sourcesContent":["import { infrastructureFailure, type InfrastructureFailure } from './errors.js'\n\nexport type HealthResponseOptions = {\n errorMessage?: (error: unknown) => string\n failure?: (error: unknown) => InfrastructureFailure\n}\n\nexport async function healthResponse(check: () => Promise<void> | void, options: HealthResponseOptions = {}) {\n try {\n await check()\n return Response.json({ ok: true })\n } catch (error) {\n if (options.failure) {\n const failure = options.failure(error)\n return Response.json({ ok: false, error: failure.message, code: failure.code }, { status: 503 })\n }\n return Response.json({ ok: false, error: options.errorMessage?.(error) ?? 'health check failed' }, { status: 503 })\n }\n}\n\nexport const databaseHealthFailure = (error: unknown) =>\n infrastructureFailure(error, { code: 'database_unavailable', message: 'database unavailable', retryable: true })\n"]}
1
+ {"version":3,"file":"health.js","sourceRoot":"","sources":["../../src/server/health.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,KAAiC,EAAE,OAAO,GAA0B,EAAE;IACzG,IAAI,CAAC;QACH,MAAM,KAAK,EAAE,CAAA;QACb,OAAO,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAA;IACpC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAA;QACxC,OAAO,QAAQ,CAAC,IAAI,CAClB,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,qBAAqB,EAAE,EACjH,EAAE,MAAM,EAAE,GAAG,EAAE,CAChB,CAAA;IACH,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAkB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,sBAAsB,EAAE,OAAO,EAAE,sBAAsB,EAAE,CAAC,CAAA","sourcesContent":["export type HealthFailure = { code: string; message: string }\n\nexport type HealthResponseOptions = {\n /** Maps a failed check to the code and message the response may expose; the cause itself never leaves the server. */\n failure?: (error: unknown) => HealthFailure\n}\n\nexport async function healthResponse(check: () => Promise<void> | void, options: HealthResponseOptions = {}) {\n try {\n await check()\n return Response.json({ ok: true })\n } catch (error) {\n const failure = options.failure?.(error)\n return Response.json(\n failure ? { ok: false, error: failure.message, code: failure.code } : { ok: false, error: 'health check failed' },\n { status: 503 },\n )\n }\n}\n\nexport const databaseHealthFailure = (): HealthFailure => ({ code: 'database_unavailable', message: 'database unavailable' })\n"]}
@@ -1,13 +1,5 @@
1
- export { canonicalRedirect } from './canonical-host.js';
2
- export type { CanonicalRedirectOptions } from './canonical-host.js';
3
- export { errorHasCode, infrastructureDiagnostic, infrastructureFailure, InfrastructureError, safeInfrastructureError } from './errors.js';
4
- export type { InfrastructureFailure } from './errors.js';
1
+ export { errorHasCode } from './errors.js';
5
2
  export { databaseHealthFailure, healthResponse } from './health.js';
6
- export type { HealthResponseOptions } from './health.js';
7
- export { createRateLimit, forwardedClientAddress, memoryRateLimitStore, rateLimitTable } from './rate-limit.js';
8
- export type { RateLimitCounter, RateLimitDecision, RateLimitOptions, RateLimitStore } from './rate-limit.js';
9
- export { createRpc } from './rpc.js';
10
- export { currentServerFunction, withServerFunction } from './server-function.js';
11
- export type { ServerFunctionIdentity } from './server-function.js';
3
+ export type { HealthFailure, HealthResponseOptions } from './health.js';
12
4
  export type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js';
13
5
  export { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js';
@@ -1,8 +1,4 @@
1
- export { canonicalRedirect } from './canonical-host.js';
2
- export { errorHasCode, infrastructureDiagnostic, infrastructureFailure, InfrastructureError, safeInfrastructureError } from './errors.js';
1
+ export { errorHasCode } from './errors.js';
3
2
  export { databaseHealthFailure, healthResponse } from './health.js';
4
- export { createRateLimit, forwardedClientAddress, memoryRateLimitStore, rateLimitTable } from './rate-limit.js';
5
- export { createRpc } from './rpc.js';
6
- export { currentServerFunction, withServerFunction } from './server-function.js';
7
3
  export { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js';
8
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAEvD,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAA;AAEzI,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAEnE,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAE/G,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAA;AAGhF,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA","sourcesContent":["export { canonicalRedirect } from './canonical-host.js'\nexport type { CanonicalRedirectOptions } from './canonical-host.js'\nexport { errorHasCode, infrastructureDiagnostic, infrastructureFailure, InfrastructureError, safeInfrastructureError } from './errors.js'\nexport type { InfrastructureFailure } from './errors.js'\nexport { databaseHealthFailure, healthResponse } from './health.js'\nexport type { HealthResponseOptions } from './health.js'\nexport { createRateLimit, forwardedClientAddress, memoryRateLimitStore, rateLimitTable } from './rate-limit.js'\nexport type { RateLimitCounter, RateLimitDecision, RateLimitOptions, RateLimitStore } from './rate-limit.js'\nexport { createRpc } from './rpc.js'\nexport { currentServerFunction, withServerFunction } from './server-function.js'\nexport type { ServerFunctionIdentity } from './server-function.js'\nexport type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js'\nexport { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAGnE,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA","sourcesContent":["export { errorHasCode } from './errors.js'\nexport { databaseHealthFailure, healthResponse } from './health.js'\nexport type { HealthFailure, HealthResponseOptions } from './health.js'\nexport type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js'\nexport { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js'\n"]}
@@ -0,0 +1,11 @@
1
+ export type ChunkRecoveryOptions = {
2
+ storageKey: string;
3
+ noticeId?: string;
4
+ retryWindowMs?: number;
5
+ };
6
+ /**
7
+ * An inline script that reloads the page, at most once per retry window, when an entry module fails to load after a
8
+ * deploy replaced the build. Without it the server-rendered HTML stays inert. TanStack Router already reloads for lazy
9
+ * route chunks; this covers the entry graph it cannot reach. Optionally reveals a hidden element once reloading stops.
10
+ */
11
+ export declare function chunkRecoveryScript(options: ChunkRecoveryOptions): string;