@eagleoutice/flowr 2.11.0 → 2.12.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 (256) hide show
  1. package/README.md +190 -260
  2. package/abstract-interpretation/data-frame/mappers/arguments.js +7 -1
  3. package/abstract-interpretation/domains/set-range-domain.js +1 -1
  4. package/abstract-interpretation/domains/set-upper-bound-domain.js +6 -2
  5. package/benchmark/slicer.d.ts +1 -1
  6. package/benchmark/slicer.js +3 -1
  7. package/benchmark/summarizer/second-phase/graph.js +5 -0
  8. package/cli/common/options.d.ts +8 -0
  9. package/cli/common/options.js +2 -0
  10. package/cli/common/scripts-info.d.ts +8 -0
  11. package/cli/flowr.js +1 -1
  12. package/cli/repl/commands/repl-commands.d.ts +1 -0
  13. package/cli/repl/commands/repl-commands.js +69 -17
  14. package/cli/repl/commands/repl-dataflow.js +48 -4
  15. package/cli/repl/commands/repl-main.d.ts +2 -0
  16. package/cli/repl/commands/repl-main.js +5 -0
  17. package/cli/repl/commands/repl-query.d.ts +4 -1
  18. package/cli/repl/commands/repl-query.js +72 -22
  19. package/cli/repl/commands/repl-signature.d.ts +7 -0
  20. package/cli/repl/commands/repl-signature.js +119 -0
  21. package/cli/repl/core.d.ts +8 -1
  22. package/cli/repl/core.js +46 -6
  23. package/cli/repl/ghost-hint.d.ts +37 -0
  24. package/cli/repl/ghost-hint.js +72 -0
  25. package/cli/repl/parser/slice-query-parser.d.ts +11 -1
  26. package/cli/repl/parser/slice-query-parser.js +45 -16
  27. package/cli/repl/print-version.d.ts +2 -4
  28. package/cli/repl/print-version.js +41 -23
  29. package/cli/repl/server/connection.js +19 -17
  30. package/cli/slicer-app.d.ts +2 -0
  31. package/cli/slicer-app.js +3 -3
  32. package/cli/wiki.d.ts +2 -2
  33. package/cli/wiki.js +2 -2
  34. package/config.d.ts +70 -13
  35. package/config.js +65 -7
  36. package/control-flow/cfg-dead-code.js +0 -1
  37. package/control-flow/control-flow-graph.js +6 -6
  38. package/control-flow/diff-cfg.js +2 -2
  39. package/control-flow/semantic-cfg-guided-visitor.js +2 -0
  40. package/core/print/slice-diff-ansi.js +8 -8
  41. package/core/steps/all/core/20-dataflow.d.ts +2 -2
  42. package/core/steps/all/static-slicing/00-slice.d.ts +5 -0
  43. package/core/steps/all/static-slicing/00-slice.js +1 -1
  44. package/core/steps/all/static-slicing/10-reconstruct.d.ts +7 -0
  45. package/core/steps/all/static-slicing/10-reconstruct.js +6 -2
  46. package/core/steps/pipeline/default-pipelines.d.ts +20 -16
  47. package/data/r-base-packages.generated.d.ts +44 -0
  48. package/data/r-base-packages.generated.js +32 -0
  49. package/data/r-base-primitives.generated.d.ts +1 -0
  50. package/data/r-base-primitives.generated.js +15 -0
  51. package/data/sigdb/sigdb.remote.json +112 -0
  52. package/dataflow/environments/built-in-proc-name.d.ts +4 -0
  53. package/dataflow/environments/built-in-proc-name.js +4 -0
  54. package/dataflow/environments/built-in.d.ts +14 -4
  55. package/dataflow/environments/built-in.js +13 -2
  56. package/dataflow/environments/data-masking-functions.d.ts +12 -0
  57. package/dataflow/environments/data-masking-functions.js +46 -0
  58. package/dataflow/environments/default-builtin-config.d.ts +72 -19
  59. package/dataflow/environments/default-builtin-config.js +48 -14
  60. package/dataflow/environments/diff.js +1 -1
  61. package/dataflow/environments/environment.js +1 -2
  62. package/dataflow/environments/identifier.d.ts +11 -4
  63. package/dataflow/environments/identifier.js +28 -10
  64. package/dataflow/environments/resolve-by-name.js +16 -2
  65. package/dataflow/extractor.js +6 -3
  66. package/dataflow/graph/call-graph.d.ts +2 -2
  67. package/dataflow/graph/df-helper.d.ts +4 -4
  68. package/dataflow/graph/diff-dataflow-graph.js +2 -2
  69. package/dataflow/graph/edge.d.ts +3 -3
  70. package/dataflow/graph/edge.js +3 -3
  71. package/dataflow/graph/graph-helper.d.ts +2 -2
  72. package/dataflow/internal/linker.js +1 -1
  73. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +7 -0
  74. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +20 -0
  75. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +1 -0
  76. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +2 -49
  77. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +6 -1
  78. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +7 -1
  79. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +19 -0
  80. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +111 -6
  81. package/dataflow/internal/process/functions/call/built-in/built-in-pipe.js +13 -0
  82. package/dataflow/internal/process/functions/call/built-in/built-in-replacement.js +2 -3
  83. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +9 -0
  84. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +19 -0
  85. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +12 -4
  86. package/dataflow/internal/process/functions/call/common.js +8 -1
  87. package/dataflow/internal/process/functions/call/default-call-handling.js +6 -0
  88. package/dataflow/internal/process/functions/call/known-call-handling.d.ts +17 -0
  89. package/dataflow/internal/process/functions/call/known-call-handling.js +32 -0
  90. package/dataflow/internal/process/functions/call/named-call-handling.js +29 -7
  91. package/dataflow/internal/process/functions/process-argument.js +12 -1
  92. package/dataflow/internal/process/process-named-call.d.ts +18 -1
  93. package/dataflow/internal/process/process-named-call.js +94 -0
  94. package/dataflow/processor.d.ts +18 -0
  95. package/documentation/data/faq/faqs.js +5 -1
  96. package/documentation/doc-capabilities.js +1 -1
  97. package/documentation/doc-util/doc-cli-option.d.ts +10 -0
  98. package/documentation/doc-util/doc-cli-option.js +23 -0
  99. package/documentation/doc-util/doc-dfg.js +2 -1
  100. package/documentation/doc-util/doc-query.d.ts +9 -3
  101. package/documentation/doc-util/doc-query.js +9 -4
  102. package/documentation/wiki-dataflow-graph.js +8 -5
  103. package/documentation/wiki-interface.js +3 -2
  104. package/documentation/wiki-linter.js +1 -1
  105. package/documentation/wiki-linting-and-testing.js +4 -1
  106. package/documentation/wiki-mk/doc-context.d.ts +14 -0
  107. package/documentation/wiki-mk/doc-context.js +3 -0
  108. package/documentation/wiki-mk/doc-maker.js +3 -1
  109. package/documentation/wiki-query.js +19 -1
  110. package/documentation/wiki-setup.js +10 -7
  111. package/documentation/wiki-signature-database.d.ts +16 -0
  112. package/documentation/wiki-signature-database.js +293 -0
  113. package/linter/linter-format.d.ts +7 -0
  114. package/linter/linter-rules.d.ts +10 -9
  115. package/linter/rules/naming-convention.d.ts +1 -0
  116. package/linter/rules/naming-convention.js +2 -0
  117. package/linter/rules/no-leaked-credentials.js +1 -2
  118. package/linter/rules/roxygen-arguments.js +18 -5
  119. package/linter/rules/stop-with-call-arg.js +2 -2
  120. package/linter/rules/undefined-symbol-util.d.ts +36 -0
  121. package/linter/rules/undefined-symbol-util.js +149 -0
  122. package/linter/rules/undefined-symbol.d.ts +58 -17
  123. package/linter/rules/undefined-symbol.js +143 -33
  124. package/linter/rules/unused-definition.d.ts +8 -1
  125. package/linter/rules/unused-definition.js +126 -1
  126. package/package.json +23 -10
  127. package/project/context/abstract-flowr-analyzer-context.js +7 -1
  128. package/project/context/flowr-analyzer-context.d.ts +8 -0
  129. package/project/context/flowr-analyzer-context.js +10 -0
  130. package/project/context/flowr-analyzer-dependencies-context.d.ts +28 -4
  131. package/project/context/flowr-analyzer-dependencies-context.js +53 -1
  132. package/project/context/flowr-analyzer-files-context.d.ts +1 -0
  133. package/project/context/flowr-analyzer-files-context.js +2 -1
  134. package/project/context/flowr-analyzer-functions-context.js +1 -1
  135. package/project/context/flowr-file.d.ts +5 -0
  136. package/project/context/flowr-file.js +5 -0
  137. package/project/flowr-analyzer-builder.js +12 -2
  138. package/project/plugins/file-plugins/files/flowr-description-file.js +6 -3
  139. package/project/plugins/file-plugins/files/flowr-namespace-file.js +9 -3
  140. package/project/plugins/file-plugins/files/flowr-news-file.js +1 -3
  141. package/project/plugins/file-plugins/flowr-analyzer-inst-file-plugin.d.ts +26 -0
  142. package/project/plugins/file-plugins/flowr-analyzer-inst-file-plugin.js +39 -0
  143. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-description-file-plugin.js +1 -1
  144. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.js +2 -2
  145. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-namespace-file-plugin.js +1 -0
  146. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.d.ts +18 -2
  147. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.js +19 -0
  148. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +120 -0
  149. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +518 -0
  150. package/project/plugins/package-version-plugins/package.d.ts +5 -3
  151. package/project/plugins/package-version-plugins/package.js +27 -25
  152. package/project/plugins/plugin-registry.d.ts +3 -2
  153. package/project/plugins/plugin-registry.js +4 -2
  154. package/project/plugins/project-discovery/flowr-analyzer-gitignore-project-discovery-plugin.js +7 -2
  155. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +3 -1
  156. package/project/sigdb/build.d.ts +131 -0
  157. package/project/sigdb/build.js +628 -0
  158. package/project/sigdb/codec.d.ts +51 -0
  159. package/project/sigdb/codec.js +122 -0
  160. package/project/sigdb/decode.d.ts +58 -0
  161. package/project/sigdb/decode.js +129 -0
  162. package/project/sigdb/decompress.d.ts +44 -0
  163. package/project/sigdb/decompress.js +176 -0
  164. package/project/sigdb/hash.d.ts +9 -0
  165. package/project/sigdb/hash.js +54 -0
  166. package/project/sigdb/index-format.d.ts +40 -0
  167. package/project/sigdb/index-format.js +28 -0
  168. package/project/sigdb/manifest.d.ts +68 -0
  169. package/project/sigdb/manifest.js +146 -0
  170. package/project/sigdb/reader.d.ts +250 -0
  171. package/project/sigdb/reader.js +692 -0
  172. package/project/sigdb/schema.d.ts +196 -0
  173. package/project/sigdb/schema.js +33 -0
  174. package/project/sigdb/sigdb-download.d.ts +65 -0
  175. package/project/sigdb/sigdb-download.js +237 -0
  176. package/project/sigdb/signature-match.d.ts +26 -0
  177. package/project/sigdb/signature-match.js +40 -0
  178. package/project/sigdb/version.d.ts +20 -0
  179. package/project/sigdb/version.js +55 -0
  180. package/queries/catalog/call-context-query/call-context-query-executor.js +1 -3
  181. package/queries/catalog/config-query/config-query-format.d.ts +3 -1
  182. package/queries/catalog/config-query/config-query-format.js +68 -9
  183. package/queries/catalog/dataflow-query/dataflow-query-format.js +11 -1
  184. package/queries/catalog/dependencies-query/dependencies-query-executor.js +1 -1
  185. package/queries/catalog/linter-query/linter-query-executor.d.ts +2 -0
  186. package/queries/catalog/linter-query/linter-query-executor.js +6 -1
  187. package/queries/catalog/linter-query/linter-query-format.d.ts +2 -1
  188. package/queries/catalog/linter-query/linter-query-format.js +40 -8
  189. package/queries/catalog/project-query/project-query-executor.d.ts +15 -0
  190. package/queries/catalog/project-query/project-query-executor.js +96 -4
  191. package/queries/catalog/project-query/project-query-format.d.ts +44 -0
  192. package/queries/catalog/project-query/project-query-format.js +33 -2
  193. package/queries/catalog/signature-query/signature-query-executor.d.ts +29 -0
  194. package/queries/catalog/signature-query/signature-query-executor.js +461 -0
  195. package/queries/catalog/signature-query/signature-query-format.d.ts +138 -0
  196. package/queries/catalog/signature-query/signature-query-format.js +76 -0
  197. package/queries/catalog/signature-query/signature-query-render.d.ts +15 -0
  198. package/queries/catalog/signature-query/signature-query-render.js +155 -0
  199. package/queries/catalog/static-slice-query/static-slice-query-executor.js +9 -3
  200. package/queries/catalog/static-slice-query/static-slice-query-format.d.ts +10 -0
  201. package/queries/catalog/static-slice-query/static-slice-query-format.js +19 -1
  202. package/queries/query-print.js +5 -0
  203. package/queries/query.d.ts +10 -1
  204. package/queries/query.js +5 -2
  205. package/r-bridge/init.js +5 -1
  206. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.d.ts +10 -0
  207. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.js +55 -0
  208. package/r-bridge/lang-4.x/ast/model/processing/node-id.d.ts +16 -0
  209. package/r-bridge/lang-4.x/ast/model/processing/node-id.js +27 -0
  210. package/r-bridge/lang-4.x/ast/parser/json/format.js +89 -2
  211. package/r-bridge/lang-4.x/ast/parser/main/internal/structure/normalize-expressions.js +2 -4
  212. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize.js +2 -1
  213. package/r-bridge/parser.d.ts +2 -0
  214. package/r-bridge/retriever.js +4 -1
  215. package/r-bridge/roxygen2/documentation-provider.js +2 -1
  216. package/r-bridge/shell.d.ts +5 -0
  217. package/r-bridge/shell.js +17 -1
  218. package/reconstruct/inline/source-inline-map.d.ts +48 -0
  219. package/reconstruct/inline/source-inline-map.js +94 -0
  220. package/reconstruct/reconstruct.d.ts +19 -2
  221. package/reconstruct/reconstruct.js +79 -16
  222. package/search/search-executor/search-generators.js +5 -22
  223. package/search/search-executor/search-transformer.js +10 -6
  224. package/slicing/criterion/parse.d.ts +22 -4
  225. package/slicing/criterion/parse.js +125 -18
  226. package/slicing/static/slice-call.d.ts +24 -1
  227. package/slicing/static/slice-call.js +90 -0
  228. package/slicing/static/static-slicer.d.ts +7 -0
  229. package/slicing/static/static-slicer.js +38 -3
  230. package/util/collections/arrays.d.ts +4 -5
  231. package/util/collections/arrays.js +7 -18
  232. package/util/hash.d.ts +14 -0
  233. package/util/hash.js +31 -0
  234. package/util/mermaid/dfg.d.ts +7 -2
  235. package/util/mermaid/dfg.js +53 -13
  236. package/util/r-base-packages.d.ts +19 -0
  237. package/util/r-base-packages.js +72 -0
  238. package/util/r-license.js +2 -10
  239. package/util/r-version.d.ts +45 -15
  240. package/util/r-version.js +97 -36
  241. package/util/range.d.ts +15 -0
  242. package/util/range.js +39 -0
  243. package/util/schema.d.ts +10 -0
  244. package/util/schema.js +22 -0
  245. package/util/text/ansi.d.ts +13 -1
  246. package/util/text/ansi.js +27 -4
  247. package/util/text/args.js +1 -2
  248. package/util/version.js +28 -8
  249. package/data/pkgdb/pkgdb-latest.json.br +0 -0
  250. package/data/pkgdb/pkgdb-tiny.json.br +0 -0
  251. package/documentation/wiki-package-database.d.ts +0 -9
  252. package/documentation/wiki-package-database.js +0 -63
  253. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-pkgdb-plugin.d.ts +0 -63
  254. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-pkgdb-plugin.js +0 -174
  255. package/project/plugins/package-version-plugins/pkgdb.d.ts +0 -133
  256. package/project/plugins/package-version-plugins/pkgdb.js +0 -370
