paperlint 18.2.2 → 18.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,275 @@
1
+ /**
2
+ * The candidate sources over a fake `Get`: arXiv comment search, the Semantic Scholar listing, the
3
+ * OAI licence and the e-print. Every URL asked is recorded, so a test also sees what was NOT asked.
4
+ */
5
+ import { describe, expect, test } from "vitest";
6
+ import type { Slot } from "./rules.ts";
7
+ import {
8
+ arxivCandidates,
9
+ baseId,
10
+ eprint,
11
+ licenceUrl,
12
+ parseFeed,
13
+ s2Candidates,
14
+ s2Url,
15
+ type Found,
16
+ } from "./sources.ts";
17
+ import { fakeGet } from "./testkit.ts";
18
+
19
+ const entry = (id: string, comment = "Accepted at X 2025") =>
20
+ `<entry><id>http://arxiv.org/abs/${id}</id><updated>2025-06-01T00:00:00Z</updated>
21
+ <title>Paper
22
+ ${id}</title><arxiv:comment>${comment}</arxiv:comment>
23
+ <arxiv:primary_category term="cs.LG"/><author><name>A &amp; B</name></author></entry>`;
24
+ const feed = (...ids: string[]) =>
25
+ `<feed>${ids.map((id) => entry(id)).join("")}</feed>`;
26
+
27
+ const slot: Slot = {
28
+ field: "ml",
29
+ series: "X",
30
+ year: 2025,
31
+ cap: 1,
32
+ queries: ['co:"X 2025"', 'co:"Y 2025"'],
33
+ max_results: 2,
34
+ venue: "x",
35
+ classSpec: "neurips",
36
+ };
37
+ const all = async (g: AsyncGenerator<Found>) => {
38
+ const out: Found[] = [];
39
+ for await (const f of g) out.push(f);
40
+ return out;
41
+ };
42
+ const brief = (fs: readonly Found[]) =>
43
+ fs.map((f) =>
44
+ "searchError" in f ? f : { id: f.id, rank: f.rank, query: f.query },
45
+ );
46
+
47
+ describe("arXiv's feed", () => {
48
+ test("an entry's fields, entities decoded, a missing tag empty", () => {
49
+ // Guards: what a candidate carries into rule 1.
50
+ expect(
51
+ parseFeed(`${feed("2501.00001v2")}<entry><id>x/abs/2</id></entry>`),
52
+ ).toEqual([
53
+ {
54
+ id: "2501.00001v2",
55
+ updated: "2025-06-01",
56
+ title: "Paper 2501.00001v2",
57
+ comment: "Accepted at X 2025",
58
+ journal_ref: "",
59
+ category: "cs.LG",
60
+ authors: ["A & B"],
61
+ },
62
+ {
63
+ id: "2",
64
+ updated: "",
65
+ title: "",
66
+ comment: "",
67
+ journal_ref: "",
68
+ category: "",
69
+ authors: [],
70
+ },
71
+ ]);
72
+ // Guards: the version is dropped from an id.
73
+ expect(baseId("2501.00001v12")).toBe("2501.00001");
74
+ });
75
+ });
76
+
77
+ describe("arXiv comment search", () => {
78
+ test("queries in turn, page by page, a repeated id skipped, ranks in that order", async () => {
79
+ const { get, asked } = fakeGet([
80
+ ["Y+2025%22&sortBy=submittedDate&sortOrder=descending&start=2", feed()],
81
+ [
82
+ "Y+2025%22&sortBy=submittedDate&sortOrder=descending&start=0",
83
+ feed("c", "a"),
84
+ ],
85
+ ["start=0", feed("a", "b")],
86
+ [
87
+ "X+2025%22&sortBy=submittedDate&sortOrder=descending&start=2",
88
+ feed("d"),
89
+ ],
90
+ ]);
91
+ const found = await all(arxivCandidates(get, slot, 3));
92
+ // Guards: the fixed order a reader audits in the probe log.
93
+ expect(brief(found)).toEqual([
94
+ { id: "a", rank: 1, query: 'co:"X 2025"' },
95
+ { id: "b", rank: 2, query: 'co:"X 2025"' },
96
+ { id: "d", rank: 3, query: 'co:"X 2025"' },
97
+ { id: "c", rank: 4, query: 'co:"Y 2025"' },
98
+ ]);
99
+ // Guards: a short page ends a query; no page beyond it is asked.
100
+ expect(asked.length).toBe(4);
101
+ });
102
+
103
+ test("at most maxPages pages, and a failed page ends the slot", async () => {
104
+ const pages = fakeGet([["start=0", feed("a", "b")]]);
105
+ // Guards: maxPages 1 asks one page even when it is full.
106
+ expect(
107
+ brief(
108
+ await all(
109
+ arxivCandidates(pages.get, { ...slot, queries: ['co:"X 2025"'] }, 1),
110
+ ),
111
+ ),
112
+ ).toEqual([
113
+ { id: "a", rank: 1, query: 'co:"X 2025"' },
114
+ { id: "b", rank: 2, query: 'co:"X 2025"' },
115
+ ]);
116
+ const failing = fakeGet([["start=0", { status: "503 after 4 attempts" }]]);
117
+ // Guards: the error is yielded, and the second query is never asked.
118
+ expect(await all(arxivCandidates(failing.get, slot, 3))).toEqual([
119
+ { searchError: 'co:"X 2025" page 0: 503 after 4 attempts' },
120
+ ]);
121
+ expect(failing.asked.length).toBe(1);
122
+ });
123
+ });
124
+
125
+ const s2Page = (
126
+ ids: readonly (string | null | Readonly<{ bare: string }>)[],
127
+ token?: string,
128
+ ) =>
129
+ JSON.stringify({
130
+ ...(token === undefined ? {} : { token }),
131
+ data: ids.map((id) =>
132
+ id === null
133
+ ? { title: null, venue: null }
134
+ : typeof id === "object"
135
+ ? { externalIds: { ArXiv: id.bare } }
136
+ : {
137
+ title: `T${id}`,
138
+ venue: "OSDI",
139
+ publicationDate: null,
140
+ externalIds: { ArXiv: id },
141
+ },
142
+ ),
143
+ });
144
+ const s2Slot: Slot = { ...slot, source: "semantic-scholar", s2Venue: "OSDI" };
145
+
146
+ describe("the Semantic Scholar listing", () => {
147
+ test("the URL names the S2 venue, else the series", () => {
148
+ // Guards: the venue S2 spells, and the fallback.
149
+ expect([s2Url(s2Slot), s2Url(slot)]).toEqual([
150
+ "https://api.semanticscholar.org/graph/v1/paper/search/bulk?query=*&venue=OSDI&year=2025&fields=title,externalIds,venue,year,publicationDate",
151
+ "https://api.semanticscholar.org/graph/v1/paper/search/bulk?query=*&venue=X&year=2025&fields=title,externalIds,venue,year,publicationDate",
152
+ ]);
153
+ });
154
+
155
+ test("pages followed by token, deduplicated, in arXiv-id order, with arXiv's metadata", async () => {
156
+ const { get, asked } = fakeGet([
157
+ ["token=t1", s2Page(["2501.00003", "2501.00001"])],
158
+ ["semanticscholar", s2Page(["2501.00002", null, "2501.00001"], "t1")],
159
+ ["id_list=", feed("2501.00001v1", "2501.00002v3")],
160
+ ]);
161
+ const found = await all(s2Candidates(get, s2Slot));
162
+ // Guards: ranks by arXiv id; an id arXiv does not describe comes with empty metadata.
163
+ expect(
164
+ found.map((f) =>
165
+ "searchError" in f ? f : [f.id, f.rank, f.updated, f.s2],
166
+ ),
167
+ ).toEqual([
168
+ [
169
+ "2501.00001v1",
170
+ 1,
171
+ "2025-06-01",
172
+ { venue: "OSDI", publicationDate: null },
173
+ ],
174
+ [
175
+ "2501.00002v3",
176
+ 2,
177
+ "2025-06-01",
178
+ { venue: "OSDI", publicationDate: null },
179
+ ],
180
+ ["2501.00003", 3, "", { venue: "OSDI", publicationDate: null }],
181
+ ]);
182
+ // Guards: one metadata request for the three ids.
183
+ expect(asked[2]).toBe(
184
+ "https://export.arxiv.org/api/query?id_list=2501.00001,2501.00002,2501.00003&max_results=50",
185
+ );
186
+ });
187
+
188
+ test("a listing stops after 20 pages", async () => {
189
+ // Page i answers with the token of page i+1; checked from the highest, so "p1" never catches "p12".
190
+ const pages = Array.from({ length: 24 }, (_, i) => i + 1)
191
+ .toReversed()
192
+ .map(
193
+ (i) =>
194
+ [
195
+ `token=p${String(i)}`,
196
+ s2Page([String(i)], `p${String(i + 1)}`),
197
+ ] as const,
198
+ );
199
+ const { get, asked } = fakeGet([
200
+ ["id_list=", feed()],
201
+ ...pages,
202
+ ["semanticscholar", s2Page([{ bare: "0" }], "p1")],
203
+ ]);
204
+ await all(s2Candidates(get, s2Slot));
205
+ // Guards: 20 listing pages, then the metadata request.
206
+ expect(asked.filter((u) => u.includes("semanticscholar")).length).toBe(20);
207
+ });
208
+ });
209
+
210
+ describe("the Semantic Scholar listing fails", () => {
211
+ test.each([
212
+ [
213
+ "the listing fails",
214
+ [["semanticscholar", { status: "429 after 4 attempts" }]],
215
+ "s2 429 after 4 attempts",
216
+ ],
217
+ [
218
+ "the listing is not understood",
219
+ [["semanticscholar", "{}"]],
220
+ "s2 answer not understood",
221
+ ],
222
+ [
223
+ "a later page fails",
224
+ [
225
+ ["token=t1", { status: "500" }],
226
+ ["semanticscholar", s2Page(["1"], "t1")],
227
+ ],
228
+ "s2 500",
229
+ ],
230
+ [
231
+ "arXiv's metadata fails",
232
+ [
233
+ ["semanticscholar", s2Page(["1"])],
234
+ ["id_list=", { status: "503" }],
235
+ ],
236
+ "arXiv metadata of listed ids from rank 1: 503",
237
+ ],
238
+ ] as const)("%s: one search error", async (_, routes, searchError) => {
239
+ // Guards: the slot's walk ends with the reason, as the run log shows it.
240
+ expect(await all(s2Candidates(fakeGet(routes).get, s2Slot))).toEqual([
241
+ { searchError },
242
+ ]);
243
+ });
244
+ });
245
+
246
+ describe("the licence and the e-print", () => {
247
+ test("the OAI record's licence, its absence, a failure; the e-print URL", async () => {
248
+ const { get, asked } = fakeGet([
249
+ [
250
+ "2501.00001",
251
+ "<record><license>http://creativecommons.org/licenses/by/4.0/</license></record>",
252
+ ],
253
+ ["2501.00002", "<record/>"],
254
+ ["src/", "bytes"],
255
+ ]);
256
+ // Guards: the three outcomes of the licence lookup, the version dropped from the identifier.
257
+ expect([
258
+ await licenceUrl(get, "2501.00001v2"),
259
+ await licenceUrl(get, "2501.00002"),
260
+ await licenceUrl(get, "2501.00009"),
261
+ ]).toEqual([
262
+ { ok: true, url: "http://creativecommons.org/licenses/by/4.0/" },
263
+ { ok: true, url: undefined },
264
+ { ok: false, status: "404" },
265
+ ]);
266
+ // Guards: the versioned e-print.
267
+ expect((await eprint(get, "2501.00001v2")).ok).toBe(true);
268
+ expect(asked).toEqual([
269
+ "https://export.arxiv.org/oai2?verb=GetRecord&identifier=oai:arXiv.org:2501.00001&metadataPrefix=arXiv",
270
+ "https://export.arxiv.org/oai2?verb=GetRecord&identifier=oai:arXiv.org:2501.00002&metadataPrefix=arXiv",
271
+ "https://export.arxiv.org/oai2?verb=GetRecord&identifier=oai:arXiv.org:2501.00009&metadataPrefix=arXiv",
272
+ "https://arxiv.org/src/2501.00001v2",
273
+ ]);
274
+ });
275
+ });
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Where candidates come from, behind one port (`Get`): arXiv's search API (comment search,
3
+ * `co:"<venue> <year>"`), Semantic Scholar's bulk venue listing, arXiv's OAI record (the licence)
4
+ * and the e-print. URLs are built and answers parsed here; the transport (`http.ts`) and the
5
+ * tests' fakes both plug into `Get`. Candidates come in a FIXED order, each with its 1-based rank.
6
+ */
7
+ import { z } from "zod";
8
+ import { jsonOf } from "./archive.ts";
9
+ import type { Candidate } from "./paper.ts";
10
+ import type { Slot } from "./rules.ts";
11
+
12
+ export type Fetched =
13
+ | Readonly<{ ok: true; bytes: Uint8Array }>
14
+ | Readonly<{ ok: false; status: string }>;
15
+
16
+ /** One GET; the transport throttles and retries, so a caller sees only the final answer. */
17
+ export type Get = (url: string) => Promise<Fetched>;
18
+
19
+ const ARXIV_API = "https://export.arxiv.org/api/query";
20
+ const text = (b: Uint8Array): string => Buffer.from(b).toString("utf8");
21
+ export const baseId = (id: string): string => id.replace(/v\d+$/, "");
22
+
23
+ const decode = (s: string): string =>
24
+ s
25
+ .replace(/&lt;/g, "<")
26
+ .replace(/&gt;/g, ">")
27
+ .replace(/&quot;/g, '"')
28
+ .replace(/&#39;|&apos;/g, "'")
29
+ .replace(/&amp;/g, "&");
30
+
31
+ const tag = (x: string, t: string): string => {
32
+ const m = new RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`).exec(x);
33
+ return m === null ? "" : decode(String(m[1])).replace(/\s+/g, " ").trim();
34
+ };
35
+
36
+ type Entry = Omit<Candidate, "rank" | "query" | "s2">;
37
+
38
+ /** The entries of an arXiv API Atom feed, in feed order. */
39
+ export const parseFeed = (xml: string): readonly Entry[] =>
40
+ [...xml.matchAll(/<entry>([\s\S]*?)<\/entry>/g)].map(([, raw]) => {
41
+ const e = String(raw);
42
+ return {
43
+ id: tag(e, "id").replace(/^.*\/abs\//, ""),
44
+ updated: tag(e, "updated").slice(0, 10),
45
+ title: tag(e, "title"),
46
+ comment: tag(e, "arxiv:comment"),
47
+ journal_ref: tag(e, "arxiv:journal_ref"),
48
+ category: /<arxiv:primary_category[^>]*term="([^"]+)"/.exec(e)?.[1] ?? "",
49
+ authors: [...e.matchAll(/<author>\s*<name>([\s\S]*?)<\/name>/g)].map(
50
+ (m) => decode(String(m[1])).trim(),
51
+ ),
52
+ };
53
+ });
54
+
55
+ /** A candidate, or the reason a source stopped giving them (logged as the slot's search error). */
56
+ export type Found = Candidate | Readonly<{ searchError: string }>;
57
+
58
+ /**
59
+ * arXiv comment search: each query of the slot in turn, page by page (`max_results` a page, at
60
+ * most `maxPages` pages), newest submission first; an id seen earlier in the slot is skipped.
61
+ */
62
+ export async function* arxivCandidates(
63
+ get: Get,
64
+ slot: Slot,
65
+ maxPages: number,
66
+ ): AsyncGenerator<Found> {
67
+ const seen = new Set<string>();
68
+ for (const query of slot.queries) {
69
+ let failed = false; // the page's error is its query's last item; then the slot ends
70
+ for await (const e of searchPages(get, slot, query, maxPages)) {
71
+ failed = "searchError" in e;
72
+ if ("searchError" in e) yield e;
73
+ else if (!seen.has(e.id)) {
74
+ seen.add(e.id);
75
+ yield { ...e, rank: seen.size, query };
76
+ }
77
+ }
78
+ if (failed) return;
79
+ }
80
+ }
81
+
82
+ /** One query's results, page after page, until a short page or `maxPages`. */
83
+ async function* searchPages(
84
+ get: Get,
85
+ slot: Slot,
86
+ query: string,
87
+ maxPages: number,
88
+ ): AsyncGenerator<Entry | Readonly<{ searchError: string }>> {
89
+ for (let page = 0; page < maxPages; page++) {
90
+ const u = new URL(ARXIV_API);
91
+ u.searchParams.set("search_query", query);
92
+ u.searchParams.set("sortBy", "submittedDate");
93
+ u.searchParams.set("sortOrder", "descending");
94
+ u.searchParams.set("start", String(page * slot.max_results));
95
+ u.searchParams.set("max_results", String(slot.max_results));
96
+ const r = await get(u.toString());
97
+ if (!r.ok) {
98
+ yield { searchError: `${query} page ${String(page)}: ${r.status}` };
99
+ return;
100
+ }
101
+ const entries = parseFeed(text(r.bytes));
102
+ yield* entries;
103
+ if (entries.length < slot.max_results) return;
104
+ }
105
+ }
106
+
107
+ const S2Page = z.object({
108
+ token: z.string().nullish(),
109
+ data: z.array(
110
+ z.object({
111
+ title: z.string().nullish(),
112
+ venue: z.string().nullish(),
113
+ publicationDate: z.string().nullish(),
114
+ externalIds: z.object({ ArXiv: z.string().optional() }).nullish(),
115
+ }),
116
+ ),
117
+ });
118
+ type Listed = Readonly<{
119
+ id: string;
120
+ venue: string;
121
+ publicationDate: string | null;
122
+ title: string;
123
+ }>;
124
+
125
+ /** The Semantic Scholar bulk-search URL of one venue edition: the proceedings as S2 lists them. */
126
+ export const s2Url = (slot: Slot): string =>
127
+ `https://api.semanticscholar.org/graph/v1/paper/search/bulk?query=*&venue=${encodeURIComponent(slot.s2Venue ?? slot.series)}&year=${String(slot.year)}&fields=title,externalIds,venue,year,publicationDate`;
128
+
129
+ const listed = (p: z.infer<typeof S2Page>["data"][number]): Listed[] =>
130
+ p.externalIds?.ArXiv === undefined
131
+ ? []
132
+ : [
133
+ {
134
+ id: p.externalIds.ArXiv,
135
+ venue: p.venue ?? "",
136
+ publicationDate: p.publicationDate ?? null,
137
+ title: p.title ?? "",
138
+ },
139
+ ];
140
+
141
+ /** Every page of the listing (at most 20, following `token`), or why it stopped. */
142
+ async function s2Pages(
143
+ get: Get,
144
+ url: string,
145
+ token: string | null = null,
146
+ page = 0,
147
+ ): Promise<readonly Listed[] | string> {
148
+ const r = await get(
149
+ token === null ? url : `${url}&token=${encodeURIComponent(token)}`,
150
+ );
151
+ if (!r.ok) return `s2 ${r.status}`;
152
+ const parsed = S2Page.safeParse(jsonOf(text(r.bytes)));
153
+ if (!parsed.success) return "s2 answer not understood";
154
+ const here = parsed.data.data.flatMap(listed);
155
+ const next = parsed.data.token ?? null;
156
+ if (next === null || page >= 19) return here;
157
+ const rest = await s2Pages(get, url, next, page + 1);
158
+ return typeof rest === "string" ? rest : [...here, ...rest];
159
+ }
160
+
161
+ /** One chunk of listed ids with arXiv's metadata; an id arXiv does not describe has none. */
162
+ async function withMetadata(
163
+ get: Get,
164
+ chunk: readonly Listed[],
165
+ ): Promise<readonly (readonly [Listed, Entry | undefined])[] | string> {
166
+ const r = await get(
167
+ `${ARXIV_API}?id_list=${chunk.map((p) => p.id).join(",")}&max_results=50`,
168
+ );
169
+ if (!r.ok) return r.status;
170
+ const byId = new Map(
171
+ parseFeed(text(r.bytes)).map((e) => [baseId(e.id), e] as const),
172
+ );
173
+ return chunk.map((p) => [p, byId.get(p.id)] as const);
174
+ }
175
+
176
+ /**
177
+ * A Semantic Scholar venue listing: the entries with an arXiv id, in arXiv-id order, each with
178
+ * arXiv's metadata (fetched 50 ids at a time). An id arXiv does not describe comes with empty
179
+ * metadata (`updated` empty), and the collector rejects it.
180
+ */
181
+ export async function* s2Candidates(
182
+ get: Get,
183
+ slot: Slot,
184
+ ): AsyncGenerator<Found> {
185
+ const url = s2Url(slot);
186
+ const pages = await s2Pages(get, url);
187
+ if (typeof pages === "string") {
188
+ yield { searchError: pages };
189
+ return;
190
+ }
191
+ const list = [...new Map(pages.map((p) => [p.id, p])).values()].toSorted(
192
+ (a, b) => (a.id < b.id ? -1 : 1),
193
+ );
194
+ for (let i = 0; i < list.length; i += 50) {
195
+ const chunk = await withMetadata(get, list.slice(i, i + 50));
196
+ if (typeof chunk === "string") {
197
+ yield {
198
+ searchError: `arXiv metadata of listed ids from rank ${String(i + 1)}: ${chunk}`,
199
+ };
200
+ return;
201
+ }
202
+ for (const [j, [p, e]] of chunk.entries())
203
+ yield {
204
+ ...(e ?? { ...NO_METADATA, id: p.id, title: p.title }),
205
+ rank: i + j + 1,
206
+ query: url,
207
+ s2: { venue: p.venue, publicationDate: p.publicationDate },
208
+ };
209
+ }
210
+ }
211
+
212
+ const NO_METADATA = {
213
+ updated: "",
214
+ comment: "",
215
+ journal_ref: "",
216
+ category: "",
217
+ authors: [],
218
+ } as const;
219
+
220
+ /** The `<license>` of arXiv's OAI record of a paper, or undefined for arXiv's default licence. */
221
+ export async function licenceUrl(
222
+ get: Get,
223
+ id: string,
224
+ ): Promise<
225
+ Readonly<
226
+ { ok: true; url: string | undefined } | { ok: false; status: string }
227
+ >
228
+ > {
229
+ const r = await get(
230
+ `https://export.arxiv.org/oai2?verb=GetRecord&identifier=oai:arXiv.org:${baseId(id)}&metadataPrefix=arXiv`,
231
+ );
232
+ return r.ok
233
+ ? { ok: true, url: /<license>([^<]*)<\/license>/.exec(text(r.bytes))?.[1] }
234
+ : r;
235
+ }
236
+
237
+ /** The e-print of one versioned id. */
238
+ export const eprint = (get: Get, id: string): Promise<Fetched> =>
239
+ get(`https://arxiv.org/src/${id}`);
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Builders for the collector's tests: a tar stream written the way arXiv's e-prints are (ustar
3
+ * headers, GNU long names, pax paths), and a fake `Get` routed by URL that records every request.
4
+ * Nothing here touches the disk or the network.
5
+ */
6
+ import { gzipSync } from "node:zlib";
7
+ import type { ArchiveFile } from "./archive.ts";
8
+ import type { Fetched, Get } from "./sources.ts";
9
+
10
+ export type TarIn = Readonly<{
11
+ name: string;
12
+ body?: string;
13
+ /** The tar type flag: "0" a file (the default), "2" a symlink, "5" a directory, "L", "x". */
14
+ type?: string;
15
+ prefix?: string;
16
+ }>;
17
+
18
+ const header = (e: TarIn, size: number): Uint8Array => {
19
+ const h = Buffer.alloc(512);
20
+ h.write(e.name.slice(0, 100), 0, "latin1");
21
+ h.write(`${size.toString(8).padStart(11, "0")}\0`, 124, "latin1");
22
+ h.write(e.type ?? "0", 156, "latin1");
23
+ h.write("ustar\0", 257, "latin1");
24
+ h.write(e.prefix ?? "", 345, "latin1");
25
+ return h;
26
+ };
27
+
28
+ /** A tar stream of the entries, in order, ended by two empty blocks. */
29
+ export const tar = (entries: readonly TarIn[]): Uint8Array =>
30
+ Buffer.concat([
31
+ ...entries.flatMap((e) => {
32
+ const body = Buffer.from(e.body ?? "", "latin1");
33
+ const pad = Buffer.alloc((512 - (body.length % 512)) % 512);
34
+ return [header(e, body.length), body, pad];
35
+ }),
36
+ Buffer.alloc(1024),
37
+ ]);
38
+
39
+ export const tarGz = (entries: readonly TarIn[]): Uint8Array =>
40
+ gzipSync(tar(entries));
41
+
42
+ export const file = (path: string, text: string): ArchiveFile => ({
43
+ path,
44
+ bytes: Buffer.from(text, "latin1"),
45
+ });
46
+
47
+ export const text = (f: ArchiveFile): string =>
48
+ Buffer.from(f.bytes).toString("latin1");
49
+
50
+ /** A main file: a class, a document, and whatever body is given. */
51
+ export const mainTex = (
52
+ body: string,
53
+ cls = "\\documentclass{article}",
54
+ ): string => `${cls}\n\\begin{document}\n${body}\n\\end{document}\n`;
55
+
56
+ export type Route = string | Uint8Array | Readonly<{ status: string }>;
57
+
58
+ /**
59
+ * A `Get` that answers by the first route whose key the URL contains, and records each URL asked.
60
+ * A URL no route matches answers status 404, so a test sees an unexpected request in `asked`.
61
+ */
62
+ export function fakeGet(
63
+ routes: ReadonlyArray<readonly [string, Route]>,
64
+ ): Readonly<{ get: Get; asked: string[] }> {
65
+ const asked: string[] = [];
66
+ const answer = (r: Route | undefined): Fetched =>
67
+ r === undefined
68
+ ? { ok: false, status: "404" }
69
+ : typeof r === "string"
70
+ ? { ok: true, bytes: Buffer.from(r, "utf8") }
71
+ : r instanceof Uint8Array
72
+ ? { ok: true, bytes: r }
73
+ : { ok: false, status: r.status };
74
+ const get: Get = (url) => {
75
+ asked.push(url);
76
+ return Promise.resolve(answer(routes.find(([k]) => url.includes(k))?.[1]));
77
+ };
78
+ return { get, asked };
79
+ }