@powerformer/prism-client 0.6.0 → 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.
package/build-info.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@powerformer/prism-client",
3
- "version": "0.6.0",
4
- "gitCommit": "e17454fe9ca4694c7898e91264af4b8f3a23f02c",
5
- "sourceSha256": "737da051a673a2bc1037ec3577a83519beaf69b14ecf500ac018d3cb98d913ba",
3
+ "version": "0.7.0",
4
+ "gitCommit": "c8330b2269f97bbe95a5944e6d58bc95e5b2ab86",
5
+ "sourceSha256": "bf41b5215e1bd81b7a06ce5f24c426bc189b8c061d86f7ba04b041e8d646724d",
6
6
  "contentContract": "app/contracts",
7
- "contentContractSha256": "933ed061701bdfb2d31f55a582dd8b8d329fbd9d6db25500ba9ed2126f1aa002"
7
+ "contentContractSha256": "443ac891fd70f4ff6c59193de4668cb7bd0136d879eead0b0e100e4f480ddd32"
8
8
  }
@@ -2,7 +2,7 @@ import {
2
2
  Prism,
3
3
  PrismError,
4
4
  storeFor
5
- } from "./chunk-TG3NAWSK.js";
5
+ } from "./chunk-MYDJI2NW.js";
6
6
 
7
7
  // app/sdk/runtime.ts
8
8
  var key = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/runtime/v1"), globalRegistry = globalThis, registry = globalRegistry[key] ??= /* @__PURE__ */ new Map();
@@ -15333,9 +15333,24 @@ function parseResourceManifestV3(value) {
15333
15333
  contents: input2.contents.map((item) => ({ ...item, contentUrl: resourceLocaleContentPath(input2.resourceId, input2.environment, input2.contentPublicationId, item.locale, item.sha256) }))
15334
15334
  }), manifestVersion: "v3", mainUrl: input2.mainUrl, contents: input2.contents };
15335
15335
  }