@@ -0,0 +1,692 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SigDatabaseSet = exports.SigDatabase = void 0;
7
+ exports.readSignatureDb = readSignatureDb;
8
+ exports.getSharedSigSourceSync = getSharedSigSourceSync;
9
+ exports.getSharedSigSource = getSharedSigSource;
10
+ exports.verifyShardedDatabase = verifyShardedDatabase;
11
+ /**
12
+ * The read path for the `flowr-sigdb` package database: fast partial readers for a single bundle
13
+ * ({@link SigDatabase}) and a sharded set ({@link SigDatabaseSet}), the process-wide shared-source cache,
14
+ * whole-bundle reading, and the post-write verification gate. This is the surface the package-version plugin
15
+ * uses; the format/codec/writer building blocks live in the sibling `sigdb/*` modules (imported directly).
16
+ */
17
+ const node_fs_1 = __importDefault(require("node:fs"));
18
+ const node_path_1 = __importDefault(require("node:path"));
19
+ const node_readline_1 = __importDefault(require("node:readline"));
20
+ const r_version_1 = require("../../util/r-version");
21
+ const schema_1 = require("./schema");
22
+ const version_1 = require("./version");
23
+ const index_format_1 = require("./index-format");
24
+ const decode_1 = require("./decode");
25
+ const decompress_1 = require("./decompress");
26
+ const codec_1 = require("./codec");
27
+ const hash_1 = require("./hash");
28
+ const manifest_1 = require("./manifest");
29
+ /** apply one `d` line (`["d", start, payload]`, new newline-blob or legacy `string[]` form) to the dictionary in place */
30
+ function applyDictLine(json, strings) {
31
+ const [, start, payload] = JSON.parse(json);
32
+ const batch = typeof payload === 'string' ? payload.split('\n') : payload;
33
+ for (let k = 0; k < batch.length; k++) {
34
+ strings[start + k] = batch[k];
35
+ }
36
+ }
37
+ function readDictSection(buf, strings) {
38
+ let off = 0;
39
+ while (off < buf.length) {
40
+ let nl = buf.indexOf(0x0a, off);
41
+ if (nl < 0) {
42
+ nl = buf.length;
43
+ }
44
+ if (nl > off) {
45
+ applyDictLine(buf.toString('utf8', off, nl), strings);
46
+ }
47
+ off = nl + 1;
48
+ }
49
+ }
50
+ /** stream-read a whole bundle into a {@link SigDb} (any size; never one string). Prefer {@link SigDatabase} for partial access. */
51
+ async function readSignatureDb(file) {
52
+ const rl = node_readline_1.default.createInterface({ input: (0, decompress_1.sigDbStream)(file), crlfDelay: Infinity });
53
+ let header;
54
+ const strings = [];
55
+ const blobs = [];
56
+ const pkgs = {};
57
+ const meta = {};
58
+ for await (const line of rl) {
59
+ if (line.length === 0) {
60
+ continue;
61
+ }
62
+ if (header === undefined) {
63
+ header = JSON.parse(line);
64
+ continue;
65
+ }
66
+ const tag = line.charCodeAt(2); // '["X",...' -> the tag char
67
+ if (tag === 100 /* d */) {
68
+ applyDictLine(line, strings);
69
+ }
70
+ else if (tag === 98 /* b */) {
71
+ const [, i, tuple] = JSON.parse(line);
72
+ blobs[i] = (0, decode_1.tupleToBlob)(tuple);
73
+ }
74
+ else if (tag === 109 /* m */) {
75
+ const [, , batch] = JSON.parse(line);
76
+ for (const [name, m] of batch) {
77
+ meta[name] = m;
78
+ }
79
+ }
80
+ else if (tag === 112 /* p */) {
81
+ const [, , batch] = JSON.parse(line);
82
+ for (const [name, i] of batch) {
83
+ pkgs[name] = i;
84
+ }
85
+ }
86
+ }
87
+ return { ...header, strings, blobs, pkgs, meta };
88
+ }
89
+ /**
90
+ * Fast, partial reader for a single bundle. `open()`/`openSync()` load the string dictionary + `.idx`
91
+ * once (a single ranged read of the dictionary section -- no full parse), then every query seeks straight
92
+ * to one package blob on demand. `open()` additionally decompresses a `.br`/`.gz` source into a
93
+ * hash-keyed cache and reuses it on later startups. Implements {@link PackageSignatureSource}.
94
+ */
95
+ class SigDatabase {
96
+ closed = false;
97
+ /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; FIFO-bounded to cap memory */
98
+ blobCache = new Map();
99
+ static BlobCacheCap = 2048;
100
+ fd;
101
+ strings;
102
+ index;
103
+ content;
104
+ cranBase;
105
+ constructor(fd, strings, index, content, cranBase) {
106
+ this.fd = fd;
107
+ this.strings = strings;
108
+ this.index = index;
109
+ this.content = content;
110
+ this.cranBase = cranBase;
111
+ }
112
+ /**
113
+ * Open a plain, seekable `.sigs.ndjson` synchronously. Pass `index` to skip reading the `.idx`,
114
+ * and `strings` to use an already-loaded shared dictionary instead of the file's own `d` section (for a
115
+ * blob-only shard). One ranged read loads the dictionary -- no readline overhead.
116
+ */
117
+ static openSync(plainFile, opts = {}) {
118
+ if ((0, decompress_1.isCompressed)(plainFile)) {
119
+ throw new Error('SigDatabase.openSync needs the plain .sigs.ndjson; use open() for .br/.zst/.gz');
120
+ }
121
+ const index = opts.index ?? (0, index_format_1.readSigDbIndex)(plainFile);
122
+ const fd = node_fs_1.default.openSync(plainFile, 'r');
123
+ const head = Buffer.allocUnsafe(Math.min(65536, index.byteCount));
124
+ node_fs_1.default.readSync(fd, head, 0, head.length, 0);
125
+ const header = (0, decompress_1.parseHeader)(head.toString('utf8'));
126
+ let strings = opts.strings;
127
+ if (!strings) {
128
+ strings = [];
129
+ const [dictStart, dictBytes] = index.dict;
130
+ if (dictBytes > 0) {
131
+ const buf = Buffer.allocUnsafe(dictBytes);
132
+ node_fs_1.default.readSync(fd, buf, 0, dictBytes, dictStart);
133
+ readDictSection(buf, strings);
134
+ }
135
+ }
136
+ const cranBase = header?.cranBase ?? schema_1.DefaultCranBase;
137
+ return new SigDatabase(fd, strings, index, header?.content, cranBase);
138
+ }
139
+ /** open a `.sigs.ndjson`, `.br` or `.gz`; compressed sources are decompressed into a hash-keyed cache once */
140
+ static async open(source, opts = {}) {
141
+ return SigDatabase.openSync(await (0, decompress_1.ensurePlain)(source, opts));
142
+ }
143
+ /**
144
+ * Like {@link open} but fully synchronous (blocking decompression); a `hash` keys the cache when `source`
145
+ * is compressed. Pass `strings` for a blob-only shard that shares an already-loaded dictionary.
146
+ */
147
+ static openSyncFrom(source, opts) {
148
+ const plain = (0, decompress_1.isCompressed)(source)
149
+ ? (opts.hash !== undefined ? (0, decompress_1.ensurePlainSync)(source, { cacheDir: opts.cacheDir, hash: opts.hash, index: opts.index })
150
+ : (() => {
151
+ throw new Error('openSyncFrom needs a hash to key the cache for a compressed source');
152
+ })())
153
+ : source;
154
+ return SigDatabase.openSync(plain, { index: opts.index, strings: opts.strings });
155
+ }
156
+ has(pkg) {
157
+ return this.index.pkgs[pkg] !== undefined;
158
+ }
159
+ packageNames() {
160
+ return Object.keys(this.index.pkgs);
161
+ }
162
+ /** load a single package's blob by seeking to its line (undefined if absent); cached by blob index */
163
+ blob(pkg) {
164
+ const blobIdx = this.index.pkgs[pkg];
165
+ if (blobIdx === undefined) {
166
+ return undefined;
167
+ }
168
+ const cached = this.blobCache.get(blobIdx);
169
+ if (cached !== undefined) {
170
+ return cached;
171
+ }
172
+ const blob = this.readBlobAt(this.index.blobs[blobIdx]);
173
+ if (this.blobCache.size >= SigDatabase.BlobCacheCap) {
174
+ const oldest = this.blobCache.keys().next().value;
175
+ if (oldest !== undefined) {
176
+ this.blobCache.delete(oldest);
177
+ }
178
+ }
179
+ this.blobCache.set(blobIdx, blob);
180
+ return blob;
181
+ }
182
+ /** seek to a byte range, read + decode the package blob there (no caching) */
183
+ readBlobAt([start, bytes]) {
184
+ const buf = Buffer.allocUnsafe(bytes);
185
+ node_fs_1.default.readSync(this.fd, buf, 0, bytes, start);
186
+ const [, , tuple] = JSON.parse(buf.toString('utf8'));
187
+ return (0, decode_1.tupleToBlob)(tuple);
188
+ }
189
+ /** read every unique package blob in index order (used to re-hash a whole shard during verification) */
190
+ allBlobs() {
191
+ return this.index.blobs.map(range => this.readBlobAt(range));
192
+ }
193
+ /** recompute this bundle's self-contained content hash from its re-read data (matches {@link writeSignatureDb}) */
194
+ contentHash(blobs = this.allBlobs()) {
195
+ // use only this bundle's own package metadata, in package-index order -- a shared manifest may hoist a
196
+ // superset of metadata that the self-contained bundle was NOT hashed over
197
+ const meta = {};
198
+ for (const pkg of Object.keys(this.index.pkgs)) {
199
+ meta[pkg] = this.index.meta[pkg];
200
+ }
201
+ return (0, hash_1.contentHash)({ strings: this.strings, blobs, pkgs: this.index.pkgs, meta });
202
+ }
203
+ /** whether this bundle actually carries the given version of a package (not just the package) */
204
+ hasVersion(pkg, version) {
205
+ return this.blob(pkg)?.versions[version] !== undefined;
206
+ }
207
+ lookup(pkg, version) {
208
+ const blob = this.blob(pkg);
209
+ const meta = this.index.meta[pkg];
210
+ if (!blob || !meta) {
211
+ return undefined;
212
+ }
213
+ return (0, decode_1.deriveLibraryExports)(this.strings, blob, meta, pkg, version, this.cranBase);
214
+ }
215
+ functions(pkg, version) {
216
+ const blob = this.blob(pkg);
217
+ const meta = this.index.meta[pkg];
218
+ if (!blob || !meta) {
219
+ return undefined;
220
+ }
221
+ const ver = (0, version_1.resolveVersion)(blob, meta[0], version);
222
+ const idxs = ver !== undefined ? (0, decode_1.versionFnIndices)(blob, ver) : undefined;
223
+ return idxs?.map(i => (0, decode_1.decodeFunction)(this.strings, blob, i));
224
+ }
225
+ dependencies(pkg, version) {
226
+ const blob = this.blob(pkg);
227
+ const meta = this.index.meta[pkg];
228
+ if (!blob || !meta) {
229
+ return undefined;
230
+ }
231
+ const ver = (0, version_1.resolveVersion)(blob, meta[0], version);
232
+ return ver !== undefined ? (0, decode_1.decodeDependencies)(this.strings, blob, ver) : undefined;
233
+ }
234
+ /** whether this is an R-core / base package (its versions are the R releases it shipped with; see {@link SigDbPkgMeta}) */
235
+ isBaseR(pkg) {
236
+ return this.index.meta[pkg]?.[3] === 1;
237
+ }
238
+ /**
239
+ * The R versions a base package was part of core, in ascending R-version order (exactly its stored
240
+ * versions). `undefined` for a non-base package. E.g. `mva` returns `…1.9.1`, `parallel` `2.14.0…`.
241
+ */
242
+ coreVersions(pkg) {
243
+ if (!this.isBaseR(pkg)) {
244
+ return undefined;
245
+ }
246
+ return Object.keys(this.blob(pkg)?.versions ?? {}).map(r_version_1.RVersion.parseOrZero).sort((a, b) => r_version_1.RVersion.compare(a.str, b.str));
247
+ }
248
+ /** the release date of a package version (defaulting to the newest release), or `undefined` if unknown */
249
+ releaseDate(pkg, version) {
250
+ const blob = this.blob(pkg);
251
+ const meta = this.index.meta[pkg];
252
+ if (!blob || !meta) {
253
+ return undefined;
254
+ }
255
+ const ver = version ?? (0, version_1.newestVersion)(blob, meta[0]);
256
+ const day = ver !== undefined ? blob.dates[ver] : undefined;
257
+ return day !== undefined ? new Date((0, version_1.dayToMillis)(day)) : undefined;
258
+ }
259
+ /** every known release date of a package, in ascending R-version order (empty when no dates were stored) */
260
+ releaseDates(pkg) {
261
+ return (0, version_1.releasesOf)(this.blob(pkg));
262
+ }
263
+ /** the newest version of a package by release date (falling back to the recorded latest, then SemVer order) */
264
+ latestVersion(pkg) {
265
+ const blob = this.blob(pkg);
266
+ const meta = this.index.meta[pkg];
267
+ const ver = blob && meta ? (0, version_1.newestVersion)(blob, meta[0]) : undefined;
268
+ return ver !== undefined ? r_version_1.RVersion.parseOrZero(ver) : undefined;
269
+ }
270
+ /** close the underlying file descriptor (idempotent; safe to call more than once) */
271
+ close() {
272
+ if (!this.closed) {
273
+ this.closed = true;
274
+ this.blobCache.clear();
275
+ node_fs_1.default.closeSync(this.fd);
276
+ }
277
+ }
278
+ }
279
+ exports.SigDatabase = SigDatabase;
280
+ /** current-tier shards are preferred over full-tier ones (smaller/faster) when both can serve a request */
281
+ function tierRank(ref) {
282
+ return ref.tier === 'current' ? 0 : 1;
283
+ }
284
+ /** apply the include/exclude shard filters (include first, then exclude), preserving manifest order */
285
+ function selectShards(shards, include, exclude) {
286
+ let out = include ? shards.filter(s => include.includes(s.id)) : [...shards];
287
+ if (exclude) {
288
+ out = out.filter(s => !exclude.includes(s.id));
289
+ }
290
+ return out;
291
+ }
292
+ /**
293
+ * A transparent, read-only view over several {@link SigDatabase} shards described by a {@link SigDbManifest}.
294
+ * When the manifest embeds each shard's index (the default), `openManifest()` reads only that small file to
295
+ * build the package to shard routing table.
296
+ */
297
+ class SigDatabaseSet {
298
+ opened;
299
+ manifest;
300
+ /** the directory the manifest's shard/dict paths are relative to */
301
+ baseDir;
302
+ indices;
303
+ /** package name to shard indices, ordered by preference (current before full) */
304
+ routes;
305
+ cacheDir;
306
+ constructor(manifest, baseDir, indices, routes, cacheDir) {
307
+ this.manifest = manifest;
308
+ this.baseDir = baseDir;
309
+ this.indices = indices;
310
+ this.routes = routes;
311
+ this.cacheDir = cacheDir;
312
+ this.opened = new Array(manifest.shards.length).fill(undefined);
313
+ }
314
+ /** read + validate a manifest and apply the include/exclude shard filter */
315
+ static prepManifest(manifestFile, opts) {
316
+ const baseDir = node_path_1.default.dirname(manifestFile);
317
+ const full = (0, manifest_1.readManifestFile)(manifestFile);
318
+ if (full.format !== manifest_1.SigDbManifestMagic) {
319
+ throw new Error(`not a ${manifest_1.SigDbManifestMagic} (got ${String(full.format)})`);
320
+ }
321
+ const active = selectShards(full.shards, opts.includeShards, opts.excludeShards);
322
+ if (active.length === 0) {
323
+ throw new Error('openManifest: no shards left after include/exclude filtering');
324
+ }
325
+ return { baseDir, manifest: { ...full, shards: active } };
326
+ }
327
+ /** build the package to shard routing (current before full) and construct the set from resolved indices */
328
+ static assemble(manifest, baseDir, indices, cacheDir) {
329
+ const order = manifest.shards.map((_, i) => i).sort((a, b) => tierRank(manifest.shards[a]) - tierRank(manifest.shards[b]));
330
+ const routes = new Map();
331
+ for (const i of order) {
332
+ for (const pkg of Object.keys(indices[i].pkgs)) {
333
+ const list = routes.get(pkg);
334
+ if (list) {
335
+ list.push(i);
336
+ }
337
+ else {
338
+ routes.set(pkg, [i]);
339
+ }
340
+ }
341
+ }
342
+ return new SigDatabaseSet(manifest, baseDir, indices, routes, cacheDir);
343
+ }
344
+ static async openManifest(manifestFile, opts = {}) {
345
+ const { baseDir, manifest } = SigDatabaseSet.prepManifest(manifestFile, opts);
346
+ // prefer the embedded (compact) index with hoisted meta
347
+ const indices = await Promise.all(manifest.shards.map(async (s) => s.idx ? (0, index_format_1.decodeIndex)(s.idx, manifest.meta) : (0, index_format_1.readSigDbIndex)(await (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(baseDir, s.path), { cacheDir: opts.cacheDir, hash: s.hash }))));
348
+ return SigDatabaseSet.assemble(manifest, baseDir, indices, opts.cacheDir);
349
+ }
350
+ /**
351
+ * Synchronous {@link openManifest} -- needs every shard to embed its index (the default for the bundles
352
+ * flowR ships). Shards and dictionaries still decompress lazily.
353
+ */
354
+ static openManifestSync(manifestFile, opts = {}) {
355
+ const { baseDir, manifest } = SigDatabaseSet.prepManifest(manifestFile, opts);
356
+ const indices = manifest.shards.map(s => {
357
+ if (!s.idx) {
358
+ throw new Error(`openManifestSync needs every shard to embed its index; shard '${s.id}' does not -- use openManifest`);
359
+ }
360
+ return (0, index_format_1.decodeIndex)(s.idx, manifest.meta);
361
+ });
362
+ return SigDatabaseSet.assemble(manifest, baseDir, indices, opts.cacheDir);
363
+ }
364
+ /** shared dictionaries, loaded (decompressed + parsed) once and cached by id */
365
+ dictCache = new Map();
366
+ /** load (and cache) a shared dictionary's strings, decompressing its `.br` into the cache once */
367
+ dictionaryStrings(dictId) {
368
+ const cached = this.dictCache.get(dictId);
369
+ if (cached) {
370
+ return cached;
371
+ }
372
+ const ref = this.manifest.dicts?.find(d => d.id === dictId);
373
+ if (!ref) {
374
+ throw new Error(`manifest references unknown dictionary '${dictId}'`);
375
+ }
376
+ const plain = (0, decompress_1.ensurePlainSync)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true });
377
+ const strings = [];
378
+ const fd = node_fs_1.default.openSync(plain, 'r');
379
+ try {
380
+ const [start, bytes] = ref.range;
381
+ const buf = Buffer.allocUnsafe(bytes);
382
+ node_fs_1.default.readSync(fd, buf, 0, bytes, start);
383
+ readDictSection(buf, strings);
384
+ }
385
+ finally {
386
+ node_fs_1.default.closeSync(fd);
387
+ }
388
+ this.dictCache.set(dictId, strings);
389
+ return strings;
390
+ }
391
+ /** lazily open a shard -- decompressing its `.br` (and its shared dictionary) into the cache on first access */
392
+ shard(i) {
393
+ const existing = this.opened[i];
394
+ if (existing) {
395
+ return existing;
396
+ }
397
+ const ref = this.manifest.shards[i];
398
+ const strings = ref.dict ? this.dictionaryStrings(ref.dict) : undefined;
399
+ const db = SigDatabase.openSyncFrom((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, index: this.indices[i], strings });
400
+ this.opened[i] = db;
401
+ return db;
402
+ }
403
+ /**
404
+ * Warm the shards (and their shared dictionaries) needed for `pkgs`, or **everything** when omitted.
405
+ * Afterward, the synchronous query methods, for the latest *and* historical versions, do no I/O or decompression.
406
+ */
407
+ async preload(pkgs) {
408
+ const need = new Set();
409
+ if (pkgs) {
410
+ for (const p of pkgs) {
411
+ for (const i of this.routes.get(p) ?? []) {
412
+ need.add(i);
413
+ }
414
+ }
415
+ }
416
+ else {
417
+ this.manifest.shards.forEach((_, i) => need.add(i));
418
+ }
419
+ await this.warmShards(need);
420
+ }
421
+ /**
422
+ * Warm just the shards matching `include`, e.g., only the current-tier top shards (the base + most-downloaded
423
+ * packages) to speed up common lookups without paying for the long tail or the history shards. See {@link preload}.
424
+ */
425
+ async preloadShards(include) {
426
+ const need = new Set();
427
+ this.manifest.shards.forEach((s, i) => {
428
+ if (include(s)) {
429
+ need.add(i);
430
+ }
431
+ });
432
+ await this.warmShards(need);
433
+ }
434
+ /** decompress the given shards + their shared dictionaries concurrently, then open them (see {@link preload}) */
435
+ async warmShards(need) {
436
+ const dicts = new Set();
437
+ for (const i of need) {
438
+ const d = this.manifest.shards[i].dict;
439
+ if (d) {
440
+ dicts.add(d);
441
+ }
442
+ }
443
+ const shardJobs = [...need].map(i => (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, this.manifest.shards[i].path), { cacheDir: this.cacheDir, hash: this.manifest.shards[i].hash, index: this.indices[i] }));
444
+ const dictJobs = [...dicts].map(id => {
445
+ const ref = this.manifest.dicts?.find(d => d.id === id);
446
+ return ref ? (0, decompress_1.ensurePlain)((0, decompress_1.resolveSource)(this.baseDir, ref.path), { cacheDir: this.cacheDir, hash: ref.hash, indexless: true }) : Promise.resolve('');
447
+ });
448
+ await Promise.all([...shardJobs, ...dictJobs]);
449
+ // open each shard from the now-decompressed cache (cheap; parses each shared dictionary once) so later
450
+ // synchronous queries -- including historical, pinned-version lookups -- never block
451
+ for (const i of need) {
452
+ this.shard(i);
453
+ }
454
+ }
455
+ /** the shard indices that can serve this package, preferred order; optionally requiring a specific version */
456
+ route(pkg, version) {
457
+ const candidates = this.routes.get(pkg) ?? [];
458
+ if (version === undefined) {
459
+ return candidates;
460
+ }
461
+ // keep only shards that actually carry the requested version (current shards may hold only the latest)
462
+ return candidates.filter(i => this.shard(i).hasVersion(pkg, version));
463
+ }
464
+ /** read (once) the blob from the shard with the most complete history -- a `full` or `history` tier if present */
465
+ historyBlob(pkg) {
466
+ const candidates = this.routes.get(pkg);
467
+ if (!candidates || candidates.length === 0) {
468
+ return undefined;
469
+ }
470
+ const full = candidates.find(i => this.manifest.shards[i].tier === 'full' || this.manifest.shards[i].tier === 'history');
471
+ return this.shard(full ?? candidates[0]).blob(pkg);
472
+ }
473
+ has(pkg) {
474
+ return this.routes.has(pkg);
475
+ }
476
+ /** whether any active shard actually carries the given version of a package (not just the package) */
477
+ hasVersion(pkg, version) {
478
+ return this.route(pkg, version).length > 0;
479
+ }
480
+ packageNames() {
481
+ return [...this.routes.keys()];
482
+ }
483
+ /** open (blocking) and return every shard database with its manifest ref -- used for whole-set verification */
484
+ allShards() {
485
+ return this.manifest.shards.map((ref, i) => ({ ref, db: this.shard(i) }));
486
+ }
487
+ /** load (and cache) a shared dictionary's strings by id -- for verification/inspection */
488
+ sharedDictionary(id) {
489
+ return this.dictionaryStrings(id);
490
+ }
491
+ /** the first non-empty result from the shards that can serve `pkg` (in preferred order: current before full) */
492
+ firstOf(pkg, version, read) {
493
+ for (const i of this.route(pkg, version)) {
494
+ const r = read(this.shard(i));
495
+ if (r) {
496
+ return r;
497
+ }
498
+ }
499
+ return undefined;
500
+ }
501
+ lookup(pkg, version) {
502
+ return this.firstOf(pkg, version, db => db.lookup(pkg, version));
503
+ }
504
+ functions(pkg, version) {
505
+ return this.firstOf(pkg, version, db => db.functions(pkg, version));
506
+ }
507
+ dependencies(pkg, version) {
508
+ return this.firstOf(pkg, version, db => db.dependencies(pkg, version));
509
+ }
510
+ /** whether this is an R-core / base package (see {@link SigDatabase.isBaseR}); O(1) via the hoisted metadata */
511
+ isBaseR(pkg) {
512
+ const meta = this.manifest.meta?.[pkg];
513
+ if (meta) {
514
+ return meta[3] === 1;
515
+ }
516
+ return this.route(pkg).some(i => this.shard(i).isBaseR(pkg));
517
+ }
518
+ /** the R versions a base package was part of core (ascending); `undefined` if not a base package */
519
+ coreVersions(pkg) {
520
+ if (!this.isBaseR(pkg)) {
521
+ return undefined;
522
+ }
523
+ return Object.keys(this.historyBlob(pkg)?.versions ?? {}).map(r_version_1.RVersion.parseOrZero).sort((a, b) => r_version_1.RVersion.compare(a.str, b.str));
524
+ }
525
+ /** every known release of a package (version + date), ascending -- read once from the most complete shard */
526
+ releaseDates(pkg) {
527
+ return (0, version_1.releasesOf)(this.historyBlob(pkg));
528
+ }
529
+ /** the release date of a package version (defaulting to the newest release), or `undefined` if unknown */
530
+ releaseDate(pkg, version) {
531
+ const blob = this.historyBlob(pkg);
532
+ if (!blob) {
533
+ return undefined;
534
+ }
535
+ const ver = version ?? (0, version_1.newestVersion)(blob, this.manifest.meta?.[pkg]?.[0] ?? '');
536
+ const day = ver !== undefined ? blob.dates[ver] : undefined;
537
+ return day !== undefined ? new Date((0, version_1.dayToMillis)(day)) : undefined;
538
+ }
539
+ /** the newest version of a package by release date (falling back to the recorded latest, then SemVer order) */
540
+ latestVersion(pkg) {
541
+ const blob = this.historyBlob(pkg);
542
+ const ver = blob ? (0, version_1.newestVersion)(blob, this.manifest.meta?.[pkg]?.[0] ?? '') : undefined;
543
+ return ver !== undefined ? r_version_1.RVersion.parseOrZero(ver) : undefined;
544
+ }
545
+ /**
546
+ * Close every opened shard's file descriptor and drop the in-memory caches (opened shards + shared
547
+ * dictionaries), so the (potentially large) dictionary strings can be reclaimed by the GC. Idempotent.
548
+ */
549
+ close() {
550
+ for (const db of this.opened) {
551
+ db?.close();
552
+ }
553
+ this.opened.fill(undefined);
554
+ this.dictCache.clear();
555
+ }
556
+ }
557
+ exports.SigDatabaseSet = SigDatabaseSet;
558
+ const sharedSources = new Map();
559
+ /** whether a bundle path can be opened synchronously (a plain `.sigs.ndjson` or an index-embedding manifest) */
560
+ function isSyncOpenable(source) {
561
+ return (0, codec_1.stripCompressedExt)(source).endsWith('.manifest.json') || source.endsWith(schema_1.SigDbExt);
562
+ }
563
+ /**
564
+ * Open a path-based source once, process-wide, synchronously. Returns the shared instance (opening it on the
565
+ * first call), or `undefined` if the path needs async opening (a `.br`/`.gz` bundle -- use {@link getSharedSigSource}).
566
+ * Throws only if a sync-openable source fails to open.
567
+ */
568
+ function getSharedSigSourceSync(source) {
569
+ const cached = sharedSources.get(source);
570
+ if (cached) {
571
+ return cached;
572
+ }
573
+ if (!isSyncOpenable(source)) {
574
+ return undefined;
575
+ }
576
+ const opened = source.endsWith(schema_1.SigDbExt) ? SigDatabase.openSync(source) : SigDatabaseSet.openManifestSync(source);
577
+ sharedSources.set(source, opened);
578
+ return opened;
579
+ }
580
+ /** Open a path-based source once, process-wide (async: also handles `.br`/`.zst`/`.gz` bundles and non-embedded manifests). */
581
+ async function getSharedSigSource(source) {
582
+ const cached = sharedSources.get(source);
583
+ if (cached) {
584
+ return cached;
585
+ }
586
+ const opened = (0, codec_1.stripCompressedExt)(source).endsWith('.manifest.json')
587
+ ? await SigDatabaseSet.openManifest(source)
588
+ : await SigDatabase.open(source);
589
+ const raced = sharedSources.get(source); // a concurrent opener may have won the race
590
+ if (raced) {
591
+ opened.close();
592
+ return raced;
593
+ }
594
+ sharedSources.set(source, opened);
595
+ return opened;
596
+ }
597
+ /**
598
+ * Re-read a written sharded database from its (compressed) files and check it is internally consistent:
599
+ * every shard's content hash recomputed from its re-read blobs matches both the manifest and the file
600
+ * header; every shared dictionary's hash matches; the manifest routes every package a shard holds; a
601
+ * sample of packages decodes (functions + dependencies) with all string indices in range; and any
602
+ * `requirePackages` (e.g. base R) are present. This is a strong correctness gate: correctness over speed.
603
+ */
604
+ async function verifyShardedDatabase(manifestFile, opts = {}) {
605
+ const errors = [];
606
+ const set = await SigDatabaseSet.openManifest(manifestFile, opts);
607
+ const manifest = set.manifest;
608
+ // 1. every shared dictionary hash matches its re-read strings
609
+ let dictsOk = true;
610
+ for (const dref of manifest.dicts ?? []) {
611
+ const strings = set.sharedDictionary(dref.id);
612
+ const actual = (0, hash_1.dictionaryHash)(strings);
613
+ if (strings.length !== dref.strings) {
614
+ dictsOk = false;
615
+ errors.push(`dictionary '${dref.id}': expected ${dref.strings} strings, re-read ${strings.length}`);
616
+ }
617
+ if (actual !== dref.hash) {
618
+ dictsOk = false;
619
+ errors.push(`dictionary '${dref.id}': hash ${actual} != manifest ${dref.hash}`);
620
+ }
621
+ }
622
+ // 2. every shard's content hash, recomputed from its re-read blobs, matches the manifest and the file header
623
+ const shardResults = [];
624
+ for (const { ref, db } of set.allShards()) {
625
+ const blobs = db.allBlobs();
626
+ // shared-dictionary shards are hashed over blobs+pkgs only; self-contained shards over their whole content
627
+ const actual = ref.dict ? (0, hash_1.shardHash)(blobs, db.index.pkgs) : db.contentHash(blobs);
628
+ const headerHash = db.content?.hash;
629
+ const hashOk = actual === ref.hash && (headerHash === undefined || headerHash === ref.hash);
630
+ if (!hashOk) {
631
+ errors.push(`shard '${ref.id}': recomputed hash ${actual} vs manifest ${ref.hash}${headerHash && headerHash !== ref.hash ? ` (header ${headerHash})` : ''}`);
632
+ }
633
+ const packages = Object.keys(db.index.pkgs).length;
634
+ if (packages !== ref.packages) {
635
+ errors.push(`shard '${ref.id}': manifest says ${ref.packages} packages, index has ${packages}`);
636
+ }
637
+ shardResults.push({ id: ref.id, packages, hashOk, expectedHash: ref.hash, actualHash: actual });
638
+ }
639
+ // 3. routing covers every package that any shard holds
640
+ const routed = new Set(set.packageNames());
641
+ for (const { ref, db } of set.allShards()) {
642
+ for (const pkg of Object.keys(db.index.pkgs)) {
643
+ if (!routed.has(pkg)) {
644
+ errors.push(`package '${pkg}' in shard '${ref.id}' is not routed by the manifest`);
645
+ }
646
+ }
647
+ }
648
+ // 4. spot-check: a spread of packages decodes with all string indices resolving to real strings
649
+ const names = [...routed].sort();
650
+ const sample = opts.sample ?? 200;
651
+ const step = Math.max(1, Math.floor(names.length / sample));
652
+ let spotChecked = 0;
653
+ for (let i = 0; i < names.length; i += step) {
654
+ const pkg = names[i];
655
+ const exp = set.lookup(pkg);
656
+ if (!exp) {
657
+ errors.push(`spot-check: lookup('${pkg}') returned nothing though it is routed`);
658
+ continue;
659
+ }
660
+ const fns = set.functions(pkg);
661
+ for (const f of fns ?? []) {
662
+ if (typeof f.name !== 'string' || (f.file !== undefined && typeof f.file !== 'string')) {
663
+ errors.push(`spot-check: '${pkg}' function decoded with a non-string name/file (dictionary index out of range?)`);
664
+ break;
665
+ }
666
+ for (const p of f.signature) {
667
+ if (typeof p.name !== 'string' || (p.default !== undefined && typeof p.default !== 'string')) {
668
+ errors.push(`spot-check: '${pkg}' param decoded with a non-string name/default (dictionary index out of range?)`);
669
+ break;
670
+ }
671
+ }
672
+ }
673
+ for (const d of set.dependencies(pkg) ?? []) {
674
+ if (typeof d.name !== 'string' || (d.constraint !== undefined && typeof d.constraint !== 'string')) {
675
+ errors.push(`spot-check: '${pkg}' dependency decoded with a non-string name/constraint (dictionary index out of range?)`);
676
+ break;
677
+ }
678
+ }
679
+ spotChecked++;
680
+ }
681
+ // 5. required packages (e.g. base R) are present
682
+ const missingRequired = (opts.requirePackages ?? []).filter(p => !routed.has(p));
683
+ for (const p of missingRequired) {
684
+ errors.push(`required package '${p}' is missing`);
685
+ }
686
+ set.close();
687
+ return {
688
+ ok: errors.length === 0, dictsOk, shards: shardResults,
689
+ routedPackages: routed.size, spotChecked, missingRequired, errors
690
+ };
691
+ }
692
+ //# sourceMappingURL=reader.js.map