@pacspace-io/check 0.5.5 → 0.6.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 (29) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/README.md +36 -2
  3. package/dist/check.d.ts +6 -1
  4. package/dist/cli.d.ts +5 -1
  5. package/dist/cli.js +2496 -380
  6. package/dist/index.js +518 -91
  7. package/dist/inputs.txt +12 -0
  8. package/dist/open-io.d.ts +38 -0
  9. package/dist/open.d.ts +16 -15
  10. package/dist/records-crypto-types/records/flag-threads-v1.d.ts +53 -0
  11. package/dist/records-crypto-types/records/labels.d.ts +37 -0
  12. package/dist/records-crypto-types/records/link-handle-v1.d.ts +16 -0
  13. package/dist/records-crypto-types/records/reader-crypto-v1.d.ts +198 -0
  14. package/dist/records-crypto-types/records/reader-link-v1.d.ts +164 -0
  15. package/dist/records-crypto-types/records/shared-record-ack-v2.d.ts +72 -0
  16. package/dist/records-crypto-types/records/trail-index-v1.d.ts +89 -0
  17. package/dist/records-crypto-types/records/trail-rule.d.ts +54 -0
  18. package/dist/records-crypto-types/records-crypto/asymmetric/ack-flag-notes-v1.d.ts +57 -0
  19. package/dist/records-crypto-types/records-crypto/asymmetric/flag-notes-v1.d.ts +55 -0
  20. package/dist/records-crypto-types/records-crypto/asymmetric/index.d.ts +3 -0
  21. package/dist/records-crypto-types/records-crypto/asymmetric/reader-wraps-v1.d.ts +83 -0
  22. package/dist/records-crypto-types/records-crypto/disclosure-envelope-v1.d.ts +1 -1
  23. package/dist/records-crypto-types/records-crypto/index.d.ts +1 -1
  24. package/dist/records-crypto-types/records-crypto/records-encryption-v1.d.ts +1 -0
  25. package/dist/records-crypto.js +547 -66
  26. package/dist/report.d.ts +20 -1
  27. package/dist/shared-record-link.d.ts +121 -0
  28. package/dist/shared-record-words.d.ts +97 -0
  29. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -2097,16 +2097,10 @@ async function readRecordCopyV1(file) {
2097
2097
  }
2098
2098
 
2099
2099
  // ../shared/src/records/record-seal-history-v1.ts
2100
- var import_ethers13 = require("ethers");
2100
+ var import_ethers14 = require("ethers");
2101
2101
 
2102
2102
  // ../shared/src/demo/mirror-node-record-chain-reader.ts
2103
- var import_ethers12 = require("ethers");
2104
-
2105
- // ../shared/src/records/inspect-record-calldata-v1.ts
2106
- var MIRROR_NODE_BY_CHAIN = Object.freeze({
2107
- 296: "https://testnet.mirrornode.hedera.com",
2108
- 295: "https://mainnet-public.mirrornode.hedera.com"
2109
- });
2103
+ var import_ethers13 = require("ethers");
2110
2104
 
2111
2105
  // ../shared/src/records/ledger-write-search-v1.ts
2112
2106
  var LEDGER_WRITE_SEARCH_WINDOW_LIMIT_SECONDS = 7 * 24 * 60 * 60;
@@ -2116,7 +2110,15 @@ var HEX40 = /^0x[0-9a-f]{40}$/;
2116
2110
  var HEX642 = /^0x[0-9a-f]{64}$/;
2117
2111
  var HEX_DATA = /^0x[0-9a-f]*$/;
2118
2112
  var TIMESTAMP = /^\d+(\.\d+)?$/;
