ras-stack 5.5.6 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/README.md +32 -34
  2. package/config/oxlint.json +1 -0
  3. package/dist/cli.d.ts +0 -27
  4. package/dist/cli.js +4 -32
  5. package/dist/cli.js.map +1 -1
  6. package/package.json +12 -228
  7. package/config/vite.mjs +0 -3
  8. package/dist/auth/client.d.ts +0 -11
  9. package/dist/auth/client.js +0 -57
  10. package/dist/auth/client.js.map +0 -1
  11. package/dist/auth/index.d.ts +0 -9
  12. package/dist/auth/index.js +0 -6
  13. package/dist/auth/index.js.map +0 -1
  14. package/dist/auth/origins.d.ts +0 -13
  15. package/dist/auth/origins.js +0 -41
  16. package/dist/auth/origins.js.map +0 -1
  17. package/dist/auth/providers.d.ts +0 -11
  18. package/dist/auth/providers.js +0 -26
  19. package/dist/auth/providers.js.map +0 -1
  20. package/dist/auth/random.d.ts +0 -2
  21. package/dist/auth/random.js +0 -10
  22. package/dist/auth/random.js.map +0 -1
  23. package/dist/auth/react.d.ts +0 -18
  24. package/dist/auth/react.js +0 -34
  25. package/dist/auth/react.js.map +0 -1
  26. package/dist/auth/secret.d.ts +0 -8
  27. package/dist/auth/secret.js +0 -44
  28. package/dist/auth/secret.js.map +0 -1
  29. package/dist/auth/settings.d.ts +0 -54
  30. package/dist/auth/settings.js +0 -37
  31. package/dist/auth/settings.js.map +0 -1
  32. package/dist/build/cli.d.ts +0 -1
  33. package/dist/build/cli.js +0 -24
  34. package/dist/build/cli.js.map +0 -1
  35. package/dist/build/index.d.ts +0 -17
  36. package/dist/build/index.js +0 -93
  37. package/dist/build/index.js.map +0 -1
  38. package/dist/changesets/cli.d.ts +0 -1
  39. package/dist/changesets/cli.js +0 -14
  40. package/dist/changesets/cli.js.map +0 -1
  41. package/dist/changesets/index.d.ts +0 -1
  42. package/dist/changesets/index.js +0 -38
  43. package/dist/changesets/index.js.map +0 -1
  44. package/dist/config.d.ts +0 -3
  45. package/dist/config.js +0 -3
  46. package/dist/config.js.map +0 -1
  47. package/dist/conformance/index.d.ts +0 -9
  48. package/dist/conformance/index.js +0 -92
  49. package/dist/conformance/index.js.map +0 -1
  50. package/dist/database/index.d.ts +0 -19
  51. package/dist/database/index.js +0 -21
  52. package/dist/database/index.js.map +0 -1
  53. package/dist/database/libsql.d.ts +0 -14
  54. package/dist/database/libsql.js +0 -31
  55. package/dist/database/libsql.js.map +0 -1
  56. package/dist/database/postgres.d.ts +0 -13
  57. package/dist/database/postgres.js +0 -16
  58. package/dist/database/postgres.js.map +0 -1
  59. package/dist/database/pragmas.d.ts +0 -7
  60. package/dist/database/pragmas.js +0 -12
  61. package/dist/database/pragmas.js.map +0 -1
  62. package/dist/database/sqlite.d.ts +0 -20
  63. package/dist/database/sqlite.js +0 -45
  64. package/dist/database/sqlite.js.map +0 -1
  65. package/dist/email/index.d.ts +0 -63
  66. package/dist/email/index.js +0 -95
  67. package/dist/email/index.js.map +0 -1
  68. package/dist/managed/catalog.d.ts +0 -40
  69. package/dist/managed/catalog.js +0 -114
  70. package/dist/managed/catalog.js.map +0 -1
  71. package/dist/managed/cli.d.ts +0 -1
  72. package/dist/managed/cli.js +0 -54
  73. package/dist/managed/cli.js.map +0 -1
  74. package/dist/managed/environment.d.ts +0 -5
  75. package/dist/managed/environment.js +0 -52
  76. package/dist/managed/environment.js.map +0 -1
  77. package/dist/managed/files.d.ts +0 -4
  78. package/dist/managed/files.js +0 -30
  79. package/dist/managed/files.js.map +0 -1
  80. package/dist/managed/install.d.ts +0 -4
  81. package/dist/managed/install.js +0 -62
  82. package/dist/managed/install.js.map +0 -1
  83. package/dist/managed/model.d.ts +0 -24
  84. package/dist/managed/model.js +0 -30
  85. package/dist/managed/model.js.map +0 -1
  86. package/dist/managed/plan.d.ts +0 -13
  87. package/dist/managed/plan.js +0 -99
  88. package/dist/managed/plan.js.map +0 -1
  89. package/dist/managed/pnpm.d.ts +0 -23
  90. package/dist/managed/pnpm.js +0 -2808
  91. package/dist/managed/pnpm.js.map +0 -7
  92. package/dist/managed/process.d.ts +0 -4
  93. package/dist/managed/process.js +0 -23
  94. package/dist/managed/process.js.map +0 -1
  95. package/dist/managed/sync.d.ts +0 -6
  96. package/dist/managed/sync.js +0 -96
  97. package/dist/managed/sync.js.map +0 -1
  98. package/dist/managed/tools.d.ts +0 -1
  99. package/dist/managed/tools.js +0 -7
  100. package/dist/managed/tools.js.map +0 -1
  101. package/dist/posthog/config.d.ts +0 -19
  102. package/dist/posthog/config.js +0 -51
  103. package/dist/posthog/config.js.map +0 -1
  104. package/dist/posthog/index.d.ts +0 -4
  105. package/dist/posthog/index.js +0 -3
  106. package/dist/posthog/index.js.map +0 -1
  107. package/dist/posthog/proxy.d.ts +0 -30
  108. package/dist/posthog/proxy.js +0 -51
  109. package/dist/posthog/proxy.js.map +0 -1
  110. package/dist/posthog/react.d.ts +0 -39
  111. package/dist/posthog/react.js +0 -81
  112. package/dist/posthog/react.js.map +0 -1
  113. package/dist/posthog/request.d.ts +0 -12
  114. package/dist/posthog/request.js +0 -22
  115. package/dist/posthog/request.js.map +0 -1
  116. package/dist/posthog/server.d.ts +0 -67
  117. package/dist/posthog/server.js +0 -388
  118. package/dist/posthog/server.js.map +0 -1
  119. package/dist/query/index.d.ts +0 -8
  120. package/dist/query/index.js +0 -17
  121. package/dist/query/index.js.map +0 -1
  122. package/dist/realtime/client.d.ts +0 -19
  123. package/dist/realtime/client.js +0 -37
  124. package/dist/realtime/client.js.map +0 -1
  125. package/dist/realtime/environment.d.ts +0 -10
  126. package/dist/realtime/environment.js +0 -28
  127. package/dist/realtime/environment.js.map +0 -1
  128. package/dist/realtime/index.d.ts +0 -6
  129. package/dist/realtime/index.js +0 -4
  130. package/dist/realtime/index.js.map +0 -1
  131. package/dist/realtime/publisher.d.ts +0 -37
  132. package/dist/realtime/publisher.js +0 -195
  133. package/dist/realtime/publisher.js.map +0 -1
  134. package/dist/realtime/react.d.ts +0 -13
  135. package/dist/realtime/react.js +0 -78
  136. package/dist/realtime/react.js.map +0 -1
  137. package/dist/realtime/tokens.d.ts +0 -6
  138. package/dist/realtime/tokens.js +0 -13
  139. package/dist/realtime/tokens.js.map +0 -1
  140. package/dist/runtime/dev.d.ts +0 -21
  141. package/dist/runtime/dev.js +0 -138
  142. package/dist/runtime/dev.js.map +0 -1
  143. package/dist/runtime/index.d.ts +0 -2
  144. package/dist/runtime/index.js +0 -2
  145. package/dist/runtime/index.js.map +0 -1
  146. package/dist/runtime/stack.d.ts +0 -65
  147. package/dist/runtime/stack.js +0 -226
  148. package/dist/runtime/stack.js.map +0 -1
  149. package/dist/server/canonical-host.d.ts +0 -6
  150. package/dist/server/canonical-host.js +0 -23
  151. package/dist/server/canonical-host.js.map +0 -1
  152. package/dist/server/errors.d.ts +0 -1
  153. package/dist/server/errors.js +0 -20
  154. package/dist/server/errors.js.map +0 -1
  155. package/dist/server/health.d.ts +0 -10
  156. package/dist/server/health.js +0 -12
  157. package/dist/server/health.js.map +0 -1
  158. package/dist/server/index.d.ts +0 -7
  159. package/dist/server/index.js +0 -5
  160. package/dist/server/index.js.map +0 -1
  161. package/dist/server/rpc.d.ts +0 -19
  162. package/dist/server/rpc.js +0 -52
  163. package/dist/server/rpc.js.map +0 -1
  164. package/dist/server/server-function.d.ts +0 -8
  165. package/dist/server/server-function.js +0 -18
  166. package/dist/server/server-function.js.map +0 -1
  167. package/dist/server/singleton.d.ts +0 -4
  168. package/dist/server/singleton.js +0 -48
  169. package/dist/server/singleton.js.map +0 -1
  170. package/dist/spacetime/index.d.ts +0 -36
  171. package/dist/spacetime/index.js +0 -103
  172. package/dist/spacetime/index.js.map +0 -1
  173. package/dist/tanstack/client.d.ts +0 -11
  174. package/dist/tanstack/client.js +0 -33
  175. package/dist/tanstack/client.js.map +0 -1
  176. package/dist/tanstack/middleware.d.ts +0 -9
  177. package/dist/tanstack/middleware.js +0 -32
  178. package/dist/tanstack/middleware.js.map +0 -1
  179. package/dist/tanstack/server.d.ts +0 -10
  180. package/dist/tanstack/server.js +0 -14
  181. package/dist/tanstack/server.js.map +0 -1
  182. package/dist/uploads/index.d.ts +0 -29
  183. package/dist/uploads/index.js +0 -83
  184. package/dist/uploads/index.js.map +0 -1
  185. package/dist/vite/config.d.ts +0 -18
  186. package/dist/vite/config.js +0 -88
  187. package/dist/vite/config.js.map +0 -1
  188. package/dist/vite/index.d.ts +0 -2
  189. package/dist/vite/index.js +0 -2
  190. package/dist/vite/index.js.map +0 -1
  191. package/pnpmfile.mjs +0 -1
