@kaleidal/relikt 0.1.1 → 0.1.3

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 (2) hide show
  1. package/dist/relikt.js +325 -125
  2. package/package.json +1 -1
package/dist/relikt.js CHANGED
@@ -24893,13 +24893,22 @@ var Shot = object({
24893
24893
  theme: Theme.optional(),
24894
24894
  fullPage: boolean2()
24895
24895
  });
24896
+ var Box = {
24897
+ viewport: string2(),
24898
+ x: number2(),
24899
+ y: number2(),
24900
+ width: number2().positive(),
24901
+ height: number2().positive()
24902
+ };
24903
+ var Link = union([object({ ...Box, path: string2() }), object({ ...Box, part: string2() })]);
24896
24904
  var Part = object({
24897
24905
  id: string2(),
24898
24906
  type: _enum(partTypes),
24899
24907
  name: string2(),
24900
24908
  path: string2().optional(),
24901
24909
  capture: array(_enum(captureModes)),
24902
- shots: array(Shot)
24910
+ shots: array(Shot),
24911
+ links: array(Link).default([])
24903
24912
  });
24904
24913
  var Flow = object({
24905
24914
  file: string2(),
@@ -24978,6 +24987,9 @@ function exhibitSlug(date, label) {
24978
24987
  function shotFile(partId, viewport, theme) {
24979
24988
  return `${layout.shots}/${partId}/${theme ? `${viewport}-${theme}` : viewport}.png`;
24980
24989
  }
24990
+ function flowFile(title) {
24991
+ return `${layout.flows}/${slugify2(title) || "flow"}.webm`;
24992
+ }
24981
24993
  function isDedupable(path) {
24982
24994
  return path.startsWith("visual/") || path.startsWith(`${layout.artifacts}/`);
24983
24995
  }
@@ -25012,7 +25024,7 @@ async function treeHash(files) {
25012
25024
  var encoder = new TextEncoder;
25013
25025
  // src/exhibit/exhibit.ts
25014
25026
  import { existsSync } from "node:fs";
25015
- import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
25027
+ import { mkdir as mkdir2, readFile as readFile2, rm, writeFile as writeFile2 } from "node:fs/promises";
25016
25028
  import { dirname as dirname2, join as join2, relative } from "node:path";
25017
25029
 
25018
25030
  // src/util/run.ts
@@ -25086,6 +25098,9 @@ var authScreen = /sign[\s-]?(in|up)|log[\s-]?in|auth|password/i;
25086
25098
  function isCoverCandidate(part, shot) {
25087
25099
  return part.type !== "dialog" && shot.viewport === "laptop" && shot.theme !== "dark" && !authScreen.test(`${part.name} ${part.path ?? ""}`);
25088
25100
  }
25101
+ function partId(name) {
25102
+ return slugify2(name) || "untitled";
25103
+ }
25089
25104
  function freeFolder(base) {
25090
25105
  if (!existsSync(base))
25091
25106
  return base;
@@ -25104,7 +25119,7 @@ class Exhibit {
25104
25119
  this.manifest = manifest;
25105
25120
  }
25106
25121
  static async create(options) {
25107
- const date = today();
25122
+ const date = options.date ? Manifest.shape.date.parse(options.date) : today();
25108
25123
  const label = options.label ?? options.reason;
25109
25124
  const dir = freeFolder(join2(exhibitsRoot, slugify2(options.project), exhibitSlug(date, label)));
25110
25125
  const manifest = {
@@ -25145,14 +25160,41 @@ class Exhibit {
25145
25160
  await mkdir2(dirname2(full), { recursive: true });
25146
25161
  return full;
25147
25162
  }
25148
- part(id, init) {
25149
- let part = this.manifest.parts.find((existing) => existing.id === id);
25150
- if (!part) {
25151
- part = { id, ...init, capture: [], shots: [] };
25152
- this.manifest.parts.push(part);
25163
+ async freshFile(file) {
25164
+ const full = await this.ensureDir(file);
25165
+ await rm(full, { force: true });
25166
+ return full;
25167
+ }
25168
+ part(init, retake = false) {
25169
+ const id = partId(init.name);
25170
+ const existing = this.manifest.parts.find((part) => part.id === id);
25171
+ if (existing && !retake) {
25172
+ throw new Error(`"${existing.name}" is already captured. Give this capture its own name, or pass retake to replace its shots.`);
25153
25173
  }
25174
+ if (existing)
25175
+ return Object.assign(existing, init);
25176
+ const part = { id, ...init, capture: [], shots: [], links: [] };
25177
+ this.manifest.parts.push(part);
25154
25178
  return part;
25155
25179
  }
25180
+ freeName(name) {
25181
+ const taken = (candidate) => this.manifest.parts.some((part) => part.id === partId(candidate));
25182
+ let candidate = name;
25183
+ for (let count = 2;taken(candidate); count++)
25184
+ candidate = `${name} ${count}`;
25185
+ return candidate;
25186
+ }
25187
+ linkPages(part, links) {
25188
+ part.links = [...part.links.filter((link) => !("path" in link)), ...links];
25189
+ }
25190
+ linkPart(from, link) {
25191
+ from.links = [...from.links.filter((existing) => !("part" in existing) || existing.part !== link.part), link];
25192
+ }
25193
+ markReplayable(part, replayable) {
25194
+ part.capture = part.capture.filter((mode) => mode !== "replayable");
25195
+ if (replayable)
25196
+ part.capture.unshift("replayable");
25197
+ }
25156
25198
  addShot(part, shot) {
25157
25199
  part.shots = part.shots.filter((existing) => existing.file !== shot.file);
25158
25200
  part.shots.push(shot);
@@ -25234,7 +25276,7 @@ async function whoamiCommand() {
25234
25276
  }
25235
25277
 
25236
25278
  // src/exhibit/artifacts.ts
25237
- import { copyFile, open as open2, rm, stat } from "node:fs/promises";
25279
+ import { copyFile, open as open2, rm as rm2, stat } from "node:fs/promises";
25238
25280
  import { basename } from "node:path";
25239
25281
 
25240
25282
  // src/util/hash.ts
@@ -25343,7 +25385,7 @@ async function detect(path) {
25343
25385
  async function addArtifact(exhibit, source, overrides = {}) {
25344
25386
  const file = `${layout.artifacts}/${basename(source)}`;
25345
25387
  const target = await exhibit.ensureDir(file);
25346
- await rm(target, { force: true });
25388
+ await rm2(target, { force: true });
25347
25389
  await copyFile(source, target);
25348
25390
  const detected = await detect(target);
25349
25391
  const artifact = {
@@ -25364,7 +25406,7 @@ async function addSourceTarball(exhibit, cwd) {
25364
25406
  const commit = exhibit.manifest.source.commit?.slice(0, 12) ?? "worktree";
25365
25407
  const file = `${layout.artifacts}/source-${commit}.tar.gz`;
25366
25408
  const target = await exhibit.ensureDir(file);
25367
- await rm(target, { force: true });
25409
+ await rm2(target, { force: true });
25368
25410
  await run("sh", ["-c", `git ls-files -z -co --exclude-standard | tar --null --ignore-failed-read -T - -czf "$0"`, target], { cwd: root });
25369
25411
  const artifact = {
25370
25412
  file,
@@ -25381,12 +25423,14 @@ async function addSourceTarball(exhibit, cwd) {
25381
25423
  // src/replay/serve.ts
25382
25424
  import { createReadStream as createReadStream2, existsSync as existsSync3, statSync } from "node:fs";
25383
25425
  import { createServer } from "node:http";
25426
+ import { isIPv6 } from "node:net";
25384
25427
  import { extname, join as join4, normalize } from "node:path";
25385
25428
 
25386
25429
  // ../replay-runtime/src/archive.ts
25387
25430
  var runtimePrefix = "/__relikt/";
25388
25431
  var workerPath = "/relikt-sw.js";
25389
25432
  var archivePath = `${runtimePrefix}archive.json`;
25433
+ var notArchivedHeader = "x-relikt-not-archived";
25390
25434
  function isRuntimePath(pathname) {
25391
25435
  return pathname === workerPath || pathname.startsWith(runtimePrefix);
25392
25436
  }
@@ -25420,7 +25464,7 @@ var types = {
25420
25464
  ".json": "application/json",
25421
25465
  ".png": "image/png"
25422
25466
  };
25423
- function serveReplay(exhibit, port) {
25467
+ function serveReplay(exhibit, port, address = "127.0.0.1") {
25424
25468
  const root = exhibit.path(layout.replay);
25425
25469
  if (!existsSync3(join4(root, replayLayout.bootstrap)))
25426
25470
  throw new Error("This exhibit has no replay");
@@ -25436,7 +25480,11 @@ function serveReplay(exhibit, port) {
25436
25480
  response.writeHead(200, { "content-type": types[extname(file)] ?? "application/octet-stream", "cache-control": "no-cache" });
25437
25481
  createReadStream2(file).pipe(response);
25438
25482
  });
25439
- return new Promise((resolve) => server.listen(port, "127.0.0.1", () => resolve(`http://localhost:${port}/`)));
25483
+ return new Promise((resolve) => server.listen(port, address, () => {
25484
+ const { port: bound } = server.address();
25485
+ const host = isIPv6(address) ? `[${address}]` : "localhost";
25486
+ resolve({ url: `http://${host}:${bound}/`, close: () => server.close() });
25487
+ }));
25440
25488
  }
25441
25489
 
25442
25490
  // src/sync/pull.ts
@@ -25463,11 +25511,11 @@ import { readFile as readFile4, stat as stat2 } from "node:fs/promises";
25463
25511
  import { join as join6 } from "node:path";
25464
25512
 
25465
25513
  // src/util/fs.ts
25466
- import { mkdir as mkdir3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
25514
+ import { mkdir as mkdir3, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
25467
25515
  import { dirname as dirname3 } from "node:path";
25468
25516
  async function writeFresh(path, data) {
25469
25517
  await mkdir3(dirname3(path), { recursive: true });
25470
- await rm2(path, { force: true });
25518
+ await rm3(path, { force: true });
25471
25519
  await writeFile3(path, data);
25472
25520
  }
25473
25521
 
@@ -25593,6 +25641,7 @@ async function newCommand(project, options) {
25593
25641
  kind: Kind.parse(options.kind),
25594
25642
  reason: Reason.parse(options.reason),
25595
25643
  label: options.label,
25644
+ date: options.date,
25596
25645
  cwd: process.cwd()
25597
25646
  });
25598
25647
  console.log(exhibit.dir);
@@ -25612,14 +25661,12 @@ async function listCommand() {
25612
25661
  }
25613
25662
  }
25614
25663
  async function replayCommand(reference, port) {
25615
- const url = await serveReplay(await openExhibit(reference), port);
25664
+ const { url } = await serveReplay(await openExhibit(reference), port);
25616
25665
  console.log(`Replay running at ${url}`);
25617
25666
  }
25618
25667
 
25619
25668
  // src/capture/desktop/session.ts
25620
- import { mkdtemp as mkdtemp2, readFile as readFile6, rename as rename2, rm as rm4 } from "node:fs/promises";
25621
- import { tmpdir as tmpdir2 } from "node:os";
25622
- import { dirname as dirname5, join as join14 } from "node:path";
25669
+ import { readFile as readFile6, rm as rm5 } from "node:fs/promises";
25623
25670
 
25624
25671
  // src/capture/options.ts
25625
25672
  var desktopViewports = {
@@ -25650,9 +25697,10 @@ async function settle2(page, idle = 4000) {
25650
25697
  await page.waitForLoadState("networkidle", { timeout: idle }).catch(() => {
25651
25698
  return;
25652
25699
  });
25653
- await page.evaluate(() => new Promise((resolve) => {
25654
- document.fonts.ready.then(() => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 250))));
25700
+ await page.evaluate(() => document.fonts.ready.then(() => {
25701
+ return;
25655
25702
  }));
25703
+ await page.waitForTimeout(250);
25656
25704
  }
25657
25705
  async function sameOriginLinks(page) {
25658
25706
  return page.evaluate(() => {
@@ -25683,8 +25731,8 @@ function electronBinary(executable, cwd) {
25683
25731
  function defined(env) {
25684
25732
  return Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== undefined));
25685
25733
  }
25686
- function scopeRefs(snapshot, window) {
25687
- return snapshot.replace(/\[ref=(e\d+)\]/g, `[ref=${window}:$1]`);
25734
+ function scopeRefs(snapshot, window2) {
25735
+ return snapshot.replace(/\[ref=(e\d+)\]/g, `[ref=${window2}:$1]`);
25688
25736
  }
25689
25737
  function links() {
25690
25738
  const routes = new Map;
@@ -25729,10 +25777,10 @@ class ElectronApp {
25729
25777
  await settle2(page);
25730
25778
  return new ElectronApp(display, app, page);
25731
25779
  }
25732
- page(window) {
25733
- const page = this.app.windows()[Number(window) - 1];
25780
+ page(window2) {
25781
+ const page = this.app.windows()[Number(window2) - 1];
25734
25782
  if (!page)
25735
- throw new Error(`There is no window ${window}`);
25783
+ throw new Error(`There is no window ${window2}`);
25736
25784
  return page;
25737
25785
  }
25738
25786
  async outline() {
@@ -25758,13 +25806,13 @@ ${await this.active.ariaSnapshot()}`).digest("hex");
25758
25806
  async raise(page) {
25759
25807
  this.active = page;
25760
25808
  const title = await page.title();
25761
- const window = (await this.display.sway.windows()).find((candidate) => candidate.title === title);
25762
- if (window)
25763
- await this.display.sway.focus(window.id);
25809
+ const window2 = (await this.display.sway.windows()).find((candidate) => candidate.title === title);
25810
+ if (window2)
25811
+ await this.display.sway.focus(window2.id);
25764
25812
  }
25765
25813
  async activate(ref) {
25766
- const [window = "", element] = ref.split(":");
25767
- const page = this.page(window);
25814
+ const [window2 = "", element] = ref.split(":");
25815
+ const page = this.page(window2);
25768
25816
  if (!element)
25769
25817
  return this.raise(page);
25770
25818
  this.active = page;
@@ -25773,8 +25821,8 @@ ${await this.active.ariaSnapshot()}`).digest("hex");
25773
25821
  async type(text, ref) {
25774
25822
  if (!ref)
25775
25823
  return this.active.keyboard.type(text);
25776
- const [window = "", element] = ref.split(":");
25777
- this.active = this.page(window);
25824
+ const [window2 = "", element] = ref.split(":");
25825
+ this.active = this.page(window2);
25778
25826
  await this.active.locator(`aria-ref=${element}`).fill(text);
25779
25827
  }
25780
25828
  async press(key) {
@@ -26187,8 +26235,8 @@ class Atspi {
26187
26235
  doAction(target, index) {
26188
26236
  return this.call(target, action, "DoAction", "i", [index]);
26189
26237
  }
26190
- async contentOrigin(window) {
26191
- const children2 = (await this.call(window, accessible, "GetChildren")).map(node2);
26238
+ async contentOrigin(window2) {
26239
+ const children2 = (await this.call(window2, accessible, "GetChildren")).map(node2);
26192
26240
  const boxes = (await Promise.all(children2.map((child) => this.extents(child)))).filter((box) => box.x >= 0 && box.y >= 0 && box.width > 0 && box.height > 0);
26193
26241
  if (!boxes.length)
26194
26242
  return { x: 0, y: 0 };
@@ -26311,8 +26359,8 @@ function outline(root) {
26311
26359
  for (const child of element.children)
26312
26360
  visit(child, flatten ? depth : depth + 1, flatten ? owner : element.name);
26313
26361
  };
26314
- for (const window of root.children)
26315
- visit(window, 0, "");
26362
+ for (const window2 of root.children)
26363
+ visit(window2, 0, "");
26316
26364
  return lines.join(`
26317
26365
  `);
26318
26366
  }
@@ -26394,14 +26442,14 @@ function beforeExit(child, work) {
26394
26442
  }
26395
26443
  async function start(display, atspi, target, theme) {
26396
26444
  const known = new Set((await atspi.applications()).map((app) => app.bus));
26397
- const window = display.sway.nextWindow();
26445
+ const window2 = display.sway.nextWindow();
26398
26446
  const child = spawn3("sh", ["-c", target.command], {
26399
26447
  cwd: target.cwd,
26400
26448
  env: { ...display.env, ...target.env, ...themeEnvironment[theme] },
26401
26449
  detached: true,
26402
26450
  stdio: "ignore"
26403
26451
  });
26404
- await beforeExit(child, window);
26452
+ await beforeExit(child, window2);
26405
26453
  const root = await atspi.newApplication(known, accessibilityDeadline());
26406
26454
  await atspi.quiet(quietTime, settleLimit);
26407
26455
  return { child, root };
@@ -26476,16 +26524,16 @@ class NativeApp {
26476
26524
  await this.click(element);
26477
26525
  }
26478
26526
  async raise(title) {
26479
- const window = (await this.display.sway.windows()).find((candidate) => candidate.title === title);
26480
- if (!window)
26527
+ const window2 = (await this.display.sway.windows()).find((candidate) => candidate.title === title);
26528
+ if (!window2)
26481
26529
  throw new Error(`No window titled "${title}" is open`);
26482
- await this.display.sway.focus(window.id);
26530
+ await this.display.sway.focus(window2.id);
26483
26531
  }
26484
26532
  async click(element) {
26485
26533
  const [windowRef = ""] = element.ref.split(".");
26486
26534
  const owner = await this.element(windowRef);
26487
26535
  const windows = await this.display.sway.windows();
26488
- const host = windows.find((window) => window.title === owner.name) ?? windows.find((window) => window.focused);
26536
+ const host = windows.find((window2) => window2.title === owner.name) ?? windows.find((window2) => window2.focused);
26489
26537
  if (!host)
26490
26538
  throw new Error(`Cannot find the window that holds ${element.ref}`);
26491
26539
  const origin = await this.atspi.contentOrigin(owner.node);
@@ -26556,7 +26604,7 @@ class NativeApp {
26556
26604
  }
26557
26605
 
26558
26606
  // src/capture/desktop/display/display.ts
26559
- import { mkdtemp, rm as rm3 } from "node:fs/promises";
26607
+ import { mkdtemp, rm as rm4 } from "node:fs/promises";
26560
26608
  import { tmpdir } from "node:os";
26561
26609
  import { join as join13 } from "node:path";
26562
26610
 
@@ -27107,7 +27155,7 @@ class Sway {
27107
27155
  return workspaces(await this.ipc.tree()).flatMap((workspace) => views([...workspace.nodes, ...workspace.floating_nodes]).map(asWindow));
27108
27156
  }
27109
27157
  async visibleArea() {
27110
- return union2((await this.windows()).filter((window) => window.visible).map((window) => window.rect));
27158
+ return union2((await this.windows()).filter((window2) => window2.visible).map((window2) => window2.rect));
27111
27159
  }
27112
27160
  setOutput(width, height, scale) {
27113
27161
  return this.ipc.command(`output * mode --custom ${width * scale}x${height * scale} scale ${scale}`);
@@ -27165,7 +27213,7 @@ class HiddenDisplay {
27165
27213
  const base = { ...userEnvironment(), XDG_RUNTIME_DIR: dir, DBUS_SESSION_BUS_ADDRESS: bus.address, AT_SPI_BUS_ADDRESS: bus.address };
27166
27214
  const sway = await Sway.start(dir, base).catch(async (error) => {
27167
27215
  await bus.close();
27168
- await rm3(dir, { recursive: true, force: true });
27216
+ await rm4(dir, { recursive: true, force: true });
27169
27217
  throw error;
27170
27218
  });
27171
27219
  const env = {
@@ -27221,12 +27269,15 @@ class HiddenDisplay {
27221
27269
  this.pointer.close();
27222
27270
  await this.sway.stop();
27223
27271
  await this.bus.close();
27224
- await rm3(this.dir, { recursive: true, force: true });
27272
+ await rm4(this.dir, { recursive: true, force: true });
27225
27273
  }
27226
27274
  }
27227
27275
 
27228
27276
  // src/capture/desktop/session.ts
27229
27277
  var home = desktopViewports.laptop;
27278
+ function partInit(options) {
27279
+ return { type: options.type ?? "window", name: options.name, path: options.path };
27280
+ }
27230
27281
  async function openApp(display, target) {
27231
27282
  await display.setViewport(home);
27232
27283
  const app = { command: target.command, cwd: target.cwd, env: target.env ?? {} };
@@ -27304,16 +27355,13 @@ class DesktopSession {
27304
27355
  async capture(options) {
27305
27356
  if (options.path !== undefined)
27306
27357
  await this.app.navigate(options.path);
27307
- const part = this.part(options);
27358
+ const part = this.exhibit.part(partInit(options), options.retake);
27308
27359
  this.journal.push({ action: "capture", options });
27309
27360
  await this.shoot(part, options);
27310
27361
  this.flow?.parts.push(part.id);
27311
27362
  await this.exhibit.save();
27312
27363
  return part;
27313
27364
  }
27314
- part(options) {
27315
- return this.exhibit.part(slugify2(options.name) || "untitled", { type: options.type ?? "window", name: options.name, path: options.path });
27316
- }
27317
27365
  themesNow(requested) {
27318
27366
  if (this.replayTheme)
27319
27367
  return requested.filter((theme) => theme === this.replayTheme);
@@ -27380,8 +27428,8 @@ class DesktopSession {
27380
27428
  async startFlow(title) {
27381
27429
  if (this.flow)
27382
27430
  throw new Error(`A flow named "${this.flow.title}" is already recording`);
27383
- const file = join14(await mkdtemp2(join14(tmpdir2(), "relikt-flow-")), "flow.webm");
27384
- const recording = await this.display.record(file);
27431
+ const file = flowFile(title);
27432
+ const recording = await this.display.record(await this.exhibit.freshFile(file));
27385
27433
  this.flow = { title, file, startedAt: Date.now(), parts: [], viewport: this.viewport, recording };
27386
27434
  }
27387
27435
  async stopFlow() {
@@ -27390,13 +27438,8 @@ class DesktopSession {
27390
27438
  throw new Error("No flow is recording");
27391
27439
  this.flow = undefined;
27392
27440
  await flow.recording.stop();
27393
- const file = `${layout.flows}/${slugify2(flow.title) || "flow"}.webm`;
27394
- const target = await this.exhibit.ensureDir(file);
27395
- await rm4(target, { force: true });
27396
- await rename2(flow.file, target);
27397
- await rm4(dirname5(flow.file), { recursive: true, force: true });
27398
27441
  this.exhibit.addFlow({
27399
- file,
27442
+ file: flow.file,
27400
27443
  title: flow.title,
27401
27444
  seconds: (Date.now() - flow.startedAt) / 1000,
27402
27445
  width: flow.viewport.width,
@@ -27404,7 +27447,7 @@ class DesktopSession {
27404
27447
  parts: [...new Set(flow.parts)]
27405
27448
  });
27406
27449
  await this.exhibit.save();
27407
- return file;
27450
+ return flow.file;
27408
27451
  }
27409
27452
  wantsDarkPass() {
27410
27453
  return !this.liveThemes && this.journal.some((step) => step.action === "capture" && (step.options.themes ?? themes).includes("dark"));
@@ -27417,7 +27460,7 @@ class DesktopSession {
27417
27460
  await app.relaunch("dark");
27418
27461
  for (const [index, step] of steps.entries()) {
27419
27462
  if (step.action === "capture") {
27420
- await this.shoot(this.part(step.options), step.options);
27463
+ await this.shoot(this.exhibit.part(partInit(step.options), true), step.options);
27421
27464
  continue;
27422
27465
  }
27423
27466
  const replayed = await this.interact(step).then(() => true, () => false);
@@ -27440,7 +27483,7 @@ class DesktopSession {
27440
27483
  this.flow = undefined;
27441
27484
  await this.app.close().finally(() => this.display.close());
27442
27485
  if (flow)
27443
- await rm4(dirname5(flow.file), { recursive: true, force: true });
27486
+ await rm5(this.exhibit.path(flow.file), { force: true });
27444
27487
  }
27445
27488
  }
27446
27489
 
@@ -27466,7 +27509,7 @@ class Walk {
27466
27509
  async capture(name, type, path) {
27467
27510
  this.captured++;
27468
27511
  this.log(`[${this.captured}] ${type} ${name}`);
27469
- await this.session.capture({ name, type, path });
27512
+ await this.session.capture({ name: this.session.exhibit.freeName(name), type, path });
27470
27513
  }
27471
27514
  async next(kind) {
27472
27515
  if (this.full)
@@ -27498,11 +27541,11 @@ class Walk {
27498
27541
  }
27499
27542
  }
27500
27543
  async windows(discovery) {
27501
- for (const window of discovery.windows) {
27544
+ for (const window2 of discovery.windows) {
27502
27545
  if (discovery.windows.length > 1)
27503
- await this.session.activate(window.ref);
27546
+ await this.session.activate(window2.ref);
27504
27547
  await this.unseen();
27505
- await this.capture(window.name || "Main window", "window");
27548
+ await this.capture(window2.name || "Main window", "window");
27506
27549
  }
27507
27550
  }
27508
27551
  async routes(discovery) {
@@ -27555,14 +27598,11 @@ async function walkDesktop(session, log) {
27555
27598
  }
27556
27599
 
27557
27600
  // src/capture/web/session.ts
27558
- import { mkdtemp as mkdtemp3, rename as rename3, rm as rm6 } from "node:fs/promises";
27559
- import { tmpdir as tmpdir3 } from "node:os";
27560
- import { join as join17 } from "node:path";
27561
27601
  import { chromium } from "playwright-core";
27562
27602
 
27563
27603
  // src/replay/build.ts
27564
- import { copyFile as copyFile2, mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
27565
- import { join as join15 } from "node:path";
27604
+ import { copyFile as copyFile2, mkdir as mkdir6, rm as rm6 } from "node:fs/promises";
27605
+ import { join as join14 } from "node:path";
27566
27606
 
27567
27607
  // ../replay-runtime/dist/shim.js
27568
27608
  var shim_default = `(()=>{var l="relikt:not-archived";function d(e){let t=Date,r=t.now(),a=()=>e+(t.now()-r);class n extends t{constructor(...c){if(c.length===0)super(a());else super(...c)}static now(){return a()}}globalThis.Date=new Proxy(n,{apply:()=>new n().toString()})}var o,p;function m(){if(o?.isConnected)return o;o=document.createElement("relikt-notice");let e=o.attachShadow({mode:"closed"});return e.innerHTML=\`<style>
@@ -27573,16 +27613,15 @@ p{margin:0;padding:7px 14px;border-radius:999px;background:rgba(20,20,19,.88);co
27573
27613
  `;
27574
27614
 
27575
27615
  // ../replay-runtime/dist/sw.js
27576
- var sw_default = 'var m="/__relikt/";var y="/__relikt/archive.json",v=(e)=>`/__relikt/bodies/${e}`,w=(e)=>`/__relikt/shots/${e}`,b="x-relikt-not-archived",x="relikt:not-archived";function A(e){return e==="/relikt-sw.js"||e.startsWith("/__relikt/")}var L=new Set(["_","t","ts","cb","timestamp","nocache","_t","rand"]);function c(e,t){let i=[...e.searchParams.entries()].filter(([r])=>!t||!L.has(r)).sort(([r],[s])=>r.localeCompare(s)),n=new URLSearchParams(i).toString();return`${e.origin}${e.pathname}${n?`?${n}`:""}`}function l(e,t,i){let n=e.get(t);if(n)n.push(i);else e.set(t,[i])}class d{archive;withBody=new Map;exact=new Map;loose=new Map;path=new Map;served=new Map;origins;shell;constructor(e){this.archive=e;for(let t of e.entries){let i=new URL(t.url),n=t.method.toUpperCase();if(t.requestBody)l(this.withBody,`${n} ${c(i,!1)} ${t.requestBody}`,t);l(this.exact,`${n} ${c(i,!1)}`,t),l(this.loose,`${n} ${c(i,!0)}`,t),l(this.path,`${n} ${i.origin}${i.pathname}`,t)}this.origins=new Set(e.entries.map((t)=>new URL(t.url).origin)),this.shell=this.findShell()}match(e,t,i){let n=e.toUpperCase(),r=[i&&[this.withBody,`${n} ${c(t,!1)} ${i}`],[this.exact,`${n} ${c(t,!1)}`],[this.loose,`${n} ${c(t,!0)}`],[this.path,`${n} ${t.origin}${t.pathname}`]].filter(Boolean);for(let[s,o]of r){let a=s.get(o);if(!a)continue;let h=this.served.get(o)??0;return this.served.set(o,h+1),a[Math.min(h,a.length-1)]}return}fallbackShot(e){return this.archive.fallbacks.find((t)=>t.path===e)?.shot}findShell(){let e=this.archive.entries.filter((i)=>i.method==="GET"&&i.status===200&&new URL(i.url).origin===this.archive.origin&&i.headers.some(([n,r])=>n==="content-type"&&r.includes("text/html")));return new Set(e.map((i)=>i.body)).size===1?e[0]:void 0}}function k(e){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not archived</title><style>html,body{margin:0;min-height:100%;background:#f3f2ef;color:#5f5e5a;font:13px/1.5 ui-monospace,SFMono-Regular,monospace}\n@media(prefers-color-scheme:dark){html,body{background:#141413;color:#8b8a86}}\nmain{min-height:100vh;display:grid;place-items:center;text-align:center;padding:24px;box-sizing:border-box}\na{color:inherit}\nfigure{margin:0}\nimg{display:block;width:100%;height:auto}\nfigcaption{position:fixed;left:50%;bottom:16px;transform:translateX(-50%);padding:6px 12px;border-radius:999px;background:rgba(20,20,19,.86);color:#f3f2ef}</style></head>\n<body><main><div><p>${S(e)} was not archived.</p><p><a href="javascript:history.back()">Go back</a></p></div></main></body></html>`}function P(e,t){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${S(e)}</title><style>html,body{margin:0;min-height:100%;background:#f3f2ef;color:#5f5e5a;font:13px/1.5 ui-monospace,SFMono-Regular,monospace}\n@media(prefers-color-scheme:dark){html,body{background:#141413;color:#8b8a86}}\nmain{min-height:100vh;display:grid;place-items:center;text-align:center;padding:24px;box-sizing:border-box}\na{color:inherit}\nfigure{margin:0}\nimg{display:block;width:100%;height:auto}\nfigcaption{position:fixed;left:50%;bottom:16px;transform:translateX(-50%);padding:6px 12px;border-radius:999px;background:rgba(20,20,19,.86);color:#f3f2ef}</style></head>\n<body><figure><img src="${t}" alt=""><figcaption>Screenshot only · <a href="javascript:history.back()">back</a></figcaption></figure></body></html>`}function S(e){return e.replace(/[<>&"]/g,(t)=>`&#${t.charCodeAt(0)};`)}var M=new Set([301,302,303,307,308]),C="relikt-bodies";async function T(e){let t=await caches.open(C),i=new URL(v(e),self.location.origin).href,n=await t.match(i);if(n)return n;let r=await fetch(i);if(r.ok)await t.put(i,r.clone());return r}function j(e,t){let i=new URL(e,t.origin);if(i.origin!==t.origin)return i.href;return new URL(i.pathname+i.search+i.hash,self.location.origin).href}function B(e,t,i){let n=`<script>window.__relikt=${JSON.stringify(t).replace(/</g,"\\\\u003c")};${i}</script>`,r=/<head[^>]*>/i.exec(e);if(r)return e.slice(0,r.index+r[0].length)+n+e.slice(r.index+r[0].length);return n+e}async function p(e,t,i){let n=new Headers(e.headers);if(M.has(e.status)){let s=n.get("location");if(s)return Response.redirect(j(s,t),e.status)}if(!e.body||e.status===204||e.status===304)return new Response(null,{status:e.status===304?200:e.status,headers:n});let r=await T(e.body);if(!r.ok)return g();if(n.get("content-type")?.includes("text/html")){let{source:s,config:o}=await i();return new Response(B(await r.text(),o,s),{status:e.status,headers:n})}return new Response(r.body,{status:e.status,headers:n})}function g(){return new Response(JSON.stringify({error:"not archived"}),{status:404,headers:{"content-type":"application/json",[b]:"1"}})}function R(e){return new Response(e,{headers:{"content-type":"text/html; charset=utf-8"}})}var U;function E(){return U??=(async()=>{let[e,t]=await Promise.all([fetch(y).then((r)=>r.json()),fetch(`${m}shim.js`).then((r)=>r.text())]),i=new d(e),n={origin:e.origin,origins:[...i.origins],frozenAt:e.frozenAt,storage:e.storage};return{archive:e,matcher:i,shim:{source:t,config:n}}})(),U}self.addEventListener("install",(e)=>e.waitUntil(E().then(()=>self.skipWaiting())));self.addEventListener("activate",(e)=>e.waitUntil(self.clients.claim()));async function W(e){if(e.method==="GET"||e.method==="HEAD")return;let t=await e.clone().arrayBuffer();if(t.byteLength===0)return;let i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i),(n)=>n.toString(16).padStart(2,"0")).join("")}async function z(e,t){(e?await self.clients.get(e):void 0)?.postMessage({type:x,url:t})}async function H(e){let{archive:t,matcher:i,shim:n}=await E(),r=e.request,s=new URL(r.url),o=s.origin===self.location.origin,a=o?new URL(s.pathname+s.search,t.origin):s,h=r.mode==="navigate",f=i.match(r.method,a,await W(r));if(f)return p(f,t,async()=>n);if(h&&o){if(i.shell)return p(i.shell,t,async()=>n);let u=i.fallbackShot(s.pathname);return R(u?P(s.pathname,w(u)):k(s.pathname))}if(r.destination==="")await z(e.clientId,a.href);return g()}self.addEventListener("fetch",(e)=>{let t=new URL(e.request.url);if(t.origin===self.location.origin&&A(t.pathname))return;if(!t.protocol.startsWith("http"))return;e.respondWith(H(e))});\n';
27616
+ var sw_default = 'var y="/__relikt/";var v="/__relikt/archive.json",w=(e)=>`/__relikt/bodies/${e}`,b=(e)=>`/__relikt/shots/${e}`,d="x-relikt-not-archived",x="relikt:not-archived";function A(e){return e==="/relikt-sw.js"||e.startsWith("/__relikt/")}var L=new Set(["_","t","ts","cb","timestamp","nocache","_t","rand"]);function c(e,t){let i=[...e.searchParams.entries()].filter(([r])=>!t||!L.has(r)).sort(([r],[o])=>r.localeCompare(o)),n=new URLSearchParams(i).toString();return`${e.origin}${e.pathname}${n?`?${n}`:""}`}function l(e,t,i){let n=e.get(t);if(n)n.push(i);else e.set(t,[i])}class p{archive;withBody=new Map;exact=new Map;loose=new Map;path=new Map;served=new Map;origins;shell;constructor(e){this.archive=e;for(let t of e.entries){let i=new URL(t.url),n=t.method.toUpperCase();if(t.requestBody)l(this.withBody,`${n} ${c(i,!1)} ${t.requestBody}`,t);l(this.exact,`${n} ${c(i,!1)}`,t),l(this.loose,`${n} ${c(i,!0)}`,t),l(this.path,`${n} ${i.origin}${i.pathname}`,t)}this.origins=new Set(e.entries.map((t)=>new URL(t.url).origin)),this.shell=this.findShell()}match(e,t,i){let n=e.toUpperCase(),r=[i&&[this.withBody,`${n} ${c(t,!1)} ${i}`],[this.exact,`${n} ${c(t,!1)}`],[this.loose,`${n} ${c(t,!0)}`],[this.path,`${n} ${t.origin}${t.pathname}`]].filter(Boolean);for(let[o,s]of r){let a=o.get(s);if(!a)continue;let h=this.served.get(s)??0;return this.served.set(s,h+1),a[Math.min(h,a.length-1)]}return}fallbackShot(e){return this.archive.fallbacks.find((t)=>t.path===e)?.shot}findShell(){let e=this.archive.entries.filter((i)=>i.method==="GET"&&i.status===200&&new URL(i.url).origin===this.archive.origin&&i.headers.some(([n,r])=>n==="content-type"&&r.includes("text/html")));return new Set(e.map((i)=>i.body)).size===1?e[0]:void 0}}function k(e){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not archived</title><style>html,body{margin:0;min-height:100%;background:#f3f2ef;color:#5f5e5a;font:13px/1.5 ui-monospace,SFMono-Regular,monospace}\n@media(prefers-color-scheme:dark){html,body{background:#141413;color:#8b8a86}}\nmain{min-height:100vh;display:grid;place-items:center;text-align:center;padding:24px;box-sizing:border-box}\na{color:inherit}\nfigure{margin:0}\nimg{display:block;width:100%;height:auto}\nfigcaption{position:fixed;left:50%;bottom:16px;transform:translateX(-50%);padding:6px 12px;border-radius:999px;background:rgba(20,20,19,.86);color:#f3f2ef}</style></head>\n<body><main><div><p>${S(e)} was not archived.</p><p><a href="javascript:history.back()">Go back</a></p></div></main></body></html>`}function P(e,t){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${S(e)}</title><style>html,body{margin:0;min-height:100%;background:#f3f2ef;color:#5f5e5a;font:13px/1.5 ui-monospace,SFMono-Regular,monospace}\n@media(prefers-color-scheme:dark){html,body{background:#141413;color:#8b8a86}}\nmain{min-height:100vh;display:grid;place-items:center;text-align:center;padding:24px;box-sizing:border-box}\na{color:inherit}\nfigure{margin:0}\nimg{display:block;width:100%;height:auto}\nfigcaption{position:fixed;left:50%;bottom:16px;transform:translateX(-50%);padding:6px 12px;border-radius:999px;background:rgba(20,20,19,.86);color:#f3f2ef}</style></head>\n<body><figure><img src="${t}" alt=""><figcaption>Screenshot only · <a href="javascript:history.back()">back</a></figcaption></figure></body></html>`}function S(e){return e.replace(/[<>&"]/g,(t)=>`&#${t.charCodeAt(0)};`)}var M=new Set([301,302,303,307,308]),C="relikt-bodies";async function T(e){let t=await caches.open(C),i=new URL(w(e),self.location.origin).href,n=await t.match(i);if(n)return n;let r=await fetch(i);if(r.ok)await t.put(i,r.clone());return r}function j(e,t){let i=new URL(e,t.origin);if(i.origin!==t.origin)return i.href;return new URL(i.pathname+i.search+i.hash,self.location.origin).href}function B(e,t,i){let n=`<script>window.__relikt=${JSON.stringify(t).replace(/</g,"\\\\u003c")};${i}</script>`,r=/<head[^>]*>/i.exec(e);if(r)return e.slice(0,r.index+r[0].length)+n+e.slice(r.index+r[0].length);return n+e}async function g(e,t,i){let n=new Headers(e.headers);if(M.has(e.status)){let o=n.get("location");if(o)return Response.redirect(j(o,t),e.status)}if(!e.body||e.status===204)return new Response(null,{status:e.status,headers:n});let r=await T(e.body);if(!r.ok)return f();if(n.get("content-type")?.includes("text/html")){let{source:o,config:s}=await i();return new Response(B(await r.text(),s,o),{status:e.status,headers:n})}return new Response(r.body,{status:e.status,headers:n})}function f(){return new Response(JSON.stringify({error:"not archived"}),{status:404,headers:{"content-type":"application/json",[d]:"1"}})}function R(e){return new Response(e,{headers:{"content-type":"text/html; charset=utf-8",[d]:"1"}})}var U;function E(){return U??=(async()=>{let[e,t]=await Promise.all([fetch(v).then((r)=>r.json()),fetch(`${y}shim.js`).then((r)=>r.text())]),i=new p(e),n={origin:e.origin,origins:[...i.origins],frozenAt:e.frozenAt,storage:e.storage};return{archive:e,matcher:i,shim:{source:t,config:n}}})(),U}self.addEventListener("install",(e)=>e.waitUntil(E().then(()=>self.skipWaiting())));self.addEventListener("activate",(e)=>e.waitUntil(self.clients.claim()));async function W(e){if(e.method==="GET"||e.method==="HEAD")return;let t=await e.clone().arrayBuffer();if(t.byteLength===0)return;let i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i),(n)=>n.toString(16).padStart(2,"0")).join("")}async function z(e,t){(e?await self.clients.get(e):void 0)?.postMessage({type:x,url:t})}async function H(e){let{archive:t,matcher:i,shim:n}=await E(),r=e.request,o=new URL(r.url),s=o.origin===self.location.origin,a=s?new URL(o.pathname+o.search,t.origin):o,h=r.mode==="navigate",u=i.match(r.method,a,await W(r));if(u)return g(u,t,async()=>n);if(h&&s){if(i.shell)return g(i.shell,t,async()=>n);let m=i.fallbackShot(o.pathname);return R(m?P(o.pathname,b(m)):k(o.pathname))}if(r.destination==="")await z(e.clientId,a.href);return f()}self.addEventListener("fetch",(e)=>{let t=new URL(e.request.url);if(t.origin===self.location.origin&&A(t.pathname))return;if(!t.protocol.startsWith("http"))return;e.respondWith(H(e))});\n';
27577
27617
 
27578
27618
  // src/replay/build.ts
27579
27619
  var replayRuntimeDir = `${layout.replay}/__relikt`;
27580
27620
  var replayBodiesDir = `${replayRuntimeDir}/${replayLayout.bodies}`;
27581
27621
  async function writeReplay(exhibit, archive) {
27582
- const root = exhibit.path(layout.replay);
27583
27622
  const runtime = exhibit.path(replayRuntimeDir);
27584
- const shots = join15(runtime, "shots");
27585
- await rm5(shots, { recursive: true, force: true });
27623
+ const shots = join14(runtime, "shots");
27624
+ await rm6(shots, { recursive: true, force: true });
27586
27625
  await mkdir6(shots, { recursive: true });
27587
27626
  const fallbacks = [];
27588
27627
  for (const part of exhibit.manifest.parts) {
@@ -27590,18 +27629,11 @@ async function writeReplay(exhibit, archive) {
27590
27629
  if (part.type !== "route" || !part.path || !shot)
27591
27630
  continue;
27592
27631
  const name = `${part.id}.png`;
27593
- await copyFile2(exhibit.path(shot.file), join15(shots, name));
27632
+ await copyFile2(exhibit.path(shot.file), join14(shots, name));
27594
27633
  fallbacks.push({ path: new URL(part.path, archive.origin).pathname, shot: name });
27595
27634
  }
27596
27635
  const complete = { ...archive, fallbacks };
27597
- await writeFresh(join15(root, replayLayout.bootstrap), bootstrapHtml(archive.start, exhibit.manifest.project));
27598
- await writeFresh(join15(root, replayLayout.worker), sw_default);
27599
- await writeFresh(join15(runtime, replayLayout.shim), shim_default);
27600
- await writeFresh(join15(runtime, replayLayout.archive), JSON.stringify(complete));
27601
- for (const part of exhibit.manifest.parts) {
27602
- if (part.type === "route" && part.path && !part.capture.includes("replayable"))
27603
- part.capture.unshift("replayable");
27604
- }
27636
+ await writeFresh(join14(runtime, replayLayout.archive), JSON.stringify(complete));
27605
27637
  exhibit.manifest.replay = {
27606
27638
  root: layout.replay,
27607
27639
  start: archive.start,
@@ -27609,8 +27641,18 @@ async function writeReplay(exhibit, archive) {
27609
27641
  frozenAt: new Date(archive.frozenAt).toISOString(),
27610
27642
  requests: archive.entries.length
27611
27643
  };
27644
+ await writeRuntime(exhibit);
27612
27645
  await exhibit.save();
27613
27646
  }
27647
+ async function writeRuntime(exhibit) {
27648
+ const { replay, project } = exhibit.manifest;
27649
+ if (!replay)
27650
+ return;
27651
+ const root = exhibit.path(layout.replay);
27652
+ await writeFresh(join14(root, replayLayout.bootstrap), bootstrapHtml(replay.start, project));
27653
+ await writeFresh(join14(root, replayLayout.worker), sw_default);
27654
+ await writeFresh(join14(exhibit.path(replayRuntimeDir), replayLayout.shim), shim_default);
27655
+ }
27614
27656
 
27615
27657
  // src/replay/scrub.ts
27616
27658
  var placeholder = "relikt-demo";
@@ -27706,10 +27748,45 @@ function scrubStorage(entries) {
27706
27748
  return Object.fromEntries(entries.map(({ name, value }) => [name, sensitiveName.test(name) && !/^[{[]/.test(value.trim()) ? placeholder : scrubJsonOrText(value)]));
27707
27749
  }
27708
27750
 
27751
+ // src/capture/web/links.ts
27752
+ async function pageLinks(page, fullPage) {
27753
+ return page.evaluate((fullPage) => {
27754
+ const offsetX = fullPage ? window.scrollX : 0;
27755
+ const offsetY = fullPage ? window.scrollY : 0;
27756
+ const right = fullPage ? document.documentElement.scrollWidth : window.innerWidth;
27757
+ const bottom = fullPage ? document.documentElement.scrollHeight : window.innerHeight;
27758
+ const here = location.pathname + location.search;
27759
+ const links = new Map;
27760
+ for (const anchor of document.querySelectorAll("a[href]")) {
27761
+ const url = new URL(anchor.href, location.href);
27762
+ const path = url.pathname + url.search;
27763
+ if (url.origin !== location.origin || path === here)
27764
+ continue;
27765
+ const rect = anchor.getBoundingClientRect();
27766
+ if (rect.width < 4 || rect.height < 4 || getComputedStyle(anchor).visibility === "hidden")
27767
+ continue;
27768
+ const x = rect.left + offsetX;
27769
+ const y = rect.top + offsetY;
27770
+ if (x < 0 || y < 0 || x + rect.width > right || y + rect.height > bottom)
27771
+ continue;
27772
+ const box = { path, x: Math.round(x), y: Math.round(y), width: Math.round(rect.width), height: Math.round(rect.height) };
27773
+ links.set(`${path} ${box.x} ${box.y}`, box);
27774
+ }
27775
+ return [...links.values()];
27776
+ }, fullPage);
27777
+ }
27778
+ async function elementBox(page, locator, fullPage) {
27779
+ const box = await locator.boundingBox();
27780
+ if (!box || box.width < 1 || box.height < 1)
27781
+ return;
27782
+ const scroll = fullPage ? await page.evaluate(() => ({ x: window.scrollX, y: window.scrollY })) : { x: 0, y: 0 };
27783
+ return { x: Math.round(box.x + scroll.x), y: Math.round(box.y + scroll.y), width: Math.round(box.width), height: Math.round(box.height) };
27784
+ }
27785
+
27709
27786
  // src/capture/web/recorder.ts
27710
27787
  import { existsSync as existsSync7 } from "node:fs";
27711
27788
  import { mkdir as mkdir7, writeFile as writeFile7 } from "node:fs/promises";
27712
- import { join as join16 } from "node:path";
27789
+ import { join as join15 } from "node:path";
27713
27790
  var credentialBody = /passw|token|secret|otp|api[-_]?key/i;
27714
27791
 
27715
27792
  class Recorder {
@@ -27733,11 +27810,18 @@ class Recorder {
27733
27810
  }
27734
27811
  async drain() {
27735
27812
  await this.settle();
27736
- return this.entries.sort((a, b) => a.at - b.at).map(({ at: _, ...entry }) => entry);
27813
+ const previous = new Map;
27814
+ return this.entries.sort((a, b) => a.at - b.at).filter((entry) => {
27815
+ const request = `${entry.method} ${entry.url} ${entry.requestBody ?? ""}`;
27816
+ const response = `${entry.status} ${entry.body ?? ""}`;
27817
+ const repeated = previous.get(request) === response;
27818
+ previous.set(request, response);
27819
+ return !repeated;
27820
+ }).map(({ at: _, ...entry }) => entry);
27737
27821
  }
27738
27822
  async storeBody(bytes) {
27739
27823
  const hash = sha256(bytes);
27740
- const path = join16(this.bodiesDir, hash);
27824
+ const path = join15(this.bodiesDir, hash);
27741
27825
  if (!existsSync7(path)) {
27742
27826
  await mkdir7(this.bodiesDir, { recursive: true });
27743
27827
  await writeFile7(path, bytes);
@@ -27749,7 +27833,7 @@ class Recorder {
27749
27833
  if (!url.startsWith("http"))
27750
27834
  return;
27751
27835
  const response = await request.response();
27752
- if (!response)
27836
+ if (!response || response.status() === 304)
27753
27837
  return;
27754
27838
  const at = request.timing().startTime;
27755
27839
  const headers = await response.allHeaders();
@@ -27785,6 +27869,8 @@ class WebSession {
27785
27869
  start;
27786
27870
  startedAt;
27787
27871
  flow;
27872
+ shown;
27873
+ opener;
27788
27874
  constructor(exhibit, browser, context, page, recorder, origin, start, startedAt) {
27789
27875
  this.exhibit = exhibit;
27790
27876
  this.browser = browser;
@@ -27795,7 +27881,7 @@ class WebSession {
27795
27881
  this.start = start;
27796
27882
  this.startedAt = startedAt;
27797
27883
  }
27798
- static async launch(exhibit, url, headed = false) {
27884
+ static async launch(exhibit, url, { headed = false, record = true } = {}) {
27799
27885
  const target = new URL(url);
27800
27886
  const browser = await chromium.launch({ headless: !headed });
27801
27887
  const context = await browser.newContext({
@@ -27805,8 +27891,8 @@ class WebSession {
27805
27891
  serviceWorkers: "block",
27806
27892
  reducedMotion: "no-preference"
27807
27893
  });
27808
- const recorder = new Recorder(exhibit.path(replayBodiesDir));
27809
- recorder.attach(context);
27894
+ const recorder = record ? new Recorder(exhibit.path(replayBodiesDir)) : undefined;
27895
+ recorder?.attach(context);
27810
27896
  const page = await context.newPage();
27811
27897
  const startedAt = Date.now();
27812
27898
  await page.goto(target.href);
@@ -27820,6 +27906,7 @@ class WebSession {
27820
27906
  return this.page.locator(`aria-ref=${ref}`);
27821
27907
  }
27822
27908
  async navigate(path) {
27909
+ this.opener = undefined;
27823
27910
  await this.page.goto(new URL(path, this.origin).href);
27824
27911
  await settle2(this.page);
27825
27912
  }
@@ -27829,15 +27916,36 @@ class WebSession {
27829
27916
  async afterAction() {
27830
27917
  await settle2(this.page, 2500);
27831
27918
  }
27919
+ async click(ref) {
27920
+ const target = this.locate(ref);
27921
+ const from = this.opener ? undefined : this.onScreen();
27922
+ const box = from && await elementBox(this.page, target, from.type === "route");
27923
+ if (from && box)
27924
+ this.opener = { from, box };
27925
+ await target.click();
27926
+ await this.afterAction();
27927
+ }
27928
+ onScreen() {
27929
+ const url = this.page.url();
27930
+ if (this.shown?.url === url)
27931
+ return this.shown.part;
27932
+ const { pathname, search } = new URL(url);
27933
+ return this.exhibit.manifest.parts.find((part) => part.type === "route" && (part.path === pathname + search || part.path === pathname));
27934
+ }
27832
27935
  async capture(options) {
27833
27936
  const type = options.type ?? "route";
27834
27937
  if (options.path !== undefined)
27835
27938
  await this.navigate(options.path);
27836
27939
  const path = type === "route" ? options.path ?? new URL(this.page.url()).pathname : undefined;
27837
- const id = path === "/" ? "home" : slugify2(options.name) || "untitled";
27838
- const part = this.exhibit.part(id, { type, name: options.name, path });
27940
+ const part = this.exhibit.part({ type, name: options.name, path }, options.retake);
27839
27941
  const viewports2 = pickViewports(viewports, options.viewports);
27840
27942
  const themes2 = options.themes ?? [...themes];
27943
+ const links = await pageLinks(this.page, type === "route");
27944
+ this.exhibit.linkPages(part, links.map((link) => ({ ...link, viewport: home2.name })));
27945
+ if (options.path === undefined && this.opener && this.opener.from !== part) {
27946
+ this.exhibit.linkPart(this.opener.from, { ...this.opener.box, viewport: home2.name, part: part.id });
27947
+ }
27948
+ this.opener = undefined;
27841
27949
  for (const viewport of viewports2) {
27842
27950
  await this.page.setViewportSize({ width: viewport.width, height: viewport.height });
27843
27951
  let light;
@@ -27853,7 +27961,7 @@ class WebSession {
27853
27961
  light = image;
27854
27962
  if (theme === "dark" && light?.equals(image))
27855
27963
  continue;
27856
- const file = shotFile(id, viewport.name, theme);
27964
+ const file = shotFile(part.id, viewport.name, theme);
27857
27965
  await writeFresh(this.exhibit.path(file), image);
27858
27966
  this.exhibit.addShot(part, {
27859
27967
  file,
@@ -27867,7 +27975,8 @@ class WebSession {
27867
27975
  }
27868
27976
  await this.page.setViewportSize({ width: home2.width, height: home2.height });
27869
27977
  await this.page.emulateMedia({ colorScheme: "light" });
27870
- this.flow?.parts.push(id);
27978
+ this.shown = { part, url: this.page.url() };
27979
+ this.flow?.parts.push(part.id);
27871
27980
  await this.exhibit.save();
27872
27981
  return part;
27873
27982
  }
@@ -27892,10 +28001,9 @@ class WebSession {
27892
28001
  async startFlow(title) {
27893
28002
  if (this.flow)
27894
28003
  throw new Error(`A flow named "${this.flow.title}" is already recording`);
27895
- const dir = await mkdtemp3(join17(tmpdir3(), "relikt-flow-"));
27896
- const file = join17(dir, "flow.webm");
28004
+ const file = flowFile(title);
27897
28005
  const viewport = this.page.viewportSize() ?? home2;
27898
- await this.page.screencast.start({ path: file, size: viewport });
28006
+ await this.page.screencast.start({ path: await this.exhibit.freshFile(file), size: viewport });
27899
28007
  const actions = await this.page.screencast.showActions({ cursor: "pointer", duration: 400 });
27900
28008
  this.flow = {
27901
28009
  title,
@@ -27915,12 +28023,8 @@ class WebSession {
27915
28023
  throw new Error("No flow is recording");
27916
28024
  this.flow = undefined;
27917
28025
  await flow.stop();
27918
- const file = `${layout.flows}/${slugify2(flow.title) || "flow"}.webm`;
27919
- const target = await this.exhibit.ensureDir(file);
27920
- await rm6(target, { force: true });
27921
- await rename3(flow.file, target);
27922
28026
  this.exhibit.addFlow({
27923
- file,
28027
+ file: flow.file,
27924
28028
  title: flow.title,
27925
28029
  seconds: (Date.now() - flow.startedAt) / 1000,
27926
28030
  width: flow.viewport.width,
@@ -27928,11 +28032,15 @@ class WebSession {
27928
28032
  parts: [...new Set(flow.parts)]
27929
28033
  });
27930
28034
  await this.exhibit.save();
27931
- return file;
28035
+ return flow.file;
27932
28036
  }
27933
28037
  async finish() {
27934
28038
  if (this.flow)
27935
28039
  await this.stopFlow();
28040
+ if (!this.recorder) {
28041
+ await this.browser.close();
28042
+ return;
28043
+ }
27936
28044
  const entries = await this.recorder.drain();
27937
28045
  const state = await this.context.storageState();
27938
28046
  const storage = state.origins.find((origin) => origin.origin === this.origin)?.localStorage ?? [];
@@ -27986,6 +28094,83 @@ async function recognize(exhibit) {
27986
28094
  return result;
27987
28095
  }
27988
28096
 
28097
+ // src/replay/verify.ts
28098
+ import { readFile as readFile8 } from "node:fs/promises";
28099
+ import { chromium as chromium2 } from "playwright-core";
28100
+ var { laptop } = viewports;
28101
+ var unfamiliarAddress = "::1";
28102
+ function dataUrl(png) {
28103
+ return `data:image/png;base64,${png.toString("base64")}`;
28104
+ }
28105
+ async function matches(scratch, captured, replayed) {
28106
+ return scratch.evaluate(async ({ captured, replayed, aspect }) => {
28107
+ const width = 24;
28108
+ const tolerance = 16;
28109
+ const height = Math.round(width * aspect);
28110
+ const luminance = async (src) => {
28111
+ const image = new Image;
28112
+ image.src = src;
28113
+ await image.decode();
28114
+ const canvas = new OffscreenCanvas(width, height);
28115
+ const context = canvas.getContext("2d", { willReadFrequently: true });
28116
+ context.drawImage(image, 0, 0, image.naturalWidth, image.naturalWidth * aspect, 0, 0, width, height);
28117
+ const { data } = context.getImageData(0, 0, width, height);
28118
+ const values = new Uint8Array(width * height);
28119
+ for (let index = 0;index < values.length; index++) {
28120
+ values[index] = Math.round(0.299 * data[index * 4] + 0.587 * data[index * 4 + 1] + 0.114 * data[index * 4 + 2]);
28121
+ }
28122
+ return values;
28123
+ };
28124
+ const [expected, actual] = await Promise.all([luminance(captured), luminance(replayed)]);
28125
+ const histogram = new Uint32Array(32);
28126
+ for (const value of expected)
28127
+ histogram[value >> 3]++;
28128
+ const background = histogram.indexOf(Math.max(...histogram)) * 8 + 4;
28129
+ let content = 0;
28130
+ let different = 0;
28131
+ for (let index = 0;index < expected.length; index++) {
28132
+ if (Math.abs(expected[index] - background) > tolerance)
28133
+ content++;
28134
+ if (Math.abs(expected[index] - actual[index]) > tolerance)
28135
+ different++;
28136
+ }
28137
+ return different <= content / 2;
28138
+ }, { captured: dataUrl(captured), replayed: dataUrl(replayed), aspect: laptop.height / laptop.width });
28139
+ }
28140
+ async function verifyReplay(exhibit) {
28141
+ await writeRuntime(exhibit);
28142
+ const routes = exhibit.manifest.parts.flatMap((part) => {
28143
+ const shot = part.shots.find((candidate) => candidate.viewport === laptop.name && candidate.theme !== "dark");
28144
+ return part.type === "route" && part.path && shot ? [{ part, shot }] : [];
28145
+ });
28146
+ if (!routes.length)
28147
+ return [];
28148
+ const server = await serveReplay(exhibit, 0, unfamiliarAddress);
28149
+ const browser = await chromium2.launch();
28150
+ const replayable = [];
28151
+ try {
28152
+ const context = await browser.newContext({ viewport: { width: laptop.width, height: laptop.height }, colorScheme: "light" });
28153
+ const page = await context.newPage();
28154
+ const scratch = await context.newPage();
28155
+ await page.goto(server.url);
28156
+ await page.evaluate(() => navigator.serviceWorker.ready.then(() => true));
28157
+ for (const { part, shot } of routes) {
28158
+ const response = await page.goto(new URL(part.path, server.url).href);
28159
+ await settle2(page);
28160
+ const archived = !response?.headers()[notArchivedHeader];
28161
+ const works = archived && await matches(scratch, await readFile8(exhibit.path(shot.file)), await page.screenshot());
28162
+ exhibit.markReplayable(part, works);
28163
+ if (works)
28164
+ replayable.push(part.id);
28165
+ }
28166
+ } finally {
28167
+ await browser.close();
28168
+ server.close();
28169
+ }
28170
+ await exhibit.save();
28171
+ return replayable;
28172
+ }
28173
+
27989
28174
  // src/sync/push.ts
27990
28175
  import { createReadStream as createReadStream3 } from "node:fs";
27991
28176
  import { open as open3 } from "node:fs/promises";
@@ -28056,7 +28241,7 @@ async function preserveWeb(exhibit, url) {
28056
28241
  const routes = await web.discoverRoutes();
28057
28242
  for (const [index, path] of routes.entries()) {
28058
28243
  console.log(`[${index + 1}/${routes.length}] ${path}`);
28059
- await web.capture({ name: routeName(path), path });
28244
+ await web.capture({ name: exhibit.freeName(routeName(path)), path });
28060
28245
  }
28061
28246
  await web.finish();
28062
28247
  }
@@ -28075,7 +28260,14 @@ async function preserveDesktop(exhibit, command, electron) {
28075
28260
  }
28076
28261
  async function preserveCommand(project, options) {
28077
28262
  const kind = Kind.parse(options.kind);
28078
- const exhibit = await Exhibit.create({ project, kind, reason: Reason.parse(options.reason), label: options.label, cwd: process.cwd() });
28263
+ const exhibit = await Exhibit.create({
28264
+ project,
28265
+ kind,
28266
+ reason: Reason.parse(options.reason),
28267
+ label: options.label,
28268
+ date: options.date,
28269
+ cwd: process.cwd()
28270
+ });
28079
28271
  console.log(exhibit.dir);
28080
28272
  if (kind === "web") {
28081
28273
  if (!options.url)
@@ -28087,6 +28279,8 @@ async function preserveCommand(project, options) {
28087
28279
  throw new Error("Pass --command with the command that starts the app");
28088
28280
  await preserveDesktop(exhibit, options.command, options.electron);
28089
28281
  }
28282
+ if (exhibit.manifest.replay)
28283
+ await verifyReplay(exhibit);
28090
28284
  if (await gitRoot(process.cwd()))
28091
28285
  await addSourceTarball(exhibit, process.cwd());
28092
28286
  if (exhibit.manifest.parts.length)
@@ -28123,7 +28317,7 @@ async function searchCommand(query) {
28123
28317
  // src/commands/setup.ts
28124
28318
  import { spawn as spawn7 } from "node:child_process";
28125
28319
  import { createRequire as createRequire3 } from "node:module";
28126
- import { dirname as dirname6, join as join18 } from "node:path";
28320
+ import { dirname as dirname5, join as join16 } from "node:path";
28127
28321
  async function checks3() {
28128
28322
  const tools = [
28129
28323
  ["tesseract", "screenshot search"],
@@ -28144,7 +28338,7 @@ async function checks3() {
28144
28338
  }
28145
28339
  function installChromium() {
28146
28340
  const require2 = createRequire3(import.meta.url);
28147
- const cli = join18(dirname6(require2.resolve("playwright-core/package.json")), "cli.js");
28341
+ const cli = join16(dirname5(require2.resolve("playwright-core/package.json")), "cli.js");
28148
28342
  return new Promise((resolve, reject) => {
28149
28343
  const child = spawn7(process.execPath, [cli, "install", "chromium"], { stdio: "inherit" });
28150
28344
  child.on("close", (code) => code === 0 ? resolve() : reject(new Error("Installing Chromium failed")));
@@ -36679,7 +36873,7 @@ class StdioServerTransport {
36679
36873
  // package.json
36680
36874
  var package_default = {
36681
36875
  name: "@kaleidal/relikt",
36682
- version: "0.1.1",
36876
+ version: "0.1.3",
36683
36877
  description: "Preserve software before it is killed or redesigned: screenshots, flows, offline replays and the actual files.",
36684
36878
  keywords: [
36685
36879
  "archive",
@@ -36771,7 +36965,8 @@ function registerCaptureTools(server) {
36771
36965
  type: _enum(partTypes).optional().describe("Defaults to 'route' for websites and 'window' for desktop apps"),
36772
36966
  viewports: array(_enum(viewportNames)).optional().describe("Websites: mobile, laptop, wide. Desktop apps: narrow, laptop, wide."),
36773
36967
  themes: array(_enum(themes)).optional(),
36774
- cover: boolean2().optional().describe("Use this part as the exhibit's cover image")
36968
+ cover: boolean2().optional().describe("Use this part as the exhibit's cover image"),
36969
+ retake: boolean2().optional().describe("Replace the shots of the part already captured under this name. Without it, reusing a name is an error.")
36775
36970
  }
36776
36971
  }, async ({ cover, ...input }) => {
36777
36972
  const part = await requireCapturing().capture(input);
@@ -36890,6 +37085,7 @@ function registerExhibitTools(server) {
36890
37085
  reason: _enum(reasons),
36891
37086
  label: string2().optional().describe("Short label, e.g. 'before v2'. Defaults to the reason."),
36892
37087
  title: string2().optional(),
37088
+ date: exports_iso.date().optional().describe("The day this snapshot stands for, as yyyy-mm-dd. Defaults to today; for a project killed earlier, use the date of its last commit."),
36893
37089
  cwd: string2().describe("Absolute path of the project's repository")
36894
37090
  }
36895
37091
  }, async (input) => {
@@ -36923,7 +37119,7 @@ function registerExhibitTools(server) {
36923
37119
  return text("notes.md written");
36924
37120
  });
36925
37121
  server.registerTool("exhibit_finalize", {
36926
- description: "OCR every screenshot, deduplicate files into the archive's object store and, when signed in, upload the exhibit to relikt.dev.",
37122
+ description: "Check which routes work in the offline replay, OCR every screenshot, deduplicate files into the archive's object store and, when signed in, upload the exhibit to relikt.dev.",
36927
37123
  inputSchema: { upload: boolean2().default(true) }
36928
37124
  }, async ({ upload }) => {
36929
37125
  const exhibit = requireExhibit();
@@ -36931,13 +37127,15 @@ function registerExhibitTools(server) {
36931
37127
  throw new Error("A browser session is still running. Call web_finish first.");
36932
37128
  if (session.desktop)
36933
37129
  throw new Error("A desktop app is still running. Call desktop_finish first.");
37130
+ const replayable = exhibit.manifest.replay ? (await verifyReplay(exhibit)).length : 0;
36934
37131
  await recognize(exhibit);
37132
+ const replay = exhibit.manifest.replay ? ` ${replayable} routes work in the replay; the rest show screenshots.` : "";
36935
37133
  if (!upload) {
36936
37134
  await snapshotFiles(exhibit);
36937
- return text(`Finalized at ${exhibit.dir}`);
37135
+ return text(`Finalized at ${exhibit.dir}.${replay}`);
36938
37136
  }
36939
37137
  const result = await push(await Api.connect(), exhibit);
36940
- return text(`Finalized at ${exhibit.dir} and uploaded to ${result.url}`);
37138
+ return text(`Finalized at ${exhibit.dir} and uploaded to ${result.url}.${replay}`);
36941
37139
  });
36942
37140
  }
36943
37141
 
@@ -36953,11 +37151,12 @@ function registerWebTools(server) {
36953
37151
  description: "Open the locally running app in a recording browser. Every response is recorded for the replay. Run the app against seeded demo data, never a real account.",
36954
37152
  inputSchema: {
36955
37153
  url: string2().url().describe("Where the app runs locally, e.g. http://localhost:5173/"),
36956
- headed: boolean2().default(false)
37154
+ headed: boolean2().default(false),
37155
+ record: boolean2().default(true).describe("Record responses for the offline replay. Turn off to add screens to an exhibit whose replay is already built.")
36957
37156
  }
36958
- }, async ({ url, headed }) => {
37157
+ }, async ({ url, headed, record }) => {
36959
37158
  requireIdle();
36960
- session.web = await WebSession.launch(requireExhibit(), url, headed);
37159
+ session.web = await WebSession.launch(requireExhibit(), url, { headed, record });
36961
37160
  return snapshotResult();
36962
37161
  });
36963
37162
  server.registerTool("web_snapshot", { description: "Accessibility snapshot of the current page with [ref=…] handles." }, snapshotResult);
@@ -36967,9 +37166,7 @@ function registerWebTools(server) {
36967
37166
  return snapshotResult();
36968
37167
  });
36969
37168
  server.registerTool("web_click", { description: "Click an element by its snapshot ref.", inputSchema: { ref: string2() } }, async ({ ref }) => {
36970
- const web = requireWeb();
36971
- await web.locate(ref).click();
36972
- await web.afterAction();
37169
+ await requireWeb().click(ref);
36973
37170
  return snapshotResult();
36974
37171
  });
36975
37172
  server.registerTool("web_hover", { description: "Hover an element by its snapshot ref.", inputSchema: { ref: string2() } }, async ({ ref }) => {
@@ -37011,7 +37208,7 @@ function registerWebTools(server) {
37011
37208
  await web.finish();
37012
37209
  session.web = undefined;
37013
37210
  const replay = web.exhibit.manifest.replay;
37014
- return text(`Replay built with ${replay?.requests ?? 0} recorded requests`);
37211
+ return text(replay ? `Replay has ${replay.requests} recorded requests` : "Browser closed");
37015
37212
  });
37016
37213
  }
37017
37214
 
@@ -37019,7 +37216,7 @@ function registerWebTools(server) {
37019
37216
  var instructions = `Relikt preserves software as exhibits: systematic screenshots, flow videos, a clickable offline replay for websites, and the real artifacts, in a plain folder that outlives the project.
37020
37217
 
37021
37218
  To preserve a project:
37022
- 1. exhibit_create with the project's repository as cwd.
37219
+ 1. exhibit_create with the project's repository as cwd. If the project was killed or frozen before today, pass the date of its last commit.
37023
37220
  2. Run the app locally against seeded demo data (never a real account).
37024
37221
  3. Capture every part of it (see below for websites and desktop apps).
37025
37222
  4. Record flows for key interactions and anything animated with flow_start / flow_stop.
@@ -37030,7 +37227,7 @@ To preserve a project:
37030
37227
  Websites:
37031
37228
  - web_start with the app's local URL.
37032
37229
  - Build a complete route list: read the router or pages directory in the source, then web_discover_routes, and merge both.
37033
- - capture every route (path), then every dialog, menu, sheet and empty/error state reachable by interaction (type 'dialog', no path). Sign in through the app's own login screen so it is recorded too.
37230
+ - capture every route (path), then every dialog, menu, sheet and empty/error state reachable by interaction (type 'dialog', no path). Open each one by clicking from the screen it belongs to and capture it right away: that click becomes a clickable spot linking the two screenshots. Sign in through the app's own login screen so it is recorded too.
37034
37231
  - Click through everything a visitor would try, so the replay has the responses it needs. Then web_finish.
37035
37232
 
37036
37233
  Desktop apps (GTK, libadwaita, Qt, Flatpak, AppImage, Electron):
@@ -37068,10 +37265,10 @@ async function serveMcp() {
37068
37265
  // src/main.ts
37069
37266
  var help = `relikt ${version2}
37070
37267
 
37071
- relikt preserve <project> --reason <killed|redesign|milestone> [--label <text>] [--no-upload]
37268
+ relikt preserve <project> --reason <killed|redesign|milestone> [--label <text>] [--date <yyyy-mm-dd>] [--no-upload]
37072
37269
  [--kind web] --url <local url>
37073
37270
  --kind desktop --command <command that starts the app> [--electron]
37074
- relikt new <project> --kind <kind> --reason <reason> [--label <text>]
37271
+ relikt new <project> --kind <kind> --reason <reason> [--label <text>] [--date <yyyy-mm-dd>]
37075
37272
  relikt add <exhibit> <file...> [--target <text>] [--platform <name>] [--arch <name>]
37076
37273
  relikt list
37077
37274
  relikt replay [exhibit] [--port 4870]
@@ -37090,6 +37287,7 @@ var { values, positionals } = parseArgs({
37090
37287
  options: {
37091
37288
  reason: { type: "string" },
37092
37289
  label: { type: "string" },
37290
+ date: { type: "string" },
37093
37291
  kind: { type: "string" },
37094
37292
  url: { type: "string" },
37095
37293
  command: { type: "string" },
@@ -37116,6 +37314,7 @@ var commands = {
37116
37314
  reason: required2(values.reason, "--reason"),
37117
37315
  kind: values.kind ?? "web",
37118
37316
  label: values.label,
37317
+ date: values.date,
37119
37318
  url: values.url,
37120
37319
  command: values.command,
37121
37320
  electron: values.electron,
@@ -37124,7 +37323,8 @@ var commands = {
37124
37323
  new: () => newCommand(required2(rest[0], "<project>"), {
37125
37324
  kind: required2(values.kind, "--kind"),
37126
37325
  reason: required2(values.reason, "--reason"),
37127
- label: values.label
37326
+ label: values.label,
37327
+ date: values.date
37128
37328
  }),
37129
37329
  add: () => addCommand(required2(rest[0], "<exhibit>"), rest.slice(1), values),
37130
37330
  list: listCommand,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaleidal/relikt",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Preserve software before it is killed or redesigned: screenshots, flows, offline replays and the actual files.",
5
5
  "keywords": [
6
6
  "archive",