react-native-update-cli 2.29.0 → 2.29.2

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 (85) hide show
  1. package/lib/account.js +2 -4
  2. package/lib/api.d.ts +1 -1
  3. package/lib/api.js +35 -73
  4. package/lib/app.js +13 -27
  5. package/lib/auto-update.d.ts +1 -1
  6. package/lib/auto-update.js +6 -16
  7. package/lib/bin.js +4 -6
  8. package/lib/bundle-pack.js +26 -60
  9. package/lib/bundle-runner.js +89 -119
  10. package/lib/bundle.js +18 -26
  11. package/lib/diff.js +43 -133
  12. package/lib/locales/en.d.ts +0 -10
  13. package/lib/locales/en.js +0 -10
  14. package/lib/locales/zh.d.ts +0 -10
  15. package/lib/locales/zh.js +0 -10
  16. package/lib/native-package.js +27 -99
  17. package/lib/package.d.ts +6 -1
  18. package/lib/package.js +56 -108
  19. package/lib/provider.js +3 -5
  20. package/lib/symbolicate.js +1 -16
  21. package/lib/utils/add-gitignore.js +0 -1
  22. package/lib/utils/app-info-parser/aab.d.ts +5 -22
  23. package/lib/utils/app-info-parser/aab.js +89 -226
  24. package/lib/utils/app-info-parser/apk.d.ts +12 -13
  25. package/lib/utils/app-info-parser/apk.js +28 -78
  26. package/lib/utils/app-info-parser/ipa.d.ts +2 -14
  27. package/lib/utils/app-info-parser/ipa.js +9 -70
  28. package/lib/utils/app-info-parser/resource-finder.d.ts +1 -34
  29. package/lib/utils/app-info-parser/resource-finder.js +95 -234
  30. package/lib/utils/app-info-parser/xml-parser/binary.d.ts +6 -55
  31. package/lib/utils/app-info-parser/xml-parser/binary.js +152 -556
  32. package/lib/utils/app-info-parser/zip.d.ts +6 -24
  33. package/lib/utils/app-info-parser/zip.js +19 -86
  34. package/lib/utils/check-plugin.d.ts +7 -5
  35. package/lib/utils/check-plugin.js +15 -25
  36. package/lib/utils/dep-versions.d.ts +0 -6
  37. package/lib/utils/dep-versions.js +2 -27
  38. package/lib/utils/failure-fingerprint.js +3 -4
  39. package/lib/utils/fs-helpers.d.ts +18 -0
  40. package/lib/utils/fs-helpers.js +84 -0
  41. package/lib/utils/git.d.ts +0 -1
  42. package/lib/utils/git.js +0 -8
  43. package/lib/utils/hash.d.ts +3 -0
  44. package/lib/utils/hash.js +19 -0
  45. package/lib/utils/hbcTransform.d.ts +9 -2
  46. package/lib/utils/hbcTransform.js +41 -70
  47. package/lib/utils/hermes-base.d.ts +1 -5
  48. package/lib/utils/hermes-base.js +136 -196
  49. package/lib/utils/hermes-literals.d.ts +5 -3
  50. package/lib/utils/hermes-literals.js +30 -53
  51. package/lib/utils/hermes-raw.d.ts +7 -0
  52. package/lib/utils/hermes-raw.js +26 -9
  53. package/lib/utils/http-helper.d.ts +0 -1
  54. package/lib/utils/http-helper.js +0 -20
  55. package/lib/utils/i18n.js +0 -2
  56. package/lib/utils/index.d.ts +5 -19
  57. package/lib/utils/index.js +95 -189
  58. package/lib/utils/latest-version.d.ts +19 -0
  59. package/lib/utils/latest-version.js +137 -0
  60. package/lib/utils/options.d.ts +2 -1
  61. package/lib/utils/options.js +5 -7
  62. package/lib/utils/runtime.d.ts +1 -1
  63. package/lib/utils/runtime.js +2 -10
  64. package/lib/utils/upload-request.d.ts +33 -0
  65. package/lib/utils/upload-request.js +120 -0
  66. package/lib/utils/zip-entries.d.ts +23 -0
  67. package/lib/utils/zip-entries.js +130 -139
  68. package/lib/utils/zip-options.js +29 -56
  69. package/lib/utils/zip-range.js +29 -69
  70. package/lib/utils/zip-raw-writer.js +6 -5
  71. package/lib/versions.d.ts +5 -0
  72. package/lib/versions.js +86 -153
  73. package/package.json +1 -9
  74. package/lib/utils/app-info-parser/app.d.ts +0 -4
  75. package/lib/utils/app-info-parser/app.js +0 -10
  76. package/lib/utils/app-info-parser/index.d.ts +0 -16
  77. package/lib/utils/app-info-parser/index.js +0 -46
  78. package/lib/utils/app-info-parser/utils.d.ts +0 -31
  79. package/lib/utils/app-info-parser/utils.js +0 -135
  80. package/lib/utils/app-info-parser/xml-parser/manifest.d.ts +0 -10
  81. package/lib/utils/app-info-parser/xml-parser/manifest.js +0 -202
  82. package/lib/utils/latest-version/index.d.ts +0 -149
  83. package/lib/utils/latest-version/index.js +0 -326
  84. package/lib/utils/plugin-config.d.ts +0 -9
  85. package/lib/utils/plugin-config.js +0 -61
@@ -15,21 +15,25 @@ exports.getAabInfo = getAabInfo;
15
15
  exports.printVersionCommand = printVersionCommand;
16
16
  const chalk_1 = __importDefault(require("chalk"));
17
17
  const compare_versions_1 = require("compare-versions");
18
- const crypto_1 = require("crypto");
19
18
  const path_1 = __importDefault(require("path"));
20
19
  const read_1 = require("read");
21
- const yauzl_1 = require("yauzl");
22
20
  const package_json_1 = __importDefault(require("../../package.json"));
23
21
  const check_plugin_1 = require("./check-plugin");
24
22
  Object.defineProperty(exports, "checkPlugins", { enumerable: true, get: function () { return check_plugin_1.checkPlugins; } });
25
23
  const constants_1 = require("./constants");
26
24
  const dep_versions_1 = require("./dep-versions");
25
+ const hash_1 = require("./hash");
27
26
  const i18n_1 = require("./i18n");
27
+ const options_1 = require("./options");
28
+ const zip_entries_1 = require("./zip-entries");
28
29
  // app-info-parser (and its zip/plist/protobuf stack) is only needed by the
29
30
  // package commands; load it on first use instead of on every CLI start.
30
- function createAppInfoParser(fn) {
31
- const { default: AppInfoParser } = require('./app-info-parser');
32
- return new AppInfoParser(fn);
31
+ function loadAppInfoParser() {
32
+ return {
33
+ ...require('./app-info-parser/apk'),
34
+ ...require('./app-info-parser/ipa'),
35
+ ...require('./app-info-parser/zip'),
36
+ };
33
37
  }
34
38
  /**
35
39
  * tty-table (~25 ms to load) only when a table is rendered. Bun's require of
@@ -41,10 +45,8 @@ function loadTtyTable() {
41
45
  }
42
46
  /** True when prompts cannot or must not be shown. */
43
47
  function isNonInteractive(env = process.env, stdinIsTTY = process.stdin.isTTY, globalFlag = global.NO_INTERACTIVE) {
44
- const envValue = env.NO_INTERACTIVE?.toLowerCase();
45
48
  return (globalFlag === true ||
46
- envValue === 'true' ||
47
- envValue === '1' ||
49
+ (0, options_1.isTruthyEnv)(env.NO_INTERACTIVE) ||
48
50
  stdinIsTTY !== true);
49
51
  }
50
52
  async function question(query, password) {
@@ -57,180 +59,124 @@ async function question(query, password) {
57
59
  replace: password ? '*' : undefined,
58
60
  });
59
61
  }
60
- function translateOptions(options, map) {
61
- if (!map) {
62
- // Existing logic for template replacement if no map is provided
63
- const ret = {};
64
- for (const key in options) {
65
- const value = options[key];
66
- if (typeof value === 'string') {
67
- ret[key] = value.replace(/\$\{(\w+)\}/g, (placeholder, name) => {
68
- const replacement = options[name] ?? process.env[name];
69
- if (typeof replacement === 'string' ||
70
- typeof replacement === 'number' ||
71
- typeof replacement === 'boolean') {
72
- return String(replacement);
73
- }
74
- return placeholder;
75
- });
76
- }
77
- else {
78
- ret[key] = value;
79
- }
62
+ /** Expand `${name}` placeholders in string options from other options or the environment. */
63
+ function translateOptions(options) {
64
+ const ret = {};
65
+ for (const key in options) {
66
+ const value = options[key];
67
+ if (typeof value === 'string') {
68
+ ret[key] = value.replace(/\$\{(\w+)\}/g, (placeholder, name) => {
69
+ const replacement = options[name] ?? process.env[name];
70
+ if (typeof replacement === 'string' ||
71
+ typeof replacement === 'number' ||
72
+ typeof replacement === 'boolean') {
73
+ return String(replacement);
74
+ }
75
+ return placeholder;
76
+ });
80
77
  }
81
- return ret;
82
- }
83
- const result = { ...options };
84
- for (const [key, value] of Object.entries(map)) {
85
- if (result[key] !== undefined) {
86
- result[value] = result[key];
87
- delete result[key];
78
+ else {
79
+ ret[key] = value;
88
80
  }
89
81
  }
90
- return result;
82
+ return ret;
91
83
  }
92
84
  // bundleHash: sha256 of the raw bundle bytes extracted from the package. Must
93
85
  // stay byte-identical with what the client hashes at runtime (its embedded
94
86
  // bundle, which is also the pdiff source) — the server compares the two to
95
87
  // decide pdiff applicability. Raw bytes, no normalization of any kind.
96
- // getEntries is typed Buffer | Blob (app-info-parser's browser/node duality);
97
- // under Node it is always a Buffer, but handle both.
98
- async function sha256(data) {
99
- const buffer = Buffer.isBuffer(data)
100
- ? data
101
- : Buffer.from(await data.arrayBuffer());
102
- return (0, crypto_1.createHash)('sha256').update(buffer).digest('hex');
103
- }
104
- // Anchored exact paths: unanchored/unescaped patterns also matched entries
105
- // like index.android.bundle.map or .backup, and a later match would silently
106
- // overwrite the real bundle, registering a wrong bundleHash.
107
- exports.ApkBundleFileName = /^assets\/index\.android\.bundle$/;
108
- const ApkUpdateJsonName = /^res\/raw\/update\.json$/;
109
- async function getApkInfo(fn) {
110
- const appInfoParser = createAppInfoParser(fn);
111
- // read both entries in a single scan over the archive
112
- const entries = await appInfoParser.parser.getEntries([
113
- exports.ApkBundleFileName,
114
- ApkUpdateJsonName,
115
- ]);
116
- const bundleFile = entries[String(exports.ApkBundleFileName)];
88
+ function requireBundle(bundleFile, packageType, entryFile) {
117
89
  if (!bundleFile) {
118
- throw new Error((0, i18n_1.t)('bundleNotFound', {
119
- packageType: 'apk',
120
- entryFile: 'index.android.bundle',
121
- }));
122
- }
123
- const updateJsonFile = entries[String(ApkUpdateJsonName)];
124
- let appCredential = {};
125
- if (updateJsonFile) {
126
- appCredential = JSON.parse(updateJsonFile.toString()).android;
127
- }
128
- const { versionName, application } = await appInfoParser.parse();
129
- let buildTime = 0;
130
- if (Array.isArray(application.metaData)) {
131
- for (const meta of application.metaData) {
132
- if (meta.name === 'pushy_build_time') {
133
- if (Array.isArray(meta.value)) {
134
- const firstValue = meta.value[0];
135
- buildTime = Number(firstValue);
136
- }
137
- else if (meta.value !== undefined) {
138
- buildTime = Number(meta.value);
139
- }
140
- }
141
- }
90
+ throw new Error((0, i18n_1.t)('bundleNotFound', { packageType, entryFile }));
142
91
  }
92
+ return bundleFile;
93
+ }
94
+ function requireBuildTime(value) {
95
+ const buildTime = Number(value);
143
96
  if (!Number.isFinite(buildTime) || buildTime === 0) {
144
97
  throw new Error((0, i18n_1.t)('buildTimeNotFound'));
145
98
  }
99
+ return buildTime;
100
+ }
101
+ /** The common shape of getApkInfo / getAppInfo / getIpaInfo. */
102
+ function nativePackageInfo(versionName, buildTime, bundleFile, updateJson, platform) {
103
+ const appCredential = updateJson
104
+ ? JSON.parse(updateJson.toString())[platform]
105
+ : {};
146
106
  return {
147
107
  versionName,
148
108
  buildTime,
149
- bundleHash: await sha256(bundleFile),
109
+ bundleHash: (0, hash_1.sha256Hex)(bundleFile),
150
110
  bundleFile,
151
111
  ...appCredential,
152
112
  };
153
113
  }
114
+ // Anchored exact paths: unanchored/unescaped patterns also matched entries
115
+ // like index.android.bundle.map or .backup, and a later match would silently
116
+ // overwrite the real bundle, registering a wrong bundleHash.
117
+ exports.ApkBundleFileName = /^assets\/index\.android\.bundle$/;
118
+ const ApkUpdateJsonName = /^res\/raw\/update\.json$/;
119
+ const ApkManifestName = /^androidmanifest\.xml$/;
120
+ const ApkResourcesName = /^resources\.arsc$/;
121
+ async function getApkInfo(fn) {
122
+ const { parseApkManifest, readZipEntries } = loadAppInfoParser();
123
+ // read every entry in a single scan over the archive
124
+ const [bundleFile, updateJson, manifest, resources] = await readZipEntries(fn, [exports.ApkBundleFileName, ApkUpdateJsonName, ApkManifestName, ApkResourcesName]);
125
+ const bundle = requireBundle(bundleFile, 'apk', 'index.android.bundle');
126
+ if (!manifest) {
127
+ throw new Error("AndroidManifest.xml can't be found.");
128
+ }
129
+ const { versionName, metaData } = parseApkManifest(manifest, resources);
130
+ let buildTime;
131
+ for (const meta of metaData) {
132
+ if (meta.name === 'pushy_build_time') {
133
+ buildTime = Array.isArray(meta.value) ? meta.value[0] : meta.value;
134
+ }
135
+ }
136
+ return nativePackageInfo(versionName, requireBuildTime(buildTime), bundle, updateJson, 'android');
137
+ }
154
138
  async function getAppInfo(fn) {
155
- const appInfoParser = createAppInfoParser(fn);
139
+ const { readZipEntries } = loadAppInfoParser();
156
140
  // single scan (and single nested .hap extraction) for all three entries
157
- const [bundleFile, updateJsonFile, metaJsonFile] = await appInfoParser.parser.getEntriesFromHarmonyApp([
141
+ const [bundleFile, updateJson, metaJson] = await readZipEntries(fn, [
158
142
  /^resources\/rawfile\/bundle\.harmony\.js$/,
159
143
  /^resources\/rawfile\/update\.json$/,
160
144
  /^resources\/rawfile\/meta\.json$/,
161
145
  ]);
162
- if (!bundleFile) {
163
- throw new Error((0, i18n_1.t)('bundleNotFound', {
164
- packageType: 'app',
165
- entryFile: 'bundle.harmony.js',
166
- }));
167
- }
168
- let appCredential = {};
169
- if (updateJsonFile) {
170
- appCredential = JSON.parse(updateJsonFile.toString()).harmony;
171
- }
172
- let metaData = {};
173
- if (metaJsonFile) {
174
- metaData = JSON.parse(metaJsonFile.toString());
175
- }
176
- const { versionName, pushy_build_time } = metaData;
177
- let buildTime = 0;
178
- if (pushy_build_time) {
179
- buildTime = Number(pushy_build_time);
180
- }
181
- if (!Number.isFinite(buildTime) || buildTime === 0) {
182
- throw new Error((0, i18n_1.t)('buildTimeNotFound'));
183
- }
184
- return {
185
- versionName,
186
- buildTime,
187
- bundleHash: await sha256(bundleFile),
188
- bundleFile,
189
- ...appCredential,
190
- };
146
+ const bundle = requireBundle(bundleFile, 'app', 'bundle.harmony.js');
147
+ const { versionName, pushy_build_time } = metaJson
148
+ ? JSON.parse(metaJson.toString())
149
+ : {};
150
+ return nativePackageInfo(versionName, requireBuildTime(pushy_build_time), bundle, updateJson, 'harmony');
191
151
  }
192
152
  // lowercase because the zip reader also matches against the lowercased entry
193
153
  // name (real IPAs use "Payload/")
194
154
  exports.IpaBundleFileName = /^payload\/[^/]+\.app\/main\.jsbundle$/;
195
155
  const IpaUpdateJsonName = /^payload\/[^/]+\.app\/assets\/update\.json$/;
156
+ const IpaPlistName = /payload\/[^/]+?.app\/info.plist$/i;
196
157
  const IpaBuildTimeName = /^payload\/[^/]+\.app\/pushy_build_time\.txt$/;
197
158
  // Not in root bundle when use `use_frameworks`
198
159
  const IpaBuildTimeFrameworkName = /^payload\/[^/]+\.app\/frameworks\/react_native_update\.framework\/pushy_build_time\.txt$/;
199
160
  async function getIpaInfo(fn) {
200
- const appInfoParser = createAppInfoParser(fn);
201
- // read all four entries in a single scan over the archive
202
- const entries = await appInfoParser.parser.getEntries([
161
+ const { parsePlist, readZipEntries } = loadAppInfoParser();
162
+ // read every entry in a single scan over the archive
163
+ const [bundleFile, updateJson, plist, buildTimeTxt, frameworkBuildTimeTxt] = await readZipEntries(fn, [
203
164
  exports.IpaBundleFileName,
204
165
  IpaUpdateJsonName,
166
+ IpaPlistName,
205
167
  IpaBuildTimeName,
206
168
  IpaBuildTimeFrameworkName,
207
169
  ]);
208
- const bundleFile = entries[String(exports.IpaBundleFileName)];
209
- if (!bundleFile) {
210
- throw new Error((0, i18n_1.t)('bundleNotFound', {
211
- packageType: 'ipa',
212
- entryFile: 'main.jsbundle',
213
- }));
214
- }
215
- const updateJsonFile = entries[String(IpaUpdateJsonName)];
216
- let appCredential = {};
217
- if (updateJsonFile) {
218
- appCredential = JSON.parse(updateJsonFile.toString()).ios;
170
+ const bundle = requireBundle(bundleFile, 'ipa', 'main.jsbundle');
171
+ if (!plist) {
172
+ throw new Error("Info.plist can't be found.");
219
173
  }
220
- const { CFBundleShortVersionString: versionName } = await appInfoParser.parse();
221
- const buildTimeTxtBuffer = entries[String(IpaBuildTimeName)] ??
222
- entries[String(IpaBuildTimeFrameworkName)];
174
+ const { CFBundleShortVersionString: versionName } = await parsePlist(plist);
175
+ const buildTimeTxtBuffer = buildTimeTxt ?? frameworkBuildTimeTxt;
223
176
  if (!buildTimeTxtBuffer) {
224
177
  throw new Error((0, i18n_1.t)('buildTimeNotFound'));
225
178
  }
226
- const buildTime = buildTimeTxtBuffer.toString().trim();
227
- return {
228
- versionName,
229
- buildTime,
230
- bundleHash: await sha256(bundleFile),
231
- bundleFile,
232
- ...appCredential,
233
- };
179
+ return nativePackageInfo(versionName, buildTimeTxtBuffer.toString().trim(), bundle, updateJson, 'ios');
234
180
  }
235
181
  async function getAabInfo(fn) {
236
182
  const protobuf = require('protobufjs');
@@ -305,7 +251,7 @@ async function getAabInfo(fn) {
305
251
  // through extractApk → getApkInfo which enforces the bundle's presence.
306
252
  let bundleHash;
307
253
  try {
308
- bundleHash = await sha256(await readZipEntry(fn, 'base/assets/index.android.bundle'));
254
+ bundleHash = (0, hash_1.sha256Hex)(await readZipEntry(fn, 'base/assets/index.android.bundle'));
309
255
  }
310
256
  catch {
311
257
  // no embedded bundle (e.g. debug AAB); omit the field
@@ -318,46 +264,10 @@ async function getAabInfo(fn) {
318
264
  };
319
265
  }
320
266
  async function readZipEntry(fn, entryName) {
321
- return new Promise((resolve, reject) => {
322
- (0, yauzl_1.open)(fn, { lazyEntries: true }, (err, zipfile) => {
323
- if (err || !zipfile) {
324
- reject(err ?? new Error('Failed to open zip file'));
325
- return;
326
- }
327
- let found = false;
328
- zipfile.readEntry();
329
- zipfile.on('entry', (entry) => {
330
- if (entry.fileName === entryName) {
331
- found = true;
332
- zipfile.openReadStream(entry, (streamError, readStream) => {
333
- if (streamError || !readStream) {
334
- zipfile.close();
335
- reject(streamError ?? new Error('Failed to read zip entry'));
336
- return;
337
- }
338
- const chunks = [];
339
- readStream.on('data', (chunk) => chunks.push(chunk));
340
- readStream.on('end', () => {
341
- zipfile.close();
342
- resolve(Buffer.concat(chunks));
343
- });
344
- readStream.on('error', (error) => {
345
- zipfile.close();
346
- reject(error);
347
- });
348
- });
349
- }
350
- else {
351
- zipfile.readEntry();
352
- }
353
- });
354
- zipfile.on('end', () => {
355
- if (!found)
356
- reject(new Error(`${entryName} not found in AAB`));
357
- });
358
- zipfile.on('error', reject);
359
- });
360
- });
267
+ const data = await (0, zip_entries_1.readFirstEntry)(fn, (name) => name === entryName);
268
+ if (!data)
269
+ throw new Error(`${entryName} not found in AAB`);
270
+ return data;
361
271
  }
362
272
  async function resolveResource(fn, resourceId, root) {
363
273
  const pkgId = (resourceId >> 24) & 0xff;
@@ -414,18 +324,14 @@ const VERSION_CHECK_PACKAGES = [
414
324
  * waits (refreshing the cache on the way).
415
325
  */
416
326
  async function getLatestVersions(background) {
417
- // the registry client pulls in global-dirs/registry-auth-token/semver: only
418
- // pay for them when actually checking
419
- const { default: latestVersion } = require('./latest-version');
420
- return latestVersion(VERSION_CHECK_PACKAGES, {
327
+ // the registry client pulls in registry-auth-token: only pay for it when
328
+ // actually checking
329
+ const { getLatestVersions: fetchLatestVersions } = require('./latest-version');
330
+ return fetchLatestVersions(VERSION_CHECK_PACKAGES, {
421
331
  useCache: true,
422
332
  ...(background ? { unref: true } : { cacheMaxAge: 0 }),
423
- requestOptions: {
424
- timeout: 2000,
425
- },
426
- })
427
- .then((pkgs) => pkgs.map((pkg) => pkg.latest))
428
- .catch(() => VERSION_CHECK_PACKAGES.map(() => undefined));
333
+ timeout: 2000,
334
+ });
429
335
  }
430
336
  function isNewer(latest, current) {
431
337
  if (!latest || !current) {
@@ -0,0 +1,19 @@
1
+ export interface LatestVersionOptions {
2
+ /**
3
+ * Answer from a cache younger than `cacheMaxAge` (same registry) without
4
+ * any request; otherwise query the registry and refresh the cache, falling
5
+ * back to a stale cache when the query fails.
6
+ */
7
+ useCache?: boolean;
8
+ /** default one day; 0 always refreshes (a stale cache stays the fallback) */
9
+ cacheMaxAge?: number;
10
+ /**
11
+ * Do not let the registry request keep the process alive: its socket is
12
+ * unref'd, so the process may exit before the promise settles.
13
+ */
14
+ unref?: boolean;
15
+ /** request timeout in milliseconds */
16
+ timeout?: number;
17
+ }
18
+ /** The `latest` dist-tag of each package, `undefined` where unknown. */
19
+ export declare function getLatestVersions(pkgNames: string[], options?: LatestVersionOptions): Promise<Array<string | undefined>>;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getLatestVersions = getLatestVersions;
7
+ // Latest dist-tag lookup on the npm registry, with a per-package metadata
8
+ // cache. Trimmed from @badisi/latest-version to what the version check needs;
9
+ // the cache location and file format are unchanged.
10
+ const fs_1 = require("fs");
11
+ const path_1 = require("path");
12
+ const registry_auth_token_1 = __importDefault(require("registry-auth-token"));
13
+ const registry_url_1 = __importDefault(require("registry-auth-token/registry-url"));
14
+ const fs_helpers_1 = require("./fs-helpers");
15
+ const runtime_1 = require("./runtime");
16
+ const ONE_DAY = 1000 * 60 * 60 * 24;
17
+ const cacheFile = (pkgName) => (0, path_1.join)((0, fs_helpers_1.userCacheDir)('@badisi/latest-version'), `${pkgName}.json`);
18
+ const resolveRegistryUrl = (pkgName) => {
19
+ const i = pkgName.indexOf('/');
20
+ return (0, registry_url_1.default)(i !== -1 ? pkgName.slice(0, i) : '');
21
+ };
22
+ function downloadMetadata(pkgName, options) {
23
+ return new Promise((resolve, reject) => {
24
+ const registryUrl = resolveRegistryUrl(pkgName);
25
+ const pkgUrl = new URL(encodeURIComponent(pkgName).replace(/^%40/, '@'), registryUrl);
26
+ const headers = {
27
+ accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*',
28
+ };
29
+ const authInfo = (0, registry_auth_token_1.default)(pkgUrl.toString(), { recursive: true });
30
+ if (authInfo) {
31
+ headers.authorization = `${authInfo.type} ${authInfo.token}`;
32
+ }
33
+ const requestOptions = {
34
+ headers,
35
+ host: pkgUrl.hostname,
36
+ path: pkgUrl.pathname,
37
+ port: pkgUrl.port,
38
+ timeout: options.timeout,
39
+ // HTTP(S)_PROXY / NO_PROXY, like every other request of the CLI
40
+ agent: (0, runtime_1.proxyAgentFor)(pkgUrl.toString()),
41
+ };
42
+ const { get } = require(pkgUrl.protocol === 'https:' ? 'https' : 'http');
43
+ const request = get(requestOptions, (res) => {
44
+ if (res.statusCode !== 200) {
45
+ res.resume(); // consume response data to free up memory
46
+ reject(new Error(`Request error (${res.statusCode}): ${pkgUrl}`));
47
+ return;
48
+ }
49
+ let rawData = '';
50
+ res.setEncoding('utf8');
51
+ res.on('data', (chunk) => {
52
+ rawData += chunk;
53
+ });
54
+ res.once('error', reject);
55
+ res.once('end', () => {
56
+ try {
57
+ resolve({
58
+ name: pkgName,
59
+ lastUpdateDate: Date.now(),
60
+ distTags: JSON.parse(rawData)['dist-tags'],
61
+ registryUrl,
62
+ });
63
+ }
64
+ catch (err) {
65
+ reject(err);
66
+ }
67
+ });
68
+ });
69
+ request.once('timeout', () => {
70
+ request.destroy(new Error(`Request timed out: ${pkgUrl}`));
71
+ });
72
+ request.once('error', reject);
73
+ if (options.unref) {
74
+ // A background check must never delay the process exit: drop the
75
+ // socket's ref (also for a pooled keep-alive socket, which the agent
76
+ // ref's again right before handing it out).
77
+ request.once('socket', (socket) => {
78
+ socket.unref?.();
79
+ });
80
+ }
81
+ });
82
+ }
83
+ function saveMetadataToCache(pkg) {
84
+ try {
85
+ const filePath = cacheFile(pkg.name);
86
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(filePath), { recursive: true });
87
+ (0, fs_1.writeFileSync)(filePath, JSON.stringify(pkg));
88
+ }
89
+ catch {
90
+ // a read-only or missing cache dir must not turn into an error
91
+ }
92
+ }
93
+ /**
94
+ * The cached metadata of a package (from the same registry), and whether it is
95
+ * still younger than `cacheMaxAge`. A stale entry is returned as well so it can
96
+ * serve as a fallback when the registry is unreachable.
97
+ */
98
+ function getMetadataFromCache(pkgName, maxAge) {
99
+ try {
100
+ const metadata = JSON.parse((0, fs_1.readFileSync)(cacheFile(pkgName)).toString());
101
+ if (!metadata ||
102
+ typeof metadata.lastUpdateDate !== 'number' ||
103
+ !metadata.distTags ||
104
+ metadata.registryUrl !== resolveRegistryUrl(pkgName)) {
105
+ return undefined;
106
+ }
107
+ const age = Date.now() - metadata.lastUpdateDate;
108
+ return { metadata, fresh: maxAge !== 0 && age >= 0 && age < maxAge };
109
+ }
110
+ catch {
111
+ return undefined; // missing / unreadable / corrupt cache: no cache
112
+ }
113
+ }
114
+ async function getLatestVersion(pkgName, options) {
115
+ if (!options.useCache) {
116
+ return (await downloadMetadata(pkgName, options)).distTags.latest;
117
+ }
118
+ const cached = getMetadataFromCache(pkgName, options.cacheMaxAge ?? ONE_DAY);
119
+ if (cached?.fresh) {
120
+ return cached.metadata.distTags.latest;
121
+ }
122
+ try {
123
+ const metadata = await downloadMetadata(pkgName, options);
124
+ saveMetadataToCache(metadata);
125
+ return metadata.distTags.latest;
126
+ }
127
+ catch (err) {
128
+ if (!cached) {
129
+ throw err;
130
+ }
131
+ return cached.metadata.distTags.latest; // stale beats nothing
132
+ }
133
+ }
134
+ /** The `latest` dist-tag of each package, `undefined` where unknown. */
135
+ function getLatestVersions(pkgNames, options = {}) {
136
+ return Promise.all(pkgNames.map((name) => getLatestVersion(name, options).catch(() => undefined)));
137
+ }
@@ -1,5 +1,6 @@
1
+ /** `1` or `true` (any case), the usual spelling of an enabled env flag */
2
+ export declare function isTruthyEnv(value: string | undefined): boolean;
1
3
  export declare function getBooleanOption(options: Record<string, unknown>, key: string, fallback?: boolean): boolean;
2
4
  export declare function getStringOption(options: Record<string, unknown>, key: string, fallback?: string): string;
3
5
  export declare function getOptionalStringOption(options: Record<string, unknown>, key: string): string | undefined;
4
6
  export declare function getStringListOption(options: Record<string, unknown>, key: string): string[] | undefined;
5
- export declare function toObjectState<T extends Record<string, unknown>>(value: unknown, fallback: T): T;
@@ -1,10 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTruthyEnv = isTruthyEnv;
3
4
  exports.getBooleanOption = getBooleanOption;
4
5
  exports.getStringOption = getStringOption;
5
6
  exports.getOptionalStringOption = getOptionalStringOption;
6
7
  exports.getStringListOption = getStringListOption;
7
- exports.toObjectState = toObjectState;
8
+ /** `1` or `true` (any case), the usual spelling of an enabled env flag */
9
+ function isTruthyEnv(value) {
10
+ return value === '1' || value?.toLowerCase() === 'true';
11
+ }
8
12
  function getBooleanOption(options, key, fallback = false) {
9
13
  const value = options[key];
10
14
  if (typeof value === 'boolean') {
@@ -55,9 +59,3 @@ function getStringListOption(options, key) {
55
59
  });
56
60
  return result.length > 0 ? result : undefined;
57
61
  }
58
- function toObjectState(value, fallback) {
59
- if (value && typeof value === 'object') {
60
- return value;
61
- }
62
- return fallback;
63
- }
@@ -29,7 +29,7 @@ export declare function resolveProxy(targetUrl: string, env?: NodeJS.ProcessEnv)
29
29
  export declare function webFetch(url: string, init?: RequestInit): Promise<Response>;
30
30
  /**
31
31
  * An http.Agent routing `targetUrl` through its proxy, for the core
32
- * http/https APIs and node-fetch (the streaming uploads); undefined when the
32
+ * http/https APIs (including the streaming uploads); undefined when the
33
33
  * connection is direct. Always a CONNECT tunnel (also for http targets, like
34
34
  * undici's ProxyAgent above): the absolute-form alternative rewrites the
35
35
  * request head after it was buffered, which garbles a streaming body.
@@ -127,20 +127,12 @@ function webFetch(url, init = {}) {
127
127
  dispatcher,
128
128
  });
129
129
  }
130
- if (typeof globalThis.fetch === 'function') {
131
- return globalThis.fetch(url, init);
132
- }
133
- // Node < 18 only. Loaded on demand so the built-in fetch path never pays
134
- // for node-fetch (nor for the punycode deprecation warning it triggers on
135
- // Node ≥ 21).
136
- const mod = require('node-fetch');
137
- const nodeFetch = (mod.default ?? mod);
138
- return nodeFetch(url, init);
130
+ return globalThis.fetch(url, init);
139
131
  }
140
132
  const proxyAgents = new Map();
141
133
  /**
142
134
  * An http.Agent routing `targetUrl` through its proxy, for the core
143
- * http/https APIs and node-fetch (the streaming uploads); undefined when the
135
+ * http/https APIs (including the streaming uploads); undefined when the
144
136
  * connection is direct. Always a CONNECT tunnel (also for http targets, like
145
137
  * undici's ProxyAgent above): the absolute-form alternative rewrites the
146
138
  * request head after it was buffered, which garbles a streaming body.
@@ -0,0 +1,33 @@
1
+ import type { Agent as HttpAgent } from 'http';
2
+ import { Readable } from 'stream';
3
+ export interface UploadRequest {
4
+ method: string;
5
+ headers: Record<string, string>;
6
+ body: Readable;
7
+ }
8
+ export interface UploadResponse {
9
+ status: number;
10
+ statusText: string;
11
+ }
12
+ export declare function fileContentType(fileName: string): string;
13
+ /**
14
+ * multipart/form-data with `fields` first and the file last. The file's size
15
+ * is known up front, so the request carries Content-Length instead of a
16
+ * chunked body: what object stores expect, and the only framing that survives
17
+ * a proxy agent's rewrite of the buffered request head.
18
+ */
19
+ export declare function multipartRequest(fields: Record<string, string>, file: {
20
+ name: string;
21
+ size: number;
22
+ stream: Readable;
23
+ }): UploadRequest;
24
+ /**
25
+ * Send `request` and resolve with the response status once its head arrives
26
+ * (the body is drained and dropped). Network errors reject as they are, with
27
+ * their `code` (ECONNRESET, ...); aborting `signal` rejects with an AbortError.
28
+ */
29
+ export declare function sendUploadRequest(url: string, request: UploadRequest, options: {
30
+ agent?: HttpAgent;
31
+ signal?: AbortSignal;
32
+ userAgent?: string;
33
+ }): Promise<UploadResponse>;