@mailwoman/core 10.5.0 → 10.7.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 (50) hide show
  1. package/lib/fs/zip.ts +52 -11
  2. package/lib/geocode/result.ts +46 -0
  3. package/lib/git.ts +357 -55
  4. package/lib/layers/manifest.ts +31 -0
  5. package/lib/layers/schema.ts +14 -0
  6. package/lib/license/obligations.ts +7 -0
  7. package/lib/process.ts +320 -0
  8. package/lib/resources/git.ts +9 -5
  9. package/lib/utils/events.ts +23 -0
  10. package/out/fs/zip.d.ts +14 -1
  11. package/out/fs/zip.d.ts.map +1 -1
  12. package/out/fs/zip.js +45 -10
  13. package/out/fs/zip.js.map +1 -1
  14. package/out/geocode/result.d.ts +25 -0
  15. package/out/geocode/result.d.ts.map +1 -1
  16. package/out/geocode/result.js +40 -0
  17. package/out/geocode/result.js.map +1 -1
  18. package/out/git.d.ts +180 -4
  19. package/out/git.d.ts.map +1 -1
  20. package/out/git.js +227 -37
  21. package/out/git.js.map +1 -1
  22. package/out/layers/manifest.d.ts +19 -0
  23. package/out/layers/manifest.d.ts.map +1 -1
  24. package/out/layers/manifest.js +12 -0
  25. package/out/layers/manifest.js.map +1 -1
  26. package/out/layers/schema.d.ts +10 -0
  27. package/out/layers/schema.d.ts.map +1 -1
  28. package/out/layers/schema.js +4 -0
  29. package/out/layers/schema.js.map +1 -1
  30. package/out/license/obligations.d.ts.map +1 -1
  31. package/out/license/obligations.js +7 -0
  32. package/out/license/obligations.js.map +1 -1
  33. package/out/process.d.ts +146 -0
  34. package/out/process.d.ts.map +1 -1
  35. package/out/process.js +158 -0
  36. package/out/process.js.map +1 -1
  37. package/out/resources/git.d.ts +5 -1
  38. package/out/resources/git.d.ts.map +1 -1
  39. package/out/resources/git.js +8 -5
  40. package/out/resources/git.js.map +1 -1
  41. package/out/tools/download/libpostal-resources.d.ts +2 -2
  42. package/out/tools/download/libpostal-resources.d.ts.map +1 -1
  43. package/out/tools/download/libpostal-resources.js +4 -4
  44. package/out/tools/download/libpostal-resources.js.map +1 -1
  45. package/out/utils/events.d.ts +13 -0
  46. package/out/utils/events.d.ts.map +1 -1
  47. package/out/utils/events.js +19 -0
  48. package/out/utils/events.js.map +1 -1
  49. package/package.json +7 -7
  50. package/tools/download/libpostal-resources.ts +4 -4
@@ -65,6 +65,22 @@ export interface LayerManifest {
65
65
  * A reader distinguishes that from a recorded zero and never reports the two the same way.
66
66
  */
67
67
  sourceRecords: Readonly<Record<string, number>> | null
68
+ /**
69
+ * The URL the build downloaded its input file from, such as a Geofabrik extract's address.
70
+ *
71
+ * `null` or absent means the build did not record it.
72
+ * A build whose input has a share-alike license records it, because the license's database-access
73
+ * terms are met by pointing a recipient at the exact input that produced the artifact.
74
+ */
75
+ sourceURL?: string | null
76
+ /**
77
+ * The SHA-256 of the build's input file as lowercase hex.
78
+ *
79
+ * `null` or absent means the build did not record it.
80
+ * With {@link LayerManifest.sourceURL} it identifies the bytes the artifact was built from,
81
+ * which the URL alone does not when the publisher replaces the file at the same address.
82
+ */
83
+ sourceSHA256?: string | null
68
84
  }
69
85
 
