socket 0.14.28 → 0.14.30

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 (53) hide show
  1. package/bin/cli.js +7 -0
  2. package/bin/npm-cli.js +7 -0
  3. package/bin/npx-cli.js +7 -0
  4. package/bin/shadow/module-sync/npm +3 -0
  5. package/bin/shadow/module-sync/npx +3 -0
  6. package/bin/shadow/require/npm +3 -0
  7. package/bin/shadow/require/npx +3 -0
  8. package/dist/module-sync/cli.d.ts.map +1 -0
  9. package/dist/module-sync/cli.js +5258 -0
  10. package/dist/module-sync/constants.d.ts +20 -0
  11. package/dist/module-sync/constants.js +72 -0
  12. package/dist/module-sync/npm-cli.js +85 -0
  13. package/dist/module-sync/npm-injection.js +1611 -0
  14. package/dist/module-sync/npx-cli.js +61 -0
  15. package/dist/{sdk.d.ts → module-sync/sdk.d.ts} +1 -5
  16. package/dist/module-sync/sdk.js +253 -0
  17. package/dist/require/cli.d.ts +3 -0
  18. package/dist/require/cli.d.ts.map +1 -0
  19. package/dist/{cli.js → require/cli.js} +80 -82
  20. package/dist/require/color-or-markdown.d.ts +23 -0
  21. package/dist/require/constants.d.ts +20 -0
  22. package/dist/require/constants.js +67 -0
  23. package/dist/require/errors.d.ts +7 -0
  24. package/dist/require/link.d.ts +2 -0
  25. package/dist/require/link.js +45 -0
  26. package/dist/require/npm-cli.d.ts +2 -0
  27. package/dist/{npm-cli.js → require/npm-cli.js} +12 -10
  28. package/dist/require/npm-injection.d.ts +1 -0
  29. package/dist/{npm-injection.js → require/npm-injection.js} +170 -134
  30. package/dist/require/npx-cli.d.ts +2 -0
  31. package/dist/{npx-cli.js → require/npx-cli.js} +12 -12
  32. package/dist/require/path-resolve.d.ts +8 -0
  33. package/dist/require/path-resolve.js +183 -0
  34. package/dist/require/sdk.d.ts +9 -0
  35. package/dist/{sdk.js → require/sdk.js} +16 -36
  36. package/dist/require/settings.d.ts +9 -0
  37. package/dist/{vendor.js → require/vendor.js} +6 -1
  38. package/package.json +53 -18
  39. package/translations.json +190 -287
  40. package/bin/npm +0 -2
  41. package/bin/npx +0 -2
  42. package/dist/cli.d.ts.map +0 -1
  43. /package/dist/{cli.d.ts → module-sync/cli.d.ts} +0 -0
  44. /package/dist/{color-or-markdown.d.ts → module-sync/color-or-markdown.d.ts} +0 -0
  45. /package/dist/{errors.d.ts → module-sync/errors.d.ts} +0 -0
  46. /package/dist/{link.d.ts → module-sync/link.d.ts} +0 -0
  47. /package/dist/{link.js → module-sync/link.js} +0 -0
  48. /package/dist/{npm-cli.d.ts → module-sync/npm-cli.d.ts} +0 -0
  49. /package/dist/{npm-injection.d.ts → module-sync/npm-injection.d.ts} +0 -0
  50. /package/dist/{npx-cli.d.ts → module-sync/npx-cli.d.ts} +0 -0
  51. /package/dist/{path-resolve.d.ts → module-sync/path-resolve.d.ts} +0 -0
  52. /package/dist/{path-resolve.js → module-sync/path-resolve.js} +0 -0
  53. /package/dist/{settings.d.ts → module-sync/settings.d.ts} +0 -0
