@action-state-group/capsule-viewer 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +201 -0
  2. package/LICENSE-BSD-3-Clause +28 -0
  3. package/README.md +94 -1
  4. package/dist/alias-interpreters.d.ts +18 -0
  5. package/dist/alias-interpreters.js +50 -0
  6. package/dist/alias-interpreters.js.map +1 -0
  7. package/dist/browser.d.ts +7 -0
  8. package/dist/browser.js +25 -0
  9. package/dist/browser.js.map +1 -0
  10. package/dist/builtin-manifests.d.ts +51 -0
  11. package/dist/builtin-manifests.js +196 -0
  12. package/dist/builtin-manifests.js.map +1 -0
  13. package/dist/compliance-presentation.d.ts +51 -0
  14. package/dist/compliance-presentation.js +140 -0
  15. package/dist/compliance-presentation.js.map +1 -0
  16. package/dist/compliance-styles.d.ts +1 -0
  17. package/dist/compliance-styles.js +104 -0
  18. package/dist/compliance-styles.js.map +1 -0
  19. package/dist/compliance-view.d.ts +46 -0
  20. package/dist/compliance-view.js +828 -0
  21. package/dist/compliance-view.js.map +1 -0
  22. package/dist/compliance.d.ts +121 -0
  23. package/dist/compliance.js +412 -0
  24. package/dist/compliance.js.map +1 -0
  25. package/dist/composed-styles.d.ts +12 -0
  26. package/dist/composed-styles.js +20 -0
  27. package/dist/composed-styles.js.map +1 -0
  28. package/dist/composed-view.d.ts +24 -0
  29. package/dist/composed-view.js +186 -0
  30. package/dist/composed-view.js.map +1 -0
  31. package/dist/contract-report-wording.d.ts +195 -0
  32. package/dist/contract-report-wording.js +1141 -0
  33. package/dist/contract-report-wording.js.map +1 -0
  34. package/dist/contract-report.d.ts +92 -0
  35. package/dist/contract-report.js +63 -0
  36. package/dist/contract-report.js.map +1 -0
  37. package/dist/emitter-shell.html +310 -0
  38. package/dist/emitter.d.ts +105 -0
  39. package/dist/emitter.js +329 -0
  40. package/dist/emitter.js.map +1 -0
  41. package/dist/evidence-graph-view.d.ts +149 -0
  42. package/dist/evidence-graph-view.js +2718 -0
  43. package/dist/evidence-graph-view.js.map +1 -0
  44. package/dist/evidence-graph.iife.js +18159 -0
  45. package/dist/frame-tokens.generated.d.ts +3 -0
  46. package/dist/frame-tokens.generated.js +5 -0
  47. package/dist/frame-tokens.generated.js.map +1 -0
  48. package/dist/index.d.ts +5 -0
  49. package/dist/index.js +12 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/outcome-report-presentation.d.ts +48 -0
  52. package/dist/outcome-report-presentation.js +90 -0
  53. package/dist/outcome-report-presentation.js.map +1 -0
  54. package/dist/outcome-report-styles.d.ts +1 -0
  55. package/dist/outcome-report-styles.js +228 -0
  56. package/dist/outcome-report-styles.js.map +1 -0
  57. package/dist/outcome-report-view.d.ts +78 -0
  58. package/dist/outcome-report-view.js +1488 -0
  59. package/dist/outcome-report-view.js.map +1 -0
  60. package/dist/presentation-builder.d.ts +296 -0
  61. package/dist/presentation-builder.js +646 -0
  62. package/dist/presentation-builder.js.map +1 -0
  63. package/dist/presentation-fragment.d.ts +129 -0
  64. package/dist/presentation-fragment.js +213 -0
  65. package/dist/presentation-fragment.js.map +1 -0
  66. package/dist/presentation-mount.d.ts +26 -0
  67. package/dist/presentation-mount.js +45 -0
  68. package/dist/presentation-mount.js.map +1 -0
  69. package/dist/presentation-registry.d.ts +277 -0
  70. package/dist/presentation-registry.js +416 -0
  71. package/dist/presentation-registry.js.map +1 -0
  72. package/dist/record-content.d.ts +68 -0
  73. package/dist/record-content.js +153 -0
  74. package/dist/record-content.js.map +1 -0
  75. package/dist/record-dating.d.ts +10 -0
  76. package/dist/record-dating.js +76 -0
  77. package/dist/record-dating.js.map +1 -0
  78. package/dist/report-front-styles.d.ts +9 -0
  79. package/dist/report-front-styles.js +55 -0
  80. package/dist/report-front-styles.js.map +1 -0
  81. package/dist/report-front.d.ts +78 -0
  82. package/dist/report-front.js +274 -0
  83. package/dist/report-front.js.map +1 -0
  84. package/dist/report-levels.d.ts +206 -0
  85. package/dist/report-levels.js +739 -0
  86. package/dist/report-levels.js.map +1 -0
  87. package/dist/report-provenance.d.ts +111 -0
  88. package/dist/report-provenance.js +535 -0
  89. package/dist/report-provenance.js.map +1 -0
  90. package/dist/viewer-build.d.ts +37 -0
  91. package/dist/viewer-build.js +29 -0
  92. package/dist/viewer-build.js.map +1 -0
  93. package/dist/wording/contract-report-eu-ai-act.en.json +295 -0
  94. package/dist/wording/contract-report-outcomes.en.json +394 -0
  95. package/package.json +48 -4
