npmjs-server 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/cli.mjs +898 -53
- package/dist/cli.mjs.map +1 -1
- package/dist/ui/assets/{index-MciKHD-E.js → index-BRuGs4Xb.js} +1 -1
- package/dist/ui/index.html +1 -1
- package/package.json +9 -7
package/dist/cli.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/*!
|
|
3
3
|
* name: npmjs-server
|
|
4
|
-
* version: 0.
|
|
4
|
+
* version: 0.3.0
|
|
5
5
|
* description: NPM package registry server on Node.js
|
|
6
6
|
* author: Kouji Matsui (@kekyo@mi.kekyo.net)
|
|
7
7
|
* license: MIT
|
|
8
8
|
* repository.url: https://github.com/kekyo/npmjs-server.git
|
|
9
|
-
* git.commit.hash:
|
|
9
|
+
* git.commit.hash: c223a260e73f6d93117246af4b1f6d7450e67717
|
|
10
10
|
*/
|
|
11
11
|
import { Command, Option } from "commander";
|
|
12
12
|
import __screwUpDefaultImportModule0, { LogController } from "fastify";
|
|
@@ -27,6 +27,7 @@ import { Secret, TOTP } from "otpauth";
|
|
|
27
27
|
import { Strategy } from "passport-local";
|
|
28
28
|
import __screwUpDefaultImportModule0$2 from "dayjs";
|
|
29
29
|
import * as readline from "readline";
|
|
30
|
+
import os from "os";
|
|
30
31
|
//#region \0rolldown/runtime.js
|
|
31
32
|
var __create = Object.create;
|
|
32
33
|
var __defProp = Object.defineProperty;
|
|
@@ -52,7 +53,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
52
53
|
//#endregion
|
|
53
54
|
//#region src/generated/packageMetadata.ts
|
|
54
55
|
var name = "npmjs-server";
|
|
55
|
-
var version = "0.
|
|
56
|
+
var version = "0.3.0";
|
|
56
57
|
var description = "NPM package registry server on Node.js";
|
|
57
58
|
//#endregion
|
|
58
59
|
//#region src/utils/fileStreaming.ts
|
|
@@ -185,6 +186,35 @@ function getMimeTypeFromExtension(ext) {
|
|
|
185
186
|
}[ext.toLowerCase()] || "application/octet-stream";
|
|
186
187
|
}
|
|
187
188
|
//#endregion
|
|
189
|
+
//#region src/utils/atomicFile.ts
|
|
190
|
+
/**
|
|
191
|
+
* Replaces a private file only after its new contents have been written and synced.
|
|
192
|
+
* @param filePath Destination in an existing, writable directory.
|
|
193
|
+
* @param content Complete replacement contents.
|
|
194
|
+
* @returns Resolves after the replacement has completed.
|
|
195
|
+
* @remarks Preserves explicit read-only protection of an existing destination.
|
|
196
|
+
*/
|
|
197
|
+
var writePrivateFile = async (filePath, content) => {
|
|
198
|
+
try {
|
|
199
|
+
await access(filePath, constants.W_OK);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (error.code !== "ENOENT") throw error;
|
|
202
|
+
}
|
|
203
|
+
const temporaryPath = `${filePath}.${randomBytes(16).toString("hex")}.tmp`;
|
|
204
|
+
try {
|
|
205
|
+
const file = await open(temporaryPath, "wx", 384);
|
|
206
|
+
try {
|
|
207
|
+
await file.writeFile(content, "utf8");
|
|
208
|
+
await file.sync();
|
|
209
|
+
} finally {
|
|
210
|
+
await file.close();
|
|
211
|
+
}
|
|
212
|
+
await rename(temporaryPath, filePath);
|
|
213
|
+
} finally {
|
|
214
|
+
await rm(temporaryPath, { force: true });
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
//#endregion
|
|
188
218
|
//#region src/utils/npmPackage.ts
|
|
189
219
|
/**
|
|
190
220
|
* Decodes a package name from a route parameter.
|
|
@@ -280,9 +310,9 @@ var extractNpmTarball = async (tarball, signal) => {
|
|
|
280
310
|
};
|
|
281
311
|
//#endregion
|
|
282
312
|
//#region src/services/metadataService.ts
|
|
283
|
-
var semver = __resolveDefaultExport$
|
|
313
|
+
var semver$1 = __resolveDefaultExport$4(__screwUpDefaultImportModule0$1, false);
|
|
284
314
|
globalThis.__screwUpIsInCJS_207daccbf51b = false;
|
|
285
|
-
function __resolveDefaultExport$
|
|
315
|
+
function __resolveDefaultExport$4(module, isESM) {
|
|
286
316
|
const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_207daccbf51b === true;
|
|
287
317
|
const maybe = module;
|
|
288
318
|
const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
|
|
@@ -310,6 +340,7 @@ function __resolveDefaultExport$3(module, isESM) {
|
|
|
310
340
|
var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger) => {
|
|
311
341
|
const packagesCache = /* @__PURE__ */ new Map();
|
|
312
342
|
const distTagsCache = /* @__PURE__ */ new Map();
|
|
343
|
+
const explicitDistTags = /* @__PURE__ */ new Set();
|
|
313
344
|
let currentBaseUrl = baseUrl.replace(/\/$/, "");
|
|
314
345
|
const cacheLock = createReaderWriterLock();
|
|
315
346
|
const normalizeKey = (packageName) => packageName.toLowerCase();
|
|
@@ -319,6 +350,7 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
319
350
|
const getComputedLatestVersion = (entries) => entries[0]?.metadata.version;
|
|
320
351
|
const withComputedLatestDistTag = (entries, distTags) => {
|
|
321
352
|
const filteredTags = filterExistingDistTags(entries, distTags);
|
|
353
|
+
if (entries[0] && explicitDistTags.has(normalizeKey(entries[0].metadata.name))) return filteredTags;
|
|
322
354
|
const latest = getComputedLatestVersion(entries);
|
|
323
355
|
return latest ? {
|
|
324
356
|
latest,
|
|
@@ -335,6 +367,10 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
335
367
|
try {
|
|
336
368
|
const content = await fs.readFile(distTagsPath, "utf-8");
|
|
337
369
|
const parsed = JSON.parse(content);
|
|
370
|
+
if (parsed.format === "npmjs-server/dist-tags-v1") {
|
|
371
|
+
explicitDistTags.add(normalizeKey(entries[0].metadata.name));
|
|
372
|
+
return filterExistingDistTags(entries, parsed.tags);
|
|
373
|
+
}
|
|
338
374
|
return withComputedLatestDistTag(entries, parsed);
|
|
339
375
|
} catch {
|
|
340
376
|
return withComputedLatestDistTag(entries, {});
|
|
@@ -343,6 +379,13 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
343
379
|
const savePersistableDistTags = async (packageName, entries, distTags) => {
|
|
344
380
|
const packagePath = getPackageRootPath(packageName);
|
|
345
381
|
const distTagsPath = path.join(packagePath, "dist-tags.json");
|
|
382
|
+
if (explicitDistTags.has(normalizeKey(packageName))) {
|
|
383
|
+
await writePrivateFile(distTagsPath, JSON.stringify({
|
|
384
|
+
format: "npmjs-server/dist-tags-v1",
|
|
385
|
+
tags: filterExistingDistTags(entries, distTags)
|
|
386
|
+
}, null, 2));
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
346
389
|
const persistableTags = getPersistableDistTags(entries, distTags);
|
|
347
390
|
if (Object.keys(persistableTags).length === 0) {
|
|
348
391
|
await fs.rm(distTagsPath, { force: true });
|
|
@@ -355,8 +398,8 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
355
398
|
try {
|
|
356
399
|
const manifestPath = path.join(versionPath, "package.json");
|
|
357
400
|
const metadataPath = path.join(versionPath, "metadata.json");
|
|
358
|
-
const manifest = JSON.parse(await fs.readFile(manifestPath, "utf-8"));
|
|
359
401
|
const metadataFile = JSON.parse(await fs.readFile(metadataPath, "utf-8"));
|
|
402
|
+
const manifest = metadataFile.manifest ?? JSON.parse(await fs.readFile(manifestPath, "utf-8"));
|
|
360
403
|
const tarballName = metadataFile.tarballName ?? createTarballFileName(manifest.name || packageName, version);
|
|
361
404
|
const actualName = manifest.name || packageName;
|
|
362
405
|
const actualVersion = manifest.version || version;
|
|
@@ -366,7 +409,8 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
366
409
|
version: actualVersion,
|
|
367
410
|
manifest,
|
|
368
411
|
readme: metadataFile.readme,
|
|
369
|
-
|
|
412
|
+
packageReadme: metadataFile.packageReadme,
|
|
413
|
+
published: metadataFile.published === null ? void 0 : metadataFile.published ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
370
414
|
shasum: metadataFile.shasum,
|
|
371
415
|
integrity: metadataFile.integrity,
|
|
372
416
|
tarballName,
|
|
@@ -383,10 +427,11 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
383
427
|
return;
|
|
384
428
|
}
|
|
385
429
|
};
|
|
386
|
-
const sortEntries = (entries) => entries.sort((a, b) => semver.rcompare(a.metadata.version, b.metadata.version));
|
|
430
|
+
const sortEntries = (entries) => entries.sort((a, b) => semver$1.rcompare(a.metadata.version, b.metadata.version));
|
|
387
431
|
const scanPackageVersions = async (packageName, packagePath) => {
|
|
388
432
|
const versionDirs = await fs.readdir(packagePath);
|
|
389
433
|
const entries = (await Promise.all(versionDirs.map(async (version) => {
|
|
434
|
+
if (version.startsWith(".")) return void 0;
|
|
390
435
|
const versionPath = path.join(packagePath, version);
|
|
391
436
|
if (!(await fs.stat(versionPath)).isDirectory()) return;
|
|
392
437
|
return loadPackageEntry(packageName, version, versionPath);
|
|
@@ -423,6 +468,7 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
423
468
|
await fs.writeFile(path.join(versionPath, "package.json"), JSON.stringify(entry.metadata.manifest, null, 2), "utf-8");
|
|
424
469
|
await fs.writeFile(path.join(versionPath, "metadata.json"), JSON.stringify({
|
|
425
470
|
readme: entry.metadata.readme,
|
|
471
|
+
packageReadme: entry.metadata.packageReadme,
|
|
426
472
|
published: entry.metadata.published,
|
|
427
473
|
shasum: entry.metadata.shasum,
|
|
428
474
|
integrity: entry.metadata.integrity,
|
|
@@ -437,6 +483,7 @@ var createMetadataService = (packagesRoot = "./packages", baseUrl = "", logger)
|
|
|
437
483
|
logger.info("Initializing npm metadata cache...");
|
|
438
484
|
packagesCache.clear();
|
|
439
485
|
distTagsCache.clear();
|
|
486
|
+
explicitDistTags.clear();
|
|
440
487
|
await scanPackages();
|
|
441
488
|
const versionCount = Array.from(packagesCache.values()).reduce((sum, entries) => sum + entries.length, 0);
|
|
442
489
|
logger.info(`npm metadata cache initialized: ${packagesCache.size} packages, ${versionCount} versions (took ${Date.now() - startTime}ms)`);
|
|
@@ -835,35 +882,6 @@ var createAuthService = (config) => {
|
|
|
835
882
|
};
|
|
836
883
|
};
|
|
837
884
|
//#endregion
|
|
838
|
-
//#region src/utils/atomicFile.ts
|
|
839
|
-
/**
|
|
840
|
-
* Replaces a private file only after its new contents have been written and synced.
|
|
841
|
-
* @param filePath Destination in an existing, writable directory.
|
|
842
|
-
* @param content Complete replacement contents.
|
|
843
|
-
* @returns Resolves after the replacement has completed.
|
|
844
|
-
* @remarks Preserves explicit read-only protection of an existing destination.
|
|
845
|
-
*/
|
|
846
|
-
var writePrivateFile = async (filePath, content) => {
|
|
847
|
-
try {
|
|
848
|
-
await access(filePath, constants.W_OK);
|
|
849
|
-
} catch (error) {
|
|
850
|
-
if (error.code !== "ENOENT") throw error;
|
|
851
|
-
}
|
|
852
|
-
const temporaryPath = `${filePath}.${randomBytes(16).toString("hex")}.tmp`;
|
|
853
|
-
try {
|
|
854
|
-
const file = await open(temporaryPath, "wx", 384);
|
|
855
|
-
try {
|
|
856
|
-
await file.writeFile(content, "utf8");
|
|
857
|
-
await file.sync();
|
|
858
|
-
} finally {
|
|
859
|
-
await file.close();
|
|
860
|
-
}
|
|
861
|
-
await rename(temporaryPath, filePath);
|
|
862
|
-
} finally {
|
|
863
|
-
await rm(temporaryPath, { force: true });
|
|
864
|
-
}
|
|
865
|
-
};
|
|
866
|
-
//#endregion
|
|
867
885
|
//#region src/utils/crypto.ts
|
|
868
886
|
/**
|
|
869
887
|
* Generates a random salt for password hashing
|
|
@@ -3888,7 +3906,7 @@ var require_feedback = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
3888
3906
|
};
|
|
3889
3907
|
module.exports = feedback;
|
|
3890
3908
|
}));
|
|
3891
|
-
var zxcvbn = __resolveDefaultExport$
|
|
3909
|
+
var zxcvbn = __resolveDefaultExport$3((/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3892
3910
|
var feedback;
|
|
3893
3911
|
var matching = require_matching();
|
|
3894
3912
|
var scoring = require_scoring();
|
|
@@ -3923,7 +3941,7 @@ var zxcvbn = __resolveDefaultExport$2((/* @__PURE__ */ __toESM((/* @__PURE__ */
|
|
|
3923
3941
|
module.exports = zxcvbn;
|
|
3924
3942
|
})))(), 1)).default, false);
|
|
3925
3943
|
globalThis.__screwUpIsInCJS_7151bc62ebf5 = false;
|
|
3926
|
-
function __resolveDefaultExport$
|
|
3944
|
+
function __resolveDefaultExport$3(module, isESM) {
|
|
3927
3945
|
const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_7151bc62ebf5 === true;
|
|
3928
3946
|
const maybe = module;
|
|
3929
3947
|
const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
|
|
@@ -5512,7 +5530,7 @@ var createPackument = (baseUrl, packageName, metadataService) => {
|
|
|
5512
5530
|
tarballUrl: `${baseUrl}/${encodePackageNameForPath(metadata.name)}/-/${encodeURIComponent(metadata.tarballName)}`
|
|
5513
5531
|
})]));
|
|
5514
5532
|
const time = Object.fromEntries(versions.map((metadata) => [metadata.version, metadata.published]));
|
|
5515
|
-
const sortedPublishedTimes = versions.map((metadata) => metadata.published).sort();
|
|
5533
|
+
const sortedPublishedTimes = versions.map((metadata) => metadata.published).filter((published) => published !== void 0).sort();
|
|
5516
5534
|
return {
|
|
5517
5535
|
_id: latest.name,
|
|
5518
5536
|
name: latest.name,
|
|
@@ -5524,7 +5542,7 @@ var createPackument = (baseUrl, packageName, metadataService) => {
|
|
|
5524
5542
|
modified: sortedPublishedTimes[sortedPublishedTimes.length - 1],
|
|
5525
5543
|
...time
|
|
5526
5544
|
},
|
|
5527
|
-
readme: latest.readme ?? latest.manifest.readme ?? "",
|
|
5545
|
+
readme: latest.packageReadme ?? latest.readme ?? latest.manifest.readme ?? "",
|
|
5528
5546
|
maintainers: latest.manifest.maintainers ?? [],
|
|
5529
5547
|
keywords: latest.manifest.keywords ?? [],
|
|
5530
5548
|
license: latest.manifest.license,
|
|
@@ -6359,12 +6377,12 @@ var registerPublishRoutes = async (fastify, config) => {
|
|
|
6359
6377
|
};
|
|
6360
6378
|
//#endregion
|
|
6361
6379
|
//#region src/server.ts
|
|
6362
|
-
var Fastify = __resolveDefaultExport$
|
|
6363
|
-
var fastifyPassport = __resolveDefaultExport$
|
|
6364
|
-
var fastifySecureSession = __resolveDefaultExport$
|
|
6365
|
-
var fastifyStatic = __resolveDefaultExport$
|
|
6380
|
+
var Fastify = __resolveDefaultExport$2(__screwUpDefaultImportModule0, false);
|
|
6381
|
+
var fastifyPassport = __resolveDefaultExport$2(__screwUpDefaultImportModule1, false);
|
|
6382
|
+
var fastifySecureSession = __resolveDefaultExport$2(__screwUpDefaultImportModule2, false);
|
|
6383
|
+
var fastifyStatic = __resolveDefaultExport$2(__screwUpDefaultImportModule3, false);
|
|
6366
6384
|
globalThis.__screwUpIsInCJS_ab1cf391d59b = false;
|
|
6367
|
-
function __resolveDefaultExport$
|
|
6385
|
+
function __resolveDefaultExport$2(module, isESM) {
|
|
6368
6386
|
const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_ab1cf391d59b === true;
|
|
6369
6387
|
const maybe = module;
|
|
6370
6388
|
const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
|
|
@@ -6600,7 +6618,7 @@ var createFastifyInstance = async (config, logger, locker) => {
|
|
|
6600
6618
|
return controller.signal;
|
|
6601
6619
|
} });
|
|
6602
6620
|
const authConfig = {
|
|
6603
|
-
realm: config.realm || `npmjs-server 0.
|
|
6621
|
+
realm: config.realm || `npmjs-server 0.3.0`,
|
|
6604
6622
|
userService,
|
|
6605
6623
|
sessionService,
|
|
6606
6624
|
authFailureTracker,
|
|
@@ -6778,7 +6796,7 @@ var createFastifyInstance = async (config, logger, locker) => {
|
|
|
6778
6796
|
availableLanguages = ["en"];
|
|
6779
6797
|
}
|
|
6780
6798
|
return {
|
|
6781
|
-
realm: config.realm || `npmjs-server 0.
|
|
6799
|
+
realm: config.realm || `npmjs-server 0.3.0`,
|
|
6782
6800
|
name,
|
|
6783
6801
|
version,
|
|
6784
6802
|
git_commit_hash: "unknown",
|
|
@@ -6818,7 +6836,7 @@ var createFastifyInstance = async (config, logger, locker) => {
|
|
|
6818
6836
|
authService,
|
|
6819
6837
|
packagesRoot,
|
|
6820
6838
|
logger,
|
|
6821
|
-
realm: config.realm || `npmjs-server 0.
|
|
6839
|
+
realm: config.realm || `npmjs-server 0.3.0`,
|
|
6822
6840
|
serverUrl,
|
|
6823
6841
|
metadataService
|
|
6824
6842
|
}, locker);
|
|
@@ -6952,9 +6970,9 @@ var startFastifyServer = async (config, logger) => {
|
|
|
6952
6970
|
};
|
|
6953
6971
|
//#endregion
|
|
6954
6972
|
//#region src/logger.ts
|
|
6955
|
-
var dayjs = __resolveDefaultExport(__screwUpDefaultImportModule0$2, false);
|
|
6973
|
+
var dayjs = __resolveDefaultExport$1(__screwUpDefaultImportModule0$2, false);
|
|
6956
6974
|
globalThis.__screwUpIsInCJS_2186a1bb65e1 = false;
|
|
6957
|
-
function __resolveDefaultExport(module, isESM) {
|
|
6975
|
+
function __resolveDefaultExport$1(module, isESM) {
|
|
6958
6976
|
const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_2186a1bb65e1 === true;
|
|
6959
6977
|
const maybe = module;
|
|
6960
6978
|
const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
|
|
@@ -7077,6 +7095,19 @@ var promptPassword = (prompt) => {
|
|
|
7077
7095
|
process.stdin.on("data", onData);
|
|
7078
7096
|
});
|
|
7079
7097
|
};
|
|
7098
|
+
/**
|
|
7099
|
+
* Prompts for yes/no confirmation
|
|
7100
|
+
*/
|
|
7101
|
+
var promptConfirm = (rl, prompt, defaultValue = false) => {
|
|
7102
|
+
return new Promise((resolve) => {
|
|
7103
|
+
const defaultStr = defaultValue ? "Y/n" : "y/N";
|
|
7104
|
+
rl.question(`${prompt} [${defaultStr}]: `, (answer) => {
|
|
7105
|
+
const normalized = answer.trim().toLowerCase();
|
|
7106
|
+
if (normalized === "") resolve(defaultValue);
|
|
7107
|
+
else resolve(normalized === "y" || normalized === "yes");
|
|
7108
|
+
});
|
|
7109
|
+
});
|
|
7110
|
+
};
|
|
7080
7111
|
//#endregion
|
|
7081
7112
|
//#region src/authInit.ts
|
|
7082
7113
|
/**
|
|
@@ -7242,6 +7273,811 @@ var runTotpReset = async (config, logger, username) => {
|
|
|
7242
7273
|
}
|
|
7243
7274
|
};
|
|
7244
7275
|
//#endregion
|
|
7276
|
+
//#region src/services/importHttpClient.ts
|
|
7277
|
+
/**
|
|
7278
|
+
* Validates a source URL without permitting credentials in URLs or non-HTTP protocols.
|
|
7279
|
+
* @param value - Source URL
|
|
7280
|
+
* @returns Parsed URL
|
|
7281
|
+
* @remarks Rejects invalid URLs, embedded credentials and fragments without echoing input.
|
|
7282
|
+
*/
|
|
7283
|
+
var parseImportUrl = (value) => {
|
|
7284
|
+
let url;
|
|
7285
|
+
try {
|
|
7286
|
+
url = new URL(value);
|
|
7287
|
+
} catch {
|
|
7288
|
+
throw new Error("Invalid source URL");
|
|
7289
|
+
}
|
|
7290
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash) throw new Error("Source URLs must use HTTP(S), without credentials or fragments");
|
|
7291
|
+
return url;
|
|
7292
|
+
};
|
|
7293
|
+
/**
|
|
7294
|
+
* Creates a source reader that scopes credentials and rechecks every redirect.
|
|
7295
|
+
* @param auth - Source credentials
|
|
7296
|
+
* @param credentialUrls - Explicit URL prefixes authorized to receive credentials
|
|
7297
|
+
* @returns Source HTTP client
|
|
7298
|
+
* @remarks Redirects may leave these prefixes, but never carry credentials with them.
|
|
7299
|
+
*/
|
|
7300
|
+
var createImportHttpClient = (auth, credentialUrls) => {
|
|
7301
|
+
const prefixes = credentialUrls.map((value) => {
|
|
7302
|
+
const url = parseImportUrl(value);
|
|
7303
|
+
url.pathname = `${url.pathname.replace(/\/+$/, "")}/`;
|
|
7304
|
+
return url;
|
|
7305
|
+
});
|
|
7306
|
+
const authorization = auth.type === "basic" ? `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString("base64")}` : auth.type === "bearer" ? `Bearer ${auth.token}` : void 0;
|
|
7307
|
+
const request = async (value, json) => {
|
|
7308
|
+
let url = parseImportUrl(value);
|
|
7309
|
+
const signal = AbortSignal.timeout(12e4);
|
|
7310
|
+
for (let redirects = 0; redirects <= 10; redirects++) {
|
|
7311
|
+
const headers = { Accept: json ? "application/json" : "application/octet-stream" };
|
|
7312
|
+
if (authorization && prefixes.some((prefix) => prefix.origin === url.origin && url.pathname.startsWith(prefix.pathname))) headers.Authorization = authorization;
|
|
7313
|
+
let response;
|
|
7314
|
+
try {
|
|
7315
|
+
response = await fetch(url, {
|
|
7316
|
+
headers,
|
|
7317
|
+
signal,
|
|
7318
|
+
redirect: "manual"
|
|
7319
|
+
});
|
|
7320
|
+
} catch {
|
|
7321
|
+
throw new Error("Source request failed or timed out");
|
|
7322
|
+
}
|
|
7323
|
+
if ([
|
|
7324
|
+
301,
|
|
7325
|
+
302,
|
|
7326
|
+
303,
|
|
7327
|
+
307,
|
|
7328
|
+
308
|
|
7329
|
+
].includes(response.status)) {
|
|
7330
|
+
await response.body?.cancel();
|
|
7331
|
+
const location = response.headers.get("location");
|
|
7332
|
+
if (!location) throw new Error("Source redirect has no location");
|
|
7333
|
+
const next = parseImportUrl(new URL(location, url).href);
|
|
7334
|
+
if (url.protocol === "https:" && next.protocol !== "https:") throw new Error("Source redirect downgrades HTTPS");
|
|
7335
|
+
url = next;
|
|
7336
|
+
continue;
|
|
7337
|
+
}
|
|
7338
|
+
if (!response.ok) {
|
|
7339
|
+
await response.body?.cancel();
|
|
7340
|
+
throw new Error(`Source returned HTTP ${response.status}`);
|
|
7341
|
+
}
|
|
7342
|
+
try {
|
|
7343
|
+
return Buffer.from(await response.arrayBuffer());
|
|
7344
|
+
} catch {
|
|
7345
|
+
throw new Error("Source response was interrupted");
|
|
7346
|
+
}
|
|
7347
|
+
}
|
|
7348
|
+
throw new Error("Too many source redirects");
|
|
7349
|
+
};
|
|
7350
|
+
return {
|
|
7351
|
+
json: async (url) => {
|
|
7352
|
+
const bytes = await request(url, true);
|
|
7353
|
+
try {
|
|
7354
|
+
return JSON.parse(bytes.toString("utf8"));
|
|
7355
|
+
} catch {
|
|
7356
|
+
throw new Error("Source returned invalid JSON");
|
|
7357
|
+
}
|
|
7358
|
+
},
|
|
7359
|
+
buffer: async (url) => await request(url, false)
|
|
7360
|
+
};
|
|
7361
|
+
};
|
|
7362
|
+
//#endregion
|
|
7363
|
+
//#region src/services/importService.ts
|
|
7364
|
+
var semver = __resolveDefaultExport(__screwUpDefaultImportModule0$1, false);
|
|
7365
|
+
globalThis.__screwUpIsInCJS_45978af1291e = false;
|
|
7366
|
+
function __resolveDefaultExport(module, isESM) {
|
|
7367
|
+
const __isInCJS = typeof globalThis !== "undefined" && globalThis.__screwUpIsInCJS_45978af1291e === true;
|
|
7368
|
+
const maybe = module;
|
|
7369
|
+
const hasDefault = !!(maybe && typeof maybe === "object" && "default" in maybe);
|
|
7370
|
+
const unwrapNamespaceDefault = (value) => {
|
|
7371
|
+
if (!value || typeof value !== "object") return value;
|
|
7372
|
+
const inner = value;
|
|
7373
|
+
if ((inner.__esModule === true || typeof Symbol !== "undefined" && inner[Symbol.toStringTag] === "Module") && "default" in inner) return inner.default;
|
|
7374
|
+
return value;
|
|
7375
|
+
};
|
|
7376
|
+
const resolvedDefault = hasDefault ? unwrapNamespaceDefault(maybe.default) : void 0;
|
|
7377
|
+
if (__isInCJS) return hasDefault ? resolvedDefault ?? module : module;
|
|
7378
|
+
if (isESM) {
|
|
7379
|
+
if (hasDefault) return resolvedDefault;
|
|
7380
|
+
throw new Error("Default export not found.");
|
|
7381
|
+
}
|
|
7382
|
+
return hasDefault ? resolvedDefault ?? module : module;
|
|
7383
|
+
}
|
|
7384
|
+
var object = (value) => {
|
|
7385
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a metadata object");
|
|
7386
|
+
return value;
|
|
7387
|
+
};
|
|
7388
|
+
/**
|
|
7389
|
+
* Parses a UTF-8 list containing one package name per line.
|
|
7390
|
+
* @param content - List contents; empty lines are ignored
|
|
7391
|
+
* @returns Unique validated names in input order
|
|
7392
|
+
*/
|
|
7393
|
+
var parsePackageNames = (content) => {
|
|
7394
|
+
const names = [...new Set(content.split(/\r?\n/).map((name) => name.trim()).filter(Boolean))];
|
|
7395
|
+
if (names.some((name) => !isValidPackageName(name))) throw new Error("Package list contains an invalid name");
|
|
7396
|
+
return names;
|
|
7397
|
+
};
|
|
7398
|
+
var matchesChecksums = (bytes, dist) => {
|
|
7399
|
+
if (dist.shasum !== void 0 && (typeof dist.shasum !== "string" || !/^[a-f0-9]{40}$/i.test(dist.shasum) || createHash("sha1").update(bytes).digest("hex") !== dist.shasum.toLowerCase())) return false;
|
|
7400
|
+
if (dist.integrity !== void 0) {
|
|
7401
|
+
if (typeof dist.integrity !== "string") return false;
|
|
7402
|
+
const candidates = dist.integrity.trim().split(/\s+/).map((item) => /^(sha1|sha256|sha384|sha512)-([A-Za-z0-9+/]+={0,2})(?:\?.*)?$/.exec(item));
|
|
7403
|
+
const strongest = [
|
|
7404
|
+
"sha512",
|
|
7405
|
+
"sha384",
|
|
7406
|
+
"sha256",
|
|
7407
|
+
"sha1"
|
|
7408
|
+
].find((algorithm) => candidates.some((candidate) => candidate?.[1] === algorithm));
|
|
7409
|
+
if (!strongest || !candidates.some((candidate) => candidate?.[1] === strongest && candidate[2] === createHash(strongest).update(bytes).digest("base64"))) return false;
|
|
7410
|
+
}
|
|
7411
|
+
return true;
|
|
7412
|
+
};
|
|
7413
|
+
var metadataContents = (entry) => JSON.stringify({
|
|
7414
|
+
manifest: entry.metadata.manifest,
|
|
7415
|
+
readme: entry.metadata.readme,
|
|
7416
|
+
packageReadme: entry.metadata.packageReadme,
|
|
7417
|
+
published: entry.metadata.published ?? null,
|
|
7418
|
+
shasum: entry.metadata.shasum,
|
|
7419
|
+
integrity: entry.metadata.integrity,
|
|
7420
|
+
tarballName: entry.metadata.tarballName
|
|
7421
|
+
}, null, 2);
|
|
7422
|
+
var saveVersion = async (root, entry, bytes, exists) => {
|
|
7423
|
+
const packageRoot = path.join(root, ...entry.storage.packagePathSegments);
|
|
7424
|
+
const versionRoot = path.join(packageRoot, entry.metadata.version);
|
|
7425
|
+
if (exists) {
|
|
7426
|
+
await writePrivateFile(path.join(versionRoot, "metadata.json"), metadataContents(entry));
|
|
7427
|
+
return;
|
|
7428
|
+
}
|
|
7429
|
+
const staging = await fs.mkdtemp(path.join(packageRoot, ".import-"));
|
|
7430
|
+
try {
|
|
7431
|
+
await fs.writeFile(path.join(staging, entry.metadata.tarballName), bytes, { flag: "wx" });
|
|
7432
|
+
await fs.writeFile(path.join(staging, "package.json"), JSON.stringify(entry.metadata.manifest, null, 2));
|
|
7433
|
+
await writePrivateFile(path.join(staging, "metadata.json"), metadataContents(entry));
|
|
7434
|
+
await fs.rename(staging, versionRoot);
|
|
7435
|
+
} finally {
|
|
7436
|
+
await fs.rm(staging, {
|
|
7437
|
+
recursive: true,
|
|
7438
|
+
force: true
|
|
7439
|
+
});
|
|
7440
|
+
}
|
|
7441
|
+
};
|
|
7442
|
+
/**
|
|
7443
|
+
* Creates a hosted-registry importer, independent of the name enumeration mechanism.
|
|
7444
|
+
* @param options - Source, destination and execution settings
|
|
7445
|
+
* @returns Runnable offline importer
|
|
7446
|
+
* @remarks Run with the destination server stopped. Dependencies are never recursively imported.
|
|
7447
|
+
*/
|
|
7448
|
+
var createImportService = (options) => {
|
|
7449
|
+
const registry = parseImportUrl(options.registryUrl);
|
|
7450
|
+
registry.pathname = `${registry.pathname.replace(/\/+$/, "")}/`;
|
|
7451
|
+
if (registry.search) throw new Error("Registry URL must not contain a query");
|
|
7452
|
+
const client = createImportHttpClient(options.auth, [registry.href]);
|
|
7453
|
+
return { run: async () => {
|
|
7454
|
+
const result = {
|
|
7455
|
+
targets: [],
|
|
7456
|
+
imported: 0,
|
|
7457
|
+
skipped: 0,
|
|
7458
|
+
conflicts: 0,
|
|
7459
|
+
failed: 0,
|
|
7460
|
+
warnings: [],
|
|
7461
|
+
errors: []
|
|
7462
|
+
};
|
|
7463
|
+
const fail = (message, conflict) => {
|
|
7464
|
+
if (conflict) result.conflicts++;
|
|
7465
|
+
else result.failed++;
|
|
7466
|
+
result.errors.push(message);
|
|
7467
|
+
options.logger.error(message);
|
|
7468
|
+
};
|
|
7469
|
+
const warn = (message) => {
|
|
7470
|
+
result.warnings.push(message);
|
|
7471
|
+
options.logger.warn(message);
|
|
7472
|
+
};
|
|
7473
|
+
let names;
|
|
7474
|
+
try {
|
|
7475
|
+
const input = await options.enumerate();
|
|
7476
|
+
if (!Array.isArray(input) || input.some((name) => typeof name !== "string" || !isValidPackageName(name))) throw new Error("Invalid names");
|
|
7477
|
+
names = [...new Set(input)];
|
|
7478
|
+
} catch {
|
|
7479
|
+
fail("Package enumeration failed; the inventory is incomplete", false);
|
|
7480
|
+
return result;
|
|
7481
|
+
}
|
|
7482
|
+
const metadata = createMetadataService(options.packagesRoot, options.baseUrl, options.logger);
|
|
7483
|
+
if (!options.dryRun) await metadata.initialize();
|
|
7484
|
+
for (const name of names) {
|
|
7485
|
+
let packument;
|
|
7486
|
+
let versions;
|
|
7487
|
+
let tags;
|
|
7488
|
+
try {
|
|
7489
|
+
packument = object(await client.json(new URL(encodeURIComponent(name), registry).href));
|
|
7490
|
+
if (packument.name !== name) throw new Error("Mismatched package name");
|
|
7491
|
+
versions = object(packument.versions);
|
|
7492
|
+
if (Object.keys(versions).some((version) => !semver.valid(version) || version.includes("/") || version.includes("\\"))) throw new Error("Invalid version");
|
|
7493
|
+
tags = object(packument["dist-tags"]);
|
|
7494
|
+
if (Object.values(tags).some((version) => typeof version !== "string")) throw new Error("Invalid tags");
|
|
7495
|
+
} catch {
|
|
7496
|
+
fail(`${name}: metadata request or validation failed`, false);
|
|
7497
|
+
continue;
|
|
7498
|
+
}
|
|
7499
|
+
const versionNames = Object.keys(versions);
|
|
7500
|
+
result.targets.push({
|
|
7501
|
+
name,
|
|
7502
|
+
versions: versionNames
|
|
7503
|
+
});
|
|
7504
|
+
options.logger.info(`${name}: ${versionNames.join(", ") || "(no versions)"}`);
|
|
7505
|
+
if (options.dryRun) continue;
|
|
7506
|
+
const packageRoot = path.join(options.packagesRoot, ...packageNameToPathSegments(name));
|
|
7507
|
+
const tagsPath = path.join(packageRoot, "dist-tags.json");
|
|
7508
|
+
let existingTags;
|
|
7509
|
+
try {
|
|
7510
|
+
try {
|
|
7511
|
+
const stored = object(JSON.parse(await fs.readFile(tagsPath, "utf8")));
|
|
7512
|
+
existingTags = stored.format === "npmjs-server/dist-tags-v1" ? object(stored.tags) : stored;
|
|
7513
|
+
if (Object.values(existingTags).some((version) => typeof version !== "string")) throw new Error("Invalid destination tags");
|
|
7514
|
+
} catch (error) {
|
|
7515
|
+
if (error.code !== "ENOENT") throw error;
|
|
7516
|
+
existingTags = metadata.getDistTags(name);
|
|
7517
|
+
}
|
|
7518
|
+
await fs.mkdir(packageRoot, { recursive: true });
|
|
7519
|
+
await writePrivateFile(tagsPath, JSON.stringify({
|
|
7520
|
+
format: "npmjs-server/dist-tags-v1",
|
|
7521
|
+
tags: existingTags
|
|
7522
|
+
}, null, 2));
|
|
7523
|
+
} catch {
|
|
7524
|
+
fail(`${name}: could not prepare destination tags`, false);
|
|
7525
|
+
continue;
|
|
7526
|
+
}
|
|
7527
|
+
const available = /* @__PURE__ */ new Set();
|
|
7528
|
+
for (const version of versionNames) {
|
|
7529
|
+
const label = `${name}@${version}`;
|
|
7530
|
+
try {
|
|
7531
|
+
const document = object(versions[version]);
|
|
7532
|
+
if (document.name !== name || document.version !== version) throw new Error("Version metadata identity mismatch");
|
|
7533
|
+
const dist = object(document.dist);
|
|
7534
|
+
if (typeof dist.tarball !== "string") throw new Error("Missing tarball URL");
|
|
7535
|
+
const tarballUrl = parseImportUrl(new URL(dist.tarball, registry).href).href;
|
|
7536
|
+
const existing = metadata.getPackageEntry(name, version);
|
|
7537
|
+
let bytes;
|
|
7538
|
+
if (existing) {
|
|
7539
|
+
bytes = await fs.readFile(path.join(packageRoot, version, existing.metadata.tarballName));
|
|
7540
|
+
if (dist.shasum !== void 0 || dist.integrity !== void 0) {
|
|
7541
|
+
if (!matchesChecksums(bytes, dist)) {
|
|
7542
|
+
fail(`${label}: existing tarball conflicts with source`, true);
|
|
7543
|
+
continue;
|
|
7544
|
+
}
|
|
7545
|
+
} else if (!bytes.equals(await client.buffer(tarballUrl))) {
|
|
7546
|
+
fail(`${label}: existing tarball conflicts with source`, true);
|
|
7547
|
+
continue;
|
|
7548
|
+
}
|
|
7549
|
+
} else {
|
|
7550
|
+
bytes = await client.buffer(tarballUrl);
|
|
7551
|
+
if (!matchesChecksums(bytes, dist)) throw new Error("Tarball checksum mismatch");
|
|
7552
|
+
}
|
|
7553
|
+
const entry = await createPackageEntryFromTarball(bytes, options.baseUrl);
|
|
7554
|
+
if (entry.metadata.name !== name || entry.metadata.version !== version) throw new Error("Tarball identity mismatch");
|
|
7555
|
+
const readme = typeof document.readme === "string" ? document.readme : typeof packument.readme === "string" ? packument.readme : entry.metadata.readme;
|
|
7556
|
+
entry.metadata.readme = readme;
|
|
7557
|
+
entry.metadata.packageReadme = typeof packument.readme === "string" ? packument.readme : void 0;
|
|
7558
|
+
entry.metadata.manifest = {
|
|
7559
|
+
...entry.metadata.manifest,
|
|
7560
|
+
...document,
|
|
7561
|
+
readme,
|
|
7562
|
+
dist: {
|
|
7563
|
+
...dist,
|
|
7564
|
+
tarball: entry.metadata.tarballUrl,
|
|
7565
|
+
shasum: entry.metadata.shasum,
|
|
7566
|
+
integrity: entry.metadata.integrity
|
|
7567
|
+
}
|
|
7568
|
+
};
|
|
7569
|
+
const published = packument.time?.[version];
|
|
7570
|
+
entry.metadata.published = typeof published === "string" && !Number.isNaN(Date.parse(published)) ? published : void 0;
|
|
7571
|
+
if (!entry.metadata.published) warn(`${label}: source publication time unavailable`);
|
|
7572
|
+
if (readme === void 0) warn(`${label}: source README unavailable`);
|
|
7573
|
+
if (dist.shasum === void 0 && dist.integrity === void 0) warn(`${label}: source checksums unavailable; identity was validated`);
|
|
7574
|
+
await saveVersion(options.packagesRoot, entry, bytes, !!existing);
|
|
7575
|
+
available.add(version);
|
|
7576
|
+
if (existing) result.skipped++;
|
|
7577
|
+
else result.imported++;
|
|
7578
|
+
options.logger.info(`${label}: ${existing ? "archive unchanged; metadata reconciled" : "imported"}`);
|
|
7579
|
+
} catch {
|
|
7580
|
+
fail(`${label}: archive validation, download or storage failed`, false);
|
|
7581
|
+
}
|
|
7582
|
+
}
|
|
7583
|
+
const nextTags = { ...existingTags };
|
|
7584
|
+
for (const [tag, version] of Object.entries(tags)) {
|
|
7585
|
+
if (!available.has(version)) {
|
|
7586
|
+
fail(`${name}: tag ${tag} targets an unavailable version`, false);
|
|
7587
|
+
continue;
|
|
7588
|
+
}
|
|
7589
|
+
if (Object.prototype.hasOwnProperty.call(existingTags, tag) && existingTags[tag] !== version) {
|
|
7590
|
+
fail(`${name}: tag ${tag} conflicts with destination`, true);
|
|
7591
|
+
continue;
|
|
7592
|
+
}
|
|
7593
|
+
Object.defineProperty(nextTags, tag, {
|
|
7594
|
+
value: version,
|
|
7595
|
+
writable: true,
|
|
7596
|
+
enumerable: true,
|
|
7597
|
+
configurable: true
|
|
7598
|
+
});
|
|
7599
|
+
}
|
|
7600
|
+
try {
|
|
7601
|
+
await writePrivateFile(tagsPath, JSON.stringify({
|
|
7602
|
+
format: "npmjs-server/dist-tags-v1",
|
|
7603
|
+
tags: nextTags
|
|
7604
|
+
}, null, 2));
|
|
7605
|
+
} catch {
|
|
7606
|
+
fail(`${name}: tag storage failed`, false);
|
|
7607
|
+
}
|
|
7608
|
+
}
|
|
7609
|
+
return result;
|
|
7610
|
+
} };
|
|
7611
|
+
};
|
|
7612
|
+
//#endregion
|
|
7613
|
+
//#region src/services/nexusImportSource.ts
|
|
7614
|
+
var metadataObject = (value) => {
|
|
7615
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Nexus returned invalid component metadata");
|
|
7616
|
+
return value;
|
|
7617
|
+
};
|
|
7618
|
+
/**
|
|
7619
|
+
* Enumerates all npm package names in a specified Nexus hosted repository.
|
|
7620
|
+
* @param apiUrl - Explicit REST API base URL including /service/rest/v1/
|
|
7621
|
+
* @param repository - Name of the hosted repository to enumerate
|
|
7622
|
+
* @param auth - None or Basic credentials scoped to the supplied API URL
|
|
7623
|
+
* @returns Unique package names in the order encountered, with npm scopes restored
|
|
7624
|
+
* @remarks Rejects incomplete or inconsistent inventories rather than returning partial names.
|
|
7625
|
+
* The caller must select a hosted repository; repository types are not discovered here.
|
|
7626
|
+
* @see https://help.sonatype.com/en/components-api.html
|
|
7627
|
+
*/
|
|
7628
|
+
var enumerateNexusPackages = async (apiUrl, repository, auth) => {
|
|
7629
|
+
if (auth.type !== "none" && auth.type !== "basic") throw new Error("Nexus enumeration requires none or basic authentication");
|
|
7630
|
+
if (!/^[a-zA-Z0-9-][a-zA-Z0-9_.-]*$/.test(repository)) throw new Error("Invalid Nexus repository name");
|
|
7631
|
+
const base = parseImportUrl(apiUrl);
|
|
7632
|
+
if (base.search) throw new Error("Nexus API URL must not contain a query");
|
|
7633
|
+
base.pathname = `${base.pathname.replace(/\/+$/, "")}/`;
|
|
7634
|
+
const client = createImportHttpClient(auth, [base.href]);
|
|
7635
|
+
const names = /* @__PURE__ */ new Set();
|
|
7636
|
+
const tokens = /* @__PURE__ */ new Set();
|
|
7637
|
+
let continuationToken = null;
|
|
7638
|
+
do {
|
|
7639
|
+
const url = new URL("components", base);
|
|
7640
|
+
url.searchParams.set("repository", repository);
|
|
7641
|
+
if (continuationToken !== null) url.searchParams.set("continuationToken", continuationToken);
|
|
7642
|
+
const page = metadataObject(await client.json(url.href));
|
|
7643
|
+
if (!Array.isArray(page.items)) throw new Error("Nexus returned an invalid components page");
|
|
7644
|
+
for (const value of page.items) {
|
|
7645
|
+
const component = metadataObject(value);
|
|
7646
|
+
if (component.repository !== repository || component.format !== "npm") throw new Error("Nexus returned a component outside the requested npm repository");
|
|
7647
|
+
const { group, name } = component;
|
|
7648
|
+
if (typeof name !== "string" || group !== void 0 && group !== null && typeof group !== "string") throw new Error("Nexus returned an invalid npm package identity");
|
|
7649
|
+
const packageName = group ? `@${group}/${name}` : name;
|
|
7650
|
+
if (!isValidPackageName(packageName)) throw new Error("Nexus returned an invalid npm package name");
|
|
7651
|
+
names.add(packageName);
|
|
7652
|
+
}
|
|
7653
|
+
const token = page.continuationToken;
|
|
7654
|
+
if (token !== null) {
|
|
7655
|
+
if (typeof token !== "string" || token.length === 0) throw new Error("Nexus returned an invalid continuation token");
|
|
7656
|
+
if (tokens.has(token)) throw new Error("Nexus returned a repeated continuation token");
|
|
7657
|
+
tokens.add(token);
|
|
7658
|
+
}
|
|
7659
|
+
continuationToken = token;
|
|
7660
|
+
} while (continuationToken !== null);
|
|
7661
|
+
return [...names];
|
|
7662
|
+
};
|
|
7663
|
+
//#endregion
|
|
7664
|
+
//#region src/utils/importNpmrc.ts
|
|
7665
|
+
var import_ini = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
7666
|
+
var { hasOwnProperty } = Object.prototype;
|
|
7667
|
+
var encode = (obj, opt = {}) => {
|
|
7668
|
+
if (typeof opt === "string") opt = { section: opt };
|
|
7669
|
+
opt.align = opt.align === true;
|
|
7670
|
+
opt.newline = opt.newline === true;
|
|
7671
|
+
opt.sort = opt.sort === true;
|
|
7672
|
+
opt.whitespace = opt.whitespace === true || opt.align === true;
|
|
7673
|
+
/* istanbul ignore next */
|
|
7674
|
+
opt.platform = opt.platform || typeof process !== "undefined" && process.platform;
|
|
7675
|
+
opt.bracketedArray = opt.bracketedArray !== false;
|
|
7676
|
+
/* istanbul ignore next */
|
|
7677
|
+
const eol = opt.platform === "win32" ? "\r\n" : "\n";
|
|
7678
|
+
const separator = opt.whitespace ? " = " : "=";
|
|
7679
|
+
const children = [];
|
|
7680
|
+
const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj);
|
|
7681
|
+
let padToChars = 0;
|
|
7682
|
+
if (opt.align) padToChars = safe(keys.filter((k) => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== "object").map((k) => Array.isArray(obj[k]) ? `${k}[]` : k).concat([""]).reduce((a, b) => safe(a).length >= safe(b).length ? a : b)).length;
|
|
7683
|
+
let out = "";
|
|
7684
|
+
const arraySuffix = opt.bracketedArray ? "[]" : "";
|
|
7685
|
+
for (const k of keys) {
|
|
7686
|
+
const val = obj[k];
|
|
7687
|
+
if (val && Array.isArray(val)) for (const item of val) out += safe(`${k}${arraySuffix}`).padEnd(padToChars, " ") + separator + safe(item) + eol;
|
|
7688
|
+
else if (val && typeof val === "object") children.push(k);
|
|
7689
|
+
else out += safe(k).padEnd(padToChars, " ") + separator + safe(val) + eol;
|
|
7690
|
+
}
|
|
7691
|
+
if (opt.section && out.length) out = "[" + safe(opt.section) + "]" + (opt.newline ? eol + eol : eol) + out;
|
|
7692
|
+
for (const k of children) {
|
|
7693
|
+
const nk = splitSections(k, ".").join("\\.");
|
|
7694
|
+
const section = (opt.section ? opt.section + "." : "") + nk;
|
|
7695
|
+
const child = encode(obj[k], {
|
|
7696
|
+
...opt,
|
|
7697
|
+
section
|
|
7698
|
+
});
|
|
7699
|
+
if (out.length && child.length) out += eol;
|
|
7700
|
+
out += child;
|
|
7701
|
+
}
|
|
7702
|
+
return out;
|
|
7703
|
+
};
|
|
7704
|
+
function splitSections(str, separator) {
|
|
7705
|
+
var lastMatchIndex = 0;
|
|
7706
|
+
var lastSeparatorIndex = 0;
|
|
7707
|
+
var nextIndex = 0;
|
|
7708
|
+
var sections = [];
|
|
7709
|
+
do {
|
|
7710
|
+
nextIndex = str.indexOf(separator, lastMatchIndex);
|
|
7711
|
+
if (nextIndex !== -1) {
|
|
7712
|
+
lastMatchIndex = nextIndex + separator.length;
|
|
7713
|
+
if (nextIndex > 0 && str[nextIndex - 1] === "\\") continue;
|
|
7714
|
+
sections.push(str.slice(lastSeparatorIndex, nextIndex));
|
|
7715
|
+
lastSeparatorIndex = nextIndex + separator.length;
|
|
7716
|
+
}
|
|
7717
|
+
} while (nextIndex !== -1);
|
|
7718
|
+
sections.push(str.slice(lastSeparatorIndex));
|
|
7719
|
+
return sections;
|
|
7720
|
+
}
|
|
7721
|
+
var decode = (str, opt = {}) => {
|
|
7722
|
+
opt.bracketedArray = opt.bracketedArray !== false;
|
|
7723
|
+
const out = Object.create(null);
|
|
7724
|
+
let p = out;
|
|
7725
|
+
let section = null;
|
|
7726
|
+
const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i;
|
|
7727
|
+
const lines = str.split(/[\r\n]+/g);
|
|
7728
|
+
const duplicates = {};
|
|
7729
|
+
for (const line of lines) {
|
|
7730
|
+
if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) continue;
|
|
7731
|
+
const match = line.match(re);
|
|
7732
|
+
if (!match) continue;
|
|
7733
|
+
if (match[1] !== void 0) {
|
|
7734
|
+
section = unsafe(match[1]);
|
|
7735
|
+
if (section === "__proto__") {
|
|
7736
|
+
p = Object.create(null);
|
|
7737
|
+
continue;
|
|
7738
|
+
}
|
|
7739
|
+
p = out[section] = out[section] || Object.create(null);
|
|
7740
|
+
continue;
|
|
7741
|
+
}
|
|
7742
|
+
const keyRaw = unsafe(match[2]);
|
|
7743
|
+
let isArray;
|
|
7744
|
+
if (opt.bracketedArray) isArray = keyRaw.length > 2 && keyRaw.slice(-2) === "[]";
|
|
7745
|
+
else {
|
|
7746
|
+
duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1;
|
|
7747
|
+
isArray = duplicates[keyRaw] > 1;
|
|
7748
|
+
}
|
|
7749
|
+
const key = isArray && keyRaw.endsWith("[]") ? keyRaw.slice(0, -2) : keyRaw;
|
|
7750
|
+
if (key === "__proto__") continue;
|
|
7751
|
+
const valueRaw = match[3] ? unsafe(match[4]) : true;
|
|
7752
|
+
const value = valueRaw === "true" || valueRaw === "false" || valueRaw === "null" ? JSON.parse(valueRaw) : valueRaw;
|
|
7753
|
+
if (isArray) {
|
|
7754
|
+
if (!hasOwnProperty.call(p, key)) p[key] = [];
|
|
7755
|
+
else if (!Array.isArray(p[key])) p[key] = [p[key]];
|
|
7756
|
+
}
|
|
7757
|
+
if (Array.isArray(p[key])) p[key].push(value);
|
|
7758
|
+
else p[key] = value;
|
|
7759
|
+
}
|
|
7760
|
+
const remove = [];
|
|
7761
|
+
for (const k of Object.keys(out)) {
|
|
7762
|
+
if (!hasOwnProperty.call(out, k) || typeof out[k] !== "object" || Array.isArray(out[k])) continue;
|
|
7763
|
+
const parts = splitSections(k, ".");
|
|
7764
|
+
p = out;
|
|
7765
|
+
const l = parts.pop();
|
|
7766
|
+
const nl = l.replace(/\\\./g, ".");
|
|
7767
|
+
for (const part of parts) {
|
|
7768
|
+
if (part === "__proto__") continue;
|
|
7769
|
+
if (!hasOwnProperty.call(p, part) || typeof p[part] !== "object") p[part] = Object.create(null);
|
|
7770
|
+
p = p[part];
|
|
7771
|
+
}
|
|
7772
|
+
if (p === out && nl === l) continue;
|
|
7773
|
+
p[nl] = out[k];
|
|
7774
|
+
remove.push(k);
|
|
7775
|
+
}
|
|
7776
|
+
for (const del of remove) delete out[del];
|
|
7777
|
+
return out;
|
|
7778
|
+
};
|
|
7779
|
+
var isQuoted = (val) => {
|
|
7780
|
+
return val.startsWith("\"") && val.endsWith("\"") || val.startsWith("'") && val.endsWith("'");
|
|
7781
|
+
};
|
|
7782
|
+
var safe = (val) => {
|
|
7783
|
+
if (typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim()) return JSON.stringify(val);
|
|
7784
|
+
return val.split(";").join("\\;").split("#").join("\\#");
|
|
7785
|
+
};
|
|
7786
|
+
var unsafe = (val) => {
|
|
7787
|
+
val = (val || "").trim();
|
|
7788
|
+
if (isQuoted(val)) {
|
|
7789
|
+
if (val.charAt(0) === "'") val = val.slice(1, -1);
|
|
7790
|
+
try {
|
|
7791
|
+
val = JSON.parse(val);
|
|
7792
|
+
} catch {}
|
|
7793
|
+
} else {
|
|
7794
|
+
let esc = false;
|
|
7795
|
+
let unesc = "";
|
|
7796
|
+
for (let i = 0, l = val.length; i < l; i++) {
|
|
7797
|
+
const c = val.charAt(i);
|
|
7798
|
+
if (esc) {
|
|
7799
|
+
if ("\\;#".indexOf(c) !== -1) unesc += c;
|
|
7800
|
+
else unesc += "\\" + c;
|
|
7801
|
+
esc = false;
|
|
7802
|
+
} else if (";#".indexOf(c) !== -1) break;
|
|
7803
|
+
else if (c === "\\") esc = true;
|
|
7804
|
+
else unesc += c;
|
|
7805
|
+
}
|
|
7806
|
+
if (esc) unesc += "\\";
|
|
7807
|
+
return unesc.trim();
|
|
7808
|
+
}
|
|
7809
|
+
return val;
|
|
7810
|
+
};
|
|
7811
|
+
module.exports = {
|
|
7812
|
+
parse: decode,
|
|
7813
|
+
decode,
|
|
7814
|
+
stringify: encode,
|
|
7815
|
+
encode,
|
|
7816
|
+
safe,
|
|
7817
|
+
unsafe
|
|
7818
|
+
};
|
|
7819
|
+
})))();
|
|
7820
|
+
var directoryPath = (url) => `${url.pathname.replace(/\/+$/, "")}/`;
|
|
7821
|
+
var expandValue = (value, environment) => {
|
|
7822
|
+
if (typeof value !== "string") return void 0;
|
|
7823
|
+
let missing = false;
|
|
7824
|
+
const expanded = value.replace(/(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/g, (original, escapes, name, optional) => {
|
|
7825
|
+
if (escapes.length % 2) return original.slice((escapes.length + 1) / 2);
|
|
7826
|
+
const replacement = Object.prototype.hasOwnProperty.call(environment, name) ? environment[name] : void 0;
|
|
7827
|
+
if (replacement === void 0 && !optional) missing = true;
|
|
7828
|
+
return escapes.slice(escapes.length / 2) + (replacement ?? "");
|
|
7829
|
+
});
|
|
7830
|
+
return missing || !expanded.trim() || /[\x00-\x1f\x7f]/.test(expanded) ? void 0 : expanded;
|
|
7831
|
+
};
|
|
7832
|
+
var decodeCredential = (value) => {
|
|
7833
|
+
if (!value || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return void 0;
|
|
7834
|
+
const bytes = Buffer.from(value, "base64");
|
|
7835
|
+
const decoded = bytes.toString("utf8");
|
|
7836
|
+
if (bytes.toString("base64").replace(/=+$/, "") !== value.replace(/=+$/, "") || value.includes("=") && value !== bytes.toString("base64") || !Buffer.from(decoded, "utf8").equals(bytes) || /[\x00-\x1f\x7f]/.test(decoded)) return void 0;
|
|
7837
|
+
return decoded;
|
|
7838
|
+
};
|
|
7839
|
+
/**
|
|
7840
|
+
* Parses the supported registry and authentication settings in one user npmrc.
|
|
7841
|
+
* @param content - UTF-8 npmrc content
|
|
7842
|
+
* @param method - Selected package enumeration mode
|
|
7843
|
+
* @param environment - Environment used to expand npmrc variable references
|
|
7844
|
+
* @returns Candidates, safe diagnostics and a URL-scoped credential resolver
|
|
7845
|
+
* @remarks Does not contact servers, merge other npm configuration, or verify permissions.
|
|
7846
|
+
* Invalid credentials block fallback to broader scopes. Nexus never selects Bearer.
|
|
7847
|
+
* @see https://docs.npmjs.com/cli/v11/configuring-npm/npmrc/
|
|
7848
|
+
*/
|
|
7849
|
+
var parseImportNpmrc = (content, method, environment) => {
|
|
7850
|
+
const values = (0, import_ini.parse)(content);
|
|
7851
|
+
const registries = /* @__PURE__ */ new Set();
|
|
7852
|
+
const warnings = /* @__PURE__ */ new Set();
|
|
7853
|
+
const groups = /* @__PURE__ */ new Map();
|
|
7854
|
+
for (const [key, value] of Object.entries(values)) {
|
|
7855
|
+
if (key === "registry" || /^@[^:/\s]+:registry$/.test(key)) {
|
|
7856
|
+
try {
|
|
7857
|
+
const expanded = expandValue(value, environment);
|
|
7858
|
+
if (!expanded) throw new Error();
|
|
7859
|
+
const url = parseImportUrl(expanded);
|
|
7860
|
+
if (url.search) throw new Error();
|
|
7861
|
+
url.pathname = directoryPath(url);
|
|
7862
|
+
registries.add(url.href);
|
|
7863
|
+
} catch {
|
|
7864
|
+
warnings.add("Ignored an invalid npmrc registry URL.");
|
|
7865
|
+
}
|
|
7866
|
+
continue;
|
|
7867
|
+
}
|
|
7868
|
+
const match = /^(\/\/.*):(_authToken|_auth|username|_password)$/.exec(key);
|
|
7869
|
+
if (!match) {
|
|
7870
|
+
if ([
|
|
7871
|
+
"_authToken",
|
|
7872
|
+
"_auth",
|
|
7873
|
+
"username",
|
|
7874
|
+
"_password"
|
|
7875
|
+
].includes(key)) warnings.add("Ignored unscoped npmrc authentication.");
|
|
7876
|
+
continue;
|
|
7877
|
+
}
|
|
7878
|
+
const scope = match[1];
|
|
7879
|
+
try {
|
|
7880
|
+
if (parseImportUrl(`https:${scope}`).search || /[\s\x00-\x1f\x7f\\]/.test(scope)) throw new Error();
|
|
7881
|
+
const group = groups.get(scope) ?? {};
|
|
7882
|
+
group[match[2]] = value;
|
|
7883
|
+
groups.set(scope, group);
|
|
7884
|
+
} catch {
|
|
7885
|
+
warnings.add("Ignored an invalid npmrc authentication scope.");
|
|
7886
|
+
}
|
|
7887
|
+
}
|
|
7888
|
+
const entries = [...groups].map(([scope, group]) => {
|
|
7889
|
+
const get = (key) => expandValue(group[key], environment);
|
|
7890
|
+
let auth;
|
|
7891
|
+
if ("_authToken" in group && method === "nexus") warnings.add("Bearer authentication from npmrc is unavailable for Nexus; select none or basic manually if no Basic credentials apply.");
|
|
7892
|
+
if ("_authToken" in group && method === "list") {
|
|
7893
|
+
const token = get("_authToken");
|
|
7894
|
+
if (token && /^[\x21-\x7e]+$/.test(token)) auth = {
|
|
7895
|
+
type: "bearer",
|
|
7896
|
+
token
|
|
7897
|
+
};
|
|
7898
|
+
} else {
|
|
7899
|
+
let username;
|
|
7900
|
+
let password;
|
|
7901
|
+
if ("username" in group || "_password" in group) {
|
|
7902
|
+
username = get("username");
|
|
7903
|
+
password = decodeCredential(get("_password"));
|
|
7904
|
+
} else {
|
|
7905
|
+
const decoded = decodeCredential(get("_auth"));
|
|
7906
|
+
const separator = decoded?.indexOf(":") ?? -1;
|
|
7907
|
+
if (decoded && separator > 0) {
|
|
7908
|
+
username = decoded.slice(0, separator);
|
|
7909
|
+
password = decoded.slice(separator + 1);
|
|
7910
|
+
}
|
|
7911
|
+
}
|
|
7912
|
+
if (username && !username.includes(":") && password) auth = {
|
|
7913
|
+
type: "basic",
|
|
7914
|
+
username,
|
|
7915
|
+
password
|
|
7916
|
+
};
|
|
7917
|
+
}
|
|
7918
|
+
if (!auth && !(method === "nexus" && Object.keys(group).length === 1 && "_authToken" in group)) warnings.add("Ignored invalid or incomplete npmrc authentication.");
|
|
7919
|
+
return {
|
|
7920
|
+
scope,
|
|
7921
|
+
auth
|
|
7922
|
+
};
|
|
7923
|
+
});
|
|
7924
|
+
return {
|
|
7925
|
+
registries: [...registries],
|
|
7926
|
+
credentials: entries.flatMap(({ scope, auth }) => auth ? [{
|
|
7927
|
+
scope,
|
|
7928
|
+
type: auth.type
|
|
7929
|
+
}] : []),
|
|
7930
|
+
warnings: [...warnings],
|
|
7931
|
+
authenticationFor: (value) => {
|
|
7932
|
+
const target = parseImportUrl(value);
|
|
7933
|
+
const matching = entries.map((entry) => ({
|
|
7934
|
+
...entry,
|
|
7935
|
+
url: parseImportUrl(`${target.protocol}${entry.scope}`)
|
|
7936
|
+
})).filter(({ url }) => url.host === target.host && directoryPath(target).startsWith(directoryPath(url)));
|
|
7937
|
+
matching.sort((a, b) => directoryPath(b.url).length - directoryPath(a.url).length);
|
|
7938
|
+
return matching[0]?.auth;
|
|
7939
|
+
}
|
|
7940
|
+
};
|
|
7941
|
+
};
|
|
7942
|
+
//#endregion
|
|
7943
|
+
//#region src/importPackages.ts
|
|
7944
|
+
var readImportInput = async (read, rl) => {
|
|
7945
|
+
const error = /* @__PURE__ */ new Error("Import input was interrupted before completion");
|
|
7946
|
+
if (process.stdin.readableEnded || process.stdin.destroyed) throw error;
|
|
7947
|
+
let interrupt;
|
|
7948
|
+
const interrupted = new Promise((_resolve, reject) => {
|
|
7949
|
+
interrupt = () => reject(error);
|
|
7950
|
+
});
|
|
7951
|
+
process.stdin.once("end", interrupt);
|
|
7952
|
+
process.stdin.once("close", interrupt);
|
|
7953
|
+
process.stdin.once("error", interrupt);
|
|
7954
|
+
rl?.once("close", interrupt);
|
|
7955
|
+
rl?.once("error", interrupt);
|
|
7956
|
+
rl?.once("SIGINT", interrupt);
|
|
7957
|
+
try {
|
|
7958
|
+
return await Promise.race([read(), interrupted]);
|
|
7959
|
+
} finally {
|
|
7960
|
+
process.stdin.removeListener("end", interrupt);
|
|
7961
|
+
process.stdin.removeListener("close", interrupt);
|
|
7962
|
+
process.stdin.removeListener("error", interrupt);
|
|
7963
|
+
rl?.removeListener("close", interrupt);
|
|
7964
|
+
rl?.removeListener("error", interrupt);
|
|
7965
|
+
rl?.removeListener("SIGINT", interrupt);
|
|
7966
|
+
}
|
|
7967
|
+
};
|
|
7968
|
+
/**
|
|
7969
|
+
* Runs the interactive offline package importer without starting an HTTP server.
|
|
7970
|
+
* @param config - Resolved server configuration, including the normal package directory
|
|
7971
|
+
* @param logger - Progress output
|
|
7972
|
+
* @param dryRun - Enumerate only, without modifying the destination
|
|
7973
|
+
* @returns Exit status: zero for completion or cancellation, one for incomplete imports
|
|
7974
|
+
*/
|
|
7975
|
+
var runImportPackages = async (config, logger, dryRun) => {
|
|
7976
|
+
let rl = readline.createInterface({
|
|
7977
|
+
input: process.stdin,
|
|
7978
|
+
output: process.stdout
|
|
7979
|
+
});
|
|
7980
|
+
const input = async (prompt, defaultValue) => await readImportInput(() => promptInput(rl, prompt, defaultValue), rl);
|
|
7981
|
+
const confirm = async (prompt) => await readImportInput(() => promptConfirm(rl, prompt, false), rl);
|
|
7982
|
+
const readAuthentication = async (allowBearer, api) => {
|
|
7983
|
+
const authentication = await input(`${api ? "Nexus API authentication" : "Authentication"} (${allowBearer ? "none/basic/bearer" : "none/basic"})`, "none");
|
|
7984
|
+
if (!allowBearer && authentication === "bearer") {
|
|
7985
|
+
logger.error("Nexus enumeration requires none or basic authentication.");
|
|
7986
|
+
throw new Error("Unsupported Nexus authentication");
|
|
7987
|
+
}
|
|
7988
|
+
if (authentication === "none") return { type: "none" };
|
|
7989
|
+
if (authentication !== "basic" && authentication !== "bearer") throw new Error("Unknown authentication method");
|
|
7990
|
+
const label = api ? "Nexus API" : "Source";
|
|
7991
|
+
const username = authentication === "basic" ? await input(`${label} username`, void 0) : "";
|
|
7992
|
+
if (authentication === "basic" && (!username || username.includes(":"))) throw new Error("A valid source username is required");
|
|
7993
|
+
rl.close();
|
|
7994
|
+
const secret = await readImportInput(() => promptPassword(`${label} ${authentication === "basic" ? "password" : "token"}`), void 0);
|
|
7995
|
+
if (!secret) throw new Error("Source credentials are required");
|
|
7996
|
+
rl = readline.createInterface({
|
|
7997
|
+
input: process.stdin,
|
|
7998
|
+
output: process.stdout
|
|
7999
|
+
});
|
|
8000
|
+
return authentication === "basic" ? {
|
|
8001
|
+
type: "basic",
|
|
8002
|
+
username,
|
|
8003
|
+
password: secret
|
|
8004
|
+
} : {
|
|
8005
|
+
type: "bearer",
|
|
8006
|
+
token: secret
|
|
8007
|
+
};
|
|
8008
|
+
};
|
|
8009
|
+
try {
|
|
8010
|
+
logger.info("Import requires a hosted-only source URL. Stop the destination server before importing.");
|
|
8011
|
+
const method = await input("Enumeration method (list/nexus)", "list");
|
|
8012
|
+
if (method !== "list" && method !== "nexus") throw new Error("Unknown enumeration method");
|
|
8013
|
+
let npmrc;
|
|
8014
|
+
try {
|
|
8015
|
+
npmrc = parseImportNpmrc(await fs.readFile(path.join(os.homedir(), ".npmrc"), "utf8"), method, process.env);
|
|
8016
|
+
} catch (error) {
|
|
8017
|
+
if (error.code !== "ENOENT") logger.warn("Could not read or parse ~/.npmrc. Enter import settings manually.");
|
|
8018
|
+
}
|
|
8019
|
+
if (npmrc) {
|
|
8020
|
+
for (const warning of npmrc.warnings) logger.warn(warning);
|
|
8021
|
+
if (npmrc.registries.length || npmrc.credentials.length) {
|
|
8022
|
+
logger.info("Available ~/.npmrc settings (verify that the selected registry is hosted-only):");
|
|
8023
|
+
npmrc.registries.forEach((url, index) => logger.info(` Registry ${index + 1}: ${url}`));
|
|
8024
|
+
for (const { scope, type } of npmrc.credentials) logger.info(` Authentication: ${type} for ${scope}`);
|
|
8025
|
+
if (!await confirm("Use settings from ~/.npmrc?")) npmrc = void 0;
|
|
8026
|
+
} else {
|
|
8027
|
+
logger.info("No usable import settings in ~/.npmrc. Enter import settings manually.");
|
|
8028
|
+
npmrc = void 0;
|
|
8029
|
+
}
|
|
8030
|
+
}
|
|
8031
|
+
let registryUrl;
|
|
8032
|
+
if (npmrc?.registries.length === 1) registryUrl = npmrc.registries[0];
|
|
8033
|
+
else if (npmrc && npmrc.registries.length > 1) {
|
|
8034
|
+
const selection = await input("Registry number", void 0);
|
|
8035
|
+
const selected = npmrc.registries[Number(selection) - 1];
|
|
8036
|
+
if (!/^\d+$/.test(selection) || !selected) throw new Error("Invalid registry selection");
|
|
8037
|
+
registryUrl = selected;
|
|
8038
|
+
} else registryUrl = await input("Hosted registry URL", void 0);
|
|
8039
|
+
parseImportUrl(registryUrl);
|
|
8040
|
+
let apiUrl;
|
|
8041
|
+
let enumerate;
|
|
8042
|
+
if (method === "list") {
|
|
8043
|
+
const listFile = await input("Package name list file", void 0);
|
|
8044
|
+
if (!listFile) throw new Error("Package name list file is required");
|
|
8045
|
+
enumerate = async () => parsePackageNames(await fs.readFile(listFile, "utf8"));
|
|
8046
|
+
} else {
|
|
8047
|
+
const nexusApiUrl = await input("Nexus REST API base URL (ending in /service/rest/v1/)", void 0);
|
|
8048
|
+
parseImportUrl(nexusApiUrl);
|
|
8049
|
+
apiUrl = nexusApiUrl;
|
|
8050
|
+
const repository = await input("Nexus repository name", void 0);
|
|
8051
|
+
if (!repository) throw new Error("Nexus repository name is required");
|
|
8052
|
+
enumerate = async (auth) => await enumerateNexusPackages(nexusApiUrl, repository, auth);
|
|
8053
|
+
}
|
|
8054
|
+
const configuredAuth = npmrc?.authenticationFor(registryUrl);
|
|
8055
|
+
const auth = configuredAuth ?? await readAuthentication(method === "list", false);
|
|
8056
|
+
const apiAuth = apiUrl ? npmrc?.authenticationFor(apiUrl) ?? (configuredAuth ? await readAuthentication(false, true) : auth) : auth;
|
|
8057
|
+
const packagesRoot = await input("Destination package directory", config.packageDir || "./packages");
|
|
8058
|
+
const confirmed = await confirm(dryRun ? "Run dry-run?" : "Start import?");
|
|
8059
|
+
rl.close();
|
|
8060
|
+
if (!confirmed) {
|
|
8061
|
+
logger.info("Import cancelled.");
|
|
8062
|
+
return 0;
|
|
8063
|
+
}
|
|
8064
|
+
const result = await createImportService({
|
|
8065
|
+
registryUrl,
|
|
8066
|
+
packagesRoot,
|
|
8067
|
+
baseUrl: config.baseUrl || "",
|
|
8068
|
+
auth,
|
|
8069
|
+
enumerate: async () => await enumerate(apiAuth),
|
|
8070
|
+
dryRun,
|
|
8071
|
+
logger
|
|
8072
|
+
}).run();
|
|
8073
|
+
const versions = result.targets.reduce((count, target) => count + target.versions.length, 0);
|
|
8074
|
+
logger.info(`${dryRun ? "Dry-run" : "Import"} result: Packages: ${result.targets.length}; Versions: ${versions}; Imported: ${result.imported}; Skipped: ${result.skipped}; Conflicts: ${result.conflicts}; Failed: ${result.failed}; Warnings: ${result.warnings.length}`);
|
|
8075
|
+
return result.failed || result.conflicts ? 1 : 0;
|
|
8076
|
+
} finally {
|
|
8077
|
+
rl.close();
|
|
8078
|
+
}
|
|
8079
|
+
};
|
|
8080
|
+
//#endregion
|
|
7245
8081
|
//#region src/utils/configLoader.ts
|
|
7246
8082
|
/**
|
|
7247
8083
|
* Validates and sanitizes a config file object
|
|
@@ -7438,14 +8274,14 @@ program.name(name).summary(description).addHelpText("beforeAll", `${description}
|
|
|
7438
8274
|
"none",
|
|
7439
8275
|
"publish",
|
|
7440
8276
|
"full"
|
|
7441
|
-
])).addOption(new Option("--max-upload-size-mb <size>", "maximum package upload size in MB (1-10000)")).addOption(new Option("--proxy", "enable upstream package proxy")).addOption(new Option("--proxy-upstream-registry <url>", "upstream npm registry URL for proxy mode")).addOption(new Option("--proxy-package-dir <dir>", "package cache directory for proxy mode")).addOption(new Option("--auth-init", "initialize authentication with interactive admin user creation")).addOption(new Option("--totp-reset <username>", "reset a user's two-factor authentication (stop the server first)").conflicts("authInit")).action(async (options) => {
|
|
8277
|
+
])).addOption(new Option("--max-upload-size-mb <size>", "maximum package upload size in MB (1-10000)")).addOption(new Option("--proxy", "enable upstream package proxy")).addOption(new Option("--proxy-upstream-registry <url>", "upstream npm registry URL for proxy mode")).addOption(new Option("--proxy-package-dir <dir>", "package cache directory for proxy mode")).addOption(new Option("--auth-init", "initialize authentication with interactive admin user creation")).addOption(new Option("--totp-reset <username>", "reset a user's two-factor authentication (stop the server first)").conflicts("authInit")).addOption(new Option("--import-packages", "import from a hosted npm registry (stop the server first)").conflicts(["authInit", "totpReset"])).addOption(new Option("--dry-run", "list import targets without changing the destination").implies({ importPackages: true })).action(async (options) => {
|
|
7442
8278
|
const configFilePath = options.configFile || getConfigFileFromEnv() || "./config.json";
|
|
7443
8279
|
const configFile = await loadConfigFromPath(configFilePath, createConsoleLogger(name, "warn"));
|
|
7444
8280
|
const configDir = dirname(configFilePath);
|
|
7445
8281
|
const port = options.port !== void 0 ? parseInt(options.port, 10) : getPortFromEnv() || configFile.port || 4873;
|
|
7446
8282
|
const baseUrl = options.baseUrl || getBaseUrlFromEnv() || configFile.baseUrl;
|
|
7447
8283
|
const packageDir = options.packageDir || getPackageDirFromEnv() || configFile.packageDir || "./packages";
|
|
7448
|
-
const realm = options.realm || getRealmFromEnv() || configFile.realm || `npmjs-server 0.
|
|
8284
|
+
const realm = options.realm || getRealmFromEnv() || configFile.realm || `npmjs-server 0.3.0`;
|
|
7449
8285
|
const logLevel = options.logLevel || getLogLevelFromEnv() || configFile.logLevel || "info";
|
|
7450
8286
|
const trustedProxies = options.trustedProxies ? options.trustedProxies.split(",").map((ip) => ip.trim()) : getTrustedProxiesFromEnv() || configFile.trustedProxies;
|
|
7451
8287
|
const authMode = options.authMode || getAuthModeFromEnv() || configFile.authMode || "none";
|
|
@@ -7535,6 +8371,15 @@ program.name(name).summary(description).addHelpText("beforeAll", `${description}
|
|
|
7535
8371
|
packageDir: proxyPackageDir
|
|
7536
8372
|
}
|
|
7537
8373
|
};
|
|
8374
|
+
if (options.importPackages) {
|
|
8375
|
+
try {
|
|
8376
|
+
process.exitCode = await runImportPackages(config, logger, Boolean(options.dryRun));
|
|
8377
|
+
} catch {
|
|
8378
|
+
logger.error("Package import failed. Check the source URL, credentials and destination.");
|
|
8379
|
+
process.exitCode = 1;
|
|
8380
|
+
}
|
|
8381
|
+
return;
|
|
8382
|
+
}
|
|
7538
8383
|
if (options.totpReset) {
|
|
7539
8384
|
try {
|
|
7540
8385
|
await runTotpReset(config, logger, options.totpReset);
|