@mailquilt/cli 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/dist/bin.js +1707 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1700 -0
- package/dist/index.js.map +1 -0
- package/package.json +63 -3
- package/src/bin.ts +10 -0
- package/src/cli.ts +70 -0
- package/src/commands/check.ts +308 -0
- package/src/commands/dev.ts +137 -0
- package/src/commands/mcp.ts +59 -0
- package/src/commands/render.ts +127 -0
- package/src/dev/html.ts +583 -0
- package/src/dev/server.ts +875 -0
- package/src/index.ts +8 -0
package/dist/bin.js
ADDED
|
@@ -0,0 +1,1707 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { mkdir, readFile, readdir, realpath, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { parseArgs, promisify } from "node:util";
|
|
6
|
+
import { createEditor, createEmail, loadDocument } from "@mailquilt/core";
|
|
7
|
+
import { checkEmail, renderEmail, renderText } from "@mailquilt/renderer";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { once } from "node:events";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { watch } from "node:fs";
|
|
12
|
+
import { createServer } from "node:http";
|
|
13
|
+
import { WorkspacePathError, canonicalizeRoot, readWorkspaceFile, resolveWorkspaceReadPath, resolveWorkspaceWritePath, startMcpStdioServer, writeWorkspaceFileAtomic } from "@mailquilt/mcp";
|
|
14
|
+
// package.json
|
|
15
|
+
var version = "0.5.0";
|
|
16
|
+
// src/commands/check.ts
|
|
17
|
+
const CHECK_HELP = `Usage: mailquilt check <file.json> [options]
|
|
18
|
+
|
|
19
|
+
Check a Mail Quilt email JSON file for Problems (CI gate).
|
|
20
|
+
Exits non-zero when Problems exist or the document is refused.
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--merge-tags <json-or-file> JSON array or path to JSON file of Merge Tags
|
|
24
|
+
--strict Also fail if the email used a migrated older version
|
|
25
|
+
--json Emit machine-readable JSON output
|
|
26
|
+
-h, --help Show this help message
|
|
27
|
+
`;
|
|
28
|
+
const errorMessage$3 = (error) => error instanceof Error ? error.message : String(error);
|
|
29
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
30
|
+
const parseMergeTagsInput = async (raw, cwd) => {
|
|
31
|
+
const trimmed = raw.trim();
|
|
32
|
+
const jsonText = trimmed.startsWith("[") || trimmed.startsWith("{") ? trimmed : await readFile(path.resolve(cwd, raw), "utf-8");
|
|
33
|
+
const parsed = JSON.parse(jsonText);
|
|
34
|
+
if (!Array.isArray(parsed)) throw new TypeError("--merge-tags must be a JSON array.");
|
|
35
|
+
const tags = [];
|
|
36
|
+
for (const [index, item] of parsed.entries()) {
|
|
37
|
+
if (typeof item === "string" && item.trim() !== "") {
|
|
38
|
+
tags.push({ name: item.trim() });
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (isRecord$1(item) && typeof item.name === "string" && item.name.trim() !== "") {
|
|
42
|
+
if (item.unsubscribe !== void 0 && typeof item.unsubscribe !== "boolean") throw new TypeError(`--merge-tags[${index}].unsubscribe must be a boolean.`);
|
|
43
|
+
tags.push(item.unsubscribe === void 0 ? { name: item.name } : {
|
|
44
|
+
name: item.name,
|
|
45
|
+
unsubscribe: item.unsubscribe
|
|
46
|
+
});
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
throw new TypeError(`--merge-tags[${index}] must be a non-empty string or { name, unsubscribe? } object.`);
|
|
50
|
+
}
|
|
51
|
+
return tags;
|
|
52
|
+
};
|
|
53
|
+
const formatProblemLine = (problem) => {
|
|
54
|
+
const details = [];
|
|
55
|
+
if (problem.blockId !== void 0) details.push(`block: ${problem.blockId}`);
|
|
56
|
+
if (problem.field !== void 0) details.push(`field: ${problem.field}`);
|
|
57
|
+
if (problem.mergeTag !== void 0) details.push(`tag: {{${problem.mergeTag}}}`);
|
|
58
|
+
const suffix = details.length > 0 ? ` (${details.join(", ")})` : "";
|
|
59
|
+
return ` - [${problem.code}]${suffix} ${problem.message}\n`;
|
|
60
|
+
};
|
|
61
|
+
const loadEmailFile = async (inputFile, cwd) => {
|
|
62
|
+
const resolvedInput = path.resolve(cwd, inputFile);
|
|
63
|
+
let rawText;
|
|
64
|
+
try {
|
|
65
|
+
rawText = await readFile(resolvedInput, "utf-8");
|
|
66
|
+
} catch (error) {
|
|
67
|
+
return {
|
|
68
|
+
error: `failed to read "${inputFile}": ${errorMessage$3(error)}`,
|
|
69
|
+
ok: false
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
let parsedJson;
|
|
73
|
+
try {
|
|
74
|
+
parsedJson = JSON.parse(rawText);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return {
|
|
77
|
+
error: `invalid JSON in "${inputFile}": ${errorMessage$3(error)}`,
|
|
78
|
+
ok: false
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const originalVersion = isRecord$1(parsedJson) && typeof parsedJson.version === "number" ? parsedJson.version : void 0;
|
|
82
|
+
const loaded = loadDocument(parsedJson);
|
|
83
|
+
if (!loaded.ok) return {
|
|
84
|
+
error: `document refused: ${loaded.reason}`,
|
|
85
|
+
ok: false
|
|
86
|
+
};
|
|
87
|
+
const migratedFrom = originalVersion !== void 0 && originalVersion < loaded.document.version ? originalVersion : void 0;
|
|
88
|
+
return {
|
|
89
|
+
document: loaded.document,
|
|
90
|
+
...migratedFrom === void 0 ? {} : { migratedFrom },
|
|
91
|
+
ok: true
|
|
92
|
+
};
|
|
93
|
+
};
|
|
94
|
+
const emitCheckResult = (io, inputFile, asJson, report) => {
|
|
95
|
+
const strictMigrationFailure = report.strict && report.migratedFrom !== void 0;
|
|
96
|
+
const passed = report.problems.length === 0 && !strictMigrationFailure;
|
|
97
|
+
if (asJson) {
|
|
98
|
+
io.stdout.write(`${JSON.stringify({
|
|
99
|
+
file: inputFile,
|
|
100
|
+
...report.migratedFrom === void 0 ? {} : { migratedFrom: report.migratedFrom },
|
|
101
|
+
passed,
|
|
102
|
+
problemCount: report.problems.length,
|
|
103
|
+
problems: report.problems,
|
|
104
|
+
...strictMigrationFailure ? { strictFailure: `Document is format version ${report.migratedFrom}; current version is ${report.documentVersion}.` } : {}
|
|
105
|
+
}, null, 2)}\n`);
|
|
106
|
+
return passed ? 0 : 1;
|
|
107
|
+
}
|
|
108
|
+
if (passed) {
|
|
109
|
+
io.stdout.write(`✓ ${inputFile}: no Problems found.\n`);
|
|
110
|
+
return 0;
|
|
111
|
+
}
|
|
112
|
+
if (report.problems.length > 0) {
|
|
113
|
+
const noun = report.problems.length === 1 ? "Problem" : "Problems";
|
|
114
|
+
io.stdout.write(`✗ ${inputFile}: ${report.problems.length} ${noun} found\n`);
|
|
115
|
+
for (const problem of report.problems) io.stdout.write(formatProblemLine(problem));
|
|
116
|
+
}
|
|
117
|
+
if (strictMigrationFailure) io.stdout.write(`✗ ${inputFile}: --strict refused migrated format version ${report.migratedFrom} (current version is ${report.documentVersion}).\n`);
|
|
118
|
+
return 1;
|
|
119
|
+
};
|
|
120
|
+
const emitFailure = (io, inputFile, asJson, error) => {
|
|
121
|
+
if (asJson) io.stdout.write(`${JSON.stringify({
|
|
122
|
+
error,
|
|
123
|
+
file: inputFile,
|
|
124
|
+
passed: false,
|
|
125
|
+
problemCount: 0,
|
|
126
|
+
problems: []
|
|
127
|
+
}, null, 2)}\n`);
|
|
128
|
+
else io.stderr.write(`mailquilt check: ${error}\n`);
|
|
129
|
+
return 1;
|
|
130
|
+
};
|
|
131
|
+
const runCheck = async (args, io) => {
|
|
132
|
+
let parsed;
|
|
133
|
+
try {
|
|
134
|
+
parsed = parseArgs({
|
|
135
|
+
allowPositionals: true,
|
|
136
|
+
args: [...args],
|
|
137
|
+
options: {
|
|
138
|
+
help: {
|
|
139
|
+
short: "h",
|
|
140
|
+
type: "boolean"
|
|
141
|
+
},
|
|
142
|
+
json: { type: "boolean" },
|
|
143
|
+
"merge-tags": { type: "string" },
|
|
144
|
+
strict: { type: "boolean" }
|
|
145
|
+
},
|
|
146
|
+
strict: true
|
|
147
|
+
});
|
|
148
|
+
} catch (error) {
|
|
149
|
+
io.stderr.write(`mailquilt check: ${errorMessage$3(error)}\n`);
|
|
150
|
+
return 1;
|
|
151
|
+
}
|
|
152
|
+
if (parsed.values.help) {
|
|
153
|
+
io.stdout.write(CHECK_HELP);
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
const [inputFile] = parsed.positionals;
|
|
157
|
+
if (!inputFile || parsed.positionals.length > 1) {
|
|
158
|
+
io.stderr.write("mailquilt check: expected a single <file.json> argument.\n");
|
|
159
|
+
return 1;
|
|
160
|
+
}
|
|
161
|
+
const cwd = io.cwd ?? process.cwd();
|
|
162
|
+
const asJson = parsed.values.json === true;
|
|
163
|
+
const strict = parsed.values.strict === true;
|
|
164
|
+
let mergeTags;
|
|
165
|
+
if (typeof parsed.values["merge-tags"] === "string") try {
|
|
166
|
+
mergeTags = await parseMergeTagsInput(parsed.values["merge-tags"], cwd);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
return emitFailure(io, inputFile, asJson, `invalid --merge-tags: ${errorMessage$3(error)}`);
|
|
169
|
+
}
|
|
170
|
+
const loaded = await loadEmailFile(inputFile, cwd);
|
|
171
|
+
if (!loaded.ok) return emitFailure(io, inputFile, asJson, loaded.error);
|
|
172
|
+
try {
|
|
173
|
+
const problems = await checkEmail(loaded.document, mergeTags === void 0 ? {} : { mergeTags });
|
|
174
|
+
return emitCheckResult(io, inputFile, asJson, {
|
|
175
|
+
documentVersion: loaded.document.version,
|
|
176
|
+
...loaded.migratedFrom === void 0 ? {} : { migratedFrom: loaded.migratedFrom },
|
|
177
|
+
problems,
|
|
178
|
+
strict
|
|
179
|
+
});
|
|
180
|
+
} catch (error) {
|
|
181
|
+
return emitFailure(io, inputFile, asJson, errorMessage$3(error));
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
// src/dev/html.ts
|
|
185
|
+
const escapeHtml = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
|
|
186
|
+
/**
|
|
187
|
+
* Renders the local `mailquilt dev` host page embedding `<mail-quilt-shell>`
|
|
188
|
+
* from the locally served `@mailquilt/editor` CDN bundle with a file switcher
|
|
189
|
+
* sidebar and SSE live reload.
|
|
190
|
+
*/
|
|
191
|
+
const renderDevHtml = (rootLabel, originUrl) => {
|
|
192
|
+
const safeRoot = escapeHtml(rootLabel);
|
|
193
|
+
const safeOrigin = escapeHtml(originUrl);
|
|
194
|
+
return `<!doctype html>
|
|
195
|
+
<html lang="en">
|
|
196
|
+
<head>
|
|
197
|
+
<meta charset="utf-8" />
|
|
198
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
199
|
+
<title>Mail Quilt Dev</title>
|
|
200
|
+
<style>
|
|
201
|
+
:root {
|
|
202
|
+
color-scheme: light dark;
|
|
203
|
+
--dev-bg: #f6f6f7;
|
|
204
|
+
--dev-surface: #ffffff;
|
|
205
|
+
--dev-border: #e2e4e8;
|
|
206
|
+
--dev-text: #18181b;
|
|
207
|
+
--dev-muted: #52525b;
|
|
208
|
+
--dev-accent: #2563eb;
|
|
209
|
+
--dev-accent-soft: #eff6ff;
|
|
210
|
+
--dev-danger: #dc2626;
|
|
211
|
+
--dev-danger-soft: #fef2f2;
|
|
212
|
+
--dev-ok: #16a34a;
|
|
213
|
+
--dev-warn: #d97706;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
@media (prefers-color-scheme: dark) {
|
|
217
|
+
:root {
|
|
218
|
+
--dev-bg: #111216;
|
|
219
|
+
--dev-surface: #18191f;
|
|
220
|
+
--dev-border: #2a2c34;
|
|
221
|
+
--dev-text: #f4f4f5;
|
|
222
|
+
--dev-muted: #a1a1aa;
|
|
223
|
+
--dev-accent: #60a5fa;
|
|
224
|
+
--dev-accent-soft: #1e293b;
|
|
225
|
+
--dev-danger: #f87171;
|
|
226
|
+
--dev-danger-soft: #2c1618;
|
|
227
|
+
--dev-ok: #4ade80;
|
|
228
|
+
--dev-warn: #fbbf24;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
* {
|
|
233
|
+
box-sizing: border-box;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
html,
|
|
237
|
+
body {
|
|
238
|
+
height: 100%;
|
|
239
|
+
margin: 0;
|
|
240
|
+
background: var(--dev-bg);
|
|
241
|
+
color: var(--dev-text);
|
|
242
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
|
243
|
+
font-size: 14px;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
.layout {
|
|
247
|
+
display: flex;
|
|
248
|
+
height: 100dvh;
|
|
249
|
+
min-height: 0;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
.sidebar {
|
|
253
|
+
display: flex;
|
|
254
|
+
flex-direction: column;
|
|
255
|
+
width: 256px;
|
|
256
|
+
flex: none;
|
|
257
|
+
background: var(--dev-surface);
|
|
258
|
+
border-inline-end: 1px solid var(--dev-border);
|
|
259
|
+
min-height: 0;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
.sidebar-head {
|
|
263
|
+
display: flex;
|
|
264
|
+
align-items: center;
|
|
265
|
+
justify-content: space-between;
|
|
266
|
+
gap: 8px;
|
|
267
|
+
padding: 12px 14px;
|
|
268
|
+
border-block-end: 1px solid var(--dev-border);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
.brand {
|
|
272
|
+
display: flex;
|
|
273
|
+
align-items: center;
|
|
274
|
+
gap: 8px;
|
|
275
|
+
font-weight: 600;
|
|
276
|
+
min-width: 0;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
.badge {
|
|
280
|
+
font-size: 11px;
|
|
281
|
+
font-weight: 600;
|
|
282
|
+
padding: 2px 6px;
|
|
283
|
+
border-radius: 999px;
|
|
284
|
+
background: var(--dev-accent-soft);
|
|
285
|
+
color: var(--dev-accent);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
.new-btn {
|
|
289
|
+
appearance: none;
|
|
290
|
+
border: 1px solid var(--dev-border);
|
|
291
|
+
background: var(--dev-surface);
|
|
292
|
+
color: var(--dev-text);
|
|
293
|
+
border-radius: 6px;
|
|
294
|
+
padding: 4px 10px;
|
|
295
|
+
font-size: 12px;
|
|
296
|
+
font-weight: 500;
|
|
297
|
+
cursor: pointer;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
.new-btn:hover {
|
|
301
|
+
border-color: var(--dev-accent);
|
|
302
|
+
color: var(--dev-accent);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
.new-form {
|
|
306
|
+
display: none;
|
|
307
|
+
padding: 10px 12px;
|
|
308
|
+
border-block-end: 1px solid var(--dev-border);
|
|
309
|
+
gap: 6px;
|
|
310
|
+
flex-direction: column;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
.new-form.open {
|
|
314
|
+
display: flex;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
.new-form input {
|
|
318
|
+
width: 100%;
|
|
319
|
+
padding: 6px 8px;
|
|
320
|
+
border: 1px solid var(--dev-border);
|
|
321
|
+
border-radius: 6px;
|
|
322
|
+
background: var(--dev-bg);
|
|
323
|
+
color: var(--dev-text);
|
|
324
|
+
font-size: 13px;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
.new-form-actions {
|
|
328
|
+
display: flex;
|
|
329
|
+
gap: 6px;
|
|
330
|
+
justify-content: flex-end;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
.status-bar {
|
|
334
|
+
display: flex;
|
|
335
|
+
align-items: center;
|
|
336
|
+
justify-content: space-between;
|
|
337
|
+
gap: 8px;
|
|
338
|
+
padding: 8px 14px;
|
|
339
|
+
font-size: 12px;
|
|
340
|
+
color: var(--dev-muted);
|
|
341
|
+
border-block-end: 1px solid var(--dev-border);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
.live-pill {
|
|
345
|
+
display: inline-flex;
|
|
346
|
+
align-items: center;
|
|
347
|
+
gap: 6px;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
.dot {
|
|
351
|
+
width: 8px;
|
|
352
|
+
height: 8px;
|
|
353
|
+
border-radius: 50%;
|
|
354
|
+
background: var(--dev-warn);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
.dot.connected {
|
|
358
|
+
background: var(--dev-ok);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
.file-nav {
|
|
362
|
+
flex: 1;
|
|
363
|
+
overflow-y: auto;
|
|
364
|
+
padding: 8px;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
.file-list {
|
|
368
|
+
list-style: none;
|
|
369
|
+
margin: 0;
|
|
370
|
+
padding: 0;
|
|
371
|
+
display: flex;
|
|
372
|
+
flex-direction: column;
|
|
373
|
+
gap: 2px;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
.file-button {
|
|
377
|
+
width: 100%;
|
|
378
|
+
text-align: start;
|
|
379
|
+
appearance: none;
|
|
380
|
+
border: 0;
|
|
381
|
+
background: transparent;
|
|
382
|
+
color: var(--dev-text);
|
|
383
|
+
border-radius: 6px;
|
|
384
|
+
padding: 7px 10px;
|
|
385
|
+
font-size: 13px;
|
|
386
|
+
cursor: pointer;
|
|
387
|
+
overflow: hidden;
|
|
388
|
+
text-overflow: ellipsis;
|
|
389
|
+
white-space: nowrap;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
.file-button:hover {
|
|
393
|
+
background: var(--dev-bg);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
.file-button[aria-current="page"] {
|
|
397
|
+
background: var(--dev-accent-soft);
|
|
398
|
+
color: var(--dev-accent);
|
|
399
|
+
font-weight: 600;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
.sidebar-foot {
|
|
403
|
+
padding: 10px 14px;
|
|
404
|
+
border-block-start: 1px solid var(--dev-border);
|
|
405
|
+
font-size: 11px;
|
|
406
|
+
color: var(--dev-muted);
|
|
407
|
+
display: flex;
|
|
408
|
+
flex-direction: column;
|
|
409
|
+
gap: 4px;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
.sidebar-foot code {
|
|
413
|
+
display: block;
|
|
414
|
+
overflow: hidden;
|
|
415
|
+
text-overflow: ellipsis;
|
|
416
|
+
white-space: nowrap;
|
|
417
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
418
|
+
font-size: 11px;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
.main {
|
|
422
|
+
flex: 1;
|
|
423
|
+
min-width: 0;
|
|
424
|
+
display: flex;
|
|
425
|
+
flex-direction: column;
|
|
426
|
+
height: 100%;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
.banner {
|
|
430
|
+
display: none;
|
|
431
|
+
padding: 10px 16px;
|
|
432
|
+
background: var(--dev-danger-soft);
|
|
433
|
+
color: var(--dev-danger);
|
|
434
|
+
border-block-end: 1px solid var(--dev-border);
|
|
435
|
+
font-size: 13px;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
.banner.visible {
|
|
439
|
+
display: block;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
mail-quilt-shell {
|
|
443
|
+
flex: 1;
|
|
444
|
+
min-height: 0;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
@media (max-width: 720px) {
|
|
448
|
+
.layout {
|
|
449
|
+
flex-direction: column;
|
|
450
|
+
}
|
|
451
|
+
.sidebar {
|
|
452
|
+
width: 100%;
|
|
453
|
+
max-height: 190px;
|
|
454
|
+
border-inline-end: 0;
|
|
455
|
+
border-block-end: 1px solid var(--dev-border);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
</style>
|
|
459
|
+
</head>
|
|
460
|
+
<body>
|
|
461
|
+
<div class="layout">
|
|
462
|
+
<aside class="sidebar" aria-label="Email files">
|
|
463
|
+
<div class="sidebar-head">
|
|
464
|
+
<div class="brand">
|
|
465
|
+
<span>Mail Quilt</span>
|
|
466
|
+
<span class="badge">dev</span>
|
|
467
|
+
</div>
|
|
468
|
+
<button id="new-email-toggle" class="new-btn" type="button">+ New</button>
|
|
469
|
+
</div>
|
|
470
|
+
|
|
471
|
+
<form id="new-email-form" class="new-form">
|
|
472
|
+
<input
|
|
473
|
+
id="new-email-name"
|
|
474
|
+
type="text"
|
|
475
|
+
placeholder="campaign.json"
|
|
476
|
+
aria-label="New email file name"
|
|
477
|
+
autocomplete="off"
|
|
478
|
+
/>
|
|
479
|
+
<div class="new-form-actions">
|
|
480
|
+
<button id="new-email-cancel" class="new-btn" type="button">Cancel</button>
|
|
481
|
+
<button class="new-btn" type="submit">Create</button>
|
|
482
|
+
</div>
|
|
483
|
+
</form>
|
|
484
|
+
|
|
485
|
+
<div class="status-bar">
|
|
486
|
+
<span class="live-pill">
|
|
487
|
+
<span id="live-dot" class="dot" aria-hidden="true"></span>
|
|
488
|
+
<span id="live-label">Connecting…</span>
|
|
489
|
+
</span>
|
|
490
|
+
<span id="save-status" aria-live="polite"></span>
|
|
491
|
+
</div>
|
|
492
|
+
|
|
493
|
+
<nav class="file-nav" aria-label="Workspace emails">
|
|
494
|
+
<ul id="file-list" class="file-list"></ul>
|
|
495
|
+
</nav>
|
|
496
|
+
|
|
497
|
+
<div class="sidebar-foot">
|
|
498
|
+
<span title="${safeRoot}">Folder: <code>${safeRoot}</code></span>
|
|
499
|
+
<span title="MAILQUILT_DEV_URL=${safeOrigin}">MCP: <code>MAILQUILT_DEV_URL=${safeOrigin}</code></span>
|
|
500
|
+
</div>
|
|
501
|
+
</aside>
|
|
502
|
+
|
|
503
|
+
<main class="main">
|
|
504
|
+
<div id="error-banner" class="banner" role="alert"></div>
|
|
505
|
+
<mail-quilt-shell id="editor-shell" theme="auto"></mail-quilt-shell>
|
|
506
|
+
</main>
|
|
507
|
+
</div>
|
|
508
|
+
|
|
509
|
+
<script type="module">
|
|
510
|
+
import "/_mailquilt/cdn/index.js";
|
|
511
|
+
|
|
512
|
+
const shell = document.getElementById("editor-shell");
|
|
513
|
+
const fileList = document.getElementById("file-list");
|
|
514
|
+
const saveStatus = document.getElementById("save-status");
|
|
515
|
+
const liveDot = document.getElementById("live-dot");
|
|
516
|
+
const liveLabel = document.getElementById("live-label");
|
|
517
|
+
const errorBanner = document.getElementById("error-banner");
|
|
518
|
+
const newToggle = document.getElementById("new-email-toggle");
|
|
519
|
+
const newForm = document.getElementById("new-email-form");
|
|
520
|
+
const newInput = document.getElementById("new-email-name");
|
|
521
|
+
const newCancel = document.getElementById("new-email-cancel");
|
|
522
|
+
|
|
523
|
+
let files = [];
|
|
524
|
+
let activeFile = null;
|
|
525
|
+
let lastSyncedJson = "";
|
|
526
|
+
let saveTimer = null;
|
|
527
|
+
|
|
528
|
+
const showError = (message) => {
|
|
529
|
+
if (!message) {
|
|
530
|
+
errorBanner.textContent = "";
|
|
531
|
+
errorBanner.classList.remove("visible");
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
errorBanner.textContent = message;
|
|
535
|
+
errorBanner.classList.add("visible");
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
const setStatus = (text) => {
|
|
539
|
+
saveStatus.textContent = text;
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
const renderFileList = () => {
|
|
543
|
+
fileList.textContent = "";
|
|
544
|
+
for (const file of files) {
|
|
545
|
+
const item = document.createElement("li");
|
|
546
|
+
const button = document.createElement("button");
|
|
547
|
+
button.type = "button";
|
|
548
|
+
button.className = "file-button";
|
|
549
|
+
button.textContent = file;
|
|
550
|
+
button.title = file;
|
|
551
|
+
if (file === activeFile) {
|
|
552
|
+
button.setAttribute("aria-current", "page");
|
|
553
|
+
}
|
|
554
|
+
button.addEventListener("click", () => {
|
|
555
|
+
if (file !== activeFile) {
|
|
556
|
+
void openFile(file);
|
|
557
|
+
}
|
|
558
|
+
});
|
|
559
|
+
item.append(button);
|
|
560
|
+
fileList.append(item);
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
const updateUrl = (file) => {
|
|
565
|
+
const nextUrl = new URL(window.location.href);
|
|
566
|
+
if (file) {
|
|
567
|
+
nextUrl.searchParams.set("file", file);
|
|
568
|
+
} else {
|
|
569
|
+
nextUrl.searchParams.delete("file");
|
|
570
|
+
}
|
|
571
|
+
window.history.replaceState(null, "", nextUrl);
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
const openFile = async (file, { fromDisk = false } = {}) => {
|
|
575
|
+
clearTimeout(saveTimer);
|
|
576
|
+
activeFile = file;
|
|
577
|
+
updateUrl(file);
|
|
578
|
+
renderFileList();
|
|
579
|
+
shell.heading = file;
|
|
580
|
+
|
|
581
|
+
const response = await fetch(
|
|
582
|
+
"/api/email?file=" + encodeURIComponent(file),
|
|
583
|
+
{ cache: "no-store" }
|
|
584
|
+
);
|
|
585
|
+
const payload = await response.json();
|
|
586
|
+
if (!response.ok) {
|
|
587
|
+
showError(
|
|
588
|
+
"Cannot open " + file + ": " + (payload.reason || payload.error || response.statusText)
|
|
589
|
+
);
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
showError("");
|
|
593
|
+
const serialized = JSON.stringify(payload.document);
|
|
594
|
+
if (fromDisk && serialized === lastSyncedJson) {
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
lastSyncedJson = serialized;
|
|
598
|
+
shell.value = payload.document;
|
|
599
|
+
setStatus(fromDisk ? "Reloaded" : "Loaded");
|
|
600
|
+
};
|
|
601
|
+
|
|
602
|
+
const refreshFiles = async ({ selectInitial = false } = {}) => {
|
|
603
|
+
const response = await fetch("/api/emails", { cache: "no-store" });
|
|
604
|
+
const payload = await response.json();
|
|
605
|
+
files = Array.isArray(payload.files) ? payload.files : [];
|
|
606
|
+
renderFileList();
|
|
607
|
+
|
|
608
|
+
if (selectInitial) {
|
|
609
|
+
const requested = new URL(window.location.href).searchParams.get("file");
|
|
610
|
+
const target =
|
|
611
|
+
requested && files.includes(requested) ? requested : files[0] ?? null;
|
|
612
|
+
if (target) {
|
|
613
|
+
await openFile(target);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
const saveCurrentDocument = async (file, doc) => {
|
|
619
|
+
const serialized = JSON.stringify(doc);
|
|
620
|
+
if (serialized === lastSyncedJson) {
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
setStatus("Saving…");
|
|
624
|
+
const response = await fetch(
|
|
625
|
+
"/api/email?file=" + encodeURIComponent(file),
|
|
626
|
+
{
|
|
627
|
+
body: serialized,
|
|
628
|
+
headers: { "content-type": "application/json" },
|
|
629
|
+
method: "PUT",
|
|
630
|
+
}
|
|
631
|
+
);
|
|
632
|
+
const payload = await response.json();
|
|
633
|
+
if (!response.ok) {
|
|
634
|
+
showError(
|
|
635
|
+
"Save refused for " + file + ": " + (payload.reason || payload.error || response.statusText)
|
|
636
|
+
);
|
|
637
|
+
setStatus("Save failed");
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
showError("");
|
|
641
|
+
lastSyncedJson = JSON.stringify(payload.document);
|
|
642
|
+
setStatus("Saved");
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
shell.addEventListener("mq-change", (event) => {
|
|
646
|
+
const file = activeFile;
|
|
647
|
+
const doc = event.detail?.document;
|
|
648
|
+
if (!file || !doc) {
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
const serialized = JSON.stringify(doc);
|
|
652
|
+
if (serialized === lastSyncedJson) {
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
setStatus("Unsaved…");
|
|
656
|
+
clearTimeout(saveTimer);
|
|
657
|
+
saveTimer = setTimeout(() => {
|
|
658
|
+
void saveCurrentDocument(file, doc);
|
|
659
|
+
}, 200);
|
|
660
|
+
});
|
|
661
|
+
|
|
662
|
+
shell.addEventListener("mq-error", (event) => {
|
|
663
|
+
if (event.detail?.reason) {
|
|
664
|
+
showError(event.detail.reason);
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
newToggle.addEventListener("click", () => {
|
|
669
|
+
newForm.classList.toggle("open");
|
|
670
|
+
if (newForm.classList.contains("open")) {
|
|
671
|
+
newInput.value = "";
|
|
672
|
+
newInput.focus();
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
|
|
676
|
+
newCancel.addEventListener("click", () => {
|
|
677
|
+
newForm.classList.remove("open");
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
newForm.addEventListener("submit", async (event) => {
|
|
681
|
+
event.preventDefault();
|
|
682
|
+
let name = newInput.value.trim();
|
|
683
|
+
if (!name) {
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (!name.toLowerCase().endsWith(".json")) {
|
|
687
|
+
name += ".json";
|
|
688
|
+
}
|
|
689
|
+
const response = await fetch("/api/emails", {
|
|
690
|
+
body: JSON.stringify({ file: name }),
|
|
691
|
+
headers: { "content-type": "application/json" },
|
|
692
|
+
method: "POST",
|
|
693
|
+
});
|
|
694
|
+
const payload = await response.json();
|
|
695
|
+
if (!response.ok) {
|
|
696
|
+
showError(payload.reason || payload.error || "Could not create email.");
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
showError("");
|
|
700
|
+
newForm.classList.remove("open");
|
|
701
|
+
await refreshFiles();
|
|
702
|
+
await openFile(payload.file);
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
const connectEvents = () => {
|
|
706
|
+
const source = new EventSource("/api/events");
|
|
707
|
+
source.addEventListener("connected", (event) => {
|
|
708
|
+
liveDot.classList.add("connected");
|
|
709
|
+
liveLabel.textContent = "Live";
|
|
710
|
+
try {
|
|
711
|
+
const payload = JSON.parse(event.data);
|
|
712
|
+
if (Array.isArray(payload.files)) {
|
|
713
|
+
files = payload.files;
|
|
714
|
+
renderFileList();
|
|
715
|
+
}
|
|
716
|
+
} catch {
|
|
717
|
+
// Ignore malformed keepalive data.
|
|
718
|
+
}
|
|
719
|
+
});
|
|
720
|
+
source.addEventListener("email-changed", (event) => {
|
|
721
|
+
try {
|
|
722
|
+
const payload = JSON.parse(event.data);
|
|
723
|
+
if (Array.isArray(payload.files)) {
|
|
724
|
+
files = payload.files;
|
|
725
|
+
renderFileList();
|
|
726
|
+
}
|
|
727
|
+
if (payload.file && payload.file === activeFile) {
|
|
728
|
+
void openFile(activeFile, { fromDisk: true });
|
|
729
|
+
}
|
|
730
|
+
} catch {
|
|
731
|
+
// Ignore malformed event payload.
|
|
732
|
+
}
|
|
733
|
+
});
|
|
734
|
+
source.addEventListener("files-changed", (event) => {
|
|
735
|
+
try {
|
|
736
|
+
const payload = JSON.parse(event.data);
|
|
737
|
+
if (Array.isArray(payload.files)) {
|
|
738
|
+
files = payload.files;
|
|
739
|
+
renderFileList();
|
|
740
|
+
if (activeFile && !files.includes(activeFile) && files[0]) {
|
|
741
|
+
void openFile(files[0]);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
} catch {
|
|
745
|
+
// Ignore malformed event payload.
|
|
746
|
+
}
|
|
747
|
+
});
|
|
748
|
+
source.onerror = () => {
|
|
749
|
+
liveDot.classList.remove("connected");
|
|
750
|
+
liveLabel.textContent = "Reconnecting…";
|
|
751
|
+
};
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
await refreshFiles({ selectInitial: true });
|
|
755
|
+
connectEvents();
|
|
756
|
+
<\/script>
|
|
757
|
+
</body>
|
|
758
|
+
</html>
|
|
759
|
+
`;
|
|
760
|
+
};
|
|
761
|
+
// src/dev/server.ts
|
|
762
|
+
const MAX_BODY_BYTES = 5242880;
|
|
763
|
+
const WATCH_DEBOUNCE_MS = 40;
|
|
764
|
+
const BROWSER_SAVE_TTL_MS = 2e3;
|
|
765
|
+
const SSE_HEARTBEAT_MS = 25e3;
|
|
766
|
+
const HOST_HEADER_PATTERN = /^(?:127\.0\.0\.1|localhost)(?::(?<port>\d{1,5}))?$/iu;
|
|
767
|
+
const require = createRequire(import.meta.url);
|
|
768
|
+
const defaultEditorCdnDir = () => {
|
|
769
|
+
const pkgPath = require.resolve("@mailquilt/editor/package.json");
|
|
770
|
+
return path.join(path.dirname(pkgPath), "dist", "cdn");
|
|
771
|
+
};
|
|
772
|
+
const sha256 = (text) => createHash("sha256").update(text).digest("hex");
|
|
773
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
774
|
+
const isJsonEmailPath = (file) => {
|
|
775
|
+
if (file.trim() === "" || file.includes("\0")) return false;
|
|
776
|
+
const normalized = file.replaceAll("\\", "/");
|
|
777
|
+
if (normalized.split("/").some((segment) => segment.startsWith("."))) return false;
|
|
778
|
+
return normalized.toLowerCase().endsWith(".json");
|
|
779
|
+
};
|
|
780
|
+
const createStarterEmail = () => {
|
|
781
|
+
const editor = createEditor({ document: createEmail() });
|
|
782
|
+
const firstBlockId = editor.getDocument().rows[0]?.columns[0]?.blocks[0]?.id;
|
|
783
|
+
editor.apply({
|
|
784
|
+
settings: {
|
|
785
|
+
language: "en",
|
|
786
|
+
preheader: "Edit locally or with your AI coding agent via MCP."
|
|
787
|
+
},
|
|
788
|
+
type: "updateEmailSettings"
|
|
789
|
+
});
|
|
790
|
+
editor.apply({
|
|
791
|
+
blockType: "heading",
|
|
792
|
+
props: {
|
|
793
|
+
content: {
|
|
794
|
+
content: [{
|
|
795
|
+
content: [{
|
|
796
|
+
text: "Welcome to Mail Quilt",
|
|
797
|
+
type: "text"
|
|
798
|
+
}],
|
|
799
|
+
type: "paragraph"
|
|
800
|
+
}],
|
|
801
|
+
type: "doc"
|
|
802
|
+
},
|
|
803
|
+
level: 1
|
|
804
|
+
},
|
|
805
|
+
rowIndex: 0,
|
|
806
|
+
type: "insertBlockInNewRow"
|
|
807
|
+
});
|
|
808
|
+
if (firstBlockId !== void 0) editor.apply({
|
|
809
|
+
blockId: firstBlockId,
|
|
810
|
+
props: { content: {
|
|
811
|
+
content: [{
|
|
812
|
+
content: [{
|
|
813
|
+
text: "Changes saved here write directly to welcome.json, and edits from disk or MCP reload live.",
|
|
814
|
+
type: "text"
|
|
815
|
+
}],
|
|
816
|
+
type: "paragraph"
|
|
817
|
+
}],
|
|
818
|
+
type: "doc"
|
|
819
|
+
} },
|
|
820
|
+
type: "updateBlockProps"
|
|
821
|
+
});
|
|
822
|
+
editor.apply({
|
|
823
|
+
blockType: "button",
|
|
824
|
+
props: {
|
|
825
|
+
href: "https://editor.mailquilt.com",
|
|
826
|
+
label: "Read the docs"
|
|
827
|
+
},
|
|
828
|
+
rowIndex: 2,
|
|
829
|
+
type: "insertBlockInNewRow"
|
|
830
|
+
});
|
|
831
|
+
const loaded = loadDocument(editor.getDocument());
|
|
832
|
+
if (!loaded.ok) throw new Error(`Starter email failed validation: ${loaded.reason}`);
|
|
833
|
+
return loaded.document;
|
|
834
|
+
};
|
|
835
|
+
const isWithinRoot = (root, candidate) => {
|
|
836
|
+
const relative = path.relative(root, candidate);
|
|
837
|
+
return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
838
|
+
};
|
|
839
|
+
/** Lists all `.json` email files inside `canonicalRoot`, sorted alphabetically. */
|
|
840
|
+
const listEmailFiles = async (canonicalRoot) => {
|
|
841
|
+
const collected = [];
|
|
842
|
+
const walk = async (currentDir, visitedDirs) => {
|
|
843
|
+
let entries;
|
|
844
|
+
try {
|
|
845
|
+
entries = await readdir(currentDir, { withFileTypes: true });
|
|
846
|
+
} catch {
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
await Promise.all(entries.map(async (entry) => {
|
|
850
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules") return;
|
|
851
|
+
const fullPath = path.join(currentDir, entry.name);
|
|
852
|
+
if (entry.isDirectory()) {
|
|
853
|
+
const realDir = await realpath(fullPath).catch(() => null);
|
|
854
|
+
if (realDir && isWithinRoot(canonicalRoot, realDir) && !visitedDirs.has(realDir)) {
|
|
855
|
+
visitedDirs.add(realDir);
|
|
856
|
+
await walk(realDir, visitedDirs);
|
|
857
|
+
}
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
if (entry.isFile() && entry.name.toLowerCase().endsWith(".json")) {
|
|
861
|
+
collected.push(path.relative(canonicalRoot, fullPath).split(path.sep).join("/"));
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if (entry.isSymbolicLink() && entry.name.toLowerCase().endsWith(".json")) {
|
|
865
|
+
const realFile = await realpath(fullPath).catch(() => null);
|
|
866
|
+
if (realFile && isWithinRoot(canonicalRoot, realFile)) collected.push(path.relative(canonicalRoot, fullPath).split(path.sep).join("/"));
|
|
867
|
+
}
|
|
868
|
+
}));
|
|
869
|
+
};
|
|
870
|
+
await walk(canonicalRoot, /* @__PURE__ */ new Set([canonicalRoot]));
|
|
871
|
+
return collected.toSorted((left, right) => left.localeCompare(right));
|
|
872
|
+
};
|
|
873
|
+
const isValidHostHeader = (hostHeader, port) => {
|
|
874
|
+
if (typeof hostHeader !== "string") return false;
|
|
875
|
+
const match = HOST_HEADER_PATTERN.exec(hostHeader.trim());
|
|
876
|
+
if (!match) return false;
|
|
877
|
+
const headerPort = match.groups?.port;
|
|
878
|
+
if (headerPort === void 0) return port === 80;
|
|
879
|
+
return headerPort === String(port);
|
|
880
|
+
};
|
|
881
|
+
const isValidOriginHeader = (originHeader, port) => {
|
|
882
|
+
if (originHeader === void 0) return true;
|
|
883
|
+
let parsed;
|
|
884
|
+
try {
|
|
885
|
+
parsed = new URL(originHeader);
|
|
886
|
+
} catch {
|
|
887
|
+
return false;
|
|
888
|
+
}
|
|
889
|
+
if (parsed.protocol !== "http:") return false;
|
|
890
|
+
if (parsed.hostname !== "127.0.0.1" && parsed.hostname !== "localhost") return false;
|
|
891
|
+
const expectedPort = port === 80 ? "" : String(port);
|
|
892
|
+
return parsed.port === expectedPort;
|
|
893
|
+
};
|
|
894
|
+
const isValidFetchSite = (req) => {
|
|
895
|
+
const site = req.headers["sec-fetch-site"];
|
|
896
|
+
if (site === void 0) return true;
|
|
897
|
+
return site === "same-origin" || site === "none";
|
|
898
|
+
};
|
|
899
|
+
const sendJson = (res, statusCode, payload) => {
|
|
900
|
+
const body = JSON.stringify(payload);
|
|
901
|
+
res.writeHead(statusCode, {
|
|
902
|
+
"cache-control": "no-store",
|
|
903
|
+
"content-length": String(Buffer.byteLength(body, "utf-8")),
|
|
904
|
+
"content-type": "application/json; charset=utf-8",
|
|
905
|
+
"referrer-policy": "no-referrer",
|
|
906
|
+
"x-content-type-options": "nosniff"
|
|
907
|
+
});
|
|
908
|
+
res.end(body);
|
|
909
|
+
};
|
|
910
|
+
const readBodyUtf8 = async (req) => {
|
|
911
|
+
const chunks = [];
|
|
912
|
+
let total = 0;
|
|
913
|
+
try {
|
|
914
|
+
for await (const chunk of req) {
|
|
915
|
+
const buffer = typeof chunk === "string" ? Buffer.from(chunk, "utf-8") : Buffer.from(chunk);
|
|
916
|
+
total += buffer.length;
|
|
917
|
+
if (total > MAX_BODY_BYTES) return {
|
|
918
|
+
error: `Request body exceeds ${MAX_BODY_BYTES} bytes.`,
|
|
919
|
+
ok: false,
|
|
920
|
+
status: 413
|
|
921
|
+
};
|
|
922
|
+
chunks.push(buffer);
|
|
923
|
+
}
|
|
924
|
+
} catch (error) {
|
|
925
|
+
return {
|
|
926
|
+
error: error instanceof Error ? error.message : String(error),
|
|
927
|
+
ok: false,
|
|
928
|
+
status: 400
|
|
929
|
+
};
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
ok: true,
|
|
933
|
+
text: Buffer.concat(chunks).toString("utf-8")
|
|
934
|
+
};
|
|
935
|
+
};
|
|
936
|
+
const contentTypeForAsset = (assetPath) => {
|
|
937
|
+
switch (path.extname(assetPath).toLowerCase()) {
|
|
938
|
+
case ".js":
|
|
939
|
+
case ".mjs": return "text/javascript; charset=utf-8";
|
|
940
|
+
case ".txt": return "text/plain; charset=utf-8";
|
|
941
|
+
case ".map": return "application/json; charset=utf-8";
|
|
942
|
+
default: return null;
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
/**
|
|
946
|
+
* Starts the localhost-only (`127.0.0.1`) Mail Quilt dev server watching `dir`
|
|
947
|
+
* for `.json` email files with live SSE reload and `loadDocument()` validation.
|
|
948
|
+
*/
|
|
949
|
+
const startDevServer = async (options) => {
|
|
950
|
+
const requestedPort = options.port ?? 4173;
|
|
951
|
+
const createStarterIfEmpty = options.createStarterIfEmpty ?? true;
|
|
952
|
+
const cdnDir = canonicalizeRoot(options.cdnDir ?? defaultEditorCdnDir());
|
|
953
|
+
await mkdir(options.dir, { recursive: true });
|
|
954
|
+
const canonicalRoot = canonicalizeRoot(options.dir);
|
|
955
|
+
let initialFiles = await listEmailFiles(canonicalRoot);
|
|
956
|
+
if (initialFiles.length === 0 && createStarterIfEmpty) {
|
|
957
|
+
const starter = createStarterEmail();
|
|
958
|
+
await writeWorkspaceFileAtomic(canonicalRoot, "welcome.json", `${JSON.stringify(starter, null, 2)}\n`, { overwrite: false });
|
|
959
|
+
initialFiles = await listEmailFiles(canonicalRoot);
|
|
960
|
+
}
|
|
961
|
+
const sseClients = /* @__PURE__ */ new Set();
|
|
962
|
+
const recentBrowserSaves = /* @__PURE__ */ new Map();
|
|
963
|
+
const pendingTimers = /* @__PURE__ */ new Map();
|
|
964
|
+
const broadcast = (event, data) => {
|
|
965
|
+
const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
966
|
+
for (const client of sseClients) try {
|
|
967
|
+
client.write(frame);
|
|
968
|
+
} catch {
|
|
969
|
+
sseClients.delete(client);
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
let actualPort = requestedPort;
|
|
973
|
+
let actualUrl = `http://127.0.0.1:${actualPort}`;
|
|
974
|
+
const handleCdnAsset = async (pathname, res) => {
|
|
975
|
+
let relativeAsset;
|
|
976
|
+
try {
|
|
977
|
+
relativeAsset = decodeURIComponent(pathname.slice(16));
|
|
978
|
+
} catch {
|
|
979
|
+
sendJson(res, 400, {
|
|
980
|
+
error: "Malformed asset path.",
|
|
981
|
+
ok: false
|
|
982
|
+
});
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
const contentType = contentTypeForAsset(relativeAsset);
|
|
986
|
+
if (contentType === null) {
|
|
987
|
+
sendJson(res, 403, {
|
|
988
|
+
error: "Unsupported asset type.",
|
|
989
|
+
ok: false
|
|
990
|
+
});
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
let resolved;
|
|
994
|
+
try {
|
|
995
|
+
resolved = await resolveWorkspaceReadPath(cdnDir, relativeAsset);
|
|
996
|
+
} catch (error) {
|
|
997
|
+
if (error instanceof WorkspacePathError) {
|
|
998
|
+
sendJson(res, error.code === "not_found" ? 404 : 403, {
|
|
999
|
+
error: error.message,
|
|
1000
|
+
ok: false
|
|
1001
|
+
});
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
sendJson(res, 500, {
|
|
1005
|
+
error: "Failed to resolve asset.",
|
|
1006
|
+
ok: false
|
|
1007
|
+
});
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
const data = await readFile(resolved.absolutePath);
|
|
1011
|
+
res.writeHead(200, {
|
|
1012
|
+
"cache-control": "no-cache",
|
|
1013
|
+
"content-length": String(data.length),
|
|
1014
|
+
"content-type": contentType,
|
|
1015
|
+
"referrer-policy": "no-referrer",
|
|
1016
|
+
"x-content-type-options": "nosniff"
|
|
1017
|
+
});
|
|
1018
|
+
res.end(data);
|
|
1019
|
+
};
|
|
1020
|
+
const handleGetEmail = async (fileParam, res) => {
|
|
1021
|
+
if (fileParam === null || !isJsonEmailPath(fileParam)) {
|
|
1022
|
+
sendJson(res, 403, {
|
|
1023
|
+
error: "Invalid or non-JSON email file path.",
|
|
1024
|
+
ok: false
|
|
1025
|
+
});
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
let content;
|
|
1029
|
+
let relativePath;
|
|
1030
|
+
try {
|
|
1031
|
+
const read = await readWorkspaceFile(canonicalRoot, fileParam);
|
|
1032
|
+
({content, relativePath} = read);
|
|
1033
|
+
} catch (error) {
|
|
1034
|
+
if (error instanceof WorkspacePathError) {
|
|
1035
|
+
sendJson(res, error.code === "not_found" ? 404 : 403, {
|
|
1036
|
+
code: error.code,
|
|
1037
|
+
error: error.message,
|
|
1038
|
+
ok: false
|
|
1039
|
+
});
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
sendJson(res, 500, {
|
|
1043
|
+
error: "Failed to read email.",
|
|
1044
|
+
ok: false
|
|
1045
|
+
});
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
let parsed;
|
|
1049
|
+
try {
|
|
1050
|
+
parsed = JSON.parse(content);
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
sendJson(res, 400, {
|
|
1053
|
+
error: "Invalid JSON",
|
|
1054
|
+
ok: false,
|
|
1055
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1056
|
+
});
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
const loaded = loadDocument(parsed);
|
|
1060
|
+
if (!loaded.ok) {
|
|
1061
|
+
sendJson(res, 400, {
|
|
1062
|
+
error: "Document refused",
|
|
1063
|
+
ok: false,
|
|
1064
|
+
reason: loaded.reason
|
|
1065
|
+
});
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
sendJson(res, 200, {
|
|
1069
|
+
document: loaded.document,
|
|
1070
|
+
file: relativePath,
|
|
1071
|
+
ok: true
|
|
1072
|
+
});
|
|
1073
|
+
};
|
|
1074
|
+
const handlePutEmail = async (fileParam, req, res) => {
|
|
1075
|
+
if (fileParam === null || !isJsonEmailPath(fileParam)) {
|
|
1076
|
+
sendJson(res, 403, {
|
|
1077
|
+
error: "Invalid or non-JSON email file path.",
|
|
1078
|
+
ok: false
|
|
1079
|
+
});
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
try {
|
|
1083
|
+
await resolveWorkspaceWritePath(canonicalRoot, fileParam);
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
if (error instanceof WorkspacePathError) {
|
|
1086
|
+
sendJson(res, 403, {
|
|
1087
|
+
code: error.code,
|
|
1088
|
+
error: error.message,
|
|
1089
|
+
ok: false
|
|
1090
|
+
});
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
sendJson(res, 500, {
|
|
1094
|
+
error: "Failed to validate path.",
|
|
1095
|
+
ok: false
|
|
1096
|
+
});
|
|
1097
|
+
return;
|
|
1098
|
+
}
|
|
1099
|
+
const body = await readBodyUtf8(req);
|
|
1100
|
+
if (!body.ok) {
|
|
1101
|
+
sendJson(res, body.status, {
|
|
1102
|
+
error: body.error,
|
|
1103
|
+
ok: false
|
|
1104
|
+
});
|
|
1105
|
+
return;
|
|
1106
|
+
}
|
|
1107
|
+
let parsed;
|
|
1108
|
+
try {
|
|
1109
|
+
parsed = JSON.parse(body.text);
|
|
1110
|
+
} catch (error) {
|
|
1111
|
+
sendJson(res, 400, {
|
|
1112
|
+
error: "Invalid JSON",
|
|
1113
|
+
ok: false,
|
|
1114
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1115
|
+
});
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
const loaded = loadDocument(parsed);
|
|
1119
|
+
if (!loaded.ok) {
|
|
1120
|
+
sendJson(res, 400, {
|
|
1121
|
+
error: "Document refused",
|
|
1122
|
+
ok: false,
|
|
1123
|
+
reason: loaded.reason
|
|
1124
|
+
});
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
const serialized = `${JSON.stringify(loaded.document, null, 2)}\n`;
|
|
1128
|
+
try {
|
|
1129
|
+
const written = await writeWorkspaceFileAtomic(canonicalRoot, fileParam, serialized, { overwrite: true });
|
|
1130
|
+
recentBrowserSaves.set(written.relativePath, {
|
|
1131
|
+
expiresAt: Date.now() + BROWSER_SAVE_TTL_MS,
|
|
1132
|
+
hash: sha256(serialized)
|
|
1133
|
+
});
|
|
1134
|
+
sendJson(res, 200, {
|
|
1135
|
+
document: loaded.document,
|
|
1136
|
+
file: written.relativePath,
|
|
1137
|
+
ok: true
|
|
1138
|
+
});
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
if (error instanceof WorkspacePathError) {
|
|
1141
|
+
sendJson(res, 403, {
|
|
1142
|
+
code: error.code,
|
|
1143
|
+
error: error.message,
|
|
1144
|
+
ok: false
|
|
1145
|
+
});
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
sendJson(res, 500, {
|
|
1149
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1150
|
+
ok: false
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
};
|
|
1154
|
+
const handleCreateEmail = async (req, res) => {
|
|
1155
|
+
const body = await readBodyUtf8(req);
|
|
1156
|
+
if (!body.ok) {
|
|
1157
|
+
sendJson(res, body.status, {
|
|
1158
|
+
error: body.error,
|
|
1159
|
+
ok: false
|
|
1160
|
+
});
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
let parsed;
|
|
1164
|
+
try {
|
|
1165
|
+
parsed = JSON.parse(body.text);
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
sendJson(res, 400, {
|
|
1168
|
+
error: "Invalid JSON",
|
|
1169
|
+
ok: false,
|
|
1170
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1171
|
+
});
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
if (!isRecord(parsed) || typeof parsed.file !== "string") {
|
|
1175
|
+
sendJson(res, 400, {
|
|
1176
|
+
error: "Request body must include a string \"file\" path.",
|
|
1177
|
+
ok: false
|
|
1178
|
+
});
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
if (!isJsonEmailPath(parsed.file)) {
|
|
1182
|
+
sendJson(res, 403, {
|
|
1183
|
+
error: "Email file path must be a non-hidden .json path.",
|
|
1184
|
+
ok: false
|
|
1185
|
+
});
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
const candidateDoc = parsed.document ?? createEmail();
|
|
1189
|
+
const loaded = loadDocument(candidateDoc);
|
|
1190
|
+
if (!loaded.ok) {
|
|
1191
|
+
sendJson(res, 400, {
|
|
1192
|
+
error: "Document refused",
|
|
1193
|
+
ok: false,
|
|
1194
|
+
reason: loaded.reason
|
|
1195
|
+
});
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
const serialized = `${JSON.stringify(loaded.document, null, 2)}\n`;
|
|
1199
|
+
try {
|
|
1200
|
+
const written = await writeWorkspaceFileAtomic(canonicalRoot, parsed.file, serialized, { overwrite: false });
|
|
1201
|
+
recentBrowserSaves.set(written.relativePath, {
|
|
1202
|
+
expiresAt: Date.now() + BROWSER_SAVE_TTL_MS,
|
|
1203
|
+
hash: sha256(serialized)
|
|
1204
|
+
});
|
|
1205
|
+
sendJson(res, 201, {
|
|
1206
|
+
document: loaded.document,
|
|
1207
|
+
file: written.relativePath,
|
|
1208
|
+
ok: true
|
|
1209
|
+
});
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
if (error instanceof WorkspacePathError) {
|
|
1212
|
+
sendJson(res, 403, {
|
|
1213
|
+
code: error.code,
|
|
1214
|
+
error: error.message,
|
|
1215
|
+
ok: false
|
|
1216
|
+
});
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1220
|
+
sendJson(res, message.includes("already exists") ? 409 : 500, {
|
|
1221
|
+
error: message,
|
|
1222
|
+
ok: false
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
};
|
|
1226
|
+
const handleSseEvents = async (req, res) => {
|
|
1227
|
+
res.writeHead(200, {
|
|
1228
|
+
"cache-control": "no-cache, no-transform",
|
|
1229
|
+
connection: "keep-alive",
|
|
1230
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
1231
|
+
"x-content-type-options": "nosniff"
|
|
1232
|
+
});
|
|
1233
|
+
sseClients.add(res);
|
|
1234
|
+
req.on("close", () => {
|
|
1235
|
+
sseClients.delete(res);
|
|
1236
|
+
});
|
|
1237
|
+
const files = await listEmailFiles(canonicalRoot);
|
|
1238
|
+
res.write(`event: connected\ndata: ${JSON.stringify({ files })}\n\n`);
|
|
1239
|
+
};
|
|
1240
|
+
const handleApiRoute = async (method, url, req, res) => {
|
|
1241
|
+
const { pathname } = url;
|
|
1242
|
+
if (method === "GET" && pathname === "/api/emails") {
|
|
1243
|
+
const files = await listEmailFiles(canonicalRoot);
|
|
1244
|
+
sendJson(res, 200, {
|
|
1245
|
+
files,
|
|
1246
|
+
ok: true,
|
|
1247
|
+
root: canonicalRoot
|
|
1248
|
+
});
|
|
1249
|
+
return true;
|
|
1250
|
+
}
|
|
1251
|
+
if (method === "POST" && pathname === "/api/emails") {
|
|
1252
|
+
await handleCreateEmail(req, res);
|
|
1253
|
+
return true;
|
|
1254
|
+
}
|
|
1255
|
+
if (method === "GET" && pathname === "/api/email") {
|
|
1256
|
+
await handleGetEmail(url.searchParams.get("file"), res);
|
|
1257
|
+
return true;
|
|
1258
|
+
}
|
|
1259
|
+
if (method === "PUT" && pathname === "/api/email") {
|
|
1260
|
+
await handlePutEmail(url.searchParams.get("file"), req, res);
|
|
1261
|
+
return true;
|
|
1262
|
+
}
|
|
1263
|
+
if (method === "GET" && pathname === "/api/events") {
|
|
1264
|
+
await handleSseEvents(req, res);
|
|
1265
|
+
return true;
|
|
1266
|
+
}
|
|
1267
|
+
return false;
|
|
1268
|
+
};
|
|
1269
|
+
const handleRequest = async (req, res) => {
|
|
1270
|
+
if (!isValidHostHeader(req.headers.host, actualPort)) {
|
|
1271
|
+
sendJson(res, 403, {
|
|
1272
|
+
error: "Forbidden Host header.",
|
|
1273
|
+
ok: false
|
|
1274
|
+
});
|
|
1275
|
+
return;
|
|
1276
|
+
}
|
|
1277
|
+
if (!isValidOriginHeader(req.headers.origin, actualPort)) {
|
|
1278
|
+
sendJson(res, 403, {
|
|
1279
|
+
error: "Forbidden Origin header.",
|
|
1280
|
+
ok: false
|
|
1281
|
+
});
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
const method = req.method ?? "GET";
|
|
1285
|
+
const url = new URL(req.url ?? "/", actualUrl);
|
|
1286
|
+
const { pathname } = url;
|
|
1287
|
+
if ((pathname.startsWith("/api/") || method === "PUT" || method === "POST") && !isValidFetchSite(req)) {
|
|
1288
|
+
sendJson(res, 403, {
|
|
1289
|
+
error: "Cross-site request refused.",
|
|
1290
|
+
ok: false
|
|
1291
|
+
});
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
1295
|
+
const html = renderDevHtml(canonicalRoot, actualUrl);
|
|
1296
|
+
res.writeHead(200, {
|
|
1297
|
+
"cache-control": "no-store",
|
|
1298
|
+
"content-length": String(Buffer.byteLength(html, "utf-8")),
|
|
1299
|
+
"content-type": "text/html; charset=utf-8",
|
|
1300
|
+
"referrer-policy": "no-referrer",
|
|
1301
|
+
"x-content-type-options": "nosniff",
|
|
1302
|
+
"x-frame-options": "SAMEORIGIN"
|
|
1303
|
+
});
|
|
1304
|
+
res.end(html);
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
if (method === "GET" && pathname.startsWith("/_mailquilt/cdn/")) {
|
|
1308
|
+
await handleCdnAsset(pathname, res);
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
if (await handleApiRoute(method, url, req, res)) return;
|
|
1312
|
+
sendJson(res, 404, {
|
|
1313
|
+
error: "Not found.",
|
|
1314
|
+
ok: false
|
|
1315
|
+
});
|
|
1316
|
+
};
|
|
1317
|
+
const runRequest = async (req, res) => {
|
|
1318
|
+
try {
|
|
1319
|
+
await handleRequest(req, res);
|
|
1320
|
+
} catch (error) {
|
|
1321
|
+
if (!res.headersSent) sendJson(res, 500, {
|
|
1322
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1323
|
+
ok: false
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
const server = createServer((req, res) => {
|
|
1328
|
+
runRequest(req, res);
|
|
1329
|
+
});
|
|
1330
|
+
server.listen(requestedPort, "127.0.0.1");
|
|
1331
|
+
await once(server, "listening");
|
|
1332
|
+
actualPort = server.address().port;
|
|
1333
|
+
actualUrl = `http://127.0.0.1:${actualPort}`;
|
|
1334
|
+
const scheduleWatchEvent = (filename) => {
|
|
1335
|
+
if (!filename) return;
|
|
1336
|
+
const relative = filename.replaceAll("\\", "/");
|
|
1337
|
+
if (!isJsonEmailPath(relative)) return;
|
|
1338
|
+
const existing = pendingTimers.get(relative);
|
|
1339
|
+
if (existing !== void 0) clearTimeout(existing);
|
|
1340
|
+
const timer = setTimeout(() => {
|
|
1341
|
+
pendingTimers.delete(relative);
|
|
1342
|
+
(async () => {
|
|
1343
|
+
const files = await listEmailFiles(canonicalRoot);
|
|
1344
|
+
if (!files.includes(relative)) {
|
|
1345
|
+
broadcast("files-changed", {
|
|
1346
|
+
file: relative,
|
|
1347
|
+
files
|
|
1348
|
+
});
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
let source = "disk";
|
|
1352
|
+
const recorded = recentBrowserSaves.get(relative);
|
|
1353
|
+
if (recorded !== void 0) {
|
|
1354
|
+
if (Date.now() > recorded.expiresAt) recentBrowserSaves.delete(relative);
|
|
1355
|
+
else {
|
|
1356
|
+
const diskText = await readFile(path.join(canonicalRoot, relative), "utf-8").catch(() => null);
|
|
1357
|
+
if (diskText !== null && sha256(diskText) === recorded.hash) source = "browser";
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
broadcast("email-changed", {
|
|
1361
|
+
file: relative,
|
|
1362
|
+
files,
|
|
1363
|
+
source
|
|
1364
|
+
});
|
|
1365
|
+
})();
|
|
1366
|
+
}, WATCH_DEBOUNCE_MS);
|
|
1367
|
+
timer.unref();
|
|
1368
|
+
pendingTimers.set(relative, timer);
|
|
1369
|
+
};
|
|
1370
|
+
let watcher;
|
|
1371
|
+
try {
|
|
1372
|
+
watcher = watch(canonicalRoot, { recursive: true }, (_event, filename) => {
|
|
1373
|
+
scheduleWatchEvent(typeof filename === "string" ? filename : null);
|
|
1374
|
+
});
|
|
1375
|
+
} catch {
|
|
1376
|
+
watcher = watch(canonicalRoot, (_event, filename) => {
|
|
1377
|
+
scheduleWatchEvent(typeof filename === "string" ? filename : null);
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
watcher.on("error", () => {});
|
|
1381
|
+
const heartbeat = setInterval(() => {
|
|
1382
|
+
for (const client of sseClients) try {
|
|
1383
|
+
client.write(": keepalive\n\n");
|
|
1384
|
+
} catch {
|
|
1385
|
+
sseClients.delete(client);
|
|
1386
|
+
}
|
|
1387
|
+
}, SSE_HEARTBEAT_MS);
|
|
1388
|
+
heartbeat.unref();
|
|
1389
|
+
let closed = false;
|
|
1390
|
+
const close = async () => {
|
|
1391
|
+
if (closed) return;
|
|
1392
|
+
closed = true;
|
|
1393
|
+
clearInterval(heartbeat);
|
|
1394
|
+
for (const timer of pendingTimers.values()) clearTimeout(timer);
|
|
1395
|
+
pendingTimers.clear();
|
|
1396
|
+
watcher?.close();
|
|
1397
|
+
for (const client of sseClients) client.end();
|
|
1398
|
+
sseClients.clear();
|
|
1399
|
+
await promisify(server.close.bind(server))();
|
|
1400
|
+
};
|
|
1401
|
+
return {
|
|
1402
|
+
close,
|
|
1403
|
+
dir: canonicalRoot,
|
|
1404
|
+
files: initialFiles,
|
|
1405
|
+
port: actualPort,
|
|
1406
|
+
url: actualUrl
|
|
1407
|
+
};
|
|
1408
|
+
};
|
|
1409
|
+
// src/commands/dev.ts
|
|
1410
|
+
const DEV_HELP = `Usage: mailquilt dev [dir] [options]
|
|
1411
|
+
|
|
1412
|
+
Start the localhost-only Mail Quilt live editor & preview server over a folder
|
|
1413
|
+
of email JSON files (default: ./emails).
|
|
1414
|
+
|
|
1415
|
+
Options:
|
|
1416
|
+
--port <port> Port to bind on 127.0.0.1 (default: 4173)
|
|
1417
|
+
--open Open the editor URL in your default browser
|
|
1418
|
+
-h, --help Show this help message
|
|
1419
|
+
`;
|
|
1420
|
+
const errorMessage$2 = (error) => error instanceof Error ? error.message : String(error);
|
|
1421
|
+
const browserOpenCommand = (url) => {
|
|
1422
|
+
if (process.platform === "darwin") return {
|
|
1423
|
+
args: [url],
|
|
1424
|
+
command: "open"
|
|
1425
|
+
};
|
|
1426
|
+
if (process.platform === "win32") return {
|
|
1427
|
+
args: [
|
|
1428
|
+
"/c",
|
|
1429
|
+
"start",
|
|
1430
|
+
"",
|
|
1431
|
+
url
|
|
1432
|
+
],
|
|
1433
|
+
command: "cmd"
|
|
1434
|
+
};
|
|
1435
|
+
return {
|
|
1436
|
+
args: [url],
|
|
1437
|
+
command: "xdg-open"
|
|
1438
|
+
};
|
|
1439
|
+
};
|
|
1440
|
+
const openInBrowser = (url) => {
|
|
1441
|
+
const opener = browserOpenCommand(url);
|
|
1442
|
+
try {
|
|
1443
|
+
const child = spawn(opener.command, opener.args, {
|
|
1444
|
+
detached: true,
|
|
1445
|
+
stdio: "ignore"
|
|
1446
|
+
});
|
|
1447
|
+
child.on("error", () => {});
|
|
1448
|
+
child.unref();
|
|
1449
|
+
} catch {}
|
|
1450
|
+
};
|
|
1451
|
+
const waitForTerminationSignal = async () => {
|
|
1452
|
+
const controller = new AbortController();
|
|
1453
|
+
try {
|
|
1454
|
+
await Promise.race([once(process, "SIGINT", { signal: controller.signal }), once(process, "SIGTERM", { signal: controller.signal })]);
|
|
1455
|
+
} finally {
|
|
1456
|
+
controller.abort();
|
|
1457
|
+
}
|
|
1458
|
+
};
|
|
1459
|
+
const runDev = async (args, io) => {
|
|
1460
|
+
let parsed;
|
|
1461
|
+
try {
|
|
1462
|
+
parsed = parseArgs({
|
|
1463
|
+
allowPositionals: true,
|
|
1464
|
+
args: [...args],
|
|
1465
|
+
options: {
|
|
1466
|
+
help: {
|
|
1467
|
+
short: "h",
|
|
1468
|
+
type: "boolean"
|
|
1469
|
+
},
|
|
1470
|
+
open: { type: "boolean" },
|
|
1471
|
+
port: { type: "string" }
|
|
1472
|
+
},
|
|
1473
|
+
strict: true
|
|
1474
|
+
});
|
|
1475
|
+
} catch (error) {
|
|
1476
|
+
io.stderr.write(`mailquilt dev: ${errorMessage$2(error)}\n`);
|
|
1477
|
+
return 1;
|
|
1478
|
+
}
|
|
1479
|
+
if (parsed.values.help) {
|
|
1480
|
+
io.stdout.write(DEV_HELP);
|
|
1481
|
+
return 0;
|
|
1482
|
+
}
|
|
1483
|
+
if (parsed.positionals.length > 1) {
|
|
1484
|
+
io.stderr.write("mailquilt dev: expected at most one [dir] argument.\n");
|
|
1485
|
+
return 1;
|
|
1486
|
+
}
|
|
1487
|
+
let port = 4173;
|
|
1488
|
+
if (typeof parsed.values.port === "string") {
|
|
1489
|
+
if (!/^\d+$/u.test(parsed.values.port)) {
|
|
1490
|
+
io.stderr.write(`mailquilt dev: invalid --port "${parsed.values.port}".\n`);
|
|
1491
|
+
return 1;
|
|
1492
|
+
}
|
|
1493
|
+
port = Number(parsed.values.port);
|
|
1494
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
1495
|
+
io.stderr.write("mailquilt dev: --port must be between 0 and 65535.\n");
|
|
1496
|
+
return 1;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
const cwd = io.cwd ?? process.cwd();
|
|
1500
|
+
const dir = path.resolve(cwd, parsed.positionals[0] ?? "./emails");
|
|
1501
|
+
let handle;
|
|
1502
|
+
try {
|
|
1503
|
+
handle = await startDevServer({
|
|
1504
|
+
dir,
|
|
1505
|
+
port
|
|
1506
|
+
});
|
|
1507
|
+
} catch (error) {
|
|
1508
|
+
io.stderr.write(`mailquilt dev: ${errorMessage$2(error)}\n`);
|
|
1509
|
+
return 1;
|
|
1510
|
+
}
|
|
1511
|
+
const count = handle.files.length;
|
|
1512
|
+
const noun = count === 1 ? "email" : "emails";
|
|
1513
|
+
io.stdout.write(`Mail Quilt dev server running at ${handle.url}\n`);
|
|
1514
|
+
io.stdout.write(`Watching: ${handle.dir} (${count} ${noun})\n`);
|
|
1515
|
+
io.stdout.write(`MCP preview URL: MAILQUILT_DEV_URL=${handle.url}\n`);
|
|
1516
|
+
if (parsed.values.open === true) openInBrowser(handle.url);
|
|
1517
|
+
try {
|
|
1518
|
+
await waitForTerminationSignal();
|
|
1519
|
+
} finally {
|
|
1520
|
+
await handle.close();
|
|
1521
|
+
}
|
|
1522
|
+
return 0;
|
|
1523
|
+
};
|
|
1524
|
+
// src/commands/mcp.ts
|
|
1525
|
+
const MCP_HELP = `Usage: mailquilt mcp [options]
|
|
1526
|
+
|
|
1527
|
+
Start the Mail Quilt MCP server over stdio.
|
|
1528
|
+
|
|
1529
|
+
Options:
|
|
1530
|
+
--root <dir> Workspace root directory (default: current working directory)
|
|
1531
|
+
--dev-url <url> Active mailquilt dev URL (default: MAILQUILT_DEV_URL)
|
|
1532
|
+
-h, --help Show this help message
|
|
1533
|
+
`;
|
|
1534
|
+
const errorMessage$1 = (error) => error instanceof Error ? error.message : String(error);
|
|
1535
|
+
const runMcp = async (args, io) => {
|
|
1536
|
+
let parsed;
|
|
1537
|
+
try {
|
|
1538
|
+
parsed = parseArgs({
|
|
1539
|
+
allowPositionals: false,
|
|
1540
|
+
args: [...args],
|
|
1541
|
+
options: {
|
|
1542
|
+
"dev-url": { type: "string" },
|
|
1543
|
+
help: {
|
|
1544
|
+
short: "h",
|
|
1545
|
+
type: "boolean"
|
|
1546
|
+
},
|
|
1547
|
+
root: { type: "string" }
|
|
1548
|
+
},
|
|
1549
|
+
strict: true
|
|
1550
|
+
});
|
|
1551
|
+
} catch (error) {
|
|
1552
|
+
io.stderr.write(`mailquilt mcp: ${errorMessage$1(error)}\n`);
|
|
1553
|
+
return 1;
|
|
1554
|
+
}
|
|
1555
|
+
if (parsed.values.help) {
|
|
1556
|
+
io.stdout.write(MCP_HELP);
|
|
1557
|
+
return 0;
|
|
1558
|
+
}
|
|
1559
|
+
const cwd = io.cwd ?? process.cwd();
|
|
1560
|
+
const root = typeof parsed.values.root === "string" ? path.resolve(cwd, parsed.values.root) : cwd;
|
|
1561
|
+
const devUrl = typeof parsed.values["dev-url"] === "string" ? parsed.values["dev-url"] : void 0;
|
|
1562
|
+
await startMcpStdioServer({
|
|
1563
|
+
devUrl,
|
|
1564
|
+
root
|
|
1565
|
+
});
|
|
1566
|
+
return 0;
|
|
1567
|
+
};
|
|
1568
|
+
// src/commands/render.ts
|
|
1569
|
+
const RENDER_HELP = `Usage: mailquilt render <file.json> [options]
|
|
1570
|
+
|
|
1571
|
+
Render a Mail Quilt email JSON file to HTML (default) or plain text.
|
|
1572
|
+
|
|
1573
|
+
Options:
|
|
1574
|
+
--out <path> Write output to a file instead of stdout
|
|
1575
|
+
--text Render plain text instead of HTML
|
|
1576
|
+
--social-icons-url <url> Base URL for Social Block icons
|
|
1577
|
+
-h, --help Show this help message
|
|
1578
|
+
`;
|
|
1579
|
+
const errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
1580
|
+
const runRender = async (args, io) => {
|
|
1581
|
+
let parsed;
|
|
1582
|
+
try {
|
|
1583
|
+
parsed = parseArgs({
|
|
1584
|
+
allowPositionals: true,
|
|
1585
|
+
args: [...args],
|
|
1586
|
+
options: {
|
|
1587
|
+
help: {
|
|
1588
|
+
short: "h",
|
|
1589
|
+
type: "boolean"
|
|
1590
|
+
},
|
|
1591
|
+
out: { type: "string" },
|
|
1592
|
+
"social-icons-url": { type: "string" },
|
|
1593
|
+
text: { type: "boolean" }
|
|
1594
|
+
},
|
|
1595
|
+
strict: true
|
|
1596
|
+
});
|
|
1597
|
+
} catch (error) {
|
|
1598
|
+
io.stderr.write(`mailquilt render: ${errorMessage(error)}\n`);
|
|
1599
|
+
return 1;
|
|
1600
|
+
}
|
|
1601
|
+
if (parsed.values.help) {
|
|
1602
|
+
io.stdout.write(RENDER_HELP);
|
|
1603
|
+
return 0;
|
|
1604
|
+
}
|
|
1605
|
+
const [inputFile] = parsed.positionals;
|
|
1606
|
+
if (!inputFile || parsed.positionals.length > 1) {
|
|
1607
|
+
io.stderr.write("mailquilt render: expected a single <file.json> argument.\n");
|
|
1608
|
+
return 1;
|
|
1609
|
+
}
|
|
1610
|
+
const cwd = io.cwd ?? process.cwd();
|
|
1611
|
+
const resolvedInput = path.resolve(cwd, inputFile);
|
|
1612
|
+
let rawText;
|
|
1613
|
+
try {
|
|
1614
|
+
rawText = await readFile(resolvedInput, "utf-8");
|
|
1615
|
+
} catch (error) {
|
|
1616
|
+
io.stderr.write(`mailquilt render: failed to read "${inputFile}": ${errorMessage(error)}\n`);
|
|
1617
|
+
return 1;
|
|
1618
|
+
}
|
|
1619
|
+
let parsedJson;
|
|
1620
|
+
try {
|
|
1621
|
+
parsedJson = JSON.parse(rawText);
|
|
1622
|
+
} catch (error) {
|
|
1623
|
+
io.stderr.write(`mailquilt render: invalid JSON in "${inputFile}": ${errorMessage(error)}\n`);
|
|
1624
|
+
return 1;
|
|
1625
|
+
}
|
|
1626
|
+
const loaded = loadDocument(parsedJson);
|
|
1627
|
+
if (!loaded.ok) {
|
|
1628
|
+
io.stderr.write(`mailquilt render: document refused: ${loaded.reason}\n`);
|
|
1629
|
+
return 1;
|
|
1630
|
+
}
|
|
1631
|
+
const asText = parsed.values.text === true;
|
|
1632
|
+
const socialIconsUrl = typeof parsed.values["social-icons-url"] === "string" ? parsed.values["social-icons-url"] : void 0;
|
|
1633
|
+
let output;
|
|
1634
|
+
try {
|
|
1635
|
+
output = asText ? renderText(loaded.document) : await renderEmail(loaded.document, socialIconsUrl === void 0 ? {} : { socialIconsUrl });
|
|
1636
|
+
} catch (error) {
|
|
1637
|
+
io.stderr.write(`mailquilt render: ${errorMessage(error)}\n`);
|
|
1638
|
+
return 1;
|
|
1639
|
+
}
|
|
1640
|
+
if (typeof parsed.values.out === "string") {
|
|
1641
|
+
const outPath = path.resolve(cwd, parsed.values.out);
|
|
1642
|
+
try {
|
|
1643
|
+
await mkdir(path.dirname(outPath), { recursive: true });
|
|
1644
|
+
await writeFile(outPath, output, "utf-8");
|
|
1645
|
+
} catch (error) {
|
|
1646
|
+
io.stderr.write(`mailquilt render: failed to write "${parsed.values.out}": ${errorMessage(error)}\n`);
|
|
1647
|
+
return 1;
|
|
1648
|
+
}
|
|
1649
|
+
return 0;
|
|
1650
|
+
}
|
|
1651
|
+
io.stdout.write(output);
|
|
1652
|
+
return 0;
|
|
1653
|
+
};
|
|
1654
|
+
// src/cli.ts
|
|
1655
|
+
const MAIN_HELP = `Usage: mailquilt <command> [options]
|
|
1656
|
+
|
|
1657
|
+
Commands:
|
|
1658
|
+
render <file.json> [--out <path>] [--text] [--social-icons-url <url>]
|
|
1659
|
+
Render an email JSON file to HTML or plain text.
|
|
1660
|
+
|
|
1661
|
+
check <file.json> [--merge-tags <json-or-file>] [--strict] [--json]
|
|
1662
|
+
Check an email for Problems (exits non-zero when Problems exist).
|
|
1663
|
+
|
|
1664
|
+
mcp [--root <dir>] [--dev-url <url>]
|
|
1665
|
+
Start the @mailquilt/mcp server over stdio.
|
|
1666
|
+
|
|
1667
|
+
dev [dir] [--port <port>] [--open]
|
|
1668
|
+
Start the local live Mail Quilt editor over a folder of JSON emails.
|
|
1669
|
+
|
|
1670
|
+
Options:
|
|
1671
|
+
-h, --help Show this help message
|
|
1672
|
+
-v, --version Show CLI version
|
|
1673
|
+
`;
|
|
1674
|
+
const DEFAULT_IO = {
|
|
1675
|
+
stderr: process.stderr,
|
|
1676
|
+
stdout: process.stdout
|
|
1677
|
+
};
|
|
1678
|
+
/** Executes the Mail Quilt CLI for `argv` and returns the exit code. */
|
|
1679
|
+
const runCli = async (argv, io = DEFAULT_IO) => {
|
|
1680
|
+
const [command, ...rest] = argv;
|
|
1681
|
+
if (command === void 0 || command === "-h" || command === "--help") {
|
|
1682
|
+
io.stdout.write(MAIN_HELP);
|
|
1683
|
+
return 0;
|
|
1684
|
+
}
|
|
1685
|
+
if (command === "-v" || command === "--version") {
|
|
1686
|
+
io.stdout.write(`${version}\n`);
|
|
1687
|
+
return 0;
|
|
1688
|
+
}
|
|
1689
|
+
switch (command) {
|
|
1690
|
+
case "render": return await runRender(rest, io);
|
|
1691
|
+
case "check": return await runCheck(rest, io);
|
|
1692
|
+
case "mcp": return await runMcp(rest, io);
|
|
1693
|
+
case "dev": return await runDev(rest, io);
|
|
1694
|
+
default:
|
|
1695
|
+
io.stderr.write(`mailquilt: unknown command "${command}". Run "mailquilt --help" for usage.\n`);
|
|
1696
|
+
return 1;
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
// src/bin.ts
|
|
1700
|
+
try {
|
|
1701
|
+
process.exitCode = await runCli(process.argv.slice(2));
|
|
1702
|
+
} catch (error) {
|
|
1703
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1704
|
+
process.stderr.write(`mailquilt: ${message}\n`);
|
|
1705
|
+
process.exitCode = 1;
|
|
1706
|
+
}
|
|
1707
|
+
export {};
|