@powerformer/prism-client 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,483 @@
1
+ import {
2
+ registerReadObserver
3
+ } from "./chunk-MYDJI2NW.js";
4
+
5
+ // app/sdk/visual-map.ts
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ import { execFileSync } from "node:child_process";
8
+ import { createCipheriv, createDecipheriv, privateDecrypt, publicEncrypt, randomBytes, constants } from "node:crypto";
9
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+ var TRACE_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/visual-trace-storage/v1");
12
+ function traceStorage() {
13
+ let host = globalThis;
14
+ return host[TRACE_STORAGE_KEY] ??= new AsyncLocalStorage();
15
+ }
16
+ var LIVE_ROUTES_KEY = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/visual-live-routes/v1");
17
+ function liveRouteStore() {
18
+ let host = globalThis;
19
+ return host[LIVE_ROUTES_KEY] ??= /* @__PURE__ */ new Map();
20
+ }
21
+ var autoHooked = !1;
22
+ function enableAutomaticReadTracing() {
23
+ autoHooked || (autoHooked = !0, registerReadObserver((event) => {
24
+ recordPrismRead({
25
+ resourceId: event.resourceId,
26
+ locale: event.locale,
27
+ publicationId: event.meta.publicationId,
28
+ versionId: event.meta.versionId,
29
+ generation: event.meta.generation,
30
+ visualExpectations: event.meta.visualExpectations
31
+ });
32
+ }));
33
+ }
34
+ function runWithPageTrace(pathname, fn) {
35
+ let store = { pathname, reads: /* @__PURE__ */ new Map() };
36
+ return Promise.resolve(traceStorage().run(store, fn));
37
+ }
38
+ function currentPageTrace() {
39
+ return traceStorage().getStore();
40
+ }
41
+ var DEFAULT_TRACE_LOCALES = ["en", "zh", "ja", "ko", "de", "fr", "ru", "es", "pt-br", "it", "tr"];
42
+ function recordPrismRead(record) {
43
+ let store = traceStorage().getStore();
44
+ if (!store) return;
45
+ if (record.canonicalPath) {
46
+ let tracedCanonical = stripLocalePrefix(store.pathname, DEFAULT_TRACE_LOCALES).canonicalPath;
47
+ if (normalizePathname(record.canonicalPath) !== tracedCanonical) return;
48
+ }
49
+ let key = `${record.resourceId}:${record.locale}:${record.pageId ?? record.selector?.keyValue ?? "*"}`, prev = store.reads.get(key);
50
+ prev && prev.selector && !record.selector || store.reads.set(key, {
51
+ ...prev,
52
+ ...record,
53
+ visualExpectations: record.visualExpectations ?? prev?.visualExpectations
54
+ });
55
+ }
56
+ function recordLivePageReads(pathname, reads) {
57
+ reads.length && liveRouteStore().set(normalizePathname(pathname), reads);
58
+ }
59
+ function getLivePageReads() {
60
+ return liveRouteStore();
61
+ }
62
+ function appendWorkerTrace(traceDir, pathname, reads) {
63
+ if (!reads.length) return;
64
+ mkdirSync(traceDir, { recursive: !0 });
65
+ let file = join(traceDir, `worker-${process.pid}.ndjson`);
66
+ appendFileSync(file, `${JSON.stringify({ pathname: normalizePathname(pathname), reads })}
67
+ `, "utf8");
68
+ }
69
+ function normalizePathname(pathname) {
70
+ let clean = pathname.split(/[?#]/)[0] || "/", withLead = clean.startsWith("/") ? clean : `/${clean}`;
71
+ return withLead === "/" || /\.[a-z0-9]+$/i.test(withLead) || withLead.endsWith("/") ? withLead : `${withLead}/`;
72
+ }
73
+ function stripLocalePrefix(pathname, locales) {
74
+ let norm = normalizePathname(pathname), nonDefault = locales.filter((l) => l !== "en");
75
+ for (let loc of nonDefault) {
76
+ if (norm === `/${loc}/`) return { locale: loc, canonicalPath: "/" };
77
+ if (norm.startsWith(`/${loc}/`)) return { locale: loc, canonicalPath: norm.slice(loc.length + 1) };
78
+ }
79
+ return { locale: "en", canonicalPath: norm };
80
+ }
81
+ function resolveBuildRef(rootDir) {
82
+ let fromEnv = process.env.GITHUB_SHA || process.env.CF_PAGES_COMMIT_SHA || process.env.PRISM_BUILD_REF;
83
+ if (fromEnv && /^[a-f0-9]{7,40}$/i.test(fromEnv.trim())) return fromEnv.trim();
84
+ try {
85
+ return execFileSync("git", ["rev-parse", "HEAD"], { cwd: rootDir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ function isVisualEnvelope(value) {
91
+ if (!value || typeof value != "object") return !1;
92
+ let v = value;
93
+ return v.v === 1 && v.alg === "RSA-OAEP-256+A256GCM" && typeof v.kid == "string" && typeof v.ek == "string" && typeof v.iv == "string" && typeof v.ct == "string";
94
+ }
95
+ function encryptVisualEnvelope(payload, publicKeyPem, kid = "prism-visual-v1") {
96
+ let dek = randomBytes(32), iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", dek, iv), plaintext = Buffer.from(JSON.stringify(payload), "utf8"), encrypted = Buffer.concat([cipher.update(plaintext), cipher.final(), cipher.getAuthTag()]), ek = publicEncrypt({ key: publicKeyPem, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" }, dek);
97
+ return {
98
+ v: 1,
99
+ alg: "RSA-OAEP-256+A256GCM",
100
+ kid,
101
+ ek: ek.toString("base64"),
102
+ iv: iv.toString("base64"),
103
+ ct: encrypted.toString("base64")
104
+ };
105
+ }
106
+ function decryptVisualEnvelope(envelope, privateKeyPem) {
107
+ let dek = privateDecrypt(
108
+ { key: privateKeyPem, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
109
+ Buffer.from(envelope.ek, "base64")
110
+ ), iv = Buffer.from(envelope.iv, "base64"), raw = Buffer.from(envelope.ct, "base64");
111
+ if (raw.length < 16) throw new Error("Invalid visual envelope ciphertext");
112
+ let ct = raw.subarray(0, raw.length - 16), tag = raw.subarray(raw.length - 16), decipher = createDecipheriv("aes-256-gcm", dek, iv);
113
+ decipher.setAuthTag(tag);
114
+ let text = Buffer.concat([decipher.update(ct), decipher.final()]).toString("utf8");
115
+ return JSON.parse(text);
116
+ }
117
+ function readOverridesFile(filePath) {
118
+ return !filePath || !existsSync(filePath) ? {} : JSON.parse(readFileSync(filePath, "utf8"));
119
+ }
120
+ function buildVisualConfigFromTraces(input) {
121
+ let overrides = input.overrides ?? {}, locales = overrides.locales?.length ? [...overrides.locales] : ["en", "zh", "ja", "ko", "de", "fr", "ru", "es", "pt-br", "it", "tr"], ignoreSelectors = overrides.ignoreSelectors?.length ? [...overrides.ignoreSelectors] : ["header", "footer", "nav", ".site-chrome", '[aria-hidden="true"]'], resources = {}, expectationMap = /* @__PURE__ */ new Map(), canonicalPages = /* @__PURE__ */ new Map();
122
+ for (let [pathname, reads] of input.pageReads.entries()) {
123
+ let { canonicalPath } = stripLocalePrefix(pathname, locales), list = canonicalPages.get(canonicalPath) ?? [];
124
+ for (let read of reads)
125
+ resources[read.resourceId] = {
126
+ ...read.module ? { module: read.module } : {},
127
+ publicationId: read.publicationId,
128
+ versionId: read.versionId,
129
+ generation: read.generation
130
+ }, read.visualExpectations?.length && expectationMap.set(`${read.resourceId}:${read.versionId}`, {
131
+ resourceId: read.resourceId,
132
+ versionId: read.versionId,
133
+ expectations: read.visualExpectations
134
+ }), list.some((item) => item.resourceId === read.resourceId && item.selector?.keyValue === read.selector?.keyValue) || list.push(read);
135
+ canonicalPages.set(canonicalPath, list);
136
+ }
137
+ let patternBuckets = /* @__PURE__ */ new Map();
138
+ for (let [canonicalPath, reads] of canonicalPages.entries()) {
139
+ let segments = canonicalPath.split("/").filter(Boolean), lastSeg = segments[segments.length - 1], pattern = canonicalPath, bindings = [];
140
+ for (let r of reads)
141
+ if (r.selector && lastSeg && r.selector.keyValue === lastSeg && segments.length >= 2) {
142
+ let paramName = r.selector.keyField === "slug" ? "slug" : "id";
143
+ pattern = `/${segments.slice(0, -1).join("/")}/:${paramName}/`, bindings.push({
144
+ resourceId: r.resourceId,
145
+ ...r.module ? { module: r.module } : {},
146
+ selector: { collection: r.selector.collection, keyField: r.selector.keyField, fromParam: paramName }
147
+ });
148
+ } else
149
+ bindings.push({
150
+ resourceId: r.resourceId,
151
+ ...r.module ? { module: r.module } : {},
152
+ ...r.selector ? { selector: r.selector } : {}
153
+ });
154
+ let existing = patternBuckets.get(pattern) ?? [];
155
+ for (let b of bindings) {
156
+ let sig = JSON.stringify(b);
157
+ existing.some((e) => JSON.stringify(e) === sig) || existing.push(b);
158
+ }
159
+ patternBuckets.set(pattern, existing);
160
+ }
161
+ let routes = [], moduleToResourceId = /* @__PURE__ */ new Map();
162
+ for (let [rid, meta] of Object.entries(resources))
163
+ meta.module && moduleToResourceId.set(meta.module, rid);
164
+ for (let [pattern, bindings] of [...patternBuckets.entries()].sort(([a], [b]) => a.localeCompare(b))) {
165
+ let matchedDeclared = (overrides.routes ?? []).filter((r) => r.pattern === pattern), matchingRouteOverrides = matchedDeclared.flatMap((r) => r.overrides ?? []), matchingModuleOverrides = bindings.flatMap((b) => b.module && overrides.modules?.[b.module]?.overrides ? overrides.modules[b.module].overrides : []), mergedOverrides = [...matchingRouteOverrides, ...matchingModuleOverrides], mergedPolicies = Object.assign({}, ...matchedDeclared.map((r) => r.listPolicies ?? {}));
166
+ routes.push({
167
+ pattern,
168
+ bindings,
169
+ ...mergedOverrides.length ? { overrides: mergedOverrides } : {},
170
+ ...Object.keys(mergedPolicies).length ? { listPolicies: mergedPolicies } : {}
171
+ });
172
+ }
173
+ for (let declared of overrides.routes ?? []) {
174
+ if (routes.some((r) => r.pattern === declared.pattern)) continue;
175
+ let rid = declared.resourceId ?? (declared.module ? moduleToResourceId.get(declared.module) : void 0), bindings = declared.bindings?.length ? declared.bindings : rid ? [{
176
+ resourceId: rid,
177
+ ...declared.module ? { module: declared.module } : {},
178
+ ...declared.selector ? { selector: declared.selector } : {}
179
+ }] : [];
180
+ bindings.length && routes.push({
181
+ pattern: declared.pattern,
182
+ bindings,
183
+ ...declared.overrides?.length ? { overrides: declared.overrides } : {},
184
+ ...declared.listPolicies && Object.keys(declared.listPolicies).length ? { listPolicies: declared.listPolicies } : {}
185
+ });
186
+ }
187
+ return {
188
+ publicConfig: {
189
+ schemaVersion: 1,
190
+ environment: input.environment,
191
+ buildRef: input.buildRef,
192
+ locales,
193
+ ignoreSelectors,
194
+ resources,
195
+ routes
196
+ },
197
+ expectations: [...expectationMap.values()]
198
+ };
199
+ }
200
+ var VOID_TAGS = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
201
+ function decodeEntities(s) {
202
+ return s.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;|&apos;/gi, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)));
203
+ }
204
+ function parseMiniHtml(html) {
205
+ let root = { type: "element", tag: "#document", attrs: {}, text: "", children: [], parent: null }, stack = [root], tokenRe = /<!--[\s\S]*?-->|<!DOCTYPE[^>]*>|<\/([a-zA-Z][a-zA-Z0-9:-]*)\s*>|<([a-zA-Z][a-zA-Z0-9:-]*)((?:\s+[^<>'"=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|([^<]+)/g, m, rawSkipTag = null;
206
+ for (; (m = tokenRe.exec(html)) !== null; ) {
207
+ let [, closeTag, openTag, rawAttrs, selfClose, textChunk] = m;
208
+ if (rawSkipTag) {
209
+ closeTag && closeTag.toLowerCase() === rawSkipTag && (rawSkipTag = null, stack.length > 1 && stack.pop());
210
+ continue;
211
+ }
212
+ if (closeTag) {
213
+ let target = closeTag.toLowerCase();
214
+ for (let i = stack.length - 1; i >= 1; i--)
215
+ if (stack[i].tag === target) {
216
+ stack.length = i;
217
+ break;
218
+ }
219
+ continue;
220
+ }
221
+ if (openTag) {
222
+ let tag = openTag.toLowerCase(), attrs = {};
223
+ if (rawAttrs) {
224
+ let attrRe = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g, am;
225
+ for (; (am = attrRe.exec(rawAttrs)) !== null; )
226
+ attrs[am[1].toLowerCase()] = decodeEntities(am[2] ?? am[3] ?? am[4] ?? "");
227
+ }
228
+ let parent = stack[stack.length - 1], el = { type: "element", tag, attrs, text: "", children: [], parent };
229
+ parent.children.push(el), tag === "script" || tag === "style" ? selfClose || (stack.push(el), rawSkipTag = tag) : !selfClose && !VOID_TAGS.has(tag) && stack.push(el);
230
+ continue;
231
+ }
232
+ if (textChunk) {
233
+ let parent = stack[stack.length - 1];
234
+ parent.children.push({ type: "text", tag: "#text", attrs: {}, text: decodeEntities(textChunk), children: [], parent });
235
+ }
236
+ }
237
+ return root;
238
+ }
239
+ function nodeText(node) {
240
+ return node.type === "text" ? node.text : node.tag === "script" || node.tag === "style" ? "" : node.children.map(nodeText).join("");
241
+ }
242
+ function normalizeSpace(s) {
243
+ return s.normalize("NFKC").replace(/[\u2018\u2019]/g, "'").replace(/[\u201C\u201D]/g, '"').replace(/\s+/g, " ").trim();
244
+ }
245
+ function descendants(node) {
246
+ let out = [], walk = (n) => {
247
+ for (let c of n.children)
248
+ c.type === "element" && (out.push(c), walk(c));
249
+ };
250
+ return walk(node), out;
251
+ }
252
+ function matchesPredicate(el, pred, indexInParent) {
253
+ let trimmed = pred.trim();
254
+ if (/^\d+$/.test(trimmed)) return indexInParent === Number(trimmed);
255
+ let parts = trimmed.split(/\s+and\s+/i);
256
+ for (let part of parts) {
257
+ let p = part.trim(), eqAttr = /^@([a-zA-Z0-9_:-]+)\s*=\s*['"]([^'"]*)['"]$/.exec(p);
258
+ if (eqAttr) {
259
+ if ((el.attrs[eqAttr[1].toLowerCase()] ?? null) !== eqAttr[2]) return !1;
260
+ continue;
261
+ }
262
+ let containsAttr = /^contains\(\s*@([a-zA-Z0-9_:-]+)\s*,\s*['"]([^'"]*)['"]\s*\)$/.exec(p);
263
+ if (containsAttr) {
264
+ if (!(el.attrs[containsAttr[1].toLowerCase()] ?? "").includes(containsAttr[2])) return !1;
265
+ continue;
266
+ }
267
+ let hasAttr = /^@([a-zA-Z0-9_:-]+)$/.exec(p);
268
+ if (hasAttr) {
269
+ if (!Object.hasOwn(el.attrs, hasAttr[1].toLowerCase())) return !1;
270
+ continue;
271
+ }
272
+ let normEq = /^normalize-space\(\s*\)\s*=\s*['"]([^'"]*)['"]$/.exec(p);
273
+ if (normEq) {
274
+ if (normalizeSpace(nodeText(el)) !== normalizeSpace(normEq[1])) return !1;
275
+ continue;
276
+ }
277
+ return !1;
278
+ }
279
+ return !0;
280
+ }
281
+ function evaluateHtmlXPath(html, xpath) {
282
+ let doc = parseMiniHtml(html), expr = xpath.trim(), attrExtract = null, trailingAttr = /\/@([a-zA-Z0-9_:-]+)$/.exec(expr);
283
+ trailingAttr && (attrExtract = trailingAttr[1].toLowerCase(), expr = expr.slice(0, trailingAttr.index));
284
+ let steps = [], i = 0;
285
+ for (; i < expr.length; ) {
286
+ let deep = !1;
287
+ expr.startsWith("//", i) ? (deep = !0, i += 2) : expr[i] === "/" && (i += 1);
288
+ let raw = "", depth = 0, quote = null;
289
+ for (; i < expr.length; ) {
290
+ let ch = expr[i];
291
+ if (quote) {
292
+ raw += ch, ch === quote && (quote = null), i++;
293
+ continue;
294
+ }
295
+ if (ch === "'" || ch === '"') {
296
+ quote = ch, raw += ch, i++;
297
+ continue;
298
+ }
299
+ if (ch === "[") {
300
+ depth++, raw += ch, i++;
301
+ continue;
302
+ }
303
+ if (ch === "]") {
304
+ depth--, raw += ch, i++;
305
+ continue;
306
+ }
307
+ if (ch === "/" && depth === 0) break;
308
+ raw += ch, i++;
309
+ }
310
+ if (!raw) continue;
311
+ let tagMatch = /^([a-zA-Z0-9_*-]+)/.exec(raw), tag = (tagMatch?.[1] ?? "*").toLowerCase(), predicates = [], rest = raw.slice(tagMatch?.[0].length ?? 0), p = 0;
312
+ for (; p < rest.length; )
313
+ if (rest[p] === "[") {
314
+ let d = 1, q = null, buf = "";
315
+ for (p++; p < rest.length && d > 0; ) {
316
+ let ch = rest[p];
317
+ if (q) {
318
+ buf += ch, ch === q && (q = null), p++;
319
+ continue;
320
+ }
321
+ if (ch === "'" || ch === '"') {
322
+ q = ch, buf += ch, p++;
323
+ continue;
324
+ }
325
+ if (ch === "[") d++;
326
+ else if (ch === "]" && (d--, d === 0)) {
327
+ p++;
328
+ break;
329
+ }
330
+ buf += ch, p++;
331
+ }
332
+ predicates.push(buf);
333
+ } else p++;
334
+ steps.push({ deep, tag, predicates });
335
+ }
336
+ let current = [doc];
337
+ for (let step of steps) {
338
+ let next = [], seen = /* @__PURE__ */ new Set();
339
+ for (let ctx of current) {
340
+ let byTag = (step.deep ? descendants(ctx) : ctx.children.filter((c) => c.type === "element")).filter((el) => step.tag === "*" || el.tag === step.tag);
341
+ for (let el of byTag) {
342
+ if (seen.has(el)) continue;
343
+ let pos = (el.parent?.children ?? []).filter((c) => c.type === "element" && (step.tag === "*" || c.tag === el.tag)).indexOf(el) + 1;
344
+ step.predicates.every((pred) => matchesPredicate(el, pred, pos)) && (seen.add(el), next.push(el));
345
+ }
346
+ }
347
+ current = next;
348
+ }
349
+ return current.map((el) => attrExtract ? { text: el.attrs[attrExtract] ?? "", attr: attrExtract } : { text: normalizeSpace(nodeText(el)) });
350
+ }
351
+ function verifyVisualExpectations(input) {
352
+ let items = [];
353
+ for (let bundle of input.bundles)
354
+ for (let exp of bundle.expectations) {
355
+ let normPath = normalizePathname(exp.pagePath), rel = normPath === "/" ? "index.html" : `${normPath.replace(/^\/|\/$/g, "")}/index.html`, htmlPath = resolve(input.outDir, rel);
356
+ if (!existsSync(htmlPath)) {
357
+ items.push({
358
+ resourceId: bundle.resourceId,
359
+ versionId: bundle.versionId,
360
+ pagePath: normPath,
361
+ xpath: exp.xpath,
362
+ pointer: exp.pointer,
363
+ locale: exp.locale,
364
+ status: "page_not_found",
365
+ expected: exp.expectedValue,
366
+ actual: null,
367
+ detail: `Built HTML file not found: ${rel}`
368
+ });
369
+ continue;
370
+ }
371
+ let html = readFileSync(htmlPath, "utf8"), matches = evaluateHtmlXPath(html, exp.xpath);
372
+ if (matches.length === 0) {
373
+ items.push({
374
+ resourceId: bundle.resourceId,
375
+ versionId: bundle.versionId,
376
+ pagePath: normPath,
377
+ xpath: exp.xpath,
378
+ pointer: exp.pointer,
379
+ locale: exp.locale,
380
+ status: "xpath_not_found",
381
+ expected: exp.expectedValue,
382
+ actual: null,
383
+ detail: `XPath matched 0 nodes in ${rel}`
384
+ });
385
+ continue;
386
+ }
387
+ let actual = matches[0].text, ok = !1, expectedStr = typeof exp.expectedValue == "string" ? normalizeSpace(exp.expectedValue) : String(exp.expectedValue);
388
+ if (exp.matchType === "exact-text")
389
+ ok = actual === expectedStr;
390
+ else if (exp.matchType === "media-src")
391
+ ok = actual === String(exp.expectedValue) || actual.includes(String(exp.expectedValue));
392
+ else if (exp.matchType === "override-number")
393
+ ok = actual.includes(String(exp.expectedValue)) && !/\b(?:NaN|undefined|null)\b/.test(actual);
394
+ else if (exp.matchType === "template-segments") {
395
+ let plain = normalizeSpace(expectedStr.replace(/\*\*/g, "").replace(/\{[^}]+\}/g, " ")), segments = expectedStr.replace(/\*\*/g, "").split(/\{[^}]+\}/).map(normalizeSpace).filter((s) => s.length >= 3);
396
+ ok = segments.length > 0 ? segments.every((seg) => actual.includes(seg)) : actual.includes(plain);
397
+ } else if (exp.matchType === "richtext-html") {
398
+ let stripped = normalizeSpace(String(exp.expectedValue).replace(/<[^>]+>/g, " ")), head = stripped.slice(0, Math.min(40, stripped.length));
399
+ ok = head.length > 0 && actual.includes(head);
400
+ }
401
+ items.push({
402
+ resourceId: bundle.resourceId,
403
+ versionId: bundle.versionId,
404
+ pagePath: normPath,
405
+ xpath: exp.xpath,
406
+ pointer: exp.pointer,
407
+ locale: exp.locale,
408
+ status: ok ? "passed" : "value_mismatch",
409
+ expected: exp.expectedValue,
410
+ actual,
411
+ detail: ok ? "Matched expected rendered output" : `Expected "${expectedStr}" but rendered "${actual}"`
412
+ });
413
+ }
414
+ let passed = items.filter((i) => i.status === "passed").length, failed = items.length - passed;
415
+ return { ok: failed === 0, checkedAt: (/* @__PURE__ */ new Date()).toISOString(), total: items.length, passed, failed, items };
416
+ }
417
+ function finalizeVisualArtifacts(options) {
418
+ let prismDir = resolve(options.rootDir, ".prism"), traceDir = join(prismDir, "trace"), cacheDir = join(prismDir, "cache"), cacheFile = join(cacheDir, "trace-state.json");
419
+ mkdirSync(cacheDir, { recursive: !0 });
420
+ let merged = /* @__PURE__ */ new Map();
421
+ if (existsSync(cacheFile))
422
+ try {
423
+ let prev = JSON.parse(readFileSync(cacheFile, "utf8"));
424
+ for (let [k, v] of Object.entries(prev)) {
425
+ let rel = k === "/" ? "index.html" : `${k.replace(/^\/|\/$/g, "")}/index.html`;
426
+ existsSync(resolve(options.outDir, rel)) && merged.set(k, v);
427
+ }
428
+ } catch {
429
+ }
430
+ if (existsSync(traceDir)) {
431
+ for (let file of readdirSync(traceDir).filter((f) => f.endsWith(".ndjson"))) {
432
+ let lines = readFileSync(join(traceDir, file), "utf8").split(`
433
+ `).filter(Boolean);
434
+ for (let line of lines)
435
+ try {
436
+ let entry = JSON.parse(line);
437
+ merged.set(normalizePathname(entry.pathname), entry.reads);
438
+ } catch {
439
+ }
440
+ }
441
+ rmSync(traceDir, { recursive: !0, force: !0 });
442
+ }
443
+ writeFileSync(cacheFile, JSON.stringify(Object.fromEntries(merged), null, 2) + `
444
+ `, "utf8");
445
+ let overrides = readOverridesFile(options.overridesFile ? resolve(options.rootDir, options.overridesFile) : void 0), { publicConfig, expectations } = buildVisualConfigFromTraces({
446
+ pageReads: merged,
447
+ environment: options.environment,
448
+ buildRef: resolveBuildRef(options.rootDir),
449
+ overrides
450
+ }), visualMapPath = join(prismDir, "visual-map.json");
451
+ writeFileSync(visualMapPath, JSON.stringify({
452
+ ...publicConfig,
453
+ tracedPages: merged.size
454
+ }, null, 2) + `
455
+ `, "utf8"), mkdirSync(options.outDir, { recursive: !0 });
456
+ let publicConfigPath = resolve(options.outDir, "prism-visual.json"), outputBody = options.encryptPublicKeyPem ? encryptVisualEnvelope(publicConfig, options.encryptPublicKeyPem, options.encryptKeyId ?? "prism-visual-v1") : publicConfig;
457
+ writeFileSync(publicConfigPath, JSON.stringify(outputBody) + `
458
+ `, "utf8");
459
+ let verifyReport;
460
+ return options.verify && expectations.length > 0 && (verifyReport = verifyVisualExpectations({ outDir: options.outDir, bundles: expectations }), writeFileSync(join(prismDir, "visual-verify-report.json"), JSON.stringify(verifyReport, null, 2) + `
461
+ `, "utf8")), { visualMapPath, publicConfigPath, publicConfig, verifyReport };
462
+ }
463
+
464
+ export {
465
+ enableAutomaticReadTracing,
466
+ runWithPageTrace,
467
+ currentPageTrace,
468
+ recordPrismRead,
469
+ recordLivePageReads,
470
+ getLivePageReads,
471
+ appendWorkerTrace,
472
+ normalizePathname,
473
+ stripLocalePrefix,
474
+ resolveBuildRef,
475
+ isVisualEnvelope,
476
+ encryptVisualEnvelope,
477
+ decryptVisualEnvelope,
478
+ readOverridesFile,
479
+ buildVisualConfigFromTraces,
480
+ evaluateHtmlXPath,
481
+ verifyVisualExpectations,
482
+ finalizeVisualArtifacts
483
+ };
@@ -1,13 +1,22 @@
1
1
  /** Prism delivery protocol. Browser-safe; server hashing lives in publication.ts. */
2
2
  import { z } from 'zod/v4';
3
- import type { ResourceEnvironment, ResourceManifest, ResourceManifestV2, ResourceMain } from './types.js';
4
- export type { ResourceEnvironment, ResourceManifest, ResourceManifestV2, ResourceMain } from './types.js';
3
+ import type { ResourceEnvironment, ResourceVisibility, ResourceManifest, ResourceManifestV2, ResourceMain } from './types.js';
4
+ export type { ResourceEnvironment, ResourceVisibility, ResourceManifest, ResourceManifestV2, ResourceMain } from './types.js';
5
5
  export declare const RESOURCE_CDN_ORIGIN = "https://r.open-design.ai";
6
+ export declare const RESOURCE_DEV_CDN_ORIGIN = "https://r.powerformer.net";
7
+ export declare const RESOURCE_INTERNAL_CDN_ORIGIN = "https://r-internal.powerformer.net";
6
8
  export declare const MANIFEST_PROTOCOL = "v1";
7
9
  export declare const DEFAULT_RESOURCE_CHANNEL = "stable";
8
10
  export declare const MANIFEST_CACHE_CONTROL = "no-store";
9
11
  export declare const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
12
+ export declare const PRIVATE_IMMUTABLE_CACHE_CONTROL = "private, max-age=31536000, immutable";
10
13
  export declare const REVALIDATE_CACHE_CONTROL = "no-cache";
14
+ export declare const resourceVisibilitySchema: z.ZodEnum<{
15
+ public: "public";
16
+ internal: "internal";
17
+ }>;
18
+ export declare function immutableCacheControl(visibility?: ResourceVisibility): string;
19
+ export declare function resourceFileDeliveryOrigin(visibility?: ResourceVisibility): string;
11
20
  export declare const resourceIdSchema: z.ZodString;
12
21
  export declare const channelNameSchema: z.ZodString;
13
22
  export declare const versionIdSchema: z.ZodString;
@@ -53,7 +62,7 @@ export declare function parseResourceMain(value: unknown): ResourceMain;
53
62
  export type { ResourceManifestV3, ResourceMainV2 } from './types.js';
54
63
  export declare const resourceUuidSchema: z.ZodUUID;
55
64
  export declare const slugSchema: z.ZodString;
56
- export declare function resourceDeliveryOrigin(environment: ResourceEnvironment): string;
65
+ export declare function resourceDeliveryOrigin(environment: ResourceEnvironment, visibility?: ResourceVisibility): string;
57
66
  export declare function resourcePublicMainPath(id: string, channel: string): string;
58
67
  export declare function resourcePublicManifestPath(id: string, channel: string): string;
59
68
  export declare function resourcePublicLocalePath(id: string, channel: string, locale: string): string;
@@ -67,9 +76,26 @@ export declare function resourcePublicContentPath(id: string, publicationId: str
67
76
  export declare function resourceStorageKey(environment: ResourceEnvironment, publicPath: string): string;
68
77
  export declare function parseResourceManifestV3(value: unknown): import('./types.js').ResourceManifestV3;
69
78
  export declare function buildResourceManifestV3(input: Omit<import('./types.js').ResourceManifestV3, 'manifestVersion'>): import('./types.js').ResourceManifestV3;
79
+ export declare const visualExpectationSchema: z.ZodObject<{
80
+ pagePath: z.ZodString;
81
+ xpath: z.ZodString;
82
+ pointer: z.ZodString;
83
+ locale: z.ZodString;
84
+ matchType: z.ZodEnum<{
85
+ "exact-text": "exact-text";
86
+ "template-segments": "template-segments";
87
+ "richtext-html": "richtext-html";
88
+ "media-src": "media-src";
89
+ "override-number": "override-number";
90
+ }>;
91
+ beforeValue: z.ZodOptional<z.ZodCustom<z.core.util.JSONType, z.core.util.JSONType>>;
92
+ expectedValue: z.ZodCustom<z.core.util.JSONType, z.core.util.JSONType>;
93
+ capturedBuildRef: z.ZodOptional<z.ZodString>;
94
+ createdAt: z.ZodOptional<z.ZodString>;
95
+ }, z.core.$strip>;
70
96
  export declare function parseResourceMainV2(value: unknown): import('./types.js').ResourceMainV2;
71
97
  export declare function parseResourceManifestV4(value: unknown): import('./types.js').ResourceManifestV4;
72
98
  export declare function buildResourceManifestV4(input: Omit<import('./types.js').ResourceManifestV4, 'manifestVersion'>): import('./types.js').ResourceManifestV4;
73
99
  export declare function parseDeliveryManifest(value: unknown): import('./types.js').DeliveryManifest;
74
- /** Public paths use the selected environment bucket's custom domain. */
75
- export declare function resourceDeliveryUrl(path: string, environment: ResourceEnvironment, legacyOrigin?: string): string;
100
+ /** Public paths use the selected environment/visibility bucket's custom domain. */
101
+ export declare function resourceDeliveryUrl(path: string, environment: ResourceEnvironment, legacyOrigin?: string, visibility?: ResourceVisibility): string;
@@ -1,5 +1,6 @@
1
1
  /** Portable wire types. Validation is implemented once in resource-manifest.ts. */
2
2
  export type ResourceEnvironment = 'dev' | 'prod';
3
+ export type ResourceVisibility = 'public' | 'internal';
3
4
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
4
5
  [key: string]: JsonValue;
5
6
  };
@@ -44,8 +45,20 @@ export type ResourceManifestV3 = Omit<ResourceManifestV2, 'manifestVersion' | 'm
44
45
  manifestVersion: 'v3';
45
46
  mainUrl: string;
46
47
  };
48
+ export type VisualExpectation = {
49
+ pagePath: string;
50
+ xpath: string;
51
+ pointer: string;
52
+ locale: string;
53
+ matchType: 'exact-text' | 'template-segments' | 'richtext-html' | 'media-src' | 'override-number';
54
+ beforeValue?: JsonValue;
55
+ expectedValue: JsonValue;
56
+ capturedBuildRef?: string;
57
+ createdAt?: string;
58
+ };
47
59
  export type ResourceMainV2 = Omit<ResourceMain, 'mainVersion'> & {
48
60
  mainVersion: 'v2';
61
+ visualExpectations?: VisualExpectation[];
49
62
  };
50
63
  /** Both generic and version manifests reference the selected Version's files. */
51
64
  export type ResourceManifestV4 = Omit<ResourceManifestV3, 'manifestVersion'> & {
@@ -1,6 +1,8 @@
1
1
  import type { AstroIntegration } from 'astro';
2
+ import type { Environment } from './types.js';
2
3
  export interface PrismContentOptions {
3
4
  resources: readonly string[];
5
+ visibility?: import('./types.js').Visibility;
4
6
  channel?: string;
5
7
  version?: string;
6
8
  locale?: string;
@@ -11,3 +13,30 @@ export interface PrismContentOptions {
11
13
  };
12
14
  }
13
15
  export declare function prismContent(options: PrismContentOptions): AstroIntegration;
16
+ export interface PrismVisualMapOptions {
17
+ /** Optional project overrides file relative to project root (default: 'prism.visual.json'). */
18
+ overridesFile?: string;
19
+ /** Explicit environment override; defaults to PRISM_CONTENT_ENV or ('dev' in dev, 'prod' in build). */
20
+ environment?: Environment;
21
+ /** Optional RSA public key PEM for envelope encrypting out/prism-visual.json (plaintext in local dev). */
22
+ encryptPublicKeyPem?: string;
23
+ encryptKeyId?: string;
24
+ /** Dev-only optional resolver so Chrome extension can inspect live 11-locale slices locally on 127.0.0.1. */
25
+ devSliceResolver?: (params: {
26
+ resourceId: string;
27
+ module?: string;
28
+ collection?: string;
29
+ keyField?: string;
30
+ keyValue?: string;
31
+ }) => unknown;
32
+ /** Dev-only optional provider returning initial known resource metadata before the first page load. */
33
+ devResourcesProvider?: () => Array<{
34
+ resourceId: string;
35
+ module?: string;
36
+ publicationId: string;
37
+ versionId: string;
38
+ generation: number;
39
+ }>;
40
+ }
41
+ /** Zero-template-intrusion Astro integration: traces Prism reads per page into .prism/ and out/prism-visual.json. */
42
+ export declare function prismVisualMap(options?: PrismVisualMapOptions): AstroIntegration;