@vtex-email/core 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.
- package/dist/compile/artifact.d.ts +36 -0
- package/dist/compile/artifact.d.ts.map +1 -0
- package/dist/compile/assemble.d.ts +15 -0
- package/dist/compile/assemble.d.ts.map +1 -0
- package/dist/compile/syntax.d.ts +3 -0
- package/dist/compile/syntax.d.ts.map +1 -0
- package/dist/compile/target.d.ts +4 -0
- package/dist/compile/target.d.ts.map +1 -0
- package/dist/define-email.d.ts +68 -0
- package/dist/define-email.d.ts.map +1 -0
- package/dist/diagnostics.d.ts +28 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/expression/path.d.ts +23 -0
- package/dist/expression/path.d.ts.map +1 -0
- package/dist/fixture/check.d.ts +6 -0
- package/dist/fixture/check.d.ts.map +1 -0
- package/dist/fixture/locale-path.d.ts +9 -0
- package/dist/fixture/locale-path.d.ts.map +1 -0
- package/dist/hbs/engine.d.ts +16 -0
- package/dist/hbs/engine.d.ts.map +1 -0
- package/dist/hbs/source.d.ts +6 -0
- package/dist/hbs/source.d.ts.map +1 -0
- package/dist/i18n/catalog.d.ts +3 -0
- package/dist/i18n/catalog.d.ts.map +1 -0
- package/dist/i18n/merge.d.ts +14 -0
- package/dist/i18n/merge.d.ts.map +1 -0
- package/dist/i18n/message.d.ts +20 -0
- package/dist/i18n/message.d.ts.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1369 -0
- package/dist/markers/bind.d.ts +13 -0
- package/dist/markers/bind.d.ts.map +1 -0
- package/dist/markers/html-anchors.d.ts +6 -0
- package/dist/markers/html-anchors.d.ts.map +1 -0
- package/dist/markers/restore.d.ts +8 -0
- package/dist/markers/restore.d.ts.map +1 -0
- package/dist/markers/sites.d.ts +21 -0
- package/dist/markers/sites.d.ts.map +1 -0
- package/dist/markers/tokens.d.ts +41 -0
- package/dist/markers/tokens.d.ts.map +1 -0
- package/dist/output/commit.d.ts +15 -0
- package/dist/output/commit.d.ts.map +1 -0
- package/dist/profile.d.ts +48 -0
- package/dist/profile.d.ts.map +1 -0
- package/dist/runtime/document.d.ts +2 -0
- package/dist/runtime/document.d.ts.map +1 -0
- package/dist/runtime/evaluate.d.ts +14 -0
- package/dist/runtime/evaluate.d.ts.map +1 -0
- package/dist/schema/zod-def.d.ts +23 -0
- package/dist/schema/zod-def.d.ts.map +1 -0
- package/dist/scope/analyze-paths.d.ts +6 -0
- package/dist/scope/analyze-paths.d.ts.map +1 -0
- package/dist/scope/structure.d.ts +32 -0
- package/dist/scope/structure.d.ts.map +1 -0
- package/package.json +21 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1369 @@
|
|
|
1
|
+
// src/compile/artifact.ts
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
function sha256(content) {
|
|
4
|
+
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
5
|
+
}
|
|
6
|
+
function normalizeOutput(content) {
|
|
7
|
+
const normalized = content.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
|
8
|
+
if (normalized.includes("\r")) throw new Error("Output still contains CR.");
|
|
9
|
+
return normalized;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// src/diagnostics.ts
|
|
13
|
+
function errorDiagnostic(code, message, extra = {}) {
|
|
14
|
+
return { code, severity: "error", message, ...extra };
|
|
15
|
+
}
|
|
16
|
+
function warningDiagnostic(code, message, extra = {}) {
|
|
17
|
+
return { code, severity: "warning", message, ...extra };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/hbs/source.ts
|
|
21
|
+
function emitLiteral(value) {
|
|
22
|
+
if (typeof value === "string") {
|
|
23
|
+
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
|
24
|
+
}
|
|
25
|
+
if (typeof value === "number") {
|
|
26
|
+
if (!Number.isFinite(value)) throw new Error("Invalid numeric literal.");
|
|
27
|
+
return String(value);
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "boolean") return value ? "true" : "false";
|
|
30
|
+
return "null";
|
|
31
|
+
}
|
|
32
|
+
function emitInterpolation(path2) {
|
|
33
|
+
return `{{${path2}}}`;
|
|
34
|
+
}
|
|
35
|
+
function emitHelperCall(name, args) {
|
|
36
|
+
return `{{${name}${args.length > 0 ? ` ${args.join(" ")}` : ""}}}`;
|
|
37
|
+
}
|
|
38
|
+
function emitBlockOpen(name, args) {
|
|
39
|
+
return `{{#${name}${args.length > 0 ? ` ${args.join(" ")}` : ""}}}`;
|
|
40
|
+
}
|
|
41
|
+
function emitBlockClose(name) {
|
|
42
|
+
return `{{/${name}}}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/profile.ts
|
|
46
|
+
function syntaxHelperNames(profile) {
|
|
47
|
+
return profile.capabilities.filter((capability) => capability.form !== "path").map((capability) => capability.name);
|
|
48
|
+
}
|
|
49
|
+
function findCapability(profile, name, form) {
|
|
50
|
+
if (!name) return void 0;
|
|
51
|
+
return profile.capabilities.find((item) => item.name === name && (form === void 0 || item.form === form));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/scope/structure.ts
|
|
55
|
+
function nestSites(sites, markers, anchors) {
|
|
56
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
57
|
+
for (const [id, site] of sites) {
|
|
58
|
+
const node = siteNode(site);
|
|
59
|
+
if (node) nodes.set(id, node);
|
|
60
|
+
}
|
|
61
|
+
const containers = [];
|
|
62
|
+
for (const [id, site] of sites) {
|
|
63
|
+
if (site.kind !== "block") continue;
|
|
64
|
+
const anchor = anchors.get(id);
|
|
65
|
+
if (!anchor) continue;
|
|
66
|
+
containers.push({ start: anchor.start, end: anchor.end, blockId: id, slot: "children" });
|
|
67
|
+
const marker = markers.get(id);
|
|
68
|
+
if (marker?.kind === "open" && marker.elseId) {
|
|
69
|
+
const elseAnchor = anchors.get(marker.elseId);
|
|
70
|
+
if (elseAnchor) {
|
|
71
|
+
containers.push({ start: elseAnchor.start, end: elseAnchor.end, blockId: id, slot: "fallback" });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const roots = [];
|
|
76
|
+
const placed = [];
|
|
77
|
+
for (const [id, node] of nodes) {
|
|
78
|
+
const anchor = anchors.get(id);
|
|
79
|
+
const start = anchor?.start ?? 0;
|
|
80
|
+
const parent = anchor ? parentOf(id, anchor, containers) : null;
|
|
81
|
+
if (!parent) roots.push({ start, node });
|
|
82
|
+
else placed.push({ start, blockId: parent.blockId, slot: parent.slot, node });
|
|
83
|
+
}
|
|
84
|
+
for (const item of placed.sort((left, right) => left.start - right.start)) {
|
|
85
|
+
const block = nodes.get(item.blockId);
|
|
86
|
+
if (block?.kind === "block") block[item.slot].push(item.node);
|
|
87
|
+
else roots.push({ start: item.start, node: item.node });
|
|
88
|
+
}
|
|
89
|
+
return roots.sort((left, right) => left.start - right.start).map((item) => item.node);
|
|
90
|
+
}
|
|
91
|
+
function parentOf(id, anchor, containers) {
|
|
92
|
+
let best = null;
|
|
93
|
+
for (const container of containers) {
|
|
94
|
+
if (container.blockId === id && container.slot === "children") continue;
|
|
95
|
+
const inside = anchor.start >= container.start && anchor.end <= container.end;
|
|
96
|
+
if (!inside) continue;
|
|
97
|
+
const size = container.end - container.start;
|
|
98
|
+
if (!best || size < best.size) best = { blockId: container.blockId, slot: container.slot, size };
|
|
99
|
+
}
|
|
100
|
+
return best;
|
|
101
|
+
}
|
|
102
|
+
function siteNode(site) {
|
|
103
|
+
if (site.kind === "block" && site.block && site.path) {
|
|
104
|
+
return {
|
|
105
|
+
kind: "block",
|
|
106
|
+
block: site.block,
|
|
107
|
+
path: site.path.emitted,
|
|
108
|
+
parentHops: site.path.parentHops,
|
|
109
|
+
children: [],
|
|
110
|
+
fallback: []
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
if (site.kind === "value" && site.path) {
|
|
114
|
+
return { kind: "ref", role: "value", path: site.path.emitted, parentHops: site.path.parentHops };
|
|
115
|
+
}
|
|
116
|
+
if (site.kind === "literal") {
|
|
117
|
+
return { kind: "ref", role: "value", parentHops: 0, args: mapArgs(site) };
|
|
118
|
+
}
|
|
119
|
+
if (site.kind === "helper") {
|
|
120
|
+
return {
|
|
121
|
+
kind: "ref",
|
|
122
|
+
role: "helper",
|
|
123
|
+
parentHops: 0,
|
|
124
|
+
...site.helper ? { helper: site.helper } : {},
|
|
125
|
+
args: mapArgs(site)
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
if (site.kind === "attr") {
|
|
129
|
+
return {
|
|
130
|
+
kind: "ref",
|
|
131
|
+
role: "attr",
|
|
132
|
+
parentHops: site.path?.parentHops ?? 0,
|
|
133
|
+
...site.path ? { path: site.path.emitted } : {},
|
|
134
|
+
...site.attribute ? { attribute: site.attribute } : {},
|
|
135
|
+
args: mapArgs(site)
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
function mapArgs(site) {
|
|
141
|
+
return (site.args ?? []).map((arg) => ({
|
|
142
|
+
kind: arg.kind,
|
|
143
|
+
emitted: arg.emitted,
|
|
144
|
+
parentHops: arg.path?.parentHops ?? 0
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/markers/html-anchors.ts
|
|
149
|
+
import { parse } from "parse5";
|
|
150
|
+
function parseHtml(html) {
|
|
151
|
+
return parse(html, { sourceCodeLocationInfo: true });
|
|
152
|
+
}
|
|
153
|
+
function walkElements(node, visit) {
|
|
154
|
+
if ("tagName" in node && "attrs" in node) visit(node);
|
|
155
|
+
if ("childNodes" in node) {
|
|
156
|
+
for (const child of node.childNodes) walkElements(child, visit);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// src/markers/bind.ts
|
|
161
|
+
function bindSites(html, markers, sites, profile) {
|
|
162
|
+
const capabilityIssues = checkCapabilities(sites, profile);
|
|
163
|
+
if (capabilityIssues.length > 0) return { ok: false, diagnostics: capabilityIssues };
|
|
164
|
+
const located = locate(html, markers);
|
|
165
|
+
if (!located.ok) return located;
|
|
166
|
+
const scopeIssues = checkScope(sites, located.anchors, profile);
|
|
167
|
+
if (scopeIssues.length > 0) return { ok: false, diagnostics: scopeIssues };
|
|
168
|
+
const next = /* @__PURE__ */ new Map();
|
|
169
|
+
for (const [id, marker] of markers) {
|
|
170
|
+
const site = sites.get(id);
|
|
171
|
+
const filled = materialize(marker, site);
|
|
172
|
+
if (!filled.ok) return filled;
|
|
173
|
+
next.set(id, filled.marker);
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
ok: true,
|
|
177
|
+
markers: next,
|
|
178
|
+
used: usedCapabilities(sites, profile),
|
|
179
|
+
structure: nestSites(sites, markers, located.anchors)
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function checkCapabilities(sites, profile) {
|
|
183
|
+
const diagnostics = [];
|
|
184
|
+
for (const site of sites.values()) {
|
|
185
|
+
if (site.kind === "helper") {
|
|
186
|
+
const capability = findCapability(profile, site.helper ?? "");
|
|
187
|
+
if (!capability || capability.form !== "inline") {
|
|
188
|
+
diagnostics.push(errorDiagnostic("HBS002", `Helper is not enabled: ${site.helper ?? ""}`));
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
diagnostics.push(...checkArguments(capability, site));
|
|
192
|
+
}
|
|
193
|
+
if (site.kind === "block") {
|
|
194
|
+
const capability = findCapability(profile, site.block ?? "");
|
|
195
|
+
if (!capability || capability.form !== "block") {
|
|
196
|
+
diagnostics.push(errorDiagnostic("HBS002", `Block is not enabled: ${site.block ?? ""}`));
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (capability.context === void 0 || capability.elseContext === void 0) {
|
|
200
|
+
diagnostics.push(errorDiagnostic("HBS002", `Block ${site.block ?? ""} does not declare its context.`));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
diagnostics.push(...checkParentCapability(site.path, profile));
|
|
204
|
+
for (const arg of site.args ?? []) diagnostics.push(...checkParentCapability(arg.path, profile));
|
|
205
|
+
}
|
|
206
|
+
return diagnostics;
|
|
207
|
+
}
|
|
208
|
+
function checkArguments(capability, site) {
|
|
209
|
+
const args = site.args ?? [];
|
|
210
|
+
if (capability.arity && (args.length < capability.arity.min || args.length > capability.arity.max)) {
|
|
211
|
+
return [
|
|
212
|
+
errorDiagnostic(
|
|
213
|
+
"HBS002",
|
|
214
|
+
`Helper ${capability.name} expected ${capability.arity.min} argument(s) and received ${args.length}.`
|
|
215
|
+
)
|
|
216
|
+
];
|
|
217
|
+
}
|
|
218
|
+
if (!capability.args) return [];
|
|
219
|
+
const diagnostics = [];
|
|
220
|
+
capability.args.forEach((expected, index) => {
|
|
221
|
+
const actual = args[index];
|
|
222
|
+
if (actual && actual.kind !== expected) {
|
|
223
|
+
diagnostics.push(
|
|
224
|
+
errorDiagnostic("HBS002", `Helper ${capability.name} argument ${index + 1} must be a ${expected}.`)
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
return diagnostics;
|
|
229
|
+
}
|
|
230
|
+
function checkParentCapability(path2, profile) {
|
|
231
|
+
if (!path2 || path2.parentHops === 0) return [];
|
|
232
|
+
const capability = findCapability(profile, "../", "path");
|
|
233
|
+
if (!capability)
|
|
234
|
+
return [errorDiagnostic("HBS002", "The profile does not enable the ../ segment.", { path: path2.emitted })];
|
|
235
|
+
return [];
|
|
236
|
+
}
|
|
237
|
+
function checkScope(sites, anchors, profile) {
|
|
238
|
+
const regions = regionsFrom(sites, anchors, profile);
|
|
239
|
+
const diagnostics = [];
|
|
240
|
+
for (const [id, site] of sites) {
|
|
241
|
+
const anchor = anchors.get(id);
|
|
242
|
+
if (!anchor) {
|
|
243
|
+
diagnostics.push(errorDiagnostic("TOK001", `Marker ${id} was not located for scope validation.`));
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
const depth = depthAt(anchor.start, id, regions);
|
|
247
|
+
diagnostics.push(...checkDepth(site.path, depth));
|
|
248
|
+
for (const arg of site.args ?? []) diagnostics.push(...checkDepth(arg.path, depth));
|
|
249
|
+
}
|
|
250
|
+
return diagnostics;
|
|
251
|
+
}
|
|
252
|
+
function regionsFrom(sites, anchors, profile) {
|
|
253
|
+
const regions = [];
|
|
254
|
+
for (const [id, site] of sites) {
|
|
255
|
+
if (site.kind !== "block" || !site.block) continue;
|
|
256
|
+
const anchor = anchors.get(id);
|
|
257
|
+
const capability = findCapability(profile, site.block);
|
|
258
|
+
if (!anchor || !capability) continue;
|
|
259
|
+
regions.push({ ...anchor, id, pushes: capability.context === "item" });
|
|
260
|
+
}
|
|
261
|
+
return regions;
|
|
262
|
+
}
|
|
263
|
+
function depthAt(offset, selfId, regions) {
|
|
264
|
+
let depth = 0;
|
|
265
|
+
for (const region of regions) {
|
|
266
|
+
if (!region.pushes || region.id === selfId) continue;
|
|
267
|
+
if (offset > region.start && offset < region.end) depth += 1;
|
|
268
|
+
}
|
|
269
|
+
return depth;
|
|
270
|
+
}
|
|
271
|
+
function checkDepth(path2, depth) {
|
|
272
|
+
if (!path2 || path2.parentHops <= depth) return [];
|
|
273
|
+
return [errorDiagnostic("HBS001", `Path "${path2.emitted}" goes beyond the root context.`, { path: path2.emitted })];
|
|
274
|
+
}
|
|
275
|
+
function usedCapabilities(sites, profile) {
|
|
276
|
+
const names = /* @__PURE__ */ new Set();
|
|
277
|
+
for (const site of sites.values()) {
|
|
278
|
+
if (site.kind === "block" && site.block) names.add(site.block);
|
|
279
|
+
if (site.kind === "helper" && site.helper) names.add(site.helper);
|
|
280
|
+
if (site.path && site.path.parentHops > 0) names.add("../");
|
|
281
|
+
for (const arg of site.args ?? []) {
|
|
282
|
+
if (arg.path && arg.path.parentHops > 0) names.add("../");
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return profile.capabilities.filter((capability) => names.has(capability.name));
|
|
286
|
+
}
|
|
287
|
+
function materialize(marker, site) {
|
|
288
|
+
if (marker.kind === "else") return { ok: true, marker: { ...marker } };
|
|
289
|
+
if (!site) return { ok: false, diagnostics: [errorDiagnostic("TOK001", "A marker has no descriptor.")] };
|
|
290
|
+
if (marker.kind === "text" && site.kind === "value" && site.path) {
|
|
291
|
+
return { ok: true, marker: { ...marker, replacement: emitInterpolation(site.path.emitted) } };
|
|
292
|
+
}
|
|
293
|
+
if (marker.kind === "text" && site.kind === "helper" && site.helper) {
|
|
294
|
+
return {
|
|
295
|
+
ok: true,
|
|
296
|
+
marker: {
|
|
297
|
+
...marker,
|
|
298
|
+
replacement: emitHelperCall(
|
|
299
|
+
site.helper,
|
|
300
|
+
(site.args ?? []).map((arg) => arg.emitted)
|
|
301
|
+
)
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
if (marker.kind === "text" && site.kind === "literal") {
|
|
306
|
+
const literal = site.args?.find((arg) => arg.kind === "literal");
|
|
307
|
+
if (literal) return { ok: true, marker: { ...marker, replacement: emitInterpolation(literal.emitted) } };
|
|
308
|
+
}
|
|
309
|
+
if (marker.kind === "attr" && site.kind === "attr") {
|
|
310
|
+
const path2 = site.path;
|
|
311
|
+
const literal = site.args?.find((arg) => arg.kind === "literal");
|
|
312
|
+
if (path2) return { ok: true, marker: { ...marker, replacement: emitInterpolation(path2.emitted) } };
|
|
313
|
+
if (literal) return { ok: true, marker: { ...marker, replacement: emitInterpolation(literal.emitted) } };
|
|
314
|
+
}
|
|
315
|
+
if (marker.kind === "open" && site.kind === "block" && site.block && site.path) {
|
|
316
|
+
return {
|
|
317
|
+
ok: true,
|
|
318
|
+
marker: {
|
|
319
|
+
...marker,
|
|
320
|
+
open: emitBlockOpen(site.block, [site.path.emitted]),
|
|
321
|
+
close: emitBlockClose(site.block)
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
return { ok: false, diagnostics: [errorDiagnostic("TOK001", "A marker descriptor does not match its kind.")] };
|
|
326
|
+
}
|
|
327
|
+
function locate(html, markers) {
|
|
328
|
+
const document = parseHtml(html);
|
|
329
|
+
const anchors = /* @__PURE__ */ new Map();
|
|
330
|
+
const diagnostics = [];
|
|
331
|
+
walkElements(document, (element) => {
|
|
332
|
+
const location = element.sourceCodeLocation;
|
|
333
|
+
if (!location || location.startOffset < 0 || location.endOffset < 0) return;
|
|
334
|
+
for (const attr of element.attrs) {
|
|
335
|
+
const marker = markers.get(attr.value);
|
|
336
|
+
if (!marker) continue;
|
|
337
|
+
if (attr.name === "data-anchor") {
|
|
338
|
+
anchors.set(attr.value, { id: attr.value, start: location.startOffset, end: location.endOffset });
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (marker.kind === "attr" && attr.name === marker.attribute) {
|
|
342
|
+
anchors.set(attr.value, { id: attr.value, start: location.startOffset, end: location.endOffset });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
for (const id of markers.keys()) {
|
|
347
|
+
if (!anchors.has(id)) diagnostics.push(errorDiagnostic("TOK001", `Marker ${id} was not located.`));
|
|
348
|
+
}
|
|
349
|
+
if (diagnostics.length > 0) return { ok: false, diagnostics };
|
|
350
|
+
return { ok: true, anchors };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// src/markers/tokens.ts
|
|
354
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
355
|
+
var TOKEN_PREFIX = "vtx";
|
|
356
|
+
var TOKEN_BODY_LENGTH = 20;
|
|
357
|
+
var TOKEN_LENGTH = TOKEN_PREFIX.length + TOKEN_BODY_LENGTH;
|
|
358
|
+
var HEX_CHAR = /^[0-9a-f]$/i;
|
|
359
|
+
var ALPHA_NUM = /^[0-9A-Za-z]$/;
|
|
360
|
+
function mintToken(parts) {
|
|
361
|
+
const payload = `${parts.kind}
|
|
362
|
+
${parts.index}
|
|
363
|
+
${parts.path}
|
|
364
|
+
${parts.detail}`;
|
|
365
|
+
const body = createHash2("sha256").update(payload).digest("hex").slice(0, TOKEN_BODY_LENGTH);
|
|
366
|
+
return `${TOKEN_PREFIX}${body}`;
|
|
367
|
+
}
|
|
368
|
+
function isHexChar(value) {
|
|
369
|
+
return value !== void 0 && HEX_CHAR.test(value);
|
|
370
|
+
}
|
|
371
|
+
function isAlphaNum(value) {
|
|
372
|
+
return value !== void 0 && ALPHA_NUM.test(value);
|
|
373
|
+
}
|
|
374
|
+
function scanTokens(html, markers) {
|
|
375
|
+
const counts = /* @__PURE__ */ new Map();
|
|
376
|
+
let cursor = 0;
|
|
377
|
+
while (cursor < html.length) {
|
|
378
|
+
const at = html.indexOf(TOKEN_PREFIX, cursor);
|
|
379
|
+
if (at === -1) break;
|
|
380
|
+
const before = at > 0 ? html[at - 1] : void 0;
|
|
381
|
+
let hexEnd = at + TOKEN_PREFIX.length;
|
|
382
|
+
while (isHexChar(html[hexEnd])) hexEnd += 1;
|
|
383
|
+
const hexLength = hexEnd - (at + TOKEN_PREFIX.length);
|
|
384
|
+
if (isHexChar(before)) {
|
|
385
|
+
if (hexLength > 0) {
|
|
386
|
+
return invalid(at, html);
|
|
387
|
+
}
|
|
388
|
+
cursor = at + TOKEN_PREFIX.length;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
if (hexLength === TOKEN_BODY_LENGTH) {
|
|
392
|
+
const candidate = html.slice(at, at + TOKEN_LENGTH);
|
|
393
|
+
if (!markers.has(candidate)) return invalid(at, html);
|
|
394
|
+
counts.set(candidate, (counts.get(candidate) ?? 0) + 1);
|
|
395
|
+
cursor = at + TOKEN_LENGTH;
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
if (hexLength > 0 || isAlphaNum(html[at + TOKEN_PREFIX.length])) {
|
|
399
|
+
return invalid(at, html);
|
|
400
|
+
}
|
|
401
|
+
cursor = at + TOKEN_PREFIX.length;
|
|
402
|
+
}
|
|
403
|
+
for (const [id, marker] of markers) {
|
|
404
|
+
const seen = counts.get(id) ?? 0;
|
|
405
|
+
const allowed = marker.kind === "attr" ? seen >= 1 : seen === 1;
|
|
406
|
+
if (!allowed) {
|
|
407
|
+
return {
|
|
408
|
+
ok: false,
|
|
409
|
+
index: html.indexOf(id),
|
|
410
|
+
message: `Marker ${id} appears ${seen} time(s); the compiler allows one occurrence.`
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
return { ok: true, counts };
|
|
415
|
+
}
|
|
416
|
+
function opaqueTokenIssue(text) {
|
|
417
|
+
const scanned = scanTokens(text, /* @__PURE__ */ new Map());
|
|
418
|
+
return scanned.ok ? null : scanned.message;
|
|
419
|
+
}
|
|
420
|
+
function invalid(index, html) {
|
|
421
|
+
return {
|
|
422
|
+
ok: false,
|
|
423
|
+
index,
|
|
424
|
+
message: `Invalid opaque marker near ${html.slice(index, index + 32)}`
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// src/markers/restore.ts
|
|
429
|
+
function restoreHandlebars(html, markers) {
|
|
430
|
+
const source = html.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
|
|
431
|
+
if (source.includes("{{")) {
|
|
432
|
+
return fail("HBS001", "Rendered HTML already contains Handlebars delimiters.");
|
|
433
|
+
}
|
|
434
|
+
const scanned = scanTokens(source, markers);
|
|
435
|
+
if (!scanned.ok) return fail("TOK001", scanned.message);
|
|
436
|
+
const document = parseHtml(source);
|
|
437
|
+
const located = /* @__PURE__ */ new Map();
|
|
438
|
+
const attrLocated = /* @__PURE__ */ new Map();
|
|
439
|
+
walkElements(document, (element) => {
|
|
440
|
+
for (const attr of element.attrs) {
|
|
441
|
+
if (!markers.has(attr.value)) continue;
|
|
442
|
+
if (attr.name === "data-anchor") located.set(attr.value, element);
|
|
443
|
+
else {
|
|
444
|
+
const sites = attrLocated.get(attr.value) ?? [];
|
|
445
|
+
sites.push({ element, attribute: attr.name });
|
|
446
|
+
attrLocated.set(attr.value, sites);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
const edits = [];
|
|
451
|
+
for (const [id, marker] of markers) {
|
|
452
|
+
const built = editsFor(source, id, marker, markers, located, attrLocated);
|
|
453
|
+
if (!built.ok) return built;
|
|
454
|
+
edits.push(...built.edits);
|
|
455
|
+
}
|
|
456
|
+
const overlap = findOverlap(edits);
|
|
457
|
+
if (overlap) return fail("TOK001", overlap);
|
|
458
|
+
const ordered = [...edits].sort((left, right) => right.start - left.start || left.rank - right.rank);
|
|
459
|
+
let output = source;
|
|
460
|
+
for (const edit of ordered) {
|
|
461
|
+
if (output.slice(edit.start, edit.end) !== edit.expected) {
|
|
462
|
+
return fail("TOK001", "Marker offset does not match the original string.");
|
|
463
|
+
}
|
|
464
|
+
output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
|
|
465
|
+
}
|
|
466
|
+
const leftover = opaqueTokenIssue(output);
|
|
467
|
+
if (leftover || output.includes("data-anchor")) {
|
|
468
|
+
return fail("TOK001", leftover ?? "An internal marker remained after restoration.");
|
|
469
|
+
}
|
|
470
|
+
return { ok: true, html: output };
|
|
471
|
+
}
|
|
472
|
+
function editsFor(source, id, marker, markers, located, attrLocated) {
|
|
473
|
+
if (marker.kind === "text") return textEdits(source, id, marker, located);
|
|
474
|
+
if (marker.kind === "attr") return attrEdits(source, id, marker, attrLocated);
|
|
475
|
+
if (marker.kind === "open") return openEdits(source, id, marker, markers, located);
|
|
476
|
+
return elseEdits(source, id, marker, markers, located);
|
|
477
|
+
}
|
|
478
|
+
function textEdits(source, id, marker, located) {
|
|
479
|
+
const closed = explicitElement(source, id, located.get(id));
|
|
480
|
+
if (!closed.ok) return closed;
|
|
481
|
+
return {
|
|
482
|
+
ok: true,
|
|
483
|
+
edits: [
|
|
484
|
+
{
|
|
485
|
+
start: closed.location.startOffset,
|
|
486
|
+
end: closed.location.endOffset,
|
|
487
|
+
text: marker.replacement,
|
|
488
|
+
expected: closed.text,
|
|
489
|
+
rank: 0
|
|
490
|
+
}
|
|
491
|
+
]
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
function attrEdits(source, id, marker, attrLocated) {
|
|
495
|
+
const sites = attrLocated.get(id) ?? [];
|
|
496
|
+
const declared = sites.filter((site) => site.attribute === marker.attribute);
|
|
497
|
+
if (declared.length !== 1) {
|
|
498
|
+
return fail("TOK001", `Attribute ${marker.attribute} of marker ${id} appears ${declared.length} time(s).`);
|
|
499
|
+
}
|
|
500
|
+
const edits = [];
|
|
501
|
+
for (const site of sites) {
|
|
502
|
+
if (site.attribute === marker.attribute) {
|
|
503
|
+
const location2 = site.element.sourceCodeLocation?.attrs?.[site.attribute];
|
|
504
|
+
if (!location2) return fail("TOK001", `Attribute ${site.attribute} of marker ${id} was not located.`);
|
|
505
|
+
const expected2 = source.slice(location2.startOffset, location2.endOffset);
|
|
506
|
+
if (expected2 !== `${site.attribute}="${id}"`) {
|
|
507
|
+
return fail("TOK001", `Attribute ${site.attribute} was escaped or shifted.`);
|
|
508
|
+
}
|
|
509
|
+
edits.push({
|
|
510
|
+
start: location2.startOffset,
|
|
511
|
+
end: location2.endOffset,
|
|
512
|
+
text: `${site.attribute}="${marker.replacement}"`,
|
|
513
|
+
expected: expected2,
|
|
514
|
+
rank: 0
|
|
515
|
+
});
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (!isImagePreload(site.element, site.attribute)) {
|
|
519
|
+
return fail("TOK001", `Marker ${id} was copied to ${site.element.tagName} ${site.attribute}.`);
|
|
520
|
+
}
|
|
521
|
+
const location = site.element.sourceCodeLocation;
|
|
522
|
+
if (!location || location.startOffset < 0 || location.endOffset < 0) {
|
|
523
|
+
return fail("TOK001", `Preload for marker ${id} has no offsets.`);
|
|
524
|
+
}
|
|
525
|
+
const expected = source.slice(location.startOffset, location.endOffset);
|
|
526
|
+
if (!expected.startsWith("<link") || !expected.endsWith(">") || !expected.includes(id)) {
|
|
527
|
+
return fail("TOK001", `Preload for marker ${id} was shifted.`);
|
|
528
|
+
}
|
|
529
|
+
edits.push({
|
|
530
|
+
start: location.startOffset,
|
|
531
|
+
end: location.endOffset,
|
|
532
|
+
text: "",
|
|
533
|
+
expected,
|
|
534
|
+
rank: 0
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
return { ok: true, edits };
|
|
538
|
+
}
|
|
539
|
+
function openEdits(source, id, marker, markers, located) {
|
|
540
|
+
const closed = explicitElement(source, id, located.get(id));
|
|
541
|
+
if (!closed.ok) return closed;
|
|
542
|
+
const { location } = closed;
|
|
543
|
+
const attr = location.attrs?.["data-anchor"];
|
|
544
|
+
if (!attr) return fail("TOK001", `Opening ${id} was not located.`);
|
|
545
|
+
const attrText = source.slice(attr.startOffset, attr.endOffset);
|
|
546
|
+
if (attrText !== `data-anchor="${id}"`) return fail("TOK001", `Anchor ${id} was escaped or shifted.`);
|
|
547
|
+
const edits = [
|
|
548
|
+
{ start: location.startOffset, end: location.startOffset, text: marker.open, expected: "", rank: 0 },
|
|
549
|
+
anchorRemoval(source, attr.startOffset, attr.endOffset, attrText)
|
|
550
|
+
];
|
|
551
|
+
if (!marker.elseId) {
|
|
552
|
+
edits.push({
|
|
553
|
+
start: location.endOffset,
|
|
554
|
+
end: location.endOffset,
|
|
555
|
+
text: marker.close,
|
|
556
|
+
expected: "",
|
|
557
|
+
rank: 1
|
|
558
|
+
});
|
|
559
|
+
return { ok: true, edits };
|
|
560
|
+
}
|
|
561
|
+
const alternative = markers.get(marker.elseId);
|
|
562
|
+
if (!alternative || alternative.kind !== "else" || alternative.openId !== id) {
|
|
563
|
+
return fail("TOK001", `Alternative for block ${id} is not balanced.`);
|
|
564
|
+
}
|
|
565
|
+
return { ok: true, edits };
|
|
566
|
+
}
|
|
567
|
+
function elseEdits(source, id, marker, markers, located) {
|
|
568
|
+
const opener = markers.get(marker.openId);
|
|
569
|
+
const closed = explicitElement(source, id, located.get(id));
|
|
570
|
+
if (!opener || opener.kind !== "open" || opener.elseId !== id) {
|
|
571
|
+
return fail("TOK001", `Closing for block ${id} is not balanced.`);
|
|
572
|
+
}
|
|
573
|
+
if (!closed.ok) return closed;
|
|
574
|
+
const { location } = closed;
|
|
575
|
+
const attr = location.attrs?.["data-anchor"];
|
|
576
|
+
if (!attr) return fail("TOK001", `Closing for block ${id} is not balanced.`);
|
|
577
|
+
const attrText = source.slice(attr.startOffset, attr.endOffset);
|
|
578
|
+
if (attrText !== `data-anchor="${id}"`) return fail("TOK001", `Alternative anchor ${id} was escaped.`);
|
|
579
|
+
return {
|
|
580
|
+
ok: true,
|
|
581
|
+
edits: [
|
|
582
|
+
{ start: location.startOffset, end: location.startOffset, text: "{{else}}", expected: "", rank: 0 },
|
|
583
|
+
anchorRemoval(source, attr.startOffset, attr.endOffset, attrText),
|
|
584
|
+
{ start: location.endOffset, end: location.endOffset, text: opener.close, expected: "", rank: 1 }
|
|
585
|
+
]
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
function findOverlap(edits) {
|
|
589
|
+
const ordered = [...edits].sort((left, right) => left.start - right.start || left.end - right.end);
|
|
590
|
+
for (let index = 1; index < ordered.length; index += 1) {
|
|
591
|
+
const previous = ordered[index - 1];
|
|
592
|
+
const current = ordered[index];
|
|
593
|
+
if (previous && current && previous.start < current.end && current.start < previous.end) {
|
|
594
|
+
return "Marker edits overlap.";
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
function explicitElement(source, id, element) {
|
|
600
|
+
const location = element?.sourceCodeLocation;
|
|
601
|
+
if (!element || !location || location.startOffset < 0 || location.endOffset < 0) {
|
|
602
|
+
return fail("TOK001", `Element for marker ${id} was not located.`);
|
|
603
|
+
}
|
|
604
|
+
if (!location.endTag) {
|
|
605
|
+
return fail("TOK001", `Element for marker ${id} has no explicit closing tag.`);
|
|
606
|
+
}
|
|
607
|
+
const text = source.slice(location.startOffset, location.endOffset);
|
|
608
|
+
if (!text.toLowerCase().endsWith(`</${element.tagName}>`) || !text.includes(id)) {
|
|
609
|
+
return fail("TOK001", `Element for marker ${id} does not end at the closing tag.`);
|
|
610
|
+
}
|
|
611
|
+
return { ok: true, location, text };
|
|
612
|
+
}
|
|
613
|
+
function isImagePreload(element, attribute) {
|
|
614
|
+
if (element.tagName !== "link" || attribute !== "href") return false;
|
|
615
|
+
const rel = element.attrs.find((attr) => attr.name === "rel")?.value;
|
|
616
|
+
const as = element.attrs.find((attr) => attr.name === "as")?.value;
|
|
617
|
+
return rel === "preload" && as === "image";
|
|
618
|
+
}
|
|
619
|
+
function anchorRemoval(source, start, end, attrText) {
|
|
620
|
+
const withSpace = start > 0 && source[start - 1] === " ";
|
|
621
|
+
return {
|
|
622
|
+
start: withSpace ? start - 1 : start,
|
|
623
|
+
end,
|
|
624
|
+
text: "",
|
|
625
|
+
expected: withSpace ? ` ${attrText}` : attrText,
|
|
626
|
+
rank: 2
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
function fail(code, message) {
|
|
630
|
+
return { ok: false, diagnostics: [errorDiagnostic(code, message)] };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// src/hbs/engine.ts
|
|
634
|
+
import handlebarsImport from "handlebars";
|
|
635
|
+
var handlebars = handlebarsImport;
|
|
636
|
+
function createHandlebars() {
|
|
637
|
+
return handlebars.create();
|
|
638
|
+
}
|
|
639
|
+
function compileOptions(knownHelperNames) {
|
|
640
|
+
const knownHelpers = {};
|
|
641
|
+
for (const name of knownHelperNames) knownHelpers[name] = true;
|
|
642
|
+
return { knownHelpersOnly: true, knownHelpers, noEscape: false };
|
|
643
|
+
}
|
|
644
|
+
function handlebarsDiagnostic(error) {
|
|
645
|
+
const message = error instanceof Error ? error.message : "Failed to compile Handlebars.";
|
|
646
|
+
const code = /helper/i.test(message) ? "HBS002" : "HBS001";
|
|
647
|
+
return errorDiagnostic(code, message);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/compile/syntax.ts
|
|
651
|
+
function validateHandlebarsSyntax(source, knownHelperNames) {
|
|
652
|
+
const instance = createHandlebars();
|
|
653
|
+
try {
|
|
654
|
+
const generated = instance.precompile(source, compileOptions(knownHelperNames));
|
|
655
|
+
if (typeof generated !== "string") {
|
|
656
|
+
return errorDiagnostic("HBS001", "Handlebars precompilation did not return source text.");
|
|
657
|
+
}
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return handlebarsDiagnostic(error);
|
|
660
|
+
}
|
|
661
|
+
return null;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// src/compile/target.ts
|
|
665
|
+
function unverifiedCapabilityDiagnostic(capability, templateId) {
|
|
666
|
+
if (capability.evidence === "verified") return null;
|
|
667
|
+
return warningDiagnostic(
|
|
668
|
+
"TARGET001",
|
|
669
|
+
`Capability ${capability.name} is ${capability.evidence} and is not verified on the destination.`,
|
|
670
|
+
{ templateId, capability: { name: capability.name, evidence: capability.evidence } }
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// src/compile/assemble.ts
|
|
675
|
+
function assembleDocument(input) {
|
|
676
|
+
const bound = bindSites(input.html, input.markers, input.sites, input.profile);
|
|
677
|
+
if (!bound.ok) return fail2(stamp(bound.diagnostics, input));
|
|
678
|
+
const restored = restoreHandlebars(input.html, bound.markers);
|
|
679
|
+
if (!restored.ok) return fail2(stamp(restored.diagnostics, input));
|
|
680
|
+
const content = normalizeOutput(restored.html);
|
|
681
|
+
const syntax = validateHandlebarsSyntax(content, syntaxHelperNames(input.profile));
|
|
682
|
+
if (syntax) return fail2([{ ...syntax, templateId: input.templateId, locale: input.locale }]);
|
|
683
|
+
const diagnostics = targetWarnings(bound.used, input.templateId);
|
|
684
|
+
const digest = sha256(content);
|
|
685
|
+
const manifest = {
|
|
686
|
+
formatVersion: 1,
|
|
687
|
+
templateId: input.templateId,
|
|
688
|
+
event: input.event,
|
|
689
|
+
profileId: input.profile.id,
|
|
690
|
+
locales: [input.locale],
|
|
691
|
+
defaultLocale: input.locale,
|
|
692
|
+
sha256: digest,
|
|
693
|
+
capabilities: bound.used.map((capability) => ({
|
|
694
|
+
name: capability.name,
|
|
695
|
+
evidence: capability.evidence,
|
|
696
|
+
note: capability.note
|
|
697
|
+
})),
|
|
698
|
+
homologation: "experimental",
|
|
699
|
+
warnings: diagnostics.map((issue) => issue.message)
|
|
700
|
+
};
|
|
701
|
+
return {
|
|
702
|
+
ok: true,
|
|
703
|
+
artifacts: [{ name: `${input.templateId}.html`, content, sha256: digest }],
|
|
704
|
+
diagnostics,
|
|
705
|
+
manifest,
|
|
706
|
+
structure: bound.structure
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
function targetWarnings(used, templateId) {
|
|
710
|
+
return used.flatMap((capability) => {
|
|
711
|
+
const issue = unverifiedCapabilityDiagnostic(capability, templateId);
|
|
712
|
+
return issue ? [issue] : [];
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
function stamp(diagnostics, input) {
|
|
716
|
+
return diagnostics.map((issue) => ({ ...issue, templateId: input.templateId, locale: input.locale }));
|
|
717
|
+
}
|
|
718
|
+
function fail2(diagnostics) {
|
|
719
|
+
return { ok: false, diagnostics };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/define-email.ts
|
|
723
|
+
var SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
724
|
+
function isSafeEmailId(id) {
|
|
725
|
+
return SAFE_ID.test(id);
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// src/expression/path.ts
|
|
729
|
+
var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
730
|
+
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
731
|
+
var INDEX = /^[0-9]+$/;
|
|
732
|
+
function parentHops(segments) {
|
|
733
|
+
let hops = 0;
|
|
734
|
+
for (const segment of segments) {
|
|
735
|
+
if (segment !== "..") break;
|
|
736
|
+
hops += 1;
|
|
737
|
+
}
|
|
738
|
+
return hops;
|
|
739
|
+
}
|
|
740
|
+
function parsePath(input, allowParent) {
|
|
741
|
+
if (input.length === 0) return { ok: false, message: "Empty path." };
|
|
742
|
+
if (input.includes("@") || input.includes("[") || input.includes("]")) {
|
|
743
|
+
return { ok: false, message: `Unsupported path syntax: ${input}` };
|
|
744
|
+
}
|
|
745
|
+
const segments = [];
|
|
746
|
+
let cursor = 0;
|
|
747
|
+
while (input.startsWith("../", cursor)) {
|
|
748
|
+
if (!allowParent) return { ok: false, message: "The profile does not allow the ../ segment." };
|
|
749
|
+
segments.push("..");
|
|
750
|
+
cursor += 3;
|
|
751
|
+
}
|
|
752
|
+
if (cursor < input.length) {
|
|
753
|
+
const rest = input.slice(cursor);
|
|
754
|
+
if (rest.length === 0) return { ok: false, message: "Incomplete path." };
|
|
755
|
+
for (const segment of rest.split(".")) {
|
|
756
|
+
if (!IDENTIFIER.test(segment) && !INDEX.test(segment)) {
|
|
757
|
+
return { ok: false, message: `Unsupported path segment: ${segment}` };
|
|
758
|
+
}
|
|
759
|
+
if (FORBIDDEN_SEGMENTS.has(segment) || segment === "this") {
|
|
760
|
+
return { ok: false, message: `Rejected path segment: ${segment}` };
|
|
761
|
+
}
|
|
762
|
+
segments.push(segment);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
if (segments.every((segment) => segment === "..")) {
|
|
766
|
+
return { ok: false, message: "Path has no property." };
|
|
767
|
+
}
|
|
768
|
+
return { ok: true, segments, emitted: emitPath(segments) };
|
|
769
|
+
}
|
|
770
|
+
function emitPath(segments) {
|
|
771
|
+
let output = "";
|
|
772
|
+
for (const segment of segments) {
|
|
773
|
+
if (segment === "..") {
|
|
774
|
+
output += output.length === 0 ? ".." : "/..";
|
|
775
|
+
} else if (output.length === 0) {
|
|
776
|
+
output = segment;
|
|
777
|
+
} else if (output.endsWith("..")) {
|
|
778
|
+
output += `/${segment}`;
|
|
779
|
+
} else {
|
|
780
|
+
output += `.${segment}`;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
return output;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/fixture/check.ts
|
|
787
|
+
import "zod";
|
|
788
|
+
|
|
789
|
+
// src/schema/zod-def.ts
|
|
790
|
+
var MUTATING = /* @__PURE__ */ new Set(["transform", "default", "prefault", "catch", "pipe"]);
|
|
791
|
+
function asSchema(schema) {
|
|
792
|
+
return schema;
|
|
793
|
+
}
|
|
794
|
+
function schemaDef(schema) {
|
|
795
|
+
return schema.def;
|
|
796
|
+
}
|
|
797
|
+
function combineSchemas(schemas) {
|
|
798
|
+
const first = schemas[0];
|
|
799
|
+
if (!first || schemas.length === 1) return first ?? {};
|
|
800
|
+
return { def: { type: "union", options: schemas } };
|
|
801
|
+
}
|
|
802
|
+
function peelSchema(schema) {
|
|
803
|
+
let current = schema;
|
|
804
|
+
let optional = false;
|
|
805
|
+
const seen = /* @__PURE__ */ new Set();
|
|
806
|
+
while (current.def && !seen.has(current)) {
|
|
807
|
+
seen.add(current);
|
|
808
|
+
const type = current.def.type;
|
|
809
|
+
if (type === "optional" || type === "nullable") {
|
|
810
|
+
optional = true;
|
|
811
|
+
if (!current.def.innerType) return { status: "unanalyzable" };
|
|
812
|
+
current = current.def.innerType;
|
|
813
|
+
continue;
|
|
814
|
+
}
|
|
815
|
+
return { status: "ready", schema: current, optional };
|
|
816
|
+
}
|
|
817
|
+
return { status: "unanalyzable" };
|
|
818
|
+
}
|
|
819
|
+
function isScalarType(type) {
|
|
820
|
+
return type === "string" || type === "number" || type === "int" || type === "boolean" || type === "bigint" || type === "literal" || type === "enum" || type === "null" || type === "date" || type === "any" || type === "unknown";
|
|
821
|
+
}
|
|
822
|
+
function schemaMutates(schema) {
|
|
823
|
+
const seen = /* @__PURE__ */ new Set();
|
|
824
|
+
const visit = (node) => {
|
|
825
|
+
if (!node || typeof node !== "object" || seen.has(node)) return false;
|
|
826
|
+
seen.add(node);
|
|
827
|
+
const def = node.def;
|
|
828
|
+
if (!def || typeof def !== "object") return false;
|
|
829
|
+
if (def.coerce === true || typeof def.type === "string" && MUTATING.has(def.type)) return true;
|
|
830
|
+
for (const value of Object.values(def)) {
|
|
831
|
+
if (Array.isArray(value)) {
|
|
832
|
+
if (value.some((item) => visit(item))) return true;
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
835
|
+
if (value && typeof value === "object") {
|
|
836
|
+
if ("def" in value) {
|
|
837
|
+
if (visit(value)) return true;
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
if (Object.values(value).some((item) => visit(item))) return true;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
return false;
|
|
844
|
+
};
|
|
845
|
+
return visit(schema);
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/fixture/check.ts
|
|
849
|
+
function checkFixture(schema, data) {
|
|
850
|
+
if (schemaMutates(schema)) {
|
|
851
|
+
return errorDiagnostic("DATA001", "Schema applies coercion, a default, or a transform.");
|
|
852
|
+
}
|
|
853
|
+
const before = JSON.stringify(data);
|
|
854
|
+
const copy = structuredClone(data);
|
|
855
|
+
const parsed = schema.safeParse(copy);
|
|
856
|
+
if (JSON.stringify(data) !== before) {
|
|
857
|
+
return errorDiagnostic("DATA001", "Validation changed the fixture.");
|
|
858
|
+
}
|
|
859
|
+
if (!parsed.success) {
|
|
860
|
+
const message = parsed.error.issues.map((issue) => issue.message).join("; ");
|
|
861
|
+
return errorDiagnostic("DATA001", message || "Fixture is outside the contract.");
|
|
862
|
+
}
|
|
863
|
+
return null;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// src/fixture/locale-path.ts
|
|
867
|
+
function readPathValue(data, pathExpression) {
|
|
868
|
+
const parsed = parsePath(pathExpression, false);
|
|
869
|
+
if (!parsed.ok) return void 0;
|
|
870
|
+
let cursor = data;
|
|
871
|
+
for (const segment of parsed.segments) {
|
|
872
|
+
if (cursor === null || typeof cursor !== "object") return void 0;
|
|
873
|
+
cursor = cursor[segment];
|
|
874
|
+
}
|
|
875
|
+
return cursor;
|
|
876
|
+
}
|
|
877
|
+
function withForcedLocale(data, localePath, locale) {
|
|
878
|
+
const copy = structuredClone(data);
|
|
879
|
+
const parsed = parsePath(localePath, false);
|
|
880
|
+
if (!parsed.ok) return { ok: false, message: parsed.message };
|
|
881
|
+
let cursor = copy;
|
|
882
|
+
const segments = parsed.segments;
|
|
883
|
+
for (let index = 0; index < segments.length - 1; index += 1) {
|
|
884
|
+
const key = segments[index];
|
|
885
|
+
if (!key || cursor === null || typeof cursor !== "object")
|
|
886
|
+
return { ok: false, message: `Cannot set ${localePath}.` };
|
|
887
|
+
const record = cursor;
|
|
888
|
+
const next = record[key];
|
|
889
|
+
if (next === void 0 || next === null) {
|
|
890
|
+
const upcoming = segments[index + 1] ?? "";
|
|
891
|
+
record[key] = /^[0-9]+$/.test(upcoming) ? [] : {};
|
|
892
|
+
}
|
|
893
|
+
cursor = record[key];
|
|
894
|
+
}
|
|
895
|
+
const last = segments[segments.length - 1];
|
|
896
|
+
if (!last || cursor === null || typeof cursor !== "object") return { ok: false, message: `Cannot set ${localePath}.` };
|
|
897
|
+
cursor[last] = locale;
|
|
898
|
+
return { ok: true, data: copy };
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
// src/i18n/message.ts
|
|
902
|
+
var PLACEHOLDER = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;
|
|
903
|
+
function parseMessage(value) {
|
|
904
|
+
if (value.includes("{{") || value.includes("}}")) {
|
|
905
|
+
return { ok: false, message: "Message contains Handlebars delimiters." };
|
|
906
|
+
}
|
|
907
|
+
const parts = [];
|
|
908
|
+
const placeholders = [];
|
|
909
|
+
let cursor = 0;
|
|
910
|
+
for (const match of value.matchAll(PLACEHOLDER)) {
|
|
911
|
+
const index = match.index ?? 0;
|
|
912
|
+
const name = match[1];
|
|
913
|
+
if (!name) return { ok: false, message: "Invalid placeholder." };
|
|
914
|
+
const text = value.slice(cursor, index);
|
|
915
|
+
if (text.includes("{") || text.includes("}")) return { ok: false, message: "Invalid placeholder." };
|
|
916
|
+
if (text.length > 0) parts.push({ type: "text", value: text });
|
|
917
|
+
parts.push({ type: "placeholder", name });
|
|
918
|
+
placeholders.push(name);
|
|
919
|
+
cursor = index + match[0].length;
|
|
920
|
+
}
|
|
921
|
+
const rest = value.slice(cursor);
|
|
922
|
+
if (rest.includes("{") || rest.includes("}")) return { ok: false, message: "Invalid placeholder." };
|
|
923
|
+
if (rest.length > 0) parts.push({ type: "text", value: rest });
|
|
924
|
+
if (new Set(placeholders).size !== placeholders.length) {
|
|
925
|
+
return { ok: false, message: "A placeholder is repeated in the message." };
|
|
926
|
+
}
|
|
927
|
+
return { ok: true, parts, placeholders };
|
|
928
|
+
}
|
|
929
|
+
function placeholderSignature(value) {
|
|
930
|
+
const parsed = parseMessage(value);
|
|
931
|
+
if (!parsed.ok) return null;
|
|
932
|
+
return parsed.placeholders.slice().sort().join("\0");
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// src/i18n/catalog.ts
|
|
936
|
+
function checkCatalogs(locales, catalogs) {
|
|
937
|
+
const diagnostics = [];
|
|
938
|
+
const first = catalogs[locales[0] ?? ""];
|
|
939
|
+
const expected = first ? Object.keys(first).sort().join("\0") : "";
|
|
940
|
+
for (const locale of locales) {
|
|
941
|
+
const catalog = catalogs[locale];
|
|
942
|
+
if (!catalog) {
|
|
943
|
+
diagnostics.push(errorDiagnostic("I18N001", `Missing catalog for ${locale}.`, { locale }));
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
if (Object.keys(catalog).sort().join("\0") !== expected) {
|
|
947
|
+
diagnostics.push(
|
|
948
|
+
errorDiagnostic("I18N001", `Catalog keys for ${locale} differ from the other locales.`, { locale })
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
for (const [key, value] of Object.entries(catalog)) {
|
|
952
|
+
const parsed = parseMessage(value);
|
|
953
|
+
if (!parsed.ok || opaqueTokenIssue(value)) {
|
|
954
|
+
diagnostics.push(
|
|
955
|
+
errorDiagnostic("I18N001", `Translation ${key} contains delimiters that are not allowed.`, { locale })
|
|
956
|
+
);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
if (first) {
|
|
960
|
+
for (const key of Object.keys(first)) {
|
|
961
|
+
const current = catalog[key];
|
|
962
|
+
const original = first[key];
|
|
963
|
+
if (current === void 0 || original === void 0) continue;
|
|
964
|
+
const left = placeholderSignature(original);
|
|
965
|
+
const right = placeholderSignature(current);
|
|
966
|
+
if (left !== null && right !== null && left !== right) {
|
|
967
|
+
diagnostics.push(errorDiagnostic("I18N001", `Placeholders for ${key} differ between locales.`, { locale }));
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
return diagnostics;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// src/i18n/merge.ts
|
|
976
|
+
function mergeLocaleDocuments(input) {
|
|
977
|
+
if (input.documents.length === 0) throw new Error("Nothing to merge.");
|
|
978
|
+
const byLocale = new Map(input.documents.map((document) => [document.locale, document.html]));
|
|
979
|
+
const fallback = byLocale.get(input.defaultLocale);
|
|
980
|
+
if (!fallback) throw new Error("The default locale must be present in the list.");
|
|
981
|
+
const branches = [];
|
|
982
|
+
for (const document of input.documents) {
|
|
983
|
+
if (document.locale === input.defaultLocale) continue;
|
|
984
|
+
branches.push({ literal: document.locale, html: document.html });
|
|
985
|
+
}
|
|
986
|
+
for (const alias of input.aliases ?? []) {
|
|
987
|
+
const html = byLocale.get(alias.locale);
|
|
988
|
+
if (!html) throw new Error(`Alias ${alias.alias} points at an unknown locale.`);
|
|
989
|
+
branches.push({ literal: alias.alias, html });
|
|
990
|
+
}
|
|
991
|
+
if (branches.length === 0) return fallback;
|
|
992
|
+
const path2 = parsePath(input.localePath, true);
|
|
993
|
+
if (!path2.ok) throw new Error(path2.message);
|
|
994
|
+
const equality = input.equality ?? "eq";
|
|
995
|
+
let body = fallback;
|
|
996
|
+
for (let index = branches.length - 1; index >= 0; index -= 1) {
|
|
997
|
+
const branch = branches[index];
|
|
998
|
+
if (!branch) continue;
|
|
999
|
+
body = [
|
|
1000
|
+
emitBlockOpen(equality, [path2.emitted, emitLiteral(branch.literal)]),
|
|
1001
|
+
branch.html,
|
|
1002
|
+
"{{else}}",
|
|
1003
|
+
body,
|
|
1004
|
+
emitBlockClose(equality)
|
|
1005
|
+
].join("\n");
|
|
1006
|
+
}
|
|
1007
|
+
return `${body}
|
|
1008
|
+
`;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// src/output/commit.ts
|
|
1012
|
+
import { mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
1013
|
+
import path from "node:path";
|
|
1014
|
+
async function releaseArtifacts(input) {
|
|
1015
|
+
for (const file of input.files) {
|
|
1016
|
+
if (file.name === "manifest.json") continue;
|
|
1017
|
+
const issue = validateHandlebarsSyntax(file.content, input.helperNames);
|
|
1018
|
+
if (issue) return issue;
|
|
1019
|
+
}
|
|
1020
|
+
await commitArtifacts(input.directory, input.files, input.remove);
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
async function commitArtifacts(directory, files, remove = []) {
|
|
1024
|
+
const prepared = files.map((file) => {
|
|
1025
|
+
assertArtifactName(file.name);
|
|
1026
|
+
if (file.content.length === 0) throw new Error(`Empty artifact content: ${file.name}`);
|
|
1027
|
+
return { name: file.name, content: normalizeOutput(file.content) };
|
|
1028
|
+
});
|
|
1029
|
+
for (const name of remove) assertArtifactName(name);
|
|
1030
|
+
await mkdir(directory, { recursive: true });
|
|
1031
|
+
const stagingDir = path.join(directory, `.staging-${process.pid}-${Date.now()}`);
|
|
1032
|
+
await mkdir(stagingDir);
|
|
1033
|
+
const promoted = [];
|
|
1034
|
+
const removed = [];
|
|
1035
|
+
try {
|
|
1036
|
+
const staged = [];
|
|
1037
|
+
for (const [index, file] of prepared.entries()) {
|
|
1038
|
+
const temp = path.join(stagingDir, `${index}.html`);
|
|
1039
|
+
await writeFile(temp, file.content, { encoding: "utf8" });
|
|
1040
|
+
staged.push({ temp, finalPath: path.join(directory, file.name), backup: path.join(stagingDir, `${index}.bak`) });
|
|
1041
|
+
}
|
|
1042
|
+
for (const item of staged) {
|
|
1043
|
+
await mkdir(path.dirname(item.finalPath), { recursive: true });
|
|
1044
|
+
const hadOriginal = await moveIfExists(item.finalPath, item.backup);
|
|
1045
|
+
try {
|
|
1046
|
+
await rename(item.temp, item.finalPath);
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
if (hadOriginal) await rename(item.backup, item.finalPath);
|
|
1049
|
+
throw error;
|
|
1050
|
+
}
|
|
1051
|
+
promoted.push({ finalPath: item.finalPath, backup: item.backup, hadOriginal });
|
|
1052
|
+
}
|
|
1053
|
+
for (const [index, name] of remove.entries()) {
|
|
1054
|
+
const finalPath = path.join(directory, name);
|
|
1055
|
+
const backup = path.join(stagingDir, `remove-${index}.bak`);
|
|
1056
|
+
if (await moveIfExists(finalPath, backup)) removed.push({ finalPath, backup });
|
|
1057
|
+
}
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
for (const item of [...removed].reverse()) {
|
|
1060
|
+
await rename(item.backup, item.finalPath);
|
|
1061
|
+
}
|
|
1062
|
+
for (const item of [...promoted].reverse()) {
|
|
1063
|
+
await rm(item.finalPath, { force: true });
|
|
1064
|
+
if (item.hadOriginal) await rename(item.backup, item.finalPath);
|
|
1065
|
+
}
|
|
1066
|
+
await rm(stagingDir, { recursive: true, force: true });
|
|
1067
|
+
throw error;
|
|
1068
|
+
}
|
|
1069
|
+
await rm(stagingDir, { recursive: true, force: true });
|
|
1070
|
+
}
|
|
1071
|
+
function assertArtifactName(name) {
|
|
1072
|
+
if (name.length === 0 || name.includes("\\") || name.includes("\0") || path.isAbsolute(name)) {
|
|
1073
|
+
throw new Error(`Invalid artifact name: ${name}`);
|
|
1074
|
+
}
|
|
1075
|
+
const parts = name.split("/");
|
|
1076
|
+
if (parts.some((part) => part.length === 0 || part === "." || part === "..")) {
|
|
1077
|
+
throw new Error(`Invalid artifact name: ${name}`);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
async function moveIfExists(from, to) {
|
|
1081
|
+
try {
|
|
1082
|
+
await rename(from, to);
|
|
1083
|
+
return true;
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
if (isEnoent(error)) return false;
|
|
1086
|
+
throw error;
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
function isEnoent(error) {
|
|
1090
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// src/runtime/document.ts
|
|
1094
|
+
function singleDocumentIssue(html) {
|
|
1095
|
+
const counts = {
|
|
1096
|
+
doctype: countNeedle(html, "<!doctype"),
|
|
1097
|
+
html: countTag(html, "html"),
|
|
1098
|
+
head: countTag(html, "head"),
|
|
1099
|
+
body: countTag(html, "body")
|
|
1100
|
+
};
|
|
1101
|
+
if (counts.doctype === 1 && counts.html === 1 && counts.head === 1 && counts.body === 1) return null;
|
|
1102
|
+
return `Resolved document has structure ${JSON.stringify(counts)}.`;
|
|
1103
|
+
}
|
|
1104
|
+
function countNeedle(html, needle) {
|
|
1105
|
+
const source = html.toLowerCase();
|
|
1106
|
+
const target = needle.toLowerCase();
|
|
1107
|
+
let count = 0;
|
|
1108
|
+
let index = 0;
|
|
1109
|
+
while (index < source.length) {
|
|
1110
|
+
const found = source.indexOf(target, index);
|
|
1111
|
+
if (found === -1) break;
|
|
1112
|
+
count += 1;
|
|
1113
|
+
index = found + target.length;
|
|
1114
|
+
}
|
|
1115
|
+
return count;
|
|
1116
|
+
}
|
|
1117
|
+
function countTag(html, tag) {
|
|
1118
|
+
const source = html.toLowerCase();
|
|
1119
|
+
const target = `<${tag.toLowerCase()}`;
|
|
1120
|
+
let count = 0;
|
|
1121
|
+
let index = 0;
|
|
1122
|
+
while (index < source.length) {
|
|
1123
|
+
const found = source.indexOf(target, index);
|
|
1124
|
+
if (found === -1) break;
|
|
1125
|
+
const next = source[found + target.length];
|
|
1126
|
+
if (next === ">" || next === " " || next === "/" || next === "\n" || next === "\r" || next === " ") count += 1;
|
|
1127
|
+
index = found + target.length;
|
|
1128
|
+
}
|
|
1129
|
+
return count;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// src/runtime/evaluate.ts
|
|
1133
|
+
var TemplateFailure = class extends Error {
|
|
1134
|
+
diagnostics;
|
|
1135
|
+
constructor(diagnostics) {
|
|
1136
|
+
super(diagnostics.map((item) => item.message).join("\n"));
|
|
1137
|
+
this.name = "TemplateFailure";
|
|
1138
|
+
this.diagnostics = diagnostics;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
function renderTemplate(source, data, simulator) {
|
|
1142
|
+
const instance = createHandlebars();
|
|
1143
|
+
const options = compileOptions(simulator.helpers.map((helper) => helper.name));
|
|
1144
|
+
for (const helper of simulator.helpers) {
|
|
1145
|
+
if (helper.kind === "inline") {
|
|
1146
|
+
const apply = helper.apply;
|
|
1147
|
+
instance.registerHelper(helper.name, ((...args) => apply(...args.slice(0, -1))));
|
|
1148
|
+
} else {
|
|
1149
|
+
const apply = helper.apply;
|
|
1150
|
+
instance.registerHelper(helper.name, function(...args) {
|
|
1151
|
+
const blockOptions = args.at(-1);
|
|
1152
|
+
return apply(this, args.slice(0, -1), blockOptions);
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
let template;
|
|
1157
|
+
try {
|
|
1158
|
+
template = instance.compile(source, options);
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
throw new TemplateFailure([handlebarsDiagnostic(error)]);
|
|
1161
|
+
}
|
|
1162
|
+
return template(data);
|
|
1163
|
+
}
|
|
1164
|
+
function evaluateArtifact(input) {
|
|
1165
|
+
if (input.profile.id.length === 0) {
|
|
1166
|
+
throw new TemplateFailure([errorDiagnostic("HBS002", "The emission profile has no id.")]);
|
|
1167
|
+
}
|
|
1168
|
+
const html = renderTemplate(input.source, input.data, input.simulator);
|
|
1169
|
+
const issue = singleDocumentIssue(html);
|
|
1170
|
+
if (issue) throw new TemplateFailure([errorDiagnostic("HTML001", issue)]);
|
|
1171
|
+
return html;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/scope/analyze-paths.ts
|
|
1175
|
+
function analyzePaths(schema, nodes) {
|
|
1176
|
+
return walk(nodes, [{ schema: asSchema(schema), prefix: [] }], []);
|
|
1177
|
+
}
|
|
1178
|
+
function analyzeRootPath(schema, path2) {
|
|
1179
|
+
const parsed = parsePath(path2, true);
|
|
1180
|
+
if (!parsed.ok) return errorDiagnostic("PATH001", parsed.message, { path: path2 });
|
|
1181
|
+
const lookup = resolve(
|
|
1182
|
+
asSchema(schema),
|
|
1183
|
+
parsed.segments.filter((segment) => segment !== "..")
|
|
1184
|
+
);
|
|
1185
|
+
return missingDiagnostic(path2, lookup);
|
|
1186
|
+
}
|
|
1187
|
+
function walk(nodes, stack, guards) {
|
|
1188
|
+
const diagnostics = [];
|
|
1189
|
+
for (const node of nodes) {
|
|
1190
|
+
if (node.kind === "ref") {
|
|
1191
|
+
diagnostics.push(...inspectRef(node, stack, guards));
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
const absolute = absoluteSegments(node.path, node.parentHops, stack);
|
|
1195
|
+
const missing = absolute ? null : contractDiagnostic(node.path, "missing");
|
|
1196
|
+
if (!absolute || missing) {
|
|
1197
|
+
if (missing) diagnostics.push(missing);
|
|
1198
|
+
continue;
|
|
1199
|
+
}
|
|
1200
|
+
const lookup = lookupAt(stack, node.parentHops, absolute.local);
|
|
1201
|
+
const issue = contractDiagnostic(node.path, lookup.status);
|
|
1202
|
+
if (issue) {
|
|
1203
|
+
diagnostics.push(issue);
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
if (lookup.status !== "found") continue;
|
|
1207
|
+
if (node.block === "each") {
|
|
1208
|
+
const elements = arrayElements(lookup.schema);
|
|
1209
|
+
if (!elements) {
|
|
1210
|
+
diagnostics.push(errorDiagnostic("PATH001", `Path "${node.path}" is not an array.`, { path: node.path }));
|
|
1211
|
+
continue;
|
|
1212
|
+
}
|
|
1213
|
+
const child = { schema: elements, prefix: [...absolute.segments, "[]"] };
|
|
1214
|
+
const outer = framesAt(stack, node.parentHops);
|
|
1215
|
+
diagnostics.push(...walk(node.children, [...outer, child], guards));
|
|
1216
|
+
diagnostics.push(...walk(node.fallback, outer, guards));
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
const nextGuards = [...guards, absolute.segments];
|
|
1220
|
+
diagnostics.push(...walk(node.children, stack, nextGuards));
|
|
1221
|
+
diagnostics.push(...walk(node.fallback, stack, nextGuards));
|
|
1222
|
+
}
|
|
1223
|
+
return diagnostics;
|
|
1224
|
+
}
|
|
1225
|
+
function inspectRef(node, stack, guards) {
|
|
1226
|
+
const diagnostics = [];
|
|
1227
|
+
if (node.path) diagnostics.push(...inspectPath(node.path, node.parentHops, stack, guards));
|
|
1228
|
+
for (const arg of node.args ?? []) {
|
|
1229
|
+
if (arg.kind === "path") diagnostics.push(...inspectPath(arg.emitted, arg.parentHops, stack, guards));
|
|
1230
|
+
}
|
|
1231
|
+
return diagnostics;
|
|
1232
|
+
}
|
|
1233
|
+
function inspectPath(path2, hops, stack, guards) {
|
|
1234
|
+
const absolute = absoluteSegments(path2, hops, stack);
|
|
1235
|
+
if (!absolute) {
|
|
1236
|
+
const missing = contractDiagnostic(path2, "missing");
|
|
1237
|
+
return missing ? [missing] : [];
|
|
1238
|
+
}
|
|
1239
|
+
const lookup = lookupAt(stack, hops, absolute.local);
|
|
1240
|
+
const issue = contractDiagnostic(path2, lookup.status);
|
|
1241
|
+
if (issue) return [issue];
|
|
1242
|
+
if (lookup.status === "found" && lookup.optional && !guarded(absolute.segments, guards)) {
|
|
1243
|
+
return [warningDiagnostic("PATH002", `Optional path "${path2}" is used without a guard.`, { path: path2 })];
|
|
1244
|
+
}
|
|
1245
|
+
return [];
|
|
1246
|
+
}
|
|
1247
|
+
function missingDiagnostic(path2, lookup) {
|
|
1248
|
+
return contractDiagnostic(path2, lookup.status);
|
|
1249
|
+
}
|
|
1250
|
+
function contractDiagnostic(path2, status) {
|
|
1251
|
+
if (status === "missing") {
|
|
1252
|
+
return errorDiagnostic("PATH001", `Path "${path2}" does not exist in the contract.`, { path: path2 });
|
|
1253
|
+
}
|
|
1254
|
+
if (status === "unanalyzable") {
|
|
1255
|
+
return errorDiagnostic("PATH_UNANALYZABLE", `Path "${path2}" cannot be analyzed.`, { path: path2 });
|
|
1256
|
+
}
|
|
1257
|
+
return null;
|
|
1258
|
+
}
|
|
1259
|
+
function guarded(segments, guards) {
|
|
1260
|
+
return guards.some(
|
|
1261
|
+
(guard) => guard.length > 0 && guard.length <= segments.length && guard.every((part, index) => part === segments[index])
|
|
1262
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
function framesAt(stack, hops) {
|
|
1265
|
+
const depth = Math.max(0, stack.length - 1 - hops);
|
|
1266
|
+
return stack.slice(0, depth + 1);
|
|
1267
|
+
}
|
|
1268
|
+
function absoluteSegments(path2, hops, stack) {
|
|
1269
|
+
const parsed = parsePath(path2, true);
|
|
1270
|
+
if (!parsed.ok) return null;
|
|
1271
|
+
const local = parsed.segments.filter((segment) => segment !== "..");
|
|
1272
|
+
const base = framesAt(stack, hops).at(-1)?.prefix ?? [];
|
|
1273
|
+
return { local, segments: [...base, ...local] };
|
|
1274
|
+
}
|
|
1275
|
+
function lookupAt(stack, hops, segments) {
|
|
1276
|
+
const frame = framesAt(stack, hops).at(-1);
|
|
1277
|
+
if (!frame) return { status: "missing" };
|
|
1278
|
+
return resolve(frame.schema, segments);
|
|
1279
|
+
}
|
|
1280
|
+
function resolve(schema, segments) {
|
|
1281
|
+
const peeled = peelSchema(schema);
|
|
1282
|
+
if (peeled.status !== "ready") return peeled;
|
|
1283
|
+
if (segments.length === 0) return { status: "found", optional: peeled.optional, schema: peeled.schema };
|
|
1284
|
+
const current = schemaDef(peeled.schema);
|
|
1285
|
+
if (current?.type === "union" && current.options) {
|
|
1286
|
+
const results = current.options.map((option) => resolve(option, segments));
|
|
1287
|
+
if (results.some((result) => result.status === "unanalyzable")) return { status: "unanalyzable" };
|
|
1288
|
+
const found = results.filter((result) => result.status === "found");
|
|
1289
|
+
if (found.length === 0) return { status: "missing" };
|
|
1290
|
+
const optional = peeled.optional || found.length !== results.length || found.some((result) => result.optional);
|
|
1291
|
+
return { status: "found", optional, schema: combineSchemas(found.map((result) => result.schema)) };
|
|
1292
|
+
}
|
|
1293
|
+
if (current?.type === "object" && current.shape) {
|
|
1294
|
+
const field = current.shape[segments[0] ?? ""];
|
|
1295
|
+
if (!field) return { status: "missing" };
|
|
1296
|
+
const next = resolve(field, segments.slice(1));
|
|
1297
|
+
if (next.status !== "found") return next;
|
|
1298
|
+
return { status: "found", optional: peeled.optional || next.optional, schema: next.schema };
|
|
1299
|
+
}
|
|
1300
|
+
if (current?.type === "array" && current.element) {
|
|
1301
|
+
if (!/^[0-9]+$/.test(segments[0] ?? "")) return { status: "missing" };
|
|
1302
|
+
const next = resolve(current.element, segments.slice(1));
|
|
1303
|
+
if (next.status !== "found") return next;
|
|
1304
|
+
return { status: "found", optional: peeled.optional || next.optional, schema: next.schema };
|
|
1305
|
+
}
|
|
1306
|
+
if (isScalarType(current?.type)) return { status: "missing" };
|
|
1307
|
+
return { status: "unanalyzable" };
|
|
1308
|
+
}
|
|
1309
|
+
function arrayElements(schema) {
|
|
1310
|
+
const peeled = peelSchema(schema);
|
|
1311
|
+
if (peeled.status !== "ready") return null;
|
|
1312
|
+
const current = schemaDef(peeled.schema);
|
|
1313
|
+
if (current?.type === "array" && current.element) return current.element;
|
|
1314
|
+
if (current?.type === "union" && current.options) {
|
|
1315
|
+
const elements = [];
|
|
1316
|
+
for (const option of current.options) {
|
|
1317
|
+
const element = arrayElements(option);
|
|
1318
|
+
if (!element) return null;
|
|
1319
|
+
elements.push(element);
|
|
1320
|
+
}
|
|
1321
|
+
return combineSchemas(elements);
|
|
1322
|
+
}
|
|
1323
|
+
return null;
|
|
1324
|
+
}
|
|
1325
|
+
export {
|
|
1326
|
+
TOKEN_BODY_LENGTH,
|
|
1327
|
+
TOKEN_LENGTH,
|
|
1328
|
+
TOKEN_PREFIX,
|
|
1329
|
+
TemplateFailure,
|
|
1330
|
+
analyzePaths,
|
|
1331
|
+
analyzeRootPath,
|
|
1332
|
+
assembleDocument,
|
|
1333
|
+
bindSites,
|
|
1334
|
+
checkCatalogs,
|
|
1335
|
+
checkFixture,
|
|
1336
|
+
commitArtifacts,
|
|
1337
|
+
emitBlockClose,
|
|
1338
|
+
emitBlockOpen,
|
|
1339
|
+
emitHelperCall,
|
|
1340
|
+
emitInterpolation,
|
|
1341
|
+
emitLiteral,
|
|
1342
|
+
emitPath,
|
|
1343
|
+
errorDiagnostic,
|
|
1344
|
+
evaluateArtifact,
|
|
1345
|
+
findCapability,
|
|
1346
|
+
isSafeEmailId,
|
|
1347
|
+
mergeLocaleDocuments,
|
|
1348
|
+
mintToken,
|
|
1349
|
+
nestSites,
|
|
1350
|
+
normalizeOutput,
|
|
1351
|
+
opaqueTokenIssue,
|
|
1352
|
+
parentHops,
|
|
1353
|
+
parseMessage,
|
|
1354
|
+
parsePath,
|
|
1355
|
+
placeholderSignature,
|
|
1356
|
+
readPathValue,
|
|
1357
|
+
releaseArtifacts,
|
|
1358
|
+
renderTemplate,
|
|
1359
|
+
restoreHandlebars,
|
|
1360
|
+
scanTokens,
|
|
1361
|
+
schemaMutates,
|
|
1362
|
+
sha256,
|
|
1363
|
+
singleDocumentIssue,
|
|
1364
|
+
syntaxHelperNames,
|
|
1365
|
+
unverifiedCapabilityDiagnostic,
|
|
1366
|
+
validateHandlebarsSyntax,
|
|
1367
|
+
warningDiagnostic,
|
|
1368
|
+
withForcedLocale
|
|
1369
|
+
};
|