@@ -1,65 +0,0 @@
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 type CentrifugoEnvironmentOptions = {
17
- apiKey: string;
18
- clientTokenSecret?: string;
19
- subscriptionTokenSecret?: string;
20
- allowedOrigins?: string;
21
- redisUrl?: string;
22
- };
23
- export type RealtimeStackOptions = {
24
- app: Omit<RuntimeProcess, 'name'>;
25
- centrifugo: {
26
- command?: string;
27
- configPath: string;
28
- cwd?: string;
29
- env?: NodeJS.ProcessEnv;
30
- environment: CentrifugoEnvironmentOptions;
31
- };
32
- caddy: {
33
- command?: string;
34
- configPath: string;
35
- cwd?: string;
36
- env?: NodeJS.ProcessEnv;
37
- proxy?: CaddyRealtimeProxyOptions;
38
- runtime?: CaddyRuntimeEnvironmentOptions;
39
- };
40
- supervisor?: SupervisorOptions;
41
- };
42
- export declare function runRealtimeStack(options: RealtimeStackOptions): Promise<number>;
43
- export declare function centrifugoEnvironment(options: CentrifugoEnvironmentOptions): NodeJS.ProcessEnv;
44
- export type CaddyRuntimeEnvironmentOptions = {
45
- configHome?: string;
46
- dataHome?: string;
47
- };
48
- export declare function caddyRuntimeEnvironment(options?: CaddyRuntimeEnvironmentOptions): NodeJS.ProcessEnv;
49
- export type CaddyRealtimeProxyOptions = {
50
- publicPort?: number;
51
- appPort?: number;
52
- realtimePort?: number;
53
- websocketPath?: string;
54
- /** Compress responses with zstd and gzip. On unless turned off: Caddy already skips upgrades and incompressible content. */
55
- encode?: boolean;
56
- };
57
- export declare function caddyRealtimeProxy(options?: CaddyRealtimeProxyOptions): string;
58
- export declare function requiredValue(value: string | undefined, name: string): string;
59
- export declare function port(value: number, name: string): number;
60
- export type PersistedRealtimeSecretOptions = {
61
- prefix?: string;
62
- defaultFile?: string;
63
- };
64
- export declare function persistedRealtimeSecret(environment?: NodeJS.ProcessEnv, options?: PersistedRealtimeSecretOptions): string;
65
- export {};
@@ -1,226 +0,0 @@
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
- async function superviseProcesses(processes, options, shutdownOrder) {
6
- for (const process of processes) {
7
- if (!process.command.trim())
8
- throw new Error(`runtime process ${process.name} must have a command`);
9
- }
10
- const signalSource = options.signalSource ?? process;
11
- const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 10_000;
12
- if (!Number.isSafeInteger(shutdownTimeoutMs) || shutdownTimeoutMs < 0) {
13
- throw new Error('shutdownTimeoutMs must be a non-negative integer');
14
- }
15
- const spawnProcess = options.spawn ??
16
- ((specification) => spawn(specification.command, [...(specification.args ?? [])], {
17
- cwd: specification.cwd,
18
- env: specification.env ?? process.env,
19
- stdio: 'inherit',
20
- }));
21
- const children = new Map();
22
- const exits = new Map();
23
- let settled = false;
24
- let phasedShutdown = false;
25
- let expectedExit;
26
- let resolveResult;
27
- const result = new Promise((resolve) => {
28
- resolveResult = resolve;
29
- });
30
- const finishImmediately = async (status) => {
31
- if (settled)
32
- return;
33
- settled = true;
34
- signalSource.off('SIGINT', onSignal);
35
- signalSource.off('SIGTERM', onSignal);
36
- const active = [...children.keys()].filter(running);
37
- for (const child of active)
38
- child.kill('SIGTERM');
39
- if (!(await beforeDeadline(Promise.all(active.map((child) => exits.get(child))), shutdownTimeoutMs))) {
40
- for (const child of active)
41
- if (running(child))
42
- child.kill('SIGKILL');
43
- }
44
- resolveResult(status);
45
- };
46
- const finishInPhases = async () => {
47
- if (settled || phasedShutdown)
48
- return;
49
- phasedShutdown = true;
50
- signalSource.off('SIGINT', onSignal);
51
- signalSource.off('SIGTERM', onSignal);
52
- const deadline = Date.now() + shutdownTimeoutMs;
53
- for (const name of shutdownOrder) {
54
- if (settled)
55
- return;
56
- const child = [...children].find(([, childName]) => childName === name)?.[0];
57
- if (!child || !running(child))
58
- continue;
59
- expectedExit = child;
60
- child.kill('SIGTERM');
61
- // oxlint-disable-next-line no-await-in-loop -- Shutdown phases must remain dependency-ordered.
62
- const exited = await beforeDeadline(exits.get(child), Math.max(0, deadline - Date.now()));
63
- expectedExit = undefined;
64
- if (settled)
65
- return;
66
- if (!exited) {
67
- settled = true;
68
- for (const runningChild of children.keys())
69
- if (running(runningChild))
70
- runningChild.kill('SIGKILL');
71
- resolveResult(0);
72
- return;
73
- }
74
- }
75
- settled = true;
76
- resolveResult(0);
77
- };
78
- const onSignal = () => void finishInPhases();
79
- signalSource.once('SIGINT', onSignal);
80
- signalSource.once('SIGTERM', onSignal);
81
- try {
82
- for (const specification of processes) {
83
- const child = spawnProcess(specification);
84
- children.set(child, specification.name);
85
- let resolveExit;
86
- exits.set(child, new Promise((resolve) => {
87
- resolveExit = resolve;
88
- }));
89
- child.once('error', () => void finishImmediately(1));
90
- child.once('exit', (code) => {
91
- resolveExit();
92
- if (!phasedShutdown || child !== expectedExit)
93
- void finishImmediately(code && code > 0 ? code : 1);
94
- });
95
- }
96
- }
97
- catch (error) {
98
- await finishImmediately(1);
99
- throw error;
100
- }
101
- return result;
102
- }
103
- async function beforeDeadline(exited, timeoutMs) {
104
- let timer;
105
- const timeout = new Promise((resolve) => {
106
- timer = setTimeout(() => resolve(false), timeoutMs);
107
- });
108
- const result = await Promise.race([exited.then(() => true), timeout]);
109
- if (timer)
110
- clearTimeout(timer);
111
- return result;
112
- }
113
- function running(child) {
114
- return child.exitCode === null && child.signalCode === null;
115
- }
116
- export async function runRealtimeStack(options) {
117
- const configPath = absolutePath(options.caddy.configPath, 'caddy.configPath');
118
- const centrifugoConfigPath = absolutePath(options.centrifugo.configPath, 'centrifugo.configPath');
119
- await mkdir(path.dirname(configPath), { recursive: true });
120
- await writeFile(configPath, caddyRealtimeProxy(options.caddy.proxy), 'utf8');
121
- return superviseProcesses([
122
- { name: 'app', ...options.app },
123
- {
124
- name: 'realtime',
125
- command: options.centrifugo.command ?? 'centrifugo',
126
- args: [`--config=${centrifugoConfigPath}`],
127
- ...(options.centrifugo.cwd ? { cwd: options.centrifugo.cwd } : {}),
128
- env: { ...options.centrifugo.env, ...centrifugoEnvironment(options.centrifugo.environment) },
129
- },
130
- {
131
- name: 'proxy',
132
- command: options.caddy.command ?? 'caddy',
133
- args: ['run', '--config', configPath, '--adapter', 'caddyfile'],
134
- ...(options.caddy.cwd ? { cwd: options.caddy.cwd } : {}),
135
- env: { ...options.caddy.env, ...caddyRuntimeEnvironment(options.caddy.runtime) },
136
- },
137
- ], options.supervisor ?? {}, ['proxy', 'app', 'realtime']);
138
- }
139
- export function centrifugoEnvironment(options) {
140
- const apiKey = requiredValue(options.apiKey, 'apiKey');
141
- const clientTokenSecret = options.clientTokenSecret?.trim();
142
- const subscriptionTokenSecret = options.subscriptionTokenSecret?.trim();
143
- return {
144
- CENTRIFUGO_HTTP_API_KEY: apiKey,
145
- CENTRIFUGO_CLIENT_ALLOWED_ORIGINS: options.allowedOrigins?.trim() || '*',
146
- CENTRIFUGO_HTTP_SERVER_ADDRESS: '127.0.0.1',
147
- CENTRIFUGO_HEALTH_ENABLED: 'true',
148
- ...(clientTokenSecret ? { CENTRIFUGO_CLIENT_TOKEN_HMAC_SECRET_KEY: clientTokenSecret } : {}),
149
- ...(subscriptionTokenSecret
150
- ? {
151
- CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_ENABLED: 'true',
152
- CENTRIFUGO_CLIENT_SUBSCRIPTION_TOKEN_HMAC_SECRET_KEY: subscriptionTokenSecret,
153
- }
154
- : {}),
155
- ...(options.redisUrl
156
- ? { CENTRIFUGO_ENGINE_TYPE: 'redis', CENTRIFUGO_ENGINE_REDIS_ADDRESS: requiredValue(options.redisUrl, 'redisUrl') }
157
- : {}),
158
- };
159
- }
160
- export function caddyRuntimeEnvironment(options = {}) {
161
- const configHome = absolutePath(options.configHome ?? '/tmp/caddy-config', 'configHome');
162
- const dataHome = absolutePath(options.dataHome ?? '/tmp/caddy-data', 'dataHome');
163
- return { XDG_CONFIG_HOME: configHome, XDG_DATA_HOME: dataHome };
164
- }
165
- export function caddyRealtimeProxy(options = {}) {
166
- const publicPort = port(options.publicPort ?? 3000, 'publicPort');
167
- const appPort = port(options.appPort ?? 3001, 'appPort');
168
- const realtimePort = port(options.realtimePort ?? 8000, 'realtimePort');
169
- const websocketPath = options.websocketPath ?? '/connection/';
170
- if (!/^\/[A-Za-z0-9._~/-]+\/$/.test(websocketPath) || websocketPath.includes('//')) {
171
- throw new Error('websocketPath must be a normalized absolute directory path');
172
- }
173
- return `{
174
- \tservers {
175
- \t\ttrusted_proxies static private_ranges
176
- \t\ttrusted_proxies_strict
177
- \t}
178
- }
179
-
180
- :${publicPort} {
181
- ${options.encode === false ? '' : '\tencode zstd gzip\n'}\troute {
182
- \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}\`
183
- \t\trespond @foreignWebSocketOrigin 403
184
-
185
- \t\thandle ${websocketPath}* {
186
- \t\t\treverse_proxy 127.0.0.1:${realtimePort}
187
- \t\t}
188
-
189
- \t\thandle {
190
- \t\t\treverse_proxy 127.0.0.1:${appPort}
191
- \t\t}
192
- \t}
193
- }
194
- `;
195
- }
196
- export function requiredValue(value, name) {
197
- const normalized = value?.trim();
198
- if (!normalized)
199
- throw new Error(`${name} is required`);
200
- return normalized;
201
- }
202
- export function port(value, name) {
203
- if (!Number.isInteger(value) || value < 1 || value > 65_535)
204
- throw new Error(`${name} must be a valid TCP port`);
205
- return value;
206
- }
207
- function absolutePath(value, name) {
208
- if (!path.isAbsolute(value))
209
- throw new Error(`${name} must be an absolute path`);
210
- return value;
211
- }
212
- // The secret lands back in the environment so the supervised application inherits the value Centrifugo was given.
213
- export function persistedRealtimeSecret(environment = process.env, options = {}) {
214
- const prefix = options.prefix ?? '';
215
- const file = environment[`${prefix}REALTIME_SECRET_FILE`]?.trim() || options.defaultFile || '/data/realtime-secret';
216
- const secret = persistedSecret({
217
- directory: path.dirname(file),
218
- filename: path.basename(file),
219
- environment,
220
- environmentKey: `${prefix}REALTIME_SECRET`,
221
- bytes: 48,
222
- });
223
- environment[`${prefix}REALTIME_SECRET`] = secret;
224
- return secret;
225
- }
226
- //# sourceMappingURL=stack.js.map
@@ -1 +0,0 @@
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,KAAK,UAAU,kBAAkB,CAAC,SAAoC,EAAE,OAA0B,EAAE,aAAgC;IAClI,KAAK,MAAM,OAAO,IAAI,SAAS,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,OAAO,CAAC,IAA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UAAU,IAAI,CAAC,KAAa,EAAE,IAAY;IAC9C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,2BAA2B,CAAC,CAAA;IAChH,OAAO,KAAK,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 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\nasync function superviseProcesses(processes: readonly RuntimeProcess[], options: SupervisorOptions, shutdownOrder: readonly string[]) {\n for (const process of processes) {\n if (!process.command.trim()) throw new Error(`runtime process ${process.name} must have a command`)\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 const active = [...children.keys()].filter(running)\n for (const child of active) child.kill('SIGTERM')\n if (!(await beforeDeadline(Promise.all(active.map((child) => exits.get(child)!)), shutdownTimeoutMs))) {\n for (const child of active) if (running(child)) child.kill('SIGKILL')\n }\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 = () => void finishInPhases()\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<unknown>, 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\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\nexport function requiredValue(value: string | undefined, name: string) {\n const normalized = value?.trim()\n if (!normalized) throw new Error(`${name} is required`)\n return normalized\n}\n\nexport function 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,6 +0,0 @@
1
- export type CanonicalRedirectOptions = {
2
- canonicalUrl?: string;
3
- pathsServedOnAnyHost?: ReadonlySet<string>;
4
- };
5
- export declare function canonicalRedirect(requestUrl: string, options: CanonicalRedirectOptions): string | null;
6
- export declare function loopback(hostname: string): boolean;
@@ -1,23 +0,0 @@
1
- export function canonicalRedirect(requestUrl, options) {
2
- if (!options.canonicalUrl?.trim())
3
- return null;
4
- try {
5
- const canonical = new URL(options.canonicalUrl);
6
- const incoming = new URL(requestUrl);
7
- if (incoming.host === canonical.host || options.pathsServedOnAnyHost?.has(incoming.pathname))
8
- return null;
9
- // A sibling process calling over the loopback interface is not a visitor who typed the wrong hostname.
10
- // Redirecting it sends an internal request out to the public name, and its client may not follow the
11
- // redirect, may drop the method, or may not be able to reach that name at all.
12
- if (loopback(incoming.hostname))
13
- return null;
14
- return new URL(incoming.pathname + incoming.search + incoming.hash, canonical.origin).toString();
15
- }
16
- catch {
17
- return null;
18
- }
19
- }
20
- export function loopback(hostname) {
21
- return hostname === 'localhost' || hostname === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(hostname);
22
- }
23
- //# sourceMappingURL=canonical-host.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"canonical-host.js","sourceRoot":"","sources":["../../src/server/canonical-host.ts"],"names":[],"mappings":"AAKA,MAAM,UAAU,iBAAiB,CAAC,UAAkB,EAAE,OAAiC;IACrF,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,EAAE;QAAE,OAAO,IAAI,CAAA;IAC9C,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;QAC/C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,CAAA;QACpC,IAAI,QAAQ,CAAC,IAAI,KAAK,SAAS,CAAC,IAAI,IAAI,OAAO,CAAC,oBAAoB,EAAE,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAA;QACzG,uGAAuG;QACvG,qGAAqG;QACrG,+EAA+E;QAC/E,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,OAAO,IAAI,CAAA;QAC5C,OAAO,IAAI,GAAG,CAAC,QAAQ,CAAC,QAAQ,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAA;IAClG,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,QAAgB;IACvC,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,OAAO,IAAI,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;AACnG,CAAC","sourcesContent":["export type CanonicalRedirectOptions = {\n canonicalUrl?: string\n pathsServedOnAnyHost?: ReadonlySet<string>\n}\n\nexport function canonicalRedirect(requestUrl: string, options: CanonicalRedirectOptions) {\n if (!options.canonicalUrl?.trim()) return null\n try {\n const canonical = new URL(options.canonicalUrl)\n const incoming = new URL(requestUrl)\n if (incoming.host === canonical.host || options.pathsServedOnAnyHost?.has(incoming.pathname)) return null\n // A sibling process calling over the loopback interface is not a visitor who typed the wrong hostname.\n // Redirecting it sends an internal request out to the public name, and its client may not follow the\n // redirect, may drop the method, or may not be able to reach that name at all.\n if (loopback(incoming.hostname)) return null\n return new URL(incoming.pathname + incoming.search + incoming.hash, canonical.origin).toString()\n } catch {\n return null\n }\n}\n\nexport function loopback(hostname: string) {\n return hostname === 'localhost' || hostname === '[::1]' || /^127(?:\\.\\d{1,3}){3}$/.test(hostname)\n}\n"]}
@@ -1 +0,0 @@
1
- export declare function errorHasCode(error: unknown, code: string | number): boolean;
@@ -1,20 +0,0 @@
1
- export function errorHasCode(error, code) {
2
- return findProperty(error, 'code', (value) => typeof value === 'string' || typeof value === 'number') === code;
3
- }
4
- function findProperty(error, property, matches) {
5
- let current = error;
6
- const seen = new Set();
7
- while (current && !seen.has(current)) {
8
- seen.add(current);
9
- if (typeof current !== 'object')
10
- return undefined;
11
- if (property in current) {
12
- const value = current[property];
13
- if (matches(value))
14
- return value;
15
- }
16
- current = 'cause' in current ? current.cause : undefined;
17
- }
18
- return undefined;
19
- }
20
- //# sourceMappingURL=errors.js.map
@@ -1 +0,0 @@
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,10 +0,0 @@
1
- export type HealthFailure = {
2
- code: string;
3
- message: string;
4
- };
5
- export type HealthResponseOptions = {
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;
8
- };
9
- export declare function healthResponse(check: () => Promise<void> | void, options?: HealthResponseOptions): Promise<Response>;
10
- export declare const databaseHealthFailure: () => HealthFailure;
@@ -1,12 +0,0 @@
1
- export async function healthResponse(check, options = {}) {
2
- try {
3
- await check();
4
- return Response.json({ ok: true });
5
- }
6
- catch (error) {
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 });
9
- }
10
- }
11
- export const databaseHealthFailure = () => ({ code: 'database_unavailable', message: 'database unavailable' });
12
- //# sourceMappingURL=health.js.map
@@ -1 +0,0 @@
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,7 +0,0 @@
1
- export { errorHasCode } from './errors.js';
2
- export { databaseHealthFailure, healthResponse } from './health.js';
3
- export type { HealthFailure, HealthResponseOptions } from './health.js';
4
- export type { RpcErrorContext, RpcLogger, RpcObserver, RpcOptions } from './rpc.js';
5
- export { currentServerFunction } from './server-function.js';
6
- export type { ServerFunctionIdentity } from './server-function.js';
7
- export { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js';
@@ -1,5 +0,0 @@
1
- export { errorHasCode } from './errors.js';
2
- export { databaseHealthFailure, healthResponse } from './health.js';
3
- export { currentServerFunction } from './server-function.js';
4
- export { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js';
5
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
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,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAE5D,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 { currentServerFunction } from './server-function.js'\nexport type { ServerFunctionIdentity } from './server-function.js'\nexport { clearGlobalSingleton, globalAsyncSingleton, globalSingleton, peekGlobalSingleton } from './singleton.js'\n"]}
@@ -1,19 +0,0 @@
1
- /** Where a failure happened: the request, the server function it ran when the identity middleware names it, and the status of a thrown `Response`. */
2
- export type RpcErrorContext = {
3
- method?: string;
4
- path?: string;
5
- function?: string;
6
- status?: number;
7
- };
8
- export type RpcLogger = (error: unknown, context: RpcErrorContext, request?: Request) => void | Promise<void>;
9
- export type RpcObserver = <T>(request: Request | undefined, work: () => Promise<T>) => Promise<T>;
10
- export type RpcOptions = {
11
- getRequest?: () => Request;
12
- requireMutation?: (request: Request) => void;
13
- logError?: RpcLogger;
14
- observe?: RpcObserver;
15
- };
16
- export declare function createRpc(options?: RpcOptions): {
17
- rpc: <T>(work: () => Promise<T> | T) => Promise<T>;
18
- mutationRpc: <T>(work: () => Promise<T> | T, request?: Request | undefined) => Promise<T>;
19
- };
@@ -1,52 +0,0 @@
1
- import { currentServerFunction } from './server-function.js';
2
- export function createRpc(options = {}) {
3
- async function rpc(work) {
4
- return run(work, resolveRequest(options.getRequest));
5
- }
6
- async function run(work, request) {
7
- const execute = async () => {
8
- try {
9
- return await work();
10
- }
11
- catch (thrown) {
12
- const status = thrown instanceof Response ? thrown.status : undefined;
13
- const error = thrown instanceof Response ? new Error((await thrown.text()) || `request failed (${thrown.status})`, { cause: thrown }) : thrown;
14
- // A 4xx answer is the caller's to fix; a 5xx one, such as an unreachable upstream, is the server's.
15
- if (status === undefined || status >= 500) {
16
- try {
17
- await options.logError?.(error, requestContext(request, status), request);
18
- }
19
- catch { }
20
- }
21
- throw error;
22
- }
23
- };
24
- return options.observe ? options.observe(request, execute) : execute();
25
- }
26
- function mutationRpc(work, request = resolveRequest(options.getRequest)) {
27
- return run(() => {
28
- if (!request)
29
- throw new Error('mutation request is unavailable');
30
- options.requireMutation?.(request);
31
- return work();
32
- }, request);
33
- }
34
- return { rpc, mutationRpc };
35
- }
36
- function resolveRequest(getRequest) {
37
- try {
38
- return getRequest?.();
39
- }
40
- catch {
41
- return undefined;
42
- }
43
- }
44
- function requestContext(request, status) {
45
- const name = currentServerFunction()?.name;
46
- return {
47
- ...(request ? { method: request.method, path: new URL(request.url).pathname } : {}),
48
- ...(name ? { function: name } : {}),
49
- ...(status === undefined ? {} : { status }),
50
- };
51
- }
52
- //# sourceMappingURL=rpc.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/server/rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAA;AAc5D,MAAM,UAAU,SAAS,CAAC,OAAO,GAAe,EAAE;IAChD,KAAK,UAAU,GAAG,CAAI,IAA0B;QAC9C,OAAO,GAAG,CAAC,IAAI,EAAE,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;IACtD,CAAC;IAED,KAAK,UAAU,GAAG,CAAI,IAA0B,EAAE,OAA4B;QAC5E,MAAM,OAAO,GAAG,KAAK,IAAI,EAAE;YACzB,IAAI,CAAC;gBACH,OAAO,MAAM,IAAI,EAAE,CAAA;YACrB,CAAC;YAAC,OAAO,MAAM,EAAE,CAAC;gBAChB,MAAM,MAAM,GAAG,MAAM,YAAY,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAA;gBACrE,MAAM,KAAK,GACT,MAAM,YAAY,QAAQ,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,mBAAmB,MAAM,CAAC,MAAM,GAAG,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA;gBAClI,oGAAoG;gBACpG,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,IAAI,GAAG,EAAE,CAAC;oBAC1C,IAAI,CAAC;wBACH,MAAM,O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,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACnC,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC;KAC5C,CAAA;AACH,CAAC","sourcesContent":["import { currentServerFunction } from './server-function.js'\n\n/** Where a failure happened: the request, the server function it ran when the identity middleware names it, and the status of a thrown `Response`. */\nexport type RpcErrorContext = { method?: string; path?: string; function?: string; status?: number }\nexport type RpcLogger = (error: unknown, context: RpcErrorContext, request?: Request) => void | Promise<void>\nexport type RpcObserver = <T>(request: Request | undefined, work: () => Promise<T>) => Promise<T>\n\nexport type RpcOptions = {\n getRequest?: () => Request\n requireMutation?: (request: Request) => void\n logError?: RpcLogger\n observe?: RpcObserver\n}\n\nexport function createRpc(options: RpcOptions = {}) {\n async function rpc<T>(work: () => Promise<T> | T): Promise<T> {\n return run(work, resolveRequest(options.getRequest))\n }\n\n async function run<T>(work: () => Promise<T> | T, request: Request | undefined): Promise<T> {\n const execute = async () => {\n try {\n return await work()\n } catch (thrown) {\n const status = thrown instanceof Response ? thrown.status : undefined\n const error =\n thrown instanceof Response ? new Error((await thrown.text()) || `request failed (${thrown.status})`, { cause: thrown }) : thrown\n // A 4xx answer is the caller's to fix; a 5xx one, such as an unreachable upstream, is the server's.\n if (status === undefined || status >= 500) {\n try {\n await options.logError?.(error, requestContext(request, status), request)\n } catch {}\n }\n throw error\n }\n }\n return options.observe ? options.observe(request, execute) : execute()\n }\n\n function mutationRpc<T>(work: () => Promise<T> | T, request = resolveRequest(options.getRequest)) {\n return run(() => {\n if (!request) throw new Error('mutation request is unavailable')\n options.requireMutation?.(request)\n return work()\n }, request)\n }\n\n return { rpc, mutationRpc }\n}\n\nfunction resolveRequest(getRequest: (() => Request) | undefined) {\n try {\n return getRequest?.()\n } catch {\n return undefined\n }\n}\n\nfunction requestContext(request: Request | undefined, status: number | undefined): RpcErrorContext {\n const name = currentServerFunction()?.name\n return {\n ...(request ? { method: request.method, path: new URL(request.url).pathname } : {}),\n ...(name ? { function: name } : {}),\n ...(status === undefined ? {} : { status }),\n }\n}\n"]}
@@ -1,8 +0,0 @@
1
- /** The server function a call runs, as the framework's compiler names it. */
2
- export type ServerFunctionIdentity = {
3
- name: string;
4
- filename: string;
5
- };
6
- /** Runs work with its server function's identity available to telemetry recorded inside it. */
7
- export declare function withServerFunction<T>(identity: ServerFunctionIdentity, work: () => T): T;
8
- export declare function currentServerFunction(): ServerFunctionIdentity | undefined;
@@ -1,18 +0,0 @@
1
- let storage;
2
- // Resolved through the running process, so a browser bundle that includes framework middleware never loads a Node module.
3
- function identityStorage() {
4
- if (storage === undefined) {
5
- const hooks = globalThis.process?.getBuiltinModule?.('node:async_hooks');
6
- storage = hooks ? new hooks.AsyncLocalStorage() : null;
7
- }
8
- return storage;
9
- }
10
- /** Runs work with its server function's identity available to telemetry recorded inside it. */
11
- export function withServerFunction(identity, work) {
12
- const current = identityStorage();
13
- return current ? current.run(identity, work) : work();
14
- }
15
- export function currentServerFunction() {
16
- return identityStorage()?.getStore();
17
- }
18
- //# sourceMappingURL=server-function.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"server-function.js","sourceRoot":"","sources":["../../src/server/server-function.ts"],"names":[],"mappings":"AAOA,IAAI,OAAqE,CAAA;AAEzE,0HAA0H;AAC1H,SAAS,eAAe;IACtB,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;QAC1B,MAAM,KAAK,GAAI,UAAwC,CAAC,OAAO,EAAE,gBAAgB,EAAE,CAAC,kBAAkB,CAAC,CAAA;QACvG,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,iBAAiB,EAA0B,CAAC,CAAC,CAAC,IAAI,CAAA;IAChF,CAAC;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,kBAAkB,CAAI,QAAgC,EAAE,IAAa;IACnF,MAAM,OAAO,GAAG,eAAe,EAAE,CAAA;IACjC,OAAO,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;AACvD,CAAC;AAED,MAAM,UAAU,qBAAqB;IACnC,OAAO,eAAe,EAAE,EAAE,QAAQ,EAAE,CAAA;AACtC,CAAC","sourcesContent":["import type { AsyncLocalStorage } from 'node:async_hooks'\n\n/** The server function a call runs, as the framework's compiler names it. */\nexport type ServerFunctionIdentity = { name: string; filename: string }\n\ntype NodeProcess = { getBuiltinModule?: (id: 'node:async_hooks') => typeof import('node:async_hooks') | undefined }\n\nlet storage: AsyncLocalStorage<ServerFunctionIdentity> | null | undefined\n\n// Resolved through the running process, so a browser bundle that includes framework middleware never loads a Node module.\nfunction identityStorage() {\n if (storage === undefined) {\n const hooks = (globalThis as { process?: NodeProcess }).process?.getBuiltinModule?.('node:async_hooks')\n storage = hooks ? new hooks.AsyncLocalStorage<ServerFunctionIdentity>() : null\n }\n return storage\n}\n\n/** Runs work with its server function's identity available to telemetry recorded inside it. */\nexport function withServerFunction<T>(identity: ServerFunctionIdentity, work: () => T): T {\n const current = identityStorage()\n return current ? current.run(identity, work) : work()\n}\n\nexport function currentServerFunction(): ServerFunctionIdentity | undefined {\n return identityStorage()?.getStore()\n}\n"]}
@@ -1,4 +0,0 @@
1
- export declare function globalSingleton<T>(key: string, create: () => T): T;
2
- export declare function globalAsyncSingleton<T>(key: string, create: () => T | Promise<T>): Promise<T>;
3
- export declare function peekGlobalSingleton(key: string): unknown;
4
- export declare function clearGlobalSingleton<T>(key: string, dispose?: (value: Awaited<T>) => void | Promise<void>): Promise<boolean>;
@@ -1,48 +0,0 @@
1
- const storeKey = Symbol.for('ras-stack.server.singletons');
2
- function store() {
3
- const target = globalThis;
4
- return (target[storeKey] ??= new Map());
5
- }
6
- export function globalSingleton(key, create) {
7
- const singletons = store();
8
- const existing = singletons.get(key);
9
- if (existing) {
10
- if (existing.kind !== 'sync')
11
- throw new Error(`singleton ${key} is asynchronous`);
12
- return existing.value;
13
- }
14
- const value = create();
15
- singletons.set(key, { kind: 'sync', value });
16
- return value;
17
- }
18
- export function globalAsyncSingleton(key, create) {
19
- const singletons = store();
20
- const existing = singletons.get(key);
21
- if (existing) {
22
- if (existing.kind !== 'async')
23
- throw new Error(`singleton ${key} is synchronous`);
24
- return existing.value;
25
- }
26
- const pending = Promise.resolve().then(create);
27
- const guarded = pending.catch((error) => {
28
- if (singletons.get(key)?.value === guarded)
29
- singletons.delete(key);
30
- throw error;
31
- });
32
- singletons.set(key, { kind: 'async', value: guarded });
33
- return guarded;
34
- }
35
- export function peekGlobalSingleton(key) {
36
- return store().get(key)?.value;
37
- }
38
- export async function clearGlobalSingleton(key, dispose) {
39
- const singletons = store();
40
- if (!singletons.has(key))
41
- return false;
42
- const value = singletons.get(key)?.value;
43
- singletons.delete(key);
44
- if (dispose)
45
- await dispose(await value);
46
- return true;
47
- }
48
- //# sourceMappingURL=singleton.js.map