@cloudflare/worker-bundler 0.2.2 → 0.2.3

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,630 @@
1
+ import { parse } from "smol-toml";
2
+ import { unzipSync } from "fflate";
3
+ import * as semver from "semver";
4
+ //#region src/common.ts
5
+ const DEFAULT_TIMEOUT_MS = 3e4;
6
+ /**
7
+ * Check if a file path is likely a text file.
8
+ */
9
+ function isTextFile(path) {
10
+ const textExtensions = [
11
+ ".js",
12
+ ".mjs",
13
+ ".cjs",
14
+ ".ts",
15
+ ".mts",
16
+ ".cts",
17
+ ".tsx",
18
+ ".jsx",
19
+ ".json",
20
+ ".md",
21
+ ".txt",
22
+ ".css",
23
+ ".html",
24
+ ".yml",
25
+ ".yaml",
26
+ ".toml",
27
+ ".xml",
28
+ ".svg",
29
+ ".map",
30
+ ".d.ts",
31
+ ".d.mts",
32
+ ".d.cts",
33
+ ".py"
34
+ ];
35
+ const configFiles = [
36
+ "LICENSE",
37
+ "README",
38
+ "CHANGELOG",
39
+ "package.json",
40
+ "tsconfig.json",
41
+ ".npmignore",
42
+ ".gitignore"
43
+ ];
44
+ const fileName = path.split("/").pop() ?? "";
45
+ if (configFiles.some((f) => fileName.toUpperCase().startsWith(f.toUpperCase()))) return true;
46
+ return textExtensions.some((ext) => path.toLowerCase().endsWith(ext));
47
+ }
48
+ /**
49
+ * Fetch with a timeout.
50
+ * Throws an error if the request takes longer than the specified timeout.
51
+ */
52
+ async function fetchWithTimeout(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
53
+ const controller = new AbortController();
54
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
55
+ try {
56
+ return await fetch(url, {
57
+ ...options,
58
+ signal: controller.signal
59
+ });
60
+ } catch (error) {
61
+ if (error instanceof Error && error.name === "AbortError") throw new Error(`Request to ${url} timed out after ${timeoutMs}ms (npm registry slow or unreachable from this Worker)`);
62
+ throw error;
63
+ } finally {
64
+ clearTimeout(timeoutId);
65
+ }
66
+ }
67
+ //#endregion
68
+ //#region src/installer-python.ts
69
+ const PYODIDE_VERSION = "v0.27.5";
70
+ const PYPI_SIMPLE_API = "https://pypi.org/simple";
71
+ let pyodideLockfile = null;
72
+ /**
73
+ * Install Python dependencies declared in a pyproject.toml file.
74
+ */
75
+ async function installDependenciesPython(fileSystem, pyprojectTomlContent) {
76
+ const result = {
77
+ installed: [],
78
+ warnings: []
79
+ };
80
+ let pyprojectToml;
81
+ try {
82
+ pyprojectToml = parse(pyprojectTomlContent);
83
+ } catch {
84
+ result.warnings.push("Failed to parse pyproject.toml");
85
+ return result;
86
+ }
87
+ const depsToInstall = pyprojectToml.project?.dependencies ?? [];
88
+ depsToInstall.push("workers-runtime-sdk");
89
+ if (!pyodideLockfile) try {
90
+ pyodideLockfile = await fetchPyodideLockfile(PYODIDE_VERSION);
91
+ } catch (error) {
92
+ const message = error instanceof Error ? error.message : String(error);
93
+ result.warnings.push(`Could not retrieve Pyodide lockfile, attempts to retrieve packages from the Pyodide CDN may fail. Error: ${message}`);
94
+ }
95
+ const installedPackages = /* @__PURE__ */ new Set();
96
+ const inProgress = /* @__PURE__ */ new Map();
97
+ await Promise.all(depsToInstall.map((dependencySpecifier) => installPythonPackage(dependencySpecifier, result, fileSystem, installedPackages, inProgress, PYPI_SIMPLE_API)));
98
+ return result;
99
+ }
100
+ /**
101
+ * Parse a Python version specifier string (PEP 508).
102
+ * Currently only extracts the package name.
103
+ */
104
+ function parsePythonDependencySpecifier(spec) {
105
+ let head = spec.split(";", 1)[0] ?? "";
106
+ const match = head.match(/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)/);
107
+ return { name: match ? match[1] : head.trim() };
108
+ }
109
+ /**
110
+ * Install a single Python package from the Pyodide index.
111
+ * Uses PyPI as a fallback.
112
+ */
113
+ async function installPythonPackage(dependencySpecifier, result, fileSystem, installedPackages, inProgress, backupRegistry) {
114
+ const name = parsePythonDependencySpecifier(dependencySpecifier)["name"];
115
+ if (installedPackages.has(name)) return;
116
+ if (!shouldInstallDependency(dependencySpecifier)) return;
117
+ installedPackages.add(name);
118
+ const existing = inProgress.get(name);
119
+ if (existing) return existing;
120
+ const installPromise = (async () => {
121
+ try {
122
+ let response = {};
123
+ let wheel = {};
124
+ let version = "";
125
+ let registryResult = await retrieveFromPyodide(name);
126
+ if (registryResult) [response, wheel, version] = registryResult;
127
+ else {
128
+ registryResult = await retrieveFromPyPI(name, backupRegistry);
129
+ if (registryResult) [response, wheel, version] = registryResult;
130
+ else throw new Error(`Failed to download ${name}@${version}: ${response.status} ${response.statusText} (${wheel.url})`);
131
+ }
132
+ const buffer = await response.arrayBuffer();
133
+ const wheelContents = extractWheel(new Uint8Array(buffer));
134
+ const dependencies = getDependenciesFromWheel(wheelContents);
135
+ const packageFilesWheel = stripWheelToPackage(wheelContents);
136
+ result.installed.push(`${name}@${version}`);
137
+ for (const [filePath, content] of Object.entries(packageFilesWheel)) fileSystem.write(`python_modules/${filePath}`, content);
138
+ await Promise.all(dependencies.map((dep) => installPythonPackage(dep, result, fileSystem, installedPackages, inProgress, PYPI_SIMPLE_API)));
139
+ } catch (error) {
140
+ const message = error instanceof Error ? error.message : String(error);
141
+ result.warnings.push(`Failed to install ${name}: ${message}`);
142
+ }
143
+ })();
144
+ inProgress.set(name, installPromise);
145
+ try {
146
+ await installPromise;
147
+ } finally {
148
+ inProgress.delete(name);
149
+ }
150
+ }
151
+ async function retrieveFromPyPI(name, registry) {
152
+ const metadata = await fetchPythonPackageMetadata(name, registry);
153
+ const version = metadata.version;
154
+ const wheel = metadata.wheel;
155
+ const response = await fetchWithTimeout(wheel.url, {}, DEFAULT_TIMEOUT_MS * 2);
156
+ if (!response.ok) return null;
157
+ return [
158
+ response,
159
+ wheel,
160
+ version
161
+ ];
162
+ }
163
+ async function retrieveFromPyodide(name) {
164
+ const pyodideWheel = getPyodideWheel(name);
165
+ if (!pyodideWheel) return null;
166
+ const response = await fetchWithTimeout(pyodideWheel.url, {}, DEFAULT_TIMEOUT_MS * 2);
167
+ if (!response.ok) return null;
168
+ const version = pyodideWheel.package.version;
169
+ return [
170
+ response,
171
+ pyodideWheel.file,
172
+ version
173
+ ];
174
+ }
175
+ function shouldInstallDependency(dependencySpecifier) {
176
+ const semicolonPos = dependencySpecifier.indexOf(";");
177
+ if (semicolonPos > -1 && (dependencySpecifier.substring(semicolonPos).includes("extra ==") || dependencySpecifier.substring(semicolonPos).includes("extra=="))) return false;
178
+ return true;
179
+ }
180
+ /**
181
+ * Strip a Python wheel down to just the package contents.
182
+ *
183
+ * TODO: Re-review this function once we've cleared issues with file extension limits
184
+ * in workerd; this function excludes certain metadata files in *.dist-info/ for now but it shouldn't remain this way
185
+ */
186
+ function stripWheelToPackage(files) {
187
+ const result = {};
188
+ for (const [path, content] of Object.entries(files)) {
189
+ if (path.includes(".dist-info/") || path.includes(".data/")) continue;
190
+ result[path] = content;
191
+ }
192
+ return result;
193
+ }
194
+ /**
195
+ * Fetch the Pyodide lockfile for a given Pyodide version.
196
+ *
197
+ * The lockfile lists all pre-built packages available in the Pyodide
198
+ * distribution, including their wheel URLs, hashes, and dependencies.
199
+ */
200
+ async function fetchPyodideLockfile(version) {
201
+ const url = `https://cdn.jsdelivr.net/pyodide/${version}/full/pyodide-lock.json`;
202
+ try {
203
+ const response = await fetchWithTimeout(url);
204
+ if (!response.ok) return null;
205
+ return await response.json();
206
+ } catch {
207
+ return null;
208
+ }
209
+ }
210
+ /**
211
+ * Normalize a Python package name per PEP 503.
212
+ *
213
+ * Lowercases the name and collapses runs of `-`, `_`, and `.` into a single `-`.
214
+ */
215
+ function normalizePythonName(name) {
216
+ return name.toLowerCase().replace(/[-_.]+/g, "-");
217
+ }
218
+ /**
219
+ * Look up a package in the loaded Pyodide lockfile and return the URL and a
220
+ * Simple-API-shaped file entry for its wheel.
221
+ *
222
+ * Returns `null` if the lockfile is not loaded or the package is not present.
223
+ */
224
+ function getPyodideWheel(name) {
225
+ if (!pyodideLockfile) return null;
226
+ const normalizedName = normalizePythonName(name);
227
+ const pkg = pyodideLockfile.packages[normalizedName];
228
+ if (!pkg) return null;
229
+ const baseUrl = `https://cdn.jsdelivr.net/pyodide/${PYODIDE_VERSION}/full`;
230
+ const url = pkg.file_name.startsWith("http") ? pkg.file_name : `${baseUrl}/${pkg.file_name}`;
231
+ return {
232
+ package: pkg,
233
+ url,
234
+ file: {
235
+ filename: pkg.file_name,
236
+ url,
237
+ hashes: { sha256: pkg.sha256 }
238
+ }
239
+ };
240
+ }
241
+ async function fetchPythonPackageMetadata(name, registry) {
242
+ const metadataResponse = await fetchWithTimeout(`${registry}/${normalizePythonName(name)}/`, { headers: { Accept: "application/vnd.pypi.simple.v1+json" } });
243
+ if (!metadataResponse.ok) {
244
+ const hint = metadataResponse.status === 404 ? " (package not found — check the name in pyproject.toml)" : "";
245
+ throw new Error(`Registry ${registry} returned ${metadataResponse.status} ${metadataResponse.statusText} for "${name}"${hint}`);
246
+ }
247
+ const wheel = selectLatestCompatibleWheel((await metadataResponse.json()).files);
248
+ if (!wheel) throw new Error(`No compatible wheel found for ${name} on registry ${registry}`);
249
+ const version = parseVersionFromWheelName(wheel.filename);
250
+ if (!version) throw new Error(`Could not parse version from wheel filename: ${wheel.filename}`);
251
+ return {
252
+ version,
253
+ wheel
254
+ };
255
+ }
256
+ /**
257
+ * Select a compatible wheel from PyPI Simple API files list.
258
+ * Prefers py3-none-any or py2.py3-none-any wheels for maximum compatibility.
259
+ * Selects the latest version from compatible wheels.
260
+ * TODO: implement proper platform/python version matching
261
+ */
262
+ function selectLatestCompatibleWheel(files) {
263
+ const wheels = files.filter((f) => f.filename.endsWith(".whl"));
264
+ if (wheels.length === 0) return null;
265
+ const universal = wheels.filter((w) => w.filename.endsWith("-py3-none-any.whl") || w.filename.endsWith("-py2.py3-none-any.whl"));
266
+ const candidates = universal.length > 0 ? universal : wheels;
267
+ let latest = null;
268
+ let latestVersion;
269
+ for (const wheel of candidates) {
270
+ const version = parseVersionFromWheelName(wheel.filename);
271
+ if (!version) continue;
272
+ if (!latest || !latestVersion || comparePythonVersions(version, latestVersion) > 0) {
273
+ latest = wheel;
274
+ latestVersion = version;
275
+ }
276
+ }
277
+ return latest;
278
+ }
279
+ /**
280
+ * Compare two PEP 440 version strings.
281
+ * Returns >0 if a > b, <0 if a < b, 0 if equal.
282
+ *
283
+ * Python versions (PEP 440) are not semver-compatible (e.g. "3.6.2.1" has four
284
+ * release segments), so semver cannot be used here. This is a minimal
285
+ * comparison: it compares the dotted numeric release segments, and treats
286
+ * pre-release/dev versions (a/b/rc/alpha/beta/dev/pre) as lower than the same
287
+ * release so a stable release is preferred.
288
+ * TODO: full PEP 440 ordering (post-releases, local versions, epochs) if needed.
289
+ */
290
+ function comparePythonVersions(a, b) {
291
+ const parse = (v) => {
292
+ const releaseMatch = v.match(/^[0-9]+(?:\.[0-9]+)*/);
293
+ const release = (releaseMatch?.[0] ?? "0").split(".").map(Number);
294
+ const rest = v.slice(releaseMatch?.[0].length ?? 0);
295
+ return {
296
+ release,
297
+ isPre: /^[.\-_]?(a|b|c|rc|alpha|beta|dev|pre)/i.test(rest)
298
+ };
299
+ };
300
+ const av = parse(a);
301
+ const bv = parse(b);
302
+ const len = Math.max(av.release.length, bv.release.length);
303
+ for (let i = 0; i < len; i++) {
304
+ const diff = (av.release[i] ?? 0) - (bv.release[i] ?? 0);
305
+ if (diff !== 0) return diff;
306
+ }
307
+ if (av.isPre !== bv.isPre) return av.isPre ? -1 : 1;
308
+ return 0;
309
+ }
310
+ /**
311
+ * Parse version from a wheel filename.
312
+ * Wheel format: {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl
313
+ *
314
+ * With no build tag (5 parts): distribution-version-python-abi-platform.whl
315
+ * With build tag (6+ parts): distribution-version-build-python-abi-platform.whl
316
+ */
317
+ function parseVersionFromWheelName(filename) {
318
+ const parts = filename.replace(/\.whl$/, "").split("-");
319
+ if (parts.length < 5) return void 0;
320
+ return parts[1];
321
+ }
322
+ /**
323
+ * Extract Requires-Dist entries from a wheel's *.dist-info/METADATA file.
324
+ * Accepts the file record returned by `extractWheel`.
325
+ * Returns an empty array if METADATA is missing or contains no dependencies.
326
+ */
327
+ function getDependenciesFromWheel(files) {
328
+ const metadataPath = Object.keys(files).find((path) => path.endsWith(".dist-info/METADATA"));
329
+ if (!metadataPath) return [];
330
+ const metadata = files[metadataPath];
331
+ if (!metadata) return [];
332
+ if (typeof metadata !== "string") return [];
333
+ return parseRequiresDist(metadata);
334
+ }
335
+ /**
336
+ * Parse Requires-Dist headers from Python package METADATA file (RFC 822 format).
337
+ */
338
+ function parseRequiresDist(metadata) {
339
+ const requires = [];
340
+ const lines = metadata.split(/\r?\n/);
341
+ for (const line of lines) if (line !== void 0 && line.startsWith("Requires-Dist:")) requires.push(line.slice(14).trim());
342
+ return requires;
343
+ }
344
+ /**
345
+ * Extract files from a ZIP archive (Python wheel).
346
+ */
347
+ function extractWheel(data) {
348
+ const unzipped = unzipSync(data);
349
+ const files = {};
350
+ const textDecoder = new TextDecoder();
351
+ for (const [path, content] of Object.entries(unzipped)) {
352
+ if (path.endsWith(".dist-info/METADATA")) {
353
+ files[path] = textDecoder.decode(content);
354
+ continue;
355
+ }
356
+ if (path.endsWith(".md") || path.endsWith(".css") || path.endsWith(".js") || path.endsWith(".txt") || path.endsWith("LICENSE") || path.endsWith(".rst")) continue;
357
+ if (isTextFile(path)) files[path] = textDecoder.decode(content);
358
+ else files[path] = { data: new Uint8Array(content) };
359
+ }
360
+ return files;
361
+ }
362
+ //#endregion
363
+ //#region src/installer.ts
364
+ /**
365
+ * NPM package installer for virtual file systems.
366
+ *
367
+ * This module fetches packages from the npm registry and populates
368
+ * a virtual node_modules directory structure.
369
+ * It also branches into the Python logic in installer-python.ts
370
+ * if dependencies are declared for a Python dynamic worker.
371
+ */
372
+ const NPM_REGISTRY = "https://registry.npmjs.org";
373
+ /**
374
+ * Install npm dependencies into a virtual file system.
375
+ *
376
+ * Reads the package.json from the files, resolves all dependencies,
377
+ * and populates node_modules with the package contents.
378
+ *
379
+ * @param fileSystem - Virtual file system containing package.json
380
+ * @param options - Installation options
381
+ * @returns Metadata about the installation
382
+ */
383
+ async function installDependencies(fileSystem, options = {}) {
384
+ const { dev = false, registry = NPM_REGISTRY } = options;
385
+ const result = {
386
+ installed: [],
387
+ warnings: []
388
+ };
389
+ const packageJsonContent = fileSystem.read("package.json");
390
+ const pyprojectTomlContent = fileSystem.read("pyproject.toml");
391
+ if (packageJsonContent && pyprojectTomlContent) {
392
+ result.warnings.push("Cannot have package.json and pyproject.toml");
393
+ return result;
394
+ }
395
+ if (packageJsonContent) {
396
+ let packageJson;
397
+ try {
398
+ packageJson = JSON.parse(packageJsonContent);
399
+ } catch {
400
+ result.warnings.push("Failed to parse package.json");
401
+ return result;
402
+ }
403
+ const depsToInstall = {
404
+ ...packageJson.dependencies,
405
+ ...dev ? packageJson.devDependencies : {}
406
+ };
407
+ if (Object.keys(depsToInstall).length === 0) return result;
408
+ const installedPackages = /* @__PURE__ */ new Set();
409
+ const inProgress = /* @__PURE__ */ new Map();
410
+ await Promise.all(Object.entries(depsToInstall).map(([name, versionRange]) => installPackage(name, versionRange, result, fileSystem, installedPackages, inProgress, registry)));
411
+ } else if (pyprojectTomlContent) return await installDependenciesPython(fileSystem, pyprojectTomlContent);
412
+ return result;
413
+ }
414
+ /**
415
+ * Install a single package and its dependencies recursively.
416
+ */
417
+ async function installPackage(name, versionRange, result, fileSystem, installedPackages, inProgress, registry) {
418
+ if (installedPackages.has(name)) return;
419
+ if (fileSystem.read(`node_modules/${name}/package.json`) !== null) {
420
+ installedPackages.add(name);
421
+ return;
422
+ }
423
+ const existing = inProgress.get(name);
424
+ if (existing) return existing;
425
+ const installPromise = (async () => {
426
+ try {
427
+ const metadata = await fetchPackageMetadata(name, registry);
428
+ const version = resolveVersion(versionRange, metadata);
429
+ if (!version) {
430
+ result.warnings.push(`Could not resolve version for ${name}@${versionRange}`);
431
+ return;
432
+ }
433
+ const versionMetadata = metadata.versions[version];
434
+ if (!versionMetadata) {
435
+ result.warnings.push(`Version ${version} not found for ${name}`);
436
+ return;
437
+ }
438
+ installedPackages.add(name);
439
+ result.installed.push(`${name}@${version}`);
440
+ const packageFiles = await fetchPackageFiles(name, versionMetadata);
441
+ for (const [filePath, content] of Object.entries(packageFiles)) fileSystem.write(`node_modules/${name}/${filePath}`, content);
442
+ const deps = versionMetadata.dependencies ?? {};
443
+ await Promise.all(Object.entries(deps).map(([depName, depVersion]) => installPackage(depName, depVersion, result, fileSystem, installedPackages, inProgress, registry)));
444
+ } catch (error) {
445
+ const message = error instanceof Error ? error.message : String(error);
446
+ result.warnings.push(`Failed to install ${name}: ${message}`);
447
+ }
448
+ })();
449
+ inProgress.set(name, installPromise);
450
+ try {
451
+ await installPromise;
452
+ } finally {
453
+ inProgress.delete(name);
454
+ }
455
+ }
456
+ /**
457
+ * Fetch package metadata from npm registry.
458
+ */
459
+ async function fetchPackageMetadata(name, registry) {
460
+ const url = `${registry}/${name.startsWith("@") ? `@${encodeURIComponent(name.slice(1))}` : name}`;
461
+ const response = await fetchWithTimeout(url, { headers: { Accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" } });
462
+ if (!response.ok) {
463
+ const hint = response.status === 404 ? " (package not found — check the name in package.json or set the `registry` option if it lives on a private registry)" : "";
464
+ throw new Error(`Registry returned ${response.status} ${response.statusText} for "${name}" at ${url}${hint}`);
465
+ }
466
+ return await response.json();
467
+ }
468
+ /**
469
+ * Resolve a semver range to a specific version.
470
+ */
471
+ function resolveVersion(range, metadata) {
472
+ if (range === "latest" || range === "*") return metadata["dist-tags"]["latest"];
473
+ if (metadata.versions[range]) return range;
474
+ if (metadata["dist-tags"][range]) return metadata["dist-tags"][range];
475
+ const versions = Object.keys(metadata.versions);
476
+ return semver.maxSatisfying(versions, range) ?? void 0;
477
+ }
478
+ /**
479
+ * Fetch and extract package files from npm tarball.
480
+ */
481
+ async function fetchPackageFiles(name, metadata) {
482
+ const tarballUrl = metadata.dist?.tarball;
483
+ if (!tarballUrl) throw new Error(`Registry metadata for ${name}@${metadata.version} is missing \`dist.tarball\` — the registry response is likely malformed or the version was unpublished.`);
484
+ const response = await fetchWithTimeout(tarballUrl, {}, DEFAULT_TIMEOUT_MS * 2);
485
+ if (!response.ok) throw new Error(`Failed to fetch tarball for ${name}@${metadata.version}: ${response.status} ${response.statusText} (${tarballUrl})`);
486
+ const buffer = await response.arrayBuffer();
487
+ return extractTarball(new Uint8Array(buffer));
488
+ }
489
+ /**
490
+ * Extract files from a gzipped tarball.
491
+ *
492
+ * npm packages are distributed as .tgz files (gzipped tar).
493
+ * Package contents are usually enclosed by one archive directory, which is
494
+ * removed by `parseTar` so returned paths are relative to the package root.
495
+ */
496
+ async function extractTarball(data) {
497
+ return parseTar(await decompress(data));
498
+ }
499
+ /**
500
+ * Decompress gzip data using DecompressionStream.
501
+ */
502
+ async function decompress(data) {
503
+ const ds = new DecompressionStream("gzip");
504
+ const writer = ds.writable.getWriter();
505
+ const reader = ds.readable.getReader();
506
+ writer.write(data).catch(() => {});
507
+ writer.close().catch(() => {});
508
+ const chunks = [];
509
+ let totalLength = 0;
510
+ while (true) {
511
+ const { done, value } = await reader.read();
512
+ if (done) break;
513
+ chunks.push(value);
514
+ totalLength += value.length;
515
+ }
516
+ const result = new Uint8Array(totalLength);
517
+ let offset = 0;
518
+ for (const chunk of chunks) {
519
+ result.set(chunk, offset);
520
+ offset += chunk.length;
521
+ }
522
+ return result;
523
+ }
524
+ /**
525
+ * Parse a tar archive and extract text files.
526
+ *
527
+ * TAR format:
528
+ * - 512-byte header blocks
529
+ * - File content (padded to 512 bytes)
530
+ * - Two empty blocks at the end
531
+ */
532
+ function parseTar(data) {
533
+ const textDecoder = new TextDecoder();
534
+ const regularFilePaths = [];
535
+ const textFiles = /* @__PURE__ */ new Map();
536
+ let offset = 0;
537
+ while (offset < data.length - 512) {
538
+ const header = data.slice(offset, offset + 512);
539
+ if (header.every((b) => b === 0)) break;
540
+ const filePath = normalizeTarEntryPath(readTarEntryPath(header));
541
+ const sizeStr = readString(header, 124, 12);
542
+ const typeFlag = header[156];
543
+ const size = parseInt(sizeStr.trim(), 8) || 0;
544
+ offset += 512;
545
+ const isRegularFile = typeFlag === 48 || typeFlag === 0;
546
+ if (isRegularFile && filePath !== "") regularFilePaths.push(filePath);
547
+ if (isRegularFile && size > 0 && isTextFile(filePath)) {
548
+ const content = data.slice(offset, offset + size);
549
+ try {
550
+ textFiles.set(filePath, textDecoder.decode(content));
551
+ } catch {}
552
+ }
553
+ offset += Math.ceil(size / 512) * 512;
554
+ }
555
+ const archiveRoot = findSharedTarRootDirectory(regularFilePaths);
556
+ const files = {};
557
+ for (const [filePath, content] of textFiles) {
558
+ const packagePath = archiveRoot ? filePath.slice(archiveRoot.length) : filePath;
559
+ files[packagePath] = content;
560
+ }
561
+ return files;
562
+ }
563
+ /**
564
+ * Read a TAR entry path, including the directory prefix from POSIX USTAR.
565
+ */
566
+ function readTarEntryPath(header) {
567
+ const name = readString(header, 0, 100);
568
+ if (!(readString(header, 257, 6) === "ustar" && readString(header, 263, 2) === "00")) return name;
569
+ const prefix = readString(header, 345, 155);
570
+ return prefix === "" ? name : `${prefix}/${name}`;
571
+ }
572
+ /**
573
+ * Normalize the current-directory prefix that tar writers may add to entries.
574
+ */
575
+ function normalizeTarEntryPath(filePath) {
576
+ let normalizedPath = filePath;
577
+ while (normalizedPath.startsWith("./")) normalizedPath = normalizedPath.slice(2);
578
+ return normalizedPath;
579
+ }
580
+ /**
581
+ * Return the enclosing tar directory shared by every regular file.
582
+ *
583
+ * npm clients remove one enclosing directory during extraction without
584
+ * requiring it to be named `package`. If any file is already at the archive
585
+ * root, or files have different roots, the archive is left unchanged.
586
+ */
587
+ function findSharedTarRootDirectory(filePaths) {
588
+ let sharedRoot;
589
+ for (const filePath of filePaths) {
590
+ const separatorIndex = filePath.indexOf("/");
591
+ if (separatorIndex <= 0) return;
592
+ const fileRoot = filePath.slice(0, separatorIndex + 1);
593
+ if (sharedRoot === void 0) sharedRoot = fileRoot;
594
+ else if (sharedRoot !== fileRoot) return;
595
+ }
596
+ return sharedRoot;
597
+ }
598
+ /**
599
+ * Read a null-terminated string from a buffer.
600
+ */
601
+ function readString(buffer, offset, length) {
602
+ const bytes = buffer.slice(offset, offset + length);
603
+ const nullIndex = bytes.indexOf(0);
604
+ const relevantBytes = nullIndex >= 0 ? bytes.slice(0, nullIndex) : bytes;
605
+ return new TextDecoder().decode(relevantBytes);
606
+ }
607
+ /**
608
+ * Check if files contain a package.json or pyproject.toml with dependencies that need installing.
609
+ */
610
+ function hasDependencies(files) {
611
+ const pyprojectToml = files.read("pyproject.toml");
612
+ const packageJson = files.read("package.json");
613
+ if (!packageJson && !pyprojectToml) return false;
614
+ if (packageJson) try {
615
+ const deps = JSON.parse(packageJson).dependencies ?? {};
616
+ return Object.keys(deps).length > 0;
617
+ } catch {
618
+ return false;
619
+ }
620
+ if (pyprojectToml) try {
621
+ return (parse(pyprojectToml).project?.dependencies ?? []).length > 0;
622
+ } catch {
623
+ return false;
624
+ }
625
+ return false;
626
+ }
627
+ //#endregion
628
+ export { hasDependencies as n, installDependencies as r, fetchPackageFiles as t };
629
+
630
+ //# sourceMappingURL=installer-DDvaMqav.js.map