2119
- var REFUSAL_CODES = ["redirect", "too-large", "too-many-logs", "next-page"];
2113
+ var REFUSAL_CODES = {
2114
+ redirect: true,
2115
+ "too-large": true,
2116
+ "too-many-logs": true,
2117
+ "next-page": true,
2118
+ "too-slow": true,
2119
+ "too-long": true
2120
+ };
2121
+ var MIRROR_REFUSAL_CODES = Object.keys(REFUSAL_CODES);
2120
2122
  var MirrorAnswerRefused = class extends Error {
2121
2123
  constructor(code, message) {
2122
2124
  super(message);
@@ -2127,7 +2129,7 @@ var MirrorAnswerRefused = class extends Error {
2127
2129
  function mirrorRefusalOf(error) {
2128
2130
  if (!error || typeof error !== "object") return null;
2129
2131
  const { name, code } = error;
2130
- return name === "MirrorAnswerRefused" && typeof code === "string" && REFUSAL_CODES.includes(code) ? code : null;
2132
+ return name === "MirrorAnswerRefused" && typeof code === "string" && Object.prototype.hasOwnProperty.call(REFUSAL_CODES, code) ? code : null;
2131
2133
  }
2132
2134
  function pathLabel(path) {
2133
2135
  return path ? ` (${path.split("?")[0]})` : "";
@@ -2136,8 +2138,24 @@ var mirrorRefusal = {
2136
2138
  redirect: (path) => new MirrorAnswerRefused("redirect", `mirror node answered with a redirect, which is not followed${pathLabel(path)}`),
2137
2139
  tooLarge: (maxBytes, path) => new MirrorAnswerRefused("too-large", `mirror node answer is larger than ${maxBytes} bytes${pathLabel(path)}`),
2138
2140
  tooManyLogs: (asked, path) => new MirrorAnswerRefused("too-many-logs", `mirror node returned more logs than the ${asked} asked for${pathLabel(path)}`),
2139
- nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log")
2141
+ nextPage: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that is not this contract's log"),
2142
+ /** A page whose logs do not come after the last log read. */
2143
+ notForward: () => new MirrorAnswerRefused("next-page", "mirror node gave a next page that does not follow the last"),
2144
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `mirror node log scan did not finish in ${budgetMs}ms`),
2145
+ scanTooManyRequests: (requests) => new MirrorAnswerRefused("too-long", `mirror node log scan passed ${requests} requests`),
2146
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `mirror node log scan kept more than ${logs} logs`)
2140
2147
  };
2148
+ var rpcRefusal = {
2149
+ redirect: () => new MirrorAnswerRefused("redirect", "RPC endpoint answered with a redirect, which is not followed"),
2150
+ tooLarge: (maxBytes) => new MirrorAnswerRefused("too-large", `RPC endpoint answer is larger than ${maxBytes} bytes`),
2151
+ scanTooSlow: (budgetMs) => new MirrorAnswerRefused("too-slow", `RPC log scan did not finish in ${budgetMs}ms`),
2152
+ scanTooManyLogs: (logs) => new MirrorAnswerRefused("too-long", `RPC log scan kept more than ${logs} logs`)
2153
+ };
2154
+ var LOG_SCAN_BUDGET_TIMEOUTS = 60;
2155
+ var LOG_SCAN_MAX_REQUESTS = 1e4;
2156
+ var LOG_SCAN_MAX_KEPT_LOGS = 1e6;
2157
+ var KEPT_LOG_DATA_MAX_CHARS = 2 + 64 * 3;
2158
+ var KEPT_LOG_MAX_TOPICS = 3;
2141
2159
  function isMirrorRedirect(response) {
2142
2160
  return response.redirected === true || response.type === "opaqueredirect" || response.status >= 300 && response.status < 400;
2143
2161
  }
@@ -2252,7 +2270,16 @@ function parseLedgerWriteLog(log, expected) {
2252
2270
  };
2253
2271
  }
2254
2272
 
2273
+ // ../shared/src/records/inspect-record-calldata-v1.ts
2274
+ var MIRROR_NODE_BY_CHAIN = Object.freeze({
2275
+ 296: "https://testnet.mirrornode.hedera.com",
2276
+ 295: "https://mainnet-public.mirrornode.hedera.com"
2277
+ });
2278
+
2255
2279
  // ../shared/src/demo/independent-verify-records.ts
2280
+ var import_ethers12 = require("ethers");
2281
+
2282
+ // ../shared/src/chain/rpc-guarded-send.ts
2256
2283
  var import_ethers11 = require("ethers");
2257
2284
 
2258
2285
  // ../shared/src/chain/rpc-provider.ts
@@ -2262,7 +2289,7 @@ var MIN_SECRET_LENGTH = 8;
2262
2289
  var URL_IN_TEXT = /[a-z][a-z0-9+.-]*:\/\/[^\s"'<>\\`]+/gi;
2263
2290
  var RAW_SEPARATORS = /[/?&=#;@:]/;
2264
2291
  var ETHERS_ERROR_EXTRA_FIELDS = ["operation", "reason", "event"];
2265
- function normalizeRpcUrl(value) {
2292
+ function rpcHttpUrl(value) {
2266
2293
  const trimmed = value.trim();
2267
2294
  if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
2268
2295
  if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
@@ -2270,7 +2297,7 @@ function normalizeRpcUrl(value) {
2270
2297
  }
2271
2298
  function rpcEndpointLabel(value) {
2272
2299
  try {
2273
- return new URL(normalizeRpcUrl(value)).hostname.toLowerCase();
2300
+ return new URL(rpcHttpUrl(value)).hostname.toLowerCase();
2274
2301
  } catch {
2275
2302
  return "unparseable-rpc-endpoint";
2276
2303
  }
@@ -2369,14 +2396,124 @@ function redactRpcError(error, secrets) {
2369
2396
  }
2370
2397
  return new Error(cleanText(String(error), secrets));
2371
2398
  }
2399
+ var RpcResultUnavailableError = class extends Error {
2400
+ constructor(what, reason) {
2401
+ super(`${what} from the RPC is incomplete: ${reason}`);
2402
+ this.code = "RPC_RESULT_UNAVAILABLE";
2403
+ this.name = "RpcResultUnavailableError";
2404
+ }
2405
+ };
2406
+ var HEX_QUANTITY = /^0x[0-9a-f]+$/i;
2407
+ function parseRpcQuantity(value, what) {
2408
+ if (typeof value !== "string" || !HEX_QUANTITY.test(value)) {
2409
+ throw new RpcResultUnavailableError(what, "not a hex quantity");
2410
+ }
2411
+ return BigInt(value);
2412
+ }
2413
+ var QUANTITY_RESULTS = {
2414
+ getBlockNumber: "eth_blockNumber",
2415
+ getTransactionCount: "eth_getTransactionCount",
2416
+ getBalance: "eth_getBalance",
2417
+ getGasPrice: "eth_gasPrice",
2418
+ getPriorityFee: "eth_maxPriorityFeePerGas",
2419
+ estimateGas: "eth_estimateGas"
2420
+ };
2421
+ function incompleteReason(error) {
2422
+ const short = String(error?.shortMessage ?? error?.message ?? error);
2423
+ const field = /^invalid value for value\.(\w+) \(([^(]*)/.exec(short);
2424
+ return field ? `${field[1]}: ${field[2].trim()}` : short.split(" (")[0];
2425
+ }
2426
+ function formatted(what, format) {
2427
+ try {
2428
+ return format();
2429
+ } catch (error) {
2430
+ throw new RpcResultUnavailableError(what, incompleteReason(error));
2431
+ }
2432
+ }
2433
+ var SUBSCRIBE_METHODS = /* @__PURE__ */ new Set(["eth_subscribe", "eth_newFilter"]);
2434
+ var UNSUBSCRIBE_METHODS = /* @__PURE__ */ new Set(["eth_unsubscribe", "eth_uninstallFilter"]);
2435
+ var SUBSCRIBE_RETRY_BASE_MS = 1e3;
2436
+ var SUBSCRIBE_RETRY_MAX_MS = 6e4;
2437
+ var REJECTION_MESSAGE_MAX = 300;
2438
+ function rejectionMessage(error, secrets) {
2439
+ const inner = error?.error?.message;
2440
+ let text;
2441
+ if (typeof inner === "string") text = inner;
2442
+ else if (isEthersError(error)) text = error.shortMessage;
2443
+ else if (isErrorLike(error)) text = error.message;
2444
+ else text = String(error);
2445
+ return cleanText(text, secrets).slice(0, REJECTION_MESSAGE_MAX);
2446
+ }
2447
+ function pause(ms) {
2448
+ return new Promise((resolve3) => {
2449
+ const timer = setTimeout(resolve3, ms);
2450
+ timer.unref?.();
2451
+ });
2452
+ }
2453
+ async function guardSubscriptionSend(method, send, provider, retry, secrets) {
2454
+ const report = (rejection) => {
2455
+ try {
2456
+ retry.onRejected?.(rejection);
2457
+ } catch {
2458
+ }
2459
+ };
2460
+ if (UNSUBSCRIBE_METHODS.has(method)) {
2461
+ try {
2462
+ return await send();
2463
+ } catch (error) {
2464
+ report({ method, attempt: 1, retryInMs: null, message: rejectionMessage(error, secrets) });
2465
+ return false;
2466
+ }
2467
+ }
2468
+ if (!SUBSCRIBE_METHODS.has(method)) return send();
2469
+ const base = retry.baseDelayMs ?? SUBSCRIBE_RETRY_BASE_MS;
2470
+ const max = retry.maxDelayMs ?? SUBSCRIBE_RETRY_MAX_MS;
2471
+ for (let attempt = 1; ; attempt += 1) {
2472
+ try {
2473
+ return await send();
2474
+ } catch (error) {
2475
+ if (provider.destroyed) return new Promise(() => void 0);
2476
+ const retryInMs = Math.min(base * 2 ** (attempt - 1), max);
2477
+ report({ method, attempt, retryInMs, message: rejectionMessage(error, secrets) });
2478
+ await pause(retryInMs);
2479
+ if (provider.destroyed) return new Promise(() => void 0);
2480
+ }
2481
+ }
2482
+ }
2483
+ function requestFor(url, options) {
2484
+ const request = new import_ethers10.FetchRequest(url);
2485
+ if (options.timeoutMs !== void 0) request.timeout = options.timeoutMs;
2486
+ options.prepareRequest?.(request);
2487
+ return request;
2488
+ }
2489
+ var CHAIN_ID_RESULT = /^0x[0-9a-f]{1,13}$/i;
2490
+ async function readRpcChainId(url, options = {}) {
2491
+ const secrets = rpcUrlSecrets(url);
2492
+ try {
2493
+ const request = requestFor(url, options);
2494
+ request.body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_chainId", params: [] });
2495
+ request.setHeader("content-type", "application/json");
2496
+ const response = await request.send();
2497
+ response.assertOk();
2498
+ const answer = response.bodyJson;
2499
+ const result = answer !== null && typeof answer === "object" ? answer.result : void 0;
2500
+ if (typeof result !== "string" || !CHAIN_ID_RESULT.test(result)) throw new RpcResultUnavailableError("eth_chainId", "not a chain id");
2501
+ return Number.parseInt(result, 16);
2502
+ } catch (error) {
2503
+ throw redactRpcError(error, secrets);
2504
+ }
2505
+ }
2372
2506
  var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
2373
2507
  #secrets;
2508
+ #subscriptionRetry;
2374
2509
  constructor(url, network, options) {
2375
- const { timeoutMs, ...providerOptions } = options;
2376
- const request = new import_ethers10.FetchRequest(url);
2377
- if (timeoutMs !== void 0) request.timeout = timeoutMs;
2378
- super(request, network, providerOptions);
2510
+ const { timeoutMs, subscriptionRetry, prepareRequest, ...providerOptions } = options;
2511
+ super(requestFor(url, { timeoutMs, prepareRequest }), network, providerOptions);
2379
2512
  this.#secrets = rpcUrlSecrets(url);
2513
+ this.#subscriptionRetry = subscriptionRetry ?? {};
2514
+ }
2515
+ send(method, params) {
2516
+ return guardSubscriptionSend(method, () => super.send(method, params), this, this.#subscriptionRetry, this.#secrets);
2380
2517
  }
2381
2518
  async _send(payload) {
2382
2519
  try {
@@ -2385,11 +2522,123 @@ var RedactingJsonRpcProvider = class extends import_ethers10.JsonRpcProvider {
2385
2522
  throw redactRpcError(error, this.#secrets);
2386
2523
  }
2387
2524
  }
2525
+ async _perform(req) {
2526
+ const result = await super._perform(req);
2527
+ const method = QUANTITY_RESULTS[req.method];
2528
+ if (method) parseRpcQuantity(result, method);
2529
+ return result;
2530
+ }
2531
+ _wrapTransactionResponse(tx, network) {
2532
+ return formatted("transaction", () => super._wrapTransactionResponse(tx, network));
2533
+ }
2534
+ _wrapTransactionReceipt(value, network) {
2535
+ return formatted("transaction receipt", () => super._wrapTransactionReceipt(value, network));
2536
+ }
2537
+ _wrapBlock(value, network) {
2538
+ return formatted("block", () => super._wrapBlock(value, network));
2539
+ }
2540
+ _wrapLog(value, network) {
2541
+ return formatted("log", () => super._wrapLog(value, network));
2542
+ }
2388
2543
  };
2389
2544
  function createRpcProvider(url, network, options = {}) {
2390
2545
  return new RedactingJsonRpcProvider(url, network, options);
2391
2546
  }
2392
2547
 
2548
+ // ../shared/src/chain/rpc-guarded-send.ts
2549
+ var RPC_READER_MAX_TRIES = 3;
2550
+ function basicAuthorization(username, password) {
2551
+ const decoded = (value) => {
2552
+ try {
2553
+ return decodeURIComponent(value);
2554
+ } catch {
2555
+ return value;
2556
+ }
2557
+ };
2558
+ const bytes2 = new TextEncoder().encode(`${decoded(username)}:${decoded(password)}`);
2559
+ let binary = "";
2560
+ for (const byte of bytes2) binary += String.fromCharCode(byte);
2561
+ return `Basic ${btoa(binary)}`;
2562
+ }
2563
+ function createGuardedRpcSend(options = {}) {
2564
+ const maxBytes = options.maxBytes ?? MIRROR_ANSWER_MAX_BYTES;
2565
+ return async (req, signal) => {
2566
+ if (signal?.cancelled) throw (0, import_ethers11.makeError)("request cancelled before sending", "CANCELLED");
2567
+ const fetchImpl = options.fetchImpl ?? fetch;
2568
+ const secrets = rpcUrlSecrets(req.url);
2569
+ const url = new URL(req.url);
2570
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2571
+ throw (0, import_ethers11.makeError)(`unsupported protocol ${url.protocol.replace(/:$/, "")}`, "UNSUPPORTED_OPERATION", { operation: "request" });
2572
+ }
2573
+ const headers = {};
2574
+ for (const [name, value] of Object.entries(req.headers)) {
2575
+ const lower = name.toLowerCase();
2576
+ if (lower === "content-length" || lower === "accept-encoding") continue;
2577
+ headers[lower] = value;
2578
+ }
2579
+ if (url.username !== "" || url.password !== "") {
2580
+ if (headers.authorization === void 0) headers.authorization = basicAuthorization(url.username, url.password);
2581
+ url.username = "";
2582
+ url.password = "";
2583
+ }
2584
+ const controller = new AbortController();
2585
+ let timedOut = false;
2586
+ const timer = setTimeout(() => {
2587
+ timedOut = true;
2588
+ controller.abort();
2589
+ }, req.timeout);
2590
+ let cancelled = false;
2591
+ signal?.addListener(() => {
2592
+ cancelled = true;
2593
+ controller.abort();
2594
+ });
2595
+ try {
2596
+ const body = req.body;
2597
+ const response = await fetchImpl(url.toString(), {
2598
+ method: req.method,
2599
+ headers,
2600
+ ...body ? { body } : {},
2601
+ redirect: "manual",
2602
+ signal: controller.signal
2603
+ });
2604
+ if (isMirrorRedirect(response)) {
2605
+ await response.body?.cancel?.().catch(() => void 0);
2606
+ throw rpcRefusal.redirect();
2607
+ }
2608
+ let text;
2609
+ try {
2610
+ text = await readMirrorText(response, maxBytes);
2611
+ } catch (error) {
2612
+ if (mirrorRefusalOf(error) === "too-large") throw rpcRefusal.tooLarge(maxBytes);
2613
+ throw error;
2614
+ }
2615
+ const answered = {};
2616
+ response.headers.forEach((value, name) => {
2617
+ answered[name.toLowerCase()] = value;
2618
+ });
2619
+ return { statusCode: response.status, statusMessage: response.statusText, headers: answered, body: new TextEncoder().encode(replaceRpcSecrets(text, secrets)) };
2620
+ } catch (error) {
2621
+ if (mirrorRefusalOf(error)) throw error;
2622
+ if (cancelled) throw (0, import_ethers11.makeError)("request cancelled", "CANCELLED");
2623
+ if (timedOut) throw (0, import_ethers11.makeError)("request timeout", "TIMEOUT", { operation: "request.send", reason: "timeout" });
2624
+ throw error;
2625
+ } finally {
2626
+ clearTimeout(timer);
2627
+ }
2628
+ };
2629
+ }
2630
+ function retryAfterMs(value) {
2631
+ return typeof value === "string" && /^[1-9][0-9]*$/.test(value) ? Number.parseInt(value, 10) : null;
2632
+ }
2633
+ function holdRpcRequest(request, options = {}) {
2634
+ request.getUrlFunc = createGuardedRpcSend(options);
2635
+ request.retryFunc = async (req, response, attempt) => {
2636
+ if (attempt >= RPC_READER_MAX_TRIES - 1) return false;
2637
+ const wait = retryAfterMs(response.headers["retry-after"]);
2638
+ return wait === null || wait <= req.timeout;
2639
+ };
2640
+ }
2641
+
2393
2642
  // ../shared/src/demo/independent-verify-records.ts
2394
2643
  var RECORD_LANE_ABI_V38 = [
2395
2644
  "function getRecord(bytes32 recordKey) view returns (uint256)",
@@ -2401,23 +2650,25 @@ var RECORD_LANE_ABI_V38 = [
2401
2650
  "event RecordWritten(bytes32 indexed recordKey, address indexed operator, uint8 encodingVersion, uint256 previousWord, uint256 newWord)",
2402
2651
  "event LedgerHeadAdvanced(uint256 indexed batchId, bytes32 merkleRoot, bytes32 previousHead, bytes32 newHead)"
2403
2652
  ];
2404
- var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers11.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
2405
- var RECORD_WRITTEN_TOPIC = import_ethers11.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
2653
+ var LEDGER_HEAD_ADVANCED_TOPIC = import_ethers12.ethers.id("LedgerHeadAdvanced(uint256,bytes32,bytes32,bytes32)");
2654
+ var RECORD_WRITTEN_TOPIC = import_ethers12.ethers.id("RecordWritten(bytes32,address,uint8,uint256,uint256)");
2406
2655
  var LAYOUT_NOT_REGISTERED = "layout-not-registered";
2407
2656
  function checkLayoutOnChain(onChainLayout, published) {
2408
2657
  const matchesPublished = !!published && onChainLayout.registered && onChainLayout.layoutDigest === published.digest;
2409
2658
  return { ...onChainLayout, matchesPublished, failure: matchesPublished ? null : LAYOUT_NOT_REGISTERED };
2410
2659
  }
2411
- function normalizeRpcUrl2(url) {
2660
+ function normalizeRpcUrl(url) {
2412
2661
  const trimmed = String(url || "").trim();
2413
2662
  if (trimmed.startsWith("wss://")) return trimmed.replace(/^wss:\/\//, "https://");
2414
2663
  if (trimmed.startsWith("ws://")) return trimmed.replace(/^ws:\/\//, "http://");
2415
2664
  return trimmed;
2416
2665
  }
2666
+ var ReadTimedOut = class extends Error {
2667
+ };
2417
2668
  async function withTimeout(p, ms, label) {
2418
2669
  let timer;
2419
2670
  const timeout = new Promise((_, reject) => {
2420
- timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
2671
+ timer = setTimeout(() => reject(new ReadTimedOut(`${label} timed out after ${ms}ms`)), ms);
2421
2672
  });
2422
2673
  try {
2423
2674
  return await Promise.race([p, timeout]);
@@ -2426,26 +2677,73 @@ async function withTimeout(p, ms, label) {
2426
2677
  }
2427
2678
  }
2428
2679
  function createRpcRecordChainReader(options) {
2429
- const rpcUrl = normalizeRpcUrl2(options.rpcUrl);
2680
+ const rpcUrl = normalizeRpcUrl(options.rpcUrl);
2430
2681
  if (!rpcUrl) throw new Error("rpcUrl is required.");
2431
- const contractAddress = import_ethers11.ethers.getAddress(options.contractAddress).toLowerCase();
2682
+ const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
2432
2683
  const timeoutMs = Number(options.timeoutMs || 1e4);
2433
2684
  const chunk = Math.max(1, Number(options.logsChunkSize || 2e3));
2434
- const network = options.chainId != null ? new import_ethers11.ethers.Network(`chain-${options.chainId}`, options.chainId) : void 0;
2435
- const provider = network ? createRpcProvider(rpcUrl, network, { staticNetwork: network }) : createRpcProvider(rpcUrl);
2436
- const contract = new import_ethers11.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider);
2437
- const iface = new import_ethers11.ethers.Interface(RECORD_LANE_ABI_V38);
2685
+ const now = options.scan?.now ?? Date.now;
2686
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
2687
+ const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2688
+ const prepareRequest = (request) => holdRpcRequest(request);
2689
+ const endpointFor = (chainId) => {
2690
+ const network = new import_ethers12.ethers.Network(`chain-${chainId}`, chainId);
2691
+ const provider = createRpcProvider(rpcUrl, network, { staticNetwork: network, timeoutMs, prepareRequest });
2692
+ return { provider, contract: new import_ethers12.ethers.Contract(contractAddress, RECORD_LANE_ABI_V38, provider) };
2693
+ };
2694
+ let ready = options.chainId != null ? Promise.resolve(endpointFor(options.chainId)) : null;
2695
+ function endpoint() {
2696
+ if (!ready) {
2697
+ const pending = readRpcChainId(rpcUrl, { timeoutMs, prepareRequest }).then(endpointFor);
2698
+ ready = pending;
2699
+ pending.catch(() => {
2700
+ if (ready === pending) ready = null;
2701
+ });
2702
+ }
2703
+ return ready;
2704
+ }
2705
+ function keptLog(log, topic0) {
2706
+ return String(log.address).toLowerCase() === contractAddress && log.topics.length <= KEPT_LOG_MAX_TOPICS && String(log.topics[0] ?? "").toLowerCase() === topic0 && typeof log.data === "string" && log.data.length <= KEPT_LOG_DATA_MAX_CHARS;
2707
+ }
2438
2708
  async function scanLogs(topics, fromBlock, toBlock, label) {
2439
- const latest = toBlock === "latest" ? await withTimeout(provider.getBlockNumber(), timeoutMs, "getBlockNumber") : toBlock;
2709
+ const { provider } = await endpoint();
2710
+ const budgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
2711
+ const deadline = now() + budgetMs;
2712
+ const topic0 = String(topics[0] ?? "").toLowerCase();
2713
+ const ask = async (send, what) => {
2714
+ const left = deadline - now();
2715
+ if (left <= 0) throw rpcRefusal.scanTooSlow(budgetMs);
2716
+ const allowed = Math.min(timeoutMs, left);
2717
+ try {
2718
+ return await withTimeout(send(), allowed, what);
2719
+ } catch (error) {
2720
+ if (error instanceof ReadTimedOut && allowed < timeoutMs) throw rpcRefusal.scanTooSlow(budgetMs);
2721
+ if (!mirrorRefusalOf(error) && now() >= deadline) throw rpcRefusal.scanTooSlow(budgetMs);
2722
+ throw error;
2723
+ }
2724
+ };
2725
+ const latest = toBlock === "latest" ? await ask(() => provider.getBlockNumber(), "getBlockNumber") : toBlock;
2440
2726
  const out = [];
2727
+ const pending = [];
2441
2728
  for (let start = fromBlock; start <= latest; start += chunk) {
2442
- const end = Math.min(latest, start + chunk - 1);
2443
- const logs = await withTimeout(
2444
- provider.getLogs({ address: contractAddress, topics, fromBlock: start, toBlock: end }),
2445
- timeoutMs,
2446
- `getLogs ${label} (${start}-${end})`
2447
- );
2448
- out.push(...logs);
2729
+ pending.push([start, Math.min(latest, start + chunk - 1)]);
2730
+ while (pending.length > 0) {
2731
+ const [from, to] = pending.pop();
2732
+ let logs;
2733
+ try {
2734
+ logs = await ask(() => provider.getLogs({ address: contractAddress, topics, fromBlock: from, toBlock: to }), `getLogs ${label} (${from}-${to})`);
2735
+ } catch (error) {
2736
+ if (mirrorRefusalOf(error) !== "too-large" || from >= to) throw error;
2737
+ const middle = from + Math.floor((to - from) / 2);
2738
+ pending.push([middle + 1, to], [from, middle]);
2739
+ continue;
2740
+ }
2741
+ for (const log of logs) {
2742
+ if (!keptLog(log, topic0)) continue;
2743
+ if (out.length >= maxKeptLogs) throw rpcRefusal.scanTooManyLogs(maxKeptLogs);
2744
+ out.push(log);
2745
+ }
2746
+ }
2449
2747
  }
2450
2748
  return out;
2451
2749
  }
@@ -2453,10 +2751,12 @@ function createRpcRecordChainReader(options) {
2453
2751
  contractAddress,
2454
2752
  async getRecord(recordKey) {
2455
2753
  const key = normalizeProofHash(recordKey, "recordKey");
2754
+ const { contract } = await endpoint();
2456
2755
  const word = await withTimeout(contract.getRecord(key), timeoutMs, "getRecord");
2457
2756
  return hex256(BigInt(word));
2458
2757
  },
2459
2758
  async getLayout(layoutId) {
2759
+ const { contract } = await endpoint();
2460
2760
  const l = await withTimeout(contract.getLayout(layoutId), timeoutMs, "getLayout");
2461
2761
  return {
2462
2762
  layoutDigest: String(l[0]).toLowerCase(),
@@ -2466,10 +2766,12 @@ function createRpcRecordChainReader(options) {
2466
2766
  };
2467
2767
  },
2468
2768
  async getBatchRoot(batchId) {
2769
+ const { contract } = await endpoint();
2469
2770
  const root = await withTimeout(contract.getBatchRoot(BigInt(batchId)), timeoutMs, "getBatchRoot");
2470
2771
  return normalizeProofHash(String(root), "observedProofRoot");
2471
2772
  },
2472
2773
  async getLedgerHead() {
2774
+ const { contract } = await endpoint();
2473
2775
  const head = await withTimeout(contract.getLedgerHead(), timeoutMs, "getLedgerHead");
2474
2776
  return normalizeProofHash(String(head), "ledgerHead");
2475
2777
  },
@@ -2512,14 +2814,18 @@ function createRpcRecordChainReader(options) {
2512
2814
  },
2513
2815
  async findRecordWrites(recordKey, search) {
2514
2816
  const key = normalizeProofHash(recordKey, "recordKey");
2515
- const now = search.now ?? Date.now;
2516
- const deadline = now() + search.budgetMs;
2817
+ const now2 = search.now ?? Date.now;
2818
+ const deadline = now2() + search.budgetMs;
2517
2819
  const writes = [];
2518
2820
  const blockTimes = /* @__PURE__ */ new Map();
2519
2821
  let requests = 0;
2822
+ const asked = () => {
2823
+ requests += 1;
2824
+ search.onRequest?.();
2825
+ };
2520
2826
  const CUT = Symbol("cut");
2521
2827
  const within2 = async (p) => {
2522
- const left = deadline - now();
2828
+ const left = deadline - now2();
2523
2829
  if (left <= 0) return CUT;
2524
2830
  let timer;
2525
2831
  const cut = new Promise((resolve3) => {
@@ -2534,13 +2840,16 @@ function createRpcRecordChainReader(options) {
2534
2840
  };
2535
2841
  const end = (ended) => ({ writes, ended, requests });
2536
2842
  if (search.maxRequests < 1) return end("limit");
2537
- requests += 1;
2843
+ const found = await within2(endpoint());
2844
+ if (found === CUT) return end("timeout");
2845
+ const { provider } = found;
2846
+ asked();
2538
2847
  const latest = await within2(provider.getBlockNumber());
2539
2848
  if (latest === CUT) return end("timeout");
2540
2849
  for (let to = latest; to >= 0; to -= chunk) {
2541
2850
  if (search.done(writes)) return end("done");
2542
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2543
- requests += 1;
2851
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
2852
+ asked();
2544
2853
  const logs = await within2(provider.getLogs({ address: contractAddress, topics: [RECORD_WRITTEN_TOPIC, key], fromBlock: Math.max(0, to - chunk + 1), toBlock: to }));
2545
2854
  if (logs === CUT) return end("timeout");
2546
2855
  for (const log of [...logs].reverse()) {
@@ -2548,8 +2857,8 @@ function createRpcRecordChainReader(options) {
2548
2857
  if (!parsed) continue;
2549
2858
  let committedAt = blockTimes.get(log.blockNumber);
2550
2859
  if (committedAt === void 0) {
2551
- if (requests >= search.maxRequests || now() >= deadline) return end("limit");
2552
- requests += 1;
2860
+ if (requests >= search.maxRequests || now2() >= deadline) return end("limit");
2861
+ asked();
2553
2862
  const block = await within2(provider.getBlock(log.blockNumber));
2554
2863
  if (block === CUT) return end("timeout");
2555
2864
  if (!block || !Number.isSafeInteger(block.timestamp)) throw new Error(`getBlock ${log.blockNumber} returned no time`);
@@ -2593,7 +2902,7 @@ async function readLedgerMaterial(reader, log, options) {
2593
2902
  log,
2594
2903
  `eth_getLogs LedgerHeadAdvanced from block ${options.fromBlock ?? 0}`
2595
2904
  );
2596
- const genesisHead = options.genesisHead ?? (advances[0]?.previousHead ?? import_ethers11.ethers.ZeroHash);
2905
+ const genesisHead = options.genesisHead ?? (advances[0]?.previousHead ?? import_ethers12.ethers.ZeroHash);
2597
2906
  return {
2598
2907
  genesisHead,
2599
2908
  batches: advances.map((a) => ({ batchId: a.batchId, merkleRoot: a.merkleRoot })),
@@ -2658,13 +2967,42 @@ function committedAtOf(timestamp) {
2658
2967
  const [seconds, fraction] = timestamp.split(".");
2659
2968
  return new Date(Number(seconds) * 1e3 + Number(fraction.slice(0, 3))).toISOString();
2660
2969
  }
2970
+ var SearchLimited = class {
2971
+ constructor(retryAfterMs2) {
2972
+ this.retryAfterMs = retryAfterMs2;
2973
+ }
2974
+ };
2975
+ function retryAfterMsOf(response) {
2976
+ const value = response.headers?.get?.("retry-after");
2977
+ return typeof value === "string" && /^\d{1,6}$/.test(value.trim()) ? Number(value.trim()) * 1e3 : null;
2978
+ }
2661
2979
  var KEPT_TOPICS = [RECORD_WRITTEN_TOPIC.toLowerCase(), LEDGER_HEAD_ADVANCED_TOPIC.toLowerCase()];
2662
- function keptMirrorLog(raw) {
2980
+ var HEX_DATA2 = /^0x[0-9a-fA-F]*$/;
2981
+ function mirrorLogPosition(raw) {
2982
+ if (!raw || typeof raw !== "object") return null;
2983
+ const { timestamp, index } = raw;
2984
+ if (typeof timestamp !== "string" || !CONSENSUS_TIMESTAMP.test(timestamp)) return null;
2985
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
2986
+ const [seconds, fraction] = timestamp.split(".");
2987
+ return { nanos: BigInt(seconds) * 1000000000n + BigInt(fraction), index };
2988
+ }
2989
+ function mirrorLogFollows(last, next) {
2990
+ return last === null || next.nanos > last.nanos || next.nanos === last.nanos && next.index > last.index;
2991
+ }
2992
+ function keptMirrorLog(raw, contract) {
2663
2993
  if (!raw || typeof raw !== "object") return null;
2664
2994
  const log = raw;
2665
2995
  if (!Array.isArray(log.topics) || typeof log.data !== "string") return null;
2996
+ if (log.topics.length > KEPT_LOG_MAX_TOPICS || log.data.length > KEPT_LOG_DATA_MAX_CHARS || !HEX_DATA2.test(log.data)) return null;
2666
2997
  const topics = log.topics.map((topic) => String(topic));
2667
2998
  if (!KEPT_TOPICS.includes((topics[0] ?? "").toLowerCase())) return null;
2999
+ if (topics.some((topic) => topic.length > 66)) return null;
3000
+ if (contract !== void 0) {
3001
+ if (typeof log.address !== "string" || log.address.toLowerCase() !== contract) return null;
3002
+ if (!mirrorLogPosition(raw)) return null;
3003
+ if (typeof log.block_number !== "number" || !Number.isSafeInteger(log.block_number)) return null;
3004
+ if (typeof log.transaction_hash !== "string" || log.transaction_hash.length > 98) return null;
3005
+ }
2668
3006
  return {
2669
3007
  address: log.address,
2670
3008
  data: log.data,
@@ -2679,18 +3017,25 @@ function createMirrorNodeRecordChainReader(options) {
2679
3017
  const chainId = options.chainId ?? 296;
2680
3018
  const base = (options.mirrorBaseUrl ?? MIRROR_NODE_BY_CHAIN[chainId] ?? "").replace(/\/+$/, "");
2681
3019
  if (!base) throw new Error(`No mirror node known for chain ${chainId}; pass mirrorBaseUrl.`);
2682
- const contractAddress = import_ethers12.ethers.getAddress(options.contractAddress).toLowerCase();
3020
+ const contractAddress = import_ethers13.ethers.getAddress(options.contractAddress).toLowerCase();
2683
3021
  const timeoutMs = Number(options.timeoutMs || 1e4);
2684
3022
  const pageSize = Math.min(100, Math.max(1, Number(options.pageSize || 100)));
2685
3023
  const attempts = Math.max(1, options.attempts ?? 3);
2686
3024
  const fetchImpl = options.fetchImpl ?? fetch;
2687
- const iface = new import_ethers12.ethers.Interface(RECORD_LANE_ABI_V38);
2688
- async function request(path, init) {
3025
+ const iface = new import_ethers13.ethers.Interface(RECORD_LANE_ABI_V38);
3026
+ const now = options.scan?.now ?? Date.now;
3027
+ const maxScanRequests = options.scan?.maxRequests ?? LOG_SCAN_MAX_REQUESTS;
3028
+ const maxKeptLogs = options.scan?.maxKeptLogs ?? LOG_SCAN_MAX_KEPT_LOGS;
3029
+ const scanBudgetMs = LOG_SCAN_BUDGET_TIMEOUTS * timeoutMs;
3030
+ async function request(path, init, deadline) {
2689
3031
  const url = `${base}${path}`;
2690
3032
  let lastError = null;
2691
3033
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
3034
+ const left = deadline === void 0 ? timeoutMs : deadline - now();
3035
+ if (left <= 0) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
3036
+ const allowed = Math.min(timeoutMs, left);
2692
3037
  const controller = new AbortController();
2693
- const timer = setTimeout(() => controller.abort(), timeoutMs);
3038
+ const timer = setTimeout(() => controller.abort(), allowed);
2694
3039
  try {
2695
3040
  const response = await fetchImpl(url, { ...init, redirect: "manual", signal: controller.signal });
2696
3041
  if (isMirrorRedirect(response)) {
@@ -2708,14 +3053,17 @@ function createMirrorNodeRecordChainReader(options) {
2708
3053
  }
2709
3054
  } catch (error) {
2710
3055
  if (mirrorRefusalOf(error)) throw error;
2711
- if (error.name === "AbortError") lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
2712
- else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
3056
+ if (error.name === "AbortError") {
3057
+ if (deadline !== void 0 && allowed < timeoutMs) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
3058
+ lastError = new Error(`mirror node request timed out after ${timeoutMs}ms (${path})`);
3059
+ } else if (/^mirror node \d{3} for/.test(error.message) && !/^mirror node (429|5\d\d)/.test(error.message)) throw error;
2713
3060
  else lastError = error;
2714
3061
  } finally {
2715
3062
  clearTimeout(timer);
2716
3063
  }
2717
3064
  if (attempt < attempts) await new Promise((resolve3) => setTimeout(resolve3, 250 * attempt));
2718
3065
  }
3066
+ if (deadline !== void 0 && now() >= deadline) throw mirrorRefusal.scanTooSlow(scanBudgetMs);
2719
3067
  throw lastError ?? new Error(`mirror node request failed (${path})`);
2720
3068
  }
2721
3069
  async function call(fn, args = []) {
@@ -2751,16 +3099,23 @@ function createMirrorNodeRecordChainReader(options) {
2751
3099
  params.set("limit", String(pageSize));
2752
3100
  let next = `${contractLogPath(contractAddress)}?${params.toString()}`;
2753
3101
  const out = [];
2754
- let pages = 0;
3102
+ const scan = { deadline: now() + scanBudgetMs, requests: 0 };
3103
+ let last = null;
2755
3104
  let size = pageSize;
2756
3105
  while (next) {
2757
- const { page, asked } = await readLogPage(next, size);
3106
+ const { page, asked } = await readLogPage(next, size, scan);
2758
3107
  size = Math.min(pageSize, asked * 2);
2759
3108
  const logs = Array.isArray(page.logs) ? page.logs : [...page.logs ?? []];
2760
3109
  if (logs.length > asked) throw mirrorRefusal.tooManyLogs(asked, next);
2761
3110
  for (const raw of logs) {
2762
- const log = keptMirrorLog(raw);
2763
- if (log) out.push(log);
3111
+ const position = mirrorLogPosition(raw);
3112
+ if (!position) continue;
3113
+ if (!mirrorLogFollows(last, position)) throw mirrorRefusal.notForward();
3114
+ last = position;
3115
+ const log = keptMirrorLog(raw, contractAddress);
3116
+ if (!log) continue;
3117
+ if (out.length >= maxKeptLogs) throw mirrorRefusal.scanTooManyLogs(maxKeptLogs);
3118
+ out.push(log);
2764
3119
  }
2765
3120
  const link = page.links?.next;
2766
3121
  if (link === null || link === void 0 || link === "") {
@@ -2770,16 +3125,16 @@ function createMirrorNodeRecordChainReader(options) {
2770
3125
  if (!path) throw mirrorRefusal.nextPage();
2771
3126
  next = withLogPageLimit(path, size);
2772
3127
  }
2773
- pages += 1;
2774
- if (pages > 1e4) throw new Error("mirror node log scan exceeded 10,000 pages");
2775
3128
  }
2776
3129
  return out;
2777
3130
  }
2778
- async function readLogPage(path, start) {
3131
+ async function readLogPage(path, start, scan) {
2779
3132
  let asked = start;
2780
3133
  for (; ; ) {
3134
+ if (scan.requests >= maxScanRequests) throw mirrorRefusal.scanTooManyRequests(maxScanRequests);
3135
+ scan.requests += 1;
2781
3136
  try {
2782
- return { page: await request(withLogPageLimit(path, asked)), asked };
3137
+ return { page: await request(withLogPageLimit(path, asked), void 0, scan.deadline), asked };
2783
3138
  } catch (error) {
2784
3139
  if (mirrorRefusalOf(error) !== "too-large" || asked <= 1) throw error;
2785
3140
  asked = Math.max(1, Math.floor(asked / 2));
@@ -2803,6 +3158,10 @@ function createMirrorNodeRecordChainReader(options) {
2803
3158
  try {
2804
3159
  const response = await fetchImpl(`${base}${path}`, { headers: { accept: "application/json" }, redirect: "error", signal: controller.signal });
2805
3160
  if (isMirrorRedirect(response)) throw mirrorRefusal.redirect(path);
3161
+ if (response.status === 429) {
3162
+ await response.body?.cancel?.().catch(() => void 0);
3163
+ return new SearchLimited(retryAfterMsOf(response));
3164
+ }
2806
3165
  if (!response.ok) throw new Error(`mirror node ${response.status} for a record's writes`);
2807
3166
  const page = await readMirrorJson(response, MIRROR_ANSWER_MAX_BYTES, path);
2808
3167
  if (Array.isArray(page.logs) && page.logs.length > LEDGER_WRITE_SEARCH_PAGE_LIMIT) throw mirrorRefusal.tooManyLogs(LEDGER_WRITE_SEARCH_PAGE_LIMIT, path);
@@ -2873,7 +3232,8 @@ function createMirrorNodeRecordChainReader(options) {
2873
3232
  transactionHash: log.transaction_hash,
2874
3233
  logIndex: log.index,
2875
3234
  committedAt: committedAtOf(log.timestamp),
2876
- contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0
3235
+ contractAddress: typeof log.address === "string" ? log.address.toLowerCase() : void 0,
3236
+ ...typeof log.timestamp === "string" && CONSENSUS_TIMESTAMP.test(log.timestamp) ? { consensusTimestamp: log.timestamp } : {}
2877
3237
  });
2878
3238
  }
2879
3239
  return out;
@@ -2881,25 +3241,36 @@ function createMirrorNodeRecordChainReader(options) {
2881
3241
  async findRecordWrites(recordKey, search) {
2882
3242
  const key = normalizeProofHash(recordKey, "recordKey").toLowerCase();
2883
3243
  const topic0 = RECORD_WRITTEN_TOPIC.toLowerCase();
2884
- const now = search.now ?? Date.now;
2885
- const deadline = now() + search.budgetMs;
3244
+ const now2 = search.now ?? Date.now;
3245
+ const deadline = now2() + search.budgetMs;
2886
3246
  const windowSeconds = Math.max(1, Math.floor(search.windowSeconds ?? RECORD_WRITE_SEARCH_WINDOW_SECONDS));
2887
- const nowSeconds = Math.floor(now() / 1e3);
3247
+ const nowSeconds = Math.floor(now2() / 1e3);
2888
3248
  const hint = search.startAt ? Date.parse(search.startAt) : Number.NaN;
2889
3249
  let upper = Math.min(Number.isFinite(hint) ? Math.floor(hint / 1e3) : nowSeconds, nowSeconds) + DAY_SECONDS;
2890
3250
  const writes = [];
2891
3251
  let requests = 0;
3252
+ let waits = 0;
2892
3253
  const end = (ended) => ({ writes, ended, requests });
2893
3254
  while (!search.done(writes)) {
2894
3255
  if (upper <= 0) return end("limit");
2895
3256
  const lower = Math.max(0, upper - windowSeconds);
2896
3257
  let path = ledgerWriteSearchPath({ contractAddress, topic0, recordKey: key, lower, upper });
2897
3258
  while (path) {
2898
- const left = deadline - now();
3259
+ const left = deadline - now2();
2899
3260
  if (requests >= search.maxRequests || left <= 0) return end("limit");
2900
3261
  requests += 1;
3262
+ search.onRequest?.();
2901
3263
  const page = await searchPage(path, left);
2902
3264
  if (page === "timeout") return end("timeout");
3265
+ if (page instanceof SearchLimited) {
3266
+ const waitOut = search.waitOut;
3267
+ if (!waitOut || waits >= waitOut.times) throw new Error("mirror node 429 for a record's writes");
3268
+ waits += 1;
3269
+ const wait = Math.max(0, Math.min(waitOut.maxWaitMs, page.retryAfterMs ?? waitOut.waitMs));
3270
+ if (wait >= deadline - now2()) return end("limit");
3271
+ await (waitOut.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms))))(wait);
3272
+ continue;
3273
+ }
2903
3274
  for (const log of Array.isArray(page?.logs) ? page.logs : []) {
2904
3275
  const write = parseLedgerWriteLog(log, { topic0, recordKey: key, contractAddress });
2905
3276
  if (!write || !CONSENSUS_TIMESTAMP.test(write.timestamp)) continue;
@@ -2912,10 +3283,11 @@ function createMirrorNodeRecordChainReader(options) {
2912
3283
  transactionHash: write.transactionHash,
2913
3284
  logIndex: write.logIndex ?? void 0,
2914
3285
  committedAt: write.committedAt,
2915
- contractAddress: write.address
3286
+ contractAddress: write.address,
3287
+ consensusTimestamp: write.timestamp
2916
3288
  });
2917
3289
  }
2918
- if (search.done(writes)) return end("done");
3290
+ if (!search.wholeWindows && search.done(writes)) return end("done");
2919
3291
  const link = page?.links?.next;
2920
3292
  path = nextLogPath(link, { base, contract: contractAddress });
2921
3293
  if (!path && link !== null && link !== void 0 && link !== "") throw mirrorRefusal.nextPage();
@@ -3151,7 +3523,7 @@ var hasOnly = (v, required, optional = []) => required.every((k) => Object.proto
3151
3523
  function computeSealHistoryDigestV1(form) {
3152
3524
  const rest = { ...form };
3153
3525
  delete rest.digest;
3154
- return import_ethers13.ethers.keccak256(import_ethers13.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
3526
+ return import_ethers14.ethers.keccak256(import_ethers14.ethers.toUtf8Bytes(canonicalizeJcs(rest)));
3155
3527
  }
3156
3528
  function entryShapeOk2(e) {
3157
3529
  if (!isPlainObject4(e) || !hasOnly(e, ENTRY_KEYS, ["recordHash"])) return false;
@@ -3598,13 +3970,19 @@ async function aesKey2(key, usage) {
3598
3970
  const subtle = (await platformCrypto()).subtle;
3599
3971
  return subtle.importKey("raw", key, { name: "AES-GCM" }, false, [usage]);
3600
3972
  }
3973
+ function isDecryptKey(key) {
3974
+ if (typeof CryptoKey === "undefined" || !(key instanceof CryptoKey) || key.type !== "secret" || !key.usages.includes("decrypt")) return false;
3975
+ const algorithm = key.algorithm;
3976
+ return algorithm.name === "AES-GCM" && algorithm.length === KEY_BYTES2 * 8;
3977
+ }
3601
3978
  async function decryptDisclosureV1(input) {
3602
3979
  try {
3603
3980
  const shape = readDisclosureEnvelopeShapeV1(input?.envelope);
3604
3981
  if (!shape.ok) return refuse4(shape.code);
3605
3982
  const bytes2 = fromBase64Url(input.envelope);
3606
3983
  const { key, handle } = input;
3607
- if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES2 || typeof handle !== "string") {
3984
+ const held = isDecryptKey(key);
3985
+ if (!held && (!(key instanceof Uint8Array) || key.length !== KEY_BYTES2) || typeof handle !== "string") {
3608
3986
  return refuse4("DISCLOSURE_ENVELOPE_AUTH_FAILED");
3609
3987
  }
3610
3988
  let plain;
@@ -3613,7 +3991,7 @@ async function decryptDisclosureV1(input) {
3613
3991
  plain = new Uint8Array(
3614
3992
  await subtle.decrypt(
3615
3993
  { name: "AES-GCM", iv: bytes2.subarray(1, HEADER_BYTES), additionalData: aadOf2(handle), tagLength: 128 },
3616
- await aesKey2(key, "decrypt"),
3994
+ held ? key : await aesKey2(key, "decrypt"),
3617
3995
  bytes2.subarray(HEADER_BYTES)
3618
3996
  )
3619
3997
  );
@@ -3637,121 +4015,1178 @@ async function decryptDisclosureV1(input) {
3637
4015
  // ../shared/src/records-crypto/wrap-shapes-v1.ts
3638
4016
  var SEP5 = new Uint8Array([0]);
3639
4017
 
3640
- // src/report.ts
3641
- var REPORT_SCHEMA = "pacspace-check-report/v1";
3642
- var SOURCE_REFUSAL_REASONS = {
3643
- redirect: "its source answered with a redirect, which is not followed",
3644
- "too-large": "its source gave an answer larger than this checker reads",
3645
- "too-many-logs": "its source returned a longer page than was asked for",
3646
- "next-page": "its source pointed somewhere else for the next page"
3647
- };
3648
- var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
3649
- function refusedUnopenedSentence(k) {
3650
- return `${k} refused ${entryWord(k)} could not be opened with this record key. Their seals are checked.`;
4018
+ // ../shared/src/records/link-handle-v1.ts
4019
+ var LINK_HANDLE_PREFIX = "csh1_";
4020
+ var LIST_HANDLE_PREFIX = "csl1_";
4021
+ var LINK_HANDLE_PATTERN = /^cs[hl]1_[A-Za-z0-9_-]{1,80}$/;
4022
+ var LINK_HANDLE_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
4023
+ var WHOLE_HANDLE = /^(csh1_|csl1_)([a-z2-7]{52})([a-z2-7]{4})$/;
4024
+ var LIST_BODY = /^[a-z2-7]{51}[aq]$/;
4025
+ function normalizeLinkHandleV1(text) {
4026
+ if (typeof text !== "string") return null;
4027
+ let decoded;
4028
+ try {
4029
+ decoded = decodeURIComponent(text);
4030
+ } catch {
4031
+ return null;
4032
+ }
4033
+ return decoded.trim().toLowerCase();
3651
4034
  }
3652
- var HONESTY_SENTENCE = "The check shows the record is unchanged since it was committed. It does not show that what was recorded was true.";
3653
- var SEALS_BOUNDARY_SENTENCE = "The check shows each seal was committed and that all of them are here, in order. It does not show what any entry says, or that what was recorded was true.";
3654
- var FIELDS_FAILED_SENTENCE = "The revealed fields failed the check, so none are shown.";
3655
- var ROOT_NOT_READ_SENTENCE = "The revealed fields could not be checked against the proof layer just now, so none are shown. Check again to try once more.";
3656
- var TOO_LARGE_SENTENCE = "This file is too large to be a copy of this record.";
3657
- var FILE_NOT_IN_RECORD_SENTENCE = "This file is not in the record.";
3658
- var HELD_FILE_OFFLINE_SENTENCE = "The ledger was not read (--offline); the file you hold was matched against the history file only.";
3659
- var MONTHS = [
3660
- "January",
3661
- "February",
3662
- "March",
3663
- "April",
3664
- "May",
3665
- "June",
3666
- "July",
3667
- "August",
3668
- "September",
3669
- "October",
3670
- "November",
3671
- "December"
3672
- ];
3673
- function dayOfUtc(value) {
3674
- const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
3675
- if (!match) return value;
3676
- const day = Number(match[3]);
3677
- const month = MONTHS[Number(match[2]) - 1] ?? match[2];
3678
- return `${day} ${month} ${match[1]}`;
4035
+ function linkHandlePartsV1(handle) {
4036
+ const match = typeof handle === "string" ? WHOLE_HANDLE.exec(handle) : null;
4037
+ if (!match) return null;
4038
+ const [, prefix, body, checksum] = match;
4039
+ if (prefix === LIST_HANDLE_PREFIX && !LIST_BODY.test(body)) return null;
4040
+ return { handle, prefix, body, checksum };
3679
4041
  }
3680
- function entryWord(count) {
3681
- return count === 1 ? "entry" : "entries";
4042
+ function hasListHandlePrefixV1(handle) {
4043
+ return typeof handle === "string" && handle.startsWith(LIST_HANDLE_PREFIX);
3682
4044
  }
3683
- function listEntries(numbers) {
3684
- const sorted = [...numbers].sort((a, b) => a - b);
3685
- if (sorted.length === 1) return `Entry ${sorted[0]}`;
3686
- const head = sorted.slice(0, -1).join(", ");
3687
- return `Entries ${head} and ${sorted[sorted.length - 1]}`;
4045
+
4046
+ // ../shared/src/records/reader-crypto-v1.ts
4047
+ var ReaderCryptoError = class extends Error {
4048
+ constructor(code) {
4049
+ super(code);
4050
+ this.code = code;
4051
+ this.name = "ReaderCryptoError";
4052
+ }
4053
+ };
4054
+ var SEP6 = new Uint8Array([0]);
4055
+ var P256_SPKI_PREFIX = Uint8Array.from([
4056
+ 48,
4057
+ 89,
4058
+ 48,
4059
+ 19,
4060
+ 6,
4061
+ 7,
4062
+ 42,
4063
+ 134,
4064
+ 72,
4065
+ 206,
4066
+ 61,
4067
+ 2,
4068
+ 1,
4069
+ 6,
4070
+ 8,
4071
+ 42,
4072
+ 134,
4073
+ 72,
4074
+ 206,
4075
+ 61,
4076
+ 3,
4077
+ 1,
4078
+ 7,
4079
+ 3,
4080
+ 66,
4081
+ 0
4082
+ ]);
4083
+ var HANDLE = LINK_HANDLE_PATTERN;
4084
+ var PART = /^[\x21-\x39\x3b-\x7e]{1,128}$/;
4085
+ function check(ok) {
4086
+ if (!ok) throw new ReaderCryptoError("READER_BINDING_INVALID");
3688
4087
  }
3689
- function entryWords(entries) {
3690
- if (entries.length === 1) return `Entry ${entries[0]}`;
3691
- if (entries.length === 2) return `Entries ${entries[0]} and ${entries[1]}`;
3692
- return `Entries ${entries.slice(0, -1).join(", ")}, and ${entries[entries.length - 1]}`;
4088
+ var isEpoch = (n) => Number.isSafeInteger(n) && n >= 1;
4089
+ function revealBindingV1(handle, epoch, recordKey) {
4090
+ check(HANDLE.test(handle) && isEpoch(epoch) && PART.test(recordKey));
4091
+ return `reveal:${handle}:${epoch}:${recordKey}`;
3693
4092
  }
3694
- var isAre = (count) => count === 1 ? "is" : "are";
3695
- function sameHex(a, b) {
3696
- if (!a || !b) return false;
3697
- return a.trim().toLowerCase() === b.trim().toLowerCase();
4093
+ function openRevealV1(input) {
4094
+ return decryptDisclosureV1({ envelope: input.envelope, key: input.linkKey, handle: revealBindingV1(input.handle, input.epoch, input.recordKey) });
3698
4095
  }
3699
- function countedSentence(record) {
3700
- const { entries, matched, missing, unmatched } = record;
3701
- if (entries === null) {
3702
- return `This file carries ${matched} ${entryWord(matched)} that match what was committed. The record's own count could not be read.`;
3703
- }
3704
- const parts = [`This record has ${entries} ${entryWord(entries)}.`];
3705
- if (missing.length === 0 && unmatched.length === 0 && matched >= entries) {
3706
- parts.push(
3707
- entries === 1 ? "It is here, and it matches what was committed." : `All ${entries} are here, and all ${entries} match what was committed.`
3708
- );
3709
- return parts.join(" ");
3710
- }
3711
- parts.push(`${matched} of ${entries} match what was committed.`);
3712
- if (unmatched.length) {
3713
- parts.push(`${listEntries(unmatched)} ${unmatched.length === 1 ? "does" : "do"} not.`);
3714
- }
3715
- if (missing.length) {
3716
- parts.push(`${listEntries(missing)} ${missing.length === 1 ? "is" : "are"} not in this file.`);
4096
+
4097
+ // ../shared/src/records/shared-record-list-v1.ts
4098
+ var import_ethers15 = require("ethers");
4099
+ var SHARED_RECORD_REVEAL_FIELDS_MAX_V1 = 32;
4100
+ var FIELD_POINTER = /^\/[A-Za-z][A-Za-z0-9_]{0,63}$/;
4101
+ var MODES = ["seals", "fields", "all"];
4102
+ var SharedRecordListError = class extends Error {
4103
+ constructor(code) {
4104
+ super(code);
4105
+ this.code = code;
4106
+ this.name = "SharedRecordListError";
3717
4107
  }
3718
- return parts.join(" ");
3719
- }
3720
- function sealsPassedSentence(n) {
3721
- if (n === 1) return "This record has 1 entry. Its seal is here, and it is in what was committed.";
3722
- return `This record has ${n} entries. All ${n} seals are here, in order, and each is in what was committed.`;
4108
+ };
4109
+ var isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4110
+ var hasExactly3 = (v, keys) => Object.keys(v).length === keys.length && keys.every((k) => Object.prototype.hasOwnProperty.call(v, k));
4111
+ function isCanonicalRevealTermsV1(terms) {
4112
+ if (!isPlain(terms) || !hasExactly3(terms, ["mode", "fields", "time"])) return false;
4113
+ const { mode, fields, time } = terms;
4114
+ if (!MODES.includes(mode) || typeof time !== "boolean" || !Array.isArray(fields)) return false;
4115
+ if (mode === "seals") return fields.length === 0 && time === false;
4116
+ if (mode === "all") return fields.length === 0 && time === true;
4117
+ if (fields.length > SHARED_RECORD_REVEAL_FIELDS_MAX_V1) return false;
4118
+ return fields.every((f, i) => typeof f === "string" && FIELD_POINTER.test(f) && (i === 0 || fields[i - 1] < f));
4119
+ }
4120
+ function revealsFieldsV1(terms) {
4121
+ return terms.mode !== "seals";
4122
+ }
4123
+ var SHARED_RECORD_LIST_MAX_V1 = 200;
4124
+ var ROW_KEYS = ["number", "recordKey", "chainId", "contractAddress", "lastSeq", "lastSeal"];
4125
+ var HEX_32 = /^0x[0-9a-f]{64}$/;
4126
+ var HEX_20 = /^0x[0-9a-f]{40}$/;
4127
+ var HEX_64_BARE = /^[0-9a-f]{64}$/;
4128
+ var UINT32_MAX2 = 4294967295;
4129
+ var isUint = (v, max) => Number.isSafeInteger(v) && v >= 0 && v <= max;
4130
+ function readSharedRecordListV1(rows) {
4131
+ const refuse5 = () => new SharedRecordListError("SHARED_RECORD_LIST_INVALID");
4132
+ if (!Array.isArray(rows) || rows.length < 1 || rows.length > SHARED_RECORD_LIST_MAX_V1) throw refuse5();
4133
+ const keys = /* @__PURE__ */ new Set();
4134
+ let last = 0;
4135
+ return rows.map((row) => {
4136
+ if (!isPlain(row) || !hasExactly3(row, ROW_KEYS)) throw refuse5();
4137
+ const { number, recordKey, chainId, contractAddress, lastSeq, lastSeal } = row;
4138
+ if (!isUint(number, UINT32_MAX2) || number <= last) throw refuse5();
4139
+ if (typeof recordKey !== "string" || !HEX_32.test(recordKey) || keys.has(recordKey)) throw refuse5();
4140
+ if (!isUint(chainId, Number.MAX_SAFE_INTEGER) || chainId < 1) throw refuse5();
4141
+ if (typeof contractAddress !== "string" || !HEX_20.test(contractAddress)) throw refuse5();
4142
+ if (!isUint(lastSeq, UINT32_MAX2)) throw refuse5();
4143
+ if (typeof lastSeal !== "string" || !HEX_20.test(lastSeal)) throw refuse5();
4144
+ last = number;
4145
+ keys.add(recordKey);
4146
+ return { number, recordKey, chainId, contractAddress, lastSeq, lastSeal };
4147
+ });
3723
4148
  }
3724
- function sealsSettlingSentence(n, settling) {
3725
- const m = n - settling.length;
3726
- const tail = `${entryWords(settling)} ${isAre(settling.length)} still being recorded.`;
3727
- if (m <= 0) return `This record has ${n} ${n === 1 ? "entry" : "entries"}. ${tail}`;
3728
- if (m === 1) return `This record has ${n} entries. 1 of the ${n} seals is here, and it is in what was committed. ${tail}`;
3729
- return `This record has ${n} entries. ${m} of the ${n} seals are here, in order, and each is in what was committed. ${tail}`;
4149
+ var SHARED_RECORD_LIST_LABEL_V1 = "pacspace:shared-record-list:v1";
4150
+ var SHARED_RECORD_HANDLE_LABEL_V1 = "pacspace:shared-record-handle:v1";
4151
+ var MODE_BYTE = { seals: 0, fields: 1, all: 2 };
4152
+ var utf83 = (text) => import_ethers15.ethers.toUtf8Bytes(text);
4153
+ var uint = (value, bytes2) => import_ethers15.ethers.getBytes(import_ethers15.ethers.toBeHex(BigInt(value), bytes2));
4154
+ function sharedRecordListBytesV1(terms, rows) {
4155
+ if (!isCanonicalRevealTermsV1(terms)) throw new SharedRecordListError("SHARED_RECORD_TERMS_INVALID");
4156
+ const list = readSharedRecordListV1(rows);
4157
+ const parts = [utf83(SHARED_RECORD_LIST_LABEL_V1), Uint8Array.of(0), Uint8Array.of(MODE_BYTE[terms.mode], terms.time ? 1 : 0), uint(terms.fields.length, 2)];
4158
+ for (const field of terms.fields) {
4159
+ const text = utf83(field);
4160
+ parts.push(uint(text.length, 2), text);
4161
+ }
4162
+ parts.push(uint(list.length, 2));
4163
+ for (const row of list) {
4164
+ parts.push(uint(row.number, 4), import_ethers15.ethers.getBytes(row.recordKey), uint(row.chainId, 8), import_ethers15.ethers.getBytes(row.contractAddress), uint(row.lastSeq, 4), import_ethers15.ethers.getBytes(row.lastSeal));
4165
+ }
4166
+ return import_ethers15.ethers.getBytes(import_ethers15.ethers.concat(parts));
4167
+ }
4168
+ function sharedRecordListDigestV1(terms, rows) {
4169
+ return import_ethers15.ethers.sha256(sharedRecordListBytesV1(terms, rows)).slice(2);
4170
+ }
4171
+ function base32(bytes2) {
4172
+ let bits = 0;
4173
+ let value = 0;
4174
+ let out = "";
4175
+ for (const byte of bytes2) {
4176
+ value = (value << 8 | byte) & 65535;
4177
+ bits += 8;
4178
+ while (bits >= 5) {
4179
+ out += LINK_HANDLE_ALPHABET[value >>> bits - 5 & 31];
4180
+ bits -= 5;
4181
+ }
4182
+ }
4183
+ if (bits > 0) out += LINK_HANDLE_ALPHABET[value << 5 - bits & 31];
4184
+ return out;
3730
4185
  }
3731
- function sealsFailedSentence(n, failed) {
3732
- if (n === 1) return "This record has 1 entry. Its seal is not in what was committed.";
3733
- const k = n - failed.length;
3734
- return `This record has ${n} entries. ${k} of the ${n} seals ${isAre(k)} in what was committed. ${entryWords(failed)} ${failed.length === 1 ? "is not" : "are not"}.`;
4186
+ function sharedRecordHandleBodyV1(listDigest, salt) {
4187
+ if (typeof listDigest !== "string" || !HEX_64_BARE.test(listDigest)) throw new SharedRecordListError("SHARED_RECORD_LIST_INVALID");
4188
+ if (typeof salt !== "string" || !HEX_64_BARE.test(salt)) throw new SharedRecordListError("SHARED_RECORD_SALT_INVALID");
4189
+ const digest = import_ethers15.ethers.sha256(import_ethers15.ethers.concat([utf83(SHARED_RECORD_HANDLE_LABEL_V1), Uint8Array.of(0), import_ethers15.ethers.getBytes(`0x${listDigest}`), import_ethers15.ethers.getBytes(`0x${salt}`)]));
4190
+ return base32(import_ethers15.ethers.getBytes(digest));
3735
4191
  }
3736
- function sealsMissingSentence(n, held, missing) {
3737
- return `What was committed says this record has ${n} entries. This copy has ${held} of them. Entry ${missing} is not here.`;
4192
+ function sharedRecordListFingerprintV1(list) {
4193
+ const digest = sharedRecordListDigestV1(list.reveal, list.rows);
4194
+ return { digest, body: sharedRecordHandleBodyV1(digest, list.salt) };
3738
4195
  }
3739
- function sealsFormFailedSentence(n) {
3740
- return n === null ? "These seals do not match what was committed." : `This record has ${n} entries. These seals do not match what was committed.`;
4196
+ function sharedRecordHandleNamesListV1(handle, list) {
4197
+ const parts = linkHandlePartsV1(handle);
4198
+ if (!parts || parts.prefix !== LIST_HANDLE_PREFIX) return false;
4199
+ try {
4200
+ return sharedRecordListFingerprintV1(list).body === parts.body;
4201
+ } catch {
4202
+ return false;
4203
+ }
3741
4204
  }
3742
- function revealedLine(shown, total) {
3743
- if (total === 1) return "The entry shows fields the sharer chose to reveal. Each shown field was checked against its seal.";
3744
- if (shown >= total) return "Every entry shows fields the sharer chose to reveal. Each shown field was checked against its entry's seal.";
3745
- return `${shown} of ${total} entries ${shown === 1 ? "shows" : "show"} fields the sharer chose to reveal. Each shown field was checked against its entry's seal.`;
4205
+
4206
+ // ../shared/src/records/shared-record-v2.ts
4207
+ var SHARED_RECORD_SCHEMA_V2 = "shared-record/v2";
4208
+ var SHARED_RECORD_V2_KEYS = {
4209
+ "": {
4210
+ required: ["schema", "reference", "organization", "scope", "previousScope", "rule", "sharedOn", "link", "reveal", "members", "page"],
4211
+ optional: ["list"]
4212
+ },
4213
+ "previousScope[]": { required: ["scope", "until"] },
4214
+ rule: { required: ["committedOn", "last", "changes"] },
4215
+ "rule.last": { required: ["on", "what"] },
4216
+ "rule.changes[]": { required: ["on", "what", "reason"] },
4217
+ link: { required: ["endsOn", "extendedOn", "opens"] },
4218
+ reveal: { required: ["mode", "fields", "time"] },
4219
+ list: { required: ["reveal", "salt", "rows"] },
4220
+ "list.reveal": { required: ["mode", "fields", "time"] },
4221
+ "list.rows[]": { required: ["number", "recordKey", "chainId", "contractAddress", "lastSeq", "lastSeal"] },
4222
+ "members[]": {
4223
+ required: ["number", "openedOn", "closedOn", "entries", "closedBy", "lastSeq", "joinedOn", "removed", "ruleVersion", "recordKey", "chainId", "contractAddress", "lastSeal"],
4224
+ optional: ["revealed", "recordHashVersion", "committedAt", "writtenBy"]
4225
+ },
4226
+ "members[].removed": { required: ["on", "reason"] },
4227
+ "members[].revealed": { required: ["on", "later"] },
4228
+ "members[].writtenBy": { required: ["version", "model", "builtOn", "runtime", "guardrails"] },
4229
+ page: { required: ["after", "next"] }
4230
+ };
4231
+ var isPlain2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4232
+ function sharedRecordV2KeyProblems(payload) {
4233
+ const problems = [];
4234
+ const walk = (value, path) => {
4235
+ if (Array.isArray(value)) {
4236
+ for (const item of value) walk(item, `${path}[]`);
4237
+ return;
4238
+ }
4239
+ if (!isPlain2(value)) return;
4240
+ const set = SHARED_RECORD_V2_KEYS[path];
4241
+ if (!set) {
4242
+ problems.push(`${path || "(root)"}: no object allowed here`);
4243
+ return;
4244
+ }
4245
+ const allowed = /* @__PURE__ */ new Set([...set.required, ...set.optional ?? []]);
4246
+ for (const key of set.required) if (value[key] === void 0) problems.push(`${path ? `${path}.` : ""}${key}: missing`);
4247
+ for (const key of Object.keys(value)) {
4248
+ if (!allowed.has(key)) problems.push(`${path ? `${path}.` : ""}${key}: not allowed`);
4249
+ else walk(value[key], path ? `${path}.${key}` : key);
4250
+ }
4251
+ };
4252
+ walk(payload, "");
4253
+ return problems;
3746
4254
  }
3747
- function sealsVerdict(entries, v, queued = []) {
3748
- if (v.nothingCommitted) {
3749
- return {
3750
- sentence: queued.length > 0 ? sealsSettlingSentence(queued.length, queued.map((seq) => seq + 1)) : v.reason,
3751
- passed: false
3752
- };
4255
+
4256
+ // ../shared/src/records/shared-record-check-v1.ts
4257
+ var SHARED_RECORD_CHECK_SCHEMA_V1 = "shared-record-check/v1";
4258
+ function readSharedRecordAddressV1(text) {
4259
+ if (typeof text !== "string") return null;
4260
+ let url;
4261
+ try {
4262
+ url = new URL(text.trim());
4263
+ } catch {
4264
+ return null;
3753
4265
  }
3754
- if (!v.schemaOk || !v.digestOk || !v.layoutOk || entries === null) {
4266
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
4267
+ if (!(url.protocol === "https:" || url.protocol === "http:" && local) || url.username || url.password) return null;
4268
+ const match = /^\/c\/([^/]+)(?:\/.*)?$/i.exec(url.pathname);
4269
+ if (!match) return null;
4270
+ const handle = normalizeLinkHandleV1(match[1]);
4271
+ if (!handle) return null;
4272
+ let prefix = null;
4273
+ if (hasListHandlePrefixV1(handle)) {
4274
+ if (!linkHandlePartsV1(handle)) return null;
4275
+ prefix = LIST_HANDLE_PREFIX;
4276
+ } else if (handle.startsWith(LINK_HANDLE_PREFIX)) {
4277
+ prefix = LINK_HANDLE_PREFIX;
4278
+ }
4279
+ return { origin: url.origin, host: url.host, handle, prefix, fragment: url.hash.replace(/^#/, "") };
4280
+ }
4281
+ function sharedRecordAddressOpensV1(handle, answersAs) {
4282
+ if (hasListHandlePrefixV1(handle)) return answersAs === "trail" ? "list" : "fails";
4283
+ return answersAs;
4284
+ }
4285
+ var SharedRecordAnswerError = class extends Error {
4286
+ constructor(reason, message) {
4287
+ super(message ?? reason);
4288
+ this.reason = reason;
4289
+ this.name = "SharedRecordAnswerError";
4290
+ }
4291
+ };
4292
+ function answerErrorOf(error) {
4293
+ const { name, reason } = error ?? {};
4294
+ return name === "SharedRecordAnswerError" && reason === "refused" ? "refused" : "unreachable";
4295
+ }
4296
+ var RECORD_CODE_STATUS = {
4297
+ HISTORY_NOT_SERVED: "fails",
4298
+ HISTORY_INVALID: "fails",
4299
+ HISTORY_OTHER_RECORD: "fails",
4300
+ ENTRY_MISSING: "fails",
4301
+ ENTRY_NOT_COMMITTED: "fails",
4302
+ ENTRY_FAILED: "fails",
4303
+ CLOSE_SEAL_DIFFERS: "fails",
4304
+ ENTRY_NOT_WRITTEN: "fails",
4305
+ WRITE_NOT_SERVED: "fails",
4306
+ WRITE_BEFORE_FIRST: "fails",
4307
+ RECORD_SET_BACK: "fails",
4308
+ CURRENT_WORD_ZERO: "fails",
4309
+ CURRENT_WORD_EARLIER: "fails",
4310
+ REVEAL_MISSING: "fails",
4311
+ REVEAL_NOT_OPENED: "fails",
4312
+ FIELDS_DO_NOT_MATCH: "fails",
4313
+ HISTORY_NOT_READ: "not-checked",
4314
+ LAYOUT_NOT_READ: "not-checked",
4315
+ SOURCE_UNKNOWN: "not-checked",
4316
+ SOURCE_NOT_READ: "not-checked",
4317
+ BUDGET_SPENT: "not-checked",
4318
+ LOG_PAST_BOUNDS: "not-checked",
4319
+ REVEALS_NOT_READ: "not-checked",
4320
+ ROOT_NOT_READ: "not-checked"
4321
+ };
4322
+ var LINK_CODE_STATUS = {
4323
+ LINK_NOT_A_LIST: "fails",
4324
+ MANIFEST_INVALID: "fails",
4325
+ LIST_ON_LATER_PAGE: "fails",
4326
+ LIST_INVALID: "fails",
4327
+ TERMS_DIFFER: "fails",
4328
+ LIST_NOT_ADDRESS: "fails",
4329
+ RECORDS_NOT_LIST: "fails",
4330
+ PAGING_NOT_FORWARD: "fails",
4331
+ REVEALS_INVALID: "fails",
4332
+ REVEAL_OFF_LIST: "fails",
4333
+ LINK_HAS_NO_LIST: "not-checked",
4334
+ MANIFEST_NOT_READ: "not-checked"
4335
+ };
4336
+ var SHARED_RECORD_CHECK_RECORD_REQUESTS_V1 = 40;
4337
+ var SHARED_RECORD_CHECK_RUN_REQUESTS_V1 = 1e4;
4338
+ var SHARED_RECORD_CHECK_RECORD_MS_V1 = 6e4;
4339
+ var SHARED_RECORD_CHECK_WAITS_V1 = 3;
4340
+ var SHARED_RECORD_CHECK_UNANSWERED_V1 = 3;
4341
+ var HEX323 = /^0x[0-9a-f]{64}$/;
4342
+ var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
4343
+ var DAY = /^\d{4}-\d{2}-\d{2}$/;
4344
+ var INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/;
4345
+ var CONSENSUS = /^\d{1,12}\.\d{9}$/;
4346
+ var ZERO_WORD = `0x${"0".repeat(64)}`;
4347
+ var isPlain3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4348
+ var sameTerms = (a, b) => isCanonicalRevealTermsV1(a) && a.mode === b.mode && a.time === b.time && a.fields.length === b.fields.length && a.fields.every((f, i) => f === b.fields[i]);
4349
+ var LinkStop = class extends Error {
4350
+ constructor(code) {
4351
+ super(code);
4352
+ this.code = code;
4353
+ }
4354
+ };
4355
+ var RecordStop = class extends Error {
4356
+ constructor(code, entry = null) {
4357
+ super(code);
4358
+ this.code = code;
4359
+ this.entry = entry;
4360
+ }
4361
+ };
4362
+ function readPage(raw) {
4363
+ if (!isPlain3(raw) || raw.schema !== SHARED_RECORD_SCHEMA_V2) return null;
4364
+ if (sharedRecordV2KeyProblems(raw).length > 0) return null;
4365
+ if (!Array.isArray(raw.members) || !isPlain3(raw.page) || !isPlain3(raw.link) || !isPlain3(raw.reveal)) return null;
4366
+ const { after, next } = raw.page;
4367
+ if (!Number.isSafeInteger(after) || next !== null && !Number.isSafeInteger(next)) return null;
4368
+ for (const member of raw.members) {
4369
+ if (!isPlain3(member) || !Number.isSafeInteger(member.number)) return null;
4370
+ }
4371
+ return raw;
4372
+ }
4373
+ async function readManifest(source) {
4374
+ let first = null;
4375
+ const members = [];
4376
+ let after = 0;
4377
+ for (; ; ) {
4378
+ let raw;
4379
+ try {
4380
+ raw = await source.page(after);
4381
+ } catch {
4382
+ throw new LinkStop("MANIFEST_NOT_READ");
4383
+ }
4384
+ const page = readPage(raw);
4385
+ if (!page) throw new LinkStop("MANIFEST_INVALID");
4386
+ if (page.page.after !== after) throw new LinkStop("PAGING_NOT_FORWARD");
4387
+ if (first === null) first = page;
4388
+ else if (page.list !== void 0) throw new LinkStop("LIST_ON_LATER_PAGE");
4389
+ let last = after;
4390
+ for (const member of page.members) {
4391
+ if (member.number <= last) throw new LinkStop("PAGING_NOT_FORWARD");
4392
+ last = member.number;
4393
+ members.push(member);
4394
+ if (members.length > SHARED_RECORD_LIST_MAX_V1) throw new LinkStop("RECORDS_NOT_LIST");
4395
+ }
4396
+ const next = page.page.next;
4397
+ if (next === null) break;
4398
+ if (page.members.length === 0 || next < last || next <= after) throw new LinkStop("PAGING_NOT_FORWARD");
4399
+ after = next;
4400
+ }
4401
+ let rows = null;
4402
+ if (first.list !== void 0) {
4403
+ try {
4404
+ rows = readSharedRecordListV1(first.list.rows);
4405
+ } catch {
4406
+ throw new LinkStop("LIST_INVALID");
4407
+ }
4408
+ if (!isCanonicalRevealTermsV1(first.list.reveal)) throw new LinkStop("LIST_INVALID");
4409
+ }
4410
+ return { first, members, rows };
4411
+ }
4412
+ var ROW_FIELDS = ["number", "recordKey", "chainId", "contractAddress", "lastSeq", "lastSeal"];
4413
+ function recordsAreList(members, rows) {
4414
+ if (members.length !== rows.length) return false;
4415
+ return rows.every((row, i) => ROW_FIELDS.every((field) => members[i][field] === row[field]));
4416
+ }
4417
+ function servedInstant(time) {
4418
+ if (typeof time !== "string") return null;
4419
+ const text = DAY.test(time) ? `${time}T23:59:59.999Z` : INSTANT.test(time) ? time : null;
4420
+ if (text === null) return null;
4421
+ const at = Date.parse(text);
4422
+ return Number.isFinite(at) ? at : null;
4423
+ }
4424
+ function readServedRecord(raw, row, layouts) {
4425
+ if (!isPlain3(raw) || raw.schema !== RECORD_SEAL_HISTORY_SCHEMA_V1) throw new RecordStop("HISTORY_INVALID");
4426
+ const verified = verifyRecordSealHistoryV1(raw, { layouts });
4427
+ if (verified.code === RECORDS_LAYOUT_NOT_READ) throw new RecordStop("LAYOUT_NOT_READ");
4428
+ if (!verified.schemaOk || !verified.digestOk || !verified.layoutOk) throw new RecordStop("HISTORY_INVALID");
4429
+ const history = raw;
4430
+ if (history.recordKey !== row.recordKey || history.chain.chainId !== row.chainId || history.chain.contractAddress !== row.contractAddress) {
4431
+ throw new RecordStop("HISTORY_OTHER_RECORD");
4432
+ }
4433
+ if (verified.perEntry.length !== history.entries.length) throw new RecordStop("HISTORY_INVALID");
4434
+ const bySeq = new Map(history.entries.map((e) => [e.seq, e]));
4435
+ const pending = /* @__PURE__ */ new Map();
4436
+ for (const p of history.pending) if (p.seq !== null) pending.set(p.seq, p.status);
4437
+ const failed = new Set(verified.perEntry.filter((e) => e.failedCheck !== null).map((e) => e.seq));
4438
+ for (let seq2 = 0; seq2 <= row.lastSeq; seq2 += 1) {
4439
+ if (!bySeq.has(seq2)) throw new RecordStop(pending.has(seq2) ? "ENTRY_NOT_COMMITTED" : "ENTRY_MISSING", seq2 + 1);
4440
+ if (failed.has(seq2)) throw new RecordStop("ENTRY_FAILED", seq2 + 1);
4441
+ }
4442
+ const close = bySeq.get(row.lastSeq);
4443
+ if (splitWordV1(close.newWord).sealTag !== row.lastSeal) throw new RecordStop("CLOSE_SEAL_DIFFERS", row.lastSeq + 1);
4444
+ const entries = [];
4445
+ let seq = 0;
4446
+ for (; bySeq.has(seq); seq += 1) {
4447
+ if (failed.has(seq)) throw new RecordStop("ENTRY_FAILED", seq + 1);
4448
+ const e = bySeq.get(seq);
4449
+ entries.push({ seq, previousWord: e.previousWord, newWord: e.newWord, batchId: e.batchId });
4450
+ }
4451
+ if (history.entries.some((e) => e.seq > seq)) throw new RecordStop("ENTRY_MISSING", seq + 1);
4452
+ let committingAfterClose = 0;
4453
+ for (const [at, status] of pending) if (at > row.lastSeq && status === "queued") committingAfterClose += 1;
4454
+ const times = new Map((history.ledger?.batches ?? []).map((b) => [b.batchId, servedInstant(b.blockTime)]));
4455
+ let latest = Number.NEGATIVE_INFINITY;
4456
+ for (const e of entries) {
4457
+ const at = times.get(e.batchId) ?? null;
4458
+ if (at === null) {
4459
+ latest = null;
4460
+ break;
4461
+ }
4462
+ latest = Math.max(latest, at);
4463
+ }
4464
+ return { history, entries, committingAfterClose, latest: latest === null ? null : new Date(latest).toISOString() };
4465
+ }
4466
+ function readLogWrites(raw, contractAddress) {
4467
+ if (!Array.isArray(raw)) return null;
4468
+ const byPlace = /* @__PURE__ */ new Map();
4469
+ const mirror = raw.length > 0 && raw.every((w) => isPlain3(w) && typeof w.consensusTimestamp === "string");
4470
+ for (const w of raw) {
4471
+ if (!isPlain3(w)) return null;
4472
+ const previousWord = typeof w.previousWord === "string" ? w.previousWord.toLowerCase() : "";
4473
+ const newWord = typeof w.newWord === "string" ? w.newWord.toLowerCase() : "";
4474
+ if (!HEX323.test(previousWord) || !HEX323.test(newWord)) return null;
4475
+ if (w.contractAddress !== void 0 && String(w.contractAddress).toLowerCase() !== contractAddress) return null;
4476
+ const index = w.logIndex;
4477
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return null;
4478
+ let at;
4479
+ if (mirror) {
4480
+ const stamp = w.consensusTimestamp;
4481
+ if (!CONSENSUS.test(stamp)) return null;
4482
+ const [seconds, nanos] = stamp.split(".");
4483
+ at = BigInt(seconds) * 1000000000n + BigInt(nanos);
4484
+ } else {
4485
+ if (typeof w.blockNumber !== "number" || !Number.isSafeInteger(w.blockNumber) || w.blockNumber < 0) return null;
4486
+ at = BigInt(w.blockNumber);
4487
+ }
4488
+ const place = `${at}:${index}`;
4489
+ const seen = byPlace.get(place);
4490
+ if (seen) {
4491
+ if (seen.previousWord !== previousWord || seen.newWord !== newWord) return null;
4492
+ continue;
4493
+ }
4494
+ const hash = typeof w.transactionHash === "string" ? w.transactionHash.toLowerCase() : "";
4495
+ byPlace.set(place, {
4496
+ previousWord,
4497
+ newWord,
4498
+ committedAt: typeof w.committedAt === "string" && ISO_INSTANT.test(w.committedAt) ? w.committedAt : null,
4499
+ transactionHash: HEX323.test(hash) ? hash : null,
4500
+ at,
4501
+ index
4502
+ });
4503
+ }
4504
+ return [...byPlace.values()].sort((a, b) => a.at < b.at ? -1 : a.at > b.at ? 1 : a.index - b.index);
4505
+ }
4506
+ function holdToLog(entries, log, whole) {
4507
+ const isEntry = (w, e) => w.previousWord === e.previousWord && w.newWord === e.newWord;
4508
+ const anchor = log.findIndex((w) => entries.some((e) => isEntry(w, e)));
4509
+ if (anchor === -1) {
4510
+ if (whole) throw new RecordStop("ENTRY_NOT_WRITTEN", 1);
4511
+ throw new RecordStop("BUDGET_SPENT");
4512
+ }
4513
+ const start = entries.findIndex((e) => isEntry(log[anchor], e));
4514
+ if (anchor > 0) throw new RecordStop(start === 0 ? "WRITE_BEFORE_FIRST" : "WRITE_NOT_SERVED", start === 0 ? null : start);
4515
+ const writes = /* @__PURE__ */ new Map();
4516
+ let at = 0;
4517
+ for (let i = start; i < entries.length; i += 1, at += 1) {
4518
+ if (at >= log.length) throw new RecordStop("ENTRY_NOT_WRITTEN", entries[i].seq + 1);
4519
+ if (!isEntry(log[at], entries[i])) throw new RecordStop("WRITE_NOT_SERVED", entries[i].seq + 1);
4520
+ writes.set(entries[i].seq, log[at]);
4521
+ }
4522
+ const held = /* @__PURE__ */ new Set([ZERO_WORD, ...entries.map((e) => e.newWord)]);
4523
+ let before = entries[entries.length - 1].newWord;
4524
+ let laterWrites = 0;
4525
+ for (; at < log.length; at += 1) {
4526
+ const w = log[at];
4527
+ if (w.previousWord !== before || held.has(w.newWord)) throw new RecordStop("RECORD_SET_BACK");
4528
+ held.add(w.newWord);
4529
+ before = w.newWord;
4530
+ laterWrites += 1;
4531
+ }
4532
+ if (start > 0) {
4533
+ throw new RecordStop(whole ? "ENTRY_NOT_WRITTEN" : "BUDGET_SPENT", whole ? 1 : null);
4534
+ }
4535
+ return { writes, laterWrites };
4536
+ }
4537
+ function sourceStateOf(run, row) {
4538
+ const key = `${row.chainId}:${row.contractAddress}`;
4539
+ let state = run.sources.get(key);
4540
+ if (!state) {
4541
+ state = { unanswered: 0, wholeLog: null };
4542
+ run.sources.set(key, state);
4543
+ }
4544
+ return state;
4545
+ }
4546
+ function readerFor(run, row) {
4547
+ const key = `${row.chainId}:${row.contractAddress}`;
4548
+ if (!run.readers.has(key)) {
4549
+ let made = null;
4550
+ try {
4551
+ made = run.input.proofLayer({ chainId: row.chainId, contractAddress: row.contractAddress });
4552
+ } catch {
4553
+ made = null;
4554
+ }
4555
+ run.readers.set(key, made);
4556
+ }
4557
+ return run.readers.get(key) ?? null;
4558
+ }
4559
+ function emptyRecord(row) {
4560
+ return {
4561
+ number: row.number,
4562
+ recordKey: row.recordKey,
4563
+ chainId: row.chainId,
4564
+ contractAddress: row.contractAddress,
4565
+ status: "not-checked",
4566
+ code: null,
4567
+ failedEntry: null,
4568
+ closeEntry: row.lastSeq + 1,
4569
+ entries: [],
4570
+ committingAfterClose: 0,
4571
+ laterWrites: 0,
4572
+ changedSince: false,
4573
+ fields: { status: "none", entries: [] },
4574
+ source: null,
4575
+ requests: 0
4576
+ };
4577
+ }
4578
+ function rootFor(run, row, layer, batchId) {
4579
+ const key = `${row.chainId}:${row.contractAddress}:${batchId}`;
4580
+ let root = run.roots.get(key);
4581
+ if (!root) {
4582
+ if (run.left < 1) return Promise.resolve(null);
4583
+ run.left -= 1;
4584
+ run.spent += 1;
4585
+ root = readChainRootsV1(layer.reader, [batchId]).then((read) => read.chainRoots[String(batchId)] ?? null);
4586
+ run.roots.set(key, root);
4587
+ }
4588
+ return root;
4589
+ }
4590
+ async function checkFields(run, row, served, given, layer) {
4591
+ const none = (status, stop = null) => ({ fields: { status, entries: [] }, stop, disclosure: null });
4592
+ if (given.kind === "none") return none("none");
4593
+ if (given.kind === "not-opened") return none("not-opened");
4594
+ if (given.kind === "not-read") return none("not-checked", new RecordStop("REVEALS_NOT_READ"));
4595
+ if (given.disclosure === null) return none("fails", new RecordStop(given.served ? "REVEAL_NOT_OPENED" : "REVEAL_MISSING"));
4596
+ const disclosure = given.disclosure;
4597
+ const fails = { fields: { status: "fails", entries: [] }, stop: new RecordStop("FIELDS_DO_NOT_MATCH"), disclosure };
4598
+ if (!isPlain3(disclosure) || typeof disclosure.recordKey !== "string" || disclosure.recordKey.toLowerCase() !== row.recordKey) return fails;
4599
+ let form;
4600
+ try {
4601
+ form = disclosureFormOfV1(served.history, disclosure);
4602
+ } catch {
4603
+ form = null;
4604
+ }
4605
+ if (!form) return fails;
4606
+ if (!layer) return { fields: { status: "not-checked", entries: [] }, stop: new RecordStop("SOURCE_UNKNOWN"), disclosure };
4607
+ const chainRoots = {};
4608
+ for (const batchId of new Set(form.entries.map((e) => e.batchId))) {
4609
+ const root = await rootFor(run, row, layer, batchId);
4610
+ if (root === null) return { fields: { status: "not-checked", entries: [] }, stop: new RecordStop("ROOT_NOT_READ"), disclosure };
4611
+ chainRoots[String(batchId)] = root;
4612
+ }
4613
+ let result;
4614
+ try {
4615
+ result = await verifyRecordDisclosureV1({ form, chainRoots, disclosure });
4616
+ } catch {
4617
+ return fails;
4618
+ }
4619
+ if (!result.ok) return { ...fails, stop: new RecordStop("FIELDS_DO_NOT_MATCH", result.seq === null ? null : result.seq + 1) };
4620
+ const entries = result.entries.map((e) => ({ entry: e.seq + 1, fields: e.fields.map((f) => ({ pointer: f.pointer, value: f.value })), withheld: e.withheld }));
4621
+ return { fields: { status: "matches", entries }, stop: null, disclosure };
4622
+ }
4623
+ async function checkRecord(run, row, given, kept) {
4624
+ const { input } = run;
4625
+ const out = emptyRecord(row);
4626
+ const keep = kept ? { number: row.number, sealHistory: null, disclosure: null } : null;
4627
+ if (keep) kept.push(keep);
4628
+ let grant = 0;
4629
+ let used = 0;
4630
+ let read = false;
4631
+ let fieldsStop = null;
4632
+ const stopWith = (stop) => {
4633
+ const status = RECORD_CODE_STATUS[stop.code];
4634
+ if (out.code !== null && !(out.status === "not-checked" && status === "fails")) return;
4635
+ out.status = status;
4636
+ out.code = stop.code;
4637
+ out.failedEntry = stop.entry;
4638
+ };
4639
+ try {
4640
+ let raw;
4641
+ try {
4642
+ raw = await input.source.seals(row.number);
4643
+ } catch (error) {
4644
+ throw new RecordStop(answerErrorOf(error) === "refused" ? "HISTORY_NOT_SERVED" : "HISTORY_NOT_READ");
4645
+ }
4646
+ if (keep && isPlain3(raw) && raw.schema === RECORD_SEAL_HISTORY_SCHEMA_V1) keep.sealHistory = raw;
4647
+ const served = readServedRecord(raw, row, input.layouts);
4648
+ out.committingAfterClose = served.committingAfterClose;
4649
+ out.entries = served.entries.map((e) => ({ entry: e.seq + 1, afterClose: e.seq > row.lastSeq, committedAt: null, transactionHash: null }));
4650
+ const layer = readerFor(run, row);
4651
+ out.source = layer?.source ?? null;
4652
+ const fields = await checkFields(run, row, served, given, layer);
4653
+ out.fields = fields.fields;
4654
+ fieldsStop = fields.stop;
4655
+ if (keep) keep.disclosure = fields.disclosure;
4656
+ if (!layer) throw new RecordStop("SOURCE_UNKNOWN");
4657
+ const state = sourceStateOf(run, row);
4658
+ if (state.unanswered >= SHARED_RECORD_CHECK_UNANSWERED_V1) throw new RecordStop("SOURCE_NOT_READ");
4659
+ grant = Math.max(0, Math.min(run.budget.recordRequests, run.left));
4660
+ run.left -= grant;
4661
+ if (grant < 1) throw new RecordStop("BUDGET_SPENT");
4662
+ let log = null;
4663
+ let whole = false;
4664
+ let cutOff2 = false;
4665
+ let logStop = null;
4666
+ if (input.full) {
4667
+ whole = true;
4668
+ if (state.wholeLog !== null) {
4669
+ logStop = state.wholeLog;
4670
+ } else {
4671
+ try {
4672
+ log = readLogWrites(await layer.reader.getRecordWrites(row.recordKey), row.contractAddress);
4673
+ if (log === null) logStop = "SOURCE_NOT_READ";
4674
+ } catch (error) {
4675
+ const refusal = mirrorRefusalOf(error);
4676
+ logStop = refusal === "too-slow" || refusal === "too-long" ? "LOG_PAST_BOUNDS" : "SOURCE_NOT_READ";
4677
+ state.wholeLog = logStop;
4678
+ }
4679
+ }
4680
+ } else if (!layer.reader.findRecordWrites) {
4681
+ logStop = "SOURCE_NOT_READ";
4682
+ } else if (grant < 2) {
4683
+ logStop = "BUDGET_SPENT";
4684
+ } else {
4685
+ let asked = 0;
4686
+ try {
4687
+ const search = await layer.reader.findRecordWrites(row.recordKey, {
4688
+ startAt: served.latest,
4689
+ done: (writes) => writes.some((w) => typeof w?.previousWord === "string" && w.previousWord.toLowerCase() === ZERO_WORD),
4690
+ budgetMs: run.budget.recordMs,
4691
+ maxRequests: grant - 1,
4692
+ wholeWindows: true,
4693
+ waitOut: { times: SHARED_RECORD_CHECK_WAITS_V1, waitMs: 1e3, maxWaitMs: 1e4, ...input.sleep ? { sleep: input.sleep } : {} },
4694
+ onRequest: () => {
4695
+ asked += 1;
4696
+ },
4697
+ ...input.now ? { now: input.now } : {}
4698
+ });
4699
+ if (asked === 0 && Number.isSafeInteger(search.requests) && search.requests > 0) asked = search.requests;
4700
+ log = readLogWrites(search.writes, row.contractAddress);
4701
+ if (log === null) logStop = "SOURCE_NOT_READ";
4702
+ whole = search.ended === "done";
4703
+ cutOff2 = search.ended === "timeout";
4704
+ } catch {
4705
+ logStop = "SOURCE_NOT_READ";
4706
+ state.unanswered += 1;
4707
+ }
4708
+ used += asked;
4709
+ }
4710
+ if (logStop === "SOURCE_NOT_READ") throw new RecordStop(logStop);
4711
+ if (logStop !== null) stopWith(new RecordStop(logStop));
4712
+ if (log !== null) {
4713
+ let held = null;
4714
+ try {
4715
+ held = holdToLog(served.entries, log, whole);
4716
+ } catch (error) {
4717
+ if (!(error instanceof RecordStop)) throw error;
4718
+ stopWith(error.code === "BUDGET_SPENT" && cutOff2 ? new RecordStop("SOURCE_NOT_READ") : error);
4719
+ }
4720
+ if (held) {
4721
+ out.laterWrites = held.laterWrites;
4722
+ for (const entry of out.entries) {
4723
+ const write = held.writes.get(entry.entry - 1);
4724
+ if (write) {
4725
+ entry.committedAt = write.committedAt;
4726
+ entry.transactionHash = write.transactionHash;
4727
+ }
4728
+ }
4729
+ }
4730
+ }
4731
+ let current;
4732
+ try {
4733
+ used += 1;
4734
+ current = String(await layer.reader.getRecord(row.recordKey)).toLowerCase();
4735
+ } catch {
4736
+ state.unanswered += 1;
4737
+ throw new RecordStop("SOURCE_NOT_READ");
4738
+ }
4739
+ state.unanswered = 0;
4740
+ if (!HEX323.test(current)) throw new RecordStop("SOURCE_NOT_READ");
4741
+ const last = served.entries[served.entries.length - 1];
4742
+ out.changedSince = current !== last.newWord;
4743
+ if (current === ZERO_WORD) throw new RecordStop("CURRENT_WORD_ZERO");
4744
+ if (served.entries.some((e) => e !== last && e.newWord === current)) throw new RecordStop("CURRENT_WORD_EARLIER");
4745
+ read = true;
4746
+ } catch (error) {
4747
+ if (error instanceof RecordStop) stopWith(error);
4748
+ else stopWith(new RecordStop("SOURCE_NOT_READ"));
4749
+ }
4750
+ if (fieldsStop) stopWith(fieldsStop);
4751
+ if (read && out.code === null) out.status = "matches";
4752
+ out.requests = used;
4753
+ run.spent += used;
4754
+ run.left += Math.max(0, grant - used);
4755
+ return out;
4756
+ }
4757
+ async function readReveals(input, rows, handle) {
4758
+ const onList = new Map(rows.map((row) => [row.number, row]));
4759
+ const out = /* @__PURE__ */ new Map();
4760
+ let after = 0;
4761
+ for (; ; ) {
4762
+ let raw;
4763
+ try {
4764
+ raw = await input.source.reveals(after);
4765
+ } catch {
4766
+ return "not-read";
4767
+ }
4768
+ if (!isPlain3(raw) || !Array.isArray(raw.reveals) || !isPlain3(raw.page)) throw new LinkStop("REVEALS_INVALID");
4769
+ const { next } = raw.page;
4770
+ let last = after;
4771
+ let lastEpoch = 0;
4772
+ for (const reveal of raw.reveals) {
4773
+ if (!isPlain3(reveal) || !Number.isSafeInteger(reveal.number) || !Number.isSafeInteger(reveal.epoch) || typeof reveal.envelope !== "string") throw new LinkStop("REVEALS_INVALID");
4774
+ const number = reveal.number;
4775
+ const epoch = reveal.epoch;
4776
+ if (number < last || number === last && epoch <= lastEpoch) throw new LinkStop("PAGING_NOT_FORWARD");
4777
+ if (number === after) throw new LinkStop("PAGING_NOT_FORWARD");
4778
+ last = number;
4779
+ lastEpoch = epoch;
4780
+ const row = onList.get(number);
4781
+ if (!row) throw new LinkStop("REVEAL_OFF_LIST");
4782
+ const seen = out.get(number);
4783
+ if (seen?.kind === "opened" && seen.disclosure !== null) continue;
4784
+ let disclosure = null;
4785
+ try {
4786
+ const opened = await openRevealV1({ envelope: reveal.envelope, linkKey: input.linkKey, handle, epoch, recordKey: row.recordKey });
4787
+ if (opened.ok) disclosure = opened.disclosure;
4788
+ } catch {
4789
+ disclosure = null;
4790
+ }
4791
+ out.set(number, { kind: "opened", disclosure, served: true });
4792
+ }
4793
+ if (next === null) break;
4794
+ if (!Number.isSafeInteger(next) || raw.reveals.length === 0 || next < last || next <= after) throw new LinkStop("PAGING_NOT_FORWARD");
4795
+ after = next;
4796
+ }
4797
+ return out;
4798
+ }
4799
+ var statusOf = (records2, collection) => {
4800
+ if (collection === "fails" || records2.some((r) => r.status === "fails")) return "fails";
4801
+ if (collection !== "matches" || records2.length === 0 || records2.some((r) => r.status !== "matches")) return "not-checked";
4802
+ return "matches";
4803
+ };
4804
+ async function checkSharedRecordV1(input) {
4805
+ const budget = {
4806
+ recordRequests: input.budget?.recordRequests ?? SHARED_RECORD_CHECK_RECORD_REQUESTS_V1,
4807
+ runRequests: input.budget?.runRequests ?? SHARED_RECORD_CHECK_RUN_REQUESTS_V1,
4808
+ recordMs: input.budget?.recordMs ?? SHARED_RECORD_CHECK_RECORD_MS_V1
4809
+ };
4810
+ const run = { input, budget, left: Math.max(0, budget.runRequests), spent: 0, readers: /* @__PURE__ */ new Map(), roots: /* @__PURE__ */ new Map(), sources: /* @__PURE__ */ new Map() };
4811
+ const result = {
4812
+ schema: SHARED_RECORD_CHECK_SCHEMA_V1,
4813
+ status: "not-checked",
4814
+ code: null,
4815
+ mode: input.full ? "full" : "default",
4816
+ collection: { status: "not-checked", records: 0 },
4817
+ cover: null,
4818
+ reveal: null,
4819
+ fields: "none",
4820
+ counts: { records: 0, matches: 0, fails: 0, notChecked: 0 },
4821
+ records: [],
4822
+ sources: [],
4823
+ requests: 0
4824
+ };
4825
+ const stop = (code) => {
4826
+ result.code = code;
4827
+ result.status = LINK_CODE_STATUS[code];
4828
+ if (result.status === "fails") result.collection.status = "fails";
4829
+ return result;
4830
+ };
4831
+ let manifest;
4832
+ try {
4833
+ manifest = await readManifest(input.source);
4834
+ } catch (error) {
4835
+ return stop(error instanceof LinkStop ? error.code : "MANIFEST_NOT_READ");
4836
+ }
4837
+ const { first, members, rows } = manifest;
4838
+ if (typeof first.reference === "string" && typeof first.organization === "string" && typeof first.sharedOn === "string" && typeof first.link?.endsOn === "string") {
4839
+ result.cover = { reference: first.reference, organization: first.organization, sharedOn: first.sharedOn, endsOn: first.link.endsOn };
4840
+ }
4841
+ const listAddress = input.handle !== null && hasListHandlePrefixV1(input.handle);
4842
+ if (rows === null || first.list === void 0) return stop(listAddress ? "LINK_NOT_A_LIST" : "LINK_HAS_NO_LIST");
4843
+ const list = first.list;
4844
+ result.collection.records = rows.length;
4845
+ result.counts.records = rows.length;
4846
+ result.reveal = { mode: list.reveal.mode, fields: [...list.reveal.fields], time: list.reveal.time };
4847
+ if (!sameTerms(first.reveal, list.reveal)) return stop("TERMS_DIFFER");
4848
+ if (input.handle !== null && !sharedRecordHandleNamesListV1(input.handle, list)) return stop("LIST_NOT_ADDRESS");
4849
+ if (!recordsAreList(members, rows)) return stop("RECORDS_NOT_LIST");
4850
+ result.collection.status = input.handle === null ? "not-compared" : "matches";
4851
+ const reveals = revealsFieldsV1(list.reveal);
4852
+ let given;
4853
+ if (!reveals) {
4854
+ given = async () => ({ kind: "none" });
4855
+ } else if (input.source.disclosure) {
4856
+ result.fields = "opened";
4857
+ given = async (number) => {
4858
+ try {
4859
+ const disclosure = await input.source.disclosure(number);
4860
+ return { kind: "opened", disclosure: disclosure ?? null, served: false };
4861
+ } catch {
4862
+ return { kind: "not-read" };
4863
+ }
4864
+ };
4865
+ } else if (input.linkKey && input.source.reveals && input.handle !== null) {
4866
+ let read;
4867
+ try {
4868
+ read = await readReveals(input, rows, input.handle);
4869
+ } catch (error) {
4870
+ return stop(error instanceof LinkStop ? error.code : "REVEALS_INVALID");
4871
+ }
4872
+ const all = read;
4873
+ result.fields = all === "not-read" ? "not-read" : "opened";
4874
+ given = async (number) => all === "not-read" ? { kind: "not-read" } : all.get(number) ?? { kind: "opened", disclosure: null, served: false };
4875
+ } else {
4876
+ result.fields = "not-opened";
4877
+ given = async () => ({ kind: "not-opened" });
4878
+ }
4879
+ const kept = input.keep ? [] : null;
4880
+ const records2 = new Array(rows.length);
4881
+ let next = 0;
4882
+ let done = 0;
4883
+ const worker = async () => {
4884
+ for (; ; ) {
4885
+ const at = next;
4886
+ next += 1;
4887
+ if (at >= rows.length) return;
4888
+ const row = rows[at];
4889
+ let record;
4890
+ try {
4891
+ record = await checkRecord(run, row, await given(row.number), kept);
4892
+ } catch {
4893
+ record = { ...emptyRecord(row), code: "SOURCE_NOT_READ" };
4894
+ }
4895
+ records2[at] = record;
4896
+ done += 1;
4897
+ try {
4898
+ input.onRecord?.(record, { done, of: rows.length });
4899
+ } catch {
4900
+ }
4901
+ if (input.pause) await input.pause().catch(() => void 0);
4902
+ }
4903
+ };
4904
+ const inFlight = Math.max(1, Math.min(8, Math.floor(input.inFlight ?? 1)));
4905
+ await Promise.all(Array.from({ length: Math.min(inFlight, rows.length) }, worker));
4906
+ result.records = records2;
4907
+ result.counts.matches = records2.filter((r) => r.status === "matches").length;
4908
+ result.counts.fails = records2.filter((r) => r.status === "fails").length;
4909
+ result.counts.notChecked = records2.filter((r) => r.status === "not-checked").length;
4910
+ result.requests = run.spent;
4911
+ const sources = /* @__PURE__ */ new Map();
4912
+ for (const row of rows) {
4913
+ const key = `${row.chainId}:${row.contractAddress}`;
4914
+ const at = sources.get(key);
4915
+ if (at) at.records += 1;
4916
+ else sources.set(key, { chainId: row.chainId, contractAddress: row.contractAddress, source: run.readers.get(key)?.source ?? null, records: 1 });
4917
+ }
4918
+ result.sources = [...sources.values()];
4919
+ result.status = statusOf(records2, result.collection.status === "not-compared" ? "matches" : result.collection.status);
4920
+ if (kept) {
4921
+ const byNumber = new Map(kept.map((k) => [k.number, k]));
4922
+ result.kept = {
4923
+ manifest: { ...first, members, page: { after: 0, next: null } },
4924
+ records: rows.map((row) => byNumber.get(row.number) ?? { number: row.number, sealHistory: null, disclosure: null }),
4925
+ fields: result.fields === "not-read" ? "not-opened" : result.fields
4926
+ };
4927
+ }
4928
+ return result;
4929
+ }
4930
+
4931
+ // ../shared/src/records/shared-record-pace-v1.ts
4932
+ var SHARED_RECORD_CHECK_SOURCE_PACE_V1 = 25;
4933
+ var originOf = (input) => {
4934
+ try {
4935
+ return new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).origin;
4936
+ } catch {
4937
+ return "";
4938
+ }
4939
+ };
4940
+ var cutOff = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
4941
+ function unlessCutOff(wait, signal) {
4942
+ if (!signal) return wait;
4943
+ if (signal.aborted) return Promise.reject(cutOff(signal));
4944
+ return new Promise((resolve3, reject) => {
4945
+ const onAbort = () => reject(cutOff(signal));
4946
+ signal.addEventListener("abort", onAbort, { once: true });
4947
+ wait.then(resolve3, reject).finally(() => signal.removeEventListener("abort", onAbort));
4948
+ });
4949
+ }
4950
+ function sharedRecordPacedFetchV1(fetchImpl = fetch, options = {}) {
4951
+ const perSecond = options.perSecond ?? SHARED_RECORD_CHECK_SOURCE_PACE_V1;
4952
+ if (!Number.isFinite(perSecond) || perSecond <= 0) throw new RangeError("a pace is a number of requests a second above zero");
4953
+ const gap = 1e3 / perSecond;
4954
+ const now = options.now ?? Date.now;
4955
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve3) => setTimeout(resolve3, ms)));
4956
+ const turns = /* @__PURE__ */ new Map();
4957
+ let read = -Infinity;
4958
+ const paced = async (input, init) => {
4959
+ if (init?.signal?.aborted) throw cutOff(init.signal);
4960
+ const origin = originOf(input);
4961
+ const at = now();
4962
+ if (at < read) for (const [key, owed] of turns) turns.set(key, owed - (read - at));
4963
+ read = at;
4964
+ const turn = Math.max(at, turns.get(origin) ?? -Infinity);
4965
+ turns.set(origin, turn + gap);
4966
+ if (turn > at) await unlessCutOff(sleep(turn - at), init?.signal);
4967
+ return fetchImpl(input, init);
4968
+ };
4969
+ return paced;
4970
+ }
4971
+
4972
+ // ../shared/src/records/shared-record-copy-v1.ts
4973
+ var import_ethers16 = require("ethers");
4974
+ var SHARED_RECORD_COPY_SCHEMA_V1 = "shared-record-copy/v1";
4975
+ var SHARED_RECORD_COPY_MAX_BYTES_V1 = 67108864;
4976
+ var SHARED_RECORD_COPY_SALT_LABEL_V1 = "pacspace:shared-record-copy-salt:v1";
4977
+ var SharedRecordCopyError = class extends Error {
4978
+ constructor(code) {
4979
+ super(code);
4980
+ this.code = code;
4981
+ this.name = "SharedRecordCopyError";
4982
+ }
4983
+ };
4984
+ var HEX_64_BARE2 = /^[0-9a-f]{64}$/;
4985
+ var COPY_KEYS = ["schema", "manifest", "list", "records", "fields"];
4986
+ var LIST_KEYS = ["reveal", "maskedSalt", "rows"];
4987
+ var RECORD_KEYS = ["number", "sealHistory", "disclosure"];
4988
+ var FIELDS2 = ["none", "not-opened", "opened"];
4989
+ var isPlain4 = (v) => !!v && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
4990
+ var hasExactly4 = (v, keys) => Object.keys(v).length === keys.length && keys.every((k) => Object.prototype.hasOwnProperty.call(v, k));
4991
+ function listBodyOf(handle) {
4992
+ const parts = typeof handle === "string" ? linkHandlePartsV1(handle) : null;
4993
+ return parts && parts.prefix === LIST_HANDLE_PREFIX ? parts.body : null;
4994
+ }
4995
+ function maskSharedRecordSaltV1(salt, handle) {
4996
+ const body = listBodyOf(handle);
4997
+ if (body === null) throw new SharedRecordCopyError("SHARED_RECORD_COPY_ADDRESS");
4998
+ if (typeof salt !== "string" || !HEX_64_BARE2.test(salt)) throw new SharedRecordCopyError("SHARED_RECORD_COPY_MALFORMED");
4999
+ const mask = import_ethers16.ethers.getBytes(import_ethers16.ethers.sha256(import_ethers16.ethers.concat([import_ethers16.ethers.toUtf8Bytes(SHARED_RECORD_COPY_SALT_LABEL_V1), Uint8Array.of(0), import_ethers16.ethers.toUtf8Bytes(body)])));
5000
+ const bytes2 = import_ethers16.ethers.getBytes(`0x${salt}`);
5001
+ return import_ethers16.ethers.hexlify(bytes2.map((b, i) => b ^ mask[i])).slice(2);
5002
+ }
5003
+ function buildSharedRecordCopyV1(input) {
5004
+ const malformed = () => new SharedRecordCopyError("SHARED_RECORD_COPY_MALFORMED");
5005
+ const { kept } = input;
5006
+ if (!isPlain4(kept) || !isPlain4(kept.manifest) || !Array.isArray(kept.records) || !FIELDS2.includes(kept.fields)) throw malformed();
5007
+ const { list, ...manifest } = kept.manifest;
5008
+ if (!isPlain4(list) || !isCanonicalRevealTermsV1(list.reveal)) throw malformed();
5009
+ let rows;
5010
+ try {
5011
+ rows = readSharedRecordListV1(list.rows);
5012
+ } catch {
5013
+ throw malformed();
5014
+ }
5015
+ if (kept.records.length !== rows.length || kept.records.some((r, i) => !isPlain4(r) || r.number !== rows[i].number)) throw malformed();
5016
+ const copy = {
5017
+ schema: SHARED_RECORD_COPY_SCHEMA_V1,
5018
+ manifest: { ...manifest, page: { after: 0, next: null } },
5019
+ list: { reveal: { mode: list.reveal.mode, fields: [...list.reveal.fields], time: list.reveal.time }, maskedSalt: maskSharedRecordSaltV1(list.salt, input.handle), rows },
5020
+ records: kept.records.map((r) => ({ number: r.number, sealHistory: r.sealHistory ?? null, disclosure: kept.fields === "opened" ? r.disclosure ?? null : null })),
5021
+ fields: kept.fields
5022
+ };
5023
+ if (!readSharedRecordCopyV1(copy).ok) throw malformed();
5024
+ const bytes2 = import_ethers16.ethers.toUtf8Bytes(canonicalizeJcs(copy));
5025
+ if (bytes2.length > SHARED_RECORD_COPY_MAX_BYTES_V1) throw new SharedRecordCopyError("SHARED_RECORD_COPY_TOO_LARGE");
5026
+ return { copy, bytes: bytes2, byteLength: bytes2.length };
5027
+ }
5028
+ function readSharedRecordCopyV1(json) {
5029
+ const refuse5 = { ok: false, code: "SHARED_RECORD_COPY_MALFORMED" };
5030
+ if (!isPlain4(json) || !hasExactly4(json, COPY_KEYS) || json.schema !== SHARED_RECORD_COPY_SCHEMA_V1) return refuse5;
5031
+ const { manifest, list, records: records2, fields } = json;
5032
+ if (!isPlain4(manifest) || manifest.schema !== SHARED_RECORD_SCHEMA_V2 || manifest.list !== void 0) return refuse5;
5033
+ if (sharedRecordV2KeyProblems(manifest).length > 0 || !Array.isArray(manifest.members)) return refuse5;
5034
+ if (!isPlain4(manifest.page) || manifest.page.after !== 0 || manifest.page.next !== null) return refuse5;
5035
+ if (!isPlain4(list) || !hasExactly4(list, LIST_KEYS) || !isCanonicalRevealTermsV1(list.reveal)) return refuse5;
5036
+ if (typeof list.maskedSalt !== "string" || !HEX_64_BARE2.test(list.maskedSalt)) return refuse5;
5037
+ let rows;
5038
+ try {
5039
+ rows = readSharedRecordListV1(list.rows);
5040
+ } catch {
5041
+ return refuse5;
5042
+ }
5043
+ if (typeof fields !== "string" || !FIELDS2.includes(fields)) return refuse5;
5044
+ if (fields === "none" !== !revealsFieldsV1(list.reveal)) return refuse5;
5045
+ if (!Array.isArray(records2) || records2.length !== rows.length) return refuse5;
5046
+ for (let i = 0; i < rows.length; i += 1) {
5047
+ const r = records2[i];
5048
+ if (!isPlain4(r) || !hasExactly4(r, RECORD_KEYS) || r.number !== rows[i].number) return refuse5;
5049
+ if (r.sealHistory !== null && (!isPlain4(r.sealHistory) || r.sealHistory.schema !== RECORD_SEAL_HISTORY_SCHEMA_V1)) return refuse5;
5050
+ if (r.disclosure !== null && (!isPlain4(r.disclosure) || fields !== "opened")) return refuse5;
5051
+ }
5052
+ return { ok: true, copy: json };
5053
+ }
5054
+ function sharedRecordCopySourceV1(copy, handle) {
5055
+ if (handle !== null && listBodyOf(handle) === null) throw new SharedRecordCopyError("SHARED_RECORD_COPY_ADDRESS");
5056
+ const salt = handle === null ? copy.list.maskedSalt : maskSharedRecordSaltV1(copy.list.maskedSalt, handle);
5057
+ const byNumber = new Map(copy.records.map((r) => [r.number, r]));
5058
+ const source = {
5059
+ async page(after) {
5060
+ if (after !== 0) throw new SharedRecordAnswerError("refused");
5061
+ return { ...copy.manifest, list: { reveal: copy.list.reveal, salt, rows: copy.list.rows }, page: { after: 0, next: null } };
5062
+ },
5063
+ async seals(number) {
5064
+ const history = byNumber.get(number)?.sealHistory ?? null;
5065
+ if (history === null) throw new SharedRecordAnswerError("unreachable");
5066
+ return history;
5067
+ }
5068
+ };
5069
+ if (copy.fields === "opened") source.disclosure = async (number) => byNumber.get(number)?.disclosure ?? null;
5070
+ return { handle, source };
5071
+ }
5072
+
5073
+ // src/report.ts
5074
+ var REPORT_SCHEMA = "pacspace-check-report/v1";
5075
+ var SOURCE_REFUSAL_REASONS = {
5076
+ redirect: "its source answered with a redirect, which is not followed",
5077
+ "too-large": "its source gave an answer larger than this checker reads",
5078
+ "too-many-logs": "its source returned a longer page than was asked for",
5079
+ "next-page": "its source pointed somewhere else for the next page",
5080
+ "too-slow": "its source did not finish answering in the time allowed",
5081
+ "too-long": "it holds more than this checker reads in one run"
5082
+ };
5083
+ var ENCRYPTED_OPENED_SENTENCE = "Each entry was opened on this machine and matches its sealed record hash.";
5084
+ function refusedUnopenedSentence(k) {
5085
+ return `${k} refused ${entryWord(k)} could not be opened with this record key. Their seals are checked.`;
5086
+ }
5087
+ var HONESTY_SENTENCE = "The check shows the record is unchanged since it was committed. It does not show that what was recorded was true.";
5088
+ var SEALS_BOUNDARY_SENTENCE = "The check shows each seal was committed and that all of them are here, in order. It does not show what any entry says, or that what was recorded was true.";
5089
+ var FIELDS_FAILED_SENTENCE = "The revealed fields failed the check, so none are shown.";
5090
+ var ROOT_NOT_READ_SENTENCE = "The revealed fields could not be checked against the proof layer just now, so none are shown. Check again to try once more.";
5091
+ var TOO_LARGE_SENTENCE = "This file is too large to be a copy of this record.";
5092
+ var FILE_NOT_IN_RECORD_SENTENCE = "This file is not in the record.";
5093
+ var HELD_FILE_OFFLINE_SENTENCE = "The ledger was not read (--offline); the file you hold was matched against the history file only.";
5094
+ var MONTHS = [
5095
+ "January",
5096
+ "February",
5097
+ "March",
5098
+ "April",
5099
+ "May",
5100
+ "June",
5101
+ "July",
5102
+ "August",
5103
+ "September",
5104
+ "October",
5105
+ "November",
5106
+ "December"
5107
+ ];
5108
+ function dayOfUtc(value) {
5109
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value);
5110
+ if (!match) return value;
5111
+ const day = Number(match[3]);
5112
+ const month = MONTHS[Number(match[2]) - 1] ?? match[2];
5113
+ return `${day} ${month} ${match[1]}`;
5114
+ }
5115
+ function entryWord(count) {
5116
+ return count === 1 ? "entry" : "entries";
5117
+ }
5118
+ function listEntries(numbers) {
5119
+ const sorted = [...numbers].sort((a, b) => a - b);
5120
+ if (sorted.length === 1) return `Entry ${sorted[0]}`;
5121
+ const head = sorted.slice(0, -1).join(", ");
5122
+ return `Entries ${head} and ${sorted[sorted.length - 1]}`;
5123
+ }
5124
+ function entryWords(entries) {
5125
+ if (entries.length === 1) return `Entry ${entries[0]}`;
5126
+ if (entries.length === 2) return `Entries ${entries[0]} and ${entries[1]}`;
5127
+ return `Entries ${entries.slice(0, -1).join(", ")}, and ${entries[entries.length - 1]}`;
5128
+ }
5129
+ var isAre = (count) => count === 1 ? "is" : "are";
5130
+ function sameHex(a, b) {
5131
+ if (!a || !b) return false;
5132
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
5133
+ }
5134
+ function countedSentence(record) {
5135
+ const { entries, matched, missing, unmatched } = record;
5136
+ if (entries === null) {
5137
+ return `This file carries ${matched} ${entryWord(matched)} that match what was committed. The record's own count could not be read.`;
5138
+ }
5139
+ const parts = [`This record has ${entries} ${entryWord(entries)}.`];
5140
+ if (missing.length === 0 && unmatched.length === 0 && matched >= entries) {
5141
+ parts.push(
5142
+ entries === 1 ? "It is here, and it matches what was committed." : `All ${entries} are here, and all ${entries} match what was committed.`
5143
+ );
5144
+ return parts.join(" ");
5145
+ }
5146
+ parts.push(`${matched} of ${entries} match what was committed.`);
5147
+ if (unmatched.length) {
5148
+ parts.push(`${listEntries(unmatched)} ${unmatched.length === 1 ? "does" : "do"} not.`);
5149
+ }
5150
+ if (missing.length) {
5151
+ parts.push(`${listEntries(missing)} ${missing.length === 1 ? "is" : "are"} not in this file.`);
5152
+ }
5153
+ return parts.join(" ");
5154
+ }
5155
+ function sealsPassedSentence(n) {
5156
+ if (n === 1) return "This record has 1 entry. Its seal is here, and it is in what was committed.";
5157
+ return `This record has ${n} entries. All ${n} seals are here, in order, and each is in what was committed.`;
5158
+ }
5159
+ function sealsSettlingSentence(n, settling) {
5160
+ const m = n - settling.length;
5161
+ const tail = `${entryWords(settling)} ${isAre(settling.length)} still being recorded.`;
5162
+ if (m <= 0) return `This record has ${n} ${n === 1 ? "entry" : "entries"}. ${tail}`;
5163
+ if (m === 1) return `This record has ${n} entries. 1 of the ${n} seals is here, and it is in what was committed. ${tail}`;
5164
+ return `This record has ${n} entries. ${m} of the ${n} seals are here, in order, and each is in what was committed. ${tail}`;
5165
+ }
5166
+ function sealsFailedSentence(n, failed) {
5167
+ if (n === 1) return "This record has 1 entry. Its seal is not in what was committed.";
5168
+ const k = n - failed.length;
5169
+ return `This record has ${n} entries. ${k} of the ${n} seals ${isAre(k)} in what was committed. ${entryWords(failed)} ${failed.length === 1 ? "is not" : "are not"}.`;
5170
+ }
5171
+ function sealsMissingSentence(n, held, missing) {
5172
+ return `What was committed says this record has ${n} entries. This copy has ${held} of them. Entry ${missing} is not here.`;
5173
+ }
5174
+ function sealsFormFailedSentence(n) {
5175
+ return n === null ? "These seals do not match what was committed." : `This record has ${n} entries. These seals do not match what was committed.`;
5176
+ }
5177
+ function revealedLine(shown, total) {
5178
+ if (total === 1) return "The entry shows fields the sharer chose to reveal. Each shown field was checked against its seal.";
5179
+ if (shown >= total) return "Every entry shows fields the sharer chose to reveal. Each shown field was checked against its entry's seal.";
5180
+ return `${shown} of ${total} entries ${shown === 1 ? "shows" : "show"} fields the sharer chose to reveal. Each shown field was checked against its entry's seal.`;
5181
+ }
5182
+ function sealsVerdict(entries, v, queued = []) {
5183
+ if (v.nothingCommitted) {
5184
+ return {
5185
+ sentence: queued.length > 0 ? sealsSettlingSentence(queued.length, queued.map((seq) => seq + 1)) : v.reason,
5186
+ passed: false
5187
+ };
5188
+ }
5189
+ if (!v.schemaOk || !v.digestOk || !v.layoutOk || entries === null) {
3755
5190
  return { sentence: sealsFormFailedSentence(entries), passed: false };
3756
5191
  }
3757
5192
  if (v.failedSeq.length > 0) return { sentence: sealsFailedSentence(entries, v.failedSeq.map((seq) => seq + 1)), passed: false };
@@ -3812,7 +5247,7 @@ function statementFingerprintOf(given, intact, fingerprint) {
3812
5247
  function heldFileField(held) {
3813
5248
  return held ? { matched: held.matched, entries: held.entries, blinded: held.blinded } : void 0;
3814
5249
  }
3815
- function buildReport(input) {
5250
+ function buildReportWithFacts(input) {
3816
5251
  const history = input.verification.history;
3817
5252
  const matched = history?.verifiedRecords ?? 0;
3818
5253
  const entries = history?.expectedRecords ?? (history ? matched : null);
@@ -3830,7 +5265,7 @@ function buildReport(input) {
3830
5265
  exportedAt: input.exportedAt
3831
5266
  };
3832
5267
  const statementFingerprint = statementFingerprintOf(input.statementFingerprint, intact, file.fingerprint);
3833
- const passed = input.verification.verified && (input.source.compared ? input.source.matches : true);
5268
+ const entriesMatch = input.verification.verified && (input.source.compared ? input.source.matches : true);
3834
5269
  const sentences = [];
3835
5270
  if (!intact) {
3836
5271
  sentences.push(FILE_CHANGED_SENTENCE);
@@ -3848,16 +5283,16 @@ function buildReport(input) {
3848
5283
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3849
5284
  if (fingerprintLine) sentences.push(fingerprintLine);
3850
5285
  if (input.heldFile) sentences.push(...heldFileSentences(input.heldFile));
3851
- const failed = !passed || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
5286
+ const failed = !entriesMatch || input.dailyStatement?.matches === false || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3852
5287
  const unreachable = !input.source.compared && input.source.reason === "unreachable";
3853
5288
  const exitCode = exitCodeOf(unreachable, failed);
3854
5289
  if (closesWithBoundary(exitCode)) sentences.push(HONESTY_SENTENCE);
3855
- return {
5290
+ const report = {
3856
5291
  schema: REPORT_SCHEMA,
3857
5292
  checker: input.checker,
3858
5293
  ...input.form ? { form: input.form } : {},
3859
5294
  record,
3860
- passed,
5295
+ passed: exitCode === 0,
3861
5296
  file,
3862
5297
  source: input.source,
3863
5298
  dailyStatement: input.dailyStatement,
@@ -3867,8 +5302,9 @@ function buildReport(input) {
3867
5302
  sentences,
3868
5303
  exitCode
3869
5304
  };
5305
+ return { report, entriesMatch };
3870
5306
  }
3871
- function buildSealsReport(input) {
5307
+ function buildSealsReportWithFacts(input) {
3872
5308
  const v = input.verification;
3873
5309
  const failedCount = v.failedSeq.length;
3874
5310
  const record = {
@@ -3884,7 +5320,7 @@ function buildSealsReport(input) {
3884
5320
  const verdict = sealsVerdict(input.entries, v, input.queued);
3885
5321
  const disclosure = input.disclosure;
3886
5322
  const disclosureOk = !disclosure || disclosure.kind === "verified";
3887
- const passed = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
5323
+ const entriesMatch = verdict.passed && v.verified && (input.source.compared ? input.source.matches : true) && disclosureOk;
3888
5324
  const sentences = [intact ? verdict.sentence : FILE_CHANGED_SENTENCE];
3889
5325
  if (disclosure?.kind === "verified") {
3890
5326
  sentences.push(revealedLine(disclosure.revealed.length, input.entries ?? disclosure.revealed.length));
@@ -3898,16 +5334,16 @@ function buildSealsReport(input) {
3898
5334
  const fingerprintLine = fingerprintSentence(intact, statementFingerprint);
3899
5335
  if (fingerprintLine) sentences.push(fingerprintLine);
3900
5336
  if (input.heldFile && disclosure?.kind === "verified") sentences.push(...heldFileSentences(input.heldFile));
3901
- const failed = !passed || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
5337
+ const failed = !entriesMatch || statementFingerprint !== null && !statementFingerprint.matches || !!input.heldFile && !input.heldFile.matched;
3902
5338
  const unreachable = !input.source.compared && input.source.reason === "unreachable" || disclosure?.kind === "root-not-read";
3903
5339
  const exitCode = exitCodeOf(unreachable, failed);
3904
5340
  if (closesWithBoundary(exitCode)) sentences.push(SEALS_BOUNDARY_SENTENCE);
3905
- return {
5341
+ const report = {
3906
5342
  schema: REPORT_SCHEMA,
3907
5343
  checker: input.checker,
3908
5344
  form: input.form,
3909
5345
  record,
3910
- passed,
5346
+ passed: exitCode === 0,
3911
5347
  file,
3912
5348
  source: input.source,
3913
5349
  dailyStatement: null,
@@ -3918,6 +5354,7 @@ function buildSealsReport(input) {
3918
5354
  sentences,
3919
5355
  exitCode
3920
5356
  };
5357
+ return { report, entriesMatch };
3921
5358
  }
3922
5359
  var WRITES_HEADING = "Where each entry was committed on the proof layer:";
3923
5360
  var WRITES_NOT_READ_SENTENCE = "Where each entry was committed could not be read from the proof layer this time. The check above does not depend on it.";
@@ -3980,7 +5417,7 @@ var WRITES_LOOKUP_MAX_REQUESTS = 40;
3980
5417
  var WRITES_LOOKUP_DEFAULT_BUDGET_MS = 1e4;
3981
5418
  var HEX643 = /^0x[0-9a-f]{64}$/;
3982
5419
  var HEX402 = /^0x[0-9a-f]{40}$/;
3983
- var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
5420
+ var ISO_INSTANT2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
3984
5421
  var WRITE_EXPLORERS = Object.freeze({
3985
5422
  295: "https://hashscan.io/mainnet/transaction/",
3986
5423
  296: "https://hashscan.io/testnet/transaction/"
@@ -4003,7 +5440,7 @@ function wantedEntriesOf(receipts, verifiedSeqs) {
4003
5440
  return out.sort((a, b) => a.entry - b.entry);
4004
5441
  }
4005
5442
  function printable(write, contractAddress) {
4006
- return !!write && typeof write === "object" && typeof write.contractAddress === "string" && write.contractAddress.toLowerCase() === contractAddress && typeof write.transactionHash === "string" && HEX643.test(write.transactionHash.toLowerCase()) && typeof write.committedAt === "string" && ISO_INSTANT.test(write.committedAt) && Number.isFinite(Date.parse(write.committedAt)) && typeof write.previousWord === "string" && typeof write.newWord === "string" && HEX643.test(write.previousWord.toLowerCase()) && HEX643.test(write.newWord.toLowerCase());
5443
+ return !!write && typeof write === "object" && typeof write.contractAddress === "string" && write.contractAddress.toLowerCase() === contractAddress && typeof write.transactionHash === "string" && HEX643.test(write.transactionHash.toLowerCase()) && typeof write.committedAt === "string" && ISO_INSTANT2.test(write.committedAt) && Number.isFinite(Date.parse(write.committedAt)) && typeof write.previousWord === "string" && typeof write.newWord === "string" && HEX643.test(write.previousWord.toLowerCase()) && HEX643.test(write.newWord.toLowerCase());
4007
5444
  }
4008
5445
  function hitsFor(entry, writes, contractAddress) {
4009
5446
  const seen = /* @__PURE__ */ new Map();
@@ -4033,7 +5470,7 @@ async function lookUpWrites(input) {
4033
5470
  if (input.wanted.length === 0) return { read: true, entries: [], notFound: [] };
4034
5471
  const done = (writes2) => input.wanted.every((entry) => hitsFor(entry, writes2, contractAddress).length > 0);
4035
5472
  let writes;
4036
- let cutOff = false;
5473
+ let cutOff2 = false;
4037
5474
  if (input.whole) {
4038
5475
  const all = await within(input.reader.getRecordWrites(input.recordKey), input.budgetMs);
4039
5476
  if (all === "cut") return { read: false, reason: "timeout" };
@@ -4053,7 +5490,7 @@ async function lookUpWrites(input) {
4053
5490
  );
4054
5491
  if (result === "cut") return { read: false, reason: "timeout" };
4055
5492
  writes = result.writes;
4056
- cutOff = result.ended === "timeout";
5493
+ cutOff2 = result.ended === "timeout";
4057
5494
  }
4058
5495
  const byTransaction = /* @__PURE__ */ new Map();
4059
5496
  const notFound = [];
@@ -4079,7 +5516,7 @@ async function lookUpWrites(input) {
4079
5516
  });
4080
5517
  }
4081
5518
  const entries = [...byTransaction.values()].sort((a, b) => a.entries[0] - b.entries[0]);
4082
- if (cutOff && entries.length === 0) return { read: false, reason: "timeout" };
5519
+ if (cutOff2 && entries.length === 0) return { read: false, reason: "timeout" };
4083
5520
  return { read: true, entries, notFound };
4084
5521
  } catch {
4085
5522
  return { read: false, reason: "unreachable" };
@@ -4088,7 +5525,7 @@ async function lookUpWrites(input) {
4088
5525
 
4089
5526
  // src/check.ts
4090
5527
  var CHECKER_NAME = "@pacspace-io/check";
4091
- var CHECKER_VERSION = true ? "0.5.5" : "0.0.0-dev";
5528
+ var CHECKER_VERSION = true ? "0.6.0" : "0.0.0-dev";
4092
5529
  var HISTORY_SCHEMAS = [
4093
5530
  RECORD_HISTORY_BUNDLE_SCHEMA_V1,
4094
5531
  RECORD_HISTORY_BUNDLE_SCHEMA_V2,
@@ -4168,7 +5605,7 @@ function memoizeSequenceReads(reader) {
4168
5605
  }
4169
5606
  };
4170
5607
  }
4171
- function readerFor(chain, options) {
5608
+ function readerFor2(chain, options) {
4172
5609
  const chainId = chain?.chainId;
4173
5610
  const contractAddress = chain?.contractAddress;
4174
5611
  if (!contractAddress) {
@@ -4200,8 +5637,9 @@ function readerFor(chain, options) {
4200
5637
  readsFrom: mirrorBaseUrl
4201
5638
  };
4202
5639
  }
4203
- async function withWrites(report, bundle, verification, reader, options) {
4204
- if (!options.writes || !reader || !report.passed || !report.file.intact || !report.source.compared || !report.source.matches) return report;
5640
+ async function withWrites(checked, bundle, verification, reader, options) {
5641
+ const { report } = checked;
5642
+ if (!options.writes || !reader || !checked.entriesMatch || !report.file.intact || !report.source.compared || !report.source.matches) return checked;
4205
5643
  let writes;
4206
5644
  try {
4207
5645
  const source = options.source ?? "mirror";
@@ -4221,7 +5659,7 @@ async function withWrites(report, bundle, verification, reader, options) {
4221
5659
  } catch {
4222
5660
  writes = { read: false, reason: "unreachable" };
4223
5661
  }
4224
- return { ...report, writes };
5662
+ return { ...checked, report: { ...report, writes } };
4225
5663
  }
4226
5664
  var PAYLOAD_POINTER = /^\/payloads\/(0|[1-9][0-9]*)$/;
4227
5665
  function disclosureNamesAFile(disclosure) {
@@ -4252,6 +5690,9 @@ function refuseLayoutNotRead(result) {
4252
5690
  if (result.code === RECORDS_LAYOUT_NOT_READ) throw new HistoryFileError(RECORDS_LAYOUT_NOT_READ_SENTENCE);
4253
5691
  }
4254
5692
  async function checkHistory(file, options = {}) {
5693
+ return (await checkHistoryWithFacts(file, options)).report;
5694
+ }
5695
+ async function checkHistoryWithFacts(file, options = {}) {
4255
5696
  if (options.source === "offline" && needsLedgerRoots(file)) throw new HistoryFileError(DISCLOSURE_OFFLINE_SENTENCE);
4256
5697
  if (options.heldFile && !revealsFileFingerprint(file)) throw new HistoryFileError(NOTHING_REVEALED_SENTENCE);
4257
5698
  if (options.recordKey && file.schema !== RECORD_HISTORY_BUNDLE_SCHEMA_V3) throw new HistoryFileError(KEY_ONLY_FOR_ENCRYPTED_SENTENCE);
@@ -4376,7 +5817,7 @@ async function checkBundle(file, options) {
4376
5817
  };
4377
5818
  const heldOf = (verification2, offlineRun) => options.heldFile ? heldFileOutcome(options.heldFile, verifiedPayloads(file, verification2), offlineRun) : null;
4378
5819
  if (options.source === "offline" || !offline.schemaOk || !offline.digestOk) {
4379
- return buildReport({
5820
+ return buildReportWithFacts({
4380
5821
  ...base,
4381
5822
  verification: offline,
4382
5823
  source: { compared: false, reason: "offline" },
@@ -4389,7 +5830,7 @@ async function checkBundle(file, options) {
4389
5830
  let sequence = null;
4390
5831
  let sourceReader = null;
4391
5832
  try {
4392
- const found = readerFor(bundle.chain, options);
5833
+ const found = readerFor2(bundle.chain, options);
4393
5834
  const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4394
5835
  sourceReader = reader;
4395
5836
  const level = options.full ? "ledger" : "semantic";
@@ -4412,7 +5853,7 @@ async function checkBundle(file, options) {
4412
5853
  if (error instanceof HistoryFileError) throw error;
4413
5854
  source = notReached(error);
4414
5855
  }
4415
- const report = buildReport({
5856
+ const report = buildReportWithFacts({
4416
5857
  ...base,
4417
5858
  verification,
4418
5859
  source,
@@ -4462,7 +5903,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4462
5903
  const refused = (refusal) => {
4463
5904
  refuseLayoutNotRead(refusal);
4464
5905
  if (refusal.code === "RECORD_HISTORY_DIGEST") {
4465
- return buildReport({
5906
+ return buildReportWithFacts({
4466
5907
  ...base,
4467
5908
  verification: { verified: false, digestOk: false, reason: "", history: null },
4468
5909
  source: { compared: false, reason: "offline" },
@@ -4471,7 +5912,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4471
5912
  }
4472
5913
  const sentence = encryptedRefusalSentence(refusal);
4473
5914
  if (sentence === null) throw new HistoryFileError(notThisForm);
4474
- return buildReport({
5915
+ return buildReportWithFacts({
4475
5916
  ...base,
4476
5917
  verification: { verified: false, digestOk: true, reason: sentence, history: null },
4477
5918
  source: { compared: false, reason: "offline" },
@@ -4488,7 +5929,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4488
5929
  if (!offline.ok) return refused(offline);
4489
5930
  const encrypted = { refusedUnopened: offline.refused.filter((r) => !r.opened).length };
4490
5931
  if (options.source === "offline" || !offline.verification.schemaOk || !offline.verification.digestOk) {
4491
- return buildReport({
5932
+ return buildReportWithFacts({
4492
5933
  ...base,
4493
5934
  verification: offline.verification,
4494
5935
  source: { compared: false, reason: "offline" },
@@ -4502,7 +5943,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4502
5943
  let sequence = null;
4503
5944
  let sourceReader = null;
4504
5945
  try {
4505
- const found = readerFor(bundle.chain, options);
5946
+ const found = readerFor2(bundle.chain, options);
4506
5947
  const reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4507
5948
  sourceReader = reader;
4508
5949
  const contractMatches = !!bundle.chain?.contractAddress && bundle.chain.contractAddress.toLowerCase() === reader.contractAddress.toLowerCase();
@@ -4535,7 +5976,7 @@ async function checkEncrypted(file, bundle, recordKey, options) {
4535
5976
  if (error instanceof HistoryFileError) throw error;
4536
5977
  source = notReached(error);
4537
5978
  }
4538
- const report = buildReport({
5979
+ const report = buildReportWithFacts({
4539
5980
  ...base,
4540
5981
  verification: result.verification,
4541
5982
  source,
@@ -4586,135 +6027,748 @@ function answeringReader(reader) {
4586
6027
  }
4587
6028
  };
4588
6029
  }
4589
- function notReached(error) {
4590
- const refused = mirrorRefusalOf(error);
4591
- return { compared: false, reason: "unreachable", detail: error.message, ...refused ? { refused } : {} };
6030
+ function notReached(error) {
6031
+ const refused = mirrorRefusalOf(error);
6032
+ return { compared: false, reason: "unreachable", detail: error.message, ...refused ? { refused } : {} };
6033
+ }
6034
+ var pointerToken = (name) => name.replace(/~/g, "~0").replace(/\//g, "~1");
6035
+ async function checkDisclosure(form, disclosure, reader, onRevealed) {
6036
+ const sub = disclosureFormOfV1(form, disclosure);
6037
+ if (!sub) return { kind: "refused", code: null, reason: null };
6038
+ if (!reader) return { kind: "root-not-read" };
6039
+ const recorded = answeringReader(reader);
6040
+ const batchIds = [...new Set(sub.entries.map((e) => String(e.batchId)))];
6041
+ const { chainRoots, leftOut } = await readChainRootsV1(recorded.reader, batchIds);
6042
+ if (leftOut.some((id) => !recorded.answered.has(id))) return { kind: "root-not-read" };
6043
+ const result = await verifyRecordDisclosureV1({ form: sub, chainRoots, disclosure });
6044
+ if (!result.ok) return { kind: "refused", code: result.code, reason: result.reason };
6045
+ onRevealed?.(
6046
+ result.entries.filter((e) => e.fields.length > 0 || e.content !== null).map((e) => ({
6047
+ entry: e.seq + 1,
6048
+ fields: e.fields.length ? e.fields.map((f) => ({ pointer: f.pointer, value: f.value })) : Object.entries(e.content ?? {}).map(([name, value]) => ({ pointer: `/${pointerToken(name)}`, value })),
6049
+ withheld: e.withheld
6050
+ }))
6051
+ );
6052
+ return {
6053
+ kind: "verified",
6054
+ revealed: result.entries.filter((e) => e.fields.length > 0 || e.content !== null).map((e) => e.seq),
6055
+ withheld: result.entries.reduce((sum, e) => sum + e.withheld, 0),
6056
+ payloads: result.entries.map((e) => ({
6057
+ seq: e.seq,
6058
+ items: e.content && !e.fields.length ? payloadsOfContent(e.content) : e.fields.map((field) => ({ field, match: PAYLOAD_POINTER.exec(field.pointer) })).filter((f) => f.match).sort((a, b) => Number(a.match[1]) - Number(b.match[1])).map((f) => f.field.value)
6059
+ }))
6060
+ };
6061
+ }
6062
+ async function checkSeals(formName, form, disclosure, options) {
6063
+ const layouts = getPublishedLayoutRegistry();
6064
+ let verification = verifyRecordSealHistoryV1(form, { layouts });
6065
+ refuseLayoutNotRead(verification);
6066
+ const computedFingerprint = (() => {
6067
+ try {
6068
+ return computeSealHistoryDigestV1(form);
6069
+ } catch {
6070
+ return "";
6071
+ }
6072
+ })();
6073
+ const base = {
6074
+ checker: { name: CHECKER_NAME, version: CHECKER_VERSION },
6075
+ form: formName,
6076
+ reference: String(form?.recordKey ?? ""),
6077
+ fingerprint: typeof form?.digest === "string" ? form.digest : null,
6078
+ computedFingerprint,
6079
+ statementFingerprint: options.statementFingerprint?.trim() || null,
6080
+ queued: (Array.isArray(form?.pending) ? form.pending : []).filter((p) => p?.status === "queued" && typeof p.seq === "number").map((p) => p.seq).sort((a, b) => a - b)
6081
+ };
6082
+ const entries = entryCountOf(form, layouts);
6083
+ if (options.source === "offline" || !verification.schemaOk || !verification.digestOk) {
6084
+ return buildSealsReportWithFacts({
6085
+ ...base,
6086
+ entries,
6087
+ verification,
6088
+ source: { compared: false, reason: "offline" },
6089
+ disclosure: disclosure ? { kind: "not-checked" } : null,
6090
+ heldFile: options.heldFile ? heldFileOutcome(options.heldFile, [], options.source === "offline") : null
6091
+ });
6092
+ }
6093
+ let source;
6094
+ let reader = null;
6095
+ try {
6096
+ const found = readerFor2(form.chain, options);
6097
+ reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
6098
+ const chainWord = await reader.getRecord(form.recordKey);
6099
+ verification = verifyRecordSealHistoryV1(form, { layouts, chainWord });
6100
+ const contractMatches = reader.contractAddress.toLowerCase() === String(form.chain.contractAddress).toLowerCase();
6101
+ const wordMatches = form.currentWord === null ? BigInt(chainWord) === 0n : verification.chainWordMatches === true;
6102
+ const ledgerMatches = options.full && form.ledger ? ledgerAgrees(form, await readLedgerMaterial(reader, [], {})) : true;
6103
+ const matches = contractMatches && wordMatches && ledgerMatches;
6104
+ source = {
6105
+ compared: true,
6106
+ matches,
6107
+ chainId: form.chain.chainId,
6108
+ readsFrom: found.readsFrom,
6109
+ contractAddress: reader.contractAddress.toLowerCase(),
6110
+ detail: contractMatches ? null : "The record was committed somewhere other than where this file says."
6111
+ };
6112
+ } catch (error) {
6113
+ if (error instanceof HistoryFileError) throw error;
6114
+ source = notReached(error);
6115
+ reader = null;
6116
+ }
6117
+ let disclosureOutcome = null;
6118
+ if (disclosure) {
6119
+ disclosureOutcome = verification.verified ? await checkDisclosure(form, disclosure, reader, options.onRevealed) : { kind: "not-checked" };
6120
+ }
6121
+ const held = options.heldFile ? heldFileOutcome(options.heldFile, disclosureOutcome?.kind === "verified" ? disclosureOutcome.payloads : [], false) : null;
6122
+ return buildSealsReportWithFacts({
6123
+ ...base,
6124
+ entries,
6125
+ verification,
6126
+ source,
6127
+ disclosure: disclosureOutcome,
6128
+ heldFile: held
6129
+ });
6130
+ }
6131
+
6132
+ // src/open-io.ts
6133
+ var import_node_path = require("node:path");
6134
+ var hostUnreachableSentence = (host) => `The link could not be read from ${host}. Check the connection and run it again.`;
6135
+ var NO_KEY_SENTENCE = "This link reveals fields, but it has no key after #. Ask the sender for the whole link.";
6136
+ var pathExistsSentence = (path) => `${path} already exists. Choose another path.`;
6137
+ var savedReportSentence = (path) => `Saved the report to ${path}. It opens in a browser without a network connection.`;
6138
+ var LINE_MAX_BYTES = 8192;
6139
+ var OpenStop = class extends Error {
6140
+ constructor(message, exitCode) {
6141
+ super(message);
6142
+ this.exitCode = exitCode;
6143
+ }
6144
+ };
6145
+ async function firstLineOf(io, path) {
6146
+ let bytes2;
6147
+ try {
6148
+ bytes2 = await io.readBytes((0, import_node_path.resolve)(path), LINE_MAX_BYTES);
6149
+ } catch (error) {
6150
+ throw new OpenStop(`The file could not be read: ${error.message}`, 2);
6151
+ }
6152
+ return new TextDecoder().decode(bytes2).split(/\r?\n/)[0] ?? "";
6153
+ }
6154
+ async function writeNew(io, path, bytes2) {
6155
+ if (!io.writeNewFile) throw new OpenStop(`The file could not be written: ${path}`, 2);
6156
+ try {
6157
+ await io.writeNewFile((0, import_node_path.resolve)(path), bytes2, 384);
6158
+ } catch (error) {
6159
+ if (error.code === "EEXIST") throw new OpenStop(pathExistsSentence(path), 2);
6160
+ throw new OpenStop(`The file could not be written: ${error.message}`, 2);
6161
+ }
6162
+ }
6163
+ var withoutControls = (text) => Array.from(text).filter((ch) => ch.charCodeAt(0) >= 32 && ch.charCodeAt(0) !== 127).join("");
6164
+ var escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
6165
+ function refusalOfBody(body) {
6166
+ const outer = body ?? {};
6167
+ const code = outer.error?.code ?? outer.code;
6168
+ const message = outer.error?.message ?? outer.message;
6169
+ const wait = outer.error?.retryAfterSeconds ?? outer.retryAfterSeconds;
6170
+ return {
6171
+ code: typeof code === "string" ? code : null,
6172
+ message: typeof message === "string" ? withoutControls(message).trim() || null : null,
6173
+ retryAfterSeconds: typeof wait === "number" && Number.isFinite(wait) && wait >= 0 ? wait : null
6174
+ };
6175
+ }
6176
+ async function refusalOf(response) {
6177
+ try {
6178
+ return refusalOfBody(await response.json());
6179
+ } catch {
6180
+ return { code: null, message: null, retryAfterSeconds: null };
6181
+ }
6182
+ }
6183
+ async function bodyWithin(response, max) {
6184
+ const declared = Number(response.headers.get("content-length"));
6185
+ if (Number.isFinite(declared) && declared > max) {
6186
+ await response.body?.cancel().catch(() => void 0);
6187
+ return null;
6188
+ }
6189
+ if (!response.body) return new Uint8Array(0);
6190
+ const reader = response.body.getReader();
6191
+ const chunks = [];
6192
+ let total = 0;
6193
+ for (; ; ) {
6194
+ const { done, value } = await reader.read();
6195
+ if (done) break;
6196
+ total += value.length;
6197
+ if (total > max) {
6198
+ await reader.cancel().catch(() => void 0);
6199
+ return null;
6200
+ }
6201
+ chunks.push(value);
6202
+ }
6203
+ const bytes2 = new Uint8Array(total);
6204
+ let at = 0;
6205
+ for (const chunk of chunks) {
6206
+ bytes2.set(chunk, at);
6207
+ at += chunk.length;
6208
+ }
6209
+ return bytes2;
6210
+ }
6211
+ function retryAfterSecondsOf(response, refusal) {
6212
+ const header = response.headers.get("retry-after");
6213
+ if (header !== null && /^\d{1,6}$/.test(header.trim())) return Number(header.trim());
6214
+ return refusal.retryAfterSeconds;
6215
+ }
6216
+
6217
+ // src/shared-record-words.ts
6218
+ var plural = (n, one, many) => n === 1 ? one : many;
6219
+ var records = (n) => `${n} ${plural(n, "record", "records")}`;
6220
+ var SHARED_RECORD_WORDS = {
6221
+ // ---- before the code is asked for
6222
+ /** The origin every request of this run goes to. */
6223
+ readingFrom: (origin) => `Reading this link from ${origin}.`,
6224
+ /** Said before the code is asked for and again beside the result, when the origin is not one of PacSpace's. */
6225
+ notPacSpace: (origin) => `${origin} is not a PacSpace address. A code you type is sent to it, and a result here does not show who made the link.`,
6226
+ /** Said with the code prompt. A refused code is never sent again by this run. */
6227
+ codeOnce: (host) => `The code is sent to ${host} once. Five wrong codes stop this link's code for everyone, so a code it refuses is not sent again.`,
6228
+ /** No code was typed or found in the file given. Nothing was sent. */
6229
+ noCode: "No code was given, so the link was not opened.",
6230
+ /** The link's host answered 429 to opening it. */
6231
+ openLimited: (host, seconds) => seconds === null ? `${host} is limiting how often this link can be opened. Wait, then run this again.` : `${host} is limiting how often this link can be opened. Wait ${seconds} ${plural(seconds, "second", "seconds")}, then run this again.`,
6232
+ /** A `csl1_` address that its host answers as any other kind of link. Exit code 1. */
6233
+ notAListLink: "This address names a list of records, and its host answered it as another kind of link. It fails the check.",
6234
+ /** A trail link made before lists. Exit code 3; no code is asked for. */
6235
+ noList: "This link was made before links carried a list of their records, so there is no list to check its records against. It was not checked.",
6236
+ /** `--full` over JSON-RPC. */
6237
+ fullNeedsMirror: "--full reads a contract's whole log from a mirror. Use it without --rpc.",
6238
+ /** `open --full` on a link to one record. */
6239
+ fullOnlyForList: "With open, --full is used only with a link to a list of records.",
6240
+ /** `--html` beside `--json`'s own report is fine; `--copy` when the link gave nothing to keep. */
6241
+ copyNotSaved: "No copy was saved, because the link did not serve a list that could be kept.",
6242
+ /** A kept copy of a link with `--offline`. */
6243
+ copyOffline: "A copy of a link is checked against the proof layer, so it was not checked offline. Run this again without --offline.",
6244
+ copyNotRead: "This is not a copy of a link this version can read.",
6245
+ /** `--link-file` given with a copy, and the address in it does not name a list of records. */
6246
+ copyAddress: "The link given with this copy is not the address of a link with a list of records.",
6247
+ /** An option of a single record's file given with a copy of a link. */
6248
+ copyOption: (flag) => `${flag} is not used with a copy of a link.`,
6249
+ /** `--link-file` with a file that is not a copy of a link. */
6250
+ linkFileOnlyForCopy: "--link-file is used with open, or with a copy of a link.",
6251
+ savedCopy: (path) => `Saved a copy to ${path}. It holds the revealed fields in clear. Check it again at any time with: npx @pacspace-io/check ${path}`,
6252
+ savedCopyNoFields: (path) => `Saved a copy to ${path}. Check it again at any time with: npx @pacspace-io/check ${path}`,
6253
+ progress: (done, of) => `Checked ${done} of ${records(of)}.`,
6254
+ // ---- the report's facts
6255
+ title: "PacSpace link check",
6256
+ labels: {
6257
+ host: "Link host",
6258
+ readFrom: "Read from",
6259
+ reference: "Reference",
6260
+ sharedBy: "Shared by",
6261
+ sharedOn: "Shared on",
6262
+ records: "Records",
6263
+ proofLayer: "Proof layer"
6264
+ },
6265
+ /** The cover is PacSpace's report: nothing in it is held to the address. */
6266
+ coverNote: "The reference, who shared this link and when are as its host reports them. The check does not cover them.",
6267
+ proofLayerLine: (chainId, contract, source) => source === null ? `network ${chainId}, contract ${contract}, not read` : `network ${chainId}, contract ${contract}, read from ${source}`,
6268
+ // ---- the collection
6269
+ listMatches: (n) => n === 1 ? "This link's address names a list of 1 record. The list served is that list, and the record served is the one on it." : `This link's address names a list of ${n} records. The list served is that list, and the records served are the ones on it.`,
6270
+ listNotCompared: (n) => `This copy lists ${records(n)}. No link was given with it, so its list was not compared with a link's address. Pass the link with --link-file to compare it.`,
6271
+ // ---- the result line. It never says every record matches while one is not checked.
6272
+ // A list of one record says the registered lines for one record.
6273
+ allMatch: (n) => n === 1 ? "Compared with the proof layer for this record: it matches." : `Compared with the proof layer: all ${n} records match.`,
6274
+ someFail: (failed, n) => n === 1 ? "Compared with the proof layer for this record: it does not match." : `Compared with the proof layer: ${failed} of ${n} records ${plural(failed, "does", "do")} not match.`,
6275
+ /** No record fails and at least one was not checked. */
6276
+ someNotChecked: (matched, notChecked, n) => n === 1 ? "Compared with the proof layer for this record: it was not checked." : matched === 0 ? `Compared with the proof layer: none of the ${n} records was checked.` : `Compared with the proof layer: ${matched} of ${n} records ${plural(matched, "matches", "match")}. ${notChecked} ${plural(notChecked, "was", "were")} not checked.`,
6277
+ /** At least one record fails and at least one was not checked: a list of two or more. */
6278
+ failedAndNotChecked: (failed, notChecked, n) => `Compared with the proof layer: ${failed} of ${n} records ${plural(failed, "does", "do")} not match, and ${notChecked} ${plural(notChecked, "was", "were")} not checked.`,
6279
+ /** The default check's stated limit, said with a result that passed without `--full`. */
6280
+ spanLimit: "Each record's writes were read back to its first write. A record that was set back to empty and written again before that first write is shown only by --full, which reads the contract's whole log.",
6281
+ // ---- one record
6282
+ recordFails: (number, why) => `Record ${number}: does not match. ${why}`,
6283
+ recordNotChecked: (number, why) => `Record ${number}: not checked. ${why}`,
6284
+ /** A record that moved on after it was served. Reported, never a failure. */
6285
+ changedSince: (number, later) => later > 0 ? `Record ${number} has changed since what this link served: ${later} later ${plural(later, "write is", "writes are")} on the proof layer. Its entries up to its close match what was committed.` : `Record ${number} has changed since what this link served. Its entries up to its close match what was committed.`,
6286
+ afterClose: (number, entries) => `Record ${number}: ${entries} ${plural(entries, "entry", "entries")} after its close ${plural(entries, "was", "were")} served and checked the same way. ${plural(entries, "It is", "They are")} not part of this link's list.`,
6287
+ committingAfterClose: (number, entries) => `Record ${number}: ${entries} ${plural(entries, "entry", "entries")} after its close ${plural(entries, "is", "are")} still being committed.`,
6288
+ recordsNotListed: (count) => `${count} more ${plural(count, "record is", "records are")} not listed here. --json lists them all.`,
6289
+ /** Each entry's time on the proof layer. */
6290
+ committedHeading: "When each entry was committed on the proof layer:",
6291
+ committedLine: (number, entry, when) => `Record ${number}, entry ${entry}: committed ${when}`,
6292
+ committedNotListed: (count) => `${count} more ${plural(count, "entry is", "entries are")} not listed here. --json lists them all.`,
6293
+ // ---- revealed fields
6294
+ /** A copy kept when the fields were not opened. */
6295
+ copyFieldsNotKept: "This link reveals fields, and this copy was kept without them.",
6296
+ fieldsNotRead: "This link reveals fields, and they could not be read from the link's host, so none are shown.",
6297
+ fieldsOpened: (n) => n === 1 ? "The revealed fields of 1 record were opened on this machine. Each shown field was checked against its entry's seal." : `The revealed fields of ${n} records were opened on this machine. Each shown field was checked against its entry's seal.`,
6298
+ revealedHeading: (number) => `Record ${number}, revealed fields`
6299
+ };
6300
+ var NOT_A_FORM = "What the link served is not in a form this version reads. It fails the check.";
6301
+ var NOT_ITS_LIST = "The list served is not the one this link's address names. It fails the check.";
6302
+ var LINK_CODE_WORDS = {
6303
+ LINK_NOT_A_LIST: SHARED_RECORD_WORDS.notAListLink,
6304
+ MANIFEST_INVALID: NOT_A_FORM,
6305
+ LIST_ON_LATER_PAGE: NOT_A_FORM,
6306
+ LIST_INVALID: "The list served is not a list this version reads. It fails the check.",
6307
+ PAGING_NOT_FORWARD: "The pages served do not follow one another. It fails the check.",
6308
+ TERMS_DIFFER: NOT_ITS_LIST,
6309
+ LIST_NOT_ADDRESS: NOT_ITS_LIST,
6310
+ RECORDS_NOT_LIST: "The records served are not the records on the list. It fails the check.",
6311
+ REVEALS_INVALID: "The revealed fields served are not in a form this version reads. It fails the check.",
6312
+ REVEAL_OFF_LIST: "Revealed fields were served for a record that is not on the list. It fails the check.",
6313
+ LINK_HAS_NO_LIST: SHARED_RECORD_WORDS.noList,
6314
+ MANIFEST_NOT_READ: "The link could not be read, so nothing was checked."
6315
+ };
6316
+ var entryOf = (entry) => entry === null ? "An entry" : `Entry ${entry}`;
6317
+ function recordCodeWords(code, entry, context) {
6318
+ switch (code) {
6319
+ case "HISTORY_NOT_SERVED":
6320
+ return "Its history was not served.";
6321
+ case "HISTORY_INVALID":
6322
+ return "The history served for it is not whole, or was changed.";
6323
+ case "HISTORY_OTHER_RECORD":
6324
+ return "The history served for it is another record's.";
6325
+ case "ENTRY_MISSING":
6326
+ return `${entryOf(entry)} is missing from what was served.`;
6327
+ case "ENTRY_NOT_COMMITTED":
6328
+ return `${entryOf(entry)} is not yet committed.`;
6329
+ case "ENTRY_FAILED":
6330
+ return `${entryOf(entry)} does not match what was committed.`;
6331
+ case "CLOSE_SEAL_DIFFERS":
6332
+ return "Its closing entry is not the one the list names.";
6333
+ case "ENTRY_NOT_WRITTEN":
6334
+ return `${entryOf(entry)} has no write on the proof layer.`;
6335
+ case "WRITE_NOT_SERVED":
6336
+ return "The proof layer holds a write among its entries that was not served.";
6337
+ case "WRITE_BEFORE_FIRST":
6338
+ return "The proof layer holds writes of this record from before its first entry.";
6339
+ case "RECORD_SET_BACK":
6340
+ return "A later write on the proof layer set the record back.";
6341
+ case "CURRENT_WORD_ZERO":
6342
+ return "The record on the proof layer today is empty.";
6343
+ case "CURRENT_WORD_EARLIER":
6344
+ return "The record on the proof layer today is at an earlier entry.";
6345
+ case "REVEAL_MISSING":
6346
+ return "The link reveals fields and none were served for it.";
6347
+ case "REVEAL_NOT_OPENED":
6348
+ return "Its revealed fields didn't open with this link's key.";
6349
+ case "FIELDS_DO_NOT_MATCH":
6350
+ return "Its revealed fields do not match its entries' seals.";
6351
+ case "HISTORY_NOT_READ":
6352
+ return "Its history could not be read.";
6353
+ case "LAYOUT_NOT_READ":
6354
+ return "It was written under a record layout this version does not read.";
6355
+ case "SOURCE_UNKNOWN":
6356
+ return `The checker has no address for its network (${context.chainId}). Pass one with --source <url>.`;
6357
+ case "SOURCE_NOT_READ":
6358
+ return "The proof layer source did not answer.";
6359
+ case "BUDGET_SPENT":
6360
+ return context.full || context.requests === 0 ? "The run reached the most it asks of the proof layer." : "The record lived longer than this read reaches. --full reads the contract's whole log.";
6361
+ case "LOG_PAST_BOUNDS":
6362
+ return "The contract's log holds more than this checker reads in one run.";
6363
+ case "REVEALS_NOT_READ":
6364
+ return "Its revealed fields could not be read.";
6365
+ case "ROOT_NOT_READ":
6366
+ return "What its revealed fields are checked against could not be read from the proof layer.";
6367
+ }
6368
+ }
6369
+
6370
+ // src/shared-record-link.ts
6371
+ var KEY_HOST = "records.pacspace.io";
6372
+ var KEY_HOST_READS_FROM = "https://app.pacspace.io";
6373
+ function linkOriginOf(address) {
6374
+ const origin = address.host === KEY_HOST ? KEY_HOST_READS_FROM : address.origin;
6375
+ return { addressHost: address.host, origin, host: new URL(origin).host, pacspace: origin === KEY_HOST_READS_FROM };
6376
+ }
6377
+ function rpcNameOf(rpc) {
6378
+ try {
6379
+ return new URL(rpc).origin;
6380
+ } catch {
6381
+ return "an RPC endpoint";
6382
+ }
6383
+ }
6384
+ var paceOf = (io) => ({
6385
+ ...io.now ? { now: () => io.now().getTime() } : {},
6386
+ ...io.sleep ? { sleep: io.sleep } : {}
6387
+ });
6388
+ function proofLayerFor(options) {
6389
+ const paced = sharedRecordPacedFetchV1(options.fetchImpl, options.pace);
6390
+ return ({ chainId, contractAddress }) => {
6391
+ const { source } = options;
6392
+ try {
6393
+ if (typeof source === "object") {
6394
+ return { reader: createRpcRecordChainReader({ rpcUrl: source.rpc, contractAddress, chainId, timeoutMs: options.timeoutMs }), source: rpcNameOf(source.rpc) };
6395
+ }
6396
+ const mirrorBaseUrl = source === void 0 || source === "mirror" ? MIRROR_NODE_BY_CHAIN[chainId] : source;
6397
+ if (!mirrorBaseUrl || mirrorBaseUrl === "offline") return null;
6398
+ return {
6399
+ reader: createMirrorNodeRecordChainReader({
6400
+ mirrorBaseUrl,
6401
+ chainId,
6402
+ contractAddress,
6403
+ timeoutMs: options.timeoutMs,
6404
+ fetchImpl: paced,
6405
+ // --full reads the contract's whole log once and holds every record of it to that one read.
6406
+ keepLogPages: options.full
6407
+ }),
6408
+ source: mirrorBaseUrl.replace(/\/+$/, "")
6409
+ };
6410
+ } catch {
6411
+ return null;
6412
+ }
6413
+ };
6414
+ }
6415
+ var LINK_ANSWER_MAX_BYTES = 16 * 1024 * 1024;
6416
+ var LINK_RUN_MAX_BYTES = SHARED_RECORD_COPY_MAX_BYTES_V1;
6417
+ var LINK_GAP_MS = 250;
6418
+ var LINK_WAITS = 3;
6419
+ var LINK_WAIT_MAX_MS = 6e4;
6420
+ var LINK_TIMEOUT_MS = 3e4;
6421
+ function linkHostOf(base, io, timeoutMs) {
6422
+ const fetchImpl = io.fetchImpl ?? fetch;
6423
+ const sleep = io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
6424
+ const clock = () => io.now ? io.now().getTime() : Date.now();
6425
+ let turn = Promise.resolve();
6426
+ let nextAt = 0;
6427
+ let readBytes = 0;
6428
+ const paced = () => {
6429
+ const mine = turn.then(async () => {
6430
+ const wait = nextAt - clock();
6431
+ if (wait > 0) await sleep(Math.min(wait, LINK_GAP_MS));
6432
+ nextAt = clock() + LINK_GAP_MS;
6433
+ });
6434
+ turn = mine.catch(() => void 0);
6435
+ return mine;
6436
+ };
6437
+ return {
6438
+ sleep,
6439
+ async ask(path, init = {}) {
6440
+ await paced();
6441
+ const headers = { Accept: "application/json" };
6442
+ if (init.body !== void 0) headers["Content-Type"] = "application/json";
6443
+ if (init.bearer) headers.Authorization = `Bearer ${init.bearer}`;
6444
+ const response = await fetchImpl(`${base}${path}`, {
6445
+ method: init.method ?? "GET",
6446
+ headers,
6447
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
6448
+ redirect: "error",
6449
+ signal: AbortSignal.timeout(timeoutMs)
6450
+ });
6451
+ const bytes2 = await bodyWithin(response, Math.min(LINK_ANSWER_MAX_BYTES, LINK_RUN_MAX_BYTES - readBytes));
6452
+ if (bytes2 === null) throw new Error("answer too large");
6453
+ readBytes += bytes2.length;
6454
+ let json = null;
6455
+ try {
6456
+ json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes2));
6457
+ } catch {
6458
+ json = null;
6459
+ }
6460
+ const refusal = refusalOfBody(json);
6461
+ return { status: response.status, json, refusal, retryAfterSeconds: retryAfterSecondsOf(response, refusal) };
6462
+ }
6463
+ };
6464
+ }
6465
+ function linkSourceOf(host, token) {
6466
+ const read = async (path) => {
6467
+ for (let waited = 0; ; waited += 1) {
6468
+ let answer;
6469
+ try {
6470
+ answer = await host.ask(path, { bearer: token });
6471
+ } catch {
6472
+ throw new SharedRecordAnswerError("unreachable");
6473
+ }
6474
+ if (answer.status === 200 && answer.json !== null) return answer.json;
6475
+ if (answer.status === 429 && waited < LINK_WAITS) {
6476
+ const seconds = answer.retryAfterSeconds ?? 2 ** waited;
6477
+ await host.sleep(Math.min(LINK_WAIT_MAX_MS, Math.max(1, seconds) * 1e3));
6478
+ continue;
6479
+ }
6480
+ throw new SharedRecordAnswerError(answer.status === 404 ? "refused" : "unreachable");
6481
+ }
6482
+ };
6483
+ return {
6484
+ page: (after) => read(`/record.json?v=2&after=${after}`),
6485
+ seals: (number) => read(`/members/${number}/seals`),
6486
+ reveals: (after) => read(`/reveals?after=${after}`)
6487
+ };
4592
6488
  }
4593
- var pointerToken = (name) => name.replace(/~/g, "~0").replace(/\//g, "~1");
4594
- async function checkDisclosure(form, disclosure, reader, onRevealed) {
4595
- const sub = disclosureFormOfV1(form, disclosure);
4596
- if (!sub) return { kind: "refused", code: null, reason: null };
4597
- if (!reader) return { kind: "root-not-read" };
4598
- const recorded = answeringReader(reader);
4599
- const batchIds = [...new Set(sub.entries.map((e) => String(e.batchId)))];
4600
- const { chainRoots, leftOut } = await readChainRootsV1(recorded.reader, batchIds);
4601
- if (leftOut.some((id) => !recorded.answered.has(id))) return { kind: "root-not-read" };
4602
- const result = await verifyRecordDisclosureV1({ form: sub, chainRoots, disclosure });
4603
- if (!result.ok) return { kind: "refused", code: result.code, reason: result.reason };
4604
- onRevealed?.(
4605
- result.entries.filter((e) => e.fields.length > 0 || e.content !== null).map((e) => ({
4606
- entry: e.seq + 1,
4607
- fields: e.fields.length ? e.fields.map((f) => ({ pointer: f.pointer, value: f.value })) : Object.entries(e.content ?? {}).map(([name, value]) => ({ pointer: `/${pointerToken(name)}`, value })),
4608
- withheld: e.withheld
4609
- }))
4610
- );
6489
+ var TOKEN = /^[\x21-\x7e]{16,1024}$/;
6490
+ function stopOn(answer, host) {
6491
+ if (answer.status === 429) {
6492
+ throw new OpenStop(SHARED_RECORD_WORDS.openLimited(host, answer.retryAfterSeconds === null ? null : Math.max(1, Math.ceil(answer.retryAfterSeconds))), 3);
6493
+ }
6494
+ if (answer.status >= 500 || !answer.refusal.message) throw new OpenStop(answer.refusal.message ?? hostUnreachableSentence(host), 3);
6495
+ throw new OpenStop(answer.refusal.message, 2);
6496
+ }
6497
+ var LINK_REPORT_SCHEMA = "pacspace-check-link-report/v1";
6498
+ var EXIT = { matches: 0, fails: 1, "not-checked": 3 };
6499
+ var RECORDS_LISTED_MAX = 25;
6500
+ function listed(lines) {
6501
+ if (lines.length <= RECORDS_LISTED_MAX) return lines;
6502
+ return [...lines.slice(0, RECORDS_LISTED_MAX), SHARED_RECORD_WORDS.recordsNotListed(lines.length - RECORDS_LISTED_MAX)];
6503
+ }
6504
+ function linkSentences(check2, link, copy) {
6505
+ const sentences = [];
6506
+ const n = check2.collection.records;
6507
+ if (check2.cover) sentences.push(SHARED_RECORD_WORDS.coverNote);
6508
+ if (check2.code !== null) {
6509
+ sentences.push(LINK_CODE_WORDS[check2.code]);
6510
+ } else {
6511
+ sentences.push(check2.collection.status === "not-compared" ? SHARED_RECORD_WORDS.listNotCompared(n) : SHARED_RECORD_WORDS.listMatches(n));
6512
+ const { matches, fails, notChecked } = check2.counts;
6513
+ if (fails > 0 && notChecked > 0) sentences.push(SHARED_RECORD_WORDS.failedAndNotChecked(fails, notChecked, n));
6514
+ else if (fails > 0) sentences.push(SHARED_RECORD_WORDS.someFail(fails, n));
6515
+ else if (notChecked > 0) sentences.push(SHARED_RECORD_WORDS.someNotChecked(matches, notChecked, n));
6516
+ else sentences.push(SHARED_RECORD_WORDS.allMatch(n));
6517
+ const full = check2.mode === "full";
6518
+ const why = (r) => recordCodeWords(r.code, r.failedEntry, { chainId: r.chainId, full, requests: r.requests });
6519
+ sentences.push(...listed(check2.records.filter((r) => r.status === "fails").map((r) => SHARED_RECORD_WORDS.recordFails(r.number, why(r)))));
6520
+ sentences.push(...listed(check2.records.filter((r) => r.status === "not-checked").map((r) => SHARED_RECORD_WORDS.recordNotChecked(r.number, why(r)))));
6521
+ sentences.push(...listed(check2.records.filter((r) => r.status === "matches" && r.changedSince).map((r) => SHARED_RECORD_WORDS.changedSince(r.number, r.laterWrites))));
6522
+ const after = [];
6523
+ for (const r of check2.records) {
6524
+ const served = r.entries.filter((e) => e.afterClose).length;
6525
+ if (served > 0) after.push(SHARED_RECORD_WORDS.afterClose(r.number, served));
6526
+ if (r.committingAfterClose > 0) after.push(SHARED_RECORD_WORDS.committingAfterClose(r.number, r.committingAfterClose));
6527
+ }
6528
+ sentences.push(...listed(after));
6529
+ if (check2.fields === "not-opened") sentences.push(copy ? SHARED_RECORD_WORDS.copyFieldsNotKept : NO_KEY_SENTENCE);
6530
+ else if (check2.fields === "not-read") sentences.push(SHARED_RECORD_WORDS.fieldsNotRead);
6531
+ else if (check2.fields === "opened") {
6532
+ const shown = check2.records.filter((r) => r.fields.status === "matches" && r.fields.entries.length > 0).length;
6533
+ if (shown > 0) sentences.push(SHARED_RECORD_WORDS.fieldsOpened(shown));
6534
+ }
6535
+ if (check2.status === "matches") {
6536
+ sentences.push(SEALS_BOUNDARY_SENTENCE);
6537
+ if (!full) sentences.push(SHARED_RECORD_WORDS.spanLimit);
6538
+ }
6539
+ }
6540
+ if (link && !link.pacspace) sentences.push(SHARED_RECORD_WORDS.notPacSpace(link.readFrom));
6541
+ return sentences;
6542
+ }
6543
+ function buildLinkReport(check2, link, copy) {
6544
+ const { kept: _kept, ...rest } = check2;
6545
+ void _kept;
6546
+ const exitCode = EXIT[check2.status];
4611
6547
  return {
4612
- kind: "verified",
4613
- revealed: result.entries.filter((e) => e.fields.length > 0 || e.content !== null).map((e) => e.seq),
4614
- withheld: result.entries.reduce((sum, e) => sum + e.withheld, 0),
4615
- payloads: result.entries.map((e) => ({
4616
- seq: e.seq,
4617
- items: e.content && !e.fields.length ? payloadsOfContent(e.content) : e.fields.map((field) => ({ field, match: PAYLOAD_POINTER.exec(field.pointer) })).filter((f) => f.match).sort((a, b) => Number(a.match[1]) - Number(b.match[1])).map((f) => f.field.value)
4618
- }))
6548
+ schema: LINK_REPORT_SCHEMA,
6549
+ checker: { name: CHECKER_NAME, version: CHECKER_VERSION },
6550
+ link,
6551
+ passed: exitCode === 0,
6552
+ check: rest,
6553
+ sentences: linkSentences(check2, link, copy),
6554
+ exitCode
4619
6555
  };
4620
6556
  }
4621
- async function checkSeals(formName, form, disclosure, options) {
4622
- const layouts = getPublishedLayoutRegistry();
4623
- let verification = verifyRecordSealHistoryV1(form, { layouts });
4624
- refuseLayoutNotRead(verification);
4625
- const computedFingerprint = (() => {
6557
+ function factsOf(report) {
6558
+ const { check: check2, link } = report;
6559
+ const facts = [];
6560
+ if (link) {
6561
+ facts.push([SHARED_RECORD_WORDS.labels.host, link.host]);
6562
+ if (link.readFrom !== `https://${link.host}`) facts.push([SHARED_RECORD_WORDS.labels.readFrom, link.readFrom]);
6563
+ }
6564
+ if (check2.cover) {
6565
+ facts.push([SHARED_RECORD_WORDS.labels.reference, withoutControls(check2.cover.reference)]);
6566
+ facts.push([SHARED_RECORD_WORDS.labels.sharedBy, withoutControls(check2.cover.organization)]);
6567
+ facts.push([SHARED_RECORD_WORDS.labels.sharedOn, `${dayOfUtc(check2.cover.sharedOn)} (UTC)`]);
6568
+ }
6569
+ if (check2.code === null) facts.push([SHARED_RECORD_WORDS.labels.records, String(check2.collection.records)]);
6570
+ for (const source of check2.sources) facts.push([SHARED_RECORD_WORDS.labels.proofLayer, SHARED_RECORD_WORDS.proofLayerLine(source.chainId, source.contractAddress, source.source)]);
6571
+ return facts;
6572
+ }
6573
+ function committedLines(check2) {
6574
+ const all = [];
6575
+ for (const record of check2.records) {
6576
+ for (const entry of record.entries) {
6577
+ if (!entry.afterClose && entry.committedAt) all.push(SHARED_RECORD_WORDS.committedLine(record.number, entry.entry, committedWhen(entry.committedAt)));
6578
+ }
6579
+ }
6580
+ if (all.length === 0) return [];
6581
+ const lines = [SHARED_RECORD_WORDS.committedHeading, ...all.slice(0, WRITES_LISTED_MAX)];
6582
+ if (all.length > WRITES_LISTED_MAX) lines.push(SHARED_RECORD_WORDS.committedNotListed(all.length - WRITES_LISTED_MAX));
6583
+ return lines;
6584
+ }
6585
+ function revealedOf(check2) {
6586
+ return check2.records.filter((r) => r.fields.status === "matches" && r.fields.entries.length > 0).map((r) => ({ number: r.number, entries: r.fields.entries }));
6587
+ }
6588
+ var notShown = (k) => `${k} ${k === 1 ? "field" : "fields"} not shown.`;
6589
+ function renderLinkReport(report) {
6590
+ const facts = factsOf(report);
6591
+ const width = Math.max(0, ...facts.map(([label]) => label.length));
6592
+ const lines = facts.map(([label, value]) => `${label.padEnd(width)} ${value}`);
6593
+ if (lines.length > 0) lines.push("");
6594
+ lines.push(...report.sentences);
6595
+ const committed = committedLines(report.check);
6596
+ if (committed.length > 0) lines.push("", ...committed);
6597
+ for (const record of revealedOf(report.check)) {
6598
+ lines.push("", SHARED_RECORD_WORDS.revealedHeading(record.number));
6599
+ for (const entry of record.entries) {
6600
+ lines.push(`Entry ${entry.entry}`);
6601
+ for (const field of entry.fields) lines.push(` ${field.pointer}: ${JSON.stringify(field.value)}`);
6602
+ if (entry.withheld > 0) lines.push(` ${notShown(entry.withheld)}`);
6603
+ }
6604
+ }
6605
+ return `${lines.join("\n")}
6606
+ `;
6607
+ }
6608
+ function renderLinkHtml(input) {
6609
+ const { report } = input;
6610
+ const body = [
6611
+ `<h1>${escapeHtml(SHARED_RECORD_WORDS.title)}</h1>`,
6612
+ "<table>",
6613
+ ...factsOf(report).map(([label, value]) => `<tr><th>${escapeHtml(label)}</th><td>${escapeHtml(value)}</td></tr>`),
6614
+ "</table>",
6615
+ ...report.sentences.map((sentence) => `<p>${escapeHtml(sentence)}</p>`)
6616
+ ];
6617
+ const committed = committedLines(report.check);
6618
+ if (committed.length > 0) {
6619
+ body.push(`<h2>${escapeHtml(committed[0])}</h2>`, "<ul>", ...committed.slice(1).map((line) => `<li>${escapeHtml(line)}</li>`), "</ul>");
6620
+ }
6621
+ for (const record of revealedOf(report.check)) {
6622
+ body.push(`<h2>${escapeHtml(SHARED_RECORD_WORDS.revealedHeading(record.number))}</h2>`);
6623
+ for (const entry of record.entries) {
6624
+ body.push(`<h3>Entry ${entry.entry}</h3>`, "<table>");
6625
+ for (const field of entry.fields) body.push(`<tr><th>${escapeHtml(field.pointer)}</th><td>${escapeHtml(JSON.stringify(field.value))}</td></tr>`);
6626
+ body.push("</table>");
6627
+ if (entry.withheld > 0) body.push(`<p>${escapeHtml(notShown(entry.withheld))}</p>`);
6628
+ }
6629
+ }
6630
+ body.push(`<footer>Made by ${CHECKER_NAME} ${escapeHtml(input.version)} on ${dayOfUtc(input.now.toISOString())} (UTC).</footer>`);
6631
+ return [
6632
+ "<!DOCTYPE html>",
6633
+ '<html lang="en">',
6634
+ "<head>",
6635
+ '<meta charset="utf-8">',
6636
+ `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">`,
6637
+ '<meta name="referrer" content="no-referrer">',
6638
+ `<title>${escapeHtml(SHARED_RECORD_WORDS.title)}</title>`,
6639
+ "<style>body{font-family:system-ui,sans-serif;max-width:52rem;margin:2rem auto;padding:0 1rem;line-height:1.5}th{text-align:left;padding-right:1rem;vertical-align:top;font-weight:600}td{word-break:break-all}footer{margin-top:2rem;color:#555}</style>",
6640
+ "</head>",
6641
+ "<body>",
6642
+ ...body,
6643
+ "</body>",
6644
+ "</html>",
6645
+ ""
6646
+ ].join("\n");
6647
+ }
6648
+ async function finish(io, args, report, copy) {
6649
+ io.stdout(args.json ? `${JSON.stringify(report, null, 2)}
6650
+ ` : renderLinkReport(report));
6651
+ if (args.copy) {
6652
+ if (copy) {
6653
+ await writeNew(io, args.copy, copy.bytes);
6654
+ io.stderr(`${copy.fields === "opened" ? SHARED_RECORD_WORDS.savedCopy(args.copy) : SHARED_RECORD_WORDS.savedCopyNoFields(args.copy)}
6655
+ `);
6656
+ } else {
6657
+ io.stderr(`${SHARED_RECORD_WORDS.copyNotSaved}
6658
+ `);
6659
+ }
6660
+ }
6661
+ if (args.html) {
6662
+ const page = renderLinkHtml({ report, version: CHECKER_VERSION, now: io.now ? io.now() : /* @__PURE__ */ new Date() });
6663
+ await writeNew(io, args.html, new TextEncoder().encode(page));
6664
+ io.stderr(`${savedReportSentence(args.html)}
6665
+ `);
6666
+ }
6667
+ return report.exitCode;
6668
+ }
6669
+ function progressOf(io) {
6670
+ return (done, of) => {
6671
+ if (of > RECORDS_LISTED_MAX && done < of && done % RECORDS_LISTED_MAX === 0) io.stderr(`${SHARED_RECORD_WORDS.progress(done, of)}
6672
+ `);
6673
+ };
6674
+ }
6675
+ async function runSharedRecordLink(input) {
6676
+ const { address, origin, args, io } = input;
6677
+ if (args.full && typeof args.source === "object") throw new OpenStop(SHARED_RECORD_WORDS.fullNeedsMirror, 2);
6678
+ const host = linkHostOf(`${origin.origin}/api/v1/s/${encodeURIComponent(address.handle)}`, io, args.timeoutMs ?? LINK_TIMEOUT_MS);
6679
+ const ask = async (path, init) => {
4626
6680
  try {
4627
- return computeSealHistoryDigestV1(form);
6681
+ return await host.ask(path, init);
4628
6682
  } catch {
4629
- return "";
6683
+ throw new OpenStop(hostUnreachableSentence(origin.host), 3);
4630
6684
  }
4631
- })();
4632
- const base = {
4633
- checker: { name: CHECKER_NAME, version: CHECKER_VERSION },
4634
- form: formName,
4635
- reference: String(form?.recordKey ?? ""),
4636
- fingerprint: typeof form?.digest === "string" ? form.digest : null,
4637
- computedFingerprint,
4638
- statementFingerprint: options.statementFingerprint?.trim() || null,
4639
- queued: (Array.isArray(form?.pending) ? form.pending : []).filter((p) => p?.status === "queued" && typeof p.seq === "number").map((p) => p.seq).sort((a, b) => a - b)
4640
6685
  };
4641
- const entries = entryCountOf(form, layouts);
4642
- if (options.source === "offline" || !verification.schemaOk || !verification.digestOk) {
4643
- return buildSealsReport({
4644
- ...base,
4645
- entries,
4646
- verification,
4647
- source: { compared: false, reason: "offline" },
4648
- disclosure: disclosure ? { kind: "not-checked" } : null,
4649
- heldFile: options.heldFile ? heldFileOutcome(options.heldFile, [], options.source === "offline") : null
6686
+ const state = await ask("");
6687
+ if (state.status !== 200) stopOn(state, origin.host);
6688
+ const serving = state.json?.state;
6689
+ if (serving === "off" || serving === "ended") {
6690
+ const refused = await ask("/record.json?v=2");
6691
+ if (refused.status !== 200) stopOn(refused, origin.host);
6692
+ }
6693
+ if (serving !== "open") throw new OpenStop(LINK_CODE_WORDS.MANIFEST_INVALID, 1);
6694
+ const code = await input.askCode(SHARED_RECORD_WORDS.codeOnce(origin.host));
6695
+ if (!code || !code.trim()) throw new OpenStop(SHARED_RECORD_WORDS.noCode, 2);
6696
+ const opened = await ask("/open", { method: "POST", body: { code: code.trim() } });
6697
+ if (opened.status !== 200) stopOn(opened, origin.host);
6698
+ const token = opened.json?.token;
6699
+ if (typeof token !== "string" || !TOKEN.test(token)) throw new OpenStop(hostUnreachableSentence(origin.host), 3);
6700
+ const linkKey = readDisclosureFragmentV1(`#${address.fragment}`);
6701
+ try {
6702
+ const progress = progressOf(io);
6703
+ const check2 = await checkSharedRecordV1({
6704
+ handle: address.handle,
6705
+ source: linkSourceOf(host, token),
6706
+ linkKey,
6707
+ layouts: getPublishedLayoutRegistry(),
6708
+ proofLayer: proofLayerFor({ source: args.source, full: args.full, timeoutMs: args.timeoutMs, fetchImpl: io.fetchImpl, pace: paceOf(io) }),
6709
+ full: args.full,
6710
+ inFlight: 4,
6711
+ keep: !!args.copy,
6712
+ onRecord: (_record, at) => progress(at.done, at.of),
6713
+ ...io.sleep ? { sleep: io.sleep } : {},
6714
+ ...io.now ? { now: () => io.now().getTime() } : {}
4650
6715
  });
6716
+ const report = buildLinkReport(check2, { host: origin.addressHost, readFrom: origin.origin, pacspace: origin.pacspace }, false);
6717
+ let copy = null;
6718
+ if (args.copy && check2.kept) {
6719
+ try {
6720
+ const built = buildSharedRecordCopyV1({ kept: check2.kept, handle: address.handle });
6721
+ copy = { bytes: built.bytes, fields: built.copy.fields };
6722
+ } catch {
6723
+ copy = null;
6724
+ }
6725
+ }
6726
+ return await finish(io, args, report, copy);
6727
+ } finally {
6728
+ linkKey?.fill(0);
6729
+ await host.ask("/sign-out", { method: "POST", bearer: token }).catch(() => void 0);
4651
6730
  }
4652
- let source;
4653
- let reader = null;
6731
+ }
6732
+ async function runSharedRecordCopy(input) {
6733
+ const { args, io } = input;
6734
+ if (args.source === "offline") throw new OpenStop(SHARED_RECORD_WORDS.copyOffline, 2);
6735
+ if (args.full && typeof args.source === "object") throw new OpenStop(SHARED_RECORD_WORDS.fullNeedsMirror, 2);
6736
+ let read;
4654
6737
  try {
4655
- const found = readerFor(form.chain, options);
4656
- reader = options.full ? memoizeSequenceReads(found.reader) : found.reader;
4657
- const chainWord = await reader.getRecord(form.recordKey);
4658
- verification = verifyRecordSealHistoryV1(form, { layouts, chainWord });
4659
- const contractMatches = reader.contractAddress.toLowerCase() === String(form.chain.contractAddress).toLowerCase();
4660
- const wordMatches = form.currentWord === null ? BigInt(chainWord) === 0n : verification.chainWordMatches === true;
4661
- const ledgerMatches = options.full && form.ledger ? ledgerAgrees(form, await readLedgerMaterial(reader, [], {})) : true;
4662
- const matches = contractMatches && wordMatches && ledgerMatches;
4663
- source = {
4664
- compared: true,
4665
- matches,
4666
- chainId: form.chain.chainId,
4667
- readsFrom: found.readsFrom,
4668
- contractAddress: reader.contractAddress.toLowerCase(),
4669
- detail: contractMatches ? null : "The record was committed somewhere other than where this file says."
4670
- };
4671
- } catch (error) {
4672
- if (error instanceof HistoryFileError) throw error;
4673
- source = notReached(error);
4674
- reader = null;
4675
- }
4676
- let disclosureOutcome = null;
4677
- if (disclosure) {
4678
- disclosureOutcome = verification.verified ? await checkDisclosure(form, disclosure, reader, options.onRevealed) : { kind: "not-checked" };
4679
- }
4680
- const held = options.heldFile ? heldFileOutcome(options.heldFile, disclosureOutcome?.kind === "verified" ? disclosureOutcome.payloads : [], false) : null;
4681
- return buildSealsReport({
4682
- ...base,
4683
- entries,
4684
- verification,
4685
- source,
4686
- disclosure: disclosureOutcome,
4687
- heldFile: held
6738
+ read = sharedRecordCopySourceV1(input.copy, input.address ? input.address.handle : null);
6739
+ } catch {
6740
+ throw new OpenStop(SHARED_RECORD_WORDS.copyAddress, 2);
6741
+ }
6742
+ const progress = progressOf(io);
6743
+ const check2 = await checkSharedRecordV1({
6744
+ handle: read.handle,
6745
+ source: read.source,
6746
+ layouts: getPublishedLayoutRegistry(),
6747
+ proofLayer: proofLayerFor({ source: args.source, full: args.full, timeoutMs: args.timeoutMs, fetchImpl: io.fetchImpl, pace: paceOf(io) }),
6748
+ full: args.full,
6749
+ inFlight: 4,
6750
+ onRecord: (_record, at) => progress(at.done, at.of),
6751
+ ...io.sleep ? { sleep: io.sleep } : {},
6752
+ ...io.now ? { now: () => io.now().getTime() } : {}
4688
6753
  });
6754
+ return finish(io, { copy: null, html: null, json: args.json }, buildLinkReport(check2, null, true), null);
4689
6755
  }
4690
6756
 
4691
6757
  // src/open.ts
4692
- var import_node_path = require("node:path");
4693
6758
  var LINK_PROMPT = "Paste the link, then press Enter:";
4694
6759
  var LINK_IN_ARGV_SENTENCE = "The link was given on the command line, where your shell history and other programs on this machine can see it. Next time, run open and paste the link when it asks.";
4695
6760
  var NOT_A_LINK_SENTENCE = "This is not a PacSpace record link. A record link looks like https://<host>/c/<handle>/.";
4696
6761
  var ACCESS_CODE_PROMPT = "This link asks for an access code. Type it, then press Enter:";
4697
- var hostUnreachableSentence = (host) => `The link could not be read from ${host}. Check the connection and run it again.`;
4698
- var NO_KEY_SENTENCE = "This link reveals fields, but it has no key after #. Ask the sender for the whole link.";
4699
6762
  var KEY_DOES_NOT_OPEN_SENTENCE = "The revealed fields didn't open with this link's key. Ask the sender for the whole link.";
4700
6763
  var REVEALED_HEADER = "Revealed fields";
4701
6764
  var savedCopySentence = (path) => `Saved a kept copy to ${path}. Check it again at any time with: npx @pacspace-io/check ${path}`;
4702
- var pathExistsSentence = (path) => `${path} already exists. Choose another path.`;
4703
- var savedReportSentence = (path) => `Saved the report to ${path}. It opens in a browser without a network connection.`;
4704
- var notShown = (k) => `${k} ${k === 1 ? "field" : "fields"} not shown.`;
6765
+ var notShown2 = (k) => `${k} ${k === 1 ? "field" : "fields"} not shown.`;
4705
6766
  var STEP_UP_REQUIRED = "CUSTOMER_LINK_STEP_UP_REQUIRED";
4706
6767
  var LINK_NOT_FOUND = "CUSTOMER_LINK_NOT_FOUND";
4707
- var LINE_MAX_BYTES = 8192;
4708
6768
  var OpenUsageError = class extends Error {
4709
6769
  };
4710
- var OpenStop = class extends Error {
4711
- constructor(message, exitCode) {
4712
- super(message);
4713
- this.exitCode = exitCode;
4714
- }
4715
- };
4716
6770
  function parseOpenArgs(argv) {
4717
- const args = { link: null, linkFile: null, accessCodeFile: null, copy: null, html: null, source: "mirror", timeoutMs: void 0, json: false };
6771
+ const args = { link: null, linkFile: null, accessCodeFile: null, copy: null, html: null, source: "mirror", full: false, timeoutMs: void 0, json: false };
4718
6772
  const takeValue = (flag, index) => {
4719
6773
  const value = argv[index + 1];
4720
6774
  if (value === void 0 || value.startsWith("--")) throw new OpenUsageError(`${flag} needs a value.`);
@@ -4747,6 +6801,9 @@ function parseOpenArgs(argv) {
4747
6801
  args.source = { rpc: takeValue(arg, index) };
4748
6802
  index += 1;
4749
6803
  break;
6804
+ case "--full":
6805
+ args.full = true;
6806
+ break;
4750
6807
  case "--timeout": {
4751
6808
  const parsed = Number(takeValue(arg, index));
4752
6809
  if (!Number.isFinite(parsed) || parsed <= 0) throw new OpenUsageError("--timeout needs a number of milliseconds.");
@@ -4765,62 +6822,16 @@ function parseOpenArgs(argv) {
4765
6822
  }
4766
6823
  return args;
4767
6824
  }
4768
- async function firstLineOf(io, path) {
4769
- let bytes2;
4770
- try {
4771
- bytes2 = await io.readBytes((0, import_node_path.resolve)(path), LINE_MAX_BYTES);
4772
- } catch (error) {
4773
- throw new OpenStop(`The file could not be read: ${error.message}`, 2);
4774
- }
4775
- return new TextDecoder().decode(bytes2).split(/\r?\n/)[0] ?? "";
4776
- }
4777
- function readLink(text) {
4778
- let url;
4779
- try {
4780
- url = new URL((text ?? "").trim());
4781
- } catch {
4782
- throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
4783
- }
4784
- const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
4785
- if (!(url.protocol === "https:" || url.protocol === "http:" && local) || url.username || url.password) {
4786
- throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
4787
- }
4788
- const match = /^\/c\/([^/]+)(?:\/.*)?$/.exec(url.pathname);
4789
- if (!match) throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
4790
- let handle = match[1];
4791
- try {
4792
- handle = decodeURIComponent(handle);
4793
- } catch {
4794
- }
4795
- handle = handle.trim().toLowerCase();
4796
- if (!handle) throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
4797
- return { origin: url.origin, host: url.host, handle, key: readDisclosureFragmentV1(url.hash) };
4798
- }
4799
- var withoutControls = (text) => Array.from(text).filter((ch) => ch.charCodeAt(0) >= 32 && ch.charCodeAt(0) !== 127).join("");
4800
- async function refusalOf(response) {
4801
- try {
4802
- const body = await response.json();
4803
- const code = body?.error?.code ?? body?.code;
4804
- const message = body?.error?.message ?? body?.message;
4805
- return {
4806
- code: typeof code === "string" ? code : null,
4807
- message: typeof message === "string" ? withoutControls(message).trim() || null : null
4808
- };
4809
- } catch {
4810
- return { code: null, message: null };
4811
- }
4812
- }
4813
6825
  function renderRevealed(entries) {
4814
6826
  const lines = [REVEALED_HEADER];
4815
6827
  for (const entry of entries) {
4816
6828
  lines.push(`Entry ${entry.entry}`);
4817
6829
  for (const field of entry.fields) lines.push(` ${field.pointer}: ${JSON.stringify(field.value)}`);
4818
- if (entry.withheld > 0) lines.push(` ${notShown(entry.withheld)}`);
6830
+ if (entry.withheld > 0) lines.push(` ${notShown2(entry.withheld)}`);
4819
6831
  }
4820
6832
  return `${lines.join("\n")}
4821
6833
  `;
4822
6834
  }
4823
- var escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
4824
6835
  function renderOpenHtml(input) {
4825
6836
  const { report, revealed } = input;
4826
6837
  const facts = [
@@ -4833,7 +6844,8 @@ function renderOpenHtml(input) {
4833
6844
  "<table>",
4834
6845
  ...facts.map(([label, value]) => `<tr><th>${escapeHtml(label)}</th><td>${escapeHtml(value)}</td></tr>`),
4835
6846
  "</table>",
4836
- ...report.sentences.map((sentence) => `<p>${escapeHtml(sentence)}</p>`)
6847
+ ...report.sentences.map((sentence) => `<p>${escapeHtml(sentence)}</p>`),
6848
+ ...input.notice ? [`<p>${escapeHtml(input.notice)}</p>`] : []
4837
6849
  ];
4838
6850
  if (revealed.length > 0) {
4839
6851
  body.push(`<h2>${REVEALED_HEADER}</h2>`);
@@ -4843,7 +6855,7 @@ function renderOpenHtml(input) {
4843
6855
  body.push(`<tr><th>${escapeHtml(field.pointer)}</th><td>${escapeHtml(JSON.stringify(field.value))}</td></tr>`);
4844
6856
  }
4845
6857
  body.push("</table>");
4846
- if (entry.withheld > 0) body.push(`<p>${escapeHtml(notShown(entry.withheld))}</p>`);
6858
+ if (entry.withheld > 0) body.push(`<p>${escapeHtml(notShown2(entry.withheld))}</p>`);
4847
6859
  }
4848
6860
  }
4849
6861
  body.push(`<footer>Made by ${CHECKER_NAME} ${escapeHtml(input.version)} on ${dayOfUtc(input.now.toISOString())} (UTC).</footer>`);
@@ -4864,15 +6876,14 @@ function renderOpenHtml(input) {
4864
6876
  ""
4865
6877
  ].join("\n");
4866
6878
  }
4867
- async function writeNew(io, path, bytes2) {
4868
- if (!io.writeNewFile) throw new OpenStop(`The file could not be written: ${path}`, 2);
4869
- try {
4870
- await io.writeNewFile((0, import_node_path.resolve)(path), bytes2, 384);
4871
- } catch (error) {
4872
- if (error.code === "EEXIST") throw new OpenStop(pathExistsSentence(path), 2);
4873
- throw new OpenStop(`The file could not be written: ${error.message}`, 2);
4874
- }
6879
+ function answersAsOf(status, body) {
6880
+ if (status !== 200 || !body || typeof body !== "object" || Array.isArray(body)) return null;
6881
+ const answer = body;
6882
+ if (answer.subjectKind === "TRAIL") return "trail";
6883
+ if (answer.state === "retired") return "balance";
6884
+ return "record";
4875
6885
  }
6886
+ var FIRST_ANSWER_MAX_BYTES = 1024 * 1024;
4876
6887
  async function runOpen(argv, io) {
4877
6888
  let args;
4878
6889
  try {
@@ -4894,30 +6905,69 @@ async function runOpen(argv, io) {
4894
6905
  } else {
4895
6906
  linkText = io.readLine ? await io.readLine({ prompt: LINK_PROMPT }) : null;
4896
6907
  }
4897
- const link = readLink(linkText);
6908
+ const address = readSharedRecordAddressV1(linkText);
6909
+ if (!address) throw new OpenStop(NOT_A_LINK_SENTENCE, 2);
6910
+ const origin = linkOriginOf(address);
6911
+ io.stderr(`${SHARED_RECORD_WORDS.readingFrom(origin.origin)}
6912
+ `);
6913
+ const notice = origin.pacspace ? null : SHARED_RECORD_WORDS.notPacSpace(origin.origin);
6914
+ if (notice) io.stderr(`${notice}
6915
+ `);
4898
6916
  const fetchImpl = io.fetchImpl ?? fetch;
4899
6917
  const timeoutMs = args.timeoutMs ?? 1e4;
4900
- const base = `${link.origin}/api/v1/c/${encodeURIComponent(link.handle)}`;
6918
+ const base = `${origin.origin}/api/v1/c/${encodeURIComponent(address.handle)}`;
4901
6919
  const request = async (tail, init = {}) => {
4902
6920
  const headers = { Accept: "application/json", ...init.headers ?? {} };
4903
6921
  if (cookie) headers.Cookie = cookie;
4904
6922
  try {
4905
6923
  return await fetchImpl(`${base}${tail}`, { method: init.method ?? "GET", headers, body: init.body, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
4906
6924
  } catch {
4907
- throw new OpenStop(hostUnreachableSentence(link.host), 3);
6925
+ throw new OpenStop(hostUnreachableSentence(origin.host), 3);
4908
6926
  }
4909
6927
  };
4910
6928
  const stopWith = async (response) => {
4911
6929
  const refusal = await refusalOf(response);
4912
6930
  if (refusal.message) throw new OpenStop(refusal.message, 2);
4913
- throw new OpenStop(hostUnreachableSentence(link.host), 3);
6931
+ throw new OpenStop(hostUnreachableSentence(origin.host), 3);
4914
6932
  };
6933
+ const codeOf = async () => args.accessCodeFile ? firstLineOf(io, args.accessCodeFile) : io.readLine ? io.readLine({ prompt: ACCESS_CODE_PROMPT, hidden: true }) : null;
6934
+ const first = await request("");
6935
+ let firstBody = null;
6936
+ try {
6937
+ const bytes2 = await bodyWithin(first, FIRST_ANSWER_MAX_BYTES);
6938
+ firstBody = bytes2 === null ? null : JSON.parse(new TextDecoder().decode(bytes2));
6939
+ } catch {
6940
+ firstBody = null;
6941
+ }
6942
+ const answersAs = answersAsOf(first.status, firstBody);
6943
+ const listAddress = sharedRecordAddressOpensV1(address.handle, "trail") === "list";
6944
+ if (listAddress) {
6945
+ if (!first.ok) {
6946
+ const refusal = refusalOfBody(firstBody);
6947
+ throw refusal.message && first.status < 500 ? new OpenStop(refusal.message, 2) : new OpenStop(hostUnreachableSentence(origin.host), 3);
6948
+ }
6949
+ if (answersAs === null || sharedRecordAddressOpensV1(address.handle, answersAs) !== "list") throw new OpenStop(SHARED_RECORD_WORDS.notAListLink, 1);
6950
+ return await runSharedRecordLink({
6951
+ address,
6952
+ origin,
6953
+ args,
6954
+ io,
6955
+ askCode: async (said) => {
6956
+ io.stderr(`${said}
6957
+ `);
6958
+ return codeOf();
6959
+ }
6960
+ });
6961
+ }
6962
+ if (answersAs === "trail") throw new OpenStop(SHARED_RECORD_WORDS.noList, 3);
6963
+ if (args.full) throw new OpenStop(SHARED_RECORD_WORDS.fullOnlyForList, 2);
6964
+ const key = readDisclosureFragmentV1(`#${address.fragment}`);
4915
6965
  let history = await request("/history", { headers: { "X-Record-Entries": "all" } });
4916
6966
  if (history.status === 401) {
4917
6967
  const refusal = await refusalOf(history.clone());
4918
6968
  if (refusal.code === STEP_UP_REQUIRED) {
4919
- const code = args.accessCodeFile ? await firstLineOf(io, args.accessCodeFile) : io.readLine ? await io.readLine({ prompt: ACCESS_CODE_PROMPT, hidden: true }) : null;
4920
- if (!code || !code.trim()) throw new OpenStop(refusal.message ?? hostUnreachableSentence(link.host), 2);
6969
+ const code = await codeOf();
6970
+ if (!code || !code.trim()) throw new OpenStop(refusal.message ?? hostUnreachableSentence(origin.host), 2);
4921
6971
  const verified = await request("/access/verify", {
4922
6972
  method: "POST",
4923
6973
  headers: { "Content-Type": "application/json" },
@@ -4942,15 +6992,15 @@ async function runOpen(argv, io) {
4942
6992
  if (answer.ok) {
4943
6993
  const envelope = (await answer.json().catch(() => null))?.envelope;
4944
6994
  if (typeof envelope === "string") {
4945
- if (!link.key) throw new OpenStop(NO_KEY_SENTENCE, 2);
4946
- const opened = await decryptDisclosureV1({ envelope, key: link.key, handle: link.handle });
6995
+ if (!key) throw new OpenStop(NO_KEY_SENTENCE, 2);
6996
+ const opened = await decryptDisclosureV1({ envelope, key, handle: address.handle });
4947
6997
  if (!opened.ok) throw new OpenStop(KEY_DOES_NOT_OPEN_SENTENCE, 2);
4948
6998
  disclosure = opened.disclosure;
4949
6999
  }
4950
7000
  } else if (answer.status !== 404 || (await refusalOf(answer.clone())).code !== LINK_NOT_FOUND) {
4951
7001
  await stopWith(answer);
4952
7002
  }
4953
- link.key?.fill(0);
7003
+ key?.fill(0);
4954
7004
  let copy;
4955
7005
  try {
4956
7006
  copy = await buildRecordLinkCopyV1({ sealHistory, disclosure });
@@ -4967,10 +7017,13 @@ async function runOpen(argv, io) {
4967
7017
  }
4968
7018
  });
4969
7019
  if (args.json) {
4970
- io.stdout(`${JSON.stringify({ ...report, revealedFields: revealed }, null, 2)}
7020
+ const link = { host: origin.addressHost, readFrom: origin.origin, pacspace: origin.pacspace };
7021
+ io.stdout(`${JSON.stringify({ ...report, revealedFields: revealed, link }, null, 2)}
4971
7022
  `);
4972
7023
  } else {
4973
7024
  io.stdout(renderReport(report));
7025
+ if (notice) io.stdout(`${notice}
7026
+ `);
4974
7027
  if (revealed.length > 0) io.stdout(`
4975
7028
  ${renderRevealed(revealed)}`);
4976
7029
  }
@@ -4980,7 +7033,7 @@ ${renderRevealed(revealed)}`);
4980
7033
  `);
4981
7034
  }
4982
7035
  if (args.html) {
4983
- const page = renderOpenHtml({ report, revealed, version: CHECKER_VERSION, now: io.now ? io.now() : /* @__PURE__ */ new Date() });
7036
+ const page = renderOpenHtml({ report, revealed, version: CHECKER_VERSION, now: io.now ? io.now() : /* @__PURE__ */ new Date(), notice });
4984
7037
  await writeNew(io, args.html, new TextEncoder().encode(page));
4985
7038
  io.stderr(`${savedReportSentence(args.html)}
4986
7039
  `);
@@ -5217,13 +7270,14 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
5217
7270
  }
5218
7271
  base.commit = manifest.commit;
5219
7272
  let report;
7273
+ let entriesMatch;
5220
7274
  try {
5221
- report = await checkHistory(history, {
7275
+ ({ report, entriesMatch } = await checkHistoryWithFacts(history, {
5222
7276
  source: source ?? "mirror",
5223
7277
  timeoutMs,
5224
7278
  fetchImpl,
5225
7279
  heldFile: { sha256: await sha256Hex(manifestRead.bytes), byteLength: String(manifestRead.bytes.length) }
5226
- });
7280
+ }));
5227
7281
  } catch (error) {
5228
7282
  if (error instanceof HistoryFileError) return differs([{ kind: "differs", path: historyPath }]);
5229
7283
  throw error;
@@ -5231,7 +7285,7 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
5231
7285
  if (report.exitCode === 3 || report.source.compared === false && report.source.reason === "unreachable") {
5232
7286
  return unreachable(refusedOf(report.source));
5233
7287
  }
5234
- if (!report.passed) return differs([{ kind: "differs", path: historyPath }]);
7288
+ if (!entriesMatch) return differs([{ kind: "differs", path: historyPath }]);
5235
7289
  const latest = report.record.entries;
5236
7290
  base.latestEntry = latest;
5237
7291
  const matched = report.heldFile?.entries ?? [];
@@ -5317,7 +7371,8 @@ async function checkPinned(origin, anchors, fetchImpl, rawGet, timeoutMs, source
5317
7371
  // src/cli.ts
5318
7372
  var USAGE = `Usage: pacspace-check <history.json> [options]
5319
7373
  pacspace-check <history.json> --key <path>
5320
- pacspace-check open [--link-file <path>] [--access-code-file <path>] [--copy <path>] [--html <path>] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
7374
+ pacspace-check <link-copy.json> [--link-file <path>] [--full] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
7375
+ pacspace-check open [--link-file <path>] [--access-code-file <path>] [--copy <path>] [--html <path>] [--full] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
5321
7376
  pacspace-check release [--origin <url>] [--source <url> | --rpc <url>] [--timeout <ms>] [--json]
5322
7377
  pacspace-check release --origin <url> --release-record <record key>,<network id>,<contract>
5323
7378
 
@@ -5325,6 +7380,10 @@ Checks a PacSpace record history file: every entry against what was
5325
7380
  committed, the file against its own fingerprint, and the record against
5326
7381
  the proof layer. open reads the record from the link's host, and release reads the key pages from the host it checks. Checking a file sends nothing to PacSpace.
5327
7382
 
7383
+ A link may show one record or a list of records. open checks every record
7384
+ of a list against the proof layer, and --copy keeps a copy of the list that
7385
+ can be checked again as a file.
7386
+
5328
7387
  Options:
5329
7388
  --fingerprint <0x...> the fingerprint printed on a statement; the checker
5330
7389
  says whether it names this file
@@ -5333,6 +7392,7 @@ Options:
5333
7392
  --history <path> the seal history or kept copy a disclosure is checked against
5334
7393
  --key <path> the record key for an encrypted history, read from this file (- for stdin)
5335
7394
  --link-file <path> open: read the link from this file instead of asking
7395
+ copy of a link: compare its list with the address of the link in this file
5336
7396
  --access-code-file <path> open: read the access code from this file instead of asking
5337
7397
  --copy <path> open: save a kept copy of what the link shows to a new file
5338
7398
  --html <path> open: save the report as a page that opens without a network connection
@@ -5341,13 +7401,16 @@ Options:
5341
7401
  the one known for the record's network
5342
7402
  --rpc <url> read the proof layer over JSON-RPC at this URL
5343
7403
  --full also read every daily statement
7404
+ list of records, or a copy of one: read each contract's whole log
5344
7405
  --no-lookup do not look up where each entry was committed
5345
7406
  --timeout <ms> network timeout per read (default 10000)
7407
+ list of records: a read of the link's host (default 30000)
5346
7408
  --json print the report as JSON
5347
7409
  --version print the checker's version
5348
7410
  --help print this text
5349
7411
 
5350
7412
  Exit codes: 0 the check passed as asked; 1 it did not, or the file you hold is not in it; 2 the history file, the link, a key, the file you hold, its blinding file or the arguments could not be used; 3 the proof layer or the link's host could not be reached. When more than one applies, 2 comes before 3, and 3 before 1.
7413
+ For a list of records, or a copy of one: 3 also when a record was not checked, and 1 comes before 3, so a record that does not match is reported even when another was not checked.
5351
7414
  `;
5352
7415
  var BLINDING_FILE_INVALID_SENTENCE = "This is not a valid blinding file.";
5353
7416
  var BLINDING_NEEDS_HELD_FILE_SENTENCE = "--blinding needs --held-file.";
@@ -5366,7 +7429,8 @@ function parseArgs(argv) {
5366
7429
  blinding: null,
5367
7430
  history: null,
5368
7431
  key: null,
5369
- noLookup: false
7432
+ noLookup: false,
7433
+ linkFile: null
5370
7434
  };
5371
7435
  const takeValue = (flag, index) => {
5372
7436
  const value = argv[index + 1];
@@ -5376,6 +7440,10 @@ function parseArgs(argv) {
5376
7440
  for (let index = 0; index < argv.length; index += 1) {
5377
7441
  const arg = argv[index];
5378
7442
  switch (arg) {
7443
+ case "--link-file":
7444
+ args.linkFile = takeValue(arg, index);
7445
+ index += 1;
7446
+ break;
5379
7447
  case "--help":
5380
7448
  case "-h":
5381
7449
  args.help = true;
@@ -5505,13 +7573,14 @@ async function readRecordKey(io, from) {
5505
7573
  if (bytes2.length !== 32 || Buffer.from(bytes2).toString("base64url") !== trimmed) throw new ExitTwo(NOT_A_RECORD_KEY_SENTENCE);
5506
7574
  return bytes2;
5507
7575
  }
5508
- async function readHistoryFile(io, path) {
5509
- let bytes2;
7576
+ async function readFileWithin(io, path, max) {
5510
7577
  try {
5511
- bytes2 = await io.readBytes((0, import_node_path2.resolve)(path), RECORD_LINK_COPY_MAX_BYTES_V1 + 1);
7578
+ return await io.readBytes((0, import_node_path2.resolve)(path), max + 1);
5512
7579
  } catch (error) {
5513
7580
  throw new ExitTwo(`The file could not be read: ${error.message}`);
5514
7581
  }
7582
+ }
7583
+ function historyOfBytes(bytes2) {
5515
7584
  if (bytes2.length > RECORD_LINK_COPY_MAX_BYTES_V1) throw new ExitTwo(TOO_LARGE_SENTENCE);
5516
7585
  const file = parseHistoryFile(new TextDecoder().decode(bytes2));
5517
7586
  if ((file.schema === RECORD_DISCLOSURE_SCHEMA_V1 || file.schema === RECORD_DISCLOSURE_SCHEMA_V2) && bytes2.length > RECORD_DISCLOSURE_MAX_BYTES_V1) {
@@ -5519,6 +7588,45 @@ async function readHistoryFile(io, path) {
5519
7588
  }
5520
7589
  return { file, byteLength: bytes2.length };
5521
7590
  }
7591
+ async function readHistoryFile(io, path) {
7592
+ return historyOfBytes(await readFileWithin(io, path, RECORD_LINK_COPY_MAX_BYTES_V1));
7593
+ }
7594
+ var LINK_COPY_MARK = Buffer.from(`"${SHARED_RECORD_COPY_SCHEMA_V1}"`, "utf8");
7595
+ async function readFileToCheck(io, path) {
7596
+ let bytes2 = await readFileWithin(io, path, RECORD_LINK_COPY_MAX_BYTES_V1);
7597
+ if (bytes2.length > RECORD_LINK_COPY_MAX_BYTES_V1) {
7598
+ bytes2 = await readFileWithin(io, path, SHARED_RECORD_COPY_MAX_BYTES_V1);
7599
+ if (bytes2.length > SHARED_RECORD_COPY_MAX_BYTES_V1) throw new ExitTwo(TOO_LARGE_SENTENCE);
7600
+ }
7601
+ if (!Buffer.from(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength).includes(LINK_COPY_MARK)) return { bytes: bytes2 };
7602
+ let json;
7603
+ try {
7604
+ json = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes2));
7605
+ } catch {
7606
+ return { bytes: bytes2 };
7607
+ }
7608
+ if (!json || typeof json !== "object" || json.schema !== SHARED_RECORD_COPY_SCHEMA_V1) return { bytes: bytes2 };
7609
+ const read = readSharedRecordCopyV1(json);
7610
+ if (!read.ok) throw new ExitTwo(SHARED_RECORD_WORDS.copyNotRead);
7611
+ return { linkCopy: read.copy };
7612
+ }
7613
+ async function runLinkCopy(copy, args, io) {
7614
+ const unused = [
7615
+ ["--fingerprint", args.statementFingerprint !== null],
7616
+ ["--held-file", args.heldFile !== null],
7617
+ ["--history", args.history !== null],
7618
+ ["--key", args.key !== null],
7619
+ ["--no-lookup", args.noLookup]
7620
+ ];
7621
+ const given = unused.find(([, set]) => set);
7622
+ if (given) throw new ExitTwo(SHARED_RECORD_WORDS.copyOption(given[0]));
7623
+ let address = null;
7624
+ if (args.linkFile) {
7625
+ address = readSharedRecordAddressV1(await firstLineOf(io, args.linkFile));
7626
+ if (!address) throw new ExitTwo(NOT_A_LINK_SENTENCE);
7627
+ }
7628
+ return runSharedRecordCopy({ copy, address, args: { source: args.source, full: args.full, timeoutMs: args.timeoutMs, json: args.json }, io });
7629
+ }
5522
7630
  async function heldFileDigests(io, heldPath, blindingPath) {
5523
7631
  let blinding = null;
5524
7632
  if (blindingPath) {
@@ -5668,7 +7776,10 @@ ${USAGE}`);
5668
7776
  return 2;
5669
7777
  }
5670
7778
  try {
5671
- const { file } = await readHistoryFile(io, args.file);
7779
+ const read = await readFileToCheck(io, args.file);
7780
+ if ("linkCopy" in read) return await runLinkCopy(read.linkCopy, args, io);
7781
+ if (args.linkFile) throw new ExitTwo(SHARED_RECORD_WORDS.linkFileOnlyForCopy);
7782
+ const { file } = historyOfBytes(read.bytes);
5672
7783
  let history;
5673
7784
  if (args.history) {
5674
7785
  if (file.schema !== RECORD_DISCLOSURE_SCHEMA_V1 && file.schema !== RECORD_DISCLOSURE_SCHEMA_V2) throw new ExitTwo(`${HISTORY_ONLY_FOR_DISCLOSURE_SENTENCE}
@@ -5715,6 +7826,11 @@ ${USAGE}`.trimEnd());
5715
7826
  `);
5716
7827
  return 2;
5717
7828
  }
7829
+ if (error instanceof OpenStop) {
7830
+ io.stderr(`${error.message}
7831
+ `);
7832
+ return error.exitCode;
7833
+ }
5718
7834
  io.stderr(`The check could not run: ${error.message}
5719
7835
  `);
5720
7836
  return 2;
@@ -5739,7 +7855,7 @@ function readTerminalLine(hidden) {
5739
7855
  const stdin = process.stdin;
5740
7856
  return new Promise((resolveLine) => {
5741
7857
  let line = "";
5742
- const finish = (value) => {
7858
+ const finish2 = (value) => {
5743
7859
  stdin.off("data", onData);
5744
7860
  stdin.setRawMode(false);
5745
7861
  stdin.pause();
@@ -5748,13 +7864,13 @@ function readTerminalLine(hidden) {
5748
7864
  };
5749
7865
  const onData = (chunk) => {
5750
7866
  for (const ch of chunk) {
5751
- if (ch === "\r" || ch === "\n") return finish(line);
7867
+ if (ch === "\r" || ch === "\n") return finish2(line);
5752
7868
  if (ch === "") {
5753
7869
  stdin.setRawMode(false);
5754
7870
  process.stderr.write("\n");
5755
7871
  process.exit(130);
5756
7872
  }
5757
- if (ch === "") return finish(line.length > 0 ? line : null);
7873
+ if (ch === "") return finish2(line.length > 0 ? line : null);
5758
7874
  if (ch === "\x7F" || ch === "\b") {
5759
7875
  if (line.length > 0) {
5760
7876
  line = line.slice(0, -1);