@vtex-email/preview 0.0.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.
Files changed (40) hide show
  1. package/dist/assets/browser-boundary.d.ts +2 -0
  2. package/dist/assets/browser-boundary.d.ts.map +1 -0
  3. package/dist/client/assets/index-CLODnl_b.css +1 -0
  4. package/dist/client/assets/index-CN-XJsxa.js +12 -0
  5. package/dist/client/assets/index-CN-XJsxa.js.map +1 -0
  6. package/dist/client/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  7. package/dist/client/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  8. package/dist/client/assets/public-sans-latin-400-normal-8Rpg0ruU.woff2 +0 -0
  9. package/dist/client/assets/public-sans-latin-400-normal-SBbinRkI.woff +0 -0
  10. package/dist/client/assets/public-sans-latin-500-normal-NlrCPXnF.woff2 +0 -0
  11. package/dist/client/assets/public-sans-latin-500-normal-vCxiVFAq.woff +0 -0
  12. package/dist/client/assets/public-sans-latin-600-normal-BR59oU-I.woff +0 -0
  13. package/dist/client/assets/public-sans-latin-600-normal-Fru-LXNs.woff2 +0 -0
  14. package/dist/client/index.html +15 -0
  15. package/dist/index.d.ts +6 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +954 -0
  18. package/dist/server/dev.d.ts +9 -0
  19. package/dist/server/dev.d.ts.map +1 -0
  20. package/dist/server/event-stream.d.ts +6 -0
  21. package/dist/server/event-stream.d.ts.map +1 -0
  22. package/dist/server/http-routes.d.ts +9 -0
  23. package/dist/server/http-routes.d.ts.map +1 -0
  24. package/dist/server/project-services.d.ts +20 -0
  25. package/dist/server/project-services.d.ts.map +1 -0
  26. package/dist/server/start-preview.d.ts +20 -0
  27. package/dist/server/start-preview.d.ts.map +1 -0
  28. package/dist/server/vite-plugin.d.ts +17 -0
  29. package/dist/server/vite-plugin.d.ts.map +1 -0
  30. package/dist/server/watch.d.ts +10 -0
  31. package/dist/server/watch.d.ts.map +1 -0
  32. package/dist/session/change-plan.d.ts +31 -0
  33. package/dist/session/change-plan.d.ts.map +1 -0
  34. package/dist/session/session.d.ts +40 -0
  35. package/dist/session/session.d.ts.map +1 -0
  36. package/dist/shared/contract.d.ts +58 -0
  37. package/dist/shared/contract.d.ts.map +1 -0
  38. package/dist/shared/display-document.d.ts +2 -0
  39. package/dist/shared/display-document.d.ts.map +1 -0
  40. package/package.json +35 -0
