@web-ts-toolkit/express-runtime 0.26.0 → 0.27.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/cli-api.js ADDED
@@ -0,0 +1,1084 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/index.ts
34
+ function applySettings(app, options) {
35
+ if (options.disablePoweredBy !== false) {
36
+ app.disable("x-powered-by");
37
+ }
38
+ app.set("etag", options.etag ?? false);
39
+ app.set("trust proxy", options.trustProxy ?? false);
40
+ }
41
+ function applyMiddlewareList(app, list) {
42
+ if (list) {
43
+ for (const mw of list) {
44
+ app.use(mw);
45
+ }
46
+ }
47
+ }
48
+ function applyRouters(app, options) {
49
+ const mounts = [];
50
+ if (options.router) mounts.push(options.router);
51
+ if (options.routers) mounts.push(...options.routers);
52
+ for (const mount of mounts) {
53
+ const path = typeof mount.path === "function" ? mount.path() : mount.path;
54
+ app.use(path, mount.handler);
55
+ }
56
+ }
57
+ function createExpressApp(options = {}) {
58
+ const app = (0, import_express.default)();
59
+ applySettings(app, options);
60
+ applyMiddlewareList(app, options.preMiddleware);
61
+ if (options.json !== false) {
62
+ app.use(import_express.default.json(options.json ?? { limit: "1mb" }));
63
+ }
64
+ if (options.urlencoded !== false) {
65
+ app.use(import_express.default.urlencoded(options.urlencoded ?? { extended: false, limit: "1mb" }));
66
+ }
67
+ applyMiddlewareList(app, options.middleware);
68
+ applyRouters(app, options);
69
+ applyMiddlewareList(app, options.postMiddleware);
70
+ if (options.finalize) {
71
+ options.finalize(app);
72
+ }
73
+ if (options.errorHandler) {
74
+ app.use(options.errorHandler);
75
+ }
76
+ return app;
77
+ }
78
+ function normalizePort(val) {
79
+ if (val === void 0 || val === "") {
80
+ const envPort = process.env.PORT;
81
+ if (envPort === void 0 || envPort === "") {
82
+ return 8080;
83
+ }
84
+ val = envPort;
85
+ }
86
+ if (typeof val === "string") {
87
+ const parsed = Number(val);
88
+ if (Number.isNaN(parsed)) {
89
+ return val;
90
+ }
91
+ val = parsed;
92
+ }
93
+ if (!Number.isFinite(val) || val < 0 || val > 65535) {
94
+ throw new Error(`Invalid port: ${String(val)}`);
95
+ }
96
+ return val;
97
+ }
98
+ function defaultOnError(error, port, logger) {
99
+ if (error.syscall !== "listen") {
100
+ throw error;
101
+ }
102
+ const bind = typeof port === "string" ? `Pipe ${port}` : `Port ${port}`;
103
+ if (error.code === "EACCES") {
104
+ logger.error(`${bind} requires elevated privileges`);
105
+ process.exit(1);
106
+ } else if (error.code === "EADDRINUSE") {
107
+ logger.error(`${bind} is already in use`);
108
+ process.exit(1);
109
+ } else {
110
+ throw error;
111
+ }
112
+ }
113
+ function startLocalServer(app, options = {}) {
114
+ const logger = options.logger ?? defaultLogger;
115
+ const port = normalizePort(options.port);
116
+ const host = options.host ?? process.env.HOST ?? "0.0.0.0";
117
+ const shutdownTimeout = options.shutdownTimeout ?? DEFAULT_SHUTDOWN_TIMEOUT;
118
+ const server = import_node_http.default.createServer(app);
119
+ app.set("port", port);
120
+ const onError = (error) => {
121
+ if (options.onError) {
122
+ options.onError(error);
123
+ } else {
124
+ defaultOnError(error, port, logger);
125
+ }
126
+ };
127
+ const onListening = () => {
128
+ const addr = server.address();
129
+ const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr?.port}`;
130
+ logger.log(`Server running at http://${host}:${port}/ (${bind})`);
131
+ options.onListening?.();
132
+ };
133
+ server.on("error", onError);
134
+ server.on("listening", onListening);
135
+ const shutdown = async () => {
136
+ logger.log("Shutting down...");
137
+ try {
138
+ if (options.onShutdown) {
139
+ await options.onShutdown();
140
+ }
141
+ } catch (err) {
142
+ logger.error("onShutdown hook failed:", err);
143
+ }
144
+ await new Promise((resolve) => {
145
+ const timer = setTimeout(() => {
146
+ server.closeAllConnections?.();
147
+ resolve();
148
+ }, shutdownTimeout);
149
+ server.close((err) => {
150
+ clearTimeout(timer);
151
+ if (err) {
152
+ logger.error("Server close error:", err);
153
+ }
154
+ resolve();
155
+ });
156
+ });
157
+ if (options.exitAfterShutdown) {
158
+ process.exit(0);
159
+ }
160
+ };
161
+ if (options.signals !== false) {
162
+ const list = options.signals === void 0 || options.signals === true ? DEFAULT_SIGNALS : options.signals;
163
+ for (const sig of list) {
164
+ process.once(sig, () => void shutdown());
165
+ }
166
+ }
167
+ const start = async () => {
168
+ try {
169
+ if (options.init) {
170
+ await options.init();
171
+ }
172
+ if (typeof port === "number") {
173
+ server.listen(port, host);
174
+ } else {
175
+ server.listen(port);
176
+ }
177
+ } catch (err) {
178
+ server.emit("error", err);
179
+ }
180
+ };
181
+ void start();
182
+ return {
183
+ server,
184
+ shutdown
185
+ };
186
+ }
187
+ var import_node_http, import_express, import_serverless_http, defaultLogger, DEFAULT_SIGNALS, DEFAULT_SHUTDOWN_TIMEOUT;
188
+ var init_index = __esm({
189
+ "src/index.ts"() {
190
+ "use strict";
191
+ import_node_http = __toESM(require("http"));
192
+ import_express = __toESM(require("express"));
193
+ import_serverless_http = __toESM(require("serverless-http"));
194
+ defaultLogger = {
195
+ log: (...args) => console.log(...args),
196
+ error: (...args) => console.error(...args),
197
+ debug: (...args) => console.debug(...args)
198
+ };
199
+ DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
200
+ DEFAULT_SHUTDOWN_TIMEOUT = 5e3;
201
+ }
202
+ });
203
+
204
+ // src/cli-utils.ts
205
+ function readValue(argv, index, name) {
206
+ const value = argv[index + 1];
207
+ if (value === void 0 || value.startsWith("--")) {
208
+ throw new Error(`Missing value for argument: ${name}`);
209
+ }
210
+ return value;
211
+ }
212
+ function printHelp() {
213
+ console.log(`wtt-express-runtime
214
+
215
+ Run an Express app locally, bundle it for local or serverless runtimes, or run the bundle.
216
+
217
+ Usage:
218
+ wtt-express-runtime <command> <app-module> [options]
219
+ wtt-express-runtime <app-module> [options] (alias for dev)
220
+
221
+ Commands:
222
+ dev Run the Express app as a local dev server
223
+ build Bundle the Express app as a local app module
224
+ start Run a bundled local app module
225
+ build-serverless Bundle the Express app as a serverless handler
226
+ start-serverless Run a bundled serverless handler locally
227
+
228
+ Dev options:
229
+ --port <number> Port or named pipe (default: process.env.PORT or 8080)
230
+ --host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
231
+ --no-signals Disable SIGINT/SIGTERM handler registration
232
+ --shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
233
+ --require <module> Module(s) to preload before app load (repeatable)
234
+ --env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
235
+ --watch <paths> Comma-separated paths to watch for restart (repeatable; dev only)
236
+ --ext <extensions> Comma-separated extensions to watch (default: ts,js,mjs,cjs,json)
237
+ --delay <ms> Debounce ms before restarting on change (default: 500)
238
+
239
+ Build options:
240
+ --init <path> Init hook module (default export, async function)
241
+ --out-dir <path> Output directory (default: dist)
242
+ --out-name <name> Output filename without extension (default: app)
243
+ --format <cjs|esm> Output format (default: cjs)
244
+ --target <target> Compilation target (default: node22)
245
+ --external <pkg> Mark package as external (repeatable; express always external)
246
+ --no-clean Don't clean the output directory before building
247
+
248
+ Start options:
249
+ --port <number> Port or named pipe (default: process.env.PORT or 8080)
250
+ --host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
251
+ --no-signals Disable SIGINT/SIGTERM handler registration
252
+ --shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
253
+ --require <module> Module(s) to preload before app load (repeatable)
254
+ --env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
255
+
256
+ Build-serverless options:
257
+ --init <path> Init hook module (default export, async function)
258
+ --out-dir <path> Output directory (default: dist)
259
+ --out-name <name> Output filename without extension (default: handler)
260
+ --format <cjs|esm> Output format (default: cjs)
261
+ --target <target> Compilation target (default: node22)
262
+ --external <pkg> Mark package as external (repeatable; express always external)
263
+ --no-clean Don't clean the output directory before building
264
+
265
+ Start-serverless options:
266
+ --port <number> Port or named pipe (default: process.env.PORT or 8080)
267
+ --host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
268
+ --no-signals Disable SIGINT/SIGTERM handler registration
269
+ --shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
270
+ --require <module> Module(s) to preload before handler load (repeatable)
271
+ --env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
272
+
273
+ Global options:
274
+ -V, --version Show version
275
+ -h, --help Show this help message
276
+
277
+ Examples:
278
+ wtt-express-runtime dev ./dist/app.js
279
+ wtt-express-runtime dev ./dist/app.js --port 3000 --host localhost
280
+ wtt-express-runtime dev ./src/app.ts --env .env --require tsconfig-paths/register --watch ./src,./shared
281
+ wtt-express-runtime build ./src/app.ts --out-dir dist
282
+ wtt-express-runtime start ./dist/app.js --port 3000 --env .env
283
+ wtt-express-runtime build-serverless ./src/app.ts --out-dir netlify/functions
284
+ wtt-express-runtime build-serverless ./src/app.ts --init ./src/init.ts --format esm
285
+ wtt-express-runtime start-serverless ./netlify/functions/handler.js --port 9000 --env .env
286
+ wtt-express-runtime build-serverless ./src/app.ts && wtt-express-runtime start-serverless ./dist/handler.js
287
+
288
+ Notes:
289
+ - In dev mode, the CLI evaluates arbitrary code from <app-module> in the current process.
290
+ - TypeScript app modules in dev mode require a TS loader. Run via tsx:
291
+ npx tsx ./node_modules/@web-ts-toolkit/express-runtime/dist/cli.js dev ./src/app.ts
292
+ Or use --require with a TS-aware loader module.
293
+ - --env files are parsed as KEY=VALUE; existing process.env entries are never overridden.
294
+ For advanced dotenv features (multiline, expansion), --require dotenv/config instead.
295
+ - --watch forks a child process running the same CLI without --watch. On file change,
296
+ the child is killed (SIGTERM) and respawned after the debounce delay.
297
+ - In build/build-serverless mode, express is always external. Add more externals with --external.
298
+ - In start mode, the bundled app file must default-export an Express app (or export it as "app").
299
+ If the bundle exports "init", it runs before the server starts listening.
300
+ - In start-serverless mode, the bundled handler file must be a JS/CJS module whose
301
+ "handler" export (or default export) is a function: (event, context) => Promise<result>.
302
+ - Init logic for dev mode (DB connections, etc.): add at the top level of your app module.
303
+ `);
304
+ }
305
+ function isVersion(arg) {
306
+ return arg === "-V" || arg === "--version";
307
+ }
308
+ function isHelp(arg) {
309
+ return arg === "-h" || arg === "--help";
310
+ }
311
+ function isSubcommand(arg) {
312
+ return arg === "dev" || arg === "build" || arg === "start" || arg === "build-serverless" || arg === "start-serverless";
313
+ }
314
+ function parseRepeatable(argv, index, arg, list) {
315
+ const value = readValue(argv, index, arg);
316
+ for (const part of value.split(",")) {
317
+ const trimmed = part.trim();
318
+ if (trimmed) list.push(trimmed);
319
+ }
320
+ return index + 1;
321
+ }
322
+ function parseDevArgs(argv) {
323
+ const options = {};
324
+ const requireModules = [];
325
+ const envFiles = [];
326
+ const watchPaths = [];
327
+ let watchExt;
328
+ let watchDelay;
329
+ let appPath;
330
+ for (let index = 0; index < argv.length; index += 1) {
331
+ const arg = argv[index];
332
+ if (arg === "--") {
333
+ continue;
334
+ }
335
+ if (isHelp(arg) || isVersion(arg)) {
336
+ continue;
337
+ }
338
+ if (arg === "--port") {
339
+ const port = readValue(argv, index, arg);
340
+ const portNum = Number(port);
341
+ options.port = Number.isNaN(portNum) ? port : portNum;
342
+ index += 1;
343
+ continue;
344
+ }
345
+ if (arg.startsWith("--port=")) {
346
+ const port = arg.slice("--port=".length);
347
+ const portNum = Number(port);
348
+ options.port = Number.isNaN(portNum) ? port : portNum;
349
+ continue;
350
+ }
351
+ if (arg === "--host") {
352
+ options.host = readValue(argv, index, arg);
353
+ index += 1;
354
+ continue;
355
+ }
356
+ if (arg.startsWith("--host=")) {
357
+ options.host = arg.slice("--host=".length);
358
+ continue;
359
+ }
360
+ if (arg === "--no-signals") {
361
+ options.signals = false;
362
+ continue;
363
+ }
364
+ if (arg === "--shutdown-timeout") {
365
+ options.shutdownTimeout = Number(readValue(argv, index, arg));
366
+ index += 1;
367
+ continue;
368
+ }
369
+ if (arg.startsWith("--shutdown-timeout=")) {
370
+ options.shutdownTimeout = Number(arg.slice("--shutdown-timeout=".length));
371
+ continue;
372
+ }
373
+ if (arg === "--require") {
374
+ index = parseRepeatable(argv, index, arg, requireModules);
375
+ continue;
376
+ }
377
+ if (arg.startsWith("--require=")) {
378
+ for (const part of arg.slice("--require=".length).split(",")) {
379
+ const trimmed = part.trim();
380
+ if (trimmed) requireModules.push(trimmed);
381
+ }
382
+ continue;
383
+ }
384
+ if (arg === "--env") {
385
+ index = parseRepeatable(argv, index, arg, envFiles);
386
+ continue;
387
+ }
388
+ if (arg.startsWith("--env=")) {
389
+ for (const part of arg.slice("--env=".length).split(",")) {
390
+ const trimmed = part.trim();
391
+ if (trimmed) envFiles.push(trimmed);
392
+ }
393
+ continue;
394
+ }
395
+ if (arg === "--watch") {
396
+ index = parseRepeatable(argv, index, arg, watchPaths);
397
+ continue;
398
+ }
399
+ if (arg.startsWith("--watch=")) {
400
+ for (const part of arg.slice("--watch=".length).split(",")) {
401
+ const trimmed = part.trim();
402
+ if (trimmed) watchPaths.push(trimmed);
403
+ }
404
+ continue;
405
+ }
406
+ if (arg === "--ext") {
407
+ watchExt = [];
408
+ index = parseRepeatable(argv, index, arg, watchExt);
409
+ continue;
410
+ }
411
+ if (arg.startsWith("--ext=")) {
412
+ watchExt = [];
413
+ for (const part of arg.slice("--ext=".length).split(",")) {
414
+ const trimmed = part.trim();
415
+ if (trimmed) watchExt.push(trimmed);
416
+ }
417
+ continue;
418
+ }
419
+ if (arg === "--delay") {
420
+ watchDelay = Number(readValue(argv, index, arg));
421
+ index += 1;
422
+ continue;
423
+ }
424
+ if (arg.startsWith("--delay=")) {
425
+ watchDelay = Number(arg.slice("--delay=".length));
426
+ continue;
427
+ }
428
+ if (!arg.startsWith("--")) {
429
+ if (appPath) {
430
+ throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
431
+ }
432
+ appPath = arg;
433
+ continue;
434
+ }
435
+ throw new Error(`Unknown argument: ${arg}`);
436
+ }
437
+ if (!appPath) {
438
+ printHelp();
439
+ throw new Error("Missing required argument: <app-module>");
440
+ }
441
+ return {
442
+ appPath,
443
+ options,
444
+ require: requireModules,
445
+ env: envFiles,
446
+ watch: watchPaths,
447
+ watchExt: watchExt ?? DEFAULT_WATCH_EXTENSIONS,
448
+ watchDelay: watchDelay ?? DEFAULT_WATCH_DELAY
449
+ };
450
+ }
451
+ function parseStartLikeArgs(argv, subcommandName) {
452
+ for (const arg of argv) {
453
+ if (arg === "--watch" || arg.startsWith("--watch=") || arg === "--ext" || arg.startsWith("--ext=") || arg === "--delay" || arg.startsWith("--delay=")) {
454
+ throw new Error(`--watch/--ext/--delay are not supported with the ${subcommandName} subcommand`);
455
+ }
456
+ }
457
+ return parseDevArgs(argv);
458
+ }
459
+ function parseStartArgs(argv) {
460
+ const result = parseStartLikeArgs(argv, "start");
461
+ return {
462
+ appPath: result.appPath,
463
+ options: result.options,
464
+ require: result.require,
465
+ env: result.env
466
+ };
467
+ }
468
+ function parseStartServerlessArgs(argv) {
469
+ const result = parseStartLikeArgs(argv, "start-serverless");
470
+ return {
471
+ handlerPath: result.appPath,
472
+ options: result.options,
473
+ require: result.require,
474
+ env: result.env
475
+ };
476
+ }
477
+ function parseBuildArgs(argv, outNameDefault) {
478
+ let appPath;
479
+ const external = [];
480
+ const result = {
481
+ initPath: void 0,
482
+ outDir: "dist",
483
+ outName: outNameDefault,
484
+ format: "cjs",
485
+ target: "node22",
486
+ external,
487
+ clean: true
488
+ };
489
+ for (let index = 0; index < argv.length; index += 1) {
490
+ const arg = argv[index];
491
+ if (arg === "--") {
492
+ continue;
493
+ }
494
+ if (isHelp(arg) || isVersion(arg)) {
495
+ continue;
496
+ }
497
+ if (arg === "--init") {
498
+ result.initPath = readValue(argv, index, arg);
499
+ index += 1;
500
+ continue;
501
+ }
502
+ if (arg.startsWith("--init=")) {
503
+ result.initPath = arg.slice("--init=".length);
504
+ continue;
505
+ }
506
+ if (arg === "--out-dir") {
507
+ result.outDir = readValue(argv, index, arg);
508
+ index += 1;
509
+ continue;
510
+ }
511
+ if (arg.startsWith("--out-dir=")) {
512
+ result.outDir = arg.slice("--out-dir=".length);
513
+ continue;
514
+ }
515
+ if (arg === "--out-name") {
516
+ result.outName = readValue(argv, index, arg);
517
+ index += 1;
518
+ continue;
519
+ }
520
+ if (arg.startsWith("--out-name=")) {
521
+ result.outName = arg.slice("--out-name=".length);
522
+ continue;
523
+ }
524
+ if (arg === "--format") {
525
+ const fmt = readValue(argv, index, arg);
526
+ if (fmt !== "cjs" && fmt !== "esm") {
527
+ throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
528
+ }
529
+ result.format = fmt;
530
+ index += 1;
531
+ continue;
532
+ }
533
+ if (arg.startsWith("--format=")) {
534
+ const fmt = arg.slice("--format=".length);
535
+ if (fmt !== "cjs" && fmt !== "esm") {
536
+ throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
537
+ }
538
+ result.format = fmt;
539
+ continue;
540
+ }
541
+ if (arg === "--target") {
542
+ result.target = readValue(argv, index, arg);
543
+ index += 1;
544
+ continue;
545
+ }
546
+ if (arg.startsWith("--target=")) {
547
+ result.target = arg.slice("--target=".length);
548
+ continue;
549
+ }
550
+ if (arg === "--external") {
551
+ external.push(readValue(argv, index, arg));
552
+ index += 1;
553
+ continue;
554
+ }
555
+ if (arg.startsWith("--external=")) {
556
+ external.push(arg.slice("--external=".length));
557
+ continue;
558
+ }
559
+ if (arg === "--no-clean") {
560
+ result.clean = false;
561
+ continue;
562
+ }
563
+ if (!arg.startsWith("--")) {
564
+ if (appPath) {
565
+ throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
566
+ }
567
+ appPath = arg;
568
+ continue;
569
+ }
570
+ throw new Error(`Unknown argument: ${arg}`);
571
+ }
572
+ if (!appPath) {
573
+ printHelp();
574
+ throw new Error("Missing required argument: <app-module>");
575
+ }
576
+ return { appPath, ...result };
577
+ }
578
+ function parseLocalBuildArgs(argv) {
579
+ return parseBuildArgs(argv, "app");
580
+ }
581
+ function parseBuildServerlessArgs(argv) {
582
+ return parseBuildArgs(argv, "handler");
583
+ }
584
+ function parseArgs(argv) {
585
+ if (argv.length === 0) {
586
+ printHelp();
587
+ return null;
588
+ }
589
+ if (argv.some((a) => isHelp(a))) {
590
+ printHelp();
591
+ return null;
592
+ }
593
+ if (argv.some((a) => isVersion(a))) {
594
+ console.log(CLI_VERSION);
595
+ return null;
596
+ }
597
+ const first = argv[0];
598
+ if (isSubcommand(first)) {
599
+ const rest = argv.slice(1);
600
+ if (first === "dev") {
601
+ return { subcommand: "dev", dev: parseDevArgs(rest) };
602
+ }
603
+ if (first === "build") {
604
+ return { subcommand: "build", build: parseLocalBuildArgs(rest) };
605
+ }
606
+ if (first === "start") {
607
+ return { subcommand: "start", start: parseStartArgs(rest) };
608
+ }
609
+ if (first === "build-serverless") {
610
+ return { subcommand: "build-serverless", buildServerless: parseBuildServerlessArgs(rest) };
611
+ }
612
+ return { subcommand: "start-serverless", startServerless: parseStartServerlessArgs(rest) };
613
+ }
614
+ return { subcommand: "dev", dev: parseDevArgs(argv) };
615
+ }
616
+ function isExpressApp(x) {
617
+ if (x === null || x === void 0) return false;
618
+ const t = typeof x;
619
+ if (t !== "object" && t !== "function") return false;
620
+ return typeof x.listen === "function" && typeof x.use === "function";
621
+ }
622
+ function extractExport(mod) {
623
+ return mod.default ?? mod.app;
624
+ }
625
+ async function resolveExport(exported, appPath) {
626
+ if (isExpressApp(exported)) {
627
+ return exported;
628
+ }
629
+ if (typeof exported === "function") {
630
+ const result = await exported();
631
+ if (!isExpressApp(result)) {
632
+ throw new Error(`Function in "${appPath}" did not return an Express app.`);
633
+ }
634
+ return result;
635
+ }
636
+ throw new Error(`Default export of "${appPath}" is not an Express app or an async function returning one.`);
637
+ }
638
+ async function loadApp(appPath) {
639
+ const fullPath = (0, import_node_path.resolve)(process.cwd(), appPath);
640
+ const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
641
+ const mod = await import(moduleUrl);
642
+ const exported = extractExport(mod);
643
+ if (!exported) {
644
+ throw new Error(
645
+ `Module "${appPath}" must default-export an Express app or an async function returning one. Exports: ${Object.keys(mod).join(", ")}`
646
+ );
647
+ }
648
+ return resolveExport(exported, appPath);
649
+ }
650
+ function parseEnvFile(content) {
651
+ const result = {};
652
+ for (const line of content.split("\n")) {
653
+ let trimmed = line.trim();
654
+ if (!trimmed || trimmed.startsWith("#")) continue;
655
+ if (trimmed.startsWith("export ")) trimmed = trimmed.slice("export ".length).trim();
656
+ const eqIndex = trimmed.indexOf("=");
657
+ if (eqIndex === -1) continue;
658
+ const key = trimmed.slice(0, eqIndex).trim();
659
+ let value = trimmed.slice(eqIndex + 1).trim();
660
+ if (value.length >= 2) {
661
+ const first = value[0];
662
+ const last = value[value.length - 1];
663
+ if (first === '"' && last === '"' || first === "'" && last === "'") {
664
+ value = value.slice(1, -1);
665
+ }
666
+ }
667
+ result[key] = value;
668
+ }
669
+ return result;
670
+ }
671
+ function loadEnvFiles(paths) {
672
+ for (const p of paths) {
673
+ const absPath = (0, import_node_path.resolve)(process.cwd(), p);
674
+ if (!(0, import_node_fs.existsSync)(absPath)) {
675
+ throw new Error(`Env file not found: ${p}`);
676
+ }
677
+ const content = (0, import_node_fs.readFileSync)(absPath, "utf8");
678
+ const parsed = parseEnvFile(content);
679
+ for (const [key, value] of Object.entries(parsed)) {
680
+ if (process.env[key] === void 0) {
681
+ process.env[key] = value;
682
+ }
683
+ }
684
+ }
685
+ }
686
+ async function preloadModules(modules) {
687
+ for (const mod of modules) {
688
+ moduleRequire(mod);
689
+ }
690
+ }
691
+ function buildChildArgs(args) {
692
+ const result = ["dev", args.appPath];
693
+ if (args.options.port !== void 0) result.push("--port", String(args.options.port));
694
+ if (args.options.host !== void 0) result.push("--host", args.options.host);
695
+ if (args.options.signals === false) result.push("--no-signals");
696
+ if (args.options.shutdownTimeout !== void 0)
697
+ result.push("--shutdown-timeout", String(args.options.shutdownTimeout));
698
+ for (const r of args.require) result.push("--require", r);
699
+ for (const e of args.env) result.push("--env", e);
700
+ return result;
701
+ }
702
+ function runWithWatch(args) {
703
+ const cliPath = process.argv[1];
704
+ const childArgv = buildChildArgs(args);
705
+ let child = null;
706
+ let restartTimer = null;
707
+ let isShuttingDown = false;
708
+ const restartDelay = args.watchDelay;
709
+ const spawnChild = () => {
710
+ child = (0, import_node_child_process.fork)(cliPath, childArgv, { stdio: "inherit" });
711
+ child.on("exit", (code) => {
712
+ child = null;
713
+ if (!isShuttingDown && code !== null && code !== 0) {
714
+ }
715
+ });
716
+ };
717
+ const killChild = () => {
718
+ return new Promise((resolve) => {
719
+ if (!child || !child.pid) {
720
+ resolve();
721
+ return;
722
+ }
723
+ child.once("exit", () => resolve());
724
+ child.kill("SIGTERM");
725
+ });
726
+ };
727
+ const restart = async () => {
728
+ await killChild();
729
+ spawnChild();
730
+ };
731
+ const debouncedRestart = () => {
732
+ if (restartTimer) clearTimeout(restartTimer);
733
+ restartTimer = setTimeout(() => {
734
+ restartTimer = null;
735
+ void restart();
736
+ }, restartDelay);
737
+ };
738
+ for (const watchPath of args.watch) {
739
+ const absPath = (0, import_node_path.resolve)(process.cwd(), watchPath);
740
+ if (!(0, import_node_fs.existsSync)(absPath)) {
741
+ throw new Error(`Watch path not found: ${watchPath}`);
742
+ }
743
+ (0, import_node_fs.watch)(absPath, { recursive: true }, (_eventType, filename) => {
744
+ if (!filename) return;
745
+ const ext = (0, import_node_path.extname)(filename).slice(1).toLowerCase();
746
+ if (args.watchExt.includes(ext)) {
747
+ debouncedRestart();
748
+ }
749
+ });
750
+ }
751
+ const shutdown = () => {
752
+ isShuttingDown = true;
753
+ if (restartTimer) clearTimeout(restartTimer);
754
+ if (child && child.pid) {
755
+ child.once("exit", () => process.exit(0));
756
+ child.kill("SIGTERM");
757
+ } else {
758
+ process.exit(0);
759
+ }
760
+ };
761
+ process.on("SIGINT", shutdown);
762
+ process.on("SIGTERM", shutdown);
763
+ spawnChild();
764
+ }
765
+ function generateServerlessEntry(appPath, initPath) {
766
+ const absAppPath = (0, import_node_path.resolve)(process.cwd(), appPath);
767
+ const absInitPath = initPath ? (0, import_node_path.resolve)(process.cwd(), initPath) : void 0;
768
+ const lines = [
769
+ "// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
770
+ `import { createServerlessHandler } from '@web-ts-toolkit/express-runtime';`,
771
+ `import app from ${JSON.stringify(absAppPath)};`
772
+ ];
773
+ if (absInitPath) {
774
+ lines.push(`import init from ${JSON.stringify(absInitPath)};`);
775
+ lines.push(`const handler = createServerlessHandler(app, { init });`);
776
+ } else {
777
+ lines.push(`const handler = createServerlessHandler(app);`);
778
+ }
779
+ lines.push(`export { handler };`);
780
+ return lines.join("\n") + "\n";
781
+ }
782
+ function generateRuntimeEntry(appPath, initPath) {
783
+ const absAppPath = (0, import_node_path.resolve)(process.cwd(), appPath);
784
+ const absInitPath = initPath ? (0, import_node_path.resolve)(process.cwd(), initPath) : void 0;
785
+ const lines = [
786
+ "// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
787
+ `import app from ${JSON.stringify(absAppPath)};`,
788
+ "export default app;",
789
+ "export { app };"
790
+ ];
791
+ if (absInitPath) {
792
+ lines.push(`export { default as init } from ${JSON.stringify(absInitPath)};`);
793
+ }
794
+ return lines.join("\n") + "\n";
795
+ }
796
+ async function buildBundleFromEntryContent(args) {
797
+ const tsupModule = await import("tsup");
798
+ const { build } = tsupModule;
799
+ const tempEntryPath = (0, import_node_path.resolve)(process.cwd(), args.tempEntryFilename);
800
+ (0, import_node_fs.writeFileSync)(tempEntryPath, args.entryContent, "utf8");
801
+ try {
802
+ await build({
803
+ config: false,
804
+ entry: { [args.outName]: tempEntryPath },
805
+ format: [args.format],
806
+ target: args.target,
807
+ outDir: args.outDir,
808
+ clean: args.clean,
809
+ external: ["express", ...args.external],
810
+ sourcemap: false,
811
+ dts: false,
812
+ splitting: false
813
+ });
814
+ } finally {
815
+ (0, import_node_fs.rmSync)(tempEntryPath, { force: true });
816
+ }
817
+ }
818
+ async function buildRuntime(args) {
819
+ const { runBuildEntryCommand: runBuildEntryCommand2 } = await Promise.resolve().then(() => (init_cli_api(), cli_api_exports));
820
+ await runBuildEntryCommand2(args, {
821
+ generateEntry: generateRuntimeEntry,
822
+ tempEntryFilename: TEMP_BUILD_ENTRY_FILENAME
823
+ });
824
+ }
825
+ async function buildServerless(args) {
826
+ const { runBuildEntryCommand: runBuildEntryCommand2 } = await Promise.resolve().then(() => (init_cli_api(), cli_api_exports));
827
+ await runBuildEntryCommand2(args, {
828
+ generateEntry: generateServerlessEntry,
829
+ tempEntryFilename: TEMP_SERVERLESS_ENTRY_FILENAME
830
+ });
831
+ }
832
+ function collectBody(req) {
833
+ return new Promise((resolve, reject) => {
834
+ const chunks = [];
835
+ req.on("data", (chunk) => chunks.push(chunk));
836
+ req.on("end", () => resolve(Buffer.concat(chunks)));
837
+ req.on("error", reject);
838
+ });
839
+ }
840
+ function toServerlessEvent(method, url, headers, body) {
841
+ return {
842
+ httpMethod: method,
843
+ path: url,
844
+ headers,
845
+ body: body.length > 0 ? body : void 0
846
+ };
847
+ }
848
+ function applyServerlessResult(result, res) {
849
+ if (result === null || result === void 0) {
850
+ res.status(200).end();
851
+ return;
852
+ }
853
+ const r = result;
854
+ if (typeof r.statusCode === "number") {
855
+ res.status(r.statusCode);
856
+ }
857
+ if (r.headers && typeof r.headers === "object") {
858
+ for (const [key, value] of Object.entries(r.headers)) {
859
+ if (value !== void 0) {
860
+ res.setHeader(key, Array.isArray(value) ? value.join(",") : value);
861
+ }
862
+ }
863
+ }
864
+ if (r.isBase64Encoded && typeof r.body === "string") {
865
+ res.end(Buffer.from(r.body, "base64"));
866
+ } else if (typeof r.body === "string") {
867
+ res.end(r.body);
868
+ } else {
869
+ res.end();
870
+ }
871
+ }
872
+ function createServerlessAdapterApp(handler) {
873
+ return createExpressApp({
874
+ json: false,
875
+ urlencoded: false,
876
+ finalize: (app) => {
877
+ app.use(async (req, res) => {
878
+ const body = await collectBody(req);
879
+ const event = toServerlessEvent(req.method, req.url, req.headers, body);
880
+ const result = await handler(event, {});
881
+ applyServerlessResult(result, res);
882
+ });
883
+ },
884
+ errorHandler: (error, _req, res, _next) => {
885
+ console.error("Serverless adapter error:", error);
886
+ res.status(500).end("Internal server error");
887
+ }
888
+ });
889
+ }
890
+ async function loadBuiltApp(appPath) {
891
+ const fullPath = (0, import_node_path.resolve)(process.cwd(), appPath);
892
+ const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
893
+ const mod = await import(moduleUrl);
894
+ const exported = extractExport(mod);
895
+ if (!exported) {
896
+ throw new Error(
897
+ `Module "${appPath}" must default-export an Express app or export it as "app". Exports: ${Object.keys(mod).join(", ")}`
898
+ );
899
+ }
900
+ const init = mod.init;
901
+ if (init !== void 0 && typeof init !== "function") {
902
+ throw new Error(`Module "${appPath}" must export "init" as a function when present.`);
903
+ }
904
+ return {
905
+ app: await resolveExport(exported, appPath),
906
+ init
907
+ };
908
+ }
909
+ async function loadHandler(handlerPath) {
910
+ const fullPath = (0, import_node_path.resolve)(process.cwd(), handlerPath);
911
+ const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
912
+ const mod = await import(moduleUrl);
913
+ const exported = mod.handler ?? mod.default;
914
+ if (typeof exported !== "function") {
915
+ throw new Error(
916
+ `Module "${handlerPath}" must export a "handler" function. Exports: ${Object.keys(mod).join(", ")}`
917
+ );
918
+ }
919
+ return exported;
920
+ }
921
+ var import_node_url, import_node_path, import_node_fs, import_node_module, import_node_child_process, import_meta, CLI_VERSION, DEFAULT_WATCH_EXTENSIONS, DEFAULT_WATCH_DELAY, moduleRequire, TEMP_BUILD_ENTRY_FILENAME, TEMP_SERVERLESS_ENTRY_FILENAME;
922
+ var init_cli_utils = __esm({
923
+ "src/cli-utils.ts"() {
924
+ "use strict";
925
+ import_node_url = require("url");
926
+ import_node_path = require("path");
927
+ import_node_fs = require("fs");
928
+ import_node_module = require("module");
929
+ import_node_child_process = require("child_process");
930
+ init_index();
931
+ import_meta = {};
932
+ CLI_VERSION = "0.0.0-PLACEHOLDER";
933
+ DEFAULT_WATCH_EXTENSIONS = ["ts", "js", "mjs", "cjs", "json"];
934
+ DEFAULT_WATCH_DELAY = 500;
935
+ moduleRequire = (0, import_node_module.createRequire)(
936
+ typeof import_meta !== "undefined" && import_meta.url || (0, import_node_path.resolve)(process.cwd(), "x").replace(/x$/, "")
937
+ );
938
+ TEMP_BUILD_ENTRY_FILENAME = ".express-runtime-build-entry.ts";
939
+ TEMP_SERVERLESS_ENTRY_FILENAME = ".express-runtime-build-serverless-entry.ts";
940
+ }
941
+ });
942
+
943
+ // src/cli-api.ts
944
+ var cli_api_exports = {};
945
+ __export(cli_api_exports, {
946
+ CLI_VERSION: () => CLI_VERSION,
947
+ applyServerlessResult: () => applyServerlessResult,
948
+ buildBundleFromEntryContent: () => buildBundleFromEntryContent,
949
+ buildChildArgs: () => buildChildArgs,
950
+ buildRuntime: () => buildRuntime,
951
+ buildServerless: () => buildServerless,
952
+ createServerlessAdapterApp: () => createServerlessAdapterApp,
953
+ extractExport: () => extractExport,
954
+ generateRuntimeEntry: () => generateRuntimeEntry,
955
+ generateServerlessEntry: () => generateServerlessEntry,
956
+ isExpressApp: () => isExpressApp,
957
+ loadApp: () => loadApp,
958
+ loadBuiltApp: () => loadBuiltApp,
959
+ loadEnvFiles: () => loadEnvFiles,
960
+ loadHandler: () => loadHandler,
961
+ parseArgs: () => parseArgs,
962
+ parseEnvFile: () => parseEnvFile,
963
+ preloadModules: () => preloadModules,
964
+ printHelp: () => printHelp,
965
+ readValue: () => readValue,
966
+ resolveExport: () => resolveExport,
967
+ runBuildEntryCommand: () => runBuildEntryCommand,
968
+ runCliCommand: () => runCliCommand,
969
+ runDevCommand: () => runDevCommand,
970
+ runExpressDevCommand: () => runExpressDevCommand,
971
+ runWithWatch: () => runWithWatch,
972
+ toServerlessEvent: () => toServerlessEvent
973
+ });
974
+ module.exports = __toCommonJS(cli_api_exports);
975
+ async function runDevCommand(args, runner) {
976
+ if (args.watch.length > 0) {
977
+ (runner.watch ?? runWithWatch)(args);
978
+ return;
979
+ }
980
+ if (args.env.length > 0) {
981
+ loadEnvFiles(args.env);
982
+ }
983
+ await preloadModules(args.require);
984
+ const loaded = await runner.load(args.appPath);
985
+ runner.start(loaded, { ...args.options, exitAfterShutdown: true });
986
+ }
987
+ async function runExpressDevCommand(args) {
988
+ await runDevCommand(args, {
989
+ load: loadApp,
990
+ start: (app, options) => {
991
+ startLocalServer(app, options);
992
+ }
993
+ });
994
+ }
995
+ async function runBuildEntryCommand(args, options) {
996
+ if (options.allowInit === false && args.initPath) {
997
+ throw new Error(options.initErrorMessage ?? "This build command manages init automatically. Remove --init.");
998
+ }
999
+ await buildBundleFromEntryContent({
1000
+ entryContent: options.generateEntry(args.appPath, args.initPath),
1001
+ tempEntryFilename: options.tempEntryFilename,
1002
+ outDir: args.outDir,
1003
+ outName: args.outName,
1004
+ format: args.format,
1005
+ target: args.target,
1006
+ external: args.external,
1007
+ clean: args.clean
1008
+ });
1009
+ }
1010
+ async function runCliCommand(parsedArgs) {
1011
+ if (parsedArgs.subcommand === "dev") {
1012
+ await runExpressDevCommand(parsedArgs.dev);
1013
+ return;
1014
+ }
1015
+ if (parsedArgs.subcommand === "start") {
1016
+ const { start } = parsedArgs;
1017
+ if (start.env.length > 0) {
1018
+ loadEnvFiles(start.env);
1019
+ }
1020
+ await preloadModules(start.require);
1021
+ const { app, init } = await loadBuiltApp(start.appPath);
1022
+ startLocalServer(app, {
1023
+ ...start.options,
1024
+ init: init ? async () => {
1025
+ await init();
1026
+ } : void 0,
1027
+ exitAfterShutdown: true
1028
+ });
1029
+ return;
1030
+ }
1031
+ if (parsedArgs.subcommand === "build") {
1032
+ await buildRuntime(parsedArgs.build);
1033
+ return;
1034
+ }
1035
+ if (parsedArgs.subcommand === "start-serverless") {
1036
+ const { startServerless } = parsedArgs;
1037
+ if (startServerless.env.length > 0) {
1038
+ loadEnvFiles(startServerless.env);
1039
+ }
1040
+ await preloadModules(startServerless.require);
1041
+ const handler = await loadHandler(startServerless.handlerPath);
1042
+ const app = createServerlessAdapterApp(handler);
1043
+ startLocalServer(app, { ...startServerless.options, exitAfterShutdown: true });
1044
+ return;
1045
+ }
1046
+ await buildServerless(parsedArgs.buildServerless);
1047
+ }
1048
+ var init_cli_api = __esm({
1049
+ "src/cli-api.ts"() {
1050
+ init_index();
1051
+ init_cli_utils();
1052
+ }
1053
+ });
1054
+ init_cli_api();
1055
+ // Annotate the CommonJS export names for ESM import in node:
1056
+ 0 && (module.exports = {
1057
+ CLI_VERSION,
1058
+ applyServerlessResult,
1059
+ buildBundleFromEntryContent,
1060
+ buildChildArgs,
1061
+ buildRuntime,
1062
+ buildServerless,
1063
+ createServerlessAdapterApp,
1064
+ extractExport,
1065
+ generateRuntimeEntry,
1066
+ generateServerlessEntry,
1067
+ isExpressApp,
1068
+ loadApp,
1069
+ loadBuiltApp,
1070
+ loadEnvFiles,
1071
+ loadHandler,
1072
+ parseArgs,
1073
+ parseEnvFile,
1074
+ preloadModules,
1075
+ printHelp,
1076
+ readValue,
1077
+ resolveExport,
1078
+ runBuildEntryCommand,
1079
+ runCliCommand,
1080
+ runDevCommand,
1081
+ runExpressDevCommand,
1082
+ runWithWatch,
1083
+ toServerlessEvent
1084
+ });