@preventive/triage 1.0.0-alpha.79 → 1.0.0-alpha.80

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 (60) hide show
  1. package/common/line-diff.d.ts +4 -0
  2. package/common/line-diff.js +72 -14
  3. package/common/managed/npm-packages.d.ts +2 -0
  4. package/common/managed/npm-packages.js +12 -0
  5. package/common/pretty-json.js +3 -0
  6. package/common/pretty-kinds.js +20 -0
  7. package/common/pretty-sourcemap.js +70 -0
  8. package/common/sourcemap-listing.js +78 -0
  9. package/common/sourcemap-mappings.js +136 -0
  10. package/common/sourcemap-unlist.js +85 -0
  11. package/out/activity.js +2 -2
  12. package/out/brotli-fallback.js +2 -2
  13. package/out/chunk-2XUEZHIP.js +1 -1
  14. package/out/{chunk-PLF4LBLE.js → chunk-5AVGKFMR.js} +1 -1
  15. package/out/{chunk-WB3NRZL7.js → chunk-5CJKUV53.js} +1 -1
  16. package/out/{chunk-6VXEPL32.js → chunk-5EAVJAD2.js} +1 -1
  17. package/out/{chunk-OWIBDEJJ.js → chunk-5M2X3QPK.js} +1 -1
  18. package/out/{chunk-26W3E5JE.js → chunk-5QWPKTCE.js} +1 -1
  19. package/out/chunk-74JZTGTO.js +1 -1
  20. package/out/{chunk-MKX6JODK.js → chunk-7YO4QV5P.js} +1 -1
  21. package/out/{chunk-EMNIV37E.js → chunk-DUS5ARE2.js} +1 -1
  22. package/out/{chunk-Z54AXVCK.js → chunk-GBMAXAYK.js} +2 -2
  23. package/out/chunk-GO7FT4OD.js +1 -1
  24. package/out/{chunk-V43XH2JQ.js → chunk-JXBRWLMA.js} +1 -1
  25. package/out/chunk-LBD3M3J6.js +1 -0
  26. package/out/chunk-MV66NL3G.js +3 -0
  27. package/out/chunk-N57OWFKY.js +15 -0
  28. package/out/{chunk-IIJK4F4U.js → chunk-OWSEQOL5.js} +1 -1
  29. package/out/chunk-PLGH63UC.js +2 -0
  30. package/out/{chunk-3S4YWYOM.js → chunk-PTFYDJUP.js} +1 -1
  31. package/out/chunk-QD3IBSF4.js +1 -1
  32. package/out/{chunk-ATT2QA77.js → chunk-VZPPX6MV.js} +1 -1
  33. package/out/chunk-YKCRCNYZ.js +266 -0
  34. package/out/client-managed-import.js +1 -1
  35. package/out/client-managed.js +1 -1
  36. package/out/client-sync.js +2 -2
  37. package/out/compare.js +13 -18
  38. package/out/dialogs.js +38 -38
  39. package/out/graph.js +3 -3
  40. package/out/index.html +11 -11
  41. package/out/prism.js +1 -1
  42. package/out/scan.js +2 -2
  43. package/out/terminal.js +167 -167
  44. package/out/view.js +8 -8
  45. package/package.json +14 -9
  46. package/risk/index.d.ts +3 -0
  47. package/risk/index.js +1 -1
  48. package/risk/npm/tarball.js +4 -4
  49. package/server-managed/http.ts +36 -80
  50. package/server-managed/npm-delta-worker.js +117 -44
  51. package/server-managed/npm-delta.ts +101 -22
  52. package/server-managed/npm-kept.ts +5 -0
  53. package/server-managed/npm-patch-paths.ts +29 -0
  54. package/server-managed/npm-patch.ts +11 -3
  55. package/out/chunk-4YZOXAXR.js +0 -2
  56. package/out/chunk-NTJJIEHS.js +0 -259
  57. package/out/chunk-PQPKHAI5.js +0 -15
  58. package/out/chunk-QBIUW5EF.js +0 -2
  59. package/out/chunk-XLX6XXJF.js +0 -1
  60. /package/out/{chunk-S5HSDGTP.js → chunk-DUASGS2O.js} +0 -0
@@ -15,13 +15,17 @@
15
15
  // Compare's, read and kept as Compare keeps them (`copies`). Access is the
16
16
  // caller's to check.
17
17
  import { createHash } from 'node:crypto'
18
+ import { isExactVersion } from '@preventive/upstream/semver.js'
18
19
  import { layoutBlankList, prettyExtension } from '../common/pretty-print.js'
19
- import { type KeptStore, VERSION_DELTA_KEPT_MS } from './npm-kept.ts'
20
+ import { isPatchHash, reviewBase } from '../common/managed/npm-packages.js'
21
+ import { type KeptStore, VERSION_DELTA_KEPT_MS, npmDeltaStore, npmVersionDeltaStore, npmVersionStore, privateVersionDeltaStore } from './npm-kept.ts'
20
22
  import { type Lru, lru } from './lru.ts'
21
- import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
23
+ import { plainObject } from './npm-manifest.ts'
24
+ import { NpmPackageError, type NpmPackageFile, VERSION_KEPT_MS, npmFileText } from './npm-packages.ts'
22
25
  import { PRETTY_VERSION, type PrettyCopy } from './pretty-format.js'
23
26
  import type { KeptCopies } from './pretty-copies.ts'
24
27
  import { eachOf } from './queue.ts'
28
+ import type { UpstreamCacheStore } from './upstream-cache.ts'
25
29
  import { workerTurns } from './worker-turns.ts'
26
30
 
27
31
  export interface NpmDelta { additions: number; deletions: number; best: { additions: number; deletions: number }; binary: boolean; partial?: true }
@@ -34,7 +38,7 @@ const PRETTY_MARGIN_MS = 15_000
34
38
  // The text the two sides may hold together, past which none is counted.
35
39
  const MAX_TEXT_LENGTH = 64 * 1024 * 1024
36
40
  // Bumped when what a delta counts changes; its keys carry it and PRETTY_VERSION, so none counted otherwise is read.
37
- const DELTA_VERSION = 1
41
+ const DELTA_VERSION = 4
38
42
  const COUNTING = `v${DELTA_VERSION}.${PRETTY_VERSION}`
39
43
  const COPIES_AT_ONCE = 8
40
44
 
@@ -58,13 +62,19 @@ type SideCopy = [number, string, PrettyCopy]
58
62
  type Counted = Omit<NpmDelta, 'binary' | 'partial'> & { complete: boolean; made: SideCopy[] }
59
63
  const isCounted = (told: unknown): told is Counted => lines(told) && lines((told as { best?: unknown }).best)
60
64
  && typeof (told as { complete?: unknown }).complete === 'boolean' && Array.isArray((told as { made?: unknown }).made)
