package-management 0.0.8 → 0.0.10

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/dist/index.cjs DELETED
@@ -1,1006 +0,0 @@
1
- 'use strict';
2
-
3
- const ErrorStackParser = require('error-stack-parser');
4
- const path = require('pathe');
5
- const process = require('node:process');
6
- const path$1 = require('node:path');
7
- const node_fs = require('node:fs');
8
- const execa = require('execa');
9
- const asyncCacheFn = require('async-cache-fn');
10
- const findUp = require('find-up');
11
- const promises = require('node:fs/promises');
12
- const mlly = require('mlly');
13
- const globby = require('globby');
14
- const gitignoreParser = require('parse-gitignore');
15
- const WST = require('workspace-tools');
16
- const utils = require('pathe/utils');
17
- const os = require('node:os');
18
-
19
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
20
-
21
- function _interopNamespaceCompat(e) {
22
- if (e && typeof e === 'object' && 'default' in e) return e;
23
- const n = Object.create(null);
24
- if (e) {
25
- for (const k in e) {
26
- n[k] = e[k];
27
- }
28
- }
29
- n.default = e;
30
- return n;
31
- }
32
-
33
- const ErrorStackParser__default = /*#__PURE__*/_interopDefaultCompat(ErrorStackParser);
34
- const path__default$1 = /*#__PURE__*/_interopDefaultCompat(path);
35
- const process__default = /*#__PURE__*/_interopDefaultCompat(process);
36
- const path__default = /*#__PURE__*/_interopDefaultCompat(path$1);
37
- const gitignoreParser__default = /*#__PURE__*/_interopDefaultCompat(gitignoreParser);
38
- const WST__namespace = /*#__PURE__*/_interopNamespaceCompat(WST);
39
- const os__default = /*#__PURE__*/_interopDefaultCompat(os);
40
-
41
- const toArray = (data) => Array.isArray(data) ? data : [data];
42
- const entriesOf = (o) => Object.entries(o);
43
- const fromEntries = (entries) => Object.fromEntries(entries);
44
- const notFalsy = (value) => [false, null, void 0].every((v) => v !== value);
45
- const select = (obj, selection, mode) => {
46
- if (!selection)
47
- return obj;
48
- const filtered = entriesOf(obj).filter(([key]) => {
49
- return mode === "omit" ? !selection[key] : selection[key];
50
- });
51
- return fromEntries(filtered);
52
- };
53
- function normalizePath(path$1, option) {
54
- if (typeof option === "function") {
55
- return normalizePath(path$1);
56
- }
57
- if (option === false) {
58
- return path$1;
59
- }
60
- return path.normalize(path$1);
61
- }
62
- const invariant = (predicate, message) => {
63
- if (!predicate) {
64
- throw new Error(message);
65
- }
66
- };
67
- function getArrayItemAtOffset(arr, index, offset = 0) {
68
- if (!index || !arr)
69
- return void 0;
70
- return arr[index + offset];
71
- }
72
- function isMatching(a, b) {
73
- if (!a || !b)
74
- return false;
75
- return a === b;
76
- }
77
-
78
- function findCallerStackFrame(options) {
79
- return findErrorStackFrame(options, (frame) => frame.isParentOfRootFunction);
80
- }
81
- function findErrorStackFrame(options, find) {
82
- return getErrorStackFrames(options, find)[0];
83
- }
84
- function getErrorStackFrames(options, filter) {
85
- const { error, rootFunctionName, startFrom = "top" } = options;
86
- const frames = startFrom === "bottom" ? ErrorStackParser__default.parse(error).reverse() : ErrorStackParser__default.parse(error);
87
- const { parsedFrames } = frames.reduce(
88
- (acc, frame, index) => {
89
- const parsed = parseFrame({
90
- frame,
91
- index,
92
- rootFunctionName,
93
- frames
94
- });
95
- const isValid = filter ? filter(parsed) : true;
96
- if (isValid) {
97
- acc.parsedFrames.push(parsed);
98
- }
99
- return acc;
100
- },
101
- { parsedFrames: [] }
102
- );
103
- return parsedFrames ?? [];
104
- }
105
- function parseFrame(options) {
106
- const { frame, frames, index, rootFunctionName, cwd, debug } = options ?? {};
107
- const functionName = parseFunctionName(frame.functionName);
108
- const isRootFunction = isMatching(functionName, rootFunctionName);
109
- const beforeFrameFunctionName = parseFunctionName(
110
- getArrayItemAtOffset(frames, index, -1)?.functionName
111
- );
112
- const isParentOfRootFunction = isMatching(
113
- beforeFrameFunctionName,
114
- rootFunctionName
115
- );
116
- const fileData = frame.fileName ? getFilePathData({ filepath: frame.fileName, cwd }) : void 0;
117
- const { isFileInCwd: isFrameInScope, ...restFileData } = fileData ?? {};
118
- const data = {
119
- ...restFileData,
120
- functionName,
121
- source: frame.source,
122
- sourceFunctionName: frame.functionName,
123
- isFrameInScope,
124
- place: placeFormatter(index, frames?.length),
125
- isRootFunction,
126
- isParentOfRootFunction,
127
- rootFunctionName
128
- };
129
- debug && console.log(data);
130
- return data;
131
- }
132
- function getFilePathData({
133
- filepath,
134
- cwd
135
- }) {
136
- const workingDir = cwd ?? process__default.cwd();
137
- const filePath = path.normalize(filepath);
138
- const fileBasename = path.basename(filePath);
139
- const dirPath = path.dirname(filePath);
140
- const dirBasename = path.basename(dirPath);
141
- const relativeFilePath = path.relative(workingDir, filePath);
142
- const relativeDirPath = path.dirname(relativeFilePath);
143
- const isFileInCwd = filePath.startsWith(workingDir);
144
- return {
145
- filePath,
146
- dirPath,
147
- relativeFilePath,
148
- relativeDirPath,
149
- fileBasename,
150
- dirBasename,
151
- isFileInCwd
152
- };
153
- }
154
- function parseFunctionName(functionName) {
155
- if (!functionName)
156
- return void 0;
157
- return removeStart(functionName, "Module.");
158
- }
159
- function removeStart(input, value) {
160
- return input.startsWith(value) ? input.slice(value.length) : input;
161
- }
162
- function placeFormatter(index, total) {
163
- if (!index || !total)
164
- return void 0;
165
- return [index, total].join("/");
166
- }
167
-
168
- const _filename = (options) => {
169
- const { filePath } = findCallerStackFrame({ error: new Error(), ...options }) ?? {};
170
- return filePath;
171
- };
172
- const _dirname = (options) => {
173
- const { dirPath } = findCallerStackFrame({ error: new Error(), ...options }) ?? {};
174
- return dirPath;
175
- };
176
-
177
- async function resolveModule(module) {
178
- const resolved = await module;
179
- return resolved.default || resolved;
180
- }
181
- function isPackageModuleFound(name, options) {
182
- return Boolean(resolvePackageModulePath(name, options));
183
- }
184
- function resolvePackageModulePath(name, options) {
185
- const resolvedPath = findResolvedModulePath(
186
- [`${name}/package.json`, name],
187
- options
188
- );
189
- if (resolvedPath === void 0) {
190
- console.error(`Could not resolve package ${name}`);
191
- return void 0;
192
- }
193
- return resolvedPath;
194
- }
195
- function findResolvedModulePath(paths, options) {
196
- for (const path of paths) {
197
- const resolvedPath = resolveModulePath(path, options);
198
- if (resolvedPath === void 0)
199
- continue;
200
- return resolvedPath;
201
- }
202
- }
203
- function resolveModulePath(modulePath, options) {
204
- const { normalize = true, paths, ...rest } = options ?? {};
205
- try {
206
- const path = normalizePath(modulePath, normalize);
207
- return mlly.resolvePathSync(path, {
208
- url: paths,
209
- ...rest
210
- });
211
- } catch (e) {
212
- return void 0;
213
- }
214
- }
215
-
216
- const tsconfig = (tsconfigDir) => ({
217
- get paths() {
218
- return globby.globbySync(["tsconfig.json", "tsconfig.*.json"], {
219
- cwd: tsconfigDir
220
- }) ?? [];
221
- }
222
- });
223
-
224
- function parseGitignoreFile(gitignorePath, options) {
225
- return gitignoreParser__default(gitignorePath, options);
226
- }
227
- function getGitignoreData(gitignorePath) {
228
- const gitignoreFileContent = node_fs.readFileSync(gitignorePath, "utf-8");
229
- const gitignores = parseGitignoreFile(gitignoreFileContent);
230
- return gitignores;
231
- }
232
- const gitignore = (gitignorePath) => ({
233
- get data() {
234
- return getGitignoreData(gitignorePath);
235
- },
236
- get patterns() {
237
- return getGitignoreData(gitignorePath).patterns;
238
- }
239
- });
240
-
241
- const dependencyTypeMap = {
242
- dependency: "dependencies",
243
- devDependency: "devDependencies",
244
- peerDependency: "peerDependencies",
245
- optionalDependency: "optionalDependencies"
246
- };
247
-
248
- function isDependencyInPackageJson(options, packageJson) {
249
- return Boolean(findDependencyInPackageJson(options, packageJson));
250
- }
251
- function findDependencyInPackageJson(option, packageJson) {
252
- const { name, type } = typeof option === "string" ? { name: option, type: void 0 } : option;
253
- if (!packageJson)
254
- return void 0;
255
- const allowedTypes = typeof type === "string" ? {
256
- [type]: true
257
- } : type ?? {
258
- dependency: true,
259
- devDependency: true
260
- };
261
- const allowedDependencyTypes = getAllowedDependencyTypeList(allowedTypes);
262
- const matches = allowedDependencyTypes.map((type2) => {
263
- return getPackageJsonDependencyItem({ name, type: type2 }, packageJson);
264
- }).filter(notFalsy);
265
- if (matches.length === 0)
266
- return void 0;
267
- return {
268
- firstMatch: matches[0],
269
- matches
270
- };
271
- }
272
- function getPackageJsonDependencyItem({
273
- name,
274
- type
275
- }, packageJson) {
276
- if (!packageJson)
277
- return void 0;
278
- const dependencyMap = getPackageJsonDependencyMap(type, packageJson);
279
- const version = dependencyMap?.[name];
280
- if (version === void 0)
281
- return void 0;
282
- return {
283
- name,
284
- version,
285
- type
286
- };
287
- }
288
- function getAllowedDependencyTypeList(selected) {
289
- return Object.keys(dependencyTypeMap).filter(
290
- (key) => selected[key]
291
- );
292
- }
293
- function getPackageJsonDependencyMap(type, packageJson) {
294
- return packageJson[dependencyTypeMap[type]];
295
- }
296
-
297
- function getWorkspaceFolder(options) {
298
- const {
299
- cwd = process__default.cwd(),
300
- fallbackToGitRoot = true,
301
- throwIfNotFound = true
302
- } = options ?? {};
303
- const getFolder = fallbackToGitRoot ? WST__namespace.findProjectRoot : WST__namespace.getWorkspaceRoot;
304
- const folder = getFolder(cwd);
305
- if (folder === void 0 && throwIfNotFound) {
306
- throw new Error(`Could not find workspace folder`);
307
- }
308
- return folder;
309
- }
310
-
311
- function getPackageFolder(options) {
312
- return WST__namespace.findPackageRoot(options?.cwd ?? process__default.cwd());
313
- }
314
-
315
- function getPackageInfo(options) {
316
- const packageDir = getPackageFolder(options);
317
- return readPackageInfo({ packageDir });
318
- }
319
- function readPackageInfo({
320
- packageDir
321
- }) {
322
- const packageJsonPath = path__default.join(packageDir, "package.json");
323
- const packageJson = JSON.parse(
324
- node_fs.readFileSync(packageJsonPath, "utf-8")
325
- );
326
- return {
327
- name: packageJson.name,
328
- path: packageJsonPath,
329
- dirpath: packageDir,
330
- packageJson
331
- };
332
- }
333
-
334
- function getWorkspaceProjectInfo(options) {
335
- try {
336
- const workspaceDir = getWorkspaceFolder(options);
337
- return readPackageInfo({ packageDir: workspaceDir });
338
- } catch (e) {
339
- console.error(e);
340
- throw new Error("Root workspace not found");
341
- }
342
- }
343
-
344
- function getWorkspacePackageInfoList(options) {
345
- const { workspaceDir, resolveWstList } = common(options);
346
- const wstList = WST__namespace.getWorkspaces(workspaceDir);
347
- return resolveWstList(wstList);
348
- }
349
- function common(options) {
350
- const { cwd, includeRoot: includeWorkspace } = options ?? {};
351
- const workspaceDir = getWorkspaceFolder({ cwd });
352
- function resolveWstList(list) {
353
- if (!workspaceDir)
354
- return [];
355
- if (includeWorkspace)
356
- return [getWorkspaceProjectInfo(), ...list];
357
- return list;
358
- }
359
- return {
360
- workspaceDir,
361
- includeWorkspace,
362
- resolveWstList
363
- };
364
- }
365
-
366
- function getWorkspacePackageInfoMap(options) {
367
- const workspaceInfo = getWorkspacePackageInfoList(options);
368
- const entries = workspaceInfo.map((info) => [info.name, info]);
369
- return Object.fromEntries(entries);
370
- }
371
-
372
- function getProjectInfoByName(name, options) {
373
- const { cwd } = options ?? {};
374
- return getWorkspacePackageInfoMap({ cwd })[name];
375
- }
376
-
377
- function getProjectInfo(folder, options) {
378
- if (isWorkspaceFolderTypeOption(folder)) {
379
- return getWorkspaceProjectInfo(
380
- parseWorkspaceFolderTypeOptions(folder, options)
381
- );
382
- }
383
- if (folder === "<package_folder>") {
384
- return getPackageInfo(options);
385
- }
386
- if (folder === "<gitroot_folder>") {
387
- return getPackageInfo(options);
388
- }
389
- return getProjectInfoByName(folder.packageName, options);
390
- }
391
- function isWorkspaceFolderTypeOption(option) {
392
- return Boolean(
393
- option === "<workspace_folder>" || typeof option === "object" && "<workspace_folder>" in option
394
- );
395
- }
396
- function parseWorkspaceFolderTypeOptions(option, defaultOptions) {
397
- if (typeof option === "string") {
398
- return defaultOptions ?? {};
399
- }
400
- return { ...defaultOptions, ...option["<workspace_folder>"] };
401
- }
402
- getProjectInfo({
403
- "<workspace_folder>": {}
404
- });
405
-
406
- const project = (...args) => {
407
- const [source, projectOptions] = args;
408
- const { packageJson, packageJsonPath, packageName, projectDir } = info();
409
- const {
410
- findPackageManager: findPackageManager2,
411
- detectPackageManagers,
412
- detectLockfilePackageManagers,
413
- detectGlobalPackageManagers,
414
- filterPackageManagers
415
- } = definePackageManagerClient({ cwd: projectDir });
416
- return {
417
- packageJson,
418
- packageJsonPath,
419
- packageName,
420
- projectDir,
421
- findPackageManager: findPackageManager2,
422
- detectPackageManagers,
423
- detectGlobalPackageManagers,
424
- detectLockfilePackageManagers,
425
- tsconfig: tsconfig(projectDir ?? ""),
426
- gitignore: gitignore(path__default$1.join(projectDir ?? "", ".gitignore")),
427
- filterPackageManagers,
428
- getPackageJson: () => get("packageJson"),
429
- findDependencyInPackageJson: (options) => findDependencyInPackageJson(options, get("packageJson")),
430
- isDependencyInPackageJson: (options) => isDependencyInPackageJson(options, get("packageJson"))
431
- };
432
- function info() {
433
- const {
434
- packageJson: packageJson2,
435
- name: packageName2,
436
- dirpath: projectDir2,
437
- path: packageJsonPath2
438
- } = getProjectInfo(source, projectOptions) ?? {};
439
- return {
440
- packageJson: packageJson2,
441
- packageJsonPath: packageJsonPath2,
442
- packageName: packageName2,
443
- projectDir: projectDir2
444
- };
445
- }
446
- function get(key) {
447
- return info()[key];
448
- }
449
- };
450
-
451
- function getWorkspacePackageNames(options) {
452
- return getWorkspacePackageInfoList(options).map((e) => e.name);
453
- }
454
-
455
- const workspace = {
456
- packageNames: getWorkspacePackageNames,
457
- packageGraph: getWorkspacePackageInfoMap,
458
- packageList: getWorkspacePackageInfoList,
459
- workspaceRootDir: getWorkspaceFolder,
460
- getProject: project
461
- };
462
-
463
- function importer(imports, options) {
464
- const { install: defaultInstall = true, installer } = options ?? {};
465
- return Promise.all(
466
- imports.map(async (e) => {
467
- const importOpt = resolveImportOption(e);
468
- const shouldInstall = importOpt.install ?? defaultInstall;
469
- if (shouldInstall && importOpt.name) {
470
- await installImport(importOpt.name, importOpt, installer);
471
- }
472
- const m = await importOpt.import();
473
- return resolveModule(m);
474
- })
475
- );
476
- }
477
- const definePackage = (option) => {
478
- const { name, ...rest } = typeof option === "string" ? { name: option } : option;
479
- return {
480
- name,
481
- import: () => import(name),
482
- ...rest
483
- };
484
- };
485
- function resolveImportOption(option) {
486
- if (typeof option === "function") {
487
- return {
488
- import: option
489
- };
490
- }
491
- if (option instanceof Promise) {
492
- return {
493
- import: () => option
494
- };
495
- }
496
- return option;
497
- }
498
- async function installImport(packageName, options, installer) {
499
- if (!packageName)
500
- return;
501
- const { checkExists } = options ?? {};
502
- if (checkExists && isPackageDependency(packageName))
503
- return;
504
- const installerFn = installer ?? (await workspace.getProject("<package_folder>").findPackageManager()).installPackage;
505
- await installerFn(packageName, options);
506
- }
507
-
508
- const importMap = async (importMap2, options) => {
509
- const keys = Object.keys(importMap2);
510
- const imported = await importer(
511
- keys.map((key) => importMap2[key]),
512
- options
513
- );
514
- return Object.fromEntries(
515
- keys.map((key, index) => [key, imported[index]])
516
- );
517
- };
518
-
519
- function definePackageManager(config, options) {
520
- const { cwd: defaultCwd } = options ?? {};
521
- const { command, args: agentArgs, options: agentOptions } = config;
522
- const findLockfilePath = asyncCacheFn.asyncCacheFn(async (options2) => {
523
- const { cwd = defaultCwd } = options2 ?? {};
524
- const lockfiles = toArray(config.meta.lockfile);
525
- return await findUp.findUp(lockfiles, { cwd });
526
- });
527
- const installPackage = async (packageName, options2) => {
528
- const install = agentArgs.install;
529
- const { dev, preferOffline } = select(
530
- install.options,
531
- {
532
- preferOffline: true,
533
- cwd: defaultCwd,
534
- ...options2
535
- },
536
- "pick"
537
- );
538
- const packageNames = toArray(packageName);
539
- try {
540
- await $$({
541
- command,
542
- args: [install.command, dev, preferOffline, ...packageNames],
543
- cwd: defaultCwd,
544
- ...options2
545
- });
546
- } catch (e) {
547
- throw new Error(`Failed to install: ${packageNames.join(", ")}`);
548
- }
549
- };
550
- const uninstallPackage = async (packageName, options2) => {
551
- const uninstall = agentArgs.uninstall;
552
- await Promise.all(
553
- toArray(packageName).map(async (name) => {
554
- try {
555
- await $$({
556
- command,
557
- args: [uninstall.command, name],
558
- cwd: defaultCwd,
559
- ...options2
560
- });
561
- } catch (e) {
562
- }
563
- })
564
- );
565
- };
566
- return {
567
- id: config.id,
568
- config,
569
- findLockfilePath,
570
- hasLockfile: asyncCacheFn.asyncCacheFn(async (...args) => {
571
- const lockfilePath = await findLockfilePath.noCache(...args);
572
- return Boolean(lockfilePath);
573
- }),
574
- readLockfile: asyncCacheFn.asyncCacheFn(async (...args) => {
575
- const lockfilePath = await findLockfilePath.noCache(...args);
576
- if (!lockfilePath)
577
- return void 0;
578
- return promises.readFile(lockfilePath, "utf8");
579
- }),
580
- globalVersion: asyncCacheFn.asyncCacheFn(async (...args) => {
581
- const [options2] = args;
582
- try {
583
- const { stdout } = await $$({
584
- command,
585
- args: [agentOptions.version],
586
- cwd: defaultCwd,
587
- ...options2
588
- });
589
- return `${stdout}`;
590
- } catch (e) {
591
- return void 0;
592
- }
593
- }),
594
- definePackage,
595
- installPackage,
596
- uninstallPackage,
597
- defineImportMap(imports, options2) {
598
- const { install = true } = options2 ?? {};
599
- return importMap(imports, {
600
- install,
601
- installer: installPackage
602
- });
603
- }
604
- };
605
- }
606
- async function $$(options) {
607
- const { command, args = [], silent = true, cwd, shellOptions } = options;
608
- return execa.execa(command, args.filter(notFalsy), {
609
- cwd,
610
- ...shellOptions,
611
- stdio: silent ? "ignore" : "inherit"
612
- });
613
- }
614
-
615
- function definePackageManagerConfig(config) {
616
- return config;
617
- }
618
-
619
- const bun = definePackageManagerConfig({
620
- id: "bun",
621
- name: "Bun",
622
- command: "bun",
623
- runner: "bunx",
624
- meta: {
625
- lockfile: "bun.lockb"
626
- },
627
- args: {
628
- install: {
629
- command: "install",
630
- options: {
631
- dev: "-D",
632
- preferOffline: "--prefer-offline"
633
- }
634
- },
635
- uninstall: {
636
- command: "uninstall"
637
- }
638
- },
639
- options: {
640
- version: "--version"
641
- }
642
- });
643
-
644
- const npm = definePackageManagerConfig({
645
- id: "npm",
646
- name: "NPM",
647
- command: "npm",
648
- runner: "npx",
649
- meta: {
650
- lockfile: ["package-lock.json", "npm-shrinkwrap.json"]
651
- },
652
- args: {
653
- install: {
654
- command: "install",
655
- options: {
656
- dev: "-D",
657
- preferOffline: "--prefer-offline"
658
- }
659
- },
660
- uninstall: {
661
- command: "uninstall"
662
- }
663
- },
664
- options: {
665
- version: "--version"
666
- }
667
- });
668
-
669
- const pnpm = definePackageManagerConfig({
670
- id: "pnpm",
671
- name: "PNPM",
672
- command: "pnpm",
673
- runner: "pnpx",
674
- meta: {
675
- lockfile: "pnpm-lock.yaml"
676
- },
677
- args: {
678
- install: {
679
- command: "install",
680
- options: {
681
- dev: "-D",
682
- preferOffline: "--prefer-offline"
683
- }
684
- },
685
- uninstall: {
686
- command: "remove"
687
- }
688
- },
689
- options: {
690
- version: "--version"
691
- }
692
- });
693
-
694
- const yarn = definePackageManagerConfig({
695
- id: "yarn",
696
- name: "Yarn",
697
- command: "yarn",
698
- runner: "yarn dlx",
699
- meta: {
700
- lockfile: "yarn.lock"
701
- },
702
- args: {
703
- install: {
704
- command: "add",
705
- options: {
706
- dev: "-D",
707
- preferOffline: "--prefer-offline"
708
- }
709
- },
710
- uninstall: {
711
- command: "remove"
712
- }
713
- },
714
- options: {
715
- version: "--version"
716
- }
717
- });
718
-
719
- async function findPackageManager(packageManagers, options) {
720
- const { ...rest } = options ?? {};
721
- const packageManager = await findPackageManagerSafely(packageManagers, rest);
722
- invariant(packageManager, "No package manager found");
723
- return packageManager;
724
- }
725
- async function findPackageManagerSafely(packageManagers, options) {
726
- const lockfilePm = (await detectLockfilePackageManagers(packageManagers, options))[0];
727
- if (lockfilePm) {
728
- return lockfilePm;
729
- }
730
- const globalPm = (await detectGlobalPackageManagers(packageManagers, options))[0];
731
- return globalPm;
732
- }
733
- async function detectPackageManagers(packageManagers, options) {
734
- return [
735
- ...await detectLockfilePackageManagers(packageManagers, options),
736
- ...await detectGlobalPackageManagers(packageManagers, options)
737
- ];
738
- }
739
- async function detectLockfilePackageManagers(packageManagers, options) {
740
- return filterPackageManagers(
741
- packageManagers,
742
- (e) => e.hasLockfile(options),
743
- options
744
- );
745
- }
746
- async function detectGlobalPackageManagers(packageManagers, options) {
747
- return filterPackageManagers(
748
- packageManagers,
749
- async (e) => Boolean(e.globalVersion(options)),
750
- options
751
- );
752
- }
753
- async function filterPackageManagers(packageManagers, filterFn, options) {
754
- const allowedPackageManagers = packageManagers.filter(({ id }) => {
755
- if (!options?.allowed)
756
- return true;
757
- return id in options.allowed;
758
- });
759
- return (await Promise.all(
760
- allowedPackageManagers.map(async (pm) => {
761
- const valid = await filterFn(pm);
762
- return valid ? pm : void 0;
763
- })
764
- )).filter(notFalsy);
765
- }
766
-
767
- const packageManagerConfigs = [pnpm, yarn, bun, npm];
768
- function definePackageManagerClient(options) {
769
- const configs = packageManagerConfigs.map(
770
- (config) => definePackageManager(config, options)
771
- );
772
- return {
773
- configs,
774
- findPackageManager: asyncCacheFn.asyncCacheFn(
775
- async (options2) => await findPackageManager(configs, options2)
776
- ),
777
- findPackageManagerSafely: asyncCacheFn.asyncCacheFn(
778
- async (options2) => await findPackageManagerSafely(configs, options2)
779
- ),
780
- detectPackageManagers: asyncCacheFn.asyncCacheFn(
781
- async (options2) => await detectPackageManagers(configs, options2)
782
- ),
783
- detectLockfilePackageManagers: asyncCacheFn.asyncCacheFn(
784
- async (options2) => detectLockfilePackageManagers(configs, options2)
785
- ),
786
- detectGlobalPackageManagers: asyncCacheFn.asyncCacheFn(
787
- async (options2) => detectGlobalPackageManagers(configs, options2)
788
- ),
789
- filterPackageManagers: async (filterFn, options2) => filterPackageManagers(configs, filterFn, options2)
790
- };
791
- }
792
-
793
- function isPackageDependency(packageName) {
794
- return toArray(packageName).every((name) => isDependencyInPackageJson(name));
795
- }
796
-
797
- function definePathAliases(aliasDefinitions) {
798
- const aliasMap = getAliasMap(aliasDefinitions);
799
- function getFilePath(options, aliases) {
800
- return getAliasedFilePath(
801
- { ...aliasMap, ...aliases },
802
- options
803
- );
804
- }
805
- return {
806
- aliasDefinitions,
807
- aliasMap,
808
- getFilePath
809
- };
810
- }
811
- function getAliasedFilePath(aliasMap, options) {
812
- try {
813
- if (typeof options === "string" || Array.isArray(options)) {
814
- return resolvePathTo(options, { aliasMap });
815
- }
816
- const opts = { ...options, aliasMap };
817
- if (opts.startingFrom) {
818
- return resolveRelativePathTo(opts.to, opts.startingFrom, opts);
819
- }
820
- return resolvePathTo(opts.to, opts);
821
- } catch (e) {
822
- return void 0;
823
- }
824
- }
825
- function resolveRelativePathTo(to, from, options) {
826
- const pathFrom = resolvePathTo(from, options);
827
- const pathTo = resolvePathTo(to, options);
828
- return path__default$1.relative(pathFrom, pathTo);
829
- }
830
- function resolvePathTo(pathTo, { cwd, checkExistence, glob, aliasMap }) {
831
- const normalized = normalizePathTo(pathTo, { cwd, aliasMap });
832
- if (glob) {
833
- const globPaths = globby.globbySync(normalized, { cwd });
834
- if (!globPaths[0])
835
- throw new Error(`No paths found for glob: ${normalized}`);
836
- return globPaths[0];
837
- }
838
- if (!glob && checkExistence && !node_fs.existsSync(normalized))
839
- throw new Error(`Path does not exist: ${normalized}`);
840
- return normalized;
841
- }
842
- function normalizePathTo(pathTo, options) {
843
- const { cwd, aliasMap } = options ?? {};
844
- if (Array.isArray(pathTo)) {
845
- const [baseDir] = pathTo;
846
- const aliasedPath = path__default$1.join(...pathTo.filter(isNotNull));
847
- return utils.resolveAlias(aliasedPath, {
848
- [baseDir]: executeMapFn(aliasMap, baseDir, [{ cwd }])
849
- });
850
- }
851
- return pathTo;
852
- }
853
- function executeMapFn(map, key, args) {
854
- if (!map || !key || !(key in map))
855
- return void 0;
856
- const fnArgs = Array.isArray(args) ? args : [args];
857
- const resolver = map?.[key];
858
- return typeof resolver === "function" ? resolver?.(...fnArgs) : resolver;
859
- }
860
- function getAliasMap(aliasDefs) {
861
- return Object.fromEntries(
862
- Object.entries(aliasDefs).flatMap(([alias, v]) => {
863
- const { resolve, subpaths = [] } = v;
864
- return [
865
- [alias, resolve],
866
- ...subpaths.map(({ to }) => {
867
- const subpathAlias = path__default$1.join(alias, to);
868
- return [
869
- subpathAlias,
870
- (opts) => utils.resolveAlias(subpathAlias, { [alias]: resolve(opts) })
871
- ];
872
- })
873
- ];
874
- })
875
- );
876
- }
877
- function isNotNull(value) {
878
- return value !== null && value !== void 0;
879
- }
880
-
881
- const predefinedPathAliases = {
882
- "<workspace_folder>": {
883
- resolve: (opts) => getWorkspaceFolder(opts),
884
- subpaths: [
885
- {
886
- to: "node_modules"
887
- },
888
- {
889
- to: "node_modules/.bin"
890
- }
891
- ]
892
- },
893
- "<workspace_folder?>": {
894
- resolve: (opts) => getWorkspaceFolder(opts),
895
- subpaths: [
896
- {
897
- to: "node_modules"
898
- },
899
- {
900
- to: "node_modules/.bin"
901
- }
902
- ]
903
- },
904
- "<package_folder>": {
905
- resolve: (opts) => getPackageFolder(opts),
906
- subpaths: [
907
- {
908
- to: "node_modules"
909
- },
910
- {
911
- to: "node_modules/.bin"
912
- },
913
- {
914
- to: "src"
915
- }
916
- ]
917
- },
918
- "<gitroot_folder>": {
919
- resolve: (opts) => getGitRootFolder(opts),
920
- subpaths: [
921
- {
922
- to: "node_modules"
923
- },
924
- {
925
- to: "node_modules/.bin"
926
- },
927
- {
928
- to: ".vscode"
929
- }
930
- ]
931
- },
932
- "<user_home>": {
933
- resolve: () => os__default.homedir(),
934
- subpaths: []
935
- },
936
- "<user_tmpdir>": {
937
- resolve: () => os__default.tmpdir(),
938
- subpaths: []
939
- },
940
- "<cwd>": {
941
- resolve: () => process__default.cwd(),
942
- subpaths: []
943
- },
944
- "<current_file>": {
945
- // resolve: () => fileURLToPath(import.meta.url),
946
- resolve: () => _filename({ rootFunctionName: "getFilePath" }) ?? "",
947
- subpaths: []
948
- },
949
- "<current_folder>": {
950
- // resolve: () => fileURLToPath(import.meta.url),
951
- resolve: () => _dirname({ rootFunctionName: "getFilePath" }) ?? "",
952
- subpaths: []
953
- }
954
- };
955
-
956
- const getPath = definePathAliases(predefinedPathAliases).getFilePath;
957
-
958
- function getFolderByPackageName(name, options) {
959
- const infoMap = getWorkspacePackageInfoMap({ ...options, includeRoot: true });
960
- const info = infoMap?.[name];
961
- return info?.dirpath;
962
- }
963
-
964
- function getGitRootFolder(options) {
965
- const output = execa.execaSync(`git rev-parse --show-toplevel`, {
966
- ...options,
967
- reject: false
968
- });
969
- if (!output.stdout) {
970
- console.warn(`Directory "${output.cwd}" is not in a git repository`);
971
- return void 0;
972
- }
973
- return path__default$1.normalize(output.stdout);
974
- }
975
-
976
- exports._dirname = _dirname;
977
- exports._filename = _filename;
978
- exports.definePackage = definePackage;
979
- exports.definePackageManagerClient = definePackageManagerClient;
980
- exports.definePathAliases = definePathAliases;
981
- exports.detectGlobalPackageManagers = detectGlobalPackageManagers;
982
- exports.detectLockfilePackageManagers = detectLockfilePackageManagers;
983
- exports.detectPackageManagers = detectPackageManagers;
984
- exports.filterPackageManagers = filterPackageManagers;
985
- exports.findDependencyInPackageJson = findDependencyInPackageJson;
986
- exports.findPackageManager = findPackageManager;
987
- exports.findPackageManagerSafely = findPackageManagerSafely;
988
- exports.findResolvedModulePath = findResolvedModulePath;
989
- exports.getAliasMap = getAliasMap;
990
- exports.getFolderByPackageName = getFolderByPackageName;
991
- exports.getGitRootFolder = getGitRootFolder;
992
- exports.getPackageFolder = getPackageFolder;
993
- exports.getPath = getPath;
994
- exports.getWorkspaceFolder = getWorkspaceFolder;
995
- exports.importMap = importMap;
996
- exports.importer = importer;
997
- exports.isDependencyInPackageJson = isDependencyInPackageJson;
998
- exports.isPackageDependency = isPackageDependency;
999
- exports.isPackageModuleFound = isPackageModuleFound;
1000
- exports.packageManagerConfigs = packageManagerConfigs;
1001
- exports.predefinedPathAliases = predefinedPathAliases;
1002
- exports.project = project;
1003
- exports.resolveModule = resolveModule;
1004
- exports.resolveModulePath = resolveModulePath;
1005
- exports.resolvePackageModulePath = resolvePackageModulePath;
1006
- exports.workspace = workspace;