@@ -0,0 +1,646 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ import { buildVerifiedBundleContext, classifyCountersignatures, declaredProducerKeys, isVerifiedBundleContext, verificationBanner, } from "@action-state-group/agent-action-capsule";
3
+ import { DEFAULT_EVIDENCE_GRAPH_BOOTSTRAP, emitEmbeddedHtml, emitEvidenceGraphHtml, emitStaticEvidenceGraphHtml, escapeJsonForHtmlScript, } from "./emitter.js";
4
+ import { checkWordingPackInput, DEFAULT_PACKS, wordingProblems, WordingPackError, } from "./contract-report-wording.js";
5
+ import { CONTRACT_REPORT_MANIFEST, contractReportGroupingOf, createPresentationRegistry, renderEvidenceGraph, } from "./evidence-graph-view.js";
6
+ import { jcs, sha256Hex } from "@action-state-group/agent-action-capsule";
7
+ import { BUILTIN_MANIFEST_RESULT_COMPLIANCE, BUILTIN_MANIFEST_RESULT_OUTCOME_REPORT, } from "./builtin-manifests.js";
8
+ import { bundleVerified, manifestProblems, PresentationAmbiguityError, presentationRefusalReason, PresentationRegistry, REFERENCE_PRESENTATION_RUNTIME, } from "./presentation-registry.js";
9
+ import { decodePresentationFragment, encodePresentationFragment, FRAGMENT_TOKEN_DEFAULT_BUDGET, FragmentTooLargeError, PRESENTATION_DEPTHS, PRESENTATION_FRAGMENT_VERSION, scopeDisclosures, } from "./presentation-fragment.js";
10
+ import { mountPresentation } from "./presentation-mount.js";
11
+ import { fillForNoScript } from "./report-levels.js";
12
+ /**
13
+ * One builder, four packagings (spec/presentation-builder-v0.md):
14
+ * `buildPresentation(context, {presentation, audience, format})` scopes the
15
+ * bundle for the audience, resolves the one module the registry selects,
16
+ * and packages the same scoped bundle and settings as
17
+ *
18
+ * - `html`: one self-contained offline file with its per-page CSP;
19
+ * - `fragment`: a permalink token for the URL fragment, which a browser
20
+ * never sends; the offline file is rebuilt from it byte for byte by
21
+ * {@link offlineHtmlFromFragment};
22
+ * - `embedded`: a mount function for a host element;
23
+ * - `static`: the page rendered at build time into HTML that runs no
24
+ * script at all, and says it is not self-verifying.
25
+ *
26
+ * A packaging can be unavailable for a bundle (a fragment over the link
27
+ * budget, for one); {@link availablePackagings} reports which, and why,
28
+ * without packaging anything. For one (bundle, audience) every SUPPORTED
29
+ * packaging shows the same module, the same verified content and the same
30
+ * verification state (contract I4).
31
+ */
32
+ export class PresentationBuildError extends Error {
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "PresentationBuildError";
36
+ }
37
+ }
38
+ export const PACKAGING_TARGETS = Object.freeze([
39
+ "html",
40
+ "fragment",
41
+ "embedded",
42
+ "static",
43
+ ]);
44
+ /**
45
+ * A direct build of a packaging that is unavailable. (A fragment over the
46
+ * budget keeps throwing {@link FragmentTooLargeError}, as it always has.)
47
+ */
48
+ export class PackagingUnavailableError extends PresentationBuildError {
49
+ reason;
50
+ constructor(reason) {
51
+ super(reason.message);
52
+ this.name = "PackagingUnavailableError";
53
+ this.reason = reason;
54
+ }
55
+ }
56
+ /**
57
+ * What the static page says, word for word. It runs no code, so it shows
58
+ * the verification result the builder computed and cannot re-verify.
59
+ */
60
+ export const STATIC_NOT_SELF_VERIFYING = "Not self-verifying; verify the bundle separately.";
61
+ /**
62
+ * The default size budget of a static page, in UTF-8 bytes (16 MiB). A
63
+ * static page carries every toggle's body, built at build time, so its size
64
+ * grows with the report; a page over the budget is refused
65
+ * (`static-too-large`), never written with bodies left out. A caller may
66
+ * lower or raise it (`maxStaticBytes`).
67
+ */
68
+ export const STATIC_PAGE_DEFAULT_BUDGET = 16 * 1024 * 1024;
69
+ /** The static page's second statement, before the build-time result. */
70
+ export const STATIC_BUILD_TIME_STATEMENT = "This page runs no code. It shows the verification result computed when it was built and cannot re-verify anything in your browser.";
71
+ /**
72
+ * A module's manifest pins other stylesheets than the module carries
73
+ * (contract section 5.1). No page is written; the error names both lists.
74
+ */
75
+ export class PresentationStylePinsError extends PresentationBuildError {
76
+ module;
77
+ /** The manifest's `executable.style_sha256`, as given (absent: empty). */
78
+ manifestStyleSha256;
79
+ /** The module's `styleSha256`, as given (absent: empty). */
80
+ moduleStyleSha256;
81
+ constructor(module, manifestStyleSha256, moduleStyleSha256) {
82
+ super(`module manifest ${module} style_sha256 [${manifestStyleSha256.join(", ")}] does not equal the module's style pins [${moduleStyleSha256.join(", ")}] as a set; no page is written`);
83
+ this.name = "PresentationStylePinsError";
84
+ this.module = module;
85
+ this.manifestStyleSha256 = Object.freeze([...manifestStyleSha256]);
86
+ this.moduleStyleSha256 = Object.freeze([...moduleStyleSha256]);
87
+ }
88
+ }
89
+ // Contract section 5.1: the stylesheets a module inserts are the ones its
90
+ // manifest pins, compared as sets (order and repetition decide nothing).
91
+ function checkStylePins(script) {
92
+ const manifest = script.manifest;
93
+ if (manifest === undefined)
94
+ return;
95
+ const declared = manifest.executable?.style_sha256 ?? [];
96
+ const carried = script.styleSha256 ?? [];
97
+ const a = new Set(declared);
98
+ const b = new Set(carried);
99
+ if (a.size !== b.size || [...a].some((pin) => !b.has(pin)))
100
+ throw new PresentationStylePinsError(manifest.id, declared, carried);
101
+ }
102
+ // What the emitter is given for each module: its code and pins, script and
103
+ // stylesheets alike. The manifest stays with the builder.
104
+ function emitterModules(modules) {
105
+ return modules.map((m) => ({
106
+ code: m.code,
107
+ sha256: m.sha256,
108
+ ...(m.styleSha256 === undefined ? {} : { styleSha256: m.styleSha256 }),
109
+ }));
110
+ }
111
+ /**
112
+ * The builder was asked to put into a page a module the page's runtime
113
+ * would refuse (contract section 3.2). No page is written; the error names
114
+ * both sides: the module (id, `presentation_api`, `runtime_min`) and the
115
+ * runtime's declaration.
116
+ */
117
+ export class PresentationModuleRefusedError extends PresentationBuildError {
118
+ module;
119
+ reason;
120
+ runtime;
121
+ constructor(module, reason, runtime) {
122
+ const apis = runtime.presentationApis.length === 0
123
+ ? "no presentation API"
124
+ : runtime.presentationApis.join(", ");
125
+ super(`presentation module ${module.id} (presentation_api ${module.presentation_api}, runtime_min ${module.runtime_min}) would be refused by the page's runtime (implements ${apis}; runtime version ${runtime.runtimeVersion}): ${reason}; no page is written`);
126
+ this.name = "PresentationModuleRefusedError";
127
+ this.module = Object.freeze({
128
+ id: module.id,
129
+ presentation_api: module.presentation_api,
130
+ runtime_min: module.runtime_min,
131
+ });
132
+ this.reason = reason;
133
+ this.runtime = runtime;
134
+ }
135
+ }
136
+ // The static notice's words for each state.
137
+ const STATIC_VERIFICATION_WORDS = {
138
+ verified: "verified",
139
+ incomplete: "incomplete (none of the bundle's checks failed, but some were not run)",
140
+ failed: "did not verify",
141
+ };
142
+ /** The wording key the builder reads for the page title. */
143
+ export const WORDING_TITLE_KEY = "page.title";
144
+ /**
145
+ * Check a wording pack against its digest and its shape (contract 7.4) and
146
+ * return its entries. The bytes are hashed exactly as given, before they are
147
+ * parsed. One check for every path: contract-report-wording.ts holds it.
148
+ */
149
+ export async function checkWordingPack(wording) {
150
+ try {
151
+ return (await checkWordingPackInput(wording)).entries;
152
+ }
153
+ catch (e) {
154
+ if (e instanceof WordingPackError)
155
+ throw new PresentationBuildError(e.message);
156
+ throw e;
157
+ }
158
+ }
159
+ /**
160
+ * The contract-report grouping each earlier display card draws, by module
161
+ * id. The contract-report module (CONTRACT_REPORT_MANIFEST) draws the
162
+ * grouping its bundle's data supports (`contractReportGroupingOf`).
163
+ */
164
+ const CONTRACT_REPORT_GROUPINGS = {
165
+ [BUILTIN_MANIFEST_RESULT_OUTCOME_REPORT.id]: "lines",
166
+ [BUILTIN_MANIFEST_RESULT_COMPLIANCE.id]: "groups",
167
+ };
168
+ /**
169
+ * Refuse a wording pack that does not fit the report the registry selected,
170
+ * naming every problem: the check `render-report.mjs` runs, and the one the
171
+ * page would otherwise fail on with no reason ("presentation-failed"). A
172
+ * module that is not a contract report takes no such check.
173
+ */
174
+ async function checkWordingFits(wording, module, bundle) {
175
+ const grouping = module === CONTRACT_REPORT_MANIFEST.id
176
+ ? contractReportGroupingOf(bundle)
177
+ : module === null || !Object.hasOwn(CONTRACT_REPORT_GROUPINGS, module)
178
+ ? undefined
179
+ : CONTRACT_REPORT_GROUPINGS[module];
180
+ if (grouping === undefined)
181
+ return;
182
+ let pack;
183
+ try {
184
+ pack = await checkWordingPackInput(wording);
185
+ }
186
+ catch (e) {
187
+ if (e instanceof WordingPackError)
188
+ throw new PresentationBuildError(e.message);
189
+ throw e;
190
+ }
191
+ const problems = wordingProblems(pack, DEFAULT_PACKS[grouping]);
192
+ if (problems.length > 0)
193
+ throw new PresentationBuildError(`wording pack does not fit ${module}: ${problems.join("; ")}`);
194
+ }
195
+ // The options a page's bootstrap, an embedded snippet's bootstrap and
196
+ // mount pass to renderEvidenceGraph: the audience, the format, and the
197
+ // depth and wording pack when set. The host's registry is mount's own.
198
+ function renderOptions(settings, format) {
199
+ return {
200
+ audience: settings.audience,
201
+ format,
202
+ ...(settings.depth === undefined ? {} : { depth: settings.depth }),
203
+ ...(settings.wording === undefined
204
+ ? {}
205
+ : {
206
+ wording: {
207
+ pack: settings.wording.pack,
208
+ sha256: settings.wording.sha256,
209
+ },
210
+ }),
211
+ };
212
+ }
213
+ // The one offline packager: the direct path and the fragment hand-back both
214
+ // end here, so equal settings give equal bytes. The default settings
215
+ // (audience "*", nothing else) give exactly emitEvidenceGraphHtml's page.
216
+ async function packageOffline(settings, runtime, modules) {
217
+ const entries = settings.wording === undefined
218
+ ? undefined
219
+ : await checkWordingPack(settings.wording);
220
+ const title = settings.title !== undefined && settings.title !== ""
221
+ ? settings.title
222
+ : entries?.[WORDING_TITLE_KEY];
223
+ const isDefault = settings.audience === "*" &&
224
+ settings.depth === undefined &&
225
+ settings.wording === undefined;
226
+ const bootstrap = isDefault
227
+ ? DEFAULT_EVIDENCE_GRAPH_BOOTSTRAP
228
+ : `renderEvidenceGraph(window.__BUNDLE__, document.getElementById("app"), undefined, ${escapeJsonForHtmlScript(new TextDecoder().decode(jcs(renderOptions(settings, "html"))))});`;
229
+ return emitEvidenceGraphHtml(settings.bundle, runtime.code, {
230
+ ...(title === undefined ? {} : { title }),
231
+ ...(settings.themeCss === undefined ? {} : { themeCss: settings.themeCss }),
232
+ ...(runtime.sha256 === undefined
233
+ ? {}
234
+ : { coreRuntimeSha256: runtime.sha256 }),
235
+ modules,
236
+ bootstrap,
237
+ });
238
+ }
239
+ function requireRuntime(runtime, format) {
240
+ if (runtime === undefined)
241
+ throw new PackagingUnavailableError({
242
+ code: "runtime-missing",
243
+ message: `format ${format} needs the core runtime`,
244
+ });
245
+ return runtime;
246
+ }
247
+ // Check the settings, then scope and verify the scoped bundle: once for
248
+ // every packaging.
249
+ async function scopeAndVerify(input, options) {
250
+ const { audience } = options;
251
+ if (typeof audience !== "string" || audience === "")
252
+ throw new PresentationBuildError("audience is required");
253
+ if (options.depth !== undefined &&
254
+ !PRESENTATION_DEPTHS.includes(options.depth))
255
+ throw new PresentationBuildError("depth is not L0, L1 or L2");
256
+ if (options.wording !== undefined)
257
+ await checkWordingPack(options.wording);
258
+ const given = isVerifiedBundleContext(input)
259
+ ? input
260
+ : await buildVerifiedBundleContext(input);
261
+ if (options.disclose === undefined)
262
+ return given;
263
+ if (!bundleVerified(given.verification))
264
+ throw new PresentationBuildError("refusing to scope a bundle that did not verify: removing a disclosure could hide the failure");
265
+ return buildVerifiedBundleContext(scopeDisclosures(given.bundle, options.disclose), given.countersigners === undefined
266
+ ? {}
267
+ : { countersigners: given.countersigners });
268
+ }
269
+ /**
270
+ * The page's runtime declaration (contract section 3.2): the registry's,
271
+ * when the builder resolves with a PresentationRegistry (the default one is
272
+ * the reference runtime, which the core runtime script also is); otherwise
273
+ * the reference runtime's.
274
+ */
275
+ function pageRuntime(registry) {
276
+ return registry instanceof PresentationRegistry
277
+ ? registry.runtime
278
+ : REFERENCE_PRESENTATION_RUNTIME;
279
+ }
280
+ // Contract section 3.2: a builder asked to put into a page a module the
281
+ // page's runtime would refuse writes no page and names both sides. Two ways
282
+ // to ask: inline a module-slot script whose manifest the runtime refuses,
283
+ // or request by id a module the registry holds as refused (or that matched
284
+ // this resolution and was refused).
285
+ function refuseRefusedModules(options, registry, resolution) {
286
+ const runtime = pageRuntime(registry);
287
+ for (const script of options.modules ?? []) {
288
+ const manifest = script.manifest;
289
+ if (manifest === undefined)
290
+ continue;
291
+ const problems = manifestProblems(manifest);
292
+ if (problems.length > 0)
293
+ throw new PresentationBuildError(`module manifest ${JSON.stringify(manifest.id)} is malformed: ${problems.join("; ")}`);
294
+ if (manifest.executable?.carrier !== "module-slot" ||
295
+ manifest.executable.script_sha256 !== script.sha256)
296
+ throw new PresentationBuildError(`module manifest ${manifest.id} does not pin this module-slot script (sha256 ${script.sha256})`);
297
+ checkStylePins(script);
298
+ const reason = presentationRefusalReason(manifest, runtime);
299
+ if (reason !== undefined)
300
+ throw new PresentationModuleRefusedError(manifest, reason, runtime);
301
+ }
302
+ if (options.presentation === "auto")
303
+ return;
304
+ const refused = [
305
+ ...(resolution.kind === "refusal" ? [] : resolution.refused),
306
+ ...(registry instanceof PresentationRegistry ? registry.refused() : []),
307
+ ].find((refusal) => refusal.id === options.presentation);
308
+ if (refused !== undefined)
309
+ throw new PresentationModuleRefusedError(refused, refused.reason, runtime);
310
+ }
311
+ // Resolve for one contract format. The static page is the html page
312
+ // rendered at build time, so it is resolved, and rendered, as html.
313
+ async function resolveFor(context, options, format) {
314
+ const { audience } = options;
315
+ const registry = options.registry ?? createPresentationRegistry();
316
+ let resolution;
317
+ try {
318
+ resolution = await registry.resolve(context, audience, format);
319
+ }
320
+ catch (err) {
321
+ if (err instanceof PresentationAmbiguityError)
322
+ throw new PresentationBuildError(`presentation is ambiguous for this bundle: ${err.ids.join(", ")}`);
323
+ throw err;
324
+ }
325
+ refuseRefusedModules(options, registry, resolution);
326
+ const module = resolution.kind === "module" ? resolution.module.manifest.id : null;
327
+ if (options.presentation !== "auto" && options.presentation !== module)
328
+ throw new PresentationBuildError(`presentation ${options.presentation} was requested but the registry selected ${module ?? resolution.kind} for audience ${audience} and format ${format}`);
329
+ if (options.wording !== undefined)
330
+ await checkWordingFits(options.wording, module, context.bundle);
331
+ return {
332
+ common: {
333
+ audience,
334
+ module,
335
+ resolution: resolution.kind,
336
+ bundle: context.bundle,
337
+ },
338
+ context,
339
+ registry,
340
+ };
341
+ }
342
+ const contractFormat = (target) => target === "static" ? "html" : target;
343
+ /**
344
+ * Build one presentation of a bundle for one audience in one packaging.
345
+ * `input` is a verified context or a bundle (verified here).
346
+ *
347
+ * Steps, in order: scope the bundle for the audience (only when `disclose`
348
+ * is given, and never for a bundle that did not verify, since removing a
349
+ * disclosure could hide the failure); verify the scoped bundle; resolve the
350
+ * module through the registry (an ambiguity is an error; an explicit
351
+ * `presentation` that the registry does not select is an error, and so is
352
+ * a wording pack that does not fit the selected report, with every
353
+ * problem named); package.
354
+ *
355
+ * A packaging that is unavailable throws: {@link FragmentTooLargeError} for
356
+ * a fragment over its budget, {@link PackagingUnavailableError} otherwise.
357
+ * Ask {@link availablePackagings} first to learn which are available.
358
+ */
359
+ export async function buildPresentation(input, options) {
360
+ const { format } = options;
361
+ if (!PACKAGING_TARGETS.includes(format))
362
+ throw new PresentationBuildError(`format ${JSON.stringify(format)} is not html, fragment, embedded or static`);
363
+ const context = await scopeAndVerify(input, options);
364
+ const prepared = await resolveFor(context, options, contractFormat(format));
365
+ return packageAs(prepared, format, options);
366
+ }
367
+ /**
368
+ * Report, for one (bundle, audience) and these settings, which packaging
369
+ * targets are available and why each other one is not, without returning
370
+ * any packaging: an unusable link is never handed out. Errors of the
371
+ * request itself (no audience, a bad wording pack, an ambiguous registry,
372
+ * scoping a bundle that did not verify) are thrown as buildPresentation
373
+ * throws them, since no packaging of it exists.
374
+ *
375
+ * Available here means buildPresentation succeeds for that target with the
376
+ * same settings: every target is packaged and the result discarded.
377
+ */
378
+ export async function availablePackagings(input, options) {
379
+ const context = await scopeAndVerify(input, options);
380
+ const out = [];
381
+ for (const target of PACKAGING_TARGETS) {
382
+ const prepared = await resolveFor(context, options, contractFormat(target));
383
+ try {
384
+ await packageAs(prepared, target, options);
385
+ out.push({ target, available: true });
386
+ }
387
+ catch (err) {
388
+ if (err instanceof FragmentTooLargeError)
389
+ out.push({
390
+ target,
391
+ available: false,
392
+ reason: {
393
+ code: "fragment-too-large",
394
+ subject: err.subject,
395
+ length: err.length,
396
+ limit: err.maxLength,
397
+ message: err.message,
398
+ },
399
+ });
400
+ else if (err instanceof PackagingUnavailableError)
401
+ out.push({ target, available: false, reason: err.reason });
402
+ else
403
+ throw err;
404
+ }
405
+ }
406
+ return out;
407
+ }
408
+ async function packageAs(prepared, format, options) {
409
+ const { common, registry } = prepared;
410
+ const { audience, bundle } = common;
411
+ const modules = emitterModules(options.modules ?? []);
412
+ if (format === "html") {
413
+ const html = await packageOffline({
414
+ bundle,
415
+ audience,
416
+ depth: options.depth,
417
+ title: options.title,
418
+ themeCss: options.themeCss,
419
+ wording: options.wording,
420
+ }, requireRuntime(options.runtime, format), modules);
421
+ return { ...common, format, html };
422
+ }
423
+ if (format === "fragment") {
424
+ const runtime = requireRuntime(options.runtime, format);
425
+ const runtimePin = await sha256Hex(new TextEncoder().encode(runtime.code));
426
+ if (runtime.sha256 !== undefined && runtime.sha256 !== runtimePin)
427
+ throw new PresentationBuildError("browser IIFE does not match its SHA-256 pin");
428
+ const payload = {
429
+ fragment_version: PRESENTATION_FRAGMENT_VERSION,
430
+ audience,
431
+ presentation: common.module ?? "auto",
432
+ ...(options.depth === undefined ? {} : { depth: options.depth }),
433
+ ...(options.title === undefined ? {} : { title: options.title }),
434
+ ...(options.themeCss === undefined
435
+ ? {}
436
+ : { theme_css: options.themeCss }),
437
+ ...(options.wording === undefined
438
+ ? {}
439
+ : {
440
+ wording: {
441
+ pack: options.wording.pack,
442
+ sha256: options.wording.sha256,
443
+ },
444
+ }),
445
+ core_runtime_sha256: runtimePin,
446
+ module_sha256: modules.map((m) => m.sha256),
447
+ bundle,
448
+ };
449
+ const encoded = encodePresentationFragment(payload, {
450
+ maxLength: options.maxFragmentLength ?? FRAGMENT_TOKEN_DEFAULT_BUDGET,
451
+ ...(options.viewerUrl === undefined
452
+ ? {}
453
+ : { viewerUrl: options.viewerUrl }),
454
+ });
455
+ return {
456
+ ...common,
457
+ format,
458
+ fragment: encoded.fragment,
459
+ ...(encoded.url === undefined ? {} : { url: encoded.url }),
460
+ payload,
461
+ };
462
+ }
463
+ if (format === "static") {
464
+ const page = await packageStatic(prepared, options);
465
+ return { ...common, format, ...page };
466
+ }
467
+ const embedded = renderOptions({ audience, depth: options.depth, wording: options.wording }, "embedded");
468
+ // With the core runtime, also the snippet a host page inlines: the same
469
+ // renderEvidenceGraph call as mount, written out (section 2.3).
470
+ const snippet = options.runtime === undefined
471
+ ? {}
472
+ : emitEmbeddedHtml(bundle, options.runtime.code, {
473
+ ...(options.runtime.sha256 === undefined
474
+ ? {}
475
+ : { coreRuntimeSha256: options.runtime.sha256 }),
476
+ modules,
477
+ renderOptions: new TextDecoder().decode(jcs(embedded)),
478
+ });
479
+ return {
480
+ ...common,
481
+ format,
482
+ ...snippet,
483
+ mount: (element) => mountPresentation(element, { bundle, ...embedded, registry }),
484
+ };
485
+ }
486
+ const escapeText = (value) => value
487
+ .replaceAll("&", "&")
488
+ .replaceAll("<", "&lt;")
489
+ .replaceAll(">", "&gt;")
490
+ .replaceAll('"', "&#34;");
491
+ /**
492
+ * The static page: render the scoped bundle at build time exactly as the
493
+ * offline file renders it in the reader's browser (same bundle, audience,
494
+ * html format, depth, wording and registry), then write the markup with no
495
+ * script. The page states that it is not self-verifying and gives the
496
+ * verification result the builder computed.
497
+ */
498
+ async function packageStatic(prepared, options) {
499
+ const limit = options.maxStaticBytes ?? STATIC_PAGE_DEFAULT_BUDGET;
500
+ if (!Number.isSafeInteger(limit) || limit <= 0)
501
+ throw new PresentationBuildError(`maxStaticBytes must be a positive integer, not ${String(limit)}`);
502
+ if (typeof document === "undefined")
503
+ throw new PackagingUnavailableError({
504
+ code: "no-document",
505
+ message: "format static renders at build time and needs a DOM document (in node, a jsdom document as globalThis.document)",
506
+ });
507
+ const { common, context, registry } = prepared;
508
+ const root = document.createElement("div");
509
+ // From the bundle, as the offline file does: the page there verifies the
510
+ // bundle it carries and names no countersigner, so this does the same.
511
+ // The root is in the document while it renders, as the page's #app it
512
+ // becomes, so the core's frame check sees the styles a module adds as
513
+ // they apply in the reader's browser: a module stylesheet that hides or
514
+ // restyles the banner is discarded, not packaged.
515
+ root.id = "app";
516
+ (document.body ?? document.documentElement).append(root);
517
+ try {
518
+ await renderEvidenceGraph(common.bundle, root, undefined, {
519
+ audience: common.audience,
520
+ format: "html",
521
+ ...(options.depth === undefined ? {} : { depth: options.depth }),
522
+ ...(options.wording === undefined ? {} : { wording: options.wording }),
523
+ registry,
524
+ });
525
+ }
526
+ finally {
527
+ root.remove();
528
+ }
529
+ // The page runs no script, so every toggle's body is built now, with the
530
+ // same builders the toggle runs where script runs, and every toggle stays
531
+ // open or closed as the depth left it: a toggle the reader opens shows
532
+ // what the offline file shows (capsule-viewer#67). Each conversation is
533
+ // kept once, in the core's records section, and every card's conversation
534
+ // becomes a link to it.
535
+ fillForNoScript(root);
536
+ const unbuilt = [
537
+ ...root.querySelectorAll('[data-body="pending"]'),
538
+ ].map((body) => body.localName === "details"
539
+ ? (body.querySelector(":scope > summary")?.textContent ?? "").trim()
540
+ : `<${body.localName}${body.className === "" ? "" : ` class="${body.className}"`}>`);
541
+ if (unbuilt.length > 0)
542
+ throw new PackagingUnavailableError({
543
+ code: "static-body-unbuilt",
544
+ unbuilt,
545
+ message: `${unbuilt.length} toggle ${unbuilt.length === 1 ? "body" : "bodies"} could not be built for a page that runs no script (${unbuilt.map((u) => JSON.stringify(u)).join(", ")}), so the static page is not written`,
546
+ });
547
+ // The banner state the page must show (presentation contract section
548
+ // 6.2), from the same verification and, like the page, no countersigner.
549
+ const stamps = await classifyCountersignatures(context.countersignatures.map((entry) => entry.value), context.verification.bundleDigest, declaredProducerKeys(context.bundle), undefined);
550
+ const verification = verificationBanner(context, stamps).state;
551
+ const shown = [...root.querySelectorAll("[data-verify]")].map((e) => e.getAttribute("data-verify"));
552
+ if (shown.length !== 1 || shown[0] !== verification)
553
+ throw new Error("the rendered verification state differs from the builder's");
554
+ const all = [...root.querySelectorAll("*")];
555
+ if (all.some((e) => e.localName === "script" ||
556
+ [...e.attributes].some((a) => a.name.toLowerCase().startsWith("on"))))
557
+ throw new PackagingUnavailableError({
558
+ code: "static-carries-script",
559
+ message: "the rendered page carries a script element or an event-handler attribute, so it cannot be packaged as static",
560
+ });
561
+ const appStyles = all
562
+ .filter((e) => e.localName === "style")
563
+ .map((e) => e.textContent ?? "");
564
+ const appStyleAttributes = all
565
+ .map((e) => e.getAttribute("style"))
566
+ .filter((v) => v !== null);
567
+ const entries = options.wording === undefined
568
+ ? undefined
569
+ : await checkWordingPack(options.wording);
570
+ const title = options.title !== undefined && options.title !== ""
571
+ ? options.title
572
+ : entries?.[WORDING_TITLE_KEY];
573
+ const noticeHtml = `<aside class="aac-static-notice" data-static-notice="not-self-verifying" data-built-verification="${verification}">` +
574
+ `<p><strong>${escapeText(STATIC_NOT_SELF_VERIFYING)}</strong></p>` +
575
+ `<p>${escapeText(STATIC_BUILD_TIME_STATEMENT)}</p>` +
576
+ `<p>Verification result when this page was built: <strong>${escapeText(STATIC_VERIFICATION_WORDS[verification])}</strong>.</p>` +
577
+ `</aside>`;
578
+ const html = emitStaticEvidenceGraphHtml({
579
+ appHtml: root.innerHTML,
580
+ appClass: root.className,
581
+ appStyles,
582
+ appStyleAttributes,
583
+ noticeHtml,
584
+ }, {
585
+ ...(title === undefined ? {} : { title }),
586
+ ...(options.themeCss === undefined ? {} : { themeCss: options.themeCss }),
587
+ });
588
+ const bytes = new TextEncoder().encode(html).length;
589
+ if (bytes > limit)
590
+ throw new PackagingUnavailableError({
591
+ code: "static-too-large",
592
+ bytes,
593
+ limit,
594
+ message: `the static page, with every toggle's body built, is ${bytes} bytes, over the ${limit}-byte budget; share the offline file instead, or raise maxStaticBytes`,
595
+ });
596
+ return { html, verification, bytes, limit };
597
+ }
598
+ /**
599
+ * The hand-back: rebuild the exact offline .html a fragment was made from.
600
+ * The fragment carries pins, not code; the runtime and modules given here
601
+ * must match them, or this refuses rather than build a different file.
602
+ * A module given with its manifest has its stylesheet pins checked against
603
+ * it, as {@link buildPresentation} checks them.
604
+ * It never scopes: the fragment's bundle was scoped before encoding.
605
+ */
606
+ export async function offlineHtmlFromFragment(token, runtime, modules = [], maxLength) {
607
+ const payload = decodePresentationFragment(token, maxLength);
608
+ modules.forEach(checkStylePins);
609
+ const runtimePin = await sha256Hex(new TextEncoder().encode(runtime.code));
610
+ if (runtimePin !== payload.core_runtime_sha256)
611
+ throw new PresentationBuildError("this runtime is not the one the fragment was built with");
612
+ const pins = modules.map((m) => m.sha256);
613
+ if (pins.length !== payload.module_sha256.length ||
614
+ pins.some((pin, i) => pin !== payload.module_sha256[i]))
615
+ throw new PresentationBuildError("these modules are not the ones the fragment was built with");
616
+ return packageOffline({
617
+ bundle: payload.bundle,
618
+ audience: payload.audience,
619
+ depth: payload.depth,
620
+ title: payload.title,
621
+ themeCss: payload.theme_css,
622
+ wording: payload.wording,
623
+ }, { code: runtime.code, sha256: runtimePin }, emitterModules(modules));
624
+ }
625
+ const FRAGMENT_VIEWER_MARKER = {
626
+ aac_fragment_viewer: PRESENTATION_FRAGMENT_VERSION,
627
+ };
628
+ /** The fragment viewer's bootstrap. */
629
+ export const FRAGMENT_VIEWER_BOOTSTRAP = 'EvidenceGraph.mountPresentationFragment(location.hash, document.getElementById("app"));';
630
+ /**
631
+ * A serverless fragment viewer: an offline page, with the same shell and
632
+ * CSP, whose data is the URL fragment it is opened with. Open it as
633
+ * `viewer.html#<token>`; nothing is fetched. It applies no theme CSS from
634
+ * the fragment (its CSP admits only the styles hashed into it); the theme
635
+ * comes back in the offline file {@link offlineHtmlFromFragment} rebuilds.
636
+ */
637
+ export function buildFragmentViewerHtml(runtime, modules = []) {
638
+ return emitEvidenceGraphHtml(FRAGMENT_VIEWER_MARKER, runtime.code, {
639
+ ...(runtime.sha256 === undefined
640
+ ? {}
641
+ : { coreRuntimeSha256: runtime.sha256 }),
642
+ modules,
643
+ bootstrap: FRAGMENT_VIEWER_BOOTSTRAP,
644
+ });
645
+ }
646
+ //# sourceMappingURL=presentation-builder.js.map