65
+ // The count a worker told so far, settled for should it be gone before its answer (a proof of what runs may take minutes).
66
+ const sofar = (told: unknown): Counted | null => {
67
+ const count = { ...(told as { sofar?: object } | null)?.sofar, made: [] }
68
+ return isCounted(count) ? count : null
69
+ }
61
70
  const isCopy = (copy: unknown): copy is PrettyCopy => typeof (copy as { text?: unknown } | null)?.text === 'string' && layoutBlankList((copy as { blank?: unknown }).blank) !== null
62
71
 
63
- // What the worker counts of `base` against `other`, each its text files' paths and texts, given the copies kept.
64
- function counted(base: [string, string][], other: [string, string][], copies: SideCopy[], deadline: number): Promise<Counted> {
72
+ // What the worker counts of `base` against `other`, each its files by path (a binary one's by its digest), given the copies
73
+ // kept, and whether Compare proves types and prints code (`drawable`).
74
+ function counted(base: [string, unknown][], other: [string, unknown][], copies: SideCopy[], drawable: { proves: boolean; prints: boolean }, deadline: number): Promise<Counted> {
65
75
  return workers.run(new URL('./npm-delta-worker.js', import.meta.url), {
66
- workerData: { base, other, copies, prettyUntil: deadline - PRETTY_MARGIN_MS }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
67
- }, told => (isCounted(told) ? told : null), deadline)
76
+ workerData: { base, other, copies, ...drawable, prettyUntil: deadline - PRETTY_MARGIN_MS }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
77
+ }, told => (isCounted(told) ? told : null), deadline, sofar)
68
78
  }
69
79
 
70
80
  // A side's text files, by path, how long their texts are, and its other,
@@ -112,14 +122,15 @@ function binaryChanged(olds: NpmPackageFile[], news: NpmPackageFile[]): boolean
112
122
  }
113
123
 
114
124
  type Side = { integrity: string; files: () => Promise<NpmPackageFile[]>; copies?: KeptCopies | null }
115
- // A delta's key: the integrities of the version it is against, or none, and
116
- // of the version.
117
- export const deltaKey = (base: string | null, other: string) => `${COUNTING}\0${base ?? '(empty)'}\0${other}`
125
+ // A delta's key: the integrities of the version it is against, or none, and of the version; and, against one, whether
126
+ // they are `alike`, two unpatched versions of one package, as Compare proves types and prints code of those alone.
127
+ export const deltaKey = (base: string | null, other: string, alike = true) => `${COUNTING}\0${base !== null && !alike ? 'apart\0' : ''}${base ?? '(empty)'}\0${other}`
118
128
  // The same of two public versions by their names and versions (`(empty)`
119
- // for none), as npm never gives one other files: its key in
120
- // npmVersionDeltaStore.
121
- export const versionDeltaKey = (name: string, version: string, otherName: string, otherVersion: string) =>
122
- `${COUNTING}\0${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}`
129
+ // for none), as npm never gives one other files, the first as the pnpm patch
130
+ // `patchHash` names changes it where one does, whose hash names its text:
131
+ // its key in npmVersionDeltaStore.
132
+ export const versionDeltaKey = (name: string, version: string, otherName: string, otherVersion: string, patchHash: string | null = null) =>
133
+ `${COUNTING}\0${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}${patchHash === null ? '' : `\0patch:${patchHash}`}`
123
134
  // Those of `keys` (versionDeltaKey) kept, by key, as of `now`: one kept past
124
135
  // VERSION_DELTA_KEPT_MS not, though no write has pruned it yet.
