@web-ts-toolkit/express-runtime 0.40.1 → 0.41.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.mjs CHANGED
@@ -1,768 +1,37 @@
1
1
  import {
2
- createExpressApp,
2
+ CLI_VERSION,
3
+ DEFAULT_ADAPTER_MAX_BODY_BYTES,
4
+ TEMP_BUILD_ENTRY_FILENAME,
5
+ TEMP_SERVERLESS_ENTRY_FILENAME,
6
+ applyServerlessResult,
7
+ buildBundleFromEntryContent,
8
+ buildChildArgs,
9
+ buildRuntime,
10
+ buildServerless,
11
+ collectBody,
12
+ createServerlessAdapterApp,
13
+ extractExport,
14
+ generateRuntimeEntry,
15
+ generateServerlessEntry,
16
+ isExpressApp,
17
+ loadApp,
18
+ loadBuiltApp,
19
+ loadEnvFiles,
20
+ loadHandler,
21
+ parseArgs,
22
+ parseEnvFile,
23
+ preloadModules,
24
+ printHelp,
25
+ readValue,
26
+ resolveExport,
27
+ runWithWatch,
28
+ toServerlessEvent,
29
+ validateMaxBodyBytes,
30
+ validateOutDirForClean
31
+ } from "./chunk-UPFG3S34.mjs";
32
+ import {
3
33
  startLocalServer
4
- } from "./chunk-SOW7OLVN.mjs";
5
-
6
- // src/cli-utils.ts
7
- import { pathToFileURL } from "url";
8
- import { resolve as pathResolve, extname } from "path";
9
- import { writeFileSync, rmSync, readFileSync, existsSync, watch } from "fs";
10
- import { createRequire } from "module";
11
- import { fork } from "child_process";
12
- var CLI_VERSION = "0.0.0-PLACEHOLDER";
13
- function readValue(argv, index, name) {
14
- const value = argv[index + 1];
15
- if (value === void 0 || value.startsWith("--")) {
16
- throw new Error(`Missing value for argument: ${name}`);
17
- }
18
- return value;
19
- }
20
- function printHelp() {
21
- console.log(`wtt-express-runtime
22
-
23
- Run an Express app locally, bundle it for local or serverless runtimes, or run the bundle.
24
-
25
- Usage:
26
- wtt-express-runtime <command> <app-module> [options]
27
- wtt-express-runtime <app-module> [options] (alias for dev)
28
-
29
- Commands:
30
- dev Run the Express app as a local dev server
31
- build Bundle the Express app as a local app module
32
- start Run a bundled local app module
33
- build-serverless Bundle the Express app as a serverless handler
34
- start-serverless Run a bundled serverless handler locally
35
-
36
- Dev options:
37
- --port <number> Port or named pipe (default: process.env.PORT or 8080)
38
- --host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
39
- --no-signals Disable SIGINT/SIGTERM handler registration
40
- --shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
41
- --require <module> Module(s) to preload before app load (repeatable)
42
- --env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
43
- --tsconfig <path> Tsconfig used by config-aware consumers for TS path resolution
44
- --watch <paths> Comma-separated paths to watch for restart (repeatable; dev only)
45
- --ext <extensions> Comma-separated extensions to watch (default: ts,js,mjs,cjs,json)
46
- --delay <ms> Debounce ms before restarting on change (default: 500)
47
-
48
- Build options:
49
- --init <path> Init hook module (default export, async function)
50
- --tsconfig <path> Use a custom tsconfig for bundling
51
- --out-dir <path> Output directory (default: dist)
52
- --out-name <name> Output filename without extension (default: app)
53
- --format <cjs|esm> Output format (default: cjs)
54
- --target <target> Compilation target (default: node22)
55
- --external <pkg> Mark package as external (repeatable; express always external)
56
- --no-clean Don't clean the output directory before building
57
-
58
- Start options:
59
- --port <number> Port or named pipe (default: process.env.PORT or 8080)
60
- --host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
61
- --no-signals Disable SIGINT/SIGTERM handler registration
62
- --shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
63
- --require <module> Module(s) to preload before app load (repeatable)
64
- --env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
65
-
66
- Build-serverless options:
67
- --init <path> Init hook module (default export, async function)
68
- --tsconfig <path> Use a custom tsconfig for bundling
69
- --out-dir <path> Output directory (default: dist)
70
- --out-name <name> Output filename without extension (default: handler)
71
- --format <cjs|esm> Output format (default: cjs)
72
- --target <target> Compilation target (default: node22)
73
- --external <pkg> Mark package as external (repeatable; express always external)
74
- --no-clean Don't clean the output directory before building
75
-
76
- Start-serverless options:
77
- --port <number> Port or named pipe (default: process.env.PORT or 8080)
78
- --host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
79
- --no-signals Disable SIGINT/SIGTERM handler registration
80
- --shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
81
- --require <module> Module(s) to preload before handler load (repeatable)
82
- --env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
83
-
84
- Global options:
85
- -V, --version Show version
86
- -h, --help Show this help message
87
-
88
- Examples:
89
- wtt-express-runtime dev ./dist/app.js
90
- wtt-express-runtime dev ./dist/app.js --port 3000 --host localhost
91
- wtt-express-runtime dev ./src/app.ts --env .env --require tsconfig-paths/register --watch ./src,./shared
92
- wtt-express-runtime build ./src/app.ts --out-dir dist
93
- wtt-express-runtime start ./dist/app.js --port 3000 --env .env
94
- wtt-express-runtime build-serverless ./src/app.ts --out-dir netlify/functions
95
- wtt-express-runtime build-serverless ./src/app.ts --init ./src/init.ts --format esm
96
- wtt-express-runtime start-serverless ./netlify/functions/handler.js --port 9000 --env .env
97
- wtt-express-runtime build-serverless ./src/app.ts && wtt-express-runtime start-serverless ./dist/handler.js
98
-
99
- Notes:
100
- - In dev mode, the CLI evaluates arbitrary code from <app-module> in the current process.
101
- - TypeScript app modules in dev mode require a TS loader. Run via tsx:
102
- npx tsx ./node_modules/@web-ts-toolkit/express-runtime/dist/cli.js dev ./src/app.ts
103
- Or use --require with a TS-aware loader module.
104
- - --env files are parsed as KEY=VALUE; existing process.env entries are never overridden.
105
- For advanced dotenv features (multiline, expansion), --require dotenv/config instead.
106
- - --watch forks a child process running the same CLI without --watch. On file change,
107
- the child is killed (SIGTERM) and respawned after the debounce delay.
108
- - In build/build-serverless mode, express is always external. Add more externals with --external.
109
- - In start mode, the bundled app file must default-export an Express app (or export it as "app").
110
- If the bundle exports "init", it runs before the server starts listening.
111
- - In start-serverless mode, the bundled handler file must be a JS/CJS module whose
112
- "handler" export (or default export) is a function: (event, context) => Promise<result>.
113
- - Init logic for dev mode (DB connections, etc.): add at the top level of your app module.
114
- `);
115
- }
116
- function isVersion(arg) {
117
- return arg === "-V" || arg === "--version";
118
- }
119
- function isHelp(arg) {
120
- return arg === "-h" || arg === "--help";
121
- }
122
- function isSubcommand(arg) {
123
- return arg === "dev" || arg === "build" || arg === "start" || arg === "build-serverless" || arg === "start-serverless";
124
- }
125
- var DEFAULT_WATCH_EXTENSIONS = ["ts", "js", "mjs", "cjs", "json"];
126
- var DEFAULT_WATCH_DELAY = 500;
127
- function parseRepeatable(argv, index, arg, list) {
128
- const value = readValue(argv, index, arg);
129
- for (const part of value.split(",")) {
130
- const trimmed = part.trim();
131
- if (trimmed) list.push(trimmed);
132
- }
133
- return index + 1;
134
- }
135
- function parseDevArgs(argv) {
136
- const options = {};
137
- const requireModules = [];
138
- const envFiles = [];
139
- const watchPaths = [];
140
- let watchExt;
141
- let watchDelay;
142
- let tsconfigPath;
143
- let appPath;
144
- for (let index = 0; index < argv.length; index += 1) {
145
- const arg = argv[index];
146
- if (arg === "--") {
147
- continue;
148
- }
149
- if (isHelp(arg) || isVersion(arg)) {
150
- continue;
151
- }
152
- if (arg === "--port") {
153
- const port = readValue(argv, index, arg);
154
- const portNum = Number(port);
155
- options.port = Number.isNaN(portNum) ? port : portNum;
156
- index += 1;
157
- continue;
158
- }
159
- if (arg.startsWith("--port=")) {
160
- const port = arg.slice("--port=".length);
161
- const portNum = Number(port);
162
- options.port = Number.isNaN(portNum) ? port : portNum;
163
- continue;
164
- }
165
- if (arg === "--host") {
166
- options.host = readValue(argv, index, arg);
167
- index += 1;
168
- continue;
169
- }
170
- if (arg.startsWith("--host=")) {
171
- options.host = arg.slice("--host=".length);
172
- continue;
173
- }
174
- if (arg === "--no-signals") {
175
- options.signals = false;
176
- continue;
177
- }
178
- if (arg === "--shutdown-timeout") {
179
- options.shutdownTimeout = Number(readValue(argv, index, arg));
180
- index += 1;
181
- continue;
182
- }
183
- if (arg.startsWith("--shutdown-timeout=")) {
184
- options.shutdownTimeout = Number(arg.slice("--shutdown-timeout=".length));
185
- continue;
186
- }
187
- if (arg === "--require") {
188
- index = parseRepeatable(argv, index, arg, requireModules);
189
- continue;
190
- }
191
- if (arg.startsWith("--require=")) {
192
- for (const part of arg.slice("--require=".length).split(",")) {
193
- const trimmed = part.trim();
194
- if (trimmed) requireModules.push(trimmed);
195
- }
196
- continue;
197
- }
198
- if (arg === "--env") {
199
- index = parseRepeatable(argv, index, arg, envFiles);
200
- continue;
201
- }
202
- if (arg.startsWith("--env=")) {
203
- for (const part of arg.slice("--env=".length).split(",")) {
204
- const trimmed = part.trim();
205
- if (trimmed) envFiles.push(trimmed);
206
- }
207
- continue;
208
- }
209
- if (arg === "--tsconfig") {
210
- tsconfigPath = readValue(argv, index, arg);
211
- index += 1;
212
- continue;
213
- }
214
- if (arg.startsWith("--tsconfig=")) {
215
- tsconfigPath = arg.slice("--tsconfig=".length);
216
- continue;
217
- }
218
- if (arg === "--watch") {
219
- index = parseRepeatable(argv, index, arg, watchPaths);
220
- continue;
221
- }
222
- if (arg.startsWith("--watch=")) {
223
- for (const part of arg.slice("--watch=".length).split(",")) {
224
- const trimmed = part.trim();
225
- if (trimmed) watchPaths.push(trimmed);
226
- }
227
- continue;
228
- }
229
- if (arg === "--ext") {
230
- watchExt = [];
231
- index = parseRepeatable(argv, index, arg, watchExt);
232
- continue;
233
- }
234
- if (arg.startsWith("--ext=")) {
235
- watchExt = [];
236
- for (const part of arg.slice("--ext=".length).split(",")) {
237
- const trimmed = part.trim();
238
- if (trimmed) watchExt.push(trimmed);
239
- }
240
- continue;
241
- }
242
- if (arg === "--delay") {
243
- watchDelay = Number(readValue(argv, index, arg));
244
- index += 1;
245
- continue;
246
- }
247
- if (arg.startsWith("--delay=")) {
248
- watchDelay = Number(arg.slice("--delay=".length));
249
- continue;
250
- }
251
- if (!arg.startsWith("--")) {
252
- if (appPath) {
253
- throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
254
- }
255
- appPath = arg;
256
- continue;
257
- }
258
- throw new Error(`Unknown argument: ${arg}`);
259
- }
260
- if (!appPath) {
261
- printHelp();
262
- throw new Error("Missing required argument: <app-module>");
263
- }
264
- return {
265
- appPath,
266
- options,
267
- tsconfigPath,
268
- require: requireModules,
269
- env: envFiles,
270
- watch: watchPaths,
271
- watchExt: watchExt ?? DEFAULT_WATCH_EXTENSIONS,
272
- watchDelay: watchDelay ?? DEFAULT_WATCH_DELAY
273
- };
274
- }
275
- function parseStartLikeArgs(argv, subcommandName) {
276
- for (const arg of argv) {
277
- if (arg === "--watch" || arg.startsWith("--watch=") || arg === "--tsconfig" || arg.startsWith("--tsconfig=") || arg === "--ext" || arg.startsWith("--ext=") || arg === "--delay" || arg.startsWith("--delay=")) {
278
- throw new Error(`--watch/--tsconfig/--ext/--delay are not supported with the ${subcommandName} subcommand`);
279
- }
280
- }
281
- return parseDevArgs(argv);
282
- }
283
- function parseStartArgs(argv) {
284
- const result = parseStartLikeArgs(argv, "start");
285
- return {
286
- appPath: result.appPath,
287
- options: result.options,
288
- require: result.require,
289
- env: result.env
290
- };
291
- }
292
- function parseStartServerlessArgs(argv) {
293
- const result = parseStartLikeArgs(argv, "start-serverless");
294
- return {
295
- handlerPath: result.appPath,
296
- options: result.options,
297
- require: result.require,
298
- env: result.env
299
- };
300
- }
301
- function parseBuildArgs(argv, outNameDefault) {
302
- let appPath;
303
- const external = [];
304
- const result = {
305
- initPath: void 0,
306
- tsconfigPath: void 0,
307
- outDir: "dist",
308
- outName: outNameDefault,
309
- format: "cjs",
310
- target: "node22",
311
- external,
312
- clean: true
313
- };
314
- for (let index = 0; index < argv.length; index += 1) {
315
- const arg = argv[index];
316
- if (arg === "--") {
317
- continue;
318
- }
319
- if (isHelp(arg) || isVersion(arg)) {
320
- continue;
321
- }
322
- if (arg === "--init") {
323
- result.initPath = readValue(argv, index, arg);
324
- index += 1;
325
- continue;
326
- }
327
- if (arg.startsWith("--init=")) {
328
- result.initPath = arg.slice("--init=".length);
329
- continue;
330
- }
331
- if (arg === "--tsconfig") {
332
- result.tsconfigPath = readValue(argv, index, arg);
333
- index += 1;
334
- continue;
335
- }
336
- if (arg.startsWith("--tsconfig=")) {
337
- result.tsconfigPath = arg.slice("--tsconfig=".length);
338
- continue;
339
- }
340
- if (arg === "--out-dir") {
341
- result.outDir = readValue(argv, index, arg);
342
- index += 1;
343
- continue;
344
- }
345
- if (arg.startsWith("--out-dir=")) {
346
- result.outDir = arg.slice("--out-dir=".length);
347
- continue;
348
- }
349
- if (arg === "--out-name") {
350
- result.outName = readValue(argv, index, arg);
351
- index += 1;
352
- continue;
353
- }
354
- if (arg.startsWith("--out-name=")) {
355
- result.outName = arg.slice("--out-name=".length);
356
- continue;
357
- }
358
- if (arg === "--format") {
359
- const fmt = readValue(argv, index, arg);
360
- if (fmt !== "cjs" && fmt !== "esm") {
361
- throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
362
- }
363
- result.format = fmt;
364
- index += 1;
365
- continue;
366
- }
367
- if (arg.startsWith("--format=")) {
368
- const fmt = arg.slice("--format=".length);
369
- if (fmt !== "cjs" && fmt !== "esm") {
370
- throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
371
- }
372
- result.format = fmt;
373
- continue;
374
- }
375
- if (arg === "--target") {
376
- result.target = readValue(argv, index, arg);
377
- index += 1;
378
- continue;
379
- }
380
- if (arg.startsWith("--target=")) {
381
- result.target = arg.slice("--target=".length);
382
- continue;
383
- }
384
- if (arg === "--external") {
385
- external.push(readValue(argv, index, arg));
386
- index += 1;
387
- continue;
388
- }
389
- if (arg.startsWith("--external=")) {
390
- external.push(arg.slice("--external=".length));
391
- continue;
392
- }
393
- if (arg === "--no-clean") {
394
- result.clean = false;
395
- continue;
396
- }
397
- if (!arg.startsWith("--")) {
398
- if (appPath) {
399
- throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
400
- }
401
- appPath = arg;
402
- continue;
403
- }
404
- throw new Error(`Unknown argument: ${arg}`);
405
- }
406
- if (!appPath) {
407
- printHelp();
408
- throw new Error("Missing required argument: <app-module>");
409
- }
410
- return { appPath, ...result };
411
- }
412
- function parseLocalBuildArgs(argv) {
413
- return parseBuildArgs(argv, "app");
414
- }
415
- function parseBuildServerlessArgs(argv) {
416
- return parseBuildArgs(argv, "handler");
417
- }
418
- function parseArgs(argv) {
419
- if (argv.length === 0) {
420
- printHelp();
421
- return null;
422
- }
423
- if (argv.some((a) => isHelp(a))) {
424
- printHelp();
425
- return null;
426
- }
427
- if (argv.some((a) => isVersion(a))) {
428
- console.log(CLI_VERSION);
429
- return null;
430
- }
431
- const first = argv[0];
432
- if (isSubcommand(first)) {
433
- const rest = argv.slice(1);
434
- if (first === "dev") {
435
- return { subcommand: "dev", dev: parseDevArgs(rest) };
436
- }
437
- if (first === "build") {
438
- return { subcommand: "build", build: parseLocalBuildArgs(rest) };
439
- }
440
- if (first === "start") {
441
- return { subcommand: "start", start: parseStartArgs(rest) };
442
- }
443
- if (first === "build-serverless") {
444
- return { subcommand: "build-serverless", buildServerless: parseBuildServerlessArgs(rest) };
445
- }
446
- return { subcommand: "start-serverless", startServerless: parseStartServerlessArgs(rest) };
447
- }
448
- return { subcommand: "dev", dev: parseDevArgs(argv) };
449
- }
450
- function isExpressApp(x) {
451
- if (x === null || x === void 0) return false;
452
- const t = typeof x;
453
- if (t !== "object" && t !== "function") return false;
454
- return typeof x.listen === "function" && typeof x.use === "function";
455
- }
456
- function extractExport(mod) {
457
- return mod.default ?? mod.app;
458
- }
459
- async function resolveExport(exported, appPath) {
460
- if (isExpressApp(exported)) {
461
- return exported;
462
- }
463
- if (typeof exported === "function") {
464
- const result = await exported();
465
- if (!isExpressApp(result)) {
466
- throw new Error(`Function in "${appPath}" did not return an Express app.`);
467
- }
468
- return result;
469
- }
470
- throw new Error(`Default export of "${appPath}" is not an Express app or an async function returning one.`);
471
- }
472
- async function loadApp(appPath) {
473
- const fullPath = pathResolve(process.cwd(), appPath);
474
- const moduleUrl = pathToFileURL(fullPath).href;
475
- const mod = await import(moduleUrl);
476
- const exported = extractExport(mod);
477
- if (!exported) {
478
- throw new Error(
479
- `Module "${appPath}" must default-export an Express app or an async function returning one. Exports: ${Object.keys(mod).join(", ")}`
480
- );
481
- }
482
- return resolveExport(exported, appPath);
483
- }
484
- function parseEnvFile(content) {
485
- const result = {};
486
- for (const line of content.split("\n")) {
487
- let trimmed = line.trim();
488
- if (!trimmed || trimmed.startsWith("#")) continue;
489
- if (trimmed.startsWith("export ")) trimmed = trimmed.slice("export ".length).trim();
490
- const eqIndex = trimmed.indexOf("=");
491
- if (eqIndex === -1) continue;
492
- const key = trimmed.slice(0, eqIndex).trim();
493
- let value = trimmed.slice(eqIndex + 1).trim();
494
- if (value.length >= 2) {
495
- const first = value[0];
496
- const last = value[value.length - 1];
497
- if (first === '"' && last === '"' || first === "'" && last === "'") {
498
- value = value.slice(1, -1);
499
- }
500
- }
501
- result[key] = value;
502
- }
503
- return result;
504
- }
505
- function loadEnvFiles(paths) {
506
- for (const p of paths) {
507
- const absPath = pathResolve(process.cwd(), p);
508
- if (!existsSync(absPath)) {
509
- throw new Error(`Env file not found: ${p}`);
510
- }
511
- const content = readFileSync(absPath, "utf8");
512
- const parsed = parseEnvFile(content);
513
- for (const [key, value] of Object.entries(parsed)) {
514
- if (process.env[key] === void 0) {
515
- process.env[key] = value;
516
- }
517
- }
518
- }
519
- }
520
- var moduleRequire = createRequire(
521
- pathToFileURL(pathResolve(process.cwd(), "__wtt_runtime_preload__.js"))
522
- );
523
- async function preloadModules(modules) {
524
- for (const mod of modules) {
525
- moduleRequire(mod);
526
- }
527
- }
528
- function buildChildArgs(args) {
529
- const result = ["dev", args.appPath];
530
- if (args.options.port !== void 0) result.push("--port", String(args.options.port));
531
- if (args.options.host !== void 0) result.push("--host", args.options.host);
532
- if (args.options.signals === false) result.push("--no-signals");
533
- if (args.options.shutdownTimeout !== void 0)
534
- result.push("--shutdown-timeout", String(args.options.shutdownTimeout));
535
- if (args.tsconfigPath !== void 0) result.push("--tsconfig", args.tsconfigPath);
536
- for (const r of args.require) result.push("--require", r);
537
- for (const e of args.env) result.push("--env", e);
538
- return result;
539
- }
540
- function runWithWatch(args) {
541
- const cliPath = process.argv[1];
542
- const childArgv = buildChildArgs(args);
543
- let child = null;
544
- let restartTimer = null;
545
- let isShuttingDown = false;
546
- const restartDelay = args.watchDelay;
547
- const spawnChild = () => {
548
- child = fork(cliPath, childArgv, { stdio: "inherit" });
549
- child.on("exit", (code) => {
550
- child = null;
551
- if (!isShuttingDown && code !== null && code !== 0) {
552
- }
553
- });
554
- };
555
- const killChild = () => {
556
- return new Promise((resolve) => {
557
- if (!child || !child.pid) {
558
- resolve();
559
- return;
560
- }
561
- child.once("exit", () => resolve());
562
- child.kill("SIGTERM");
563
- });
564
- };
565
- const restart = async () => {
566
- await killChild();
567
- spawnChild();
568
- };
569
- const debouncedRestart = () => {
570
- if (restartTimer) clearTimeout(restartTimer);
571
- restartTimer = setTimeout(() => {
572
- restartTimer = null;
573
- void restart();
574
- }, restartDelay);
575
- };
576
- for (const watchPath of args.watch) {
577
- const absPath = pathResolve(process.cwd(), watchPath);
578
- if (!existsSync(absPath)) {
579
- throw new Error(`Watch path not found: ${watchPath}`);
580
- }
581
- watch(absPath, { recursive: true }, (_eventType, filename) => {
582
- if (!filename) return;
583
- const ext = extname(filename).slice(1).toLowerCase();
584
- if (args.watchExt.includes(ext)) {
585
- debouncedRestart();
586
- }
587
- });
588
- }
589
- const shutdown = () => {
590
- isShuttingDown = true;
591
- if (restartTimer) clearTimeout(restartTimer);
592
- if (child && child.pid) {
593
- child.once("exit", () => process.exit(0));
594
- child.kill("SIGTERM");
595
- } else {
596
- process.exit(0);
597
- }
598
- };
599
- process.on("SIGINT", shutdown);
600
- process.on("SIGTERM", shutdown);
601
- spawnChild();
602
- }
603
- var TEMP_BUILD_ENTRY_FILENAME = ".express-runtime-build-entry.ts";
604
- var TEMP_SERVERLESS_ENTRY_FILENAME = ".express-runtime-build-serverless-entry.ts";
605
- function generateServerlessEntry(appPath, initPath) {
606
- const absAppPath = pathResolve(process.cwd(), appPath);
607
- const absInitPath = initPath ? pathResolve(process.cwd(), initPath) : void 0;
608
- const lines = [
609
- "// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
610
- `import { createServerlessHandler } from '@web-ts-toolkit/express-runtime';`,
611
- `import app from ${JSON.stringify(absAppPath)};`
612
- ];
613
- if (absInitPath) {
614
- lines.push(`import init from ${JSON.stringify(absInitPath)};`);
615
- lines.push(`const handler = createServerlessHandler(app, { init });`);
616
- } else {
617
- lines.push(`const handler = createServerlessHandler(app);`);
618
- }
619
- lines.push(`export { handler };`);
620
- return lines.join("\n") + "\n";
621
- }
622
- function generateRuntimeEntry(appPath, initPath) {
623
- const absAppPath = pathResolve(process.cwd(), appPath);
624
- const absInitPath = initPath ? pathResolve(process.cwd(), initPath) : void 0;
625
- const lines = [
626
- "// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
627
- `import app from ${JSON.stringify(absAppPath)};`,
628
- "export default app;",
629
- "export { app };"
630
- ];
631
- if (absInitPath) {
632
- lines.push(`export { default as init } from ${JSON.stringify(absInitPath)};`);
633
- }
634
- return lines.join("\n") + "\n";
635
- }
636
- async function buildBundleFromEntryContent(args) {
637
- const tsupModule = await import("tsup");
638
- const { build } = tsupModule;
639
- const tempEntryPath = pathResolve(process.cwd(), args.tempEntryFilename);
640
- writeFileSync(tempEntryPath, args.entryContent, "utf8");
641
- try {
642
- await build({
643
- config: false,
644
- entry: { [args.outName]: tempEntryPath },
645
- tsconfig: args.tsconfigPath,
646
- format: [args.format],
647
- target: args.target,
648
- outDir: args.outDir,
649
- clean: args.clean,
650
- external: ["express", ...args.external],
651
- sourcemap: false,
652
- dts: false,
653
- splitting: false
654
- });
655
- } finally {
656
- rmSync(tempEntryPath, { force: true });
657
- }
658
- }
659
- async function buildRuntime(args) {
660
- const { runBuildEntryCommand: runBuildEntryCommand2 } = await import("./cli-api.mjs");
661
- await runBuildEntryCommand2(args, {
662
- generateEntry: generateRuntimeEntry,
663
- tempEntryFilename: TEMP_BUILD_ENTRY_FILENAME
664
- });
665
- }
666
- async function buildServerless(args) {
667
- const { runBuildEntryCommand: runBuildEntryCommand2 } = await import("./cli-api.mjs");
668
- await runBuildEntryCommand2(args, {
669
- generateEntry: generateServerlessEntry,
670
- tempEntryFilename: TEMP_SERVERLESS_ENTRY_FILENAME
671
- });
672
- }
673
- function collectBody(req) {
674
- return new Promise((resolve, reject) => {
675
- const chunks = [];
676
- req.on("data", (chunk) => chunks.push(chunk));
677
- req.on("end", () => resolve(Buffer.concat(chunks)));
678
- req.on("error", reject);
679
- });
680
- }
681
- function toServerlessEvent(method, url, headers, body) {
682
- return {
683
- httpMethod: method,
684
- path: url,
685
- headers,
686
- body: body.length > 0 ? body : void 0
687
- };
688
- }
689
- function applyServerlessResult(result, res) {
690
- if (result === null || result === void 0) {
691
- res.status(200).end();
692
- return;
693
- }
694
- const r = result;
695
- if (typeof r.statusCode === "number") {
696
- res.status(r.statusCode);
697
- }
698
- if (r.headers && typeof r.headers === "object") {
699
- for (const [key, value] of Object.entries(r.headers)) {
700
- if (value !== void 0) {
701
- if (Array.isArray(value) && key.toLowerCase() === "set-cookie") {
702
- res.setHeader(key, value);
703
- } else {
704
- res.setHeader(key, Array.isArray(value) ? value.join(",") : value);
705
- }
706
- }
707
- }
708
- }
709
- if (r.isBase64Encoded && typeof r.body === "string") {
710
- res.end(Buffer.from(r.body, "base64"));
711
- } else if (typeof r.body === "string") {
712
- res.end(r.body);
713
- } else {
714
- res.end();
715
- }
716
- }
717
- function createServerlessAdapterApp(handler) {
718
- return createExpressApp({
719
- json: false,
720
- urlencoded: false,
721
- finalize: (app) => {
722
- app.use(async (req, res) => {
723
- const body = await collectBody(req);
724
- const event = toServerlessEvent(req.method, req.url, req.headers, body);
725
- const result = await handler(event, {});
726
- applyServerlessResult(result, res);
727
- });
728
- },
729
- errorHandler: (error, _req, res, _next) => {
730
- console.error("Serverless adapter error:", error);
731
- res.status(500).end("Internal server error");
732
- }
733
- });
734
- }
735
- async function loadBuiltApp(appPath) {
736
- const fullPath = pathResolve(process.cwd(), appPath);
737
- const moduleUrl = pathToFileURL(fullPath).href;
738
- const mod = await import(moduleUrl);
739
- const exported = extractExport(mod);
740
- if (!exported) {
741
- throw new Error(
742
- `Module "${appPath}" must default-export an Express app or export it as "app". Exports: ${Object.keys(mod).join(", ")}`
743
- );
744
- }
745
- const init = mod.init;
746
- if (init !== void 0 && typeof init !== "function") {
747
- throw new Error(`Module "${appPath}" must export "init" as a function when present.`);
748
- }
749
- return {
750
- app: await resolveExport(exported, appPath),
751
- init
752
- };
753
- }
754
- async function loadHandler(handlerPath) {
755
- const fullPath = pathResolve(process.cwd(), handlerPath);
756
- const moduleUrl = pathToFileURL(fullPath).href;
757
- const mod = await import(moduleUrl);
758
- const exported = mod.handler ?? mod.default;
759
- if (typeof exported !== "function") {
760
- throw new Error(
761
- `Module "${handlerPath}" must export a "handler" function. Exports: ${Object.keys(mod).join(", ")}`
762
- );
763
- }
764
- return exported;
765
- }
34
+ } from "./chunk-VPFBKM2K.mjs";
766
35
 
767
36
  // src/cli-api.ts
768
37
  async function runDevCommand(args, runner) {
@@ -775,7 +44,8 @@ async function runDevCommand(args, runner) {
775
44
  }
776
45
  await preloadModules(args.require);
777
46
  const loaded = await runner.load(args.appPath);
778
- runner.start(loaded, { ...args.options, exitAfterShutdown: true });
47
+ const server = runner.start(loaded, { ...args.options, exitAfterShutdown: true });
48
+ await server?.ready;
779
49
  }
780
50
  async function runExpressDevCommand(args) {
781
51
  await runDevCommand(args, {
@@ -789,9 +59,10 @@ async function runBuildEntryCommand(args, options) {
789
59
  if (options.allowInit === false && args.initPath) {
790
60
  throw new Error(options.initErrorMessage ?? "This build command manages init automatically. Remove --init.");
791
61
  }
62
+ const { validateOutDirForClean: validateOutDirForClean2 } = await import("./cli-utils-4POUMJN7.mjs");
63
+ validateOutDirForClean2(args.outDir, args.clean, args.appPath, args.initPath);
792
64
  await buildBundleFromEntryContent({
793
65
  entryContent: options.generateEntry(args.appPath, args.initPath),
794
- tempEntryFilename: options.tempEntryFilename,
795
66
  tsconfigPath: args.tsconfigPath,
796
67
  outDir: args.outDir,
797
68
  outName: args.outName,
@@ -812,14 +83,17 @@ async function runCliCommand(parsedArgs) {
812
83
  loadEnvFiles(start.env);
813
84
  }
814
85
  await preloadModules(start.require);
815
- const { app, init } = await loadBuiltApp(start.appPath);
816
- startLocalServer(app, {
86
+ const { app, init, shutdown } = await loadBuiltApp(start.appPath);
87
+ await startLocalServer(app, {
817
88
  ...start.options,
818
89
  init: init ? async () => {
819
90
  await init();
820
91
  } : void 0,
92
+ onShutdown: shutdown ? async () => {
93
+ await shutdown();
94
+ } : void 0,
821
95
  exitAfterShutdown: true
822
- });
96
+ }).ready;
823
97
  return;
824
98
  }
825
99
  if (parsedArgs.subcommand === "build") {
@@ -833,19 +107,23 @@ async function runCliCommand(parsedArgs) {
833
107
  }
834
108
  await preloadModules(startServerless.require);
835
109
  const handler = await loadHandler(startServerless.handlerPath);
836
- const app = createServerlessAdapterApp(handler);
837
- startLocalServer(app, { ...startServerless.options, exitAfterShutdown: true });
110
+ const app = createServerlessAdapterApp(handler, { maxBodyBytes: startServerless.maxBodyBytes });
111
+ await startLocalServer(app, { ...startServerless.options, exitAfterShutdown: true }).ready;
838
112
  return;
839
113
  }
840
114
  await buildServerless(parsedArgs.buildServerless);
841
115
  }
842
116
  export {
843
117
  CLI_VERSION,
118
+ DEFAULT_ADAPTER_MAX_BODY_BYTES,
119
+ TEMP_BUILD_ENTRY_FILENAME,
120
+ TEMP_SERVERLESS_ENTRY_FILENAME,
844
121
  applyServerlessResult,
845
122
  buildBundleFromEntryContent,
846
123
  buildChildArgs,
847
124
  buildRuntime,
848
125
  buildServerless,
126
+ collectBody,
849
127
  createServerlessAdapterApp,
850
128
  extractExport,
851
129
  generateRuntimeEntry,
@@ -866,5 +144,7 @@ export {
866
144
  runDevCommand,
867
145
  runExpressDevCommand,
868
146
  runWithWatch,
869
- toServerlessEvent
147
+ toServerlessEvent,
148
+ validateMaxBodyBytes,
149
+ validateOutDirForClean
870
150
  };