@mailquilt/cli 0.0.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.
@@ -0,0 +1,875 @@
1
+ import { createHash } from "node:crypto";
2
+ import { once } from "node:events";
3
+ import { watch } from "node:fs";
4
+ import type { Dirent, FSWatcher } from "node:fs";
5
+ import { mkdir, readdir, readFile, realpath } from "node:fs/promises";
6
+ import { createServer } from "node:http";
7
+ import type { IncomingMessage, Server, ServerResponse } from "node:http";
8
+ import { createRequire } from "node:module";
9
+ import type { AddressInfo } from "node:net";
10
+ import path from "node:path";
11
+ import { promisify } from "node:util";
12
+
13
+ import { createEditor, createEmail, loadDocument } from "@mailquilt/core";
14
+ import type { BlocksDocument } from "@mailquilt/core";
15
+ import {
16
+ canonicalizeRoot,
17
+ readWorkspaceFile,
18
+ resolveWorkspaceReadPath,
19
+ resolveWorkspaceWritePath,
20
+ WorkspacePathError,
21
+ writeWorkspaceFileAtomic,
22
+ } from "@mailquilt/mcp";
23
+
24
+ import { renderDevHtml } from "./html.js";
25
+
26
+ export interface DevServerOptions {
27
+ /** Directory containing email JSON files (default `./emails`). */
28
+ readonly dir: string;
29
+ /** Port to listen on `127.0.0.1` (default `4173`; `0` for ephemeral port). */
30
+ readonly port?: number | undefined;
31
+ /** Create a starter `welcome.json` when `dir` contains no `.json` files (default `true`). */
32
+ readonly createStarterIfEmpty?: boolean | undefined;
33
+ /** Optional override for `@mailquilt/editor`'s `dist/cdn` directory. */
34
+ readonly cdnDir?: string | undefined;
35
+ }
36
+
37
+ export interface DevServerHandle {
38
+ readonly dir: string;
39
+ readonly port: number;
40
+ readonly url: string;
41
+ readonly files: readonly string[];
42
+ readonly close: () => Promise<void>;
43
+ }
44
+
45
+ const MAX_BODY_BYTES = 5 * 1024 * 1024;
46
+ const WATCH_DEBOUNCE_MS = 40;
47
+ const BROWSER_SAVE_TTL_MS = 2000;
48
+ const SSE_HEARTBEAT_MS = 25_000;
49
+
50
+ const HOST_HEADER_PATTERN =
51
+ /^(?:127\.0\.0\.1|localhost)(?::(?<port>\d{1,5}))?$/iu;
52
+
53
+ const require = createRequire(import.meta.url);
54
+
55
+ const defaultEditorCdnDir = (): string => {
56
+ const pkgPath = require.resolve("@mailquilt/editor/package.json");
57
+ return path.join(path.dirname(pkgPath), "dist", "cdn");
58
+ };
59
+
60
+ const sha256 = (text: string): string =>
61
+ createHash("sha256").update(text).digest("hex");
62
+
63
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
64
+ typeof value === "object" && value !== null && !Array.isArray(value);
65
+
66
+ const isJsonEmailPath = (file: string): boolean => {
67
+ if (file.trim() === "" || file.includes("\0")) {
68
+ return false;
69
+ }
70
+ const normalized = file.replaceAll("\\", "/");
71
+ const segments = normalized.split("/");
72
+ if (segments.some((segment) => segment.startsWith("."))) {
73
+ return false;
74
+ }
75
+ return normalized.toLowerCase().endsWith(".json");
76
+ };
77
+
78
+ const createStarterEmail = (): BlocksDocument => {
79
+ const editor = createEditor({ document: createEmail() });
80
+ const initialDoc = editor.getDocument();
81
+ const firstBlockId = initialDoc.rows[0]?.columns[0]?.blocks[0]?.id;
82
+
83
+ editor.apply({
84
+ settings: {
85
+ language: "en",
86
+ preheader: "Edit locally or with your AI coding agent via MCP.",
87
+ },
88
+ type: "updateEmailSettings",
89
+ });
90
+ editor.apply({
91
+ blockType: "heading",
92
+ props: {
93
+ content: {
94
+ content: [
95
+ {
96
+ content: [{ text: "Welcome to Mail Quilt", type: "text" }],
97
+ type: "paragraph",
98
+ },
99
+ ],
100
+ type: "doc",
101
+ },
102
+ level: 1,
103
+ },
104
+ rowIndex: 0,
105
+ type: "insertBlockInNewRow",
106
+ });
107
+ if (firstBlockId !== undefined) {
108
+ editor.apply({
109
+ blockId: firstBlockId,
110
+ props: {
111
+ content: {
112
+ content: [
113
+ {
114
+ content: [
115
+ {
116
+ text: "Changes saved here write directly to welcome.json, and edits from disk or MCP reload live.",
117
+ type: "text",
118
+ },
119
+ ],
120
+ type: "paragraph",
121
+ },
122
+ ],
123
+ type: "doc",
124
+ },
125
+ },
126
+ type: "updateBlockProps",
127
+ });
128
+ }
129
+ editor.apply({
130
+ blockType: "button",
131
+ props: {
132
+ href: "https://editor.mailquilt.com",
133
+ label: "Read the docs",
134
+ },
135
+ rowIndex: 2,
136
+ type: "insertBlockInNewRow",
137
+ });
138
+
139
+ const loaded = loadDocument(editor.getDocument());
140
+ if (!loaded.ok) {
141
+ throw new Error(`Starter email failed validation: ${loaded.reason}`);
142
+ }
143
+ return loaded.document;
144
+ };
145
+
146
+ const isWithinRoot = (root: string, candidate: string): boolean => {
147
+ const relative = path.relative(root, candidate);
148
+ return (
149
+ relative === "" ||
150
+ (relative !== ".." &&
151
+ !relative.startsWith(`..${path.sep}`) &&
152
+ !path.isAbsolute(relative))
153
+ );
154
+ };
155
+
156
+ /** Lists all `.json` email files inside `canonicalRoot`, sorted alphabetically. */
157
+ export const listEmailFiles = async (
158
+ canonicalRoot: string
159
+ ): Promise<string[]> => {
160
+ const collected: string[] = [];
161
+
162
+ const walk = async (currentDir: string, visitedDirs: Set<string>) => {
163
+ let entries: Dirent[];
164
+ try {
165
+ entries = await readdir(currentDir, { withFileTypes: true });
166
+ } catch {
167
+ return;
168
+ }
169
+
170
+ await Promise.all(
171
+ entries.map(async (entry) => {
172
+ if (entry.name.startsWith(".") || entry.name === "node_modules") {
173
+ return;
174
+ }
175
+ const fullPath = path.join(currentDir, entry.name);
176
+ if (entry.isDirectory()) {
177
+ const realDir = await realpath(fullPath).catch(() => null);
178
+ if (
179
+ realDir &&
180
+ isWithinRoot(canonicalRoot, realDir) &&
181
+ !visitedDirs.has(realDir)
182
+ ) {
183
+ visitedDirs.add(realDir);
184
+ await walk(realDir, visitedDirs);
185
+ }
186
+ return;
187
+ }
188
+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".json")) {
189
+ collected.push(
190
+ path.relative(canonicalRoot, fullPath).split(path.sep).join("/")
191
+ );
192
+ return;
193
+ }
194
+ if (
195
+ entry.isSymbolicLink() &&
196
+ entry.name.toLowerCase().endsWith(".json")
197
+ ) {
198
+ const realFile = await realpath(fullPath).catch(() => null);
199
+ if (realFile && isWithinRoot(canonicalRoot, realFile)) {
200
+ collected.push(
201
+ path.relative(canonicalRoot, fullPath).split(path.sep).join("/")
202
+ );
203
+ }
204
+ }
205
+ })
206
+ );
207
+ };
208
+
209
+ await walk(canonicalRoot, new Set([canonicalRoot]));
210
+ return collected.toSorted((left, right) => left.localeCompare(right));
211
+ };
212
+
213
+ const isValidHostHeader = (
214
+ hostHeader: string | undefined,
215
+ port: number
216
+ ): boolean => {
217
+ if (typeof hostHeader !== "string") {
218
+ return false;
219
+ }
220
+ const match = HOST_HEADER_PATTERN.exec(hostHeader.trim());
221
+ if (!match) {
222
+ return false;
223
+ }
224
+ const headerPort = match.groups?.port;
225
+ if (headerPort === undefined) {
226
+ return port === 80;
227
+ }
228
+ return headerPort === String(port);
229
+ };
230
+
231
+ const isValidOriginHeader = (
232
+ originHeader: string | undefined,
233
+ port: number
234
+ ): boolean => {
235
+ if (originHeader === undefined) {
236
+ return true;
237
+ }
238
+ let parsed: URL;
239
+ try {
240
+ parsed = new URL(originHeader);
241
+ } catch {
242
+ return false;
243
+ }
244
+ if (parsed.protocol !== "http:") {
245
+ return false;
246
+ }
247
+ if (parsed.hostname !== "127.0.0.1" && parsed.hostname !== "localhost") {
248
+ return false;
249
+ }
250
+ const expectedPort = port === 80 ? "" : String(port);
251
+ return parsed.port === expectedPort;
252
+ };
253
+
254
+ const isValidFetchSite = (req: IncomingMessage): boolean => {
255
+ const site = req.headers["sec-fetch-site"];
256
+ if (site === undefined) {
257
+ return true;
258
+ }
259
+ return site === "same-origin" || site === "none";
260
+ };
261
+
262
+ const sendJson = (
263
+ res: ServerResponse,
264
+ statusCode: number,
265
+ payload: unknown
266
+ ): void => {
267
+ const body = JSON.stringify(payload);
268
+ res.writeHead(statusCode, {
269
+ "cache-control": "no-store",
270
+ "content-length": String(Buffer.byteLength(body, "utf-8")),
271
+ "content-type": "application/json; charset=utf-8",
272
+ "referrer-policy": "no-referrer",
273
+ "x-content-type-options": "nosniff",
274
+ });
275
+ res.end(body);
276
+ };
277
+
278
+ const readBodyUtf8 = async (
279
+ req: IncomingMessage
280
+ ): Promise<
281
+ { ok: true; text: string } | { ok: false; status: number; error: string }
282
+ > => {
283
+ const chunks: Buffer[] = [];
284
+ let total = 0;
285
+ try {
286
+ for await (const chunk of req) {
287
+ const buffer =
288
+ typeof chunk === "string"
289
+ ? Buffer.from(chunk, "utf-8")
290
+ : Buffer.from(chunk);
291
+ total += buffer.length;
292
+ if (total > MAX_BODY_BYTES) {
293
+ return {
294
+ error: `Request body exceeds ${MAX_BODY_BYTES} bytes.`,
295
+ ok: false,
296
+ status: 413,
297
+ };
298
+ }
299
+ chunks.push(buffer);
300
+ }
301
+ } catch (error) {
302
+ return {
303
+ error: error instanceof Error ? error.message : String(error),
304
+ ok: false,
305
+ status: 400,
306
+ };
307
+ }
308
+ return { ok: true, text: Buffer.concat(chunks).toString("utf-8") };
309
+ };
310
+
311
+ const contentTypeForAsset = (assetPath: string): string | null => {
312
+ const ext = path.extname(assetPath).toLowerCase();
313
+ switch (ext) {
314
+ case ".js":
315
+ case ".mjs": {
316
+ return "text/javascript; charset=utf-8";
317
+ }
318
+ case ".txt": {
319
+ return "text/plain; charset=utf-8";
320
+ }
321
+ case ".map": {
322
+ return "application/json; charset=utf-8";
323
+ }
324
+ default: {
325
+ return null;
326
+ }
327
+ }
328
+ };
329
+
330
+ /**
331
+ * Starts the localhost-only (`127.0.0.1`) Mail Quilt dev server watching `dir`
332
+ * for `.json` email files with live SSE reload and `loadDocument()` validation.
333
+ */
334
+ export const startDevServer = async (
335
+ options: DevServerOptions
336
+ ): Promise<DevServerHandle> => {
337
+ const requestedPort = options.port ?? 4173;
338
+ const createStarterIfEmpty = options.createStarterIfEmpty ?? true;
339
+ const cdnDir = canonicalizeRoot(options.cdnDir ?? defaultEditorCdnDir());
340
+
341
+ await mkdir(options.dir, { recursive: true });
342
+ const canonicalRoot = canonicalizeRoot(options.dir);
343
+
344
+ let initialFiles = await listEmailFiles(canonicalRoot);
345
+ if (initialFiles.length === 0 && createStarterIfEmpty) {
346
+ const starter = createStarterEmail();
347
+ await writeWorkspaceFileAtomic(
348
+ canonicalRoot,
349
+ "welcome.json",
350
+ `${JSON.stringify(starter, null, 2)}\n`,
351
+ { overwrite: false }
352
+ );
353
+ initialFiles = await listEmailFiles(canonicalRoot);
354
+ }
355
+
356
+ const sseClients = new Set<ServerResponse>();
357
+ const recentBrowserSaves = new Map<
358
+ string,
359
+ { hash: string; expiresAt: number }
360
+ >();
361
+ const pendingTimers = new Map<string, ReturnType<typeof setTimeout>>();
362
+
363
+ const broadcast = (event: string, data: unknown) => {
364
+ const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
365
+ for (const client of sseClients) {
366
+ try {
367
+ client.write(frame);
368
+ } catch {
369
+ sseClients.delete(client);
370
+ }
371
+ }
372
+ };
373
+
374
+ let actualPort = requestedPort;
375
+ let actualUrl = `http://127.0.0.1:${actualPort}`;
376
+
377
+ const handleCdnAsset = async (
378
+ pathname: string,
379
+ res: ServerResponse
380
+ ): Promise<void> => {
381
+ let relativeAsset: string;
382
+ try {
383
+ relativeAsset = decodeURIComponent(
384
+ pathname.slice("/_mailquilt/cdn/".length)
385
+ );
386
+ } catch {
387
+ sendJson(res, 400, { error: "Malformed asset path.", ok: false });
388
+ return;
389
+ }
390
+
391
+ const contentType = contentTypeForAsset(relativeAsset);
392
+ if (contentType === null) {
393
+ sendJson(res, 403, { error: "Unsupported asset type.", ok: false });
394
+ return;
395
+ }
396
+
397
+ let resolved: Awaited<ReturnType<typeof resolveWorkspaceReadPath>>;
398
+ try {
399
+ resolved = await resolveWorkspaceReadPath(cdnDir, relativeAsset);
400
+ } catch (error) {
401
+ if (error instanceof WorkspacePathError) {
402
+ sendJson(res, error.code === "not_found" ? 404 : 403, {
403
+ error: error.message,
404
+ ok: false,
405
+ });
406
+ return;
407
+ }
408
+ sendJson(res, 500, { error: "Failed to resolve asset.", ok: false });
409
+ return;
410
+ }
411
+
412
+ const data = await readFile(resolved.absolutePath);
413
+ res.writeHead(200, {
414
+ "cache-control": "no-cache",
415
+ "content-length": String(data.length),
416
+ "content-type": contentType,
417
+ "referrer-policy": "no-referrer",
418
+ "x-content-type-options": "nosniff",
419
+ });
420
+ res.end(data);
421
+ };
422
+
423
+ const handleGetEmail = async (
424
+ fileParam: string | null,
425
+ res: ServerResponse
426
+ ): Promise<void> => {
427
+ if (fileParam === null || !isJsonEmailPath(fileParam)) {
428
+ sendJson(res, 403, {
429
+ error: "Invalid or non-JSON email file path.",
430
+ ok: false,
431
+ });
432
+ return;
433
+ }
434
+
435
+ let content: string;
436
+ let relativePath: string;
437
+ try {
438
+ const read = await readWorkspaceFile(canonicalRoot, fileParam);
439
+ ({ content, relativePath } = read);
440
+ } catch (error) {
441
+ if (error instanceof WorkspacePathError) {
442
+ sendJson(res, error.code === "not_found" ? 404 : 403, {
443
+ code: error.code,
444
+ error: error.message,
445
+ ok: false,
446
+ });
447
+ return;
448
+ }
449
+ sendJson(res, 500, { error: "Failed to read email.", ok: false });
450
+ return;
451
+ }
452
+
453
+ let parsed: unknown;
454
+ try {
455
+ parsed = JSON.parse(content);
456
+ } catch (error) {
457
+ sendJson(res, 400, {
458
+ error: "Invalid JSON",
459
+ ok: false,
460
+ reason: error instanceof Error ? error.message : String(error),
461
+ });
462
+ return;
463
+ }
464
+
465
+ const loaded = loadDocument(parsed);
466
+ if (!loaded.ok) {
467
+ sendJson(res, 400, {
468
+ error: "Document refused",
469
+ ok: false,
470
+ reason: loaded.reason,
471
+ });
472
+ return;
473
+ }
474
+
475
+ sendJson(res, 200, {
476
+ document: loaded.document,
477
+ file: relativePath,
478
+ ok: true,
479
+ });
480
+ };
481
+
482
+ const handlePutEmail = async (
483
+ fileParam: string | null,
484
+ req: IncomingMessage,
485
+ res: ServerResponse
486
+ ): Promise<void> => {
487
+ if (fileParam === null || !isJsonEmailPath(fileParam)) {
488
+ sendJson(res, 403, {
489
+ error: "Invalid or non-JSON email file path.",
490
+ ok: false,
491
+ });
492
+ return;
493
+ }
494
+
495
+ // Check path containment before reading body.
496
+ try {
497
+ await resolveWorkspaceWritePath(canonicalRoot, fileParam);
498
+ } catch (error) {
499
+ if (error instanceof WorkspacePathError) {
500
+ sendJson(res, 403, {
501
+ code: error.code,
502
+ error: error.message,
503
+ ok: false,
504
+ });
505
+ return;
506
+ }
507
+ sendJson(res, 500, { error: "Failed to validate path.", ok: false });
508
+ return;
509
+ }
510
+
511
+ const body = await readBodyUtf8(req);
512
+ if (!body.ok) {
513
+ sendJson(res, body.status, { error: body.error, ok: false });
514
+ return;
515
+ }
516
+
517
+ let parsed: unknown;
518
+ try {
519
+ parsed = JSON.parse(body.text);
520
+ } catch (error) {
521
+ sendJson(res, 400, {
522
+ error: "Invalid JSON",
523
+ ok: false,
524
+ reason: error instanceof Error ? error.message : String(error),
525
+ });
526
+ return;
527
+ }
528
+
529
+ const loaded = loadDocument(parsed);
530
+ if (!loaded.ok) {
531
+ sendJson(res, 400, {
532
+ error: "Document refused",
533
+ ok: false,
534
+ reason: loaded.reason,
535
+ });
536
+ return;
537
+ }
538
+
539
+ const serialized = `${JSON.stringify(loaded.document, null, 2)}\n`;
540
+ try {
541
+ const written = await writeWorkspaceFileAtomic(
542
+ canonicalRoot,
543
+ fileParam,
544
+ serialized,
545
+ { overwrite: true }
546
+ );
547
+ recentBrowserSaves.set(written.relativePath, {
548
+ expiresAt: Date.now() + BROWSER_SAVE_TTL_MS,
549
+ hash: sha256(serialized),
550
+ });
551
+ sendJson(res, 200, {
552
+ document: loaded.document,
553
+ file: written.relativePath,
554
+ ok: true,
555
+ });
556
+ } catch (error) {
557
+ if (error instanceof WorkspacePathError) {
558
+ sendJson(res, 403, {
559
+ code: error.code,
560
+ error: error.message,
561
+ ok: false,
562
+ });
563
+ return;
564
+ }
565
+ sendJson(res, 500, {
566
+ error: error instanceof Error ? error.message : String(error),
567
+ ok: false,
568
+ });
569
+ }
570
+ };
571
+
572
+ const handleCreateEmail = async (
573
+ req: IncomingMessage,
574
+ res: ServerResponse
575
+ ): Promise<void> => {
576
+ const body = await readBodyUtf8(req);
577
+ if (!body.ok) {
578
+ sendJson(res, body.status, { error: body.error, ok: false });
579
+ return;
580
+ }
581
+
582
+ let parsed: unknown;
583
+ try {
584
+ parsed = JSON.parse(body.text);
585
+ } catch (error) {
586
+ sendJson(res, 400, {
587
+ error: "Invalid JSON",
588
+ ok: false,
589
+ reason: error instanceof Error ? error.message : String(error),
590
+ });
591
+ return;
592
+ }
593
+
594
+ if (!isRecord(parsed) || typeof parsed.file !== "string") {
595
+ sendJson(res, 400, {
596
+ error: 'Request body must include a string "file" path.',
597
+ ok: false,
598
+ });
599
+ return;
600
+ }
601
+
602
+ if (!isJsonEmailPath(parsed.file)) {
603
+ sendJson(res, 403, {
604
+ error: "Email file path must be a non-hidden .json path.",
605
+ ok: false,
606
+ });
607
+ return;
608
+ }
609
+
610
+ const candidateDoc = parsed.document ?? createEmail();
611
+ const loaded = loadDocument(candidateDoc);
612
+ if (!loaded.ok) {
613
+ sendJson(res, 400, {
614
+ error: "Document refused",
615
+ ok: false,
616
+ reason: loaded.reason,
617
+ });
618
+ return;
619
+ }
620
+
621
+ const serialized = `${JSON.stringify(loaded.document, null, 2)}\n`;
622
+ try {
623
+ const written = await writeWorkspaceFileAtomic(
624
+ canonicalRoot,
625
+ parsed.file,
626
+ serialized,
627
+ { overwrite: false }
628
+ );
629
+ recentBrowserSaves.set(written.relativePath, {
630
+ expiresAt: Date.now() + BROWSER_SAVE_TTL_MS,
631
+ hash: sha256(serialized),
632
+ });
633
+ sendJson(res, 201, {
634
+ document: loaded.document,
635
+ file: written.relativePath,
636
+ ok: true,
637
+ });
638
+ } catch (error) {
639
+ if (error instanceof WorkspacePathError) {
640
+ sendJson(res, 403, {
641
+ code: error.code,
642
+ error: error.message,
643
+ ok: false,
644
+ });
645
+ return;
646
+ }
647
+ const message = error instanceof Error ? error.message : String(error);
648
+ sendJson(res, message.includes("already exists") ? 409 : 500, {
649
+ error: message,
650
+ ok: false,
651
+ });
652
+ }
653
+ };
654
+
655
+ const handleSseEvents = async (
656
+ req: IncomingMessage,
657
+ res: ServerResponse
658
+ ): Promise<void> => {
659
+ res.writeHead(200, {
660
+ "cache-control": "no-cache, no-transform",
661
+ connection: "keep-alive",
662
+ "content-type": "text/event-stream; charset=utf-8",
663
+ "x-content-type-options": "nosniff",
664
+ });
665
+ sseClients.add(res);
666
+ req.on("close", () => {
667
+ sseClients.delete(res);
668
+ });
669
+ const files = await listEmailFiles(canonicalRoot);
670
+ res.write(`event: connected\ndata: ${JSON.stringify({ files })}\n\n`);
671
+ };
672
+
673
+ const handleApiRoute = async (
674
+ method: string,
675
+ url: URL,
676
+ req: IncomingMessage,
677
+ res: ServerResponse
678
+ ): Promise<boolean> => {
679
+ const { pathname } = url;
680
+ if (method === "GET" && pathname === "/api/emails") {
681
+ const files = await listEmailFiles(canonicalRoot);
682
+ sendJson(res, 200, { files, ok: true, root: canonicalRoot });
683
+ return true;
684
+ }
685
+ if (method === "POST" && pathname === "/api/emails") {
686
+ await handleCreateEmail(req, res);
687
+ return true;
688
+ }
689
+ if (method === "GET" && pathname === "/api/email") {
690
+ await handleGetEmail(url.searchParams.get("file"), res);
691
+ return true;
692
+ }
693
+ if (method === "PUT" && pathname === "/api/email") {
694
+ await handlePutEmail(url.searchParams.get("file"), req, res);
695
+ return true;
696
+ }
697
+ if (method === "GET" && pathname === "/api/events") {
698
+ await handleSseEvents(req, res);
699
+ return true;
700
+ }
701
+ return false;
702
+ };
703
+
704
+ const handleRequest = async (
705
+ req: IncomingMessage,
706
+ res: ServerResponse
707
+ ): Promise<void> => {
708
+ if (!isValidHostHeader(req.headers.host, actualPort)) {
709
+ sendJson(res, 403, { error: "Forbidden Host header.", ok: false });
710
+ return;
711
+ }
712
+ if (!isValidOriginHeader(req.headers.origin, actualPort)) {
713
+ sendJson(res, 403, { error: "Forbidden Origin header.", ok: false });
714
+ return;
715
+ }
716
+
717
+ const method = req.method ?? "GET";
718
+ const url = new URL(req.url ?? "/", actualUrl);
719
+ const { pathname } = url;
720
+
721
+ if (
722
+ (pathname.startsWith("/api/") || method === "PUT" || method === "POST") &&
723
+ !isValidFetchSite(req)
724
+ ) {
725
+ sendJson(res, 403, { error: "Cross-site request refused.", ok: false });
726
+ return;
727
+ }
728
+
729
+ if (method === "GET" && (pathname === "/" || pathname === "/index.html")) {
730
+ const html = renderDevHtml(canonicalRoot, actualUrl);
731
+ res.writeHead(200, {
732
+ "cache-control": "no-store",
733
+ "content-length": String(Buffer.byteLength(html, "utf-8")),
734
+ "content-type": "text/html; charset=utf-8",
735
+ "referrer-policy": "no-referrer",
736
+ "x-content-type-options": "nosniff",
737
+ "x-frame-options": "SAMEORIGIN",
738
+ });
739
+ res.end(html);
740
+ return;
741
+ }
742
+
743
+ if (method === "GET" && pathname.startsWith("/_mailquilt/cdn/")) {
744
+ await handleCdnAsset(pathname, res);
745
+ return;
746
+ }
747
+
748
+ if (await handleApiRoute(method, url, req, res)) {
749
+ return;
750
+ }
751
+
752
+ sendJson(res, 404, { error: "Not found.", ok: false });
753
+ };
754
+
755
+ const runRequest = async (
756
+ req: IncomingMessage,
757
+ res: ServerResponse
758
+ ): Promise<void> => {
759
+ try {
760
+ await handleRequest(req, res);
761
+ } catch (error) {
762
+ if (!res.headersSent) {
763
+ sendJson(res, 500, {
764
+ error: error instanceof Error ? error.message : String(error),
765
+ ok: false,
766
+ });
767
+ }
768
+ }
769
+ };
770
+
771
+ const server: Server = createServer((req, res) => {
772
+ void runRequest(req, res);
773
+ });
774
+
775
+ server.listen(requestedPort, "127.0.0.1");
776
+ await once(server, "listening");
777
+
778
+ const address = server.address() as AddressInfo;
779
+ actualPort = address.port;
780
+ actualUrl = `http://127.0.0.1:${actualPort}`;
781
+
782
+ const scheduleWatchEvent = (filename: string | null) => {
783
+ if (!filename) {
784
+ return;
785
+ }
786
+ const relative = filename.replaceAll("\\", "/");
787
+ if (!isJsonEmailPath(relative)) {
788
+ return;
789
+ }
790
+ const existing = pendingTimers.get(relative);
791
+ if (existing !== undefined) {
792
+ clearTimeout(existing);
793
+ }
794
+ const timer = setTimeout(() => {
795
+ pendingTimers.delete(relative);
796
+ void (async () => {
797
+ const files = await listEmailFiles(canonicalRoot);
798
+ if (!files.includes(relative)) {
799
+ broadcast("files-changed", { file: relative, files });
800
+ return;
801
+ }
802
+ let source: "browser" | "disk" = "disk";
803
+ const recorded = recentBrowserSaves.get(relative);
804
+ if (recorded !== undefined) {
805
+ if (Date.now() > recorded.expiresAt) {
806
+ recentBrowserSaves.delete(relative);
807
+ } else {
808
+ const diskText = await readFile(
809
+ path.join(canonicalRoot, relative),
810
+ "utf-8"
811
+ ).catch(() => null);
812
+ if (diskText !== null && sha256(diskText) === recorded.hash) {
813
+ source = "browser";
814
+ }
815
+ }
816
+ }
817
+ broadcast("email-changed", { file: relative, files, source });
818
+ })();
819
+ }, WATCH_DEBOUNCE_MS);
820
+ timer.unref();
821
+ pendingTimers.set(relative, timer);
822
+ };
823
+
824
+ let watcher: FSWatcher | undefined;
825
+ try {
826
+ watcher = watch(canonicalRoot, { recursive: true }, (_event, filename) => {
827
+ scheduleWatchEvent(typeof filename === "string" ? filename : null);
828
+ });
829
+ } catch {
830
+ watcher = watch(canonicalRoot, (_event, filename) => {
831
+ scheduleWatchEvent(typeof filename === "string" ? filename : null);
832
+ });
833
+ }
834
+ watcher.on("error", () => {
835
+ // Avoid unhandled watcher errors during shutdown or temporary FS hiccups.
836
+ });
837
+
838
+ const heartbeat = setInterval(() => {
839
+ for (const client of sseClients) {
840
+ try {
841
+ client.write(": keepalive\n\n");
842
+ } catch {
843
+ sseClients.delete(client);
844
+ }
845
+ }
846
+ }, SSE_HEARTBEAT_MS);
847
+ heartbeat.unref();
848
+
849
+ let closed = false;
850
+ const close = async (): Promise<void> => {
851
+ if (closed) {
852
+ return;
853
+ }
854
+ closed = true;
855
+ clearInterval(heartbeat);
856
+ for (const timer of pendingTimers.values()) {
857
+ clearTimeout(timer);
858
+ }
859
+ pendingTimers.clear();
860
+ watcher?.close();
861
+ for (const client of sseClients) {
862
+ client.end();
863
+ }
864
+ sseClients.clear();
865
+ await promisify(server.close.bind(server))();
866
+ };
867
+
868
+ return {
869
+ close,
870
+ dir: canonicalRoot,
871
+ files: initialFiles,
872
+ port: actualPort,
873
+ url: actualUrl,
874
+ };
875
+ };