15336
+ var visualExpectationSchema = external_exports.object({
15337
+ pagePath: external_exports.string().min(1).regex(/^\//),
15338
+ xpath: external_exports.string().min(1).max(1e3),
15339
+ pointer: external_exports.string().max(500),
15340
+ locale: resourceLocaleSchema,
15341
+ matchType: external_exports.enum(["exact-text", "template-segments", "richtext-html", "media-src", "override-number"]),
15342
+ beforeValue: mainJsonValueSchema.optional(),
15343
+ expectedValue: mainJsonValueSchema,
15344
+ capturedBuildRef: external_exports.string().max(120).optional(),
15345
+ createdAt: external_exports.string().max(64).optional()
15346
+ });
15336
15347
  function parseResourceMainV2(value) {
15337
- let input2 = external_exports.object({ mainVersion: external_exports.literal("v2"), resourceId: resourceUuidSchema }).passthrough().parse(value);
15338
- return { ...parseResourceMain({ ...input2, mainVersion: "v1" }), mainVersion: "v2" };
15348
+ let input2 = external_exports.object({
15349
+ mainVersion: external_exports.literal("v2"),
15350
+ resourceId: resourceUuidSchema,
15351
+ visualExpectations: external_exports.array(visualExpectationSchema).max(500).optional()
15352
+ }).passthrough().parse(value), parsed = { ...parseResourceMain({ ...input2, mainVersion: "v1" }), mainVersion: "v2" };
15353
+ return input2.visualExpectations ? { ...parsed, visualExpectations: input2.visualExpectations } : parsed;
15339
15354
  }
15340
15355
  function parseResourceManifestV4(value) {
15341
15356
  let input2 = external_exports.object({
@@ -12,7 +12,7 @@ import {
12
12
  resourceVersionManifestPath,
13
13
  resourceVisibilitySchema,
14
14
  versionAddressSchema
15
- } from "./chunk-GGTUOAAF.js";
15
+ } from "./chunk-3B2PZHLA.js";
16
16
 
17
17
  // app/sdk/errors.ts
18
18
  var PrismError = class extends Error {
@@ -83,6 +83,59 @@ function startDevServer(store, options) {
83
83
  }
84
84
 
85
85
  // app/sdk/client.ts
86
+ var OBSERVER_KEY = /* @__PURE__ */ Symbol.for("@powerformer/prism-client/read-observers/v1");
87
+ function observerSet() {
88
+ let host = globalThis;
89
+ return host[OBSERVER_KEY] ??= /* @__PURE__ */ new Set();
90
+ }
91
+ function registerReadObserver(observer) {
92
+ let set = observerSet();
93
+ return set.add(observer), () => {
94
+ set.delete(observer);
95
+ };
96
+ }
97
+ function notifyRead(event) {
98
+ let set = globalThis[OBSERVER_KEY];
99
+ if (!(!set || set.size === 0))
100
+ for (let fn of set)
101
+ try {
102
+ fn(event);
103
+ } catch {
104
+ }
105
+ }
106
+ function readProcessEnv() {
107
+ return globalThis.process?.env;
108
+ }
109
+ function resolveEnvVersionOverrides(environment) {
110
+ let env = readProcessEnv(), rawMap = env?.PRISM_VERSION_OVERRIDE?.trim() ?? "", rawSingle = env?.PRISM_VERSION?.trim() ?? "";
111
+ if (environment === "prod" && (rawMap || rawSingle))
112
+ throw new PrismError("INVALID_CONFIG", "PRISM_VERSION_OVERRIDE and PRISM_VERSION are forbidden in prod environment");
113
+ let byResource = /* @__PURE__ */ new Map();
114
+ if (rawMap)
115
+ if (rawMap.startsWith("{")) {
116
+ let parsed;
117
+ try {
118
+ parsed = JSON.parse(rawMap);
119
+ } catch {
120
+ throw new PrismError("INVALID_CONFIG", "PRISM_VERSION_OVERRIDE JSON is invalid");
121
+ }
122
+ if (!parsed || typeof parsed != "object" || Array.isArray(parsed))
123
+ throw new PrismError("INVALID_CONFIG", "PRISM_VERSION_OVERRIDE JSON must be an object");
124
+ for (let [k, v] of Object.entries(parsed))
125
+ byResource.set(
126
+ checked(resourceUuidSchema.parse, k, "PRISM_VERSION_OVERRIDE resourceId"),
127
+ checked(versionAddressSchema.parse, v, "PRISM_VERSION_OVERRIDE version")
128
+ );
129
+ } else
130
+ for (let pair of rawMap.split(",").map((s) => s.trim()).filter(Boolean)) {
131
+ let eq = pair.indexOf("=");
132
+ if (eq < 1) throw new PrismError("INVALID_CONFIG", `Invalid PRISM_VERSION_OVERRIDE entry: ${pair}`);
133
+ let id = checked(resourceUuidSchema.parse, pair.slice(0, eq).trim(), "PRISM_VERSION_OVERRIDE resourceId"), ver = checked(versionAddressSchema.parse, pair.slice(eq + 1).trim(), "PRISM_VERSION_OVERRIDE version");
134
+ byResource.set(id, ver);
135
+ }
136
+ let fallbackVersion = rawSingle ? checked(versionAddressSchema.parse, rawSingle, "PRISM_VERSION") : void 0;
137
+ return { byResource, fallbackVersion };
138
+ }
86
139
  function checked(parse, value, field) {
87
140
  try {
88
141
  return parse(value);
@@ -133,6 +186,8 @@ function select(main, requirement) {
133
186
  }
134
187
  var ClientStore = class {
135
188
  options;
189
+ envOverrides;
190
+ envFallbackVersion;
136
191
  cache = /* @__PURE__ */ new Map();
137
192
  pending = /* @__PURE__ */ new Map();
138
193
  requirements = /* @__PURE__ */ new Map();
@@ -140,14 +195,18 @@ var ClientStore = class {
140
195
  watcher;
141
196
  constructor(options) {
142
197
  if (!options || typeof options != "object") throw new PrismError("INVALID_CONFIG", "Prism options are required");
143
- this.options = {
144
- environment: checked(resourceEnvironmentSchema.parse, options.environment, "environment"),
198
+ let environment = checked(resourceEnvironmentSchema.parse, options.environment, "environment"), overrides = resolveEnvVersionOverrides(environment);
199
+ this.envOverrides = overrides.byResource, this.envFallbackVersion = overrides.fallbackVersion, this.options = {
200
+ environment,
145
201
  visibility: checked(resourceVisibilitySchema.parse, options.visibility ?? "public", "visibility"),
146
202
  channel: checked(channelNameSchema.parse, options.channel ?? DEFAULT_EDITORIAL_CHANNEL, "channel"),
147
203
  timeoutMs: positive(options.timeoutMs ?? 8e3, "timeoutMs"),
148
204
  ...options.version === void 0 ? {} : { version: checked(versionAddressSchema.parse, options.version, "version") }
149
205
  };
150
206
  }
207
+ versionFor(id) {
208
+ return this.envOverrides.get(id) ?? this.options.version ?? this.envFallbackVersion;
209
+ }
151
210
  parse(value, id) {
152
211
  let main;
153
212
  try {
@@ -170,10 +229,11 @@ var ClientStore = class {
170
229
  if (this.allowedResources && !this.allowedResources.has(id))
171
230
  throw new PrismError("INVALID_CONFIG", `Resource ${id} must be listed in prismContent resources`, { resourceId: id });
172
231
  let cached = this.cache.get(id), cachedData = cached ? select(cached.main, requirement) : void 0, requirements = this.requirements.get(id) ?? [], added = !requirements.some((r) => r.locale === requirement.locale && r.all === requirement.all && r.parse === requirement.parse);
173
- if (added && (requirements.push(requirement), this.requirements.set(id, requirements)), cached) return { entry: cached, data: cachedData };
232
+ if (added && (requirements.push(requirement), this.requirements.set(id, requirements)), cached)
233
+ return notifyRead({ resourceId: id, locale: requirement.locale ?? cached.main.defaultLocale, all: requirement.all, meta: metadata(cached.main) }), { entry: cached, data: cachedData };
174
234
  try {
175
- let entry = await this.fetch(id);
176
- return { entry, data: select(entry.main, requirement) };
235
+ let entry = await this.fetch(id), data = select(entry.main, requirement);
236
+ return notifyRead({ resourceId: id, locale: requirement.locale ?? entry.main.defaultLocale, all: requirement.all, meta: metadata(entry.main) }), { entry, data };
177
237
  } catch (error) {
178
238
  throw added && requirements.splice(requirements.indexOf(requirement), 1), error;
179
239
  }
@@ -191,9 +251,9 @@ var ClientStore = class {
191
251
  timedOut = !0, controller.abort();
192
252
  }, this.options.timeoutMs);
193
253
  try {
194
- let path = this.options.version === void 0 ? resourcePublicMainPath(id, this.options.channel) : resourceVersionMainPath(id, this.options.channel, this.options.version), expectedVersionId = this.options.version === void 0 ? void 0 : previous?.main.versionId, origin = resourceDeliveryOrigin(this.options.environment, this.options.visibility);
195
- if (this.options.version !== void 0 && !expectedVersionId) {
196
- let response2 = await fetch(new URL(resourceVersionManifestPath(id, this.options.channel, this.options.version), origin), {
254
+ let selectedVersion = this.versionFor(id), path = selectedVersion === void 0 ? resourcePublicMainPath(id, this.options.channel) : resourceVersionMainPath(id, this.options.channel, selectedVersion), expectedVersionId = selectedVersion === void 0 ? void 0 : previous?.main.versionId, origin = resourceDeliveryOrigin(this.options.environment, this.options.visibility);
255
+ if (selectedVersion !== void 0 && !expectedVersionId) {
256
+ let response2 = await fetch(new URL(resourceVersionManifestPath(id, this.options.channel, selectedVersion), origin), {
197
257
  method: "GET",
198
258
  cache: "no-store",
199
259
  credentials: "omit",
@@ -282,6 +342,8 @@ var Prism = class _Prism {
282
342
 
283
343
  export {
284
344
  PrismError,
345
+ registerReadObserver,
346
+ resolveEnvVersionOverrides,
285
347
  storeFor,
286
348
  Prism
287
349
  };
@@ -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
+ };
@@ -76,6 +76,23 @@ export declare function resourcePublicContentPath(id: string, publicationId: str
76
76
  export declare function resourceStorageKey(environment: ResourceEnvironment, publicPath: string): string;
77
77
  export declare function parseResourceManifestV3(value: unknown): import('./types.js').ResourceManifestV3;
78
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>;
79
96
  export declare function parseResourceMainV2(value: unknown): import('./types.js').ResourceMainV2;
80
97
  export declare function parseResourceManifestV4(value: unknown): import('./types.js').ResourceManifestV4;
81
98
  export declare function buildResourceManifestV4(input: Omit<import('./types.js').ResourceManifestV4, 'manifestVersion'>): import('./types.js').ResourceManifestV4;
@@ -45,8 +45,20 @@ export type ResourceManifestV3 = Omit<ResourceManifestV2, 'manifestVersion' | 'm
45
45
  manifestVersion: 'v3';
46
46
  mainUrl: string;
47
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
+ };
48
59
  export type ResourceMainV2 = Omit<ResourceMain, 'mainVersion'> & {
49
60
  mainVersion: 'v2';
61
+ visualExpectations?: VisualExpectation[];
50
62
  };
51
63
  /** Both generic and version manifests reference the selected Version's files. */
52
64
  export type ResourceManifestV4 = Omit<ResourceManifestV3, 'manifestVersion'> & {
@@ -1,4 +1,5 @@
1
1
  import type { AstroIntegration } from 'astro';
2
+ import type { Environment } from './types.js';
2
3
  export interface PrismContentOptions {
3
4
  resources: readonly string[];
4
5
  visibility?: import('./types.js').Visibility;
@@ -12,3 +13,30 @@ export interface PrismContentOptions {
12
13
  };
13
14
  }
14
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;
package/dist/sdk/astro.js CHANGED
@@ -1,15 +1,25 @@
1
+ import {
2
+ buildVisualConfigFromTraces,
3
+ enableAutomaticReadTracing,
4
+ finalizeVisualArtifacts,
5
+ getLivePageReads,
6
+ readOverridesFile,
7
+ resolveBuildRef
8
+ } from "../chunk-NSC3MYAU.js";
1
9
  import {
2
10
  getRuntime,
3
11
  releaseRuntime,
4
12
  runtimeSeeds
5
- } from "../chunk-VQYM3WCM.js";
13
+ } from "../chunk-2G5GDKYE.js";
6
14
  import {
7
15
  PrismError
8
- } from "../chunk-TG3NAWSK.js";
9
- import "../chunk-GGTUOAAF.js";
16
+ } from "../chunk-MYDJI2NW.js";
17
+ import "../chunk-3B2PZHLA.js";
10
18
 
11
19
  // app/sdk/astro.ts
12
20
  import { randomUUID } from "node:crypto";
21
+ import { join, resolve } from "node:path";
22
+ import { fileURLToPath } from "node:url";
13
23
  var virtualId = "virtual:prism", resolvedId = "\0virtual:prism";
14
24
  function prismContent(options) {
15
25
  if (!options.resources?.length) throw new PrismError("INVALID_CONFIG", "prismContent resources must not be empty");
@@ -76,6 +86,96 @@ export const prismClient = getRuntime(${JSON.stringify(runtimeId)}, ${JSON.strin
76
86
  }
77
87
  };
78
88
  }
89
+ function prismVisualMap(options = {}) {
90
+ let rootDir = process.cwd(), outDir = resolve(rootDir, "out"), activeEnv = options.environment ?? (process.env.PRISM_CONTENT_ENV === "dev" ? "dev" : "prod"), isDev = !1;
91
+ return {
92
+ name: "@powerformer/prism-client/visual-map",
93
+ hooks: {
94
+ "astro:config:setup": ({ command, config, addMiddleware }) => {
95
+ command === "preview" || command === "sync" || (isDev = command === "dev", rootDir = fileURLToPath(config.root), outDir = fileURLToPath(config.outDir), activeEnv = options.environment ?? (process.env.PRISM_CONTENT_ENV === "dev" || process.env.PRISM_CONTENT_ENV === "prod" ? process.env.PRISM_CONTENT_ENV : isDev ? "dev" : "prod"), enableAutomaticReadTracing(), isDev || (process.env.PRISM_VISUAL_TRACE_DIR = join(rootDir, ".prism", "trace")), addMiddleware({
96
+ entrypoint: "@powerformer/prism-client/visual-middleware",
97
+ order: "pre"
98
+ }));
99
+ },
100
+ "astro:server:setup": ({ server }) => {
101
+ server.middlewares.use((req, res, next) => {
102
+ let url = new URL(req.url ?? "/", "http://127.0.0.1");
103
+ if (url.pathname === "/prism-visual.json") {
104
+ let overrides = readOverridesFile(resolve(rootDir, options.overridesFile ?? "prism.visual.json")), pageReads = new Map(getLivePageReads()), seeded = options.devResourcesProvider?.() ?? [], { publicConfig } = buildVisualConfigFromTraces({
105
+ pageReads,
106
+ environment: activeEnv,
107
+ buildRef: resolveBuildRef(rootDir),
108
+ overrides
109
+ });
110
+ for (let item of seeded)
111
+ publicConfig.resources[item.resourceId] || (publicConfig.resources[item.resourceId] = {
112
+ ...item.module ? { module: item.module } : {},
113
+ publicationId: item.publicationId,
114
+ versionId: item.versionId,
115
+ generation: item.generation
116
+ });
117
+ if (overrides.routes?.length) {
118
+ let modToId = /* @__PURE__ */ new Map();
119
+ for (let [rid, meta] of Object.entries(publicConfig.resources))
120
+ meta.module && modToId.set(meta.module, rid);
121
+ for (let declared of overrides.routes) {
122
+ if (publicConfig.routes.some((r) => r.pattern === declared.pattern)) continue;
123
+ let rid = declared.resourceId ?? (declared.module ? modToId.get(declared.module) : void 0), bindings = declared.bindings?.length ? declared.bindings : rid ? [{
124
+ resourceId: rid,
125
+ ...declared.module ? { module: declared.module } : {},
126
+ ...declared.selector ? { selector: declared.selector } : {}
127
+ }] : [];
128
+ bindings.length && publicConfig.routes.push({
129
+ pattern: declared.pattern,
130
+ bindings,
131
+ ...declared.overrides?.length ? { overrides: declared.overrides } : {},
132
+ ...declared.listPolicies && Object.keys(declared.listPolicies).length ? { listPolicies: declared.listPolicies } : {}
133
+ });
134
+ }
135
+ }
136
+ res.statusCode = 200, res.setHeader("Content-Type", "application/json; charset=utf-8"), res.setHeader("Cache-Control", "no-store"), res.setHeader("X-Robots-Tag", "noindex, nofollow"), res.end(JSON.stringify(publicConfig, null, 2));
137
+ return;
138
+ }
139
+ if (url.pathname === "/__prism-dev/slice" && options.devSliceResolver) {
140
+ try {
141
+ let data = options.devSliceResolver({
142
+ resourceId: url.searchParams.get("resourceId") ?? "",
143
+ module: url.searchParams.get("module") ?? void 0,
144
+ collection: url.searchParams.get("collection") ?? void 0,
145
+ keyField: url.searchParams.get("keyField") ?? void 0,
146
+ keyValue: url.searchParams.get("keyValue") ?? void 0
147
+ });
148
+ res.statusCode = data ? 200 : 404, res.setHeader("Content-Type", "application/json; charset=utf-8"), res.setHeader("Cache-Control", "no-store"), res.end(JSON.stringify(data ?? { error: "Slice not found" }));
149
+ } catch (error) {
150
+ res.statusCode = 500, res.setHeader("Content-Type", "application/json; charset=utf-8"), res.end(JSON.stringify({ error: error instanceof Error ? error.message : "Slice resolution failed" }));
151
+ }
152
+ return;
153
+ }
154
+ next();
155
+ });
156
+ },
157
+ "astro:build:done": ({ logger }) => {
158
+ if (isDev) return;
159
+ let verifyEnabled = process.env.PRISM_VISUAL_VERIFY === "1" && !!(process.env.PRISM_VERSION_OVERRIDE || process.env.PRISM_VERSION), publicKeyPem = options.encryptPublicKeyPem ?? process.env.PRISM_VISUAL_PUBLIC_KEY_PEM, result = finalizeVisualArtifacts({
160
+ rootDir,
161
+ outDir,
162
+ environment: activeEnv,
163
+ overridesFile: options.overridesFile ?? "prism.visual.json",
164
+ encryptPublicKeyPem: publicKeyPem,
165
+ encryptKeyId: options.encryptKeyId ?? process.env.PRISM_VISUAL_KEY_ID ?? "prism-visual-v1",
166
+ verify: verifyEnabled
167
+ });
168
+ if (logger.info(`Wrote ${result.visualMapPath} and ${result.publicConfigPath} (${result.publicConfig.routes.length} routes).`), result.verifyReport && (logger.info(`Visual XPath verification: ${result.verifyReport.passed}/${result.verifyReport.total} passed.`), !result.verifyReport.ok)) {
169
+ let summary = result.verifyReport.items.filter((item) => item.status !== "passed").map((item) => ` - [${item.status}] ${item.pagePath} ${item.xpath}: ${item.detail}`).join(`
170
+ `);
171
+ throw new Error(`Prism visual XPath verification failed (${result.verifyReport.failed}/${result.verifyReport.total}):
172
+ ${summary}`);
173
+ }
174
+ }
175
+ }
176
+ };
177
+ }
79
178
  export {
80
- prismContent
179
+ prismContent,
180
+ prismVisualMap
81
181
  };
@@ -1,4 +1,11 @@
1
- import type { DevServerHandle, DevServerOptions, PrismOptions, ResourceOptions, ResourceQuery } from './types.js';
1
+ import type { DevServerHandle, DevServerOptions, PrismOptions, PrismReadObserver, ResourceOptions, ResourceQuery } from './types.js';
2
+ /** Register a zero-overhead read observer (used by Node build-time visual-map tracing). */
3
+ export declare function registerReadObserver(observer: PrismReadObserver): () => void;
4
+ /** Parse PRISM_VERSION_OVERRIDE (`uuid=ver,uuid2=ver2` or JSON map) and PRISM_VERSION. */
5
+ export declare function resolveEnvVersionOverrides(environment: 'dev' | 'prod'): {
6
+ byResource: ReadonlyMap<string, string>;
7
+ fallbackVersion?: string;
8
+ };
2
9
  export declare class Prism {
3
10
  private readonly locale?;
4
11
  constructor(options: PrismOptions);
@@ -16,7 +16,7 @@ import {
16
16
  resourceVersionLocalePath,
17
17
  resourceVersionMainPath,
18
18
  resourceVersionManifestPath
19
- } from "../chunk-GGTUOAAF.js";
19
+ } from "../chunk-3B2PZHLA.js";
20
20
 
21
21
  // app/sdk/contract.ts
22
22
  var parseResourceMain2 = parseResourceMain, parseResourceManifest2 = parseResourceManifest, parseResourceManifestV22 = parseResourceManifestV2, resourceMainPath2 = resourceMainPath, resourceEnvironmentManifestPath2 = resourceEnvironmentManifestPath, parseResourceMainV22 = parseResourceMainV2, parseResourceManifestV32 = parseResourceManifestV3, resourcePublicMainPath2 = resourcePublicMainPath, resourcePublicManifestPath2 = resourcePublicManifestPath, resourcePublicContentPath2 = resourcePublicContentPath, resourceDeliveryOrigin2 = resourceDeliveryOrigin, parseResourceManifestV42 = parseResourceManifestV4, parseDeliveryManifest2 = parseDeliveryManifest, resourceVersionMainPath2 = resourceVersionMainPath, resourceVersionManifestPath2 = resourceVersionManifestPath, resourceVersionLocalePath2 = resourceVersionLocalePath, resourcePublicLocalePath2 = resourcePublicLocalePath;
@@ -1,5 +1,5 @@
1
- export { Prism } from './client.js';
1
+ export { Prism, registerReadObserver, resolveEnvVersionOverrides } from './client.js';
2
2
  export { PrismError } from './errors.js';
3
3
  export type { PrismErrorCode } from './errors.js';
4
- export type { PrismOptions, Environment, Visibility, ResourceOptions, ResourceQuery, PublicationMeta, ResourceResult, ResourceBundleResult, DevServerOptions, DevServerHandle, DevUpdate, } from './types.js';
4
+ export type { PrismOptions, Environment, Visibility, ResourceOptions, ResourceQuery, PublicationMeta, ResourceResult, ResourceBundleResult, DevServerOptions, DevServerHandle, DevUpdate, PrismReadEvent, PrismReadObserver, VisualExpectation, } from './types.js';
5
5
  export type { ScopeRole, ResourceMembership } from '../contracts/access.js';
package/dist/sdk/index.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import {
2
2
  Prism,
3
- PrismError
4
- } from "../chunk-TG3NAWSK.js";
5
- import "../chunk-GGTUOAAF.js";
3
+ PrismError,
4
+ registerReadObserver,
5
+ resolveEnvVersionOverrides
6
+ } from "../chunk-MYDJI2NW.js";
7
+ import "../chunk-3B2PZHLA.js";
6
8
  export {
7
9
  Prism,
8
- PrismError
10
+ PrismError,
11
+ registerReadObserver,
12
+ resolveEnvVersionOverrides
9
13
  };
@@ -2,9 +2,9 @@ import {
2
2
  getRuntime,
3
3
  releaseRuntime,
4
4
  runtimeSeeds
5
- } from "../chunk-VQYM3WCM.js";
6
- import "../chunk-TG3NAWSK.js";
7
- import "../chunk-GGTUOAAF.js";
5
+ } from "../chunk-2G5GDKYE.js";
6
+ import "../chunk-MYDJI2NW.js";
7
+ import "../chunk-3B2PZHLA.js";
8
8
  export {
9
9
  getRuntime,
10
10
  releaseRuntime,
@@ -1,3 +1,5 @@
1
+ import type { VisualExpectation } from '../contracts/types.js';
2
+ export type { VisualExpectation } from '../contracts/types.js';
1
3
  export type Environment = 'dev' | 'prod';
2
4
  export type Visibility = 'public' | 'internal';
3
5
  export interface PrismOptions {
@@ -25,7 +27,15 @@ export interface PublicationMeta {
25
27
  version: string | null;
26
28
  schemaId: string;
27
29
  schemaVersion: number;
30
+ visualExpectations?: VisualExpectation[];
28
31
  }
32
+ export interface PrismReadEvent {
33
+ resourceId: string;
34
+ locale: string;
35
+ all: boolean;
36
+ meta: PublicationMeta;
37
+ }
38
+ export type PrismReadObserver = (event: PrismReadEvent) => void;
29
39
  export interface ResourceResult<T = unknown> {
30
40
  data: T;
31
41
  meta: PublicationMeta & {
@@ -0,0 +1,173 @@
1
+ import type { JsonValue, VisualExpectation } from '../contracts/types.js';
2
+ export interface PrismReadSelector {
3
+ collection: string;
4
+ keyField: string;
5
+ keyValue: string;
6
+ }
7
+ export interface PrismReadTraceRecord {
8
+ module?: string;
9
+ resourceId: string;
10
+ locale: string;
11
+ publicationId: string;
12
+ versionId: string;
13
+ generation: number;
14
+ pageId?: string;
15
+ /** Optional canonical page path owned by this item; filters out site-wide manifest/sitemap preloads during another page's render. */
16
+ canonicalPath?: string;
17
+ selector?: PrismReadSelector;
18
+ visualExpectations?: VisualExpectation[];
19
+ }
20
+ export interface VisualOverrideRule {
21
+ scope?: string;
22
+ match: string;
23
+ pointer: string;
24
+ localeScope?: 'current-locale' | 'all-locales' | 'default-locale';
25
+ control?: string;
26
+ label?: string;
27
+ }
28
+ export interface VisualRouteBinding {
29
+ resourceId: string;
30
+ module?: string;
31
+ selector?: {
32
+ collection: string;
33
+ keyField: string;
34
+ keyValue?: string;
35
+ fromParam?: string;
36
+ };
37
+ }
38
+ export interface VisualListPolicy {
39
+ allowReorder?: boolean;
40
+ allowAdd?: boolean;
41
+ allowRemove?: boolean;
42
+ }
43
+ export interface VisualRouteConfig {
44
+ pattern: string;
45
+ bindings: VisualRouteBinding[];
46
+ overrides?: VisualOverrideRule[];
47
+ listPolicies?: Record<string, VisualListPolicy>;
48
+ }
49
+ export interface VisualResourceSummary {
50
+ module?: string;
51
+ publicationId: string;
52
+ versionId: string;
53
+ generation: number;
54
+ visualExpectations?: VisualExpectation[];
55
+ }
56
+ export interface VisualPublicConfig {
57
+ schemaVersion: 1;
58
+ environment: 'dev' | 'prod';
59
+ buildRef: string | null;
60
+ locales: string[];
61
+ ignoreSelectors: string[];
62
+ resources: Record<string, Omit<VisualResourceSummary, 'visualExpectations'>>;
63
+ routes: VisualRouteConfig[];
64
+ }
65
+ export interface VisualOverridesFile {
66
+ schemaVersion?: 1;
67
+ locales?: string[];
68
+ ignoreSelectors?: string[];
69
+ routes?: Array<{
70
+ pattern: string;
71
+ module?: string;
72
+ resourceId?: string;
73
+ selector?: VisualRouteBinding['selector'];
74
+ bindings?: VisualRouteBinding[];
75
+ overrides?: VisualOverrideRule[];
76
+ listPolicies?: Record<string, VisualListPolicy>;
77
+ }>;
78
+ modules?: Record<string, {
79
+ routes?: string[];
80
+ overrides?: VisualOverrideRule[];
81
+ }>;
82
+ }
83
+ export interface VisualEnvelope {
84
+ v: 1;
85
+ alg: 'RSA-OAEP-256+A256GCM';
86
+ kid: string;
87
+ ek: string;
88
+ iv: string;
89
+ ct: string;
90
+ }
91
+ interface TraceStore {
92
+ pathname: string;
93
+ reads: Map<string, PrismReadTraceRecord>;
94
+ }
95
+ export declare function enableAutomaticReadTracing(): void;
96
+ export declare function runWithPageTrace<T>(pathname: string, fn: () => Promise<T> | T): Promise<T>;
97
+ export declare function currentPageTrace(): TraceStore | undefined;
98
+ export declare function recordPrismRead(record: PrismReadTraceRecord): void;
99
+ export declare function recordLivePageReads(pathname: string, reads: PrismReadTraceRecord[]): void;
100
+ export declare function getLivePageReads(): Map<string, PrismReadTraceRecord[]>;
101
+ export declare function appendWorkerTrace(traceDir: string, pathname: string, reads: PrismReadTraceRecord[]): void;
102
+ export declare function normalizePathname(pathname: string): string;
103
+ export declare function stripLocalePrefix(pathname: string, locales: readonly string[]): {
104
+ locale: string;
105
+ canonicalPath: string;
106
+ };
107
+ export declare function resolveBuildRef(rootDir: string): string | null;
108
+ export declare function isVisualEnvelope(value: unknown): value is VisualEnvelope;
109
+ export declare function encryptVisualEnvelope(payload: VisualPublicConfig, publicKeyPem: string, kid?: string): VisualEnvelope;
110
+ export declare function decryptVisualEnvelope(envelope: VisualEnvelope, privateKeyPem: string): VisualPublicConfig;
111
+ export declare function readOverridesFile(filePath: string | undefined): VisualOverridesFile;
112
+ /** Compact per-page reads across locales and collection detail routes into compact route patterns. */
113
+ export declare function buildVisualConfigFromTraces(input: {
114
+ pageReads: Map<string, PrismReadTraceRecord[]>;
115
+ environment: 'dev' | 'prod';
116
+ buildRef: string | null;
117
+ overrides?: VisualOverridesFile;
118
+ }): {
119
+ publicConfig: VisualPublicConfig;
120
+ expectations: Array<{
121
+ resourceId: string;
122
+ versionId: string;
123
+ expectations: VisualExpectation[];
124
+ }>;
125
+ };
126
+ /** Evaluate semantic relative/absolute XPath against MiniNode HTML5 tree. */
127
+ export declare function evaluateHtmlXPath(html: string, xpath: string): Array<{
128
+ text: string;
129
+ attr?: string;
130
+ }>;
131
+ export interface VisualVerifyItemResult {
132
+ resourceId: string;
133
+ versionId: string;
134
+ pagePath: string;
135
+ xpath: string;
136
+ pointer: string;
137
+ locale: string;
138
+ status: 'passed' | 'xpath_not_found' | 'value_mismatch' | 'page_not_found';
139
+ expected: JsonValue;
140
+ actual: string | null;
141
+ detail: string;
142
+ }
143
+ export interface VisualVerifyReport {
144
+ ok: boolean;
145
+ checkedAt: string;
146
+ total: number;
147
+ passed: number;
148
+ failed: number;
149
+ items: VisualVerifyItemResult[];
150
+ }
151
+ export declare function verifyVisualExpectations(input: {
152
+ outDir: string;
153
+ bundles: Array<{
154
+ resourceId: string;
155
+ versionId: string;
156
+ expectations: VisualExpectation[];
157
+ }>;
158
+ }): VisualVerifyReport;
159
+ export declare function finalizeVisualArtifacts(options: {
160
+ rootDir: string;
161
+ outDir: string;
162
+ environment: 'dev' | 'prod';
163
+ overridesFile?: string;
164
+ encryptPublicKeyPem?: string;
165
+ encryptKeyId?: string;
166
+ verify?: boolean;
167
+ }): {
168
+ visualMapPath: string;
169
+ publicConfigPath: string;
170
+ publicConfig: VisualPublicConfig;
171
+ verifyReport?: VisualVerifyReport;
172
+ };
173
+ export {};
@@ -0,0 +1,42 @@
1
+ import {
2
+ appendWorkerTrace,
3
+ buildVisualConfigFromTraces,
4
+ currentPageTrace,
5
+ decryptVisualEnvelope,
6
+ enableAutomaticReadTracing,
7
+ encryptVisualEnvelope,
8
+ evaluateHtmlXPath,
9
+ finalizeVisualArtifacts,
10
+ getLivePageReads,
11
+ isVisualEnvelope,
12
+ normalizePathname,
13
+ readOverridesFile,
14
+ recordLivePageReads,
15
+ recordPrismRead,
16
+ resolveBuildRef,
17
+ runWithPageTrace,
18
+ stripLocalePrefix,
19
+ verifyVisualExpectations
20
+ } from "../chunk-NSC3MYAU.js";
21
+ import "../chunk-MYDJI2NW.js";
22
+ import "../chunk-3B2PZHLA.js";
23
+ export {
24
+ appendWorkerTrace,
25
+ buildVisualConfigFromTraces,
26
+ currentPageTrace,
27
+ decryptVisualEnvelope,
28
+ enableAutomaticReadTracing,
29
+ encryptVisualEnvelope,
30
+ evaluateHtmlXPath,
31
+ finalizeVisualArtifacts,
32
+ getLivePageReads,
33
+ isVisualEnvelope,
34
+ normalizePathname,
35
+ readOverridesFile,
36
+ recordLivePageReads,
37
+ recordPrismRead,
38
+ resolveBuildRef,
39
+ runWithPageTrace,
40
+ stripLocalePrefix,
41
+ verifyVisualExpectations
42
+ };
@@ -0,0 +1,3 @@
1
+ export declare function onRequest(context: {
2
+ url: URL;
3
+ }, next: () => Promise<Response>): Promise<Response>;
@@ -0,0 +1,22 @@
1
+ import {
2
+ appendWorkerTrace,
3
+ currentPageTrace,
4
+ enableAutomaticReadTracing,
5
+ recordLivePageReads,
6
+ runWithPageTrace
7
+ } from "../chunk-NSC3MYAU.js";
8
+ import "../chunk-MYDJI2NW.js";
9
+ import "../chunk-3B2PZHLA.js";
10
+
11
+ // app/sdk/visual-middleware.ts
12
+ async function onRequest(context, next) {
13
+ enableAutomaticReadTracing();
14
+ let traceDir = process.env.PRISM_VISUAL_TRACE_DIR, capturedReads = [], response = await runWithPageTrace(context.url.pathname, async () => {
15
+ let res = await next(), store = currentPageTrace();
16
+ return store && store.reads.size > 0 && (capturedReads = [...store.reads.values()]), res;
17
+ }), contentType = response.headers.get("content-type") ?? "";
18
+ return capturedReads.length > 0 && (contentType.includes("text/html") || !contentType) && (recordLivePageReads(context.url.pathname, capturedReads), traceDir && appendWorkerTrace(traceDir, context.url.pathname, capturedReads)), response;
19
+ }
20
+ export {
21
+ onRequest
22
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerformer/prism-client",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Read published Prism multilingual content with shared caching and Astro development updates.",
6
6
  "license": "UNLICENSED",
@@ -18,6 +18,14 @@
18
18
  "types": "./dist/sdk/astro.d.ts",
19
19
  "import": "./dist/sdk/astro.js"
20
20
  },
21
+ "./visual-map": {
22
+ "types": "./dist/sdk/visual-map.d.ts",
23
+ "import": "./dist/sdk/visual-map.js"
24
+ },
25
+ "./visual-middleware": {
26
+ "types": "./dist/sdk/visual-middleware.d.ts",
27
+ "import": "./dist/sdk/visual-middleware.js"
28
+ },
21
29
  "./runtime": {
22
30
  "types": "./dist/sdk/runtime.d.ts",
23
31
  "import": "./dist/sdk/runtime.js"