package/dist/index.js ADDED
@@ -0,0 +1,954 @@
1
+ // src/server/start-preview.ts
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync as existsSync2 } from "node:fs";
4
+ import { mkdir, rm } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path7 from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { createLogger, createServer } from "vite";
9
+
10
+ // src/session/change-plan.ts
11
+ import { existsSync } from "node:fs";
12
+ import path from "node:path";
13
+ function samePath(left, right) {
14
+ const a = path.normalize(left);
15
+ const b = path.normalize(right);
16
+ if (process.platform === "win32") return a.toLowerCase() === b.toLowerCase();
17
+ return a === b;
18
+ }
19
+ function inside(directory, file) {
20
+ const relative = path.relative(directory, file);
21
+ return relative.length === 0 || !relative.startsWith("..") && !path.isAbsolute(relative);
22
+ }
23
+ function classifyChange(input) {
24
+ const missing = input.missing ?? ((file) => !existsSync(file));
25
+ let full = false;
26
+ const compile = /* @__PURE__ */ new Set();
27
+ const fixtures = /* @__PURE__ */ new Set();
28
+ const schemas = /* @__PURE__ */ new Set();
29
+ for (const file of input.files) {
30
+ if (samePath(file, input.paths.configFile) || samePath(file, input.paths.profilePath)) {
31
+ full = true;
32
+ continue;
33
+ }
34
+ const locale = localeFromCatalog(input.paths.catalogFiles, file);
35
+ if (locale) {
36
+ for (const email of input.emails) {
37
+ if (email.locales.includes(locale)) compile.add(email.id);
38
+ }
39
+ continue;
40
+ }
41
+ const fixtureOwner = input.emails.find((email) => isFixtureFile(input.paths.configDir, email, file));
42
+ if (fixtureOwner) {
43
+ fixtures.add(fixtureOwner.id);
44
+ continue;
45
+ }
46
+ const schemaOwner = schemaEmailId(input.paths.schemasDir, input.emails, file);
47
+ if (schemaOwner) {
48
+ schemas.add(schemaOwner);
49
+ continue;
50
+ }
51
+ const entry = input.emails.find((email) => samePath(email.file, file));
52
+ if (entry && missing(file)) {
53
+ full = true;
54
+ continue;
55
+ }
56
+ const dependents = input.emails.filter(
57
+ (email) => samePath(email.file, file) || email.dependencies.some((dependency) => samePath(dependency, file))
58
+ );
59
+ if (dependents.length > 0) {
60
+ for (const email of dependents) compile.add(email.id);
61
+ continue;
62
+ }
63
+ if (isEmailEntry(input.paths.emailRoots, file)) full = true;
64
+ }
65
+ if (full) return { kind: "full" };
66
+ for (const id of compile) {
67
+ fixtures.delete(id);
68
+ schemas.delete(id);
69
+ }
70
+ for (const id of schemas) fixtures.delete(id);
71
+ if (compile.size === 0 && fixtures.size === 0 && schemas.size === 0) return { kind: "none" };
72
+ return { kind: "partial", compile: [...compile], fixtures: [...fixtures], schemas: [...schemas] };
73
+ }
74
+ function localeFromCatalog(catalogFiles, file) {
75
+ const match = catalogFiles.find((item) => samePath(item, file));
76
+ if (!match) return null;
77
+ return path.basename(match, ".json");
78
+ }
79
+ function isFixtureFile(configDir, email, file) {
80
+ if (email.fixturesPattern.length === 0) return false;
81
+ return inside(fixtureDirectory(configDir, email.fixturesPattern), file);
82
+ }
83
+ function schemaEmailId(schemasDir, emails, file) {
84
+ if (!file.endsWith(".ts")) return null;
85
+ if (!samePath(path.dirname(file), schemasDir)) return null;
86
+ const fileKey = path.basename(file, ".ts");
87
+ const email = emails.find((item) => emailFileKey(item.file) === fileKey);
88
+ return email?.id ?? null;
89
+ }
90
+ function emailFileKey(file) {
91
+ const base = path.basename(file);
92
+ if (!base.endsWith(".email.tsx")) return null;
93
+ return base.slice(0, -".email.tsx".length);
94
+ }
95
+ function fixtureDirectory(configDir, fixturesRelative) {
96
+ return path.resolve(configDir, fixturesRelative);
97
+ }
98
+ function isEmailEntry(roots, file) {
99
+ if (!file.endsWith(".email.tsx")) return false;
100
+ return roots.some((root) => inside(root, file));
101
+ }
102
+ function emailRoot(pattern) {
103
+ const [first] = pattern.replaceAll("\\", "/").split("/");
104
+ if (!first || first.includes("*")) return "";
105
+ return first;
106
+ }
107
+ function relativeToConfig(file, configDir) {
108
+ if (!path.isAbsolute(file)) return file.split(path.sep).join("/");
109
+ const relative = path.relative(configDir, file);
110
+ if (relative.length === 0 || relative.startsWith("..") || path.isAbsolute(relative)) return path.basename(file);
111
+ return relative.split(path.sep).join("/");
112
+ }
113
+
114
+ // src/session/session.ts
115
+ import path2 from "node:path";
116
+ function createPreviewSession(input) {
117
+ let paths = input.paths;
118
+ let emails = input.emails.slice();
119
+ let closed = false;
120
+ let generation = 0;
121
+ let view = 0;
122
+ const listeners = /* @__PURE__ */ new Set();
123
+ const selection = {
124
+ emailId: "",
125
+ fixtureId: "",
126
+ mode: "runtime",
127
+ forcedLocale: null
128
+ };
129
+ let state = blank();
130
+ normalize();
131
+ state = snapshot("stale", input.diagnostics);
132
+ return { state: () => state, open, select, ingest, updatePaths, subscribe, close };
133
+ async function open() {
134
+ if (!input.ok) return publish(snapshot("stale", state.diagnostics));
135
+ const token = ++generation;
136
+ return finish(token, await evaluate());
137
+ }
138
+ async function select(next) {
139
+ if (closed) return state;
140
+ const round = generation;
141
+ const viewToken = ++view;
142
+ if (next.emailId) selection.emailId = next.emailId;
143
+ if (next.fixtureId) selection.fixtureId = next.fixtureId;
144
+ if (next.mode) selection.mode = next.mode;
145
+ if (next.forcedLocale !== void 0) selection.forcedLocale = next.forcedLocale;
146
+ if (selection.mode === "runtime") selection.forcedLocale = null;
147
+ normalize();
148
+ const result = await evaluate();
149
+ if (closed || viewToken !== view || round !== generation) return state;
150
+ return applyEvaluation(result);
151
+ }
152
+ async function ingest(files) {
153
+ if (closed) return state;
154
+ const plan = classifyChange({ paths, emails, files });
155
+ if (plan.kind === "none") return state;
156
+ const before = emails.map((email) => email.id);
157
+ const token = ++generation;
158
+ publish(snapshot("compiling", state.diagnostics));
159
+ let failed = false;
160
+ if (plan.kind === "full" || plan.compile.length > 0) {
161
+ const ids = plan.kind === "full" ? null : plan.compile;
162
+ const result = await input.services.compile(ids);
163
+ if (token !== generation || closed) return state;
164
+ failed = !applyCompile(ids, result);
165
+ }
166
+ if (!failed && plan.kind === "partial") {
167
+ for (const id of plan.schemas) {
168
+ const current = emails.find((email) => email.id === id);
169
+ if (!current) continue;
170
+ const revalidated = await input.services.revalidateSchema(current);
171
+ if (token !== generation || closed) return state;
172
+ emails = emails.map((email) => email.id === id ? revalidated : email);
173
+ state = { ...state, diagnostics: revalidated.diagnostics };
174
+ if (revalidated.diagnostics.some((item) => item.severity === "error")) failed = true;
175
+ }
176
+ if (!failed) {
177
+ for (const id of plan.fixtures) {
178
+ const current = emails.find((email) => email.id === id);
179
+ if (!current) continue;
180
+ const refreshed = await input.services.refreshFixtures(current);
181
+ if (token !== generation || closed) return state;
182
+ emails = emails.map((email) => email.id === id ? refreshed : email);
183
+ }
184
+ }
185
+ }
186
+ if (token !== generation || closed) return state;
187
+ if (failed) {
188
+ const next2 = publish(keep("stale", state.diagnostics));
189
+ emitIngest(plan, true, before);
190
+ return next2;
191
+ }
192
+ normalize();
193
+ const next = finish(token, await evaluate());
194
+ emitIngest(plan, false, before);
195
+ return next;
196
+ }
197
+ function emitIngest(plan, failed, before) {
198
+ if (plan.kind === "none" || !input.onIngest) return;
199
+ const after = emails.map((email) => email.id);
200
+ const beforeSet = new Set(before);
201
+ const afterSet = new Set(after);
202
+ input.onIngest({
203
+ plan: toDevPlan(plan),
204
+ failed,
205
+ added: after.filter((id) => !beforeSet.has(id)),
206
+ removed: before.filter((id) => !afterSet.has(id)),
207
+ diagnostics: state.diagnostics
208
+ });
209
+ }
210
+ function updatePaths(next) {
211
+ paths = { ...paths, ...next };
212
+ }
213
+ function subscribe(listener) {
214
+ listeners.add(listener);
215
+ listener(state);
216
+ return () => listeners.delete(listener);
217
+ }
218
+ function close() {
219
+ closed = true;
220
+ generation += 1;
221
+ view += 1;
222
+ }
223
+ function finish(token, result) {
224
+ if (token !== generation || closed) return state;
225
+ return applyEvaluation(result);
226
+ }
227
+ function applyCompile(ids, result) {
228
+ state = { ...state, diagnostics: result.diagnostics };
229
+ if (!result.ok) return false;
230
+ if (ids === null) {
231
+ emails = result.emails.slice();
232
+ return true;
233
+ }
234
+ for (const email of result.emails) {
235
+ const index = emails.findIndex((item) => item.id === email.id);
236
+ if (index >= 0) emails[index] = email;
237
+ else emails.push(email);
238
+ }
239
+ for (const id of ids) {
240
+ if (result.removedEmailIds?.includes(id)) emails = emails.filter((email) => email.id !== id);
241
+ }
242
+ return true;
243
+ }
244
+ async function evaluate() {
245
+ const email = normalize();
246
+ if (!email || selection.fixtureId.length === 0) {
247
+ return {
248
+ ok: false,
249
+ exitCode: 2,
250
+ html: "",
251
+ source: "",
252
+ diagnostics: [{ code: "CFG001", severity: "error", message: "There is no fixture to preview." }],
253
+ selector: false,
254
+ locale: "",
255
+ payloadLocale: null
256
+ };
257
+ }
258
+ if (blocksArtifact(email) || blocksFixture(email, selection.fixtureId)) {
259
+ return {
260
+ ok: false,
261
+ exitCode: 1,
262
+ html: "",
263
+ source: "",
264
+ diagnostics: email.diagnostics,
265
+ selector: false,
266
+ locale: "",
267
+ payloadLocale: null
268
+ };
269
+ }
270
+ const locale = selection.mode === "forced" ? selection.forcedLocale ?? email.defaultLocale : void 0;
271
+ return input.services.evaluate({
272
+ email,
273
+ fixtureId: selection.fixtureId,
274
+ mode: selection.mode,
275
+ ...locale ? { locale } : {}
276
+ });
277
+ }
278
+ function applyEvaluation(result) {
279
+ const diagnostics = result.diagnostics;
280
+ if (!result.ok) return publish(keep("stale", diagnostics, result.payloadLocale, result.selector));
281
+ state = {
282
+ ...snapshot("ready", diagnostics),
283
+ html: result.html,
284
+ source: result.source,
285
+ selector: result.selector,
286
+ selection: selectionView(result.payloadLocale)
287
+ };
288
+ return publish(state);
289
+ }
290
+ function normalize() {
291
+ const email = emails.find((item) => item.id === selection.emailId) ?? emails[0];
292
+ if (!email) {
293
+ selection.emailId = "";
294
+ selection.fixtureId = "";
295
+ return null;
296
+ }
297
+ selection.emailId = email.id;
298
+ const fixtures = selectable(email);
299
+ if (!fixtures.some((fixture) => fixture.id === selection.fixtureId)) {
300
+ selection.fixtureId = fixtures[0]?.id ?? "";
301
+ }
302
+ if (selection.mode === "forced" && !selection.forcedLocale) selection.forcedLocale = email.defaultLocale;
303
+ return email;
304
+ }
305
+ function snapshot(status, diagnostics) {
306
+ return {
307
+ formatVersion: 1,
308
+ status,
309
+ generation,
310
+ project: { name: path2.basename(paths.configDir) },
311
+ emails: emails.map((email) => emailView(email, paths.configDir)).sort((left, right) => left.id.localeCompare(right.id)),
312
+ selection: selectionView(state?.selection.payloadLocale ?? null),
313
+ html: state?.html ?? "",
314
+ source: state?.source ?? "",
315
+ selector: state?.selector ?? false,
316
+ data: activeData(),
317
+ diagnostics
318
+ };
319
+ }
320
+ function keep(status, diagnostics, payloadLocale = state.selection.payloadLocale, selector = state.selector) {
321
+ return {
322
+ ...snapshot(status, diagnostics),
323
+ html: state.html,
324
+ source: state.source,
325
+ selector,
326
+ selection: selectionView(payloadLocale)
327
+ };
328
+ }
329
+ function selectionView(payloadLocale) {
330
+ return {
331
+ emailId: selection.emailId,
332
+ fixtureId: selection.fixtureId,
333
+ mode: selection.mode,
334
+ payloadLocale,
335
+ forcedLocale: selection.mode === "forced" ? selection.forcedLocale : null
336
+ };
337
+ }
338
+ function publish(next) {
339
+ state = next;
340
+ if (!closed) {
341
+ for (const listener of listeners) listener(state);
342
+ }
343
+ return state;
344
+ }
345
+ function activeData() {
346
+ const email = emails.find((item) => item.id === selection.emailId);
347
+ if (!email) return null;
348
+ const fixture = selectable(email).find((item) => item.id === selection.fixtureId);
349
+ if (!fixture) return null;
350
+ return structuredClone(fixture.data);
351
+ }
352
+ function blank() {
353
+ return {
354
+ formatVersion: 1,
355
+ status: "stale",
356
+ generation: 0,
357
+ project: { name: "" },
358
+ emails: [],
359
+ selection: { emailId: "", fixtureId: "", mode: "runtime", payloadLocale: null, forcedLocale: null },
360
+ html: "",
361
+ source: "",
362
+ selector: false,
363
+ data: null,
364
+ diagnostics: []
365
+ };
366
+ }
367
+ }
368
+ function emailView(email, configDir) {
369
+ return {
370
+ id: email.id,
371
+ locales: [...email.locales],
372
+ localePath: email.localePath,
373
+ fixtures: selectable(email).map((fixture) => ({
374
+ id: fixture.id,
375
+ description: fixture.meta.description,
376
+ origin: fixture.meta.origin,
377
+ purpose: fixture.meta.purpose,
378
+ file: relativeToConfig(fixture.file, configDir),
379
+ ...fixture.meta.expectedLocale ? { expectedLocale: fixture.meta.expectedLocale } : {}
380
+ }))
381
+ };
382
+ }
383
+ function selectable(email) {
384
+ return email.fixtures.filter((fixture) => !fixture.negative);
385
+ }
386
+ function blocksArtifact(email) {
387
+ return email.diagnostics.some((item) => item.severity === "error" && item.fixtureId === void 0);
388
+ }
389
+ function blocksFixture(email, fixtureId) {
390
+ return email.diagnostics.some((item) => item.severity === "error" && item.fixtureId === fixtureId);
391
+ }
392
+ function toDevPlan(plan) {
393
+ if (plan.kind === "full") return { kind: "full" };
394
+ return { kind: "partial", compile: plan.compile, fixtures: plan.fixtures, schemas: plan.schemas };
395
+ }
396
+
397
+ // src/server/event-stream.ts
398
+ function broadcast(clients, state) {
399
+ const payload = `data: ${JSON.stringify(state)}
400
+
401
+ `;
402
+ for (const client of clients) client.write(payload);
403
+ }
404
+ function openEventStream(request, response, clients, state) {
405
+ response.writeHead(200, {
406
+ "content-type": "text/event-stream; charset=utf-8",
407
+ "cache-control": "no-cache",
408
+ connection: "keep-alive"
409
+ });
410
+ response.write("\n");
411
+ clients.add(response);
412
+ request.on("close", () => clients.delete(response));
413
+ response.write(`data: ${JSON.stringify(state)}
414
+
415
+ `);
416
+ }
417
+
418
+ // src/server/project-services.ts
419
+ import {
420
+ buildProject,
421
+ loadProjectConfig,
422
+ previewBuiltEmail,
423
+ publishDiagnostics,
424
+ refreshEmailFixtures,
425
+ revalidateEmail
426
+ } from "@vtex-email/cli/project";
427
+ import path3 from "node:path";
428
+ function previewPaths(config, configPath) {
429
+ return {
430
+ configDir: config.configDir,
431
+ configFile: configPath,
432
+ profilePath: config.profilePath,
433
+ catalogFiles: config.locales.map(
434
+ (locale) => path3.resolve(config.configDir, config.catalogs.replaceAll("{locale}", locale))
435
+ ),
436
+ emailRoots: config.emails.map((pattern) => emailRoot(pattern)).filter((root) => root.length > 0).map((root) => path3.resolve(config.configDir, root)),
437
+ schemasDir: path3.resolve(config.configDir, config.schemasDir)
438
+ };
439
+ }
440
+ function loadPreviewConfig(configPath) {
441
+ return loadProjectConfig(configPath);
442
+ }
443
+ function createProjectServices(input) {
444
+ return {
445
+ compile: async (emailIds) => presentResult(
446
+ await compileProject(input.configPath, input.warningsAsErrors, emailIds),
447
+ input.configDir,
448
+ emailIds
449
+ ),
450
+ refreshFixtures: async (email) => presentEmail(await refreshEmailFixtures(email, input.configDir), input.configDir),
451
+ revalidateSchema: async (email) => presentEmail(await revalidateEmail(input.getConfig(), email), input.configDir),
452
+ evaluate: (request) => presentPreview(previewBuiltEmail(request), input.configDir)
453
+ };
454
+ }
455
+ async function compilePreviewProject(configPath, warningsAsErrors) {
456
+ return buildProject({
457
+ configPath,
458
+ write: false,
459
+ ...warningsAsErrors ? { warningsAsErrors: true } : {}
460
+ });
461
+ }
462
+ function presentCompiled(result, configDir) {
463
+ return presentResult(result, configDir);
464
+ }
465
+ async function compileProject(configPath, warningsAsErrors, emailIds) {
466
+ const options = warningsAsErrors ? { warningsAsErrors: true } : {};
467
+ if (emailIds === null) return buildProject({ configPath, write: false, ...options });
468
+ const results = [];
469
+ for (const id of emailIds) {
470
+ results.push(await buildProject({ configPath, onlyId: id, write: false, ...options }));
471
+ }
472
+ if (results.length === 1 && results[0]) return results[0];
473
+ const ok = results.every((result) => result.ok);
474
+ return {
475
+ ok,
476
+ exitCode: results.some((result) => result.exitCode === 2) ? 2 : ok ? 0 : 1,
477
+ diagnostics: results.flatMap((result) => result.diagnostics),
478
+ manifest: null,
479
+ emails: results.flatMap((result) => result.emails),
480
+ wrote: [],
481
+ preserved: []
482
+ };
483
+ }
484
+ function presentResult(result, configDir, requestedIds = null) {
485
+ const removedEmailIds = requestedIds === null ? result.removedEmailIds : requestedIds.filter(
486
+ (id) => !result.emails.some((email) => email.id === id) && result.diagnostics.some((item) => item.code === "CFG001" && item.message === `Unknown email: ${id}`)
487
+ );
488
+ return {
489
+ ...result,
490
+ diagnostics: publishDiagnostics(result.diagnostics, configDir),
491
+ emails: result.emails.map((email) => presentEmail(email, configDir)),
492
+ ...removedEmailIds && removedEmailIds.length > 0 ? { removedEmailIds: [...removedEmailIds] } : {}
493
+ };
494
+ }
495
+ function presentEmail(email, configDir) {
496
+ return { ...email, diagnostics: publishDiagnostics(email.diagnostics, configDir) };
497
+ }
498
+ async function presentPreview(result, configDir) {
499
+ const resolved = await result;
500
+ return { ...resolved, diagnostics: publishDiagnostics(resolved.diagnostics, configDir) };
501
+ }
502
+
503
+ // src/server/vite-plugin.ts
504
+ import path6 from "node:path";
505
+
506
+ // src/server/http-routes.ts
507
+ import { readFile } from "node:fs/promises";
508
+ import path4 from "node:path";
509
+ function createPreviewMiddleware(input) {
510
+ return (request, response, next) => {
511
+ const host = request.headers.host ?? "127.0.0.1";
512
+ const location = new URL(request.url ?? "/", `http://${host}`);
513
+ if (request.method === "GET" && location.pathname === "/api/events") {
514
+ openEventStream(request, response, input.clients, input.session.state());
515
+ return;
516
+ }
517
+ if (request.method === "POST" && location.pathname === "/api/selection") {
518
+ void readBody(request).then(async (body) => {
519
+ let parsed;
520
+ try {
521
+ parsed = JSON.parse(body);
522
+ } catch {
523
+ response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
524
+ response.end('{"ok":false}');
525
+ return;
526
+ }
527
+ if (parsed.mode !== void 0 && parsed.mode !== "runtime" && parsed.mode !== "forced") {
528
+ response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
529
+ response.end('{"ok":false}');
530
+ return;
531
+ }
532
+ const nextState = await input.session.select(parsed);
533
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
534
+ response.end(JSON.stringify(nextState));
535
+ });
536
+ return;
537
+ }
538
+ if (input.serveShell && input.clientRoot && request.method === "GET" && location.pathname === "/") {
539
+ void readFile(path4.join(input.clientRoot, "index.html"), "utf8").then(
540
+ (html) => {
541
+ response.writeHead(200, {
542
+ "content-type": "text/html; charset=utf-8",
543
+ "cache-control": "no-store"
544
+ });
545
+ response.end(html);
546
+ },
547
+ () => next()
548
+ );
549
+ return;
550
+ }
551
+ next();
552
+ };
553
+ }
554
+ function readBody(request) {
555
+ return new Promise((resolve, reject) => {
556
+ let body = "";
557
+ request.setEncoding("utf8");
558
+ request.on("data", (chunk) => {
559
+ body += chunk;
560
+ if (body.length > 1e5) request.destroy(new Error("Selection body is too large."));
561
+ });
562
+ request.on("end", () => resolve(body));
563
+ request.on("error", reject);
564
+ });
565
+ }
566
+
567
+ // src/server/watch.ts
568
+ import { watch } from "node:fs";
569
+ import path5 from "node:path";
570
+ var IGNORED = /* @__PURE__ */ new Set(["node_modules", "dist", ".cache"]);
571
+ var DEBOUNCE_MS = 150;
572
+ function createDebouncedBatch(waitMs, onBatch) {
573
+ let timer;
574
+ const pending = /* @__PURE__ */ new Set();
575
+ let closed = false;
576
+ return {
577
+ push(file) {
578
+ if (closed) return;
579
+ pending.add(path5.normalize(file));
580
+ if (timer) clearTimeout(timer);
581
+ timer = setTimeout(() => {
582
+ timer = void 0;
583
+ if (closed || pending.size === 0) return;
584
+ const batch = [...pending];
585
+ pending.clear();
586
+ onBatch(batch);
587
+ }, waitMs);
588
+ },
589
+ close() {
590
+ closed = true;
591
+ if (timer) clearTimeout(timer);
592
+ timer = void 0;
593
+ pending.clear();
594
+ }
595
+ };
596
+ }
597
+ function ignoredPath(root, file, extraIgnored = []) {
598
+ const relative = path5.relative(root, file);
599
+ if (relative.startsWith("..") || path5.isAbsolute(relative)) return true;
600
+ const parts = relative.split(/[\\/]/);
601
+ if (parts.some((part) => IGNORED.has(part))) return true;
602
+ for (const ignored of extraIgnored) {
603
+ const ignoredRelative = path5.relative(root, path5.resolve(ignored));
604
+ if (ignoredRelative.startsWith("..") || path5.isAbsolute(ignoredRelative)) continue;
605
+ const normalizedRelative = relative.replaceAll("\\", "/");
606
+ const normalizedIgnored = ignoredRelative.replaceAll("\\", "/");
607
+ if (normalizedRelative === normalizedIgnored || normalizedRelative.startsWith(`${normalizedIgnored}/`)) {
608
+ return true;
609
+ }
610
+ }
611
+ return false;
612
+ }
613
+ function watchProject(configDir, waitMs, onBatch) {
614
+ const batch = createDebouncedBatch(waitMs, onBatch);
615
+ const watcher = watch(configDir, { recursive: true }, (_event, filename) => {
616
+ if (!filename) return;
617
+ const file = path5.resolve(configDir, filename.toString());
618
+ if (ignoredPath(configDir, file)) return;
619
+ batch.push(file);
620
+ });
621
+ return {
622
+ close() {
623
+ batch.close();
624
+ watcher.close();
625
+ }
626
+ };
627
+ }
628
+
629
+ // src/server/vite-plugin.ts
630
+ function previewVitePlugin(options) {
631
+ const batch = createDebouncedBatch(DEBOUNCE_MS, (files) => {
632
+ void options.session.ingest(files);
633
+ if (files.some((file) => samePath(file, options.configPath) || samePath(file, options.profilePath))) {
634
+ options.onConfigPathsChanged(files);
635
+ }
636
+ });
637
+ return {
638
+ name: "vtex-email-preview",
639
+ configureServer(server) {
640
+ const api = createPreviewMiddleware({
641
+ session: options.session,
642
+ clients: options.clients,
643
+ clientRoot: null,
644
+ serveShell: false
645
+ });
646
+ server.middlewares.use(api);
647
+ return () => {
648
+ if (options.serveCompiledClient && options.clientRoot) {
649
+ const shell = createPreviewMiddleware({
650
+ session: options.session,
651
+ clients: options.clients,
652
+ clientRoot: options.clientRoot,
653
+ serveShell: true
654
+ });
655
+ server.middlewares.use(shell);
656
+ }
657
+ attachWatcher(server, options, (file) => batch.push(file));
658
+ };
659
+ }
660
+ };
661
+ }
662
+ function attachWatcher(server, options, push) {
663
+ const extraIgnored = [options.outDir, options.cacheDir];
664
+ server.watcher.add(options.configDir);
665
+ const onFs = (file) => {
666
+ const resolved = path6.resolve(file);
667
+ if (ignoredPath(options.configDir, resolved, extraIgnored)) return;
668
+ push(resolved);
669
+ };
670
+ server.watcher.on("add", onFs);
671
+ server.watcher.on("change", onFs);
672
+ server.watcher.on("unlink", onFs);
673
+ }
674
+
675
+ // src/server/start-preview.ts
676
+ async function startPreview(input) {
677
+ const startedAt = performance.now();
678
+ const notify = input.onNotice ?? (() => void 0);
679
+ const configPath = path7.resolve(input.configPath);
680
+ notify({ kind: "phase", phase: "config" });
681
+ const loaded = await loadPreviewConfig(configPath);
682
+ if (!loaded.ok) {
683
+ notify({ kind: "failed", exitCode: 2, diagnostics: loaded.diagnostics });
684
+ return { ok: false, exitCode: 2, diagnostics: loaded.diagnostics };
685
+ }
686
+ notify({ kind: "project", name: path7.basename(loaded.config.configDir) });
687
+ const warnings = input.warningsAsErrors === true;
688
+ const resolvedClient = resolveClientRoot();
689
+ if (!resolvedClient) {
690
+ const diagnostics = [
691
+ {
692
+ code: "CFG001",
693
+ severity: "error",
694
+ message: "Preview client assets were not found. Run the package build before starting the preview."
695
+ }
696
+ ];
697
+ notify({ kind: "failed", exitCode: 1, diagnostics });
698
+ return { ok: false, exitCode: 1, diagnostics };
699
+ }
700
+ const clientRoot = resolvedClient;
701
+ notify({ kind: "phase", phase: "compile" });
702
+ const built = await compilePreviewProject(configPath, warnings);
703
+ if (!built.ok && built.exitCode === 2) {
704
+ notify({ kind: "failed", exitCode: 2, diagnostics: built.diagnostics });
705
+ return { ok: false, exitCode: 2, diagnostics: built.diagnostics };
706
+ }
707
+ const presented = presentCompiled(built, loaded.config.configDir);
708
+ notify({
709
+ kind: "discovered",
710
+ emails: presented.emails.length,
711
+ fixtures: presented.emails.reduce((total, email) => total + email.fixtures.length, 0)
712
+ });
713
+ const paths = previewPaths(loaded.config, configPath);
714
+ let resolvedConfig = loaded.config;
715
+ const session = createPreviewSession({
716
+ paths,
717
+ emails: presented.emails,
718
+ diagnostics: presented.diagnostics,
719
+ ok: presented.ok,
720
+ services: createProjectServices({
721
+ configPath,
722
+ configDir: loaded.config.configDir,
723
+ warningsAsErrors: warnings,
724
+ getConfig: () => resolvedConfig
725
+ }),
726
+ onIngest: (notice) => {
727
+ notify({
728
+ kind: "ingest",
729
+ plan: notice.plan,
730
+ failed: notice.failed,
731
+ added: notice.added,
732
+ removed: notice.removed,
733
+ diagnostics: notice.diagnostics
734
+ });
735
+ }
736
+ });
737
+ await session.open();
738
+ const hostLocked = input.host !== void 0;
739
+ const portLocked = input.port !== void 0;
740
+ let host = input.host ?? loaded.config.preview.host;
741
+ let port = input.port ?? loaded.config.preview.port;
742
+ let profilePath = loaded.config.profilePath;
743
+ let server = null;
744
+ let url = "";
745
+ const clients = /* @__PURE__ */ new Set();
746
+ let watchGeneration = 0;
747
+ let stopped = false;
748
+ const cacheDir = path7.join(
749
+ tmpdir(),
750
+ `vtex-email-vite-${createHash("sha256").update(configPath).digest("hex").slice(0, 12)}-${process.pid}`
751
+ );
752
+ await mkdir(cacheDir, { recursive: true });
753
+ const unsubscribe = session.subscribe((state) => {
754
+ broadcast(clients, state);
755
+ });
756
+ notify({ kind: "phase", phase: "server" });
757
+ try {
758
+ const bound = await listen(host, port);
759
+ server = bound.server;
760
+ url = bound.url;
761
+ port = bound.port;
762
+ } catch (error) {
763
+ unsubscribe();
764
+ session.close();
765
+ await rm(cacheDir, { recursive: true, force: true }).catch(() => void 0);
766
+ const message = formatListenError(error, host, port);
767
+ const diagnostics = [{ code: "CFG001", severity: "error", message }];
768
+ notify({ kind: "failed", exitCode: 1, diagnostics });
769
+ return { ok: false, exitCode: 1, diagnostics };
770
+ }
771
+ notify({ kind: "listening", url });
772
+ const current = session.state();
773
+ const hasErrors = current.diagnostics.some((item) => item.severity === "error");
774
+ notify({
775
+ kind: "startup",
776
+ templatesReady: current.status === "ready" && !hasErrors,
777
+ elapsedMs: performance.now() - startedAt,
778
+ diagnostics: current.diagnostics
779
+ });
780
+ return {
781
+ ok: true,
782
+ get url() {
783
+ return url;
784
+ },
785
+ close
786
+ };
787
+ async function onConfigFiles(files) {
788
+ const token = ++watchGeneration;
789
+ if (stopped || hostLocked && portLocked) return;
790
+ if (!files.some((file) => samePath(file, configPath) || samePath(file, profilePath))) return;
791
+ const next = await loadPreviewConfig(configPath);
792
+ if (!next.ok || stopped || token !== watchGeneration) return;
793
+ resolvedConfig = next.config;
794
+ profilePath = next.config.profilePath;
795
+ session.updatePaths(previewPaths(next.config, configPath));
796
+ const nextHost = hostLocked ? host : next.config.preview.host;
797
+ const nextPort = portLocked ? port : next.config.preview.port;
798
+ if (nextHost === host && nextPort === port) return;
799
+ try {
800
+ const bound = await listen(nextHost, nextPort);
801
+ host = nextHost;
802
+ port = bound.port;
803
+ url = bound.url;
804
+ server = bound.server;
805
+ notify({ kind: "listening", url });
806
+ } catch {
807
+ }
808
+ }
809
+ async function listen(nextHost, nextPort) {
810
+ const previous = server;
811
+ const next = await createServer({
812
+ configFile: false,
813
+ appType: "custom",
814
+ root: clientRoot,
815
+ base: "/",
816
+ publicDir: false,
817
+ cacheDir,
818
+ logLevel: "warn",
819
+ clearScreen: false,
820
+ ...input.onNotice ? { customLogger: viteNoticeLogger(notify) } : {},
821
+ server: {
822
+ host: nextHost,
823
+ port: nextPort,
824
+ strictPort: true,
825
+ hmr: false,
826
+ fs: {
827
+ allow: [clientRoot]
828
+ }
829
+ },
830
+ plugins: [
831
+ previewVitePlugin({
832
+ session,
833
+ clients,
834
+ configDir: resolvedConfig.configDir,
835
+ configPath,
836
+ profilePath,
837
+ outDir: path7.resolve(resolvedConfig.configDir, resolvedConfig.outDir),
838
+ cacheDir,
839
+ clientRoot,
840
+ serveCompiledClient: true,
841
+ onConfigPathsChanged: (files) => {
842
+ void onConfigFiles(files);
843
+ }
844
+ })
845
+ ]
846
+ });
847
+ try {
848
+ await next.listen();
849
+ } catch (error) {
850
+ await next.close().catch(() => void 0);
851
+ throw error;
852
+ }
853
+ if (previous) {
854
+ for (const client of clients) client.end();
855
+ clients.clear();
856
+ await previous.close().catch(() => void 0);
857
+ }
858
+ const address = next.httpServer?.address();
859
+ if (!address || typeof address === "string") {
860
+ await next.close().catch(() => void 0);
861
+ throw new Error("Preview server did not bind a TCP port.");
862
+ }
863
+ return { server: next, port: address.port, url: `http://${nextHost}:${address.port}/` };
864
+ }
865
+ async function close() {
866
+ if (stopped) return;
867
+ stopped = true;
868
+ watchGeneration += 1;
869
+ unsubscribe();
870
+ session.close();
871
+ for (const client of clients) client.end();
872
+ clients.clear();
873
+ if (server) {
874
+ await server.close().catch(() => void 0);
875
+ server = null;
876
+ }
877
+ await rm(cacheDir, { recursive: true, force: true }).catch(() => void 0);
878
+ }
879
+ }
880
+ function viteNoticeLogger(notify) {
881
+ const base = createLogger("warn", { allowClearScreen: false });
882
+ const seen = /* @__PURE__ */ new Set();
883
+ return {
884
+ hasWarned: false,
885
+ info() {
886
+ },
887
+ warn(msg) {
888
+ this.hasWarned = true;
889
+ notify({ kind: "vite", level: "warn", message: stripVitePrefix(msg) });
890
+ },
891
+ warnOnce(msg) {
892
+ const key = msg;
893
+ if (seen.has(key)) return;
894
+ seen.add(key);
895
+ this.warn(msg);
896
+ },
897
+ error(msg) {
898
+ notify({ kind: "vite", level: "error", message: stripVitePrefix(msg) });
899
+ },
900
+ clearScreen() {
901
+ },
902
+ hasErrorLogged(error) {
903
+ return base.hasErrorLogged(error);
904
+ }
905
+ };
906
+ }
907
+ function stripVitePrefix(message) {
908
+ return message.replace(/^\s*(?:\[vite\]\s*)?/i, "").trimEnd();
909
+ }
910
+ function resolveClientRoot() {
911
+ const here = path7.dirname(fileURLToPath(import.meta.url));
912
+ const candidates = [path7.join(here, "client"), path7.join(here, "../client"), path7.resolve(here, "../../dist/client")];
913
+ for (const candidate of candidates) {
914
+ if (existsSync2(path7.join(candidate, "index.html"))) return candidate;
915
+ }
916
+ return null;
917
+ }
918
+ function formatListenError(error, host, port) {
919
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
920
+ const message = error instanceof Error ? error.message : "";
921
+ if (code === "EADDRINUSE" || /already in use/i.test(message)) {
922
+ return `Preview port ${port} is already in use on ${host}.`;
923
+ }
924
+ return message.length > 0 ? message : "Failed to open the preview server.";
925
+ }
926
+
927
+ // src/server/dev.ts
928
+ async function startDev(input) {
929
+ const started = await startPreview(input);
930
+ if (!started.ok) return started.exitCode;
931
+ await new Promise((resolve) => {
932
+ let settling = false;
933
+ const stop = () => {
934
+ if (settling) return;
935
+ settling = true;
936
+ process.off("SIGINT", stop);
937
+ process.off("SIGTERM", stop);
938
+ void started.close().catch(() => void 0).finally(() => {
939
+ void Promise.resolve(input.onNotice?.({ kind: "stopped" })).finally(() => resolve());
940
+ });
941
+ };
942
+ process.on("SIGINT", stop);
943
+ process.on("SIGTERM", stop);
944
+ });
945
+ return 0;
946
+ }
947
+ export {
948
+ DEBOUNCE_MS,
949
+ classifyChange,
950
+ createPreviewSession,
951
+ startDev,
952
+ startPreview,
953
+ watchProject
954
+ };