70
86
  export interface CoverageCell {
@@ -195,6 +211,8 @@ export function toLayerManifest(row: Record<string, string | number | null>): La
195
211
  createdAt: String(row.created_at),
196
212
  sourceRecords:
197
213
  row.source_records == null ? null : parseJSONStrict<Record<string, number>>(String(row.source_records)),
214
+ sourceURL: row.source_url == null ? null : String(row.source_url),
215
+ sourceSHA256: row.source_sha256 == null ? null : String(row.source_sha256),
198
216
  }
199
217
 
200
218
  assertManifestInvariants(manifest)
@@ -316,10 +334,19 @@ export function polygonLayerManifest(
316
334
 
317
335
  /**
318
336
  * Insert one validated manifest row.
337
+ *
338
+ * The input-file columns are written only when the manifest carries them.
339
+ * A row stamped into a `layer_manifest` table created before those columns existed then still inserts.
319
340
  */
320
341
  export async function writeLayerManifest(db: layerschemahandle, manifest: LayerManifest): Promise<void> {
321
342
  assertManifestInvariants(manifest)
322
343
 
344
+ if (manifest.sourceSHA256 && !/^[0-9a-f]{64}$/.test(manifest.sourceSHA256)) {
345
+ throw new Error(
346
+ `layer manifest: sourceSHA256 must be 64 lowercase hex characters, got ${stringifyJSON(manifest.sourceSHA256)}`
347
+ )
348
+ }
349
+
323
350
  await db
324
351
  .insertInto("layer_manifest")
325
352
  .values({
@@ -337,6 +364,8 @@ export async function writeLayerManifest(db: layerschemahandle, manifest: LayerM
337
364
  spine_keys: stringifyJSON(manifest.spineKeys),
338
365
  created_at: manifest.createdAt,
339
366
  source_records: manifest.sourceRecords ? stringifyJSON(manifest.sourceRecords) : null,
367
+ ...(manifest.sourceURL ? { source_url: manifest.sourceURL } : {}),
368
+ ...(manifest.sourceSHA256 ? { source_sha256: manifest.sourceSHA256 } : {}),
340
369
  })
341
370
  .execute()
342
371
  }
@@ -370,6 +399,8 @@ export async function readLayerManifest(db: layerschemahandle): Promise<LayerMan
370
399
  // NULL and a missing column both mean the build recorded no count.
371
400
  // An empty object would make the build appear to have counted its publishers and found none.
372
401
  sourceRecords: row.source_records ? parseJSONStrict<Record<string, number>>(row.source_records) : null,
402
+ sourceURL: row.source_url ?? null,
403
+ sourceSHA256: row.source_sha256 ?? null,
373
404
  }
374
405
 
375
406
  assertManifestInvariants(manifest)
@@ -93,6 +93,16 @@ export interface LayerManifestTable {
93
93
  * See `LayerManifest.sourceRecords` in `manifest.ts`.
94
94
  */
95
95
  source_records?: string | null
96
+ /**
97
+ * The URL the build's input file was downloaded from, or NULL when the build did not record it.
98
+ * See `LayerManifest.sourceURL` in `manifest.ts`.
99
+ */
100
+ source_url?: string | null
101
+ /**
102
+ * The SHA-256 of the build's input file as lowercase hex, or NULL when the build did not record it.
103
+ * See `LayerManifest.sourceSHA256` in `manifest.ts`.
104
+ */
105
+ source_sha256?: string | null
96
106
  }
97
107
 
98
108
  /**
@@ -201,6 +211,10 @@ export async function createLayerManifestTable(db: layerschemahandle): Promise<v
201
211
  // Those artifacts read NULL, and `readLayerManifest` returns `sourceRecords: null`.
202
212
  // A build that counted records and found no publishers writes `{}`.
203
213
  .addColumn("source_records", "text")
214
+ // Nullable for the same reason: artifacts built before these columns read NULL, which states
215
+ // that the input file was not recorded rather than that it had no URL or digest.
216
+ .addColumn("source_url", "text")
217
+ .addColumn("source_sha256", "text")
204
218
  .execute()
205
219
  }
206
220
 
@@ -60,6 +60,13 @@ const KNOWN_OBLIGATIONS: ReadonlyMap<string, readonly LicenseObligation[]> = new
60
60
  ["CC-BY-4.0", [LicenseObligation.Attribution]],
61
61
  ["CC0-1.0", []],
62
62
  ["PDDL-1.0", []],
63
+ // The Datenlizenz Deutschland pair.
64
+ // Zero permits any use without restrictions or conditions.
65
+ // Namensnennung requires a source note naming the provider, the license and the dataset URI.
66
+ // It also requires a mark on changed data.
67
+ // Both texts are retained at internal/strategy/rights-receipts/address-skeletons-2026-10-17/.
68
+ ["DL-DE-ZERO-2.0", []],
69
+ ["DL-DE-BY-2.0", [LicenseObligation.Attribution]],
63
70
  // US Government works have no copyright under 17 U.S.C. § 105. SPDX has no identifier for them, so this
64
71
  // `LicenseRef` is defined in docs/engineering/reference/layer-interface.mdx.
65
72
  ["LicenseRef-USGov-Public-Domain", []],
package/lib/process.ts CHANGED
@@ -34,6 +34,9 @@ import { promisify } from "node:util"
34
34
 
35
35
  import type { PathBuilderLike } from "path-ts"
36
36
 
37
+ import type { IRuntimeLogger } from "#logging"
38
+ import { TypedEventTarget } from "#utils/events"
39
+
37
40
  export type {
38
41
  ChildProcess,
39
42
  ChildProcessByStdio,
@@ -219,6 +222,323 @@ export function spawnProcessSync(
219
222
  )
220
223
  }
221
224
 
225
+ /**
226
+ * One step of a long-running command's progress, as a {@linkcode ProgressParser}
227
+ * reads it from a line of output.
228
+ */
229
+ export interface ProcessProgress {
230
+ /**
231
+ * The phase the command reports, such as git's `Receiving objects`.
232
+ */
233
+ stage: string
234
+ /**
235
+ * Completion of the stage, from 0 to 100, when the command states it.
236
+ */
237
+ percent?: number
238
+ processed?: number
239
+ total?: number
240
+ }
241
+
242
+ /**
243
+ * Reads one line of a command's stderr and answers the progress it reports, or `null` for any other line.
244
+ */
245
+ export type ProgressParser = (line: string) => ProcessProgress | null
246
+
247
+ /**
248
+ * How a {@linkcode ProcessTask} ended.
249
+ *
250
+ * `exitCode` is `null` when a signal ended the process, and `signal` is `null` when it exited on its own.
251
+ */
252
+ export interface ProcessResult extends ProcessOutput {
253
+ command: string
254
+ exitCode: number | null
255
+ signal: NodeJS.Signals | null
256
+ }
257
+
258
+ /**
259
+ * The stream a line of output arrived on.
260
+ */
261
+ export const OutputStream = {
262
+ Stdout: "stdout",
263
+ Stderr: "stderr",
264
+ } as const
265
+
266
+ export type OutputStream = (typeof OutputStream)[keyof typeof OutputStream]
267
+
268
+ /**
269
+ * The events a {@linkcode ProcessTask} dispatches, keyed by type, with each event's `detail`.
270
+ */
271
+ export interface ProcessTaskEventMap {
272
+ /**
273
+ * One line of piped output.
274
+ *
275
+ * A carriage return ends a line as a newline does, so each redraw of a progress meter arrives separately.
276
+ */
277
+ line: { stream: OutputStream; text: string }
278
+ progress: ProcessProgress
279
+ exit: ProcessResult
280
+ }
281
+
282
+ /**
283
+ * Options for {@linkcode ProcessTask}.
284
+ */
285
+ export interface ProcessTaskOptions extends Omit<SpawnOptions, "cwd" | "stdio" | "signal"> {
286
+ cwd?: PathBuilderLike
287
+ /**
288
+ * Aborting the signal stops the process as disposal does.
289
+ */
290
+ signal?: AbortSignal
291
+ /**
292
+ * Receives the command line at debug level when the process starts and the result when it ends.
293
+ */
294
+ logger?: IRuntimeLogger
295
+ /**
296
+ * Whether a non-zero exit or a terminating signal rejects `result` with a {@linkcode ProcessError}.
297
+ *
298
+ * With `false`, `result` resolves with the {@linkcode ProcessResult}, and the caller reads `exitCode`.
299
+ *
300
+ * A command that could not start always rejects with the spawn error.
301
+ *
302
+ * @defaultValue `true`
303
+ */
304
+ reject?: boolean
305
+ /**
306
+ * `"pipe"` captures a stream and dispatches its lines.
307
+ * `"inherit"` writes it to this process's terminal.
308
+ *
309
+ * @defaultValue `"ignore"` for stdin, `"pipe"` for stdout and stderr
310
+ */
311
+ stdin?: "ignore" | "inherit" | "pipe"
312
+ stdout?: "ignore" | "inherit" | "pipe"
313
+ stderr?: "ignore" | "inherit" | "pipe"
314
+ /**
315
+ * Leave a piped stdout unread, so the caller consumes `child.stdout` as bytes,
316
+ * such as an archive piped into another process.
317
+ *
318
+ * The task then dispatches no stdout lines, and `result.stdout` is empty.
319
+ */
320
+ rawStdout?: boolean
321
+ /**
322
+ * Reads each stderr line for progress and dispatches a `progress` event for each match.
323
+ */
324
+ progress?: ProgressParser
325
+ /**
326
+ * How long disposal waits after SIGTERM before it sends SIGKILL.
327
+ *
328
+ * @defaultValue 5000
329
+ */
330
+ killGraceMs?: number
331
+ }
332
+
333
+ const DEFAULT_KILL_GRACE_MS = 5000
334
+
335
+ /**
336
+ * A running command that reports its output as events, settles `result` with its
337
+ * {@linkcode ProcessResult}, and is stopped by disposal.
338
+ *
339
+ * It follows the shape of `APIClient`: an `EventTarget` that owns its work
340
+ * and implements `AsyncDisposable`.
341
+ * A caller renders the `line` and `progress` events while the command runs.
342
+ *
343
+ * `await using` stops the command when the caller's scope ends early.
344
+ *
345
+ * Reach for {@linkcode runFile} when the caller needs only the finished output.
346
+ */
347
+ export class ProcessTask extends TypedEventTarget<ProcessTaskEventMap> implements AsyncDisposable {
348
+ public readonly command: string
349
+ public readonly child: ChildProcess
350
+ /**
351
+ * Settles once the process has exited and both streams have closed.
352
+ */
353
+ public readonly result: Promise<ProcessResult>
354
+
355
+ readonly #exited: Promise<void>
356
+ readonly #killGraceMs: number
357
+ readonly #signal: AbortSignal | undefined
358
+ readonly #onAbort = (): void => {
359
+ void this[Symbol.asyncDispose]()
360
+ }
361
+
362
+ #disposePromise: Promise<void> | null = null
363
+
364
+ constructor(file: PathBuilderLike, args: readonly PathBuilderLike[] = [], options: ProcessTaskOptions = {}) {
365
+ super()
366
+
367
+ const {
368
+ cwd,
369
+ signal,
370
+ logger,
371
+ reject = true,
372
+ stdin = "ignore",
373
+ stdout = "pipe",
374
+ stderr = "pipe",
375
+ progress,
376
+ rawStdout = false,
377
+ killGraceMs = DEFAULT_KILL_GRACE_MS,
378
+ ...spawnOptions
379
+ } = options
380
+
381
+ const argStrings = args.map((arg) => arg.toString())
382
+
383
+ this.command = [file.toString(), ...argStrings].join(" ")
384
+ this.#killGraceMs = killGraceMs
385
+ this.#signal = signal
386
+
387
+ signal?.throwIfAborted()
388
+
389
+ logger?.debug(`$ ${this.command}`)
390
+
391
+ this.child = spawn(file.toString(), argStrings, {
392
+ ...spawnOptions,
393
+ cwd: cwd?.toString(),
394
+ stdio: [stdin, stdout, stderr],
395
+ })
396
+
397
+ const captured: Record<OutputStream, string[]> = { stdout: [], stderr: [] }
398
+
399
+ const readLines = (stream: OutputStream, readable: Readable | null): void => {
400
+ if (!readable) return
401
+
402
+ let pending = ""
403
+
404
+ const emit = (text: string): void => {
405
+ captured[stream].push(text)
406
+ this.emit("line", { stream, text })
407
+
408
+ if (stream === OutputStream.Stderr && progress) {
409
+ const step = progress(text)
410
+
411
+ if (step) {
412
+ this.emit("progress", step)
413
+ }
414
+ }
415
+ }
416
+
417
+ readable.setEncoding("utf8")
418
+
419
+ readable.on("data", (chunk: string) => {
420
+ const pieces = (pending + chunk).split(/\r\n|\r|\n/u)
421
+
422
+ pending = pieces.pop() ?? ""
423
+
424
+ for (const piece of pieces) {
425
+ emit(piece)
426
+ }
427
+ })
428
+
429
+ readable.on("end", () => {
430
+ if (pending) {
431
+ emit(pending)
432
+ }
433
+
434
+ pending = ""
435
+ })
436
+ }
437
+
438
+ readLines(OutputStream.Stdout, rawStdout ? null : this.child.stdout)
439
+ readLines(OutputStream.Stderr, this.child.stderr)
440
+
441
+ this.#exited = new Promise<void>((resolve) => {
442
+ this.child.once("close", () => resolve())
443
+ // A process that never started emits `error` and no `close`.
444
+ this.child.once("error", () => resolve())
445
+ })
446
+
447
+ this.result = new Promise<ProcessResult>((resolve, rejectCompletion) => {
448
+ this.child.once("error", rejectCompletion)
449
+
450
+ this.child.once("close", (exitCode: number | null, exitSignal: NodeJS.Signals | null) => {
451
+ const result: ProcessResult = {
452
+ command: this.command,
453
+ exitCode,
454
+ signal: exitSignal,
455
+ stdout: captured.stdout.join("\n"),
456
+ stderr: captured.stderr.join("\n"),
457
+ }
458
+
459
+ logger?.debug(`${this.command} exited with ${exitSignal ?? exitCode}`)
460
+ this.emit("exit", result)
461
+
462
+ if (reject && exitCode !== 0) {
463
+ const error = new Error(
464
+ `Command failed with ${exitSignal ? `signal ${exitSignal}` : `exit code ${exitCode}`}: ${this.command}`
465
+ ) as ProcessError
466
+
467
+ error.stdout = result.stdout
468
+ error.stderr = result.stderr
469
+ error.code = exitCode ?? undefined
470
+ error.signal = exitSignal ?? undefined
471
+
472
+ rejectCompletion(error)
473
+
474
+ return
475
+ }
476
+
477
+ resolve(result)
478
+ })
479
+ }).finally(() => {
480
+ this.#signal?.removeEventListener("abort", this.#onAbort)
481
+ })
482
+
483
+ // A task that is only disposed, never awaited, must not raise an unhandled rejection.
484
+ // Awaiting callers still receive the rejection through `result`.
485
+ this.result.catch(() => undefined)
486
+
487
+ signal?.addEventListener("abort", this.#onAbort, { once: true })
488
+ }
489
+
490
+ /**
491
+ * Disposal sends SIGTERM to a running process, sends SIGKILL if it has not exited
492
+ * after `killGraceMs`, and resolves once it has exited.
493
+ * A process that already exited is left alone.
494
+ *
495
+ * Disposal never rejects.
496
+ * The `result` promise still reports how the process ended.
497
+ * Repeated calls return the same promise.
498
+ */
499
+ public [Symbol.asyncDispose](): Promise<void> {
500
+ if (this.#disposePromise) return this.#disposePromise
501
+
502
+ this.#disposePromise = this.#stop()
503
+
504
+ return this.#disposePromise
505
+ }
506
+
507
+ async #stop(): Promise<void> {
508
+ const { child } = this
509
+
510
+ if (child.exitCode === null && child.signalCode === null && child.pid !== undefined) {
511
+ child.kill("SIGTERM")
512
+
513
+ const escalation = setTimeout(() => child.kill("SIGKILL"), this.#killGraceMs)
514
+
515
+ escalation.unref()
516
+ await this.#exited
517
+ clearTimeout(escalation)
518
+ } else {
519
+ await this.#exited
520
+ }
521
+ }
522
+
523
+ public override toString(): string {
524
+ return this.command
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Run a command to completion as a {@linkcode ProcessTask} and answer its {@linkcode ProcessResult}.
530
+ *
531
+ * With `reject: false` a non-zero exit resolves, and the caller reads `exitCode`.
532
+ * Reach for the task itself when the caller renders its lines or progress while it runs.
533
+ */
534
+ export function runProcess(
535
+ file: PathBuilderLike,
536
+ args: readonly PathBuilderLike[] = [],
537
+ options: ProcessTaskOptions = {}
538
+ ): Promise<ProcessResult> {
539
+ return new ProcessTask(file, args, options).result
540
+ }
541
+
222
542
  /**
223
543
  * Options for {@linkcode forkProcess}.
224
544
  */
@@ -8,7 +8,7 @@ import { PathBuilder, type PathBuilderLike } from "path-ts"
8
8
 
9
9
  import { tryStat } from "#fs/readers/stat"
10
10
  import { makeDirectories } from "#fs/writers"
11
- import { git } from "#git"
11
+ import { GitClient } from "#git"
12
12
 
13
13
  /**
14
14
  * Metadata for a repository source.
@@ -44,22 +44,26 @@ export type SynchronizeAction = "cloned" | "pulled" | "skipped"
44
44
 
45
45
  /**
46
46
  * Synchronize a repository source, i.e. clone or pull the repository.
47
+ *
48
+ * The transfer runs through `client`, so a caller that watches the client's `progress`
49
+ * events sees the clone or pull advance, and disposing the client stops it.
47
50
  */
48
51
  export async function synchronizeRepo(
49
52
  source: RepositorySource,
50
- localRepoDirectory: PathBuilderLike
53
+ localRepoDirectory: PathBuilderLike,
54
+ client: GitClient = new GitClient({ cwd: localRepoDirectory })
51
55
  ): Promise<SynchronizeAction> {
52
56
  if (source.name.includes("deprecated")) return "skipped"
53
57
 
54
- const { ownerDirectory, repoDirectory, exists } = await prepareRepositoryDirectories(source, localRepoDirectory)
58
+ const { repoDirectory, exists } = await prepareRepositoryDirectories(source, localRepoDirectory)
55
59
 
56
60
  if (exists) {
57
- await git("pull", repoDirectory)
61
+ await client.start(["-C", repoDirectory.toString(), "pull", "--progress"]).result
58
62
 
59
63
  return "pulled"
60
64
  }
61
65
 
62
- await git(["clone", "--depth=1", source.url], ownerDirectory)
66
+ await client.clone(source.url, repoDirectory, { depth: 1 })
63
67
 
64
68
  return "cloned"
65
69
  }
@@ -9,3 +9,26 @@
9
9
  * `await once(child, "exit")` — rejecting on its `error`.
10
10
  */
11
11
  export { once } from "node:events"
12
+
13
+ /**
14
+ * An `EventTarget` whose events hold a typed `detail`, keyed by type in `EventMap`.
15
+ *
16
+ * Subclasses dispatch with `emit`, and listeners subscribe with `on`.
17
+ * The base `addEventListener` still works for a caller that wants the `CustomEvent` itself.
18
+ */
19
+ export class TypedEventTarget<EventMap extends object> extends EventTarget {
20
+ /**
21
+ * Listen for one event type with its typed `detail`, answering a function that removes the listener.
22
+ */
23
+ public on<K extends keyof EventMap & string>(type: K, listener: (detail: EventMap[K]) => void): () => void {
24
+ const handler = (event: Event): void => listener((event as CustomEvent<EventMap[K]>).detail)
25
+
26
+ this.addEventListener(type, handler)
27
+
28
+ return () => this.removeEventListener(type, handler)
29
+ }
30
+
31
+ protected emit<K extends keyof EventMap & string>(type: K, detail: EventMap[K]): void {
32
+ this.dispatchEvent(new CustomEvent(type, { detail }))
33
+ }
34
+ }
package/out/fs/zip.d.ts CHANGED
@@ -44,6 +44,19 @@ export interface ZipNameOptions {
44
44
  */
45
45
  filenameEncoding?: string;
46
46
  }
47
+ /**
48
+ * A member name as a path relative to the archive root.
49
+ * Every reader here matches and writes this form.
50
+ *
51
+ * Backslashes become forward slashes and leading slashes are removed, as `unzip` does when it extracts.
52
+ * OS Open Roads' GML archive stores `/data/`, `/doc/licence.txt` and `/readme.txt`
53
+ * beside `data/OSOpenRoads_HP.gml`.
54
+ * A reader that refused a leading slash refused that archive.
55
+ *
56
+ * @throws When the name has a drive letter or a `..` segment, so no member is
57
+ * written outside the extraction directory.
58
+ */
59
+ export declare function memberPath(name: string): string;
47
60
  export type ZipEntryContentPair = [entry: ADMZip.IZipEntry, content: Buffer];
48
61
  /**
49
62
  * Extract the contents of a zip file.
@@ -69,7 +82,7 @@ export type ZipEntrySelector = string | RegExp;
69
82
  */
70
83
  export interface ZipEntryInfo {
71
84
  /**
72
- * The archive-internal path, e.g. `it/countrywide.csv`.
85
+ * The archive-internal path, e.g. `it/countrywide.csv`, as {@link memberPath} normalizes it.
73
86
  *
74
87
  * Directory entries keep their trailing slash.
75
88
  */
@@ -1 +1 @@
1
- {"version":3,"file":"zip.d.ts","sourceRoot":"","sources":["../../lib/fs/zip.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAKH,OAAO,MAAM,MAAM,SAAS,CAAA;AAE5B,OAAO,EAAkC,KAAK,eAAe,EAAE,MAAM,SAAS,CAAA;AA6B9E;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,cAAc;IAC9B;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAA;CACzB;AAiDD,MAAM,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;AAE5E;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC,CAcpF;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAiBhF;AAED;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,MAAM,CAAA;AAE9C;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B;;;;OAIG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ,cAAc,EAAE,MAAM,CAAA;IACtB,gBAAgB,EAAE,MAAM,CAAA;CACxB;AAMD;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,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O,CAAA;IACjB;;OAEG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACtB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,iBAAiB,CACtC,WAAW,EAAE,eAAe,EAC5B,oBAAoB,EAAE,eAAe,EACrC,EAAE,QAAQ,EAAE,OAAe,EAAE,YAAoB,EAAE,GAAE,wBAA6B,GAChF,OAAO,CAAC,MAAM,EAAE,CAAC,CA4BnB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,kBAAkB,CAAC,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAgCtF"}
package/out/fs/zip.js CHANGED
@@ -33,8 +33,12 @@ import { once } from "#utils/events";
33
33
  async function openStreamingArchive(archivePath, options) {
34
34
  // `decodeStrings: false` returns the central directory's raw name bytes.
35
35
  // This lets the caller read a name when the archive does not declare its encoding.
36
- // See {@link ZipNameOptions}.
37
- const archive = await openArchive(archivePath.toString(), options?.filenameEncoding ? { decodeStrings: false } : {});
36
+ // See {@link ZipNameOptions}. yauzl's own name check is off because it throws on a
37
+ // leading slash. {@link memberPath} checks every name instead.
38
+ const archive = await openArchive(archivePath.toString(), {
39
+ validateFilenames: false,
40
+ ...(options?.filenameEncoding ? { decodeStrings: false } : {}),
41
+ });
38
42
  return Object.assign(archive, { [Symbol.asyncDispose]: () => archive.close() });
39
43
  }
40
44
  /**
@@ -47,8 +51,38 @@ async function openStreamingArchive(archivePath, options) {
47
51
  function entryName(entry, options) {
48
52
  const raw = entry.filename;
49
53
  if (typeof raw === "string")
50
- return raw;
51
- return iconv.decode(Buffer.from(raw), options?.filenameEncoding ?? "utf8");
54
+ return memberPath(raw);
55
+ return memberPath(iconv.decode(Buffer.from(raw), options?.filenameEncoding ?? "utf8"));
56
+ }
57
+ /**
58
+ * A member name as a path relative to the archive root.
59
+ * Every reader here matches and writes this form.
60
+ *
61
+ * Backslashes become forward slashes and leading slashes are removed, as `unzip` does when it extracts.
62
+ * OS Open Roads' GML archive stores `/data/`, `/doc/licence.txt` and `/readme.txt`
63
+ * beside `data/OSOpenRoads_HP.gml`.
64
+ * A reader that refused a leading slash refused that archive.
65
+ *
66
+ * @throws When the name has a drive letter or a `..` segment, so no member is
67
+ * written outside the extraction directory.
68
+ */
69
+ export function memberPath(name) {
70
+ const relative = name.replaceAll("\\", "/").replace(/^\/+/, "");
71
+ if (/^[a-z]:/i.test(relative)) {
72
+ throw new Error(`Zip member '${name}' names a drive`);
73
+ }
74
+ if (relative.split("/").includes("..")) {
75
+ throw new Error(`Zip member '${name}' has a .. segment, so it would extract outside its directory`);
76
+ }
77
+ return relative;
78
+ }
79
+ /**
80
+ * Whether a member name, already passed through {@link memberPath}, is a directory entry.
81
+ *
82
+ * The root itself, a stored `/`, normalizes to the empty name.
83
+ */
84
+ function isDirectoryMember(name) {
85
+ return name === "" || name.endsWith("/");
52
86
  }
53
87
  /**
54
88
  * One member's decompressed byte stream, ended when the owning scope exits.
@@ -168,7 +202,7 @@ export async function* readZipEntry(archivePath, selector, options) {
168
202
  export async function extractZipEntry(archivePath, selector, destinationPath) {
169
203
  await using archive = await openStreamingArchive(archivePath);
170
204
  for await (const entry of archive) {
171
- if (!selectorMatches(selector, entry.filename))
205
+ if (!selectorMatches(selector, entryName(entry)))
172
206
  continue;
173
207
  await pipeline(await entry.openReadStream(), openWriteStream(destinationPath));
174
208
  return entry.uncompressedSize;
@@ -191,11 +225,12 @@ export async function extractZipEntries(archivePath, destinationDirectory, { sel
191
225
  await using archive = await openStreamingArchive(archivePath);
192
226
  const written = [];
193
227
  for await (const entry of archive) {
194
- if (entry.filename.endsWith("/"))
228
+ const name = entryName(entry);
229
+ if (isDirectoryMember(name))
195
230
  continue;
196
- if (selector && !selectorMatches(selector, entry.filename))
231
+ if (selector && !selectorMatches(selector, name))
197
232
  continue;
198
- const relative = flatten ? basename(entry.filename) : entry.filename;
233
+ const relative = flatten ? basename(name) : name;
199
234
  const destination = resolvePath(destinationDirectory, relative);
200
235
  if (!flatten) {
201
236
  await makeDirectories(dirname(destination));
@@ -204,7 +239,7 @@ export async function extractZipEntries(archivePath, destinationDirectory, { sel
204
239
  if (existing?.size !== entry.uncompressedSize) {
205
240
  await pipeline(await entry.openReadStream(), openWriteStream(destination));
206
241
  }
207
- written.push(entry.filename);
242
+ written.push(name);
208
243
  }
209
244
  return written;
210
245
  }
@@ -228,7 +263,7 @@ export async function verifyZipIntegrity(archivePath) {
228
263
  await using archive = await openStreamingArchive(archivePath);
229
264
  let checked = 0;
230
265
  for await (const entry of archive) {
231
- if (entry.filename.endsWith("/"))
266
+ if (isDirectoryMember(entryName(entry)))
232
267
  continue;
233
268
  await using contents = await openEntryStream(entry, { validateCrc32: false });
234
269
  let checksum = 0;