125
136
  export async function keptVersionDeltas(keys: string[], kept: KeptStore<NpmDelta>, now = Date.now()): Promise<Map<string, NpmDelta>> {
@@ -135,14 +146,14 @@ export async function keptVersionDeltas(keys: string[], kept: KeptStore<NpmDelta
135
146
  // `base`, or none, as held, else shared with one asked before it, else
136
147
  // looked for where it is kept, else worked out and kept: shared from before
137
148
  // it is looked for, lest those asked together each look, find none, and work
138
- // it out.
139
- export function npmDelta(base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null = null): Promise<NpmDelta> {
140
- const key = deltaKey(base?.integrity ?? null, other.integrity)
149
+ // it out. `alike` as deltaKey has it.
150
+ export function npmDelta(base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null = null, alike = true): Promise<NpmDelta> {
151
+ const key = deltaKey(base?.integrity ?? null, other.integrity, alike)
141
152
  const known = deltas.get(key)
142
153
  if (known) return Promise.resolve(known)
143
154
  const shared = working.get(key)
144
155
  if (shared) return shared
145
- const work = worked(key, base, other, kept).finally(() => working.delete(key))
156
+ const work = worked(key, base, other, kept, { proves: !base || alike, prints: !!base && alike }).finally(() => working.delete(key))
146
157
  working.set(key, work)
147
158
  return work
148
159
  }
@@ -150,8 +161,8 @@ export function npmDelta(base: Side | null, other: Side, kept: KeptStore<NpmDelt
150
161
  // The deltas of those of `sides` (each the integrities of the version it is
151
162
  // against, or none, and of the version) held or kept, by their keys
152
163
  // (npmDelta's), in one read of `kept` for those not held: none worked out.
153
- export async function keptNpmDeltas(sides: [string | null, string][], kept: KeptStore<NpmDelta>): Promise<Map<string, NpmDelta>> {
154
- const keys = [...new Set(sides.map(([base, other]) => deltaKey(base, other)))]
164
+ export async function keptNpmDeltas(sides: [string | null, string, boolean][], kept: KeptStore<NpmDelta>): Promise<Map<string, NpmDelta>> {
165
+ const keys = [...new Set(sides.map(([base, other, alike]) => deltaKey(base, other, alike)))]
155
166
  const found = new Map(keys.flatMap(key => { const known = deltas.get(key); return known ? [[key, known] as const] : [] }))
156
167
  const unheld = keys.filter(key => !found.has(key))
157
168
  for (const [key, row] of unheld.length > 0 ? await kept.readMany(unheld) : []) {
@@ -173,7 +184,7 @@ async function keptCopies(sides: (Side | null)[], files: Map<string, Uint8Array>
173
184
 
174
185
  // As kept, else its turn awaited, then both sides' files read, counted and
175
186
  // kept, the copies it printed kept for Compare.
176
- async function worked(key: string, base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null): Promise<NpmDelta> {
187
+ async function worked(key: string, base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null, drawable: { proves: boolean; prints: boolean }): Promise<NpmDelta> {
177
188
  const known = deltaOf((await kept?.read(key))?.value)
178
189
  if (known) { deltas.set(key, known); return known }
179
190
  const sides = [base, other]
@@ -186,7 +197,8 @@ async function worked(key: string, base: Side | null, other: Side, kept: KeptSto
186
197
  if (olds.length + news.length > MAX_TEXT_LENGTH) throw new NpmPackageError(413, 'package-too-large')
187
198
  const binary = binaryChanged(olds.binaries, news.binaries)
188
199
  const byPath = [baseRead.value ?? [], otherRead.value].map(side => new Map(side.filter(file => file.link === undefined).map(file => [file.path, file.bytes])))
189
- const told = await counted(olds.read, news.read, await keptCopies(sides, byPath), Date.now() + DELTA_TIMEOUT_MS)
200
+ const withBinaries = (side: typeof olds) => [...side.read, ...side.binaries.map(file => [file.path, { format: 'digest', digest: digest(file.bytes) }] as [string, unknown])]
201
+ const told = await counted(withBinaries(olds), withBinaries(news), await keptCopies(sides, byPath), drawable, Date.now() + DELTA_TIMEOUT_MS)
190
202
  const counts: NpmDelta = { additions: told.additions, deletions: told.deletions, best: told.best, binary, ...told.complete ? {} : { partial: true as const } }
191
203
  return [counts, told.made, byPath] as const
192
204
  })
@@ -196,3 +208,70 @@ async function worked(key: string, base: Side | null, other: Side, kept: KeptSto
196
208
  ([at, path, copy]) => sides[at]!.copies!.keep(path, files[at]!.get(path)!, copy))
197
209
  return delta
198
210
  }
211
+
212
+ // The lines the versions wanting reviews of `answers` (dependencies'
213
+ // answers: pull requests', default branches', bundles') change, as their rows
214
+ // show them (reviewBase), against a version of their package or another's,
215
+ // a patched one's as its patch changes it, where they are counted already:
216
+ // kept by their names (npmVersionDeltaStore, and privateVersionDeltaStore of
217
+ // private ones, as their readers read what the repository locks), else, of
218
+ // public versions npm answered for in a day (npmVersionStore), by their
219
+ // integrities, as npmDelta keys them, then kept by their names too. Only
220
+ // those `answers` list are told, of repositories their reader reads whole,
221
+ // whose lockfiles name them. `[name, version,
222
+ // base, delta]` each, or, of one patched or against another package's
223
+ // version, `[name, version, base, patchHash, baseName, delta]`
224
+ // (npm-delta.js seedNpmDeltas); none counted here, nor npm asked.
225
+ type DeltaAsked = { name: string; version: string; base: string; baseName: string; patch: string | null }
226
+ export async function countedDeltas(db: UpstreamCacheStore, answers: object[], debug = false): Promise<unknown[][]> {
227
+ const asked = new Map<string, DeltaAsked>()
228
+ const keyOf = ({ name, version, base, baseName, patch }: DeltaAsked) => versionDeltaKey(name, version, baseName, base, patch)
229
+ for (const answer of answers as { lockfiles?: { added?: unknown; unreviewed?: unknown }[]; review?: { required?: number; reviewedBases?: true } }[]) {
230
+ const required = answer.review?.required
231
+ if (!Number.isSafeInteger(required)) continue
232
+ for (const pkg of (answer.lockfiles ?? []).flatMap(dir => [...Array.isArray(dir.added) ? dir.added : [], ...Array.isArray(dir.unreviewed) ? dir.unreviewed : []]) as
233
+ { name?: unknown; version?: unknown; source?: unknown; was?: string[]; base?: { name: string; version: string }; reviews?: unknown; rejected?: unknown; baseline?: unknown
234
+ reviewed?: unknown; unsupported?: unknown; patch?: { hash?: unknown } }[]) {
235
+ if (pkg.source !== 'registry' || typeof pkg.name !== 'string' || typeof pkg.version !== 'string' || !isExactVersion(pkg.version)) continue
236
+ if (pkg.patch !== undefined && !isPatchHash(pkg.patch?.hash)) continue
237
+ if (pkg.unsupported || pkg.baseline || pkg.reviewed || typeof pkg.reviews !== 'number' || (pkg.reviews >= required! && !pkg.rejected)) continue
238
+ const base = reviewBase({ ...pkg, name: pkg.name, version: pkg.version, ...Array.isArray(pkg.was) ? { was: pkg.was.filter(prior => typeof prior === 'string') } : {} },
239
+ answer.review)
240
+ if (base && (typeof base.name !== 'string' || typeof base.version !== 'string')) continue
241
+ const one = { name: pkg.name, version: pkg.version, base: base?.version ?? '(empty)', baseName: base?.name ?? pkg.name, patch: (pkg.patch?.hash as string | undefined) ?? null }
242
+ asked.set(keyOf(one), one)
243
+ }
244
+ }
245
+ if (asked.size === 0) return []
246
+ // As the rows' key them: a version alike unpatched and against its own package's as ever.
247
+ const told = (one: DeltaAsked, delta: NpmDelta) => one.patch === null && one.baseName === one.name ? [one.name, one.version, one.base, delta]
248
+ : [one.name, one.version, one.base, one.patch, one.baseName, delta]
249
+ const byVersions = npmVersionDeltaStore<NpmDelta>(db, debug)
250
+ const [publicly, privately] = await Promise.all([byVersions, privateVersionDeltaStore<NpmDelta>(db, debug)].map(store => keptVersionDeltas([...asked.keys()], store)))
251
+ const named = new Map([...privately!, ...publicly!])
252
+ const byName = [...asked].flatMap(([key, one]) => named.has(key) ? [told(one, named.get(key)!)] : [])
253
+ for (const key of named.keys()) asked.delete(key)
254
+ if (asked.size === 0) return byName
255
+ const versions = [...asked.values()].flatMap(({ name, version, base, baseName }) => [{ name, version }, ...base === '(empty)' || !isExactVersion(base) ? [] : [{ name: baseName, version: base }]])
256
+ const kept = await npmVersionStore(db, debug).readMany!(versions)
257
+ const integrity = (name: string, version: string) => {
258
+ const hit = kept.get(`${name}@${version}`)
259
+ const dist = hit && Date.now() - hit.at < VERSION_KEPT_MS ? hit.json['dist'] : null
260
+ return plainObject(dist) && typeof dist['integrity'] === 'string' ? dist['integrity'] : null
261
+ }
262
+ // A patched one by its integrity as its patch changes it, as GET deltas keeps it.
263
+ const sides = [...asked].flatMap(([key, one]) => {
264
+ const against = one.base === '(empty)' ? null : integrity(one.baseName, one.base), other = integrity(one.name, one.version)
265
+ const alike = one.patch === null && one.baseName === one.name
266
+ return other && (one.base === '(empty)' || against) ? [{ key, one, sides: [against, one.patch === null ? other : `${other} patch:${one.patch}`, alike] as [string | null, string, boolean] }] : []
267
+ })
268
+ if (sides.length === 0) return byName
269
+ const found = await keptNpmDeltas(sides.map(({ sides: pair }) => pair), npmDeltaStore<NpmDelta>(db, debug))
270
+ const byIntegrity = sides.flatMap(({ key, one, sides: [against, other, alike] }) => {
271
+ const delta = found.get(deltaKey(against, other, alike))
272
+ return delta ? [{ key, one, delta }] : []
273
+ })
274
+ // Kept by their names too, as those npm told of are public, for a later read past the day.
275
+ await Promise.all(byIntegrity.map(({ key, delta }) => byVersions.write(key, delta, Date.now())))
276
+ return [...byName, ...byIntegrity.map(({ one, delta }) => told(one, delta))]
277
+ }
@@ -223,6 +223,11 @@ export const npmDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptSto
223
223
  // of them, for them. Each read for VERSION_DELTA_KEPT_MS alone, pruned or not.
224
224
  export const VERSION_DELTA_KEPT_MS = 30 * 24 * 60 * 60_000
225
225
  export const npmVersionDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/version-deltas', VERSION_DELTA_KEPT_MS, debug)
226
+ // The same of those of which either is private, kept apart: read only with
227
+ // the dependencies of a repository that locks the version, as anyone who
228
+ // reads those may be told its lines (npm-delta.ts countedDeltas), npm read
229
+ // with the server's one token whoever asks. Each read for VERSION_DELTA_KEPT_MS alone.
230
+ export const privateVersionDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/private-version-deltas', VERSION_DELTA_KEPT_MS, debug)
226
231
  // The versions a repository's lockfiles locked at the commit its dependencies
227
232
  // are reviewed since (pull-dependency-reviews.ts reviewBaseline), by the
228
233
  // commit, which never change: kept as its history's pages are, never stored
@@ -1,6 +1,7 @@
1
1
  // Paths as git writes them in a diff's headers (npm-patch.ts parsePatch):
2
2
  // quoted as C writes a string where they need it, prefixed `a/` and `b/`.
3
3
  import { Buffer } from 'node:buffer'
4
+ import { NPM_PATH_FOLDS } from '../risk/index.js'
4
5
  import { NpmPackageError } from './npm-packages.ts'
5
6
 
6
7
  const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
@@ -55,3 +56,31 @@ export function namesBoth(rest: string, before: string, after: string): boolean
55
56
  const second = rest.slice(first.length + 1)
56
57
  return unquoted(first) === `a/${before}` && unquoted(second) === `b/${after}`
57
58
  }
59
+
60
+ // A path every pnpm takes as written: none of its names starts or ends in
61
+ // whitespace, which pnpm 10 and 11 trim off a path, or is `node_modules`, in
62
+ // which pnpm 12 may leave out a file a patch creates.
63
+ export const isPlainPath = (path: string) => path.split('/').every(name => name === name.trim() && name.toLowerCase() !== 'node_modules')
64
+
65
+ // Takes each path a patch creates or renames a file to, refusing one macOS or
66
+ // Windows may take for another spelled otherwise (NPM_PATH_FOLDS): one of the
67
+ // package's `paths`, a directory of one, or one taken before. So `License`
68
+ // beside `LICENSE`, or `Lib/a.js` beside `lib/`, which pnpm versions may
69
+ // write over the other, or into it.
70
+ export function pathClaims(paths: Iterable<string>): (path: string) => void {
71
+ // By each fold, the spelling of each path and directory; '' for several.
72
+ const spelled = NPM_PATH_FOLDS.map(() => new Map<string, string>())
73
+ const take = (path: string, claim: boolean) => {
74
+ for (let at = path.indexOf('/'); ; at = path.indexOf('/', at + 1)) {
75
+ const name = at === -1 ? path : path.slice(0, at)
76
+ for (const [i, fold] of NPM_PATH_FOLDS.entries()) {
77
+ const key = fold(name), was = spelled[i]!.get(key)
78
+ if (claim && was !== undefined && was !== name) throw unreadable()
79
+ spelled[i]!.set(key, was === undefined || was === name ? name : '')
80
+ }
81
+ if (at === -1) return
82
+ }
83
+ }
84
+ for (const path of paths) take(path, false)
85
+ return path => take(path, true)
86
+ }
@@ -31,7 +31,7 @@ import { type Lru, lru } from './lru.ts'
31
31
  import type { KeptStore } from './npm-kept.ts'
32
32
  import { plainObject } from './npm-manifest.ts'
33
33
  import { NpmPackageError, type NpmPackageFile, npmFileText, pathOrder } from './npm-packages.ts'
34
- import { gitPath, namesBoth, sidePath, unquoted } from './npm-patch-paths.ts'
34
+ import { gitPath, isPlainPath, namesBoth, pathClaims, sidePath, unquoted } from './npm-patch-paths.ts'
35
35
  import { type GithubAsked, type PullDependencies, lockfileFormat, repositoryFile } from './pull-dependencies.ts'
36
36
  import { eachOf } from './queue.ts'
37
37
 
@@ -98,6 +98,9 @@ function readHunk(lines: string[], at: number, end: number): { hunk: PatchHunk;
98
98
  if (!range) throw unreadable()
99
99
  let news = Number(range[4] ?? 1), olds = Number(range[2] ?? 1)
100
100
  const hunk: PatchHunk = { at: Math.max(Number(range[1]), 1) - 1, length: olds, parts: [] }
101
+ // Lines added with none to find them by, past the file's start (git's -U0): pnpm 10 and 11 add them
102
+ // before the line named, pnpm 12 after it.
103
+ if (olds === 0 && Number(range[1]) > 0) throw unreadable()
101
104
  while (olds > 0 || news > 0) {
102
105
  // A line its count reads past those read isn't one.
103
106
  if (at >= end) throw unreadable()
@@ -131,6 +134,8 @@ function readHunk(lines: string[], at: number, end: number): { hunk: PatchHunk;
131
134
  // also creates or deletes, and a `new mode` line without its `old mode`
132
135
  // (pnpm 12 alone reads one). Throws for one it can't read, or of bytes.
133
136
  export function parsePatch(patch: string): PatchedFile[] {
137
+ // One whose last line has no LF: pnpm 12 alone adds that line without one.
138
+ if (patch !== '' && !patch.endsWith('\n')) throw unreadable()
134
139
  const lines = patch.split('\n')
135
140
  // The lines read: those but the empty one past the patch's last ending.
136
141
  const end = lines.length - (patch.endsWith('\n') ? 1 : 0)
@@ -168,7 +173,7 @@ export function parsePatch(patch: string): PatchedFile[] {
168
173
  const rest = head.slice('diff --git '.length)
169
174
  const path = sides ? (created ? sides[1] : sides[0]) : gitPath(rest)
170
175
  const after = to ?? path, before = from ?? path
171
- if (before == null || after == null || ![before, after].every(isPatchPath) || !namesBoth(rest, before, after)
176
+ if (before == null || after == null || ![before, after].every(name => isPatchPath(name) && isPlainPath(name)) || !namesBoth(rest, before, after)
172
177
  || (sides && (sides[0] !== (created ? null : before) || sides[1] !== (deleted ? null : after)))) throw unreadable()
173
178
  const hunks: PatchHunk[] = []
174
179
  while (lines[at]?.startsWith('@@ ')) {
@@ -256,11 +261,14 @@ function applied(text: string, hunks: PatchHunk[]): string {
256
261
  // its tarball's are read; a file it changes the text of must be text. One it
257
262
  // creates holds its first hunk's first lines, in place of any there, as
258
263
  // patch-package writes it. A file keeps its mode but where the patch says
259
- // otherwise. A symlink, which pnpm never installs, is none to patch.
264
+ // otherwise. A symlink, which pnpm never installs, is none to patch. A path
265
+ // it creates or renames to is one macOS and Windows take as written (pathClaims).
260
266
  export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): NpmPackageFile[] {
261
267
  const byPath = new Map(files.map(file => [file.path, file]))
262
268
  const encoder = new TextEncoder()
269
+ let claim: ((path: string) => void) | undefined
263
270
  for (const file of patch) {
271
+ if (file.created || file.from !== undefined) (claim ??= pathClaims(files.map(each => each.path)))(file.path)
264
272
  if (file.created) {
265
273
  const first = file.hunks[0]?.parts[0]
266
274
  byPath.set(file.path, { path: file.path, bytes: encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : ''),
@@ -1,2 +0,0 @@
1
- import{a as e,c as t}from"./chunk-7YFJUT2P.js";var n=new Uint8Array,r=e=>e.every(e=>e<128),i=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function a(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}var o=class extends Error{constructor(e,t,{limited:n=!1}={}){super(t===void 0?e:`${e} at byte ${t}`),this.name=`ArchiveError`,this.offset=t,this.limited=n}};function s(e,t){try{return e()}catch(e){throw!(e instanceof o)||e.offset!==void 0?e:new o(e.message,t,{limited:e.limited})}}var c=class extends o{constructor(e,{bytes:t,limited:n=!1,cause:r}){super(e,void 0,{limited:n}),this.name=`CompressionError`,this.bytes=t,this.cause=r}};function l(e){try{return[CompressionStream,DecompressionStream].every(t=>new t(e))}catch{return!1}}function u(e){if(!(e instanceof Uint8Array))throw new o(`the data is not a Uint8Array`)}async function d(e,t,n,r,i,o){let s=new t(n),l=s.writable.getWriter();l.write(e).catch(()=>{}),l.close().catch(()=>{});let u=s.readable.getReader(),d=[],f=0,p=()=>o?o.subarray(0,f):d.length===1?d[0]:a(d);try{for(let e=await u.read();!e.done;e=await u.read()){let t=e.value;if(!(f+t.length<=r))throw RangeError(`output past ${r} bytes`);o&&f+t.length>o.length&&(d.push(o.subarray(0,f)),o=void 0),o?o.set(t,f):d.push(t),f+=t.length}}catch(e){u.cancel().catch(()=>{});let t=e instanceof RangeError;throw new c(t?`the data ${i}es past ${r} bytes`:`the data does not ${i}`,{bytes:p(),limited:t,cause:e})}return p()}async function f(e,t,{limit:n=1/0}={}){return u(e),await d(e,CompressionStream,t,n,`compress`)}var p=16;function m(e,t){if(e.length<18)return 0;let n=new DataView(e.buffer,e.byteOffset+e.length-4,4).getUint32(0,!0);return n<=t&&n<=e.length*p?n:0}var h=(e,t,n,r=0)=>d(e,DecompressionStream,t,n,`decompress`,r?new Uint8Array(r):void 0);async function g(e,t,{limit:n=1/0}={}){u(e);let r=t===`gzip`;try{return await h(e,t,n,r?m(e,n):0)}catch(i){if(!r||!(i instanceof c)||i.limited||e.at(-1)!==0)throw i;let a=e.findLastIndex(e=>e!==0);for(let r=a+1;r<=Math.min(a+10,e.length-1);r++)try{return await h(e.subarray(0,r),t,n)}catch(e){if(!(e instanceof c)||e.limited)throw e}throw i}}var _=(e,t,n)=>d(e,DecompressionStream,t,n.length,`decompress`,n);function v(e){return e.length<=200?JSON.stringify(e):JSON.stringify(`${e.slice(0,e.codePointAt(199)>65535?199:200)}\u2026`)}var ee=/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u,y=(e,t)=>ee.test(e)||t&&e.includes(`\\`);function b(e,t){if(typeof e!=`string`)throw new o(`${t} is not a string`);if(!e.isWellFormed())throw new o(`${t} is not well-formed Unicode`)}var x=(t,n)=>t.length>n||t.length*3>n&&e(t).length>n;function S(e,n,r){try{return t(e)}catch{throw new o(`${n} is not valid UTF-8`,r)}}var te={file:420,directory:493,symlink:511},C=e=>e===`file`||e===`contiguous-file`,ne=e=>e.type===`directory`?`${e.name}/`:e.name;function re(e,t){if(typeof e!=`object`||!e)throw new o(`an entry is not an object`);let r=e.type??`file`;if(typeof r!=`string`)throw new o(`entry type is not a string`);if(!Object.hasOwn(t,r))throw new o(`entry type ${v(r)} is not one this package writes`);let{name:i}=e;b(i,`entry name`);let a=e.data??n;if(!(a instanceof Uint8Array))throw new o(`data of ${v(i)} is not a Uint8Array`);if(a.length!==0&&!C(r))throw new o(`a ${r} cannot carry data (${v(i)})`);let s=e.linkname??``;if(b(s,`link target of ${v(i)}`),s!==``&&r!==`hardlink`&&r!==`symlink`)throw new o(`a ${r} cannot have a link target (${v(i)})`);return{name:i,type:r,data:a,linkname:s}}var w=4096,ie=255;function ae(e,t){if(b(e,t),e===``)throw new o(`${t} is empty`);if(y(e,!0))throw new o(`${t} ${v(e)} holds a control or formatting character, or a backslash`);if(e.startsWith(`/`))throw new o(`${t} ${v(e)} is absolute`);let n=e.split(`/`);if(/^[a-zA-Z]:/u.test(n.find(e=>e!==`.`)??``))throw new o(`${t} ${v(e)} starts with a drive letter`);if(x(e,w))throw new o(`${t} ${v(e)} is longer than ${w} bytes`);if(n.some(e=>x(e,ie)))throw new o(`${t} ${v(e)} has a segment longer than ${ie} bytes`);return n}function oe(e,t,n=!1){let r=ae(e,t);if(r.at(-1)===``){if(!n)throw new o(`${t} ${v(e)} ends in a slash but is not a directory`);r.pop()}let i=r.filter(e=>e!==`.`),a=i.find(e=>e===``||e===`..`);if(a!==void 0)throw new o(`${t} ${v(e)} has ${a?`a .. segment`:`an empty segment`}`);if(i.length===0){if(!n)throw new o(`${t} ${v(e)} names the archive root but is not a directory`);return`.`}let s=i.join(`/`);if(x(s,w-+!!n))throw new o(`${t} ${v(e)} is longer than ${w} bytes`);return s}function se(e=0){if(!(Number.isSafeInteger(e)&&e>=0))throw new o(`symlinksAbove ${String(e)} is not a whole number of levels`);return e}function ce(e,t,n=0){let r=ae(t,`symlink target of ${v(e)}`).filter(e=>e!==``&&e!==`.`),i=e.split(`/`).length-1;for(let a of r)if(i+=a===`..`?-1:1,i<-n){let r=n===0?`outside the archive`:`more than ${n} level${n===1?``:`s`} above the archive`;throw new o(`symlink ${v(e)} points ${r}, to ${v(t)}`)}return r}function T(e,t,n,r=0){let i=oe(e,`entry name`,t===`directory`);return t===`symlink`&&ce(i,n,r),{name:i,linkname:t===`hardlink`?oe(n,`hard link target of ${v(i)}`):n}}var le=()=>({kind:void 0,entry:void 0,symlink:void 0,first:void 0,firstNode:void 0,rest:void 0});function E(e,t,n=!0){if(e.first===t)return e.firstNode;let r=e.rest?.get(t);return r!==void 0||!n||(r=le(),e.first===void 0?Object.assign(e,{first:t,firstNode:r}):(e.rest??=new Map).set(t,r)),r}var D=[`type`,`mode`,`uid`,`gid`,`mtime`,`uname`,`gname`,`linkname`,`devmajor`,`devminor`],O=class{#e=le();#t;#n;constructor(e=!1,t=0){this.#t=e,this.#n=se(t)}get above(){return this.#n}add(e){let{name:t,type:n}=e,r=n===`symlink`?e.linkname:void 0;if(n===`hardlink`){let n=this.#o(e.linkname);if(n?.kind!==`entry`)throw new o(`hard link ${v(t)} targets ${v(e.linkname)}, which is not an earlier non-directory entry`);r=n.symlink,r!==void 0&&this.#r(t,r,`hard link ${v(t)} to symlink ${v(e.linkname)}`)}let a=t.split(`/`),s=this.#a(a),c=s.at(-1);if(c.kind!==void 0&&c.kind!==`implied`){let n=D.find(t=>c.entry[t]!==e[t]);if(n!==void 0)throw new o(`duplicate entry ${v(t)} differs in ${n}`);if(c.entry.data===void 0)throw new o(`duplicate entry ${v(t)}, which only the in-memory call can compare with the earlier one`);if(!i(c.entry.data,e.data))throw new o(`duplicate entry ${v(t)} differs in data`);return}let l=n===`directory`?`directory`:`entry`;if(c.kind!==void 0&&l!==`directory`)throw new o(`${v(t)} is already a directory, so it cannot be a ${n}`);for(let e=1;e<a.length;e++)this.#i(s[e],()=>`${v(t)} is inside ${v(a.slice(0,e).join(`/`))}, which is not a directory`);c.kind=l,c.symlink=r,c.entry=this.#t?e:Object.fromEntries(D.map(t=>[t,e[t]])),n===`symlink`&&this.#r(t,e.linkname,`symlink ${v(t)}`)}#r(e,t,n){let r=ce(e,t,this.#n),i=e.split(`/`).slice(0,-1),a=this.#a(i);for(let[e,t]of r.entries()){if(t===`..`){if(i.length===0)return;i.pop(),a.pop()}else i.push(t),a.push(E(a.at(-1),t));e<r.length-1&&i.length&&this.#i(a.at(-1),()=>`the target of ${n} passes through ${v(i.join(`/`))}, which is not a directory`)}}#i(e,t){if(e.kind===`entry`)throw new o(t());e.kind??=`implied`}#a(e){let t=[this.#e];for(let n of e)t.push(E(t.at(-1),n));return t}#o(e){return e.split(`/`).reduce((e,t)=>e&&E(e,t,!1),this.#e)}},k=512,A=e=>e===`character-device`||e===`block-device`,j={file:48,hardlink:49,symlink:50,"character-device":51,"block-device":52,directory:53,fifo:54,"contiguous-file":55},M={pax:120,global:103,longname:76,longlink:75},N=100,P=155,F=32,ue=0,I=[[`mode`,100,8],[`uid`,108,8],[`gid`,116,8],[`size`,124,12],[`mtime`,136,12]],L=148,de=156,R=157,z=257,B=265,V=297,H=329,U=337,W=345,fe=386,pe=495,me=`ustar\x0000`,he=`ustar \0`,G=e=>Uint8Array.from(e,e=>e.codePointAt(0)),K=e=>String.fromCodePoint(...e),q=(e,t,n,r)=>e.subarray(t,t+n).set(r),J=(e,t,n)=>ve(e.subarray(t,t+n)),ge=e=>8**(e-1)-1,_e=(e,t)=>e>=0&&e<=ge(t);function Y(e,t,n,r,i){if(_e(r,n)){q(e,t,n,G(r.toString(8).padStart(n-1,`0`)));return}if(!i)throw new o(`${r} does not fit an octal field of ${n-1} digits`);e[t]=r<0?255:128;let a=BigInt.asUintN((n-1)*8,BigInt(r));for(let r=t+n-1;r>t;r--)e[r]=Number(a&255n),a>>=8n}function X(e,t,n,r,i,a=!1){let s=e[t];if(s===128||s===255){let c=0n;for(let r=t+1;r<t+n;r++)c=c<<8n|BigInt(e[r]);if(s===255&&(c=BigInt.asIntN((n-1)*8,c)),c<0n&&!a)throw new o(`the ${r} field is negative`,i);if(!Number.isSafeInteger(Number(c)))throw new o(`the ${r} field is too large`,i);return Number(c)}let c=/^ *([0-7]*) *$/u.exec(K(J(e,t,n)));if(!c)throw new o(`the ${r} field is not an octal number`,i);return c[1]===``?0:Number.parseInt(c[1],8)}function ve(e){let t=e.indexOf(0);return t===-1?e:e.subarray(0,t)}function ye(e){let t=256;for(let n=0;n<L;n++)t+=e[n];for(let n=L+8;n<k;n++)t+=e[n];return t}var Z=e=>e.every(e=>e===0);function be(e){let t=new Uint8Array(k);q(t,ue,N,e.name);for(let[n,r,i]of I)Y(t,r,i,e[n],e.gnu);return t[de]=e.typeflag,q(t,R,N,e.linkname),q(t,z,8,G(e.gnu?he:me)),q(t,B,F-1,e.uname),q(t,V,F-1,e.gname),e.devmajor!==null&&Y(t,H,8,e.devmajor,e.gnu),e.devminor!==null&&Y(t,U,8,e.devminor,e.gnu),q(t,W,P,e.prefix),q(t,L,8,G(`${ye(t).toString(8).padStart(6,`0`)}\0 `)),t}var xe=(e,t,n)=>/^ *[0-7]+ *$/u.test(K(J(e,t,n)));function Se(e,t){if(ye(e)!==X(e,L,8,`checksum`,t))throw new o(`header checksum does not match`,t);let r=K(e.subarray(z,z+8)),i=r===he;if(!i&&r!==me)throw new o(`header is not in the ustar, pax or gnu format`,t);if(i&&!Z(e.subarray(fe,pe)))throw new o(`header carries an old GNU sparse map or real size`,t);let a=e[de],s=a===j[`character-device`]||a===j[`block-device`],c=[[`checksum`,L,8],...I,...s?[[`devmajor`,H,8],[`devminor`,U,8]]:[]];return{gnu:i,typeflag:a,name:J(e,ue,N),prefix:i?n:J(e,W,P),linkname:J(e,R,N),uname:J(e,B,F),gname:J(e,V,F),...Object.fromEntries(I.map(([n,r,i])=>[n,X(e,r,i,n,t,n===`mtime`)])),devmajor:s?X(e,H,8,`devmajor`,t):0,devminor:s?X(e,U,8,`devminor`,t):0,octal:c.every(([,t,n])=>xe(e,t,n))}}function Ce(t,n){let r=e(` ${t}=${n}
2
- `),i=r.length+1;for(;r.length+String(i).length!==i;)i++;return a([e(String(i)),r])}var we=e=>a(e.map(([e,t])=>Ce(e,t))),Q=`pax records cannot be changed`,Te=class extends Map{set(){throw TypeError(Q)}delete(){throw TypeError(Q)}clear(){throw TypeError(Q)}};function Ee(e,t){let n=new Te;for(let r=0;r<e.length;){let i=r,a=0;for(;i<e.length&&e[i]>=48&&e[i]<=57;i++)a=a*10+(e[i]-48);if(i===r||e[r]===48||e[i]!==32)throw new o(`a pax record does not begin with its length`,t);let s=r+a;if(s>e.length||e[s-1]!==10)throw new o(`a pax record is not as long as it says`,t);let c=e.indexOf(61,i+1);if(c===-1||c>=s-1)throw new o(`a pax record has no keyword=value`,t);let l=S(e.subarray(i+1,c),`a pax record`,t);if(l===``||y(l,!1)||l.includes(` `))throw new o(`pax keyword ${v(l)} is malformed`,t);if(n.has(l))throw new o(`pax keyword ${l} repeats`,t);Map.prototype.set.call(n,l,S(e.subarray(c+1,s-1),`a pax record`,t)),r=s}return n}var De=e=>Object.entries(e).map(([e,t])=>[t,e]),Oe=new Map([...De(j),[0,`file`]]),ke=new Map(De(M)),Ae=1<<20,je=new Te,Me=Object.freeze([]),Ne=e=>e.gnu?`gnu`:`ustar`,Pe=e=>Math.ceil(e/k)*k,Fe=new Set([`SCHILY.realsize`,`SUN.holesdata`]);function Ie(e,t){if(e.some(e=>e.startsWith(`GNU.sparse.`)||Fe.has(e)))throw new o(`sparse entries are not supported`,t)}function Le(e,t,n){if(!/^(?:0|[1-9][0-9]*)$/u.test(e)||!Number.isSafeInteger(Number(e)))throw new o(`pax ${t}=${v(e)} is not a whole number this package can hold`,n);return Number(e)}function Re(e,t,n){let r=/^(-?)([0-9]+)(?:\.([0-9]+))?$/u.exec(e);if(!r)throw new o(`pax ${t}=${v(e)} is not a time`,n);let[,i,a,s=``]=r,c=Number(i+a)-(i&&/[1-9]/u.test(s)?1:0);if(!Number.isSafeInteger(c))throw new o(`pax ${t}=${v(e)} is out of range`,n);return c}function ze(e,t){let n=S(e.name,`entry name`,t);return e.prefix.length?`${S(e.prefix,`name prefix`,t)}/${n}`:n}var Be=class{#e=[];#t=0;#n=0;#r=0;#i;#a={pax:null,longname:null,longlink:null};#o=[];#s=null;#c=null;#l=0;#u=!1;#d=0;#f;#p;constructor(e,{symlinksAbove:t,maxEntries:n=1/0,trailingGlobal:r=!1}={}){if(n!==1/0&&!(Number.isSafeInteger(n)&&n>=0))throw new o(`maxEntries ${String(n)} is not a whole number of entries`);if(typeof r!=`boolean`)throw new o(`trailingGlobal ${String(r)} is not a boolean`);this.#i=new O(e,t),this.#f=n,this.#p=r}*push(e){if(!(e instanceof Uint8Array))throw new o(`a chunk is not a Uint8Array`);for(e.length&&(this.#e.push(e),this.#n+=e.length);!this.#u;){let e=this.#m(this.#c?Pe(this.#c.size):k);if(e===null)return;let t=this.#c?this.#g(e):this.#h(e);t&&(yield t)}let t=this.#r;if(!Z(this.#m(this.#n)))throw new o(`data after the end of the archive`,t)}end(){if(!this.#u)throw this.#r===0&&this.#n===0?new o(`the archive is empty`):this.#c===null&&this.#n===0?new o(this.#l?`the archive ends with a lone zero block`:`the archive has no end marker`,this.#r):new o(`the archive is truncated`,this.#r)}#m(e){if(this.#n<e)return null;if(e===0)return n;let t,r=this.#t+e;if(r<=this.#e[0].length)t=this.#e[0].subarray(this.#t,r);else{let e=0;for(;r>this.#e[e].length;)r-=this.#e[e++].length;t=a([this.#e[0].subarray(this.#t),...this.#e.slice(1,e),this.#e[e].subarray(0,r)]),this.#e.splice(0,e)}return this.#t=r,r===this.#e[0].length&&(this.#e.shift(),this.#t=0),this.#n-=e,this.#r+=e,t}#h(e){let t=this.#r-k;if(Z(e)){if(this.#o.some(({kind:e})=>e!==`global`||!this.#p))throw new o(`an extended header is not followed by an entry`,t);this.#u=++this.#l===2;return}if(this.#l)throw new o(`a lone zero block where a header should be`,t);let n=Se(e,t),r=ke.get(n.typeflag);if(r===void 0){if(++this.#d>this.#f)throw new o(`the archive holds more than ${this.#f} entries`,t,{limited:!0});this.#c={at:t,...this.#_(n,t)}}else{if(n.size>Ae)throw new o(`a ${r} header of ${n.size} bytes is longer than any tar writes`,t);this.#c={at:t,size:n.size,extended:Object.freeze({kind:r,magic:Ne(n),octal:n.octal})}}}#g(e){let{at:t,size:n,entry:r,extended:i}=this.#c;if(this.#c=null,!Z(e.subarray(n)))throw new o(`the padding after an entry is not zero`,t);let a=e.subarray(0,n);if(r)return r.data=a,s(()=>this.#i.add(r),t),r;let{kind:c}=i;if(c===`global`){this.#s=Ee(a,t);let e=[`path`,`linkpath`,`size`].find(e=>this.#s.has(e));if(e!==void 0)throw new o(`a global header sets ${e}`,t);Ie(this.#s.keys(),t)}else{if(this.#a[c]!==null)throw new o(`two ${c} headers ahead of one entry`,t);this.#a[c]=c===`pax`?Ee(a,t):S(ve(a),`a ${c} header`,t)}this.#o.push(i)}#_(e,t){let r=Oe.get(e.typeflag);if(r===void 0)throw new o(`entry type ${v(String.fromCodePoint(e.typeflag))} is not one this package reads`,t);let{pax:i,longname:a,longlink:c}=this.#a;this.#a={pax:null,longname:null,longlink:null};let l=e=>i?.get(e)??this.#s?.get(e);if(i!==null&&Ie(i.keys(),t),a!==null&&l(`path`)!==void 0)throw new o(`both a long name header and a pax path name one entry`,t);if(c!==null&&l(`linkpath`)!==void 0)throw new o(`both a long link header and a pax linkpath name one entry`,t);let u=a??l(`path`)??ze(e,t),d=c??l(`linkpath`)??S(e.linkname,`link target`,t),{name:f,linkname:p}=s(()=>T(u,r,d,this.#i.above),t),m=(n,r=Le)=>{let i=l(n);return i===void 0?e[n]:r(i,n,t)},h=m(`size`);if(h!==0&&!C(r))throw new o(`a ${r} entry has a size`,t);if(p!==``&&r!==`hardlink`&&r!==`symlink`)throw new o(`a ${r} entry has a link target`,t);let g=n=>{let r=l(n)??S(e[n],n,t);if(y(r,!1))throw new o(`${n} ${v(r)} holds a control or formatting character`,t);return r},_=A(r),ee={name:f,type:r,mode:e.mode&4095,uid:m(`uid`),gid:m(`gid`),mtime:m(`mtime`,Re),uname:g(`uname`),gname:g(`gname`),linkname:p,devmajor:_?m(`devmajor`):0,devminor:_?m(`devminor`):0,data:n,storedName:u,storedLinkname:d,pax:i??je,globalPax:this.#s??je,extended:this.#o.length?Object.freeze(this.#o):Me,magic:Ne(e),typeflag:String.fromCodePoint(e.typeflag),storedMode:e.mode,octal:e.octal};return this.#o=[],{entry:ee,size:h}}};function Ve(e,t){let n=new Be(!0,t),r=[...n.push(e)];return n.end(),r}var He=new Set([`gnu`,`ustar`,`pax`]),Ue=47;function $(e,t,n=!1){if(!Number.isSafeInteger(e)||!n&&e<0)throw new o(`${t} ${String(e)} is not ${n?`an integer`:`a non-negative integer`}`);return e}function We(e,t){if(b(e,t),y(e,!1))throw new o(`${t} ${v(e)} holds a control or formatting character`);return e}function Ge(e,t){let n=re(e,j),{name:r,type:i,linkname:a}=n,s=$(e.devmajor??0,`devmajor`),c=$(e.devminor??0,`devminor`);if((s!==0||c!==0)&&!A(i))throw new o(`a ${i} cannot have device numbers (${v(r)})`);let l=$(e.mode??te[i]??420,`mode`);if(l>4095)throw new o(`mode ${l.toString(8)} has bits beyond the permission bits`);return{...n,mode:l,uid:$(e.uid??0,`uid`),gid:$(e.gid??0,`gid`),mtime:$(e.mtime??0,`mtime`,!0),uname:We(e.uname??``,`uname`),gname:We(e.gname??``,`gname`),devmajor:s,devminor:c,...T(r,i,a,t)}}function Ke(e,t=e.length){let n=new Uint8Array(Math.ceil(t/k)*k);return n.set(e),n}var qe=(t,r,i,a,o)=>be({gnu:o,name:e(t).subarray(0,N),prefix:n,linkname:n,uname:n,gname:n,typeflag:a,mode:420,uid:0,gid:0,size:r,mtime:i,devmajor:null,devminor:null}),Je=(e,t)=>[qe(`././@LongLink`,e.length+1,0,t,!0),Ke(e,e.length+1)];function Ye(e,t){let n=we(t),r=e.name.lastIndexOf(`/`);return[qe(r===-1?`./PaxHeaders/${e.name}`:`${e.name.slice(0,r)}/PaxHeaders/${e.name.slice(r+1)}`,n.length,Math.max(0,Math.min(e.mtime,ge(12))),M.pax,!1),Ke(n)]}function Xe(e,t){let{length:n}=e;if(n>P+N+1)throw new o(`name ${v(t)} is longer than 256 bytes, which ustar cannot hold`);let r=n>P+1?P+1:e[n-1]===Ue?n-1:n,i=e.lastIndexOf(Ue,r-1),a=n-i-1;if(i<=0||a>N||a===0)throw new o(`name ${v(t)} cannot be split into ustar's prefix and name fields`);return{prefix:e.subarray(0,i),name:e.subarray(i+1)}}function Ze(t,i){let a=i===`gnu`,s=[],c=[],l=ne(t),u=e(l),d=n,f=e(t.linkname);if(f.length>N){if(a)c.push(...Je(f,M.longlink));else if(i===`pax`)s.push([`linkpath`,t.linkname]);else throw new o(`link target of ${v(t.name)} is longer than 100 bytes, which ustar cannot hold`);f=f.subarray(0,N)}i===`pax`&&(u.length>N||!r(u))&&s.push([`path`,l]),u.length>N&&(a?c.push(...Je(u,M.longname)):i===`ustar`&&({prefix:d,name:u}=Xe(u,t.name)),u.length>N&&(u=u.subarray(0,N)));let p=(e,n,r)=>{if(a||_e(n,r))return n;if(i!==`pax`)throw new o(`${e} ${n} of ${v(t.name)} does not fit the ustar format`);return s.push([e,String(n)]),0},m=(n,a)=>{let c=e(a);if(c.length<F&&(i!==`pax`||r(c)))return c;if(i!==`pax`)throw new o(`${n} of ${v(t.name)} is longer than 31 bytes, which the ${i} format cannot hold`);return s.push([n,a]),c.subarray(0,F-1)},h=A(t.type),g={gnu:a,name:u,prefix:d,linkname:f,typeflag:j[t.type],mode:t.mode,uid:p(`uid`,t.uid,8),gid:p(`gid`,t.gid,8),size:p(`size`,t.data.length,12),mtime:p(`mtime`,t.mtime,12),devmajor:h?p(`devmajor`,t.devmajor,8):null,devminor:h?p(`devminor`,t.devminor,8):null,uname:m(`uname`,t.uname),gname:m(`gname`,t.gname)};return s.length&&c.push(...Ye(t,s)),c.push(be(g)),t.data.length&&c.push(t.data),t.data.length%k&&c.push(new Uint8Array(k-t.data.length%k)),c}function Qe({format:e=`gnu`,blocking:t=20,symlinksAbove:n}={},r=!1){if(!He.has(e))throw new o(`format ${v(String(e))} is not gnu, ustar or pax`);if(!Number.isSafeInteger(t)||t<1)throw new o(`blocking is not a positive integer`);let i=new O(r,n),a=0;return{add(t){let n=Ge(t,i.above);i.add(n);let r=Ze(n,e);for(let e of r)a+=e.length;return r},end(){let e=t*k;return[new Uint8Array(Math.ceil((a+2*k)/e)*e-a)]}}}function $e(e,t){let n=Qe(t,!0),r=[];for(let t of e)r.push(...n.add(t));return a([...r,...n.end()])}export{n as a,r as b,i as c,a as d,o as e,s as f,c as g,l as h,f as i,g as j,_ as k,v as l,S as m,te as n,ne as o,re as p,T as q,O as r,$e as s,Ve as t};