@luckystack/server 0.4.0 → 0.5.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.
package/README.md CHANGED
@@ -1,198 +1,198 @@
1
- # @luckystack/server
2
-
3
- > One-call server bootstrap for [LuckyStack](https://github.com/ItsLucky23/LuckyStack-v2). HTTP + Socket.io + framework routes (`/api/*`, `/sync/*`, `/_health`, `/_test/reset`, `/auth/*`, `/uploads/*`) wired together. Your `server.ts` shrinks to ~20 lines.
4
-
5
- ## Install
6
-
7
- ```bash
8
- npm install @luckystack/server @luckystack/core @luckystack/api @luckystack/login @luckystack/sync @luckystack/presence socket.io
9
- ```
10
-
11
- ## Quickstart — recommended (`bootstrapLuckyStack`)
12
-
13
- `bootstrapLuckyStack` is a thin wrapper around `createLuckyStackServer` that auto-imports your `luckystack/<pkg>/*.ts` overlay files in topological order before listening, so registries (DI, hooks, providers) are populated by the time the HTTP server boots. This is what `create-luckystack-app` scaffolds.
14
-
15
- ```ts
16
- import 'dotenv/config';
17
- import '../config'; // your registerProjectConfig(...)
18
- import '../deploy.config'; // your registerDeployConfig(...)
19
- import '../services.config'; // your registerServicesConfig(...)
20
-
21
- import { bootstrapLuckyStack } from '@luckystack/server';
22
- import { serveFile, serveFavicon } from './prod/serveFile';
23
-
24
- const server = await bootstrapLuckyStack({
25
- serveFile,
26
- serveFavicon,
27
- });
28
-
29
- await server.listen();
30
- ```
31
-
32
- The bootstrap call runs (in order):
33
-
34
- 1. Auto-imports `luckystack/core/*.ts`, `luckystack/deploy/*.ts`, `luckystack/login/*.ts`, `luckystack/sentry/*.ts`, `luckystack/presence/*.ts`, `luckystack/docs-ui/*.ts`, `luckystack/server/*.ts` (topologically sorted, then alphabetically inside each folder).
35
- 2. Hands off to `createLuckyStackServer(options)`.
36
-
37
- Set `skipOverlayLoad: true` to handle every registration yourself, or `overlayRoot: 'custom-folder'` to load from somewhere other than `./luckystack`.
38
-
39
- ### Pre-flight check — `verifyBootstrap`
40
-
41
- Call `verifyBootstrap` **after** the overlay loads (or after your manual registrations) and **before** `server.listen()` if you want to fail fast on missing registrations instead of silent runtime crashes:
42
-
43
- ```ts
44
- import { bootstrapLuckyStack, verifyBootstrap } from '@luckystack/server';
45
-
46
- const server = await bootstrapLuckyStack({ serveFile, serveFavicon });
47
-
48
- await verifyBootstrap({
49
- requireDeployConfig: true, // single-instance deploys can omit this
50
- requireServicesConfig: true, // only true when the router will run
51
- requireOAuthProviders: true, // false if you only use credentials login
52
- });
53
-
54
- await server.listen();
55
- ```
56
-
57
- `verifyBootstrap` throws a single descriptive `Error` listing every missing registration. The full check covers:
58
-
59
- - `ProjectConfig` — always required.
60
- - `DeployConfig` — when `requireDeployConfig: true`.
61
- - `ServicesConfig` — when `requireServicesConfig: true`.
62
- - OAuth providers — when `requireOAuthProviders: true` and only the default `credentials` entry has been registered.
63
- - `RuntimeMapsProvider` — hard-fails in production; loud-warns in dev because devkit hot-reload normally registers one. Without it, every API/sync request silently resolves to `notFound`.
64
- - `LocalizedNormalizer` — hard-fails in production; warns in dev. Without it, error responses degrade to `errorCode`-as-message (no i18n).
65
-
66
- ## Lower-level entry — `createLuckyStackServer`
67
-
68
- Use this directly when you want to control the order of imports yourself or skip the overlay convention:
69
-
70
- ```ts
71
- import { initializeSentry } from '@luckystack/error-tracking';
72
- import { registerPresenceHooks } from '@luckystack/presence';
73
- import { createLuckyStackServer } from '@luckystack/server';
74
-
75
- initializeSentry();
76
- registerPresenceHooks();
77
-
78
- const server = await createLuckyStackServer({
79
- serveFile,
80
- serveFavicon,
81
- });
82
- await server.listen();
83
- ```
84
-
85
- Both entries handle devkit hot reload + console init in dev mode automatically — opt out with `enableDevTools: false` if you have your own.
86
-
87
- ## Options
88
-
89
- ```ts
90
- interface CreateLuckyStackServerOptions {
91
- port?: number | string; // default: process.env.SERVER_PORT ?? 80
92
- ip?: string; // default: process.env.SERVER_IP ?? '127.0.0.1'
93
- serveFile?: StaticFileHandler; // catch-all for non-framework GETs (Vite output, SPA fallback)
94
- serveFavicon?: FaviconHandler; // /favicon.ico
95
- customRoutes?: CustomRouteHandler; // pre-fallback hook; return true to mark handled
96
- enableDevTools?: boolean; // default: NODE_ENV !== 'production'
97
- maxHttpBufferSize?: number; // default: 5 MB
98
- }
99
- ```
100
-
101
- `customRoutes` runs before the static file serving, so you can add project-specific HTTP endpoints (webhooks, OG image generation, etc.) without forking the package. Return `true` if you ended the response.
102
-
103
- You can also register custom routes globally via `registerCustomRoute(handler)` — the bootstrap call composes every registered handler into the running server. This is what `@luckystack/docs-ui` uses to mount `/_docs`.
104
-
105
- ```ts
106
- import { registerCustomRoute } from '@luckystack/server';
107
-
108
- registerCustomRoute(async (req, res) => {
109
- if (req.url !== '/healthz') return false;
110
- res.statusCode = 200;
111
- res.end('ok');
112
- return true;
113
- });
114
- ```
115
-
116
- ## What it wires
117
-
118
- - **HTTP server** with CORS + security headers, OPTIONS preflight, method validation, cookie sliding, CSRF middleware.
119
- - **Socket.io server** attached to the HTTP server, with optional Redis adapter when configured in deploy config.
120
- - **Framework routes:** `/_health`, `/livez`, `/readyz`, `/_test/reset` (dev/test only), `/api/*` and `/sync/*` (with SSE streaming), `/auth/api`, `/auth/callback/*`, `/uploads/*`, `/assets/*`, `/csrf-token`.
121
- - **Presence broadcasting** (when enabled in project config): connect / disconnect / reconnect, location updates, peer notifications.
122
- - **Boot UUID** written on startup so the load-balancer (`@luckystack/router`) can detect rolling restarts.
123
- - **Dev tools** in non-production: devkit hot reload, console initializer.
124
-
125
- ### HTTP route handler layout
126
-
127
- `handleHttpRequest` is now a thin (~190-line) orchestrator that sets up CORS / origin / security headers, runs the CSRF middleware, then dispatches a route-handler table. Each handler matches its own route path and returns `boolean` (handled or not). The handlers live in `packages/server/src/httpRoutes/`:
128
-
129
- | File | Routes |
130
- | --- | --- |
131
- | `csrfMiddleware.ts` + `csrfRoute.ts` | CSRF guard on writes + `GET /csrf-token` |
132
- | `healthRoutes.ts` | `/livez`, `/readyz`, `/_health` |
133
- | `testResetRoute.ts` | `/_test/reset` (dev/test only — see Security below) |
134
- | `faviconRoute.ts` | `/favicon.ico` |
135
- | `uploadsRoute.ts` | `/uploads/*` (avatar serving via `serveAvatar`) |
136
- | `authApiRoute.ts` | `/auth/api/*` |
137
- | `authCallbackRoute.ts` | `/auth/callback/*` |
138
- | `apiRoute.ts` | `/api/*` (delegates to `@luckystack/api`'s `handleHttpApiRequest`) |
139
- | `syncRoute.ts` | `/sync/*` (delegates to `@luckystack/sync`'s `handleHttpSyncRequest`) |
140
- | `customRoutes.ts` | Calls every handler registered via `registerCustomRoute(...)` and the inline `customRoutes` option |
141
- | `staticRoutes.ts` | Final fallback to the consumer's `serveFile(...)` (Vite SPA, etc.) |
142
-
143
- Top-level `handleHttpRequest` + `dispatchRoutes(handlers, ctx)` are the only orchestration; everything else is a flat list of single-purpose handlers. SSE handling, error fall-through, and dispatch order are preserved.
144
-
145
- ### Security defaults that may surprise you
146
-
147
- - **CORS fail-closed.** If neither `Origin` nor `Referer` is present, only read-only methods (GET, HEAD, OPTIONS) are allowed; state-changing methods are rejected with 403. Earlier builds fell back to `Host`, which silently bypassed CORS for non-browser callers (`curl`, server-to-server). When you `curl` a write endpoint, set `-H 'Origin: https://your-allowed-origin'`.
148
- - **`/_test/reset` is fail-closed.** It requires both `NODE_ENV` to be exactly `development` or `test` AND a non-empty `TEST_RESET_TOKEN` env var. Any other state returns 403 (no silent allow-list). Wire `TEST_RESET_TOKEN` in your dev/test `.env.local` and pass it as the `x-test-reset-token: ${TOKEN}` header on the reset call. `@luckystack/test-runner`'s `resetServerState` reads the same env var.
149
- - **CSRF middleware.** Writes to `/api/*` and `/sync/*` require an `x-csrf-token` header that matches the value minted on the session record (mirrored via `GET /auth/csrf`). The `apiRequest` helper in `@luckystack/core/client` attaches it automatically. Rejections dispatch the `csrfMismatch` hook before returning 403; the payload contains presence-only token info, never the value. The header name, token length, and cookie options are customisable via `registerCsrfConfig({ headerName, tokenLength, cookieOptions })` from `@luckystack/core` — see `packages/core/docs/csrf-config.md`.
150
-
151
- ## Public API
152
-
153
- | Export | Purpose |
154
- | --- | --- |
155
- | `bootstrapLuckyStack(options)` | High-level entry: verifies config, auto-imports overlay, then calls `createLuckyStackServer`. |
156
- | `createLuckyStackServer(options)` | Lower-level factory that returns `{ httpServer, ioServer, listen, stop, close }` (`stop`/`close` = graceful MIS-016 shutdown). |
157
- | `verifyBootstrap(requirements?)` | Pre-flight check for project/deploy/services config and required env keys. |
158
- | `registerCustomRoute(handler)` / `getCustomRoutes()` / `clearCustomRoutes()` | Global custom-route registry composed by `bootstrapLuckyStack`. |
159
- | Hook payload types: `OnSocketConnectPayload`, `OnSocketDisconnectPayload`, `PreRoomJoinPayload`, `PostRoomJoinPayload`, `PreRoomLeavePayload`, `PostRoomLeavePayload`, `OnLocationUpdatePayload` | For socket-lifecycle hook handlers. |
160
- | Types: `CreateLuckyStackServerOptions`, `BootstrapLuckyStackOptions`, `BootstrapRequirements`, `RunningLuckyStackServer`, `RouteContext`, `StaticFileHandler`, `FaviconHandler`, `CustomRouteHandler` | Handler typing. |
161
-
162
- ## Dependencies
163
-
164
- - Runtime: `@luckystack/api`, `@luckystack/core`, `@luckystack/login`, `@luckystack/presence`, `@luckystack/sync`
165
- - Peer (canonical ranges, standardized 2026-05-07):
166
- - `@prisma/client@^6.19.0` (transitively required via `@luckystack/core`)
167
- - `socket.io@^4.8.0`
168
- - Optional peer: `@luckystack/error-tracking`, `@luckystack/email`, `@luckystack/docs-ui` — bootstrap auto-detects them but does not require them.
169
-
170
- ## Selecting bundles + port at runtime
171
-
172
- `@luckystack/server/parseArgv` is a side-effect-only entrypoint. Import it as the **first line** of your `server.ts` so positional CLI args are parsed before any module that reads `process.env.SERVER_PORT` at load time (notably your project's `config.ts`).
173
-
174
- ```ts
175
- // server.ts
176
- import '@luckystack/server/parseArgv';
177
- // ...rest of your bootstrap
178
- ```
179
-
180
- Argv shape: `<bundle[,bundle...]> [port]`
181
-
182
- ```bash
183
- npm run server # default preset, port 80
184
- npm run server -- billing # one bundle, port 80
185
- npm run server -- billing,vehicles 4001 # merge bundles, listen on 4001
186
- ```
187
-
188
- When multiple presets are passed, the framework loads each preset's generated route map and shallow-merges `apis` / `syncs` / `functions`. Key collisions across presets throw at boot (services must own exactly one preset).
189
-
190
- ## Related architecture docs
191
-
192
- - [`docs/ARCHITECTURE_PACKAGING.md`](../../docs/ARCHITECTURE_PACKAGING.md) — package split, multi-service builds, preset bundles.
193
- - [`docs/ARCHITECTURE_SOCKET.md`](../../docs/ARCHITECTURE_SOCKET.md) — Socket.io setup, Redis adapter, room model.
194
- - [`docs/HOSTING.md`](../../docs/HOSTING.md) — multi-instance deployment, `@luckystack/router`, health probes.
195
-
196
- ## License
197
-
198
- MIT — see [LICENSE](../../LICENSE).
1
+ # @luckystack/server
2
+
3
+ > One-call server bootstrap for [LuckyStack](https://github.com/ItsLucky23/LuckyStack-v2). HTTP + Socket.io + framework routes (`/api/*`, `/sync/*`, `/_health`, `/_test/reset`, `/auth/*`, `/uploads/*`) wired together. Your `server.ts` shrinks to ~20 lines.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @luckystack/server @luckystack/core @luckystack/api @luckystack/login @luckystack/sync @luckystack/presence socket.io
9
+ ```
10
+
11
+ ## Quickstart — recommended (`bootstrapLuckyStack`)
12
+
13
+ `bootstrapLuckyStack` is a thin wrapper around `createLuckyStackServer` that auto-imports your `luckystack/<pkg>/*.ts` overlay files in topological order before listening, so registries (DI, hooks, providers) are populated by the time the HTTP server boots. This is what `create-luckystack-app` scaffolds.
14
+
15
+ ```ts
16
+ import 'dotenv/config';
17
+ import '../config'; // your registerProjectConfig(...)
18
+ import '../deploy.config'; // your registerDeployConfig(...)
19
+ import '../services.config'; // your registerServicesConfig(...)
20
+
21
+ import { bootstrapLuckyStack } from '@luckystack/server';
22
+ import { serveFile, serveFavicon } from './prod/serveFile';
23
+
24
+ const server = await bootstrapLuckyStack({
25
+ serveFile,
26
+ serveFavicon,
27
+ });
28
+
29
+ await server.listen();
30
+ ```
31
+
32
+ The bootstrap call runs (in order):
33
+
34
+ 1. Auto-imports `luckystack/core/*.ts`, `luckystack/deploy/*.ts`, `luckystack/login/*.ts`, `luckystack/sentry/*.ts`, `luckystack/presence/*.ts`, `luckystack/docs-ui/*.ts`, `luckystack/server/*.ts` (topologically sorted, then alphabetically inside each folder).
35
+ 2. Hands off to `createLuckyStackServer(options)`.
36
+
37
+ Set `skipOverlayLoad: true` to handle every registration yourself, or `overlayRoot: 'custom-folder'` to load from somewhere other than `./luckystack`.
38
+
39
+ ### Pre-flight check — `verifyBootstrap`
40
+
41
+ Call `verifyBootstrap` **after** the overlay loads (or after your manual registrations) and **before** `server.listen()` if you want to fail fast on missing registrations instead of silent runtime crashes:
42
+
43
+ ```ts
44
+ import { bootstrapLuckyStack, verifyBootstrap } from '@luckystack/server';
45
+
46
+ const server = await bootstrapLuckyStack({ serveFile, serveFavicon });
47
+
48
+ await verifyBootstrap({
49
+ requireDeployConfig: true, // single-instance deploys can omit this
50
+ requireServicesConfig: true, // only true when the router will run
51
+ requireOAuthProviders: true, // false if you only use credentials login
52
+ });
53
+
54
+ await server.listen();
55
+ ```
56
+
57
+ `verifyBootstrap` throws a single descriptive `Error` listing every missing registration. The full check covers:
58
+
59
+ - `ProjectConfig` — always required.
60
+ - `DeployConfig` — when `requireDeployConfig: true`.
61
+ - `ServicesConfig` — when `requireServicesConfig: true`.
62
+ - OAuth providers — when `requireOAuthProviders: true` and only the default `credentials` entry has been registered.
63
+ - `RuntimeMapsProvider` — hard-fails in production; loud-warns in dev because devkit hot-reload normally registers one. Without it, every API/sync request silently resolves to `notFound`.
64
+ - `LocalizedNormalizer` — hard-fails in production; warns in dev. Without it, error responses degrade to `errorCode`-as-message (no i18n).
65
+
66
+ ## Lower-level entry — `createLuckyStackServer`
67
+
68
+ Use this directly when you want to control the order of imports yourself or skip the overlay convention:
69
+
70
+ ```ts
71
+ import { initializeSentry } from '@luckystack/error-tracking';
72
+ import { registerPresenceHooks } from '@luckystack/presence';
73
+ import { createLuckyStackServer } from '@luckystack/server';
74
+
75
+ initializeSentry();
76
+ registerPresenceHooks();
77
+
78
+ const server = await createLuckyStackServer({
79
+ serveFile,
80
+ serveFavicon,
81
+ });
82
+ await server.listen();
83
+ ```
84
+
85
+ Both entries handle devkit hot reload + console init in dev mode automatically — opt out with `enableDevTools: false` if you have your own.
86
+
87
+ ## Options
88
+
89
+ ```ts
90
+ interface CreateLuckyStackServerOptions {
91
+ port?: number | string; // default: process.env.SERVER_PORT ?? 80
92
+ ip?: string; // default: process.env.SERVER_IP ?? '127.0.0.1'
93
+ serveFile?: StaticFileHandler; // catch-all for non-framework GETs (Vite output, SPA fallback)
94
+ serveFavicon?: FaviconHandler; // /favicon.ico
95
+ customRoutes?: CustomRouteHandler; // pre-fallback hook; return true to mark handled
96
+ enableDevTools?: boolean; // default: NODE_ENV !== 'production'
97
+ maxHttpBufferSize?: number; // default: 5 MB
98
+ }
99
+ ```
100
+
101
+ `customRoutes` runs before the static file serving, so you can add project-specific HTTP endpoints (webhooks, OG image generation, etc.) without forking the package. Return `true` if you ended the response.
102
+
103
+ You can also register custom routes globally via `registerCustomRoute(handler)` — the bootstrap call composes every registered handler into the running server. This is what `@luckystack/docs-ui` uses to mount `/_docs`.
104
+
105
+ ```ts
106
+ import { registerCustomRoute } from '@luckystack/server';
107
+
108
+ registerCustomRoute(async (req, res) => {
109
+ if (req.url !== '/healthz') return false;
110
+ res.statusCode = 200;
111
+ res.end('ok');
112
+ return true;
113
+ });
114
+ ```
115
+
116
+ ## What it wires
117
+
118
+ - **HTTP server** with CORS + security headers, OPTIONS preflight, method validation, cookie sliding, CSRF middleware.
119
+ - **Socket.io server** attached to the HTTP server, with optional Redis adapter when configured in deploy config.
120
+ - **Framework routes:** `/_health`, `/livez`, `/readyz`, `/_test/reset` (dev/test only), `/api/*` and `/sync/*` (with SSE streaming), `/auth/api`, `/auth/callback/*`, `/uploads/*`, `/assets/*`, `/csrf-token`.
121
+ - **Presence broadcasting** (when enabled in project config): connect / disconnect / reconnect, location updates, peer notifications.
122
+ - **Boot UUID** written on startup so the load-balancer (`@luckystack/router`) can detect rolling restarts.
123
+ - **Dev tools** in non-production: devkit hot reload, console initializer.
124
+
125
+ ### HTTP route handler layout
126
+
127
+ `handleHttpRequest` is now a thin (~190-line) orchestrator that sets up CORS / origin / security headers, runs the CSRF middleware, then dispatches a route-handler table. Each handler matches its own route path and returns `boolean` (handled or not). The handlers live in `packages/server/src/httpRoutes/`:
128
+
129
+ | File | Routes |
130
+ | --- | --- |
131
+ | `csrfMiddleware.ts` + `csrfRoute.ts` | CSRF guard on writes + `GET /csrf-token` |
132
+ | `healthRoutes.ts` | `/livez`, `/readyz`, `/_health` |
133
+ | `testResetRoute.ts` | `/_test/reset` (dev/test only — see Security below) |
134
+ | `faviconRoute.ts` | `/favicon.ico` |
135
+ | `uploadsRoute.ts` | `/uploads/*` (avatar serving via `serveAvatar`) |
136
+ | `authApiRoute.ts` | `/auth/api/*` |
137
+ | `authCallbackRoute.ts` | `/auth/callback/*` |
138
+ | `apiRoute.ts` | `/api/*` (delegates to `@luckystack/api`'s `handleHttpApiRequest`) |
139
+ | `syncRoute.ts` | `/sync/*` (delegates to `@luckystack/sync`'s `handleHttpSyncRequest`) |
140
+ | `customRoutes.ts` | Calls every handler registered via `registerCustomRoute(...)` and the inline `customRoutes` option |
141
+ | `staticRoutes.ts` | Final fallback to the consumer's `serveFile(...)` (Vite SPA, etc.) |
142
+
143
+ Top-level `handleHttpRequest` + `dispatchRoutes(handlers, ctx)` are the only orchestration; everything else is a flat list of single-purpose handlers. SSE handling, error fall-through, and dispatch order are preserved.
144
+
145
+ ### Security defaults that may surprise you
146
+
147
+ - **CORS fail-closed.** If neither `Origin` nor `Referer` is present, only read-only methods (GET, HEAD, OPTIONS) are allowed; state-changing methods are rejected with 403. Earlier builds fell back to `Host`, which silently bypassed CORS for non-browser callers (`curl`, server-to-server). When you `curl` a write endpoint, set `-H 'Origin: https://your-allowed-origin'`.
148
+ - **`/_test/reset` is fail-closed.** It requires both `NODE_ENV` to be exactly `development` or `test` AND a non-empty `TEST_RESET_TOKEN` env var. Any other state returns 403 (no silent allow-list). Wire `TEST_RESET_TOKEN` in your dev/test `.env.local` and pass it as the `x-test-reset-token: ${TOKEN}` header on the reset call. `@luckystack/test-runner`'s `resetServerState` reads the same env var.
149
+ - **CSRF middleware.** Writes to `/api/*` and `/sync/*` require an `x-csrf-token` header that matches the value minted on the session record (mirrored via `GET /auth/csrf`). The `apiRequest` helper in `@luckystack/core/client` attaches it automatically. Rejections dispatch the `csrfMismatch` hook before returning 403; the payload contains presence-only token info, never the value. The header name, token length, and cookie options are customisable via `registerCsrfConfig({ headerName, tokenLength, cookieOptions })` from `@luckystack/core` — see `packages/core/docs/csrf-config.md`.
150
+
151
+ ## Public API
152
+
153
+ | Export | Purpose |
154
+ | --- | --- |
155
+ | `bootstrapLuckyStack(options)` | High-level entry: verifies config, auto-imports overlay, then calls `createLuckyStackServer`. |
156
+ | `createLuckyStackServer(options)` | Lower-level factory that returns `{ httpServer, ioServer, listen, stop, close }` (`stop`/`close` = graceful MIS-016 shutdown). |
157
+ | `verifyBootstrap(requirements?)` | Pre-flight check for project/deploy/services config and required env keys. |
158
+ | `registerCustomRoute(handler)` / `getCustomRoutes()` / `clearCustomRoutes()` | Global custom-route registry composed by `bootstrapLuckyStack`. |
159
+ | Hook payload types: `OnSocketConnectPayload`, `OnSocketDisconnectPayload`, `PreRoomJoinPayload`, `PostRoomJoinPayload`, `PreRoomLeavePayload`, `PostRoomLeavePayload`, `OnLocationUpdatePayload` | For socket-lifecycle hook handlers. |
160
+ | Types: `CreateLuckyStackServerOptions`, `BootstrapLuckyStackOptions`, `BootstrapRequirements`, `RunningLuckyStackServer`, `RouteContext`, `StaticFileHandler`, `FaviconHandler`, `CustomRouteHandler` | Handler typing. |
161
+
162
+ ## Dependencies
163
+
164
+ - Runtime: `@luckystack/api`, `@luckystack/core`, `@luckystack/login`, `@luckystack/presence`, `@luckystack/sync`
165
+ - Peer (canonical ranges, standardized 2026-05-07):
166
+ - `@prisma/client@^6.19.0` (transitively required via `@luckystack/core`)
167
+ - `socket.io@^4.8.0`
168
+ - Optional peer: `@luckystack/error-tracking`, `@luckystack/email`, `@luckystack/docs-ui` — bootstrap auto-detects them but does not require them.
169
+
170
+ ## Selecting bundles + port at runtime
171
+
172
+ `@luckystack/server/parseArgv` is a side-effect-only entrypoint. Import it as the **first line** of your `server.ts` so positional CLI args are parsed before any module that reads `process.env.SERVER_PORT` at load time (notably your project's `config.ts`).
173
+
174
+ ```ts
175
+ // server.ts
176
+ import '@luckystack/server/parseArgv';
177
+ // ...rest of your bootstrap
178
+ ```
179
+
180
+ Argv shape: `<bundle[,bundle...]> [port]`
181
+
182
+ ```bash
183
+ npm run server # default preset, port 80
184
+ npm run server -- billing # one bundle, port 80
185
+ npm run server -- billing,vehicles 4001 # merge bundles, listen on 4001
186
+ ```
187
+
188
+ When multiple presets are passed, the framework loads each preset's generated route map and shallow-merges `apis` / `syncs` / `functions`. Key collisions across presets throw at boot (services must own exactly one preset).
189
+
190
+ ## Related architecture docs
191
+
192
+ - [`docs/ARCHITECTURE_PACKAGING.md`](../../docs/ARCHITECTURE_PACKAGING.md) — package split, multi-service builds, preset bundles.
193
+ - [`docs/ARCHITECTURE_SOCKET.md`](../../docs/ARCHITECTURE_SOCKET.md) — Socket.io setup, Redis adapter, room model.
194
+ - [`docs/HOSTING.md`](../../docs/HOSTING.md) — multi-instance deployment, `@luckystack/router`, health probes.
195
+
196
+ ## License
197
+
198
+ MIT — see [LICENSE](../../LICENSE).
@@ -41,4 +41,4 @@ export {
41
41
  getParsedBundles,
42
42
  getParsedPort
43
43
  };
44
- //# sourceMappingURL=chunk-X3OSC5W3.js.map
44
+ //# sourceMappingURL=chunk-RIVFTOTI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/argv.ts"],"sourcesContent":["//? Positional argv parser for the LuckyStack server boot. Replaces\r\n//? `LUCKYSTACK_BUNDLE` + `SERVER_PORT` env-var reads with a single shape:\r\n//?\r\n//? npm run server -- billing,vehicles 4001\r\n//?\r\n//? Arg 0 = comma-separated preset list (runtime maps merged across them).\r\n//? Arg 1 = listen port (numeric).\r\n//?\r\n//? `applyServerArgv()` is called by the side-effect module\r\n//? `@luckystack/server/parseArgv`, which consumers import as the FIRST line\r\n//? of their `server.ts` so the parsed port lands in `process.env.SERVER_PORT`\r\n//? before `config.ts` (top-level `backendUrl` const) is evaluated.\r\n\r\nexport interface ParsedServerArgv {\r\n bundles: string[];\r\n port: number | null;\r\n}\r\n\r\nlet parsedBundles: string[] = [];\r\nlet parsedPort: number | null = null;\r\nlet hasRun = false;\r\n\r\nconst PORT_PATTERN = /^\\d+$/;\r\n\r\nexport const parseServerArgv = (argv: string[]): ParsedServerArgv => {\r\n if (argv.length > 2) {\r\n throw new Error(\r\n `[luckystack:argv] unexpected positional argument(s): \"${argv.slice(2).join(' ')}\". ` +\r\n `Usage: npm run server -- <bundle[,bundle...]> [port]`,\r\n );\r\n }\r\n\r\n const bundles = argv[0] && argv[0].length > 0\r\n ? [...new Set(argv[0].split(',').map((s) => s.trim()).filter(Boolean))]\r\n : [];\r\n\r\n let port: number | null = null;\r\n const portArg = argv[1];\r\n if (portArg !== undefined) {\r\n if (!PORT_PATTERN.test(portArg)) {\r\n throw new Error(\r\n `[luckystack:argv] port argument must be numeric, got: \"${portArg}\". ` +\r\n `Usage: npm run server -- <bundle[,bundle...]> [port]`,\r\n );\r\n }\r\n port = Number.parseInt(portArg, 10);\r\n }\r\n\r\n return { bundles, port };\r\n};\r\n\r\nexport const applyServerArgv = (): void => {\r\n if (hasRun) return;\r\n hasRun = true;\r\n\r\n const result = parseServerArgv(process.argv.slice(2));\r\n parsedBundles = result.bundles;\r\n parsedPort = result.port;\r\n\r\n //? Writeback so the downstream env-readers (`core/env.ts` Zod schema,\r\n //? `core/bindAddress.ts` fallback, consumer `config.ts` backendUrl,\r\n //? `oauthProviders.ts` callback URL) see the resolved port without us\r\n //? having to refactor those four call sites. This is a deliberate\r\n //? implementation detail — argv is the public source of truth.\r\n if (parsedPort !== null) {\r\n process.env.SERVER_PORT = String(parsedPort);\r\n }\r\n};\r\n\r\nexport const getParsedBundles = (): string[] => parsedBundles;\r\nexport const getParsedPort = (): number | null => parsedPort;\r\n"],"mappings":";AAkBA,IAAI,gBAA0B,CAAC;AAC/B,IAAI,aAA4B;AAChC,IAAI,SAAS;AAEb,IAAM,eAAe;AAEd,IAAM,kBAAkB,CAAC,SAAqC;AACnE,MAAI,KAAK,SAAS,GAAG;AACnB,UAAM,IAAI;AAAA,MACR,yDAAyD,KAAK,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC;AAAA,IAElF;AAAA,EACF;AAEA,QAAM,UAAU,KAAK,CAAC,KAAK,KAAK,CAAC,EAAE,SAAS,IACxC,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC,EAAE,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,OAAO,CAAC,CAAC,IACpE,CAAC;AAEL,MAAI,OAAsB;AAC1B,QAAM,UAAU,KAAK,CAAC;AACtB,MAAI,YAAY,QAAW;AACzB,QAAI,CAAC,aAAa,KAAK,OAAO,GAAG;AAC/B,YAAM,IAAI;AAAA,QACR,0DAA0D,OAAO;AAAA,MAEnE;AAAA,IACF;AACA,WAAO,OAAO,SAAS,SAAS,EAAE;AAAA,EACpC;AAEA,SAAO,EAAE,SAAS,KAAK;AACzB;AAEO,IAAM,kBAAkB,MAAY;AACzC,MAAI,OAAQ;AACZ,WAAS;AAET,QAAM,SAAS,gBAAgB,QAAQ,KAAK,MAAM,CAAC,CAAC;AACpD,kBAAgB,OAAO;AACvB,eAAa,OAAO;AAOpB,MAAI,eAAe,MAAM;AACvB,YAAQ,IAAI,cAAc,OAAO,UAAU;AAAA,EAC7C;AACF;AAEO,IAAM,mBAAmB,MAAgB;AACzC,IAAM,gBAAgB,MAAqB;","names":[]}
package/dist/index.d.ts CHANGED
@@ -196,6 +196,9 @@ interface BootstrapLuckyStackOptions extends CreateLuckyStackServerOptions {
196
196
  */
197
197
  skipOverlayLoad?: boolean;
198
198
  }
199
+ declare const OVERLAY_ORDER: string[];
200
+ type OverlayLoader = () => Promise<void>;
201
+ declare const registerOverlayLoader: (loader: OverlayLoader) => void;
199
202
  declare const bootstrapLuckyStack: (options?: BootstrapLuckyStackOptions) => Promise<RunningLuckyStackServer>;
200
203
 
201
204
  interface BootstrapRequirements {
@@ -281,7 +284,12 @@ declare const getPreParamsCustomRoutes: () => readonly CustomRouteHandler[];
281
284
  declare const clearCustomRoutes: () => void;
282
285
 
283
286
  interface OriginExemptMatcher {
284
- /** A route is exempt when its path starts with this prefix. */
287
+ /**
288
+ * A route is exempt when its path equals this prefix OR continues past it on a
289
+ * path-SEGMENT boundary (i.e. `<prefix>/...`). Matching is boundary-aware so a
290
+ * prefix can't bleed into a sibling route — `/webhooks` exempts `/webhooks` and
291
+ * `/webhooks/stripe` but NOT `/webhooksadmin`.
292
+ */
285
293
  pathPrefix: string;
286
294
  }
287
295
  declare const registerOriginExemptPath: (matcher: OriginExemptMatcher) => void;
@@ -302,4 +310,4 @@ declare const registerSecurityHeaders: (builder: SecurityHeadersBuilder | null)
302
310
  /** Read the active builder (or null). */
303
311
  declare const getSecurityHeadersBuilder: () => SecurityHeadersBuilder | null;
304
312
 
305
- export { type BootstrapLuckyStackOptions, type BootstrapRequirements, type CreateLuckyStackServerOptions, type CustomRouteHandler, type CustomRoutePhase, type FaviconHandler, type GeneratedRuntimeMapsModule, type OnLocationUpdatePayload, type OnSocketConnectPayload, type OnSocketDisconnectPayload, type OriginExemptMatcher, type ParsedServerArgv, type PostRoomJoinPayload, type PostRoomLeavePayload, type PreRoomJoinPayload, type PreRoomLeavePayload, type ProdRuntimeMapsLoaderOptions, type RegisterCustomRouteOptions, type RouteContext, type RunningLuckyStackServer, type SecurityHeadersBuilder, type StaticFileHandler, type StopLuckyStackServerOptions, applyServerArgv, bootstrapLuckyStack, clearCustomRoutes, clearOriginExemptPaths, createLuckyStackServer, createProdRuntimeMapsProvider, getCustomRoutes, getOriginExemptPaths, getParsedBundles, getParsedPort, getPreParamsCustomRoutes, getSecurityHeadersBuilder, isOriginExemptPath, parseServerArgv, registerCustomRoute, registerOriginExemptPath, registerProdRuntimeMapsProvider, registerSecurityHeaders, verifyBootstrap };
313
+ export { type BootstrapLuckyStackOptions, type BootstrapRequirements, type CreateLuckyStackServerOptions, type CustomRouteHandler, type CustomRoutePhase, type FaviconHandler, type GeneratedRuntimeMapsModule, OVERLAY_ORDER, type OnLocationUpdatePayload, type OnSocketConnectPayload, type OnSocketDisconnectPayload, type OriginExemptMatcher, type ParsedServerArgv, type PostRoomJoinPayload, type PostRoomLeavePayload, type PreRoomJoinPayload, type PreRoomLeavePayload, type ProdRuntimeMapsLoaderOptions, type RegisterCustomRouteOptions, type RouteContext, type RunningLuckyStackServer, type SecurityHeadersBuilder, type StaticFileHandler, type StopLuckyStackServerOptions, applyServerArgv, bootstrapLuckyStack, clearCustomRoutes, clearOriginExemptPaths, createLuckyStackServer, createProdRuntimeMapsProvider, getCustomRoutes, getOriginExemptPaths, getParsedBundles, getParsedPort, getPreParamsCustomRoutes, getSecurityHeadersBuilder, isOriginExemptPath, parseServerArgv, registerCustomRoute, registerOriginExemptPath, registerOverlayLoader, registerProdRuntimeMapsProvider, registerSecurityHeaders, verifyBootstrap };