@@ -0,0 +1,1611 @@
1
+ 'use strict';
2
+
3
+ var constants = require('./constants.js');
4
+ var require$$0$2 = require('@babel/runtime/helpers/interopRequireWildcard');
5
+ var require$$0$1 = require('@babel/runtime/helpers/interopRequireDefault');
6
+ var require$$1$2 = require('node:events');
7
+ var require$$0 = require('node:fs');
8
+ var require$$3$3 = require('node:https');
9
+ var require$$1 = require('node:path');
10
+ var require$$3 = require('node:readline');
11
+ var require$$5 = require('node:stream');
12
+ var require$$7$1 = require('node:timers/promises');
13
+ var require$$3$1 = require('is-interactive');
14
+ var require$$5$1 = require('npm-package-arg');
15
+ var require$$3$2 = require('@socketregistry/yocto-spinner');
16
+ var require$$4 = require('semver');
17
+ var require$$6$1 = require('@socketsecurity/config');
18
+ var require$$7 = require('@socketsecurity/registry/lib/objects');
19
+ var require$$8 = require('@socketsecurity/registry/lib/packages');
20
+ var require$$1$1 = require('node:net');
21
+ var require$$2 = require('node:os');
22
+ var require$$6 = require('../../package.json');
23
+ var sdk = require('./sdk.js');
24
+ var pathResolve = require('./path-resolve.js');
25
+ var link = require('./link.js');
26
+
27
+ var npmInjection$2 = {};
28
+
29
+ var npmInjection$1 = {};
30
+
31
+ var arborist = {};
32
+
33
+ var ttyServer$1 = {};
34
+
35
+ Object.defineProperty(ttyServer$1, "__esModule", {
36
+ value: true
37
+ });
38
+ ttyServer$1.createTTYServer = createTTYServer;
39
+ var _nodeFs$1 = require$$0;
40
+ var _nodeNet = require$$1$1;
41
+ var _nodeOs = require$$2;
42
+ var _nodePath$1 = require$$1;
43
+ var _nodeReadline$1 = require$$3;
44
+ var _nodeStream$1 = require$$5;
45
+ var _package = require$$6;
46
+ var _misc$1 = sdk.misc;
47
+ const NEWLINE_CHAR_CODE = 10; /*'\n'*/
48
+
49
+ const TTY_IPC = process.env['SOCKET_SECURITY_TTY_IPC'];
50
+ const sock = _nodePath$1.join(_nodeOs.tmpdir(), `socket-security-tty-${process.pid}.sock`);
51
+ process.env['SOCKET_SECURITY_TTY_IPC'] = sock;
52
+ function createNonStandardTTYServer() {
53
+ return {
54
+ async captureTTY(mutexFn) {
55
+ return await new Promise((resolve, reject) => {
56
+ const conn = _nodeNet.createConnection({
57
+ path: TTY_IPC
58
+ }).on('error', reject);
59
+ let captured = false;
60
+ const buffs = [];
61
+ conn.on('data', function awaitCapture(chunk) {
62
+ buffs.push(chunk);
63
+ let lineBuff = Buffer.concat(buffs);
64
+ if (captured) return;
65
+ try {
66
+ const eolIndex = lineBuff.indexOf(NEWLINE_CHAR_CODE);
67
+ if (eolIndex !== -1) {
68
+ conn.removeListener('data', awaitCapture);
69
+ conn.push(lineBuff.slice(eolIndex + 1));
70
+ const {
71
+ capabilities: {
72
+ input: hasInput,
73
+ output: hasOutput
74
+ },
75
+ ipc_version: remote_ipc_version
76
+ } = JSON.parse(lineBuff.subarray(0, eolIndex).toString('utf-8'));
77
+ lineBuff = null;
78
+ captured = true;
79
+ if (remote_ipc_version !== _package.version) {
80
+ throw new Error('Mismatched STDIO tunnel IPC version, ensure you only have 1 version of socket CLI being called.');
81
+ }
82
+ const input = hasInput ? new _nodeStream$1.PassThrough() : null;
83
+ input?.pause();
84
+ if (input) conn.pipe(input);
85
+ const output = hasOutput ? new _nodeStream$1.PassThrough() : null;
86
+ if (output) {
87
+ output.pipe(conn)
88
+ // Make ora happy
89
+ ;
90
+ output.isTTY = true;
91
+ output.cursorTo = function cursorTo(x, y, callback) {
92
+ _nodeReadline$1.cursorTo(this, x, y, callback);
93
+ };
94
+ output.clearLine = function clearLine(dir, callback) {
95
+ _nodeReadline$1.clearLine(this, dir, callback);
96
+ };
97
+ }
98
+ mutexFn(hasInput ? input : undefined, hasOutput ? output : undefined).then(resolve, reject).finally(() => {
99
+ conn.unref();
100
+ conn.end();
101
+ input?.end();
102
+ output?.end();
103
+ // process.exit(13)
104
+ });
105
+ }
106
+ } catch (e) {
107
+ reject(e);
108
+ }
109
+ });
110
+ });
111
+ }
112
+ };
113
+ }
114
+ function createIPCServer(captureState, npmlog) {
115
+ const input = process.stdin;
116
+ const output = process.stderr;
117
+ return new Promise((resolve, reject) => {
118
+ const server = _nodeNet
119
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
120
+ .createServer(async conn => {
121
+ if (captureState.captured) {
122
+ await new Promise(resolve => {
123
+ captureState.pendingCaptures.push({
124
+ resolve() {
125
+ resolve();
126
+ }
127
+ });
128
+ });
129
+ } else {
130
+ captureState.captured = true;
131
+ }
132
+ const wasProgressEnabled = npmlog.progressEnabled;
133
+ npmlog.pause();
134
+ if (wasProgressEnabled) {
135
+ npmlog.disableProgress();
136
+ }
137
+ conn.write(`${JSON.stringify({
138
+ ipc_version: _package.version,
139
+ capabilities: {
140
+ input: Boolean(input),
141
+ output: true
142
+ }
143
+ })}\n`);
144
+ conn.on('data', data => {
145
+ output.write(data);
146
+ }).on('error', e => {
147
+ output.write(`there was an error prompting from a sub shell (${e?.message}), socket npm closing`);
148
+ process.exit(1);
149
+ });
150
+ input.on('data', data => {
151
+ conn.write(data);
152
+ }).on('end', () => {
153
+ conn.unref();
154
+ conn.end();
155
+ if (wasProgressEnabled) {
156
+ npmlog.enableProgress();
157
+ }
158
+ npmlog.resume();
159
+ captureState.nextCapture();
160
+ });
161
+ }).listen(sock, () => resolve(server)).on('error', reject).unref();
162
+ process.on('exit', () => {
163
+ server.close();
164
+ tryUnlinkSync(sock);
165
+ });
166
+ resolve(server);
167
+ });
168
+ }
169
+ function createStandardTTYServer(isInteractive, npmlog) {
170
+ const captureState = {
171
+ captured: false,
172
+ nextCapture: () => {
173
+ if (captureState.pendingCaptures.length > 0) {
174
+ const pendingCapture = captureState.pendingCaptures.shift();
175
+ pendingCapture?.resolve();
176
+ } else {
177
+ captureState.captured = false;
178
+ }
179
+ },
180
+ pendingCaptures: []
181
+ };
182
+ tryUnlinkSync(sock);
183
+ const input = isInteractive ? process.stdin : undefined;
184
+ const output = process.stderr;
185
+ let ipcServerPromise;
186
+ if (input) {
187
+ ipcServerPromise = createIPCServer(captureState, npmlog);
188
+ }
189
+ return {
190
+ async captureTTY(mutexFn) {
191
+ await ipcServerPromise;
192
+ if (captureState.captured) {
193
+ const captured = new Promise(resolve => {
194
+ captureState.pendingCaptures.push({
195
+ resolve() {
196
+ resolve();
197
+ }
198
+ });
199
+ });
200
+ await captured;
201
+ } else {
202
+ captureState.captured = true;
203
+ }
204
+ const wasProgressEnabled = npmlog.progressEnabled;
205
+ try {
206
+ npmlog.pause();
207
+ if (wasProgressEnabled) {
208
+ npmlog.disableProgress();
209
+ }
210
+ return await mutexFn(input, output);
211
+ } finally {
212
+ if (wasProgressEnabled) {
213
+ npmlog.enableProgress();
214
+ }
215
+ npmlog.resume();
216
+ captureState.nextCapture();
217
+ }
218
+ }
219
+ };
220
+ }
221
+ function tryUnlinkSync(filepath) {
222
+ try {
223
+ (0, _nodeFs$1.unlinkSync)(filepath);
224
+ } catch (e) {
225
+ if ((0, _misc$1.isErrnoException)(e) && e.code !== 'ENOENT') {
226
+ throw e;
227
+ }
228
+ }
229
+ }
230
+ function createTTYServer(isInteractive, npmlog) {
231
+ return !isInteractive && TTY_IPC ? createNonStandardTTYServer() : createStandardTTYServer(isInteractive, npmlog);
232
+ }
233
+
234
+ var issueRules = {};
235
+
236
+ Object.defineProperty(issueRules, "__esModule", {
237
+ value: true
238
+ });
239
+ issueRules.createIssueUXLookup = createIssueUXLookup;
240
+ //#region UX Constants
241
+
242
+ const IGNORE_UX = {
243
+ block: false,
244
+ display: false
245
+ };
246
+ const WARN_UX = {
247
+ block: false,
248
+ display: true
249
+ };
250
+ const ERROR_UX = {
251
+ block: true,
252
+ display: true
253
+ };
254
+ //#endregion
255
+ //#region utils
256
+
257
+ /**
258
+ * Iterates over all entries with ordered issue rule for deferral. Iterates over
259
+ * all issue rules and finds the first defined value that does not defer otherwise
260
+ * uses the defaultValue. Takes the value and converts into a UX workflow
261
+ */
262
+ function resolveIssueRuleUX(entriesOrderedIssueRules, defaultValue) {
263
+ if (defaultValue === true || defaultValue == null) {
264
+ defaultValue = {
265
+ action: 'error'
266
+ };
267
+ } else if (defaultValue === false) {
268
+ defaultValue = {
269
+ action: 'ignore'
270
+ };
271
+ }
272
+ let block = false;
273
+ let display = false;
274
+ let needDefault = true;
275
+ iterate_entries: for (const issueRuleArr of entriesOrderedIssueRules) {
276
+ for (const rule of issueRuleArr) {
277
+ if (issueRuleValueDoesNotDefer(rule)) {
278
+ needDefault = false;
279
+ const narrowingFilter = uxForDefinedNonDeferValue(rule);
280
+ block = block || narrowingFilter.block;
281
+ display = display || narrowingFilter.display;
282
+ continue iterate_entries;
283
+ }
284
+ }
285
+ const narrowingFilter = uxForDefinedNonDeferValue(defaultValue);
286
+ block = block || narrowingFilter.block;
287
+ display = display || narrowingFilter.display;
288
+ }
289
+ if (needDefault) {
290
+ const narrowingFilter = uxForDefinedNonDeferValue(defaultValue);
291
+ block = block || narrowingFilter.block;
292
+ display = display || narrowingFilter.display;
293
+ }
294
+ return {
295
+ block,
296
+ display
297
+ };
298
+ }
299
+
300
+ /**
301
+ * Negative form because it is narrowing the type
302
+ */
303
+ function issueRuleValueDoesNotDefer(issueRule) {
304
+ if (issueRule === undefined) {
305
+ return false;
306
+ } else if (typeof issueRule === 'object' && issueRule) {
307
+ const {
308
+ action
309
+ } = issueRule;
310
+ if (action === undefined || action === 'defer') {
311
+ return false;
312
+ }
313
+ }
314
+ return true;
315
+ }
316
+
317
+ /**
318
+ * Handles booleans for backwards compatibility
319
+ */
320
+ function uxForDefinedNonDeferValue(issueRuleValue) {
321
+ if (typeof issueRuleValue === 'boolean') {
322
+ return issueRuleValue ? ERROR_UX : IGNORE_UX;
323
+ }
324
+ const {
325
+ action
326
+ } = issueRuleValue;
327
+ if (action === 'warn') {
328
+ return WARN_UX;
329
+ } else if (action === 'ignore') {
330
+ return IGNORE_UX;
331
+ }
332
+ return ERROR_UX;
333
+ }
334
+ //#endregion
335
+
336
+ //#region exports
337
+
338
+ function createIssueUXLookup(settings) {
339
+ const cachedUX = new Map();
340
+ return context => {
341
+ const key = context.issue.type;
342
+ let ux = cachedUX.get(key);
343
+ if (ux) {
344
+ return ux;
345
+ }
346
+ const entriesOrderedIssueRules = [];
347
+ for (const settingsEntry of settings.entries) {
348
+ const orderedIssueRules = [];
349
+ let target = settingsEntry.start;
350
+ while (target !== null) {
351
+ const resolvedTarget = settingsEntry.settings[target];
352
+ if (!resolvedTarget) {
353
+ break;
354
+ }
355
+ const issueRuleValue = resolvedTarget.issueRules?.[key];
356
+ if (typeof issueRuleValue !== 'undefined') {
357
+ orderedIssueRules.push(issueRuleValue);
358
+ }
359
+ target = resolvedTarget.deferTo ?? null;
360
+ }
361
+ entriesOrderedIssueRules.push(orderedIssueRules);
362
+ }
363
+ const defaultValue = settings.defaults.issueRules[key];
364
+ let resolvedDefaultValue = {
365
+ action: 'error'
366
+ };
367
+ if (defaultValue === false) {
368
+ resolvedDefaultValue = {
369
+ action: 'ignore'
370
+ };
371
+ } else if (defaultValue && defaultValue !== true) {
372
+ resolvedDefaultValue = {
373
+ action: defaultValue.action ?? 'error'
374
+ };
375
+ }
376
+ ux = resolveIssueRuleUX(entriesOrderedIssueRules, resolvedDefaultValue);
377
+ cachedUX.set(key, ux);
378
+ return ux;
379
+ };
380
+ }
381
+
382
+ var _interopRequireDefault = require$$0$1.default;
383
+ Object.defineProperty(arborist, "__esModule", {
384
+ value: true
385
+ });
386
+ arborist.SafeArborist = void 0;
387
+ arborist.installSafeArborist = installSafeArborist;
388
+ var _nodeEvents = require$$1$2;
389
+ var _nodeFs = require$$0;
390
+ var _nodeHttps = require$$3$3;
391
+ var _nodePath = require$$1;
392
+ var _nodeReadline = require$$3;
393
+ var _nodeStream = require$$5;
394
+ var _promises = require$$7$1;
395
+ var _isInteractive = _interopRequireDefault(require$$3$1);
396
+ var _npmPackageArg = require$$5$1;
397
+ var _yoctoSpinner = require$$3$2;
398
+ var _semver = require$$4;
399
+ var _config = require$$6$1;
400
+ var _objects = require$$7;
401
+ var _packages = require$$8;
402
+ var _ttyServer = ttyServer$1;
403
+ var _constants$1 = constants.constants;
404
+ var _colorOrMarkdown = sdk.colorOrMarkdown;
405
+ var _issueRules = issueRules;
406
+ var _misc = sdk.misc;
407
+ var _pathResolve = pathResolve.pathResolve;
408
+ var _sdk = sdk.sdk;
409
+ var _settings = sdk.settings;
410
+ const POTENTIAL_BUG_ERROR_MESSAGE = `This is may be a bug with socket-npm related to changes to the npm CLI.\nPlease report to ${_constants$1.SOCKET_CLI_ISSUES_URL}.`;
411
+ const npmEntrypoint = (0, _nodeFs.realpathSync)(process.argv[1]);
412
+ const npmRootPath = (0, _pathResolve.findRoot)(_nodePath.dirname(npmEntrypoint));
413
+ function tryRequire(...ids) {
414
+ for (const data of ids) {
415
+ let id;
416
+ let transformer;
417
+ if (Array.isArray(data)) {
418
+ id = data[0];
419
+ transformer = data[1];
420
+ } else {
421
+ id = data;
422
+ transformer = mod => mod;
423
+ }
424
+ try {
425
+ // Check that the transformed value isn't `undefined` because older
426
+ // versions of packages like 'proc-log' may not export a `log` method.
427
+ const exported = transformer(require(id));
428
+ if (exported !== undefined) {
429
+ return exported;
430
+ }
431
+ } catch {}
432
+ }
433
+ return undefined;
434
+ }
435
+ if (npmRootPath === undefined) {
436
+ console.error(`Unable to find npm CLI install directory.\nSearched parent directories of ${npmEntrypoint}.\n\n${POTENTIAL_BUG_ERROR_MESSAGE}`);
437
+ process.exit(127);
438
+ }
439
+ const npmNmPath = _nodePath.join(npmRootPath, 'node_modules');
440
+ const arboristPkgPath = _nodePath.join(npmNmPath, '@npmcli/arborist');
441
+ const arboristClassPath = _nodePath.join(arboristPkgPath, 'lib/arborist/index.js');
442
+ const arboristDepValidPath = _nodePath.join(arboristPkgPath, 'lib/dep-valid.js');
443
+ const arboristEdgeClassPath = _nodePath.join(arboristPkgPath, 'lib/edge.js');
444
+ const arboristNodeClassPath = _nodePath.join(arboristPkgPath, 'lib/node.js');
445
+ const arboristOverrideSetClassPatch = _nodePath.join(arboristPkgPath, 'lib/override-set.js');
446
+ const log = tryRequire([_nodePath.join(npmNmPath, 'proc-log/lib/index.js'),
447
+ // The proc-log DefinitelyTyped definition is incorrect. The type definition
448
+ // is really that of its export log.
449
+ mod => mod.log], _nodePath.join(npmNmPath, 'npmlog/lib/log.js'));
450
+ if (log === undefined) {
451
+ console.error(`Unable to integrate with npm CLI logging infrastructure.\n\n${POTENTIAL_BUG_ERROR_MESSAGE}.`);
452
+ process.exit(127);
453
+ }
454
+ const pacote = tryRequire(_nodePath.join(npmNmPath, 'pacote'), 'pacote');
455
+ const {
456
+ tarball
457
+ } = pacote;
458
+ const translations = require(_nodePath.join(_constants$1.rootPath, 'translations.json'));
459
+ const abortController = new AbortController();
460
+ const {
461
+ signal: abortSignal
462
+ } = abortController;
463
+ const Arborist = require(arboristClassPath);
464
+ const depValid = require(arboristDepValidPath);
465
+ const Edge = require(arboristEdgeClassPath);
466
+ const Node = require(arboristNodeClassPath);
467
+ const OverrideSet = require(arboristOverrideSetClassPatch);
468
+ const kCtorArgs = Symbol('ctorArgs');
469
+ const kRiskyReify = Symbol('riskyReify');
470
+ const formatter = new _colorOrMarkdown.ColorOrMarkdown(false);
471
+ const pubToken = (0, _sdk.getDefaultKey)() ?? _sdk.FREE_API_KEY;
472
+ const ttyServer = (0, _ttyServer.createTTYServer)((0, _isInteractive.default)({
473
+ stream: process.stdin
474
+ }), log);
475
+ let _uxLookup;
476
+ async function uxLookup(settings) {
477
+ while (_uxLookup === undefined) {
478
+ // eslint-disable-next-line no-await-in-loop
479
+ await (0, _promises.setTimeout)(1, {
480
+ signal: abortSignal
481
+ });
482
+ }
483
+ return _uxLookup(settings);
484
+ }
485
+ async function* batchScan(pkgIds) {
486
+ const query = {
487
+ packages: pkgIds.map(id => {
488
+ const {
489
+ name,
490
+ version
491
+ } = pkgidParts(id);
492
+ return {
493
+ eco: 'npm',
494
+ pkg: name,
495
+ ver: version,
496
+ top: true
497
+ };
498
+ })
499
+ };
500
+ // TODO: Migrate to SDK.
501
+ const pkgDataReq = _nodeHttps.request(`${_constants$1.API_V0_URL}/scan/batch`, {
502
+ method: 'POST',
503
+ headers: {
504
+ Authorization: `Basic ${Buffer.from(`${pubToken}:`).toString('base64url')}`
505
+ },
506
+ signal: abortSignal
507
+ }).end(JSON.stringify(query));
508
+ const {
509
+ 0: res
510
+ } = await _nodeEvents.once(pkgDataReq, 'response');
511
+ const ok = res.statusCode >= 200 && res.statusCode <= 299;
512
+ if (!ok) {
513
+ throw new Error(`Socket API Error: ${res.statusCode}`);
514
+ }
515
+ const rli = _nodeReadline.createInterface(res);
516
+ for await (const line of rli) {
517
+ yield JSON.parse(line);
518
+ }
519
+ }
520
+
521
+ // Patch adding doOverrideSetsConflict is based on
522
+ // https://github.com/npm/cli/pull/7025.
523
+ function doOverrideSetsConflict(first, second) {
524
+ // If override sets contain one another then we can try to use the more specific
525
+ // one. However, if neither one is more specific, then we consider them to be
526
+ // in conflict.
527
+ return findSpecificOverrideSet(first, second) === undefined;
528
+ }
529
+ function findSocketYmlSync() {
530
+ let prevDir = null;
531
+ let dir = process.cwd();
532
+ while (dir !== prevDir) {
533
+ let ymlPath = _nodePath.join(dir, 'socket.yml');
534
+ let yml = maybeReadfileSync(ymlPath);
535
+ if (yml === undefined) {
536
+ ymlPath = _nodePath.join(dir, 'socket.yaml');
537
+ yml = maybeReadfileSync(ymlPath);
538
+ }
539
+ if (typeof yml === 'string') {
540
+ try {
541
+ return {
542
+ path: ymlPath,
543
+ parsed: _config.parseSocketConfig(yml)
544
+ };
545
+ } catch {
546
+ throw new Error(`Found file but was unable to parse ${ymlPath}`);
547
+ }
548
+ }
549
+ prevDir = dir;
550
+ dir = _nodePath.join(dir, '..');
551
+ }
552
+ return null;
553
+ }
554
+
555
+ // Patch adding findSpecificOverrideSet is based on
556
+ // https://github.com/npm/cli/pull/7025.
557
+ function findSpecificOverrideSet(first, second) {
558
+ let overrideSet = second;
559
+ while (overrideSet) {
560
+ if (overrideSet.isEqual(first)) {
561
+ return second;
562
+ }
563
+ overrideSet = overrideSet.parent;
564
+ }
565
+ overrideSet = first;
566
+ while (overrideSet) {
567
+ if (overrideSet.isEqual(second)) {
568
+ return first;
569
+ }
570
+ overrideSet = overrideSet.parent;
571
+ }
572
+ // The override sets are incomparable. Neither one contains the other.
573
+ log.silly('Conflicting override sets', first, second);
574
+ return undefined;
575
+ }
576
+ function maybeReadfileSync(filepath) {
577
+ try {
578
+ return (0, _nodeFs.readFileSync)(filepath, 'utf8');
579
+ } catch {}
580
+ return undefined;
581
+ }
582
+ async function packagesHaveRiskyIssues(safeArb, _registry, pkgs, output) {
583
+ const spinner = _yoctoSpinner({
584
+ stream: output
585
+ });
586
+ let result = false;
587
+ let {
588
+ length: remaining
589
+ } = pkgs;
590
+ if (!remaining) {
591
+ spinner.success('No changes detected');
592
+ return result;
593
+ }
594
+ const getText = () => `Looking up data for ${remaining} packages`;
595
+ spinner.start(getText());
596
+ try {
597
+ for await (const pkgData of batchScan(pkgs.map(p => p.pkgid))) {
598
+ const {
599
+ pkg: name,
600
+ ver: version
601
+ } = pkgData;
602
+ const id = `${name}@${version}`;
603
+ let displayWarning = false;
604
+ let failures = [];
605
+ if (pkgData.type === 'missing') {
606
+ result = true;
607
+ failures.push({
608
+ type: 'missingDependency',
609
+ block: false,
610
+ raw: undefined
611
+ });
612
+ } else {
613
+ let blocked = false;
614
+ for (const failure of pkgData.value.issues) {
615
+ const {
616
+ type
617
+ } = failure;
618
+ // eslint-disable-next-line no-await-in-loop
619
+ const ux = await uxLookup({
620
+ package: {
621
+ name,
622
+ version
623
+ },
624
+ issue: {
625
+ type
626
+ }
627
+ });
628
+ if (ux.block) {
629
+ result = true;
630
+ blocked = true;
631
+ }
632
+ if (ux.display) {
633
+ displayWarning = true;
634
+ }
635
+ if (ux.block || ux.display) {
636
+ failures.push({
637
+ type,
638
+ block: ux.block,
639
+ raw: failure
640
+ });
641
+ // Before we ask about problematic issues, check to see if they
642
+ // already existed in the old version if they did, be quiet.
643
+ const pkg = pkgs.find(p => p.pkgid === id && p.existing?.startsWith(`${name}@`));
644
+ if (pkg?.existing) {
645
+ const oldPkgData =
646
+ // eslint-disable-next-line no-await-in-loop
647
+ (await batchScan([pkg.existing]).next()).value;
648
+ if (oldPkgData.type === 'success') {
649
+ failures = failures.filter(issue => oldPkgData.value.issues.find(oldIssue => oldIssue.type === issue.type) === undefined);
650
+ }
651
+ }
652
+ }
653
+ }
654
+ if (!blocked) {
655
+ const pkg = pkgs.find(p => p.pkgid === id);
656
+ if (pkg) {
657
+ await tarball.stream(id, stream => {
658
+ stream.resume();
659
+ return stream.promise();
660
+ }, {
661
+ ...safeArb[kCtorArgs][0]
662
+ });
663
+ }
664
+ }
665
+ }
666
+ if (displayWarning) {
667
+ spinner.stop(`(socket) ${formatter.hyperlink(id, `https://socket.dev/npm/package/${name}/overview/${version}`)} contains risks:`);
668
+ // Filter issues for blessed packages.
669
+ if ((0, _packages.isBlessedPackageName)(name)) {
670
+ failures = failures.filter(({
671
+ type
672
+ }) => type !== 'unpopularPackage' && type !== 'unstableOwnership');
673
+ }
674
+ failures.sort((a, b) => a.type < b.type ? -1 : 1);
675
+ const lines = new Set();
676
+ for (const failure of failures) {
677
+ const {
678
+ type
679
+ } = failure;
680
+ // Based data from { pageProps: { alertTypes } } of:
681
+ // https://socket.dev/_next/data/94666139314b6437ee4491a0864e72b264547585/en-US.json
682
+ const info = translations.issues[type];
683
+ const title = info?.title ?? type;
684
+ const maybeBlocking = failure.block ? '' : ' (non-blocking)';
685
+ const maybeDesc = info?.description ? ` - ${info.description}` : '';
686
+ // TODO: emoji seems to mis-align terminals sometimes
687
+ lines.add(` ${title}${maybeBlocking}${maybeDesc}\n`);
688
+ }
689
+ for (const line of lines) {
690
+ output?.write(line);
691
+ }
692
+ spinner.start();
693
+ }
694
+ remaining -= 1;
695
+ spinner.text = remaining > 0 ? getText() : '';
696
+ }
697
+ return result;
698
+ } finally {
699
+ spinner.stop();
700
+ }
701
+ }
702
+ function pkgidParts(pkgid) {
703
+ const delimiter = pkgid.lastIndexOf('@');
704
+ const name = pkgid.slice(0, delimiter);
705
+ const version = pkgid.slice(delimiter + 1);
706
+ return {
707
+ name,
708
+ version
709
+ };
710
+ }
711
+ function toRepoUrl(resolved) {
712
+ return resolved.replace(/#[\s\S]*$/, '').replace(/\?[\s\S]*$/, '').replace(/\/[^/]*\/-\/[\s\S]*$/, '');
713
+ }
714
+ function walk(diff_, needInfoOn = []) {
715
+ const queue = [diff_];
716
+ let pos = 0;
717
+ let {
718
+ length: queueLength
719
+ } = queue;
720
+ while (pos < queueLength) {
721
+ if (pos === _constants$1.LOOP_SENTINEL) {
722
+ throw new Error('Detected infinite loop while walking Arborist diff');
723
+ }
724
+ const diff = queue[pos++];
725
+ if (!diff) {
726
+ continue;
727
+ }
728
+ if (diff.action) {
729
+ const sameVersion = diff.actual?.package.version === diff.ideal?.package.version;
730
+ let keep = false;
731
+ let existing = null;
732
+ if (diff.action === 'CHANGE') {
733
+ if (!sameVersion) {
734
+ existing = diff.actual.pkgid;
735
+ keep = true;
736
+ }
737
+ } else {
738
+ keep = diff.action !== 'REMOVE';
739
+ }
740
+ if (keep && diff.ideal?.pkgid && diff.ideal.resolved && (!diff.actual || diff.actual.resolved)) {
741
+ needInfoOn.push({
742
+ existing,
743
+ pkgid: diff.ideal.pkgid,
744
+ repository_url: toRepoUrl(diff.ideal.resolved)
745
+ });
746
+ }
747
+ }
748
+ if (diff.children) {
749
+ for (const child of diff.children) {
750
+ queue[queueLength++] = child;
751
+ }
752
+ }
753
+ }
754
+ return needInfoOn;
755
+ }
756
+
757
+ // The Edge class makes heavy use of private properties which subclasses do NOT
758
+ // have access to. So we have to recreate any functionality that relies on those
759
+ // private properties and use our own "safe" prefixed non-conflicting private
760
+ // properties. Implementation code not related to patch https://github.com/npm/cli/pull/7025
761
+ // is based on https://github.com/npm/cli/blob/v10.9.0/workspaces/arborist/lib/edge.js.
762
+ //
763
+ // The npm application
764
+ // Copyright (c) npm, Inc. and Contributors
765
+ // Licensed on the terms of The Artistic License 2.0
766
+ //
767
+ // An edge in the dependency graph.
768
+ // Represents a dependency relationship of some kind.
769
+ class SafeEdge extends Edge {
770
+ #safeAccept;
771
+ #safeError;
772
+ #safeExplanation;
773
+ #safeFrom;
774
+ #safeName;
775
+ #safeTo;
776
+ constructor(options) {
777
+ const {
778
+ accept,
779
+ from,
780
+ name
781
+ } = options;
782
+ // Defer to supper to validate options and assign non-private values.
783
+ super(options);
784
+ if (accept !== undefined) {
785
+ this.#safeAccept = accept || '*';
786
+ }
787
+ this.#safeError = null;
788
+ this.#safeExplanation = null;
789
+ this.#safeFrom = from;
790
+ this.#safeName = name;
791
+ this.#safeTo = null;
792
+ this.reload(true);
793
+ }
794
+ get accept() {
795
+ return this.#safeAccept;
796
+ }
797
+ get bundled() {
798
+ return !!this.#safeFrom?.package?.bundleDependencies?.includes(this.name);
799
+ }
800
+ get error() {
801
+ if (!this.#safeError) {
802
+ if (!this.#safeTo) {
803
+ if (this.optional) {
804
+ this.#safeError = null;
805
+ } else {
806
+ this.#safeError = 'MISSING';
807
+ }
808
+ } else if (this.peer && this.#safeFrom === this.#safeTo.parent && !this.#safeFrom?.isTop) {
809
+ this.#safeError = 'PEER LOCAL';
810
+ } else if (!this.satisfiedBy(this.#safeTo)) {
811
+ this.#safeError = 'INVALID';
812
+ }
813
+ // Patch adding "else if" condition is based on
814
+ // https://github.com/npm/cli/pull/7025.
815
+ else if (this.overrides && this.#safeTo.edgesOut.size && doOverrideSetsConflict(this.overrides, this.#safeTo.overrides)) {
816
+ // Any inconsistency between the edge's override set and the target's
817
+ // override set is potentially problematic. But we only say the edge is
818
+ // in error if the override sets are plainly conflicting. Note that if
819
+ // the target doesn't have any dependencies of their own, then this
820
+ // inconsistency is irrelevant.
821
+ this.#safeError = 'INVALID';
822
+ } else {
823
+ this.#safeError = 'OK';
824
+ }
825
+ }
826
+ if (this.#safeError === 'OK') {
827
+ return null;
828
+ }
829
+ return this.#safeError;
830
+ }
831
+
832
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
833
+ get from() {
834
+ return this.#safeFrom;
835
+ }
836
+
837
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
838
+ get spec() {
839
+ if (this.overrides?.value && this.overrides.value !== '*' && this.overrides.name === this.name) {
840
+ // Patch adding "if" condition is based on
841
+ // https://github.com/npm/cli/pull/7025.
842
+ //
843
+ // If this edge has the same overrides field as the source, then we're not
844
+ // applying an override for this edge.
845
+ if (this.overrides === this.#safeFrom?.overrides) {
846
+ // The Edge rawSpec getter will retrieve the private Edge #spec property.
847
+ return this.rawSpec;
848
+ }
849
+ if (this.overrides.value.startsWith('$')) {
850
+ const ref = this.overrides.value.slice(1);
851
+ // We may be a virtual root, if we are we want to resolve reference
852
+ // overrides from the real root, not the virtual one.
853
+ const pkg = this.#safeFrom?.sourceReference ? this.#safeFrom.sourceReference.root.package : this.#safeFrom?.root?.package;
854
+ if (pkg?.devDependencies?.[ref]) {
855
+ return pkg.devDependencies[ref];
856
+ }
857
+ if (pkg?.optionalDependencies?.[ref]) {
858
+ return pkg.optionalDependencies[ref];
859
+ }
860
+ if (pkg?.dependencies?.[ref]) {
861
+ return pkg.dependencies[ref];
862
+ }
863
+ if (pkg?.peerDependencies?.[ref]) {
864
+ return pkg.peerDependencies[ref];
865
+ }
866
+ throw new Error(`Unable to resolve reference ${this.overrides.value}`);
867
+ }
868
+ return this.overrides.value;
869
+ }
870
+ return this.rawSpec;
871
+ }
872
+
873
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
874
+ get to() {
875
+ return this.#safeTo;
876
+ }
877
+ detach() {
878
+ this.#safeExplanation = null;
879
+ // Patch replacing
880
+ // if (this.#safeTo) {
881
+ // this.#safeTo.edgesIn.delete(this)
882
+ // }
883
+ // is based on https://github.com/npm/cli/pull/7025.
884
+ this.#safeTo?.deleteEdgeIn(this);
885
+ this.#safeFrom?.edgesOut.delete(this.name);
886
+ this.#safeTo = null;
887
+ this.#safeError = 'DETACHED';
888
+ this.#safeFrom = null;
889
+ }
890
+
891
+ // Return the edge data, and an explanation of how that edge came to be here.
892
+ // @ts-ignore: Edge#explain is defined with an unused `seen = []` param.
893
+ explain() {
894
+ if (!this.#safeExplanation) {
895
+ const explanation = {
896
+ type: this.type,
897
+ name: this.name,
898
+ spec: this.spec,
899
+ bundled: false,
900
+ overridden: false,
901
+ error: undefined,
902
+ from: undefined,
903
+ rawSpec: undefined
904
+ };
905
+ if (this.rawSpec !== this.spec) {
906
+ explanation.rawSpec = this.rawSpec;
907
+ explanation.overridden = true;
908
+ }
909
+ if (this.bundled) {
910
+ explanation.bundled = this.bundled;
911
+ }
912
+ if (this.error) {
913
+ explanation.error = this.error;
914
+ }
915
+ if (this.#safeFrom) {
916
+ explanation.from = this.#safeFrom.explain();
917
+ }
918
+ this.#safeExplanation = explanation;
919
+ }
920
+ return this.#safeExplanation;
921
+ }
922
+ reload(hard = false) {
923
+ this.#safeExplanation = null;
924
+
925
+ // Patch adding newOverrideSet and oldOverrideSet is based on
926
+ // https://github.com/npm/cli/pull/7025.
927
+ let newOverrideSet;
928
+ let oldOverrideSet;
929
+ if (this.#safeFrom?.overrides) {
930
+ // Patch replacing
931
+ // this.overrides = this.#safeFrom.overrides.getEdgeRule(this)
932
+ // is based on https://github.com/npm/cli/pull/7025.
933
+ const newOverrideSet = this.#safeFrom.overrides.getEdgeRule(this);
934
+ if (newOverrideSet && !newOverrideSet.isEqual(this.overrides)) {
935
+ // If there's a new different override set we need to propagate it to
936
+ // the nodes. If we're deleting the override set then there's no point
937
+ // propagating it right now since it will be filled with another value
938
+ // later.
939
+ oldOverrideSet = this.overrides;
940
+ this.overrides = newOverrideSet;
941
+ }
942
+ } else {
943
+ this.overrides = undefined;
944
+ }
945
+ const newTo = this.#safeFrom?.resolve(this.name);
946
+ if (newTo !== this.#safeTo) {
947
+ if (this.#safeTo) {
948
+ // Patch replacing
949
+ // this.#safeTo.edgesIn.delete(this)
950
+ // is based on https://github.com/npm/cli/pull/7025.
951
+ this.#safeTo.deleteEdgeIn(this);
952
+ }
953
+ this.#safeTo = newTo ?? null;
954
+ this.#safeError = null;
955
+ if (this.#safeTo) {
956
+ this.#safeTo.addEdgeIn(this);
957
+ }
958
+ } else if (hard) {
959
+ this.#safeError = null;
960
+ }
961
+ // Patch adding "else if" condition based on
962
+ // https://github.com/npm/cli/pull/7025
963
+ else if (oldOverrideSet) {
964
+ // Propagate the new override set to the target node.
965
+ this.#safeTo.updateOverridesEdgeInRemoved(oldOverrideSet);
966
+ this.#safeTo.updateOverridesEdgeInAdded(newOverrideSet);
967
+ }
968
+ }
969
+ satisfiedBy(node) {
970
+ // Patch replacing
971
+ // if (node.name !== this.#name) {
972
+ // return false
973
+ // }
974
+ // is based on https://github.com/npm/cli/pull/7025.
975
+ if (node.name !== this.#safeName || !this.#safeFrom) {
976
+ return false;
977
+ }
978
+ // NOTE: this condition means we explicitly do not support overriding
979
+ // bundled or shrinkwrapped dependencies
980
+ if (node.hasShrinkwrap || node.inShrinkwrap || node.inBundle) {
981
+ return depValid(node, this.rawSpec, this.#safeAccept, this.#safeFrom);
982
+ }
983
+ // Patch replacing
984
+ // return depValid(node, this.spec, this.#accept, this.#from)
985
+ // is based on https://github.com/npm/cli/pull/7025.
986
+ //
987
+ // If there's no override we just use the spec.
988
+ if (!this.overrides?.keySpec) {
989
+ return depValid(node, this.spec, this.#safeAccept, this.#safeFrom);
990
+ }
991
+ // There's some override. If the target node satisfies the overriding spec
992
+ // then it's okay.
993
+ if (depValid(node, this.spec, this.#safeAccept, this.#safeFrom)) {
994
+ return true;
995
+ }
996
+ // If it doesn't, then it should at least satisfy the original spec.
997
+ if (!depValid(node, this.rawSpec, this.#safeAccept, this.#safeFrom)) {
998
+ return false;
999
+ }
1000
+ // It satisfies the original spec, not the overriding spec. We need to make
1001
+ // sure it doesn't use the overridden spec.
1002
+ // For example, we might have an ^8.0.0 rawSpec, and an override that makes
1003
+ // keySpec=8.23.0 and the override value spec=9.0.0.
1004
+ // If the node is 9.0.0, then it's okay because it's consistent with spec.
1005
+ // If the node is 8.24.0, then it's okay because it's consistent with the rawSpec.
1006
+ // If the node is 8.23.0, then it's not okay because even though it's consistent
1007
+ // with the rawSpec, it's also consistent with the keySpec.
1008
+ // So we're looking for ^8.0.0 or 9.0.0 and not 8.23.0.
1009
+ return !depValid(node, this.overrides.keySpec, this.#safeAccept, this.#safeFrom);
1010
+ }
1011
+ }
1012
+
1013
+ // Implementation code not related to patch https://github.com/npm/cli/pull/7025
1014
+ // is based on https://github.com/npm/cli/blob/v10.9.0/workspaces/arborist/lib/node.js:
1015
+ class SafeNode extends Node {
1016
+ // Return true if it's safe to remove this node, because anything that is
1017
+ // depending on it would be fine with the thing that they would resolve to if
1018
+ // it was removed, or nothing is depending on it in the first place.
1019
+ canDedupe(preferDedupe = false) {
1020
+ // Not allowed to mess with shrinkwraps or bundles.
1021
+ if (this.inDepBundle || this.inShrinkwrap) {
1022
+ return false;
1023
+ }
1024
+ // It's a top level pkg, or a dep of one.
1025
+ if (!this.resolveParent?.resolveParent) {
1026
+ return false;
1027
+ }
1028
+ // No one wants it, remove it.
1029
+ if (this.edgesIn.size === 0) {
1030
+ return true;
1031
+ }
1032
+ const other = this.resolveParent.resolveParent.resolve(this.name);
1033
+ // Nothing else, need this one.
1034
+ if (!other) {
1035
+ return false;
1036
+ }
1037
+ // If it's the same thing, then always fine to remove.
1038
+ if (other.matches(this)) {
1039
+ return true;
1040
+ }
1041
+ // If the other thing can't replace this, then skip it.
1042
+ if (!other.canReplace(this)) {
1043
+ return false;
1044
+ }
1045
+ // Patch replacing
1046
+ // if (preferDedupe || semver.gte(other.version, this.version)) {
1047
+ // return true
1048
+ // }
1049
+ // is based on https://github.com/npm/cli/pull/7025.
1050
+ //
1051
+ // If we prefer dedupe, or if the version is equal, take the other.
1052
+ if (preferDedupe || _semver.eq(other.version, this.version)) {
1053
+ return true;
1054
+ }
1055
+ // If our current version isn't the result of an override, then prefer to
1056
+ // take the greater version.
1057
+ if (!this.overridden && _semver.gt(other.version, this.version)) {
1058
+ return true;
1059
+ }
1060
+ return false;
1061
+ }
1062
+
1063
+ // Is it safe to replace one node with another? check the edges to
1064
+ // make sure no one will get upset. Note that the node might end up
1065
+ // having its own unmet dependencies, if the new node has new deps.
1066
+ // Note that there are cases where Arborist will opt to insert a node
1067
+ // into the tree even though this function returns false! This is
1068
+ // necessary when a root dependency is added or updated, or when a
1069
+ // root dependency brings peer deps along with it. In that case, we
1070
+ // will go ahead and create the invalid state, and then try to resolve
1071
+ // it with more tree construction, because it's a user request.
1072
+ canReplaceWith(node, ignorePeers) {
1073
+ if (this.name !== node.name || this.packageName !== node.packageName) {
1074
+ return false;
1075
+ }
1076
+ // Patch replacing
1077
+ // if (node.overrides !== this.overrides) {
1078
+ // return false
1079
+ // }
1080
+ // is based on https://github.com/npm/cli/pull/7025.
1081
+ //
1082
+ // If this node has no dependencies, then it's irrelevant to check the
1083
+ // override rules of the replacement node.
1084
+ if (this.edgesOut.size) {
1085
+ // XXX need to check for two root nodes?
1086
+ if (node.overrides) {
1087
+ if (!node.overrides.isEqual(this.overrides)) {
1088
+ return false;
1089
+ }
1090
+ } else {
1091
+ if (this.overrides) {
1092
+ return false;
1093
+ }
1094
+ }
1095
+ }
1096
+ // To satisfy the patch we ensure `node.overrides === this.overrides`
1097
+ // so that the condition we want to replace,
1098
+ // if (this.overrides !== node.overrides) {
1099
+ // , is not hit.`
1100
+ const oldOverrideSet = this.overrides;
1101
+ let result = true;
1102
+ if (oldOverrideSet !== node.overrides) {
1103
+ this.overrides = node.overrides;
1104
+ }
1105
+ try {
1106
+ result = super.canReplaceWith(node, ignorePeers);
1107
+ this.overrides = oldOverrideSet;
1108
+ } catch (e) {
1109
+ this.overrides = oldOverrideSet;
1110
+ throw e;
1111
+ }
1112
+ return result;
1113
+ }
1114
+ deleteEdgeIn(edge) {
1115
+ this.edgesIn.delete(edge);
1116
+ const {
1117
+ overrides
1118
+ } = edge;
1119
+ if (overrides) {
1120
+ this.updateOverridesEdgeInRemoved(overrides);
1121
+ }
1122
+ }
1123
+ addEdgeIn(edge) {
1124
+ // Patch replacing
1125
+ // if (edge.overrides) {
1126
+ // this.overrides = edge.overrides
1127
+ // }
1128
+ // is based on https://github.com/npm/cli/pull/7025.
1129
+ //
1130
+ // We need to handle the case where the new edge in has an overrides field
1131
+ // which is different from the current value.
1132
+ if (!this.overrides || !this.overrides.isEqual(edge.overrides)) {
1133
+ this.updateOverridesEdgeInAdded(edge.overrides);
1134
+ }
1135
+ this.edgesIn.add(edge);
1136
+ // Try to get metadata from the yarn.lock file.
1137
+ this.root.meta?.addEdge(edge);
1138
+ }
1139
+
1140
+ // @ts-ignore: Incorrectly typed as a property instead of an accessor.
1141
+ get overridden() {
1142
+ // Patch replacing
1143
+ // return !!(this.overrides && this.overrides.value && this.overrides.name === this.name)
1144
+ // is based on https://github.com/npm/cli/pull/7025.
1145
+ if (!this.overrides || !this.overrides.value || this.overrides.name !== this.name) {
1146
+ return false;
1147
+ }
1148
+ // The overrides rule is for a package with this name, but some override rules
1149
+ // only apply to specific versions. To make sure this package was actually
1150
+ // overridden, we check whether any edge going in had the rule applied to it,
1151
+ // in which case its overrides set is different than its source node.
1152
+ for (const edge of this.edgesIn) {
1153
+ if (edge.overrides && edge.overrides.name === this.name && edge.overrides.value === this.version) {
1154
+ if (!edge.overrides?.isEqual(edge.from?.overrides)) {
1155
+ return true;
1156
+ }
1157
+ }
1158
+ }
1159
+ return false;
1160
+ }
1161
+
1162
+ // Patch adding recalculateOutEdgesOverrides is based on
1163
+ // https://github.com/npm/cli/pull/7025.
1164
+ recalculateOutEdgesOverrides() {
1165
+ // For each edge out propagate the new overrides through.
1166
+ for (const edge of this.edgesOut.values()) {
1167
+ edge.reload(true);
1168
+ if (edge.to) {
1169
+ edge.to.updateOverridesEdgeInAdded(edge.overrides);
1170
+ }
1171
+ }
1172
+ }
1173
+
1174
+ // @ts-ignore: Incorrectly typed to accept null.
1175
+ set root(newRoot) {
1176
+ // Patch removing
1177
+ // if (!this.overrides && this.parent && this.parent.overrides) {
1178
+ // this.overrides = this.parent.overrides.getNodeRule(this)
1179
+ // }
1180
+ // is based on https://github.com/npm/cli/pull/7025.
1181
+ //
1182
+ // The "root" setter is a really large and complex function. To satisfy the
1183
+ // patch we add a dummy value to `this.overrides` so that the condition we
1184
+ // want to remove,
1185
+ // if (!this.overrides && this.parent && this.parent.overrides) {
1186
+ // , is not hit.
1187
+ if (!this.overrides) {
1188
+ this.overrides = new OverrideSet({
1189
+ overrides: ''
1190
+ });
1191
+ }
1192
+ try {
1193
+ super.root = newRoot;
1194
+ this.overrides = undefined;
1195
+ } catch (e) {
1196
+ this.overrides = undefined;
1197
+ throw e;
1198
+ }
1199
+ }
1200
+
1201
+ // Patch adding updateOverridesEdgeInAdded is based on
1202
+ // https://github.com/npm/cli/pull/7025.
1203
+ //
1204
+ // This logic isn't perfect either. When we have two edges in that have
1205
+ // different override sets, then we have to decide which set is correct. This
1206
+ // function assumes the more specific override set is applicable, so if we have
1207
+ // dependencies A->B->C and A->C and an override set that specifies what happens
1208
+ // for C under A->B, this will work even if the new A->C edge comes along and
1209
+ // tries to change the override set. The strictly correct logic is not to allow
1210
+ // two edges with different overrides to point to the same node, because even
1211
+ // if this node can satisfy both, one of its dependencies might need to be
1212
+ // different depending on the edge leading to it. However, this might cause a
1213
+ // lot of duplication, because the conflict in the dependencies might never
1214
+ // actually happen.
1215
+ updateOverridesEdgeInAdded(otherOverrideSet) {
1216
+ if (!otherOverrideSet) {
1217
+ // Assuming there are any overrides at all, the overrides field is never
1218
+ // undefined for any node at the end state of the tree. So if the new edge's
1219
+ // overrides is undefined it will be updated later. So we can wait with
1220
+ // updating the node's overrides field.
1221
+ return false;
1222
+ }
1223
+ if (!this.overrides) {
1224
+ this.overrides = otherOverrideSet;
1225
+ this.recalculateOutEdgesOverrides();
1226
+ return true;
1227
+ }
1228
+ if (this.overrides.isEqual(otherOverrideSet)) {
1229
+ return false;
1230
+ }
1231
+ const newOverrideSet = findSpecificOverrideSet(this.overrides, otherOverrideSet);
1232
+ if (newOverrideSet) {
1233
+ if (this.overrides.isEqual(newOverrideSet)) {
1234
+ return false;
1235
+ }
1236
+ this.overrides = newOverrideSet;
1237
+ this.recalculateOutEdgesOverrides();
1238
+ return true;
1239
+ }
1240
+ // This is an error condition. We can only get here if the new override set
1241
+ // is in conflict with the existing.
1242
+ log.silly('Conflicting override sets', this.name);
1243
+ return false;
1244
+ }
1245
+
1246
+ // Patch adding updateOverridesEdgeInRemoved is based on
1247
+ // https://github.com/npm/cli/pull/7025.
1248
+ updateOverridesEdgeInRemoved(otherOverrideSet) {
1249
+ // If this edge's overrides isn't equal to this node's overrides,
1250
+ // then removing it won't change newOverrideSet later.
1251
+ if (!this.overrides || !this.overrides.isEqual(otherOverrideSet)) {
1252
+ return false;
1253
+ }
1254
+ let newOverrideSet;
1255
+ for (const edge of this.edgesIn) {
1256
+ const {
1257
+ overrides: edgeOverrides
1258
+ } = edge;
1259
+ if (newOverrideSet && edgeOverrides) {
1260
+ newOverrideSet = findSpecificOverrideSet(edgeOverrides, newOverrideSet);
1261
+ } else {
1262
+ newOverrideSet = edgeOverrides;
1263
+ }
1264
+ }
1265
+ if (this.overrides.isEqual(newOverrideSet)) {
1266
+ return false;
1267
+ }
1268
+ this.overrides = newOverrideSet;
1269
+ if (newOverrideSet) {
1270
+ // Optimization: If there's any override set at all, then no non-extraneous
1271
+ // node has an empty override set. So if we temporarily have no override set
1272
+ // (for example, we removed all the edges in), there's no use updating all
1273
+ // the edges out right now. Let's just wait until we have an actual override
1274
+ // set later.
1275
+ this.recalculateOutEdgesOverrides();
1276
+ }
1277
+ return true;
1278
+ }
1279
+ }
1280
+
1281
+ // Implementation code not related to patch https://github.com/npm/cli/pull/7025
1282
+ // is based on https://github.com/npm/cli/blob/v10.9.0/workspaces/arborist/lib/override-set.js:
1283
+ class SafeOverrideSet extends OverrideSet {
1284
+ // Patch adding childrenAreEqual is based on
1285
+ // https://github.com/npm/cli/pull/7025.
1286
+ childrenAreEqual(otherOverrideSet) {
1287
+ const queue = [[this, otherOverrideSet]];
1288
+ let pos = 0;
1289
+ let {
1290
+ length: queueLength
1291
+ } = queue;
1292
+ while (pos < queueLength) {
1293
+ if (pos === _constants$1.LOOP_SENTINEL) {
1294
+ throw new Error('Detected infinite loop while comparing override sets');
1295
+ }
1296
+ const {
1297
+ 0: currSet,
1298
+ 1: currOtherSet
1299
+ } = queue[pos++];
1300
+ const {
1301
+ children
1302
+ } = currSet;
1303
+ const {
1304
+ children: otherChildren
1305
+ } = currOtherSet;
1306
+ if (children.size !== otherChildren.size) {
1307
+ return false;
1308
+ }
1309
+ for (const key of children.keys()) {
1310
+ if (!otherChildren.has(key)) {
1311
+ return false;
1312
+ }
1313
+ const child = children.get(key);
1314
+ const otherChild = otherChildren.get(key);
1315
+ if (child.value !== otherChild.value) {
1316
+ return false;
1317
+ }
1318
+ queue[queueLength++] = [child, otherChild];
1319
+ }
1320
+ }
1321
+ return true;
1322
+ }
1323
+ getEdgeRule(edge) {
1324
+ for (const rule of this.ruleset.values()) {
1325
+ if (rule.name !== edge.name) {
1326
+ continue;
1327
+ }
1328
+ // If keySpec is * we found our override.
1329
+ if (rule.keySpec === '*') {
1330
+ return rule;
1331
+ }
1332
+ // Patch replacing
1333
+ // let spec = npa(`${edge.name}@${edge.spec}`)
1334
+ // is based on https://github.com/npm/cli/pull/7025.
1335
+ //
1336
+ // We need to use the rawSpec here, because the spec has the overrides
1337
+ // applied to it already.
1338
+ let spec = _npmPackageArg(`${edge.name}@${edge.rawSpec}`);
1339
+ if (spec.type === 'alias') {
1340
+ spec = spec.subSpec;
1341
+ }
1342
+ if (spec.type === 'git') {
1343
+ if (spec.gitRange && rule.keySpec && _semver.intersects(spec.gitRange, rule.keySpec)) {
1344
+ return rule;
1345
+ }
1346
+ continue;
1347
+ }
1348
+ if (spec.type === 'range' || spec.type === 'version') {
1349
+ if (rule.keySpec && _semver.intersects(spec.fetchSpec, rule.keySpec)) {
1350
+ return rule;
1351
+ }
1352
+ continue;
1353
+ }
1354
+ // If we got this far, the spec type is one of tag, directory or file
1355
+ // which means we have no real way to make version comparisons, so we
1356
+ // just accept the override.
1357
+ return rule;
1358
+ }
1359
+ return this;
1360
+ }
1361
+
1362
+ // Patch adding isEqual is based on
1363
+ // https://github.com/npm/cli/pull/7025.
1364
+ isEqual(otherOverrideSet) {
1365
+ if (this === otherOverrideSet) {
1366
+ return true;
1367
+ }
1368
+ if (!otherOverrideSet) {
1369
+ return false;
1370
+ }
1371
+ if (this.key !== otherOverrideSet.key || this.value !== otherOverrideSet.value) {
1372
+ return false;
1373
+ }
1374
+ if (!this.childrenAreEqual(otherOverrideSet)) {
1375
+ return false;
1376
+ }
1377
+ if (!this.parent) {
1378
+ return !otherOverrideSet.parent;
1379
+ }
1380
+ return this.parent.isEqual(otherOverrideSet.parent);
1381
+ }
1382
+ }
1383
+
1384
+ // Implementation code not related to our custom behavior is based on
1385
+ // https://github.com/npm/cli/blob/v10.9.0/workspaces/arborist/lib/arborist/index.js:
1386
+ class SafeArborist extends Arborist {
1387
+ constructor(...ctorArgs) {
1388
+ const mutedArguments = [{
1389
+ ...ctorArgs[0],
1390
+ audit: true,
1391
+ dryRun: true,
1392
+ ignoreScripts: true,
1393
+ save: false,
1394
+ saveBundle: false,
1395
+ // progress: false,
1396
+ fund: false
1397
+ }, ctorArgs.slice(1)];
1398
+ super(...mutedArguments);
1399
+ this[kCtorArgs] = ctorArgs;
1400
+ }
1401
+ async [kRiskyReify](...args) {
1402
+ // SafeArborist has suffered side effects and must be rebuilt from scratch.
1403
+ const arb = new Arborist(...this[kCtorArgs]);
1404
+ const ret = await arb.reify(...args);
1405
+ Object.assign(this, arb);
1406
+ return ret;
1407
+ }
1408
+
1409
+ // @ts-ignore Incorrectly typed.
1410
+ async reify(...args) {
1411
+ const options = args[0] ? {
1412
+ ...args[0]
1413
+ } : {};
1414
+ if (options.dryRun) {
1415
+ return await this[kRiskyReify](...args);
1416
+ }
1417
+ const old = {
1418
+ ...options,
1419
+ dryRun: false,
1420
+ save: Boolean(options['save'] ?? true),
1421
+ saveBundle: Boolean(options['saveBundle'] ?? false)
1422
+ };
1423
+ args[0] = options;
1424
+ options.dryRun = true;
1425
+ options['save'] = false;
1426
+ options['saveBundle'] = false;
1427
+ // TODO: Make this deal w/ any refactor to private fields by punching the
1428
+ // class itself.
1429
+ await super.reify(...args);
1430
+ const diff = walk(this['diff']);
1431
+ options.dryRun = old.dryRun;
1432
+ options['save'] = old.save;
1433
+ options['saveBundle'] = old.saveBundle;
1434
+ // Nothing to check, mmm already installed or all private?
1435
+ if (diff.findIndex(c => c.repository_url === _constants$1.NPM_REGISTRY_URL) === -1) {
1436
+ return await this[kRiskyReify](...args);
1437
+ }
1438
+ let proceed = _constants$1.ENV[_constants$1.UPDATE_SOCKET_OVERRIDES_IN_PACKAGE_LOCK_FILE];
1439
+ if (!proceed) {
1440
+ proceed = await ttyServer.captureTTY(async (input, output) => {
1441
+ if (input && output) {
1442
+ const risky = await packagesHaveRiskyIssues(this, this['registry'], diff, output);
1443
+ if (!risky) {
1444
+ return true;
1445
+ }
1446
+ const rlin = new _nodeStream.PassThrough();
1447
+ input.pipe(rlin);
1448
+ const rlout = new _nodeStream.PassThrough();
1449
+ rlout.pipe(output, {
1450
+ end: false
1451
+ });
1452
+ const rli = _nodeReadline.createInterface(rlin, rlout);
1453
+ try {
1454
+ while (true) {
1455
+ // eslint-disable-next-line no-await-in-loop
1456
+ const answer = await new Promise(resolve => {
1457
+ rli.question('Accept risks of installing these packages (y/N)?\n', {
1458
+ signal: abortSignal
1459
+ }, resolve);
1460
+ });
1461
+ if (/^\s*y(?:es)?\s*$/i.test(answer)) {
1462
+ return true;
1463
+ }
1464
+ if (/^(?:\s*no?\s*|)$/i.test(answer)) {
1465
+ return false;
1466
+ }
1467
+ }
1468
+ } finally {
1469
+ rli.close();
1470
+ }
1471
+ } else if (await packagesHaveRiskyIssues(this, this['registry'], diff, output)) {
1472
+ throw new Error('Socket npm Unable to prompt to accept risk, need TTY to do so');
1473
+ }
1474
+ return true;
1475
+ });
1476
+ }
1477
+ if (proceed) {
1478
+ return await this[kRiskyReify](...args);
1479
+ } else {
1480
+ throw new Error('Socket npm exiting due to risks');
1481
+ }
1482
+ }
1483
+ }
1484
+ arborist.SafeArborist = SafeArborist;
1485
+ function installSafeArborist() {
1486
+ const cache = require.cache;
1487
+ cache[arboristClassPath] = {
1488
+ exports: SafeArborist
1489
+ };
1490
+ cache[arboristEdgeClassPath] = {
1491
+ exports: SafeEdge
1492
+ };
1493
+ cache[arboristNodeClassPath] = {
1494
+ exports: SafeNode
1495
+ };
1496
+ cache[arboristOverrideSetClassPatch] = {
1497
+ exports: SafeOverrideSet
1498
+ };
1499
+ }
1500
+ void (async () => {
1501
+ const remoteSettings = await (async () => {
1502
+ try {
1503
+ const socketSdk = await (0, _sdk.setupSdk)(pubToken);
1504
+ const orgResult = await socketSdk.getOrganizations();
1505
+ if (!orgResult.success) {
1506
+ throw new Error(`Failed to fetch Socket organization info: ${orgResult.error.message}`);
1507
+ }
1508
+ const orgs = [];
1509
+ for (const org of Object.values(orgResult.data.organizations)) {
1510
+ if (org) {
1511
+ orgs.push(org);
1512
+ }
1513
+ }
1514
+ const result = await socketSdk.postSettings(orgs.map(org => ({
1515
+ organization: org.id
1516
+ })));
1517
+ if (!result.success) {
1518
+ throw new Error(`Failed to fetch API key settings: ${result.error.message}`);
1519
+ }
1520
+ return {
1521
+ orgs,
1522
+ settings: result.data
1523
+ };
1524
+ } catch (e) {
1525
+ if ((0, _objects.isObject)(e) && 'cause' in e) {
1526
+ const {
1527
+ cause
1528
+ } = e;
1529
+ if ((0, _misc.isErrnoException)(cause)) {
1530
+ if (cause.code === 'ENOTFOUND' || cause.code === 'ECONNREFUSED') {
1531
+ throw new Error('Unable to connect to socket.dev, ensure internet connectivity before retrying', {
1532
+ cause: e
1533
+ });
1534
+ }
1535
+ }
1536
+ }
1537
+ throw e;
1538
+ }
1539
+ })();
1540
+ const {
1541
+ orgs,
1542
+ settings
1543
+ } = remoteSettings;
1544
+ const enforcedOrgs = (0, _settings.getSetting)('enforcedOrgs') ?? [];
1545
+
1546
+ // Remove any organizations not being enforced.
1547
+ for (const {
1548
+ 0: i,
1549
+ 1: org
1550
+ } of orgs.entries()) {
1551
+ if (!enforcedOrgs.includes(org.id)) {
1552
+ settings.entries.splice(i, 1);
1553
+ }
1554
+ }
1555
+ const socketYml = findSocketYmlSync();
1556
+ if (socketYml) {
1557
+ settings.entries.push({
1558
+ start: socketYml.path,
1559
+ settings: {
1560
+ [socketYml.path]: {
1561
+ deferTo: null,
1562
+ // TODO: TypeScript complains about the type not matching. We should
1563
+ // figure out why are providing
1564
+ // issueRules: { [issueName: string]: boolean }
1565
+ // but expecting
1566
+ // issueRules: { [issueName: string]: { action: 'defer' | 'error' | 'ignore' | 'monitor' | 'warn' } }
1567
+ issueRules: socketYml.parsed.issueRules
1568
+ }
1569
+ }
1570
+ });
1571
+ }
1572
+ _uxLookup = (0, _issueRules.createIssueUXLookup)(settings);
1573
+ })();
1574
+
1575
+ var _constants = constants.constants;
1576
+ var _arborist = arborist;
1577
+ var _link = link.link;
1578
+ // Shadow `npm` and `npx` to mitigate subshells.
1579
+ (0, _link.installLinks)(_constants.shadowBinPath, 'npm');
1580
+ (0, _arborist.installSafeArborist)();
1581
+
1582
+ (function (exports) {
1583
+
1584
+ var _interopRequireWildcard = require$$0$2.default;
1585
+ Object.defineProperty(exports, "__esModule", {
1586
+ value: true
1587
+ });
1588
+ var _exportNames = {};
1589
+ Object.defineProperty(exports, "default", {
1590
+ enumerable: true,
1591
+ get: function () {
1592
+ return _npmInjection.default;
1593
+ }
1594
+ });
1595
+ var _npmInjection = _interopRequireWildcard(npmInjection$1, true);
1596
+ Object.keys(_npmInjection).forEach(function (key) {
1597
+ if (key === "default" || key === "__esModule") return;
1598
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
1599
+ if (key in exports && exports[key] === _npmInjection[key]) return;
1600
+ Object.defineProperty(exports, key, {
1601
+ enumerable: true,
1602
+ get: function () {
1603
+ return _npmInjection[key];
1604
+ }
1605
+ });
1606
+ });
1607
+ } (npmInjection$2));
1608
+
1609
+ var npmInjection = /*@__PURE__*/constants.getDefaultExportFromCjs(npmInjection$2);
1610
+
1611
+ module.exports = npmInjection;