@visulima/package 5.0.0-alpha.4 → 5.0.0-alpha.5

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/CHANGELOG.md CHANGED
@@ -1,3 +1,22 @@
1
+ ## @visulima/package [5.0.0-alpha.5](https://github.com/visulima/visulima/compare/@visulima/package@5.0.0-alpha.4...@visulima/package@5.0.0-alpha.5) (2026-03-26)
2
+
3
+ ### Bug Fixes
4
+
5
+ * **package:** use workspace:* for internal [@visulima](https://github.com/visulima) deps ([e409128](https://github.com/visulima/visulima/commit/e409128c02a6d801dd385ae845c1ab28ca5c09da))
6
+ * **web:** improve build setup with incremental stats caching and prod install ([fe33e75](https://github.com/visulima/visulima/commit/fe33e75827586779b4b3a0c6d57b39f889ee6207))
7
+
8
+ ### Miscellaneous Chores
9
+
10
+ * **package:** migrate deps to pnpm catalogs ([301fac4](https://github.com/visulima/visulima/commit/301fac41be88df7469155649467921a72ca740a6))
11
+ * **package:** update dependencies ([fb1a43d](https://github.com/visulima/visulima/commit/fb1a43de0fd345806d76aec660d48c627d576083))
12
+ * visulima website ([#591](https://github.com/visulima/visulima/issues/591)) ([59ab2e2](https://github.com/visulima/visulima/commit/59ab2e2befb03e51cd2088956f83d9b87de6d033))
13
+
14
+
15
+ ### Dependencies
16
+
17
+ * **@visulima/fs:** upgraded to 5.0.0-alpha.5
18
+ * **@visulima/path:** upgraded to 3.0.0-alpha.6
19
+
1
20
  ## @visulima/package [5.0.0-alpha.4](https://github.com/visulima/visulima/compare/@visulima/package@5.0.0-alpha.3...@visulima/package@5.0.0-alpha.4) (2026-03-06)
2
21
 
3
22
  ### Bug Fixes
package/dist/error.js CHANGED
@@ -1 +1 @@
1
- import{default as a}from"./packem_shared/PackageNotFoundError-BictYTIA.js";export{a as PackageNotFoundError};
1
+ export { default as PackageNotFoundError } from './packem_shared/PackageNotFoundError-CJmAqa_k.js';
package/dist/index.js CHANGED
@@ -1 +1,6 @@
1
- import{default as n}from"./packem_shared/PackageNotFoundError-BictYTIA.js";import{findMonorepoRoot as r,findMonorepoRootSync as c}from"./monorepo.js";import{findPackageRoot as s,findPackageRootSync as t}from"./package.js";import{ensurePackages as P,findPackageJson as k,findPackageJsonSync as f,getPackageJsonProperty as d,hasPackageJsonAnyDependency as p,hasPackageJsonProperty as l,parsePackageJson as y,parsePackageJsonSync as J,writePackageJson as m,writePackageJsonSync as M}from"./package-json.js";import{findLockFile as R,findLockFileSync as x,findPackageManager as C,findPackageManagerSync as u,generateMissingPackagesInstallMessage as v,getPackageManagerVersion as F,identifyInitiatingPackageManager as I}from"./package-manager.js";import{isPackageInWorkspace as w,readPnpmCatalogs as D,readPnpmCatalogsSync as L,resolveCatalogReference as A,resolveCatalogReferences as E,resolveDependenciesCatalogReferences as N}from"./pnpm.js";export{n as PackageNotFoundError,P as ensurePackages,R as findLockFile,x as findLockFileSync,r as findMonorepoRoot,c as findMonorepoRootSync,k as findPackageJson,f as findPackageJsonSync,C as findPackageManager,u as findPackageManagerSync,s as findPackageRoot,t as findPackageRootSync,v as generateMissingPackagesInstallMessage,d as getPackageJsonProperty,F as getPackageManagerVersion,p as hasPackageJsonAnyDependency,l as hasPackageJsonProperty,I as identifyInitiatingPackageManager,w as isPackageInWorkspace,y as parsePackageJson,J as parsePackageJsonSync,D as readPnpmCatalogs,L as readPnpmCatalogsSync,A as resolveCatalogReference,E as resolveCatalogReferences,N as resolveDependenciesCatalogReferences,m as writePackageJson,M as writePackageJsonSync};
1
+ export { default as PackageNotFoundError } from './packem_shared/PackageNotFoundError-CJmAqa_k.js';
2
+ export { findMonorepoRoot, findMonorepoRootSync } from './monorepo.js';
3
+ export { findPackageRoot, findPackageRootSync } from './package.js';
4
+ export { ensurePackages, findPackageJson, findPackageJsonSync, getPackageJsonProperty, hasPackageJsonAnyDependency, hasPackageJsonProperty, parsePackageJson, parsePackageJsonSync, writePackageJson, writePackageJsonSync } from './package-json.js';
5
+ export { findLockFile, findLockFileSync, findPackageManager, findPackageManagerSync, generateMissingPackagesInstallMessage, getPackageManagerVersion, identifyInitiatingPackageManager } from './package-manager.js';
6
+ export { isPackageInWorkspace, readPnpmCatalogs, readPnpmCatalogsSync, resolveCatalogReference, resolveCatalogReferences, resolveDependenciesCatalogReferences } from './pnpm.js';
package/dist/monorepo.js CHANGED
@@ -1 +1,118 @@
1
- var l=Object.defineProperty;var p=(r,e)=>l(r,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";import{findUp as j,readJson as w,findUpSync as b,readJsonSync as k}from"@visulima/fs";import{NotFoundError as u}from"@visulima/fs/error";import{dirname as d,join as a}from"@visulima/path";import{findPackageManager as _,findPackageManagerSync as M}from"./package-manager.js";const g=y(import.meta.url),i=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,h=p(r=>{if(typeof i<"u"&&i.versions&&i.versions.node){const[e,t]=i.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return i.getBuiltinModule(r)}return g(r)},"__cjs_getBuiltinModule"),{existsSync:c,readFileSync:f}=h("node:fs");var S=Object.defineProperty,m=p((r,e)=>S(r,"name",{value:e,configurable:!0}),"i");const E=m(async r=>{const e=await j(["lerna.json","turbo.json"],{type:"file",...r&&{cwd:r}});if(e?.endsWith("lerna.json")){const o=await w(e);if(o.useWorkspaces||o.packages)return{path:d(e),strategy:"lerna"}}const t=e?.endsWith("turbo.json");try{const{packageManager:o,path:n}=await _(r);if(["npm","yarn"].includes(o)){const s=a(n,"package.json");if(c(s)&&f(a(n,"package.json"),"utf8").includes("workspaces"))return{path:n,strategy:t?"turbo":o}}else if(o==="pnpm"){const s=a(n,"pnpm-workspace.yaml");if(c(s))return{path:n,strategy:t?"turbo":"pnpm"}}}catch(o){if(!(o instanceof u))throw o}throw new Error(`No monorepo root could be found upwards from the directory ${r} using lerna, yarn, pnpm, or npm as indicators.`)},"findMonorepoRoot"),T=m(r=>{const e=b(["lerna.json","turbo.json"],{type:"file",...r&&{cwd:r}});if(e?.endsWith("lerna.json")){const o=k(e);if(o.useWorkspaces||o.packages)return{path:d(e),strategy:"lerna"}}const t=e?.endsWith("turbo.json");try{const{packageManager:o,path:n}=M(r);if(["npm","yarn"].includes(o)){const s=a(n,"package.json");if(c(s)&&f(a(n,"package.json"),"utf8").includes("workspaces"))return{path:n,strategy:t?"turbo":o}}else if(o==="pnpm"){const s=a(n,"pnpm-workspace.yaml");if(c(s))return{path:n,strategy:t?"turbo":"pnpm"}}}catch(o){if(!(o instanceof u))throw o}throw new Error(`No monorepo root could be found upwards from the directory ${r} using lerna, yarn, pnpm, or npm as indicators.`)},"findMonorepoRootSync");export{E as findMonorepoRoot,T as findMonorepoRootSync};
1
+ import { createRequire as __cjs_createRequire } from "node:module";
2
+
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
4
+
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
+
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
19
+
20
+ const {
21
+ existsSync,
22
+ readFileSync
23
+ } = __cjs_getBuiltinModule("node:fs");
24
+ import { findUp, readJson, findUpSync, readJsonSync } from '@visulima/fs';
25
+ import { NotFoundError } from '@visulima/fs/error';
26
+ import { dirname, join } from '@visulima/path';
27
+ import { findPackageManager, findPackageManagerSync } from './package-manager.js';
28
+
29
+ const findMonorepoRoot = async (cwd) => {
30
+ const workspaceFilePath = await findUp(["lerna.json", "turbo.json"], {
31
+ type: "file",
32
+ ...cwd && { cwd }
33
+ });
34
+ if (workspaceFilePath?.endsWith("lerna.json")) {
35
+ const lerna = await readJson(workspaceFilePath);
36
+ if (lerna.useWorkspaces || lerna.packages) {
37
+ return {
38
+ path: dirname(workspaceFilePath),
39
+ strategy: "lerna"
40
+ };
41
+ }
42
+ }
43
+ const isTurbo = workspaceFilePath?.endsWith("turbo.json");
44
+ try {
45
+ const { packageManager, path } = await findPackageManager(cwd);
46
+ if (["npm", "yarn"].includes(packageManager)) {
47
+ const packageJsonFilePath = join(path, "package.json");
48
+ if (existsSync(packageJsonFilePath)) {
49
+ const packageJson = readFileSync(join(path, "package.json"), "utf8");
50
+ if (packageJson.includes("workspaces")) {
51
+ return {
52
+ path,
53
+ strategy: isTurbo ? "turbo" : packageManager
54
+ };
55
+ }
56
+ }
57
+ } else if (packageManager === "pnpm") {
58
+ const pnpmWorkspacesFilePath = join(path, "pnpm-workspace.yaml");
59
+ if (existsSync(pnpmWorkspacesFilePath)) {
60
+ return {
61
+ path,
62
+ strategy: isTurbo ? "turbo" : "pnpm"
63
+ };
64
+ }
65
+ }
66
+ } catch (error) {
67
+ if (!(error instanceof NotFoundError)) {
68
+ throw error;
69
+ }
70
+ }
71
+ throw new Error(`No monorepo root could be found upwards from the directory ${cwd} using lerna, yarn, pnpm, or npm as indicators.`);
72
+ };
73
+ const findMonorepoRootSync = (cwd) => {
74
+ const workspaceFilePath = findUpSync(["lerna.json", "turbo.json"], {
75
+ type: "file",
76
+ ...cwd && { cwd }
77
+ });
78
+ if (workspaceFilePath?.endsWith("lerna.json")) {
79
+ const lerna = readJsonSync(workspaceFilePath);
80
+ if (lerna.useWorkspaces || lerna.packages) {
81
+ return {
82
+ path: dirname(workspaceFilePath),
83
+ strategy: "lerna"
84
+ };
85
+ }
86
+ }
87
+ const isTurbo = workspaceFilePath?.endsWith("turbo.json");
88
+ try {
89
+ const { packageManager, path } = findPackageManagerSync(cwd);
90
+ if (["npm", "yarn"].includes(packageManager)) {
91
+ const packageJsonFilePath = join(path, "package.json");
92
+ if (existsSync(packageJsonFilePath)) {
93
+ const packageJson = readFileSync(join(path, "package.json"), "utf8");
94
+ if (packageJson.includes("workspaces")) {
95
+ return {
96
+ path,
97
+ strategy: isTurbo ? "turbo" : packageManager
98
+ };
99
+ }
100
+ }
101
+ } else if (packageManager === "pnpm") {
102
+ const pnpmWorkspacesFilePath = join(path, "pnpm-workspace.yaml");
103
+ if (existsSync(pnpmWorkspacesFilePath)) {
104
+ return {
105
+ path,
106
+ strategy: isTurbo ? "turbo" : "pnpm"
107
+ };
108
+ }
109
+ }
110
+ } catch (error) {
111
+ if (!(error instanceof NotFoundError)) {
112
+ throw error;
113
+ }
114
+ }
115
+ throw new Error(`No monorepo root could be found upwards from the directory ${cwd} using lerna, yarn, pnpm, or npm as indicators.`);
116
+ };
117
+
118
+ export { findMonorepoRoot, findMonorepoRootSync };
@@ -1,4 +1,620 @@
1
- var K=Object.defineProperty;var f=(e,r)=>K(e,"name",{value:r,configurable:!0});import{createRequire as V}from"node:module";import{installPackage as X}from"@antfu/install-pkg";import{readJsonSync as L,readFileSync as H,findUp as Q,findUpSync as Z,writeJson as ee,writeJsonSync as re,readJson as ne,readFile as te}from"@visulima/fs";import{NotFoundError as I}from"@visulima/fs/error";import{parseJson as T,toPath as A}from"@visulima/fs/utils";import{readYamlSync as oe,readYaml as se}from"@visulima/fs/yaml";import{join as _}from"@visulima/path";import F from"json5";import ae from"normalize-package-data";import{readPnpmCatalogsSync as D,resolveCatalogReferences as E,readPnpmCatalogs as C}from"./pnpm.js";const U=V(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,J=f(e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[r,t]=w.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return w.getBuiltinModule(e)}return U(e)},"__cjs_getBuiltinModule"),{existsSync:N}=J("node:fs"),{createInterface:ie}=J("node:readline"),{styleText:g}=J("node:util");var ce=Object.defineProperty,l=f((e,r)=>ce(e,"name",{value:r,configurable:!0}),"f");const h=l(e=>{const r=typeof e;return e!==null&&(r==="object"||r==="function")},"isObject"),fe=l(e=>{if(!h(e))return!1;for(const r in e)if(Object.hasOwn(e,r))return!1;return!0},"isEmptyObject"),O=new Set(["__proto__","prototype","constructor"]),W=1e6,pe=l(e=>e>="0"&&e<="9","isDigit");function b(e){if(e==="0")return!0;if(/^[1-9]\d*$/.test(e)){const r=Number.parseInt(e,10);return r<=Number.MAX_SAFE_INTEGER&&r<=W}return!1}f(b,"p$1");l(b,"shouldCoerceToNumber");function k(e,r){return O.has(e)?!1:(e&&b(e)?r.push(Number.parseInt(e,10)):r.push(e),!0)}f(k,"y");l(k,"processSegment");function B(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);const r=[];let t="",n="start",o=!1,s=0;for(const a of e){if(s++,o){t+=a,o=!1;continue}if(a==="\\"){if(n==="index")throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd")throw new Error(`Invalid character '${a}' after an index at position ${s}`);o=!0,n=n==="start"?"property":n;continue}switch(a){case".":{if(n==="index")throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd"){n="property";break}if(!k(t,r))return[];t="",n="property";break}case"[":{if(n==="index")throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd"){n="index";break}if(n==="property"||n==="start"){if((t||n==="property")&&!k(t,r))return[];t=""}n="index";break}case"]":{if(n==="index"){if(t==="")t=(r.pop()||"")+"[]",n="property";else{const i=Number.parseInt(t,10);!Number.isNaN(i)&&Number.isFinite(i)&&i>=0&&i<=Number.MAX_SAFE_INTEGER&&i<=W&&t===String(i)?r.push(i):r.push(t),t="",n="indexEnd"}break}if(n==="indexEnd")throw new Error(`Invalid character '${a}' after an index at position ${s}`);t+=a;break}default:{if(n==="index"&&!pe(a))throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd")throw new Error(`Invalid character '${a}' after an index at position ${s}`);n==="start"&&(n="property"),t+=a}}}switch(o&&(t+="\\"),n){case"property":{if(!k(t,r))return[];break}case"index":throw new Error("Index was not closed");case"start":{r.push("");break}}return r}f(B,"parsePath");l(B,"parsePath");function $(e){if(typeof e=="string")return B(e);if(Array.isArray(e)){const r=[];for(const[t,n]of e.entries()){if(typeof n!="string"&&typeof n!="number")throw new TypeError(`Expected a string or number for path segment at index ${t}, got ${typeof n}`);if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`Path segment at index ${t} must be a finite number, got ${n}`);if(O.has(n))return[];typeof n=="string"&&b(n)?r.push(Number.parseInt(n,10)):r.push(n)}return r}return[]}f($,"d");l($,"normalizePath");function d(e,r,t){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return t===void 0?e:t;const n=$(r);if(n.length===0)return t;for(let o=0;o<n.length;o++){const s=n[o];if(e=e[s],e==null){if(o!==n.length-1)return t;break}}return e===void 0?t:e}f(d,"getProperty");l(d,"getProperty");function M(e,r,t){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return e;const n=e,o=$(r);if(o.length===0)return e;for(let s=0;s<o.length;s++){const a=o[s];if(s===o.length-1)e[a]=t;else if(!h(e[a])){const i=typeof o[s+1]=="number";e[a]=i?[]:{}}e=e[a]}return n}f(M,"setProperty");l(M,"setProperty");function le(e,r){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return!1;const t=$(r);if(t.length===0)return!1;for(let n=0;n<t.length;n++){const o=t[n];if(n===t.length-1)return Object.hasOwn(e,o)?(delete e[o],!0):!1;if(e=e[o],!h(e))return!1}}f(le,"deleteProperty");l(le,"deleteProperty");function y(e,r){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return!1;const t=$(r);if(t.length===0)return!1;for(const n of t){if(!h(e)||!(n in e))return!1;e=e[n]}return!0}f(y,"hasProperty");l(y,"hasProperty");function x(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.replaceAll(/[\\.[]/g,String.raw`\$&`)}f(x,"escapePath");l(x,"escapePath");function R(e){const r=Object.entries(e);return Array.isArray(e)?r.map(([t,n])=>[b(t)?Number.parseInt(t,10):t,n]):r}f(R,"m$2");l(R,"normalizeEntries");function Y(e,r={}){if(!Array.isArray(e))throw new TypeError(`Expected an array, got ${typeof e}`);const{preferDotForIndices:t=!1}=r,n=[];for(const[o,s]of e.entries()){if(typeof s!="string"&&typeof s!="number")throw new TypeError(`Expected a string or number for path segment at index ${o}, got ${typeof s}`);if(typeof s=="number")if(!Number.isInteger(s)||s<0){const a=x(String(s));n.push(o===0?a:`.${a}`)}else t&&o>0?n.push(`.${s}`):n.push(`[${s}]`);else if(typeof s=="string")if(s==="")o===0||n.push(".");else if(b(s)){const a=Number.parseInt(s,10);t&&o>0?n.push(`.${a}`):n.push(`[${a}]`)}else{const a=x(s);n.push(o===0?a:`.${a}`)}}return n.join("")}f(Y,"stringifyPath");l(Y,"stringifyPath");function*S(e,r=[],t=new Set){if(!h(e)||fe(e)){r.length>0&&(yield Y(r));return}if(!t.has(e)){t.add(e);for(const[n,o]of R(e))r.push(n),yield*S(o,r,t),r.pop();t.delete(e)}}f(S,"x");l(S,"deepKeysIterator");function ue(e){return[...S(e)]}f(ue,"deepKeys");l(ue,"deepKeys");function ge(e){const r={};if(!h(e))return r;for(const[t,n]of Object.entries(e))M(r,t,n);return r}f(ge,"unflatten");l(ge,"unflatten");var he=Object.defineProperty,j=f((e,r)=>he(e,"name",{value:r,configurable:!0}),"i");const de=j(async e=>{const{default:r=!1,message:t,transformer:n}=e,o=j(a=>{const i=g(["cyan","bold"],"?"),c=g(["bold"],a),u=r?`${g(["greenBright"],"Y")}${g(["gray"],"/n")}`:`y/${g(["yellowBright"],"N")}`;return`${i} ${c} ${g(["gray"],`(${u})`)}`},"formatMessage"),s=j(a=>n?n(a):a?g(["greenBright"],"Yes"):g(["yellowBright"],"No"),"formatAnswer");return new Promise(a=>{const i=ie({input:process.stdin,output:process.stdout}),c=o(t);i.question(c,u=>{i.close();const m=u.trim().toLowerCase();if(m===""){a(r);return}if(m==="y"||m==="yes"){console.log(`${g(["greenBright"],"✓")} ${s(!0)}`),a(!0);return}if(m==="n"||m==="no"){console.log(`${g(["yellowBright"],"✗")} ${s(!1)}`),a(!1);return}console.log(`${g(["gray"],"→")} ${s(r)}`),a(r)}),i.on("SIGINT",()=>{i.close(),console.log(`
2
- ${g(["gray"],"→")} ${s(r)}`),a(r)})})},"confirm"),ye=typeof process.stdout<"u"&&!process.versions.deno&&!globalThis.window;var me=Object.defineProperty,p=f((e,r)=>me(e,"name",{value:r,configurable:!0}),"l");const P=new Map,q=new Map;class we extends Error{static{f(this,"F")}static{p(this,"PackageJsonValidationError")}constructor(r){super(`The following warnings were encountered while normalizing package data:
3
- - ${r.join(`
4
- - `)}`),this.name="PackageJsonValidationError"}}const v=p((e,r,t=[])=>{const n=[];if(ae(e,o=>{n.push(o)},r),r&&n.length>0){const o=n.filter(s=>!t.some(a=>a instanceof RegExp?a.test(s):a===s));if(o.length>0)throw new we(o)}return e},"normalizeInput"),be=p(async e=>await se(e),"parseYamlFile"),$e=p(e=>oe(e),"parseYamlFileSync"),ke=p(async e=>{const r=await te(e);return F.parse(r)},"parseJson5File"),Pe=p(e=>{const r=H(e);return F.parse(r)},"parseJson5FileSync"),z=p(async(e,r)=>r?.yaml!==!1&&(e.endsWith(".yaml")||e.endsWith(".yml"))?be(e):r?.json5!==!1&&e.endsWith(".json5")?ke(e):ne(e),"parsePackageFile"),G=p((e,r)=>r?.yaml!==!1&&(e.endsWith(".yaml")||e.endsWith(".yml"))?$e(e):r?.json5!==!1&&e.endsWith(".json5")?Pe(e):L(e),"parsePackageFileSync"),Fe=p(async(e,r={})=>{const t={type:"file"};e&&(t.cwd=e);const n=["package.json"];r.yaml!==!1&&n.push("package.yaml","package.yml"),r.json5!==!1&&n.push("package.json5");let o;for await(const c of n)if(o=await Q(c,t),o)break;if(!o)throw new I(`No such file or directory, for ${n.join(", ").replace(/, ([^,]*)$/," or $1")} found.`);const s=r.cache&&typeof r.cache!="boolean"?r.cache:q;if(r.cache&&s.has(o))return s.get(o);const a=await z(o,r);if(r.resolveCatalogs){const c=await C(o);c&&E(a,c)}v(a,r.strict??!1,r.ignoreWarnings);const i={packageJson:a,path:o};return r.cache&&s.set(o,i),i},"findPackageJson"),De=p((e,r={})=>{const t={type:"file"};e&&(t.cwd=e);const n=["package.json"];r.yaml!==!1&&n.push("package.yaml","package.yml"),r.json5!==!1&&n.push("package.json5");let o;for(const c of n)if(o=Z(c,t),o)break;if(!o)throw new I(`No such file or directory, for ${n.join(", ").replace(/, ([^,]*)$/," or $1")} found.`);const s=r.cache&&typeof r.cache!="boolean"?r.cache:q;if(r.cache&&s.has(o))return s.get(o);const a=G(o,r);if(r.resolveCatalogs){const c=D(o);c&&E(a,c)}v(a,r.strict??!1,r.ignoreWarnings);const i={packageJson:a,path:o};return r.cache&&s.set(o,i),i},"findPackageJsonSync"),Ce=p(async(e,r={})=>{const{cwd:t,...n}=r,o=A(t??process.cwd());await ee(_(o,"package.json"),e,n)},"writePackageJson"),Oe=p((e,r={})=>{const{cwd:t,...n}=r,o=A(t??process.cwd());re(_(o,"package.json"),e,n)},"writePackageJsonSync"),We=p((e,r)=>{const t=e!==null&&typeof e=="object"&&!Array.isArray(e);if(!t&&typeof e!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");let n,o=!1,s;if(t)n=structuredClone(e);else if(N(e)){s=e;const i=r?.cache&&typeof r.cache!="boolean"?r.cache:P;if(r?.cache&&i.has(s))return i.get(s);n=G(s,r),o=!0}else n=T(e);if(r?.resolveCatalogs)if(o){const i=D(e);i&&E(n,i)}else throw new Error("The 'resolveCatalogs' option can only be used on a file path.");v(n,r?.strict??!1,r?.ignoreWarnings);const a=n;return o&&s&&r?.cache&&(r.cache&&typeof r.cache!="boolean"?r.cache:P).set(s,a),a},"parsePackageJsonSync"),Be=p(async(e,r)=>{const t=e!==null&&typeof e=="object"&&!Array.isArray(e);if(!t&&typeof e!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");let n,o=!1,s;if(t)n=structuredClone(e);else if(N(e)){s=e;const i=r?.cache&&typeof r.cache!="boolean"?r.cache:P;if(r?.cache&&i.has(s))return i.get(s);n=await z(s,r),o=!0}else n=T(e);if(r?.resolveCatalogs)if(o){const i=await C(e);i&&E(n,i)}else throw new Error("The 'resolveCatalogs' option can only be used on a file path.");v(n,r?.strict??!1,r?.ignoreWarnings);const a=n;return o&&s&&r?.cache&&(r.cache&&typeof r.cache!="boolean"?r.cache:P).set(s,a),a},"parsePackageJson"),Me=p((e,r,t)=>d(e,r,t),"getPackageJsonProperty"),Re=p((e,r)=>y(e,r),"hasPackageJsonProperty"),Ye=p((e,r,t)=>{const n=d(e,"dependencies",{}),o=d(e,"devDependencies",{}),s=d(e,"peerDependencies",{}),a={...n,...o,...t?.peerDeps===!1?{}:s};for(const i of r)if(y(a,i))return!0;return!1},"hasPackageJsonAnyDependency"),qe=p(async(e,r,t="dependencies",n={})=>{const o=d(e,"dependencies",{}),s=d(e,"devDependencies",{}),a=d(e,"peerDependencies",{}),i=[],c={deps:!0,devDeps:!0,peerDeps:!1,...n};for(const u of r)c.deps&&y(o,u)||c.devDeps&&y(s,u)||c.peerDeps&&y(a,u)||i.push(u);if(i.length!==0){if(process.env.CI||ye&&!process.stdout?.isTTY){const u=`Skipping package installation for [${r.join(", ")}] because the process is not interactive.`;if(n.throwOnWarn)throw new Error(u);n.logger?.warn?n.logger.warn(u):console.warn(u);return}if(typeof c.confirm?.message=="function"&&(c.confirm.message=c.confirm.message(i)),c.confirm?.message===void 0){const u=`${i.length===1?"Package is":"Packages are"} required for this config: ${i.join(", ")}. Do you want to install them?`;c.confirm===void 0?c.confirm={message:u}:c.confirm.message=u}await de(c.confirm)&&await X(i,{...c.installPackage,cwd:c.cwd?A(c.cwd):void 0,dev:t==="devDependencies"})}},"ensurePackages");export{qe as ensurePackages,Fe as findPackageJson,De as findPackageJsonSync,Me as getPackageJsonProperty,Ye as hasPackageJsonAnyDependency,Re as hasPackageJsonProperty,Be as parsePackageJson,We as parsePackageJsonSync,Ce as writePackageJson,Oe as writePackageJsonSync};
1
+ import { createRequire as __cjs_createRequire } from "node:module";
2
+
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
4
+
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
+
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
19
+
20
+ const {
21
+ existsSync
22
+ } = __cjs_getBuiltinModule("node:fs");
23
+ import { installPackage } from '@antfu/install-pkg';
24
+ import { findUp, findUpSync, writeJson, writeJsonSync, readJson, readJsonSync, readFile, readFileSync } from '@visulima/fs';
25
+ import { NotFoundError } from '@visulima/fs/error';
26
+ import { toPath, parseJson } from '@visulima/fs/utils';
27
+ import { readYaml, readYamlSync } from '@visulima/fs/yaml';
28
+ import { join } from '@visulima/path';
29
+ import JSON5 from 'json5';
30
+ import normalizeData from 'normalize-package-data';
31
+ import { readPnpmCatalogs, resolveCatalogReferences, readPnpmCatalogsSync } from './pnpm.js';
32
+ const {
33
+ createInterface
34
+ } = __cjs_getBuiltinModule("node:readline");
35
+ const {
36
+ styleText
37
+ } = __cjs_getBuiltinModule("node:util");
38
+
39
+ const isObject = (value) => {
40
+ const type = typeof value;
41
+ return value !== null && (type === "object" || type === "function");
42
+ };
43
+ const disallowedKeys = /* @__PURE__ */ new Set([
44
+ "__proto__",
45
+ "prototype",
46
+ "constructor"
47
+ ]);
48
+ const MAX_ARRAY_INDEX = 1e6;
49
+ const isDigit = (character) => character >= "0" && character <= "9";
50
+ function shouldCoerceToNumber(segment) {
51
+ if (segment === "0") {
52
+ return true;
53
+ }
54
+ if (/^[1-9]\d*$/.test(segment)) {
55
+ const parsedNumber = Number.parseInt(segment, 10);
56
+ return parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX;
57
+ }
58
+ return false;
59
+ }
60
+ function processSegment(segment, parts) {
61
+ if (disallowedKeys.has(segment)) {
62
+ return false;
63
+ }
64
+ if (segment && shouldCoerceToNumber(segment)) {
65
+ parts.push(Number.parseInt(segment, 10));
66
+ } else {
67
+ parts.push(segment);
68
+ }
69
+ return true;
70
+ }
71
+ function parsePath(path) {
72
+ if (typeof path !== "string") {
73
+ throw new TypeError(`Expected a string, got ${typeof path}`);
74
+ }
75
+ const parts = [];
76
+ let currentSegment = "";
77
+ let currentPart = "start";
78
+ let isEscaping = false;
79
+ let position = 0;
80
+ for (const character of path) {
81
+ position++;
82
+ if (isEscaping) {
83
+ currentSegment += character;
84
+ isEscaping = false;
85
+ continue;
86
+ }
87
+ if (character === "\\") {
88
+ if (currentPart === "index") {
89
+ throw new Error(`Invalid character '${character}' in an index at position ${position}`);
90
+ }
91
+ if (currentPart === "indexEnd") {
92
+ throw new Error(`Invalid character '${character}' after an index at position ${position}`);
93
+ }
94
+ isEscaping = true;
95
+ currentPart = currentPart === "start" ? "property" : currentPart;
96
+ continue;
97
+ }
98
+ switch (character) {
99
+ case ".": {
100
+ if (currentPart === "index") {
101
+ throw new Error(`Invalid character '${character}' in an index at position ${position}`);
102
+ }
103
+ if (currentPart === "indexEnd") {
104
+ currentPart = "property";
105
+ break;
106
+ }
107
+ if (!processSegment(currentSegment, parts)) {
108
+ return [];
109
+ }
110
+ currentSegment = "";
111
+ currentPart = "property";
112
+ break;
113
+ }
114
+ case "[": {
115
+ if (currentPart === "index") {
116
+ throw new Error(`Invalid character '${character}' in an index at position ${position}`);
117
+ }
118
+ if (currentPart === "indexEnd") {
119
+ currentPart = "index";
120
+ break;
121
+ }
122
+ if (currentPart === "property" || currentPart === "start") {
123
+ if ((currentSegment || currentPart === "property") && !processSegment(currentSegment, parts)) {
124
+ return [];
125
+ }
126
+ currentSegment = "";
127
+ }
128
+ currentPart = "index";
129
+ break;
130
+ }
131
+ case "]": {
132
+ if (currentPart === "index") {
133
+ if (currentSegment === "") {
134
+ const lastSegment = parts.pop() || "";
135
+ currentSegment = lastSegment + "[]";
136
+ currentPart = "property";
137
+ } else {
138
+ const parsedNumber = Number.parseInt(currentSegment, 10);
139
+ const isValidInteger = !Number.isNaN(parsedNumber) && Number.isFinite(parsedNumber) && parsedNumber >= 0 && parsedNumber <= Number.MAX_SAFE_INTEGER && parsedNumber <= MAX_ARRAY_INDEX && currentSegment === String(parsedNumber);
140
+ if (isValidInteger) {
141
+ parts.push(parsedNumber);
142
+ } else {
143
+ parts.push(currentSegment);
144
+ }
145
+ currentSegment = "";
146
+ currentPart = "indexEnd";
147
+ }
148
+ break;
149
+ }
150
+ if (currentPart === "indexEnd") {
151
+ throw new Error(`Invalid character '${character}' after an index at position ${position}`);
152
+ }
153
+ currentSegment += character;
154
+ break;
155
+ }
156
+ default: {
157
+ if (currentPart === "index" && !isDigit(character)) {
158
+ throw new Error(`Invalid character '${character}' in an index at position ${position}`);
159
+ }
160
+ if (currentPart === "indexEnd") {
161
+ throw new Error(`Invalid character '${character}' after an index at position ${position}`);
162
+ }
163
+ if (currentPart === "start") {
164
+ currentPart = "property";
165
+ }
166
+ currentSegment += character;
167
+ }
168
+ }
169
+ }
170
+ if (isEscaping) {
171
+ currentSegment += "\\";
172
+ }
173
+ switch (currentPart) {
174
+ case "property": {
175
+ if (!processSegment(currentSegment, parts)) {
176
+ return [];
177
+ }
178
+ break;
179
+ }
180
+ case "index": {
181
+ throw new Error("Index was not closed");
182
+ }
183
+ case "start": {
184
+ parts.push("");
185
+ break;
186
+ }
187
+ }
188
+ return parts;
189
+ }
190
+ function normalizePath(path) {
191
+ if (typeof path === "string") {
192
+ return parsePath(path);
193
+ }
194
+ if (Array.isArray(path)) {
195
+ const normalized = [];
196
+ for (const [index, segment] of path.entries()) {
197
+ if (typeof segment !== "string" && typeof segment !== "number") {
198
+ throw new TypeError(`Expected a string or number for path segment at index ${index}, got ${typeof segment}`);
199
+ }
200
+ if (typeof segment === "number" && !Number.isFinite(segment)) {
201
+ throw new TypeError(`Path segment at index ${index} must be a finite number, got ${segment}`);
202
+ }
203
+ if (disallowedKeys.has(segment)) {
204
+ return [];
205
+ }
206
+ if (typeof segment === "string" && shouldCoerceToNumber(segment)) {
207
+ normalized.push(Number.parseInt(segment, 10));
208
+ } else {
209
+ normalized.push(segment);
210
+ }
211
+ }
212
+ return normalized;
213
+ }
214
+ return [];
215
+ }
216
+ function getProperty(object, path, value) {
217
+ if (!isObject(object) || typeof path !== "string" && !Array.isArray(path)) {
218
+ return value === void 0 ? object : value;
219
+ }
220
+ const pathArray = normalizePath(path);
221
+ if (pathArray.length === 0) {
222
+ return value;
223
+ }
224
+ for (let index = 0; index < pathArray.length; index++) {
225
+ const key = pathArray[index];
226
+ object = object[key];
227
+ if (object === void 0 || object === null) {
228
+ if (index !== pathArray.length - 1) {
229
+ return value;
230
+ }
231
+ break;
232
+ }
233
+ }
234
+ return object === void 0 ? value : object;
235
+ }
236
+ function hasProperty(object, path) {
237
+ if (!isObject(object) || typeof path !== "string" && !Array.isArray(path)) {
238
+ return false;
239
+ }
240
+ const pathArray = normalizePath(path);
241
+ if (pathArray.length === 0) {
242
+ return false;
243
+ }
244
+ for (const key of pathArray) {
245
+ if (!isObject(object) || !(key in object)) {
246
+ return false;
247
+ }
248
+ object = object[key];
249
+ }
250
+ return true;
251
+ }
252
+
253
+ const confirm = async (options) => {
254
+ const { default: defaultValue = false, message, transformer } = options;
255
+ const formatMessage = (message_) => {
256
+ const questionMark = styleText(["cyan", "bold"], "?");
257
+ const boldMessage = styleText(["bold"], message_);
258
+ const defaultHint = defaultValue ? `${styleText(["greenBright"], "Y")}${styleText(["gray"], "/n")}` : `y/${styleText(["yellowBright"], "N")}`;
259
+ return `${questionMark} ${boldMessage} ${styleText(["gray"], `(${defaultHint})`)}`;
260
+ };
261
+ const formatAnswer = (answer) => {
262
+ if (transformer) {
263
+ return transformer(answer);
264
+ }
265
+ return answer ? styleText(["greenBright"], "Yes") : styleText(["yellowBright"], "No");
266
+ };
267
+ return new Promise((resolve) => {
268
+ const rl = createInterface({
269
+ input: process.stdin,
270
+ output: process.stdout
271
+ });
272
+ const formattedMessage = formatMessage(message);
273
+ rl.question(formattedMessage, (answer) => {
274
+ rl.close();
275
+ const normalizedAnswer = answer.trim().toLowerCase();
276
+ if (normalizedAnswer === "") {
277
+ resolve(defaultValue);
278
+ return;
279
+ }
280
+ if (normalizedAnswer === "y" || normalizedAnswer === "yes") {
281
+ console.log(`${styleText(["greenBright"], "✓")} ${formatAnswer(true)}`);
282
+ resolve(true);
283
+ return;
284
+ }
285
+ if (normalizedAnswer === "n" || normalizedAnswer === "no") {
286
+ console.log(`${styleText(["yellowBright"], "✗")} ${formatAnswer(false)}`);
287
+ resolve(false);
288
+ return;
289
+ }
290
+ console.log(`${styleText(["gray"], "→")} ${formatAnswer(defaultValue)}`);
291
+ resolve(defaultValue);
292
+ });
293
+ rl.on("SIGINT", () => {
294
+ rl.close();
295
+ console.log(`
296
+ ${styleText(["gray"], "→")} ${formatAnswer(defaultValue)}`);
297
+ resolve(defaultValue);
298
+ });
299
+ });
300
+ };
301
+
302
+ const isNode = typeof process.stdout < "u" && !process.versions.deno && !globalThis.window;
303
+
304
+ const PackageJsonParseCache = /* @__PURE__ */ new Map();
305
+ const PackageJsonFileCache = /* @__PURE__ */ new Map();
306
+ class PackageJsonValidationError extends Error {
307
+ constructor(warnings) {
308
+ super(`The following warnings were encountered while normalizing package data:
309
+ - ${warnings.join("\n- ")}`);
310
+ this.name = "PackageJsonValidationError";
311
+ }
312
+ }
313
+ const normalizeInput = (input, strict, ignoreWarnings = []) => {
314
+ const warnings = [];
315
+ normalizeData(
316
+ input,
317
+ (message) => {
318
+ warnings.push(message);
319
+ },
320
+ strict
321
+ );
322
+ if (strict && warnings.length > 0) {
323
+ const filteredWarnings = warnings.filter(
324
+ (warning) => !ignoreWarnings.some((pattern) => {
325
+ if (pattern instanceof RegExp) {
326
+ return pattern.test(warning);
327
+ }
328
+ return pattern === warning;
329
+ })
330
+ );
331
+ if (filteredWarnings.length > 0) {
332
+ throw new PackageJsonValidationError(filteredWarnings);
333
+ }
334
+ }
335
+ return input;
336
+ };
337
+ const parseYamlFile = async (filePath) => {
338
+ const yamlData = await readYaml(filePath);
339
+ return yamlData;
340
+ };
341
+ const parseYamlFileSync = (filePath) => {
342
+ const yamlData = readYamlSync(filePath);
343
+ return yamlData;
344
+ };
345
+ const parseJson5File = async (filePath) => {
346
+ const text = await readFile(filePath);
347
+ return JSON5.parse(text);
348
+ };
349
+ const parseJson5FileSync = (filePath) => {
350
+ const text = readFileSync(filePath);
351
+ return JSON5.parse(text);
352
+ };
353
+ const parsePackageFile = async (filePath, options) => {
354
+ if (options?.yaml !== false && (filePath.endsWith(".yaml") || filePath.endsWith(".yml"))) {
355
+ return parseYamlFile(filePath);
356
+ }
357
+ if (options?.json5 !== false && filePath.endsWith(".json5")) {
358
+ return parseJson5File(filePath);
359
+ }
360
+ return readJson(filePath);
361
+ };
362
+ const parsePackageFileSync = (filePath, options) => {
363
+ if (options?.yaml !== false && (filePath.endsWith(".yaml") || filePath.endsWith(".yml"))) {
364
+ return parseYamlFileSync(filePath);
365
+ }
366
+ if (options?.json5 !== false && filePath.endsWith(".json5")) {
367
+ return parseJson5FileSync(filePath);
368
+ }
369
+ return readJsonSync(filePath);
370
+ };
371
+ const findPackageJson = async (cwd, options = {}) => {
372
+ const findUpConfig = {
373
+ type: "file"
374
+ };
375
+ if (cwd) {
376
+ findUpConfig.cwd = cwd;
377
+ }
378
+ const searchPatterns = ["package.json"];
379
+ if (options.yaml !== false) {
380
+ searchPatterns.push("package.yaml", "package.yml");
381
+ }
382
+ if (options.json5 !== false) {
383
+ searchPatterns.push("package.json5");
384
+ }
385
+ let filePath;
386
+ for await (const pattern of searchPatterns) {
387
+ filePath = await findUp(pattern, findUpConfig);
388
+ if (filePath) {
389
+ break;
390
+ }
391
+ }
392
+ if (!filePath) {
393
+ throw new NotFoundError(`No such file or directory, for ${searchPatterns.join(", ").replace(/, ([^,]*)$/, " or $1")} found.`);
394
+ }
395
+ const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonFileCache;
396
+ if (options.cache && cache.has(filePath)) {
397
+ return cache.get(filePath);
398
+ }
399
+ const packageJson = await parsePackageFile(filePath, options);
400
+ if (options.resolveCatalogs) {
401
+ const catalogs = await readPnpmCatalogs(filePath);
402
+ if (catalogs) {
403
+ resolveCatalogReferences(packageJson, catalogs);
404
+ }
405
+ }
406
+ normalizeInput(packageJson, options.strict ?? false, options.ignoreWarnings);
407
+ const output = {
408
+ packageJson,
409
+ path: filePath
410
+ };
411
+ if (options.cache) {
412
+ cache.set(filePath, output);
413
+ }
414
+ return output;
415
+ };
416
+ const findPackageJsonSync = (cwd, options = {}) => {
417
+ const findUpConfig = {
418
+ type: "file"
419
+ };
420
+ if (cwd) {
421
+ findUpConfig.cwd = cwd;
422
+ }
423
+ const searchPatterns = ["package.json"];
424
+ if (options.yaml !== false) {
425
+ searchPatterns.push("package.yaml", "package.yml");
426
+ }
427
+ if (options.json5 !== false) {
428
+ searchPatterns.push("package.json5");
429
+ }
430
+ let filePath;
431
+ for (const pattern of searchPatterns) {
432
+ filePath = findUpSync(pattern, findUpConfig);
433
+ if (filePath) {
434
+ break;
435
+ }
436
+ }
437
+ if (!filePath) {
438
+ throw new NotFoundError(`No such file or directory, for ${searchPatterns.join(", ").replace(/, ([^,]*)$/, " or $1")} found.`);
439
+ }
440
+ const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonFileCache;
441
+ if (options.cache && cache.has(filePath)) {
442
+ return cache.get(filePath);
443
+ }
444
+ const packageJson = parsePackageFileSync(filePath, options);
445
+ if (options.resolveCatalogs) {
446
+ const catalogs = readPnpmCatalogsSync(filePath);
447
+ if (catalogs) {
448
+ resolveCatalogReferences(packageJson, catalogs);
449
+ }
450
+ }
451
+ normalizeInput(packageJson, options.strict ?? false, options.ignoreWarnings);
452
+ const output = {
453
+ packageJson,
454
+ path: filePath
455
+ };
456
+ if (options.cache) {
457
+ cache.set(filePath, output);
458
+ }
459
+ return output;
460
+ };
461
+ const writePackageJson = async (data, options = {}) => {
462
+ const { cwd, ...writeOptions } = options;
463
+ const directory = toPath(cwd ?? process.cwd());
464
+ await writeJson(join(directory, "package.json"), data, writeOptions);
465
+ };
466
+ const writePackageJsonSync = (data, options = {}) => {
467
+ const { cwd, ...writeOptions } = options;
468
+ const directory = toPath(cwd ?? process.cwd());
469
+ writeJsonSync(join(directory, "package.json"), data, writeOptions);
470
+ };
471
+ const parsePackageJsonSync = (packageFile, options) => {
472
+ const isObject = packageFile !== null && typeof packageFile === "object" && !Array.isArray(packageFile);
473
+ const isString = typeof packageFile === "string";
474
+ if (!isObject && !isString) {
475
+ throw new TypeError("`packageFile` should be either an `object` or a `string`.");
476
+ }
477
+ let json;
478
+ let isFile = false;
479
+ let filePath;
480
+ if (isObject) {
481
+ json = structuredClone(packageFile);
482
+ } else if (existsSync(packageFile)) {
483
+ filePath = packageFile;
484
+ const cache = options?.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonParseCache;
485
+ if (options?.cache && cache.has(filePath)) {
486
+ return cache.get(filePath);
487
+ }
488
+ json = parsePackageFileSync(filePath, options);
489
+ isFile = true;
490
+ } else {
491
+ json = parseJson(packageFile);
492
+ }
493
+ if (options?.resolveCatalogs) {
494
+ if (isFile) {
495
+ const catalogs = readPnpmCatalogsSync(packageFile);
496
+ if (catalogs) {
497
+ resolveCatalogReferences(json, catalogs);
498
+ }
499
+ } else {
500
+ throw new Error("The 'resolveCatalogs' option can only be used on a file path.");
501
+ }
502
+ }
503
+ normalizeInput(json, options?.strict ?? false, options?.ignoreWarnings);
504
+ const result = json;
505
+ if (isFile && filePath && options?.cache) {
506
+ const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonParseCache;
507
+ cache.set(filePath, result);
508
+ }
509
+ return result;
510
+ };
511
+ const parsePackageJson = async (packageFile, options) => {
512
+ const isObject = packageFile !== null && typeof packageFile === "object" && !Array.isArray(packageFile);
513
+ const isString = typeof packageFile === "string";
514
+ if (!isObject && !isString) {
515
+ throw new TypeError("`packageFile` should be either an `object` or a `string`.");
516
+ }
517
+ let json;
518
+ let isFile = false;
519
+ let filePath;
520
+ if (isObject) {
521
+ json = structuredClone(packageFile);
522
+ } else if (existsSync(packageFile)) {
523
+ filePath = packageFile;
524
+ const cache = options?.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonParseCache;
525
+ if (options?.cache && cache.has(filePath)) {
526
+ return cache.get(filePath);
527
+ }
528
+ json = await parsePackageFile(filePath, options);
529
+ isFile = true;
530
+ } else {
531
+ json = parseJson(packageFile);
532
+ }
533
+ if (options?.resolveCatalogs) {
534
+ if (isFile) {
535
+ const catalogs = await readPnpmCatalogs(packageFile);
536
+ if (catalogs) {
537
+ resolveCatalogReferences(json, catalogs);
538
+ }
539
+ } else {
540
+ throw new Error("The 'resolveCatalogs' option can only be used on a file path.");
541
+ }
542
+ }
543
+ normalizeInput(json, options?.strict ?? false, options?.ignoreWarnings);
544
+ const result = json;
545
+ if (isFile && filePath && options?.cache) {
546
+ const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonParseCache;
547
+ cache.set(filePath, result);
548
+ }
549
+ return result;
550
+ };
551
+ const getPackageJsonProperty = (packageJson, property, defaultValue) => getProperty(packageJson, property, defaultValue);
552
+ const hasPackageJsonProperty = (packageJson, property) => hasProperty(packageJson, property);
553
+ const hasPackageJsonAnyDependency = (packageJson, arguments_, options) => {
554
+ const dependencies = getProperty(packageJson, "dependencies", {});
555
+ const devDependencies = getProperty(packageJson, "devDependencies", {});
556
+ const peerDependencies = getProperty(packageJson, "peerDependencies", {});
557
+ const allDependencies = { ...dependencies, ...devDependencies, ...options?.peerDeps === false ? {} : peerDependencies };
558
+ for (const argument of arguments_) {
559
+ if (hasProperty(allDependencies, argument)) {
560
+ return true;
561
+ }
562
+ }
563
+ return false;
564
+ };
565
+ const ensurePackages = async (packageJson, packages, installKey = "dependencies", options = {}) => {
566
+ const dependencies = getProperty(packageJson, "dependencies", {});
567
+ const devDependencies = getProperty(packageJson, "devDependencies", {});
568
+ const peerDependencies = getProperty(packageJson, "peerDependencies", {});
569
+ const nonExistingPackages = [];
570
+ const config = {
571
+ deps: true,
572
+ devDeps: true,
573
+ peerDeps: false,
574
+ ...options
575
+ };
576
+ for (const packageName of packages) {
577
+ if (config.deps && hasProperty(dependencies, packageName) || config.devDeps && hasProperty(devDependencies, packageName) || config.peerDeps && hasProperty(peerDependencies, packageName)) {
578
+ continue;
579
+ }
580
+ nonExistingPackages.push(packageName);
581
+ }
582
+ if (nonExistingPackages.length === 0) {
583
+ return;
584
+ }
585
+ if (process.env.CI || isNode && !process.stdout?.isTTY) {
586
+ const message = `Skipping package installation for [${packages.join(", ")}] because the process is not interactive.`;
587
+ if (options.throwOnWarn) {
588
+ throw new Error(message);
589
+ } else if (options.logger?.warn) {
590
+ options.logger.warn(message);
591
+ } else {
592
+ console.warn(message);
593
+ }
594
+ return;
595
+ }
596
+ if (typeof config.confirm?.message === "function") {
597
+ config.confirm.message = config.confirm.message(nonExistingPackages);
598
+ }
599
+ if (config.confirm?.message === void 0) {
600
+ const message = `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?`;
601
+ if (config.confirm === void 0) {
602
+ config.confirm = {
603
+ message
604
+ };
605
+ } else {
606
+ config.confirm.message = message;
607
+ }
608
+ }
609
+ const answer = await confirm(config.confirm);
610
+ if (!answer) {
611
+ return;
612
+ }
613
+ await installPackage(nonExistingPackages, {
614
+ ...config.installPackage,
615
+ cwd: config.cwd ? toPath(config.cwd) : void 0,
616
+ dev: installKey === "devDependencies"
617
+ });
618
+ };
619
+
620
+ export { ensurePackages, findPackageJson, findPackageJsonSync, getPackageJsonProperty, hasPackageJsonAnyDependency, hasPackageJsonProperty, parsePackageJson, parsePackageJsonSync, writePackageJson, writePackageJsonSync };
@@ -1,13 +1,235 @@
1
- var v=Object.defineProperty;var d=(n,e)=>v(n,"name",{value:e,configurable:!0});import{createRequire as _}from"node:module";import{findUpSync as m,findUp as h}from"@visulima/fs";import{NotFoundError as p}from"@visulima/fs/error";import{join as l,dirname as t}from"@visulima/path";import{parsePackageJsonSync as M,parsePackageJson as $}from"./package-json.js";const P=_(import.meta.url),s=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,u=d(n=>{if(typeof s<"u"&&s.versions&&s.versions.node){const[e,a]=s.versions.node.split(".").map(Number);if(e>22||e===22&&a>=3||e===20&&a>=16)return s.getBuiltinModule(n)}return P(n)},"__cjs_getBuiltinModule"),{execSync:W}=u("node:child_process"),{existsSync:k,readFileSync:S}=u("node:fs");var F=Object.defineProperty,r=d((n,e)=>F(n,"name",{value:e,configurable:!0}),"t");const f=["yarn.lock","package-lock.json","pnpm-lock.yaml","npm-shrinkwrap.json","bun.lockb"],y=r(n=>{let e;if(f.forEach(i=>{!e&&k(l(n,i))&&(e=l(n,i))}),e)return e;const a=l(n,"package.json");if(k(a)&&M(S(a,"utf8")).packageManager!==void 0)return a},"packageMangerFindUpMatcher"),E=r(async n=>{if(!n)throw new p("Could not find a package manager");if(n.endsWith("package.json")){const e=await $(n);if(e.packageManager){const a=["npm","yarn","pnpm","bun"].find(i=>e.packageManager.startsWith(i));if(a)return{packageManager:a,path:t(n)}}}if(n.endsWith("yarn.lock"))return{packageManager:"yarn",path:t(n)};if(n.endsWith("package-lock.json")||n.endsWith("npm-shrinkwrap.json"))return{packageManager:"npm",path:t(n)};if(n.endsWith("pnpm-lock.yaml"))return{packageManager:"pnpm",path:t(n)};if(n.endsWith("bun.lockb"))return{packageManager:"bun",path:t(n)};throw new p("Could not find a package manager")},"findPackageManagerOnFile"),x=r(n=>{if(!n)throw new p("Could not find a package manager");if(n.endsWith("package.json")){const e=M(n);if(e.packageManager){const a=["npm","yarn","pnpm","bun"].find(i=>e.packageManager.startsWith(i));if(a)return{packageManager:a,path:t(n)}}}if(n.endsWith("yarn.lock"))return{packageManager:"yarn",path:t(n)};if(n.endsWith("package-lock.json")||n.endsWith("npm-shrinkwrap.json"))return{packageManager:"npm",path:t(n)};if(n.endsWith("pnpm-lock.yaml"))return{packageManager:"pnpm",path:t(n)};if(n.endsWith("bun.lockb"))return{packageManager:"bun",path:t(n)};throw new p("Could not find a package manager")},"findPackageManagerOnFileSync"),U=r(async n=>{const e=await h(f,{type:"file",...n&&{cwd:n}});if(!e)throw new Error("Could not find lock file");return e},"findLockFile"),q=r(n=>{const e=m(f,{type:"file",...n&&{cwd:n}});if(!e)throw new Error("Could not find lock file");return e},"findLockFileSync"),B=r(async n=>{const e=await h(y,{...n&&{cwd:n}});return E(e)},"findPackageManager"),D=r(n=>{const e=m(y,{...n&&{cwd:n}});return x(e)},"findPackageManagerSync"),J=r(n=>W(`${n} --version`).toString("utf8").trim(),"getPackageManagerVersion"),R=r(async()=>{if(!process.env.npm_config_user_agent)return;const n=process.env.npm_config_user_agent.split(" ")[0],e=n.lastIndexOf("/"),a=n.slice(0,Math.max(0,e));return{name:a==="npminstall"?"cnpm":a,version:n.slice(Math.max(0,e+1))}},"identifyInitiatingPackageManager"),V=r((n,e,a)=>{const i=e.length===1?"":"s";if(a.packageManagers===void 0&&(a.packageManagers=["npm","pnpm","yarn"]),a.packageManagers.length===0)throw new Error("No package managers provided, please provide at least one package manager");if(e.length===0)throw new Error("No missing packages provided, please provide at least one missing package");let g=`
2
- ${a.preMessage??""}
3
- ${n} could not find the following package${i}
1
+ import { createRequire as __cjs_createRequire } from "node:module";
4
2
 
5
- ${e.join(`
6
- `)}
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
7
4
 
8
- To install the missing package${i}, please run the following command:
9
- `;const w=r(o=>o.split("@").includes("@")?o:`${o}@latest`,"atLatest"),j=a.packageManagers.map(o=>{const c=e.map(b=>w(b)).join(" ");switch(o){case"bun":return` bun add ${c} -D`;case"npm":return` npm install ${c} --save-dev`;case"pnpm":return` pnpm add ${c} -D`;case"yarn":return` yarn add ${c} --dev`;default:throw new Error("Unknown package manager")}});return g+=j.join(`
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
10
6
 
11
- or
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
12
19
 
13
- `),a.postMessage&&(g+=a.postMessage),g},"generateMissingPackagesInstallMessage");export{U as findLockFile,q as findLockFileSync,B as findPackageManager,D as findPackageManagerSync,V as generateMissingPackagesInstallMessage,J as getPackageManagerVersion,R as identifyInitiatingPackageManager};
20
+ const {
21
+ execSync
22
+ } = __cjs_getBuiltinModule("node:child_process");
23
+ const {
24
+ existsSync,
25
+ readFileSync
26
+ } = __cjs_getBuiltinModule("node:fs");
27
+ import { findUp, findUpSync } from '@visulima/fs';
28
+ import { NotFoundError } from '@visulima/fs/error';
29
+ import { join, dirname } from '@visulima/path';
30
+ import { parsePackageJsonSync, parsePackageJson } from './package-json.js';
31
+
32
+ const lockFileNames = ["yarn.lock", "package-lock.json", "pnpm-lock.yaml", "npm-shrinkwrap.json", "bun.lockb"];
33
+ const packageMangerFindUpMatcher = (directory) => {
34
+ let lockFile;
35
+ lockFileNames.forEach((lockFileName) => {
36
+ if (!lockFile && existsSync(join(directory, lockFileName))) {
37
+ lockFile = join(directory, lockFileName);
38
+ }
39
+ });
40
+ if (lockFile) {
41
+ return lockFile;
42
+ }
43
+ const packageJsonFilePath = join(directory, "package.json");
44
+ if (existsSync(packageJsonFilePath)) {
45
+ const packageJson = parsePackageJsonSync(readFileSync(packageJsonFilePath, "utf8"));
46
+ if (packageJson.packageManager !== void 0) {
47
+ return packageJsonFilePath;
48
+ }
49
+ }
50
+ return void 0;
51
+ };
52
+ const findPackageManagerOnFile = async (foundFile) => {
53
+ if (!foundFile) {
54
+ throw new NotFoundError("Could not find a package manager");
55
+ }
56
+ if (foundFile.endsWith("package.json")) {
57
+ const packageJson = await parsePackageJson(foundFile);
58
+ if (packageJson.packageManager) {
59
+ const packageManagerNames = ["npm", "yarn", "pnpm", "bun"];
60
+ const foundPackageManager = packageManagerNames.find((prefix) => packageJson.packageManager.startsWith(prefix));
61
+ if (foundPackageManager) {
62
+ return {
63
+ packageManager: foundPackageManager,
64
+ path: dirname(foundFile)
65
+ };
66
+ }
67
+ }
68
+ }
69
+ if (foundFile.endsWith("yarn.lock")) {
70
+ return {
71
+ packageManager: "yarn",
72
+ path: dirname(foundFile)
73
+ };
74
+ }
75
+ if (foundFile.endsWith("package-lock.json") || foundFile.endsWith("npm-shrinkwrap.json")) {
76
+ return {
77
+ packageManager: "npm",
78
+ path: dirname(foundFile)
79
+ };
80
+ }
81
+ if (foundFile.endsWith("pnpm-lock.yaml")) {
82
+ return {
83
+ packageManager: "pnpm",
84
+ path: dirname(foundFile)
85
+ };
86
+ }
87
+ if (foundFile.endsWith("bun.lockb")) {
88
+ return {
89
+ packageManager: "bun",
90
+ path: dirname(foundFile)
91
+ };
92
+ }
93
+ throw new NotFoundError("Could not find a package manager");
94
+ };
95
+ const findPackageManagerOnFileSync = (foundFile) => {
96
+ if (!foundFile) {
97
+ throw new NotFoundError("Could not find a package manager");
98
+ }
99
+ if (foundFile.endsWith("package.json")) {
100
+ const packageJson = parsePackageJsonSync(foundFile);
101
+ if (packageJson.packageManager) {
102
+ const packageManagerNames = ["npm", "yarn", "pnpm", "bun"];
103
+ const foundPackageManager = packageManagerNames.find((prefix) => packageJson.packageManager.startsWith(prefix));
104
+ if (foundPackageManager) {
105
+ return {
106
+ packageManager: foundPackageManager,
107
+ path: dirname(foundFile)
108
+ };
109
+ }
110
+ }
111
+ }
112
+ if (foundFile.endsWith("yarn.lock")) {
113
+ return {
114
+ packageManager: "yarn",
115
+ path: dirname(foundFile)
116
+ };
117
+ }
118
+ if (foundFile.endsWith("package-lock.json") || foundFile.endsWith("npm-shrinkwrap.json")) {
119
+ return {
120
+ packageManager: "npm",
121
+ path: dirname(foundFile)
122
+ };
123
+ }
124
+ if (foundFile.endsWith("pnpm-lock.yaml")) {
125
+ return {
126
+ packageManager: "pnpm",
127
+ path: dirname(foundFile)
128
+ };
129
+ }
130
+ if (foundFile.endsWith("bun.lockb")) {
131
+ return {
132
+ packageManager: "bun",
133
+ path: dirname(foundFile)
134
+ };
135
+ }
136
+ throw new NotFoundError("Could not find a package manager");
137
+ };
138
+ const findLockFile = async (cwd) => {
139
+ const filePath = await findUp(lockFileNames, {
140
+ type: "file",
141
+ ...cwd && { cwd }
142
+ });
143
+ if (!filePath) {
144
+ throw new Error("Could not find lock file");
145
+ }
146
+ return filePath;
147
+ };
148
+ const findLockFileSync = (cwd) => {
149
+ const filePath = findUpSync(lockFileNames, {
150
+ type: "file",
151
+ ...cwd && { cwd }
152
+ });
153
+ if (!filePath) {
154
+ throw new Error("Could not find lock file");
155
+ }
156
+ return filePath;
157
+ };
158
+ const findPackageManager = async (cwd) => {
159
+ const foundFile = await findUp(packageMangerFindUpMatcher, {
160
+ ...cwd && { cwd }
161
+ });
162
+ return findPackageManagerOnFile(foundFile);
163
+ };
164
+ const findPackageManagerSync = (cwd) => {
165
+ const foundFile = findUpSync(packageMangerFindUpMatcher, {
166
+ ...cwd && { cwd }
167
+ });
168
+ return findPackageManagerOnFileSync(foundFile);
169
+ };
170
+ const getPackageManagerVersion = (name) => execSync(`${name} --version`).toString("utf8").trim();
171
+ const identifyInitiatingPackageManager = async () => {
172
+ if (!process.env.npm_config_user_agent) {
173
+ return void 0;
174
+ }
175
+ const pmSpec = process.env.npm_config_user_agent.split(" ")[0];
176
+ const separatorPos = pmSpec.lastIndexOf("/");
177
+ const name = pmSpec.slice(0, Math.max(0, separatorPos));
178
+ return {
179
+ name: name === "npminstall" ? "cnpm" : name,
180
+ version: pmSpec.slice(Math.max(0, separatorPos + 1))
181
+ };
182
+ };
183
+ const generateMissingPackagesInstallMessage = (packageName, missingPackages, options) => {
184
+ const s = missingPackages.length === 1 ? "" : "s";
185
+ if (options.packageManagers === void 0) {
186
+ options.packageManagers = ["npm", "pnpm", "yarn"];
187
+ }
188
+ if (options.packageManagers.length === 0) {
189
+ throw new Error("No package managers provided, please provide at least one package manager");
190
+ }
191
+ if (missingPackages.length === 0) {
192
+ throw new Error("No missing packages provided, please provide at least one missing package");
193
+ }
194
+ let message = `
195
+ ${options.preMessage ?? ""}
196
+ ${packageName} could not find the following package${s}
197
+
198
+ ${missingPackages.join("\n ")}
199
+
200
+ To install the missing package${s}, please run the following command:
201
+ `;
202
+ const atLatest = (name) => {
203
+ if (!name.split("@").includes("@")) {
204
+ return `${name}@latest`;
205
+ }
206
+ return name;
207
+ };
208
+ const packageManagerCommands = options.packageManagers.map((packageManager) => {
209
+ const missingPackagesString = missingPackages.map((element) => atLatest(element)).join(" ");
210
+ switch (packageManager) {
211
+ case "bun": {
212
+ return ` bun add ${missingPackagesString} -D`;
213
+ }
214
+ case "npm": {
215
+ return ` npm install ${missingPackagesString} --save-dev`;
216
+ }
217
+ case "pnpm": {
218
+ return ` pnpm add ${missingPackagesString} -D`;
219
+ }
220
+ case "yarn": {
221
+ return ` yarn add ${missingPackagesString} --dev`;
222
+ }
223
+ default: {
224
+ throw new Error("Unknown package manager");
225
+ }
226
+ }
227
+ });
228
+ message += packageManagerCommands.join("\n\nor\n\n");
229
+ if (options.postMessage) {
230
+ message += options.postMessage;
231
+ }
232
+ return message;
233
+ };
234
+
235
+ export { findLockFile, findLockFileSync, findPackageManager, findPackageManagerSync, generateMissingPackagesInstallMessage, getPackageManagerVersion, identifyInitiatingPackageManager };
package/dist/package.js CHANGED
@@ -1 +1,81 @@
1
- var u=Object.defineProperty;var c=(e,o)=>u(e,"name",{value:o,configurable:!0});import{createRequire as l}from"node:module";import{findUp as a,findUpSync as f,readJsonSync as _}from"@visulima/fs";import{dirname as r,join as d}from"@visulima/path";import{findLockFile as w,findLockFileSync as j}from"./package-manager.js";const g=l(import.meta.url),i=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,y=c(e=>{if(typeof i<"u"&&i.versions&&i.versions.node){const[o,n]=i.versions.node.split(".").map(Number);if(o>22||o===22&&n>=3||o===20&&n>=16)return i.getBuiltinModule(e)}return g(e)},"__cjs_getBuiltinModule"),{existsSync:m}=y("node:fs");var k=Object.defineProperty,s=c((e,o)=>k(e,"name",{value:o,configurable:!0}),"r");const p=s(e=>{if(m(d(e,"package.json"))){const o=_(d(e,"package.json"));if(o.name&&o.private!==!0)return"package.json"}},"packageJsonMatcher"),S=s(async e=>{try{const t=await w(e);return r(t)}catch{}const o=await a(".git/config",{...e&&{cwd:e},type:"file"});if(o)return r(r(o));const n=await a(p,{...e&&{cwd:e},type:"file"});if(n)return r(n);throw new Error("Could not find root directory")},"findPackageRoot"),q=s(e=>{try{const t=j(e);return r(t)}catch{}const o=f(".git/config",{...e&&{cwd:e},type:"file"});if(o)return r(r(o));const n=f(p,{...e&&{cwd:e},type:"file"});if(n)return r(n);throw new Error("Could not find root directory")},"findPackageRootSync");export{S as findPackageRoot,q as findPackageRootSync};
1
+ import { createRequire as __cjs_createRequire } from "node:module";
2
+
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
4
+
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
+
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
19
+
20
+ const {
21
+ existsSync
22
+ } = __cjs_getBuiltinModule("node:fs");
23
+ import { findUp, findUpSync, readJsonSync } from '@visulima/fs';
24
+ import { dirname, join } from '@visulima/path';
25
+ import { findLockFile, findLockFileSync } from './package-manager.js';
26
+
27
+ const packageJsonMatcher = (directory) => {
28
+ if (existsSync(join(directory, "package.json"))) {
29
+ const packageJson = readJsonSync(join(directory, "package.json"));
30
+ if (packageJson.name && packageJson.private !== true) {
31
+ return "package.json";
32
+ }
33
+ }
34
+ return void 0;
35
+ };
36
+ const findPackageRoot = async (cwd) => {
37
+ try {
38
+ const lockFile = await findLockFile(cwd);
39
+ return dirname(lockFile);
40
+ } catch {
41
+ }
42
+ const gitConfig = await findUp(".git/config", {
43
+ ...cwd && { cwd },
44
+ type: "file"
45
+ });
46
+ if (gitConfig) {
47
+ return dirname(dirname(gitConfig));
48
+ }
49
+ const filePath = await findUp(packageJsonMatcher, {
50
+ ...cwd && { cwd },
51
+ type: "file"
52
+ });
53
+ if (filePath) {
54
+ return dirname(filePath);
55
+ }
56
+ throw new Error("Could not find root directory");
57
+ };
58
+ const findPackageRootSync = (cwd) => {
59
+ try {
60
+ const lockFile = findLockFileSync(cwd);
61
+ return dirname(lockFile);
62
+ } catch {
63
+ }
64
+ const gitConfig = findUpSync(".git/config", {
65
+ ...cwd && { cwd },
66
+ type: "file"
67
+ });
68
+ if (gitConfig) {
69
+ return dirname(dirname(gitConfig));
70
+ }
71
+ const filePath = findUpSync(packageJsonMatcher, {
72
+ ...cwd && { cwd },
73
+ type: "file"
74
+ });
75
+ if (filePath) {
76
+ return dirname(filePath);
77
+ }
78
+ throw new Error("Could not find root directory");
79
+ };
80
+
81
+ export { findPackageRoot, findPackageRootSync };
@@ -0,0 +1,46 @@
1
+ import { findPackageManagerSync } from '../package-manager.js';
2
+
3
+ class PackageNotFoundError extends Error {
4
+ /**
5
+ * @param packageName The name of the package that was not found.
6
+ * @param packageManager The package manager used to install the package.
7
+ */
8
+ constructor(packageName, packageManager) {
9
+ if (typeof packageName === "string") {
10
+ packageName = [packageName];
11
+ }
12
+ if (packageName.length === 0) {
13
+ super("Package was not found.");
14
+ return;
15
+ }
16
+ if (packageManager === void 0) {
17
+ try {
18
+ const foundManager = findPackageManagerSync();
19
+ packageManager = foundManager.packageManager;
20
+ } catch {
21
+ }
22
+ }
23
+ if (packageManager === void 0) {
24
+ packageManager = "npm";
25
+ }
26
+ super(`Package '${packageName.join(" ")}' was not found. Please install it using '${packageManager} install ${packageName.join(" ")}'`);
27
+ }
28
+ // eslint-disable-next-line class-methods-use-this
29
+ get code() {
30
+ return "PACKAGE_NOT_FOUND";
31
+ }
32
+ // eslint-disable-next-line class-methods-use-this,@typescript-eslint/explicit-module-boundary-types
33
+ set code(_name) {
34
+ throw new Error("Cannot overwrite code PACKAGE_NOT_FOUND");
35
+ }
36
+ // eslint-disable-next-line class-methods-use-this
37
+ get name() {
38
+ return "PackageNotFoundError";
39
+ }
40
+ // eslint-disable-next-line class-methods-use-this,@typescript-eslint/explicit-module-boundary-types
41
+ set name(_name) {
42
+ throw new Error("Cannot overwrite name of PackageNotFoundError");
43
+ }
44
+ }
45
+
46
+ export { PackageNotFoundError as default };
package/dist/pnpm.js CHANGED
@@ -1 +1,105 @@
1
- var y=Object.defineProperty;var f=(t,a)=>y(t,"name",{value:a,configurable:!0});import{findUpSync as u,findUp as m}from"@visulima/fs";import{readYamlSync as v,readYaml as k}from"@visulima/fs/yaml";import{dirname as l,relative as b}from"@visulima/path";var h=Object.defineProperty,i=f((t,a)=>h(t,"name",{value:a,configurable:!0}),"c");const d=i((t,a,e)=>{const c=l(t),o=l(a),g=o===c?".":b(c,o);return e.some(p=>{const n=p.startsWith("./")?p.slice(2):p,s=g.startsWith("./")?g.slice(2):g;if(n==="."&&s===".")return!0;if(n.endsWith("/**")){const r=n.slice(0,-3);return s===r||s.startsWith(`${r}/`)}if(n.endsWith("/*")){const r=n.slice(0,-2);return r===""?s!=="."&&!s.includes("/"):s.startsWith(`${r}/`)||s===r}return s===n||s.startsWith(`${n}/`)})},"isPackageInWorkspace"),D=i(async t=>{const a=await m("pnpm-workspace.yaml",{cwd:l(t),type:"file"});if(!a)return;const e=await k(a),c=Array.isArray(e.packages)?e.packages:[];if(!d(a,t,c))return;const o={};return e.catalog&&typeof e.catalog=="object"&&(o.catalog=e.catalog),e.catalogs&&typeof e.catalogs=="object"&&(o.catalogs=e.catalogs),Object.keys(o).length>0?o:void 0},"readPnpmCatalogs"),A=i(t=>{const a=u("pnpm-workspace.yaml",{cwd:l(t),type:"file"});if(!a)return;const e=v(a),c=Array.isArray(e.packages)?e.packages:[];if(!d(a,t,c))return;const o={};return e.catalog&&typeof e.catalog=="object"&&(o.catalog=e.catalog),e.catalogs&&typeof e.catalogs=="object"&&(o.catalogs=e.catalogs),Object.keys(o).length>0?o:void 0},"readPnpmCatalogsSync"),C=i((t,a,e)=>{if(a==="catalog:")return e.catalog?.[t];if(a.startsWith("catalog:")){const c=a.slice(8);return e.catalogs?.[c]?.[t]}},"resolveCatalogReference"),W=i((t,a)=>{for(const[e,c]of Object.entries(t)){if(typeof c!="string")continue;const o=C(e,c,a);o&&(t[e]=o)}},"resolveDependenciesCatalogReferences"),O=i((t,a)=>{const e=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(const c of e){if(!t[c]||typeof t[c]!="object")continue;const o=t[c];W(o,a)}},"resolveCatalogReferences");export{d as isPackageInWorkspace,D as readPnpmCatalogs,A as readPnpmCatalogsSync,C as resolveCatalogReference,O as resolveCatalogReferences,W as resolveDependenciesCatalogReferences};
1
+ import { findUp, findUpSync } from '@visulima/fs';
2
+ import { readYaml, readYamlSync } from '@visulima/fs/yaml';
3
+ import { dirname, relative } from '@visulima/path';
4
+
5
+ const isPackageInWorkspace = (workspacePath, packagePath, workspacePackages) => {
6
+ const workspaceDirectory = dirname(workspacePath);
7
+ const packageDirectory = dirname(packagePath);
8
+ const relativePath = packageDirectory === workspaceDirectory ? "." : relative(workspaceDirectory, packageDirectory);
9
+ return workspacePackages.some((pattern) => {
10
+ const normalizedPattern = pattern.startsWith("./") ? pattern.slice(2) : pattern;
11
+ const normalizedRelativePath = relativePath.startsWith("./") ? relativePath.slice(2) : relativePath;
12
+ if (normalizedPattern === "." && normalizedRelativePath === ".") {
13
+ return true;
14
+ }
15
+ if (normalizedPattern.endsWith("/**")) {
16
+ const prefix = normalizedPattern.slice(0, -3);
17
+ return normalizedRelativePath === prefix || normalizedRelativePath.startsWith(`${prefix}/`);
18
+ }
19
+ if (normalizedPattern.endsWith("/*")) {
20
+ const prefix = normalizedPattern.slice(0, -2);
21
+ if (prefix === "") {
22
+ return normalizedRelativePath !== "." && !normalizedRelativePath.includes("/");
23
+ }
24
+ return normalizedRelativePath.startsWith(`${prefix}/`) || normalizedRelativePath === prefix;
25
+ }
26
+ return normalizedRelativePath === normalizedPattern || normalizedRelativePath.startsWith(`${normalizedPattern}/`);
27
+ });
28
+ };
29
+ const readPnpmCatalogs = async (packagePath) => {
30
+ const workspacePath = await findUp("pnpm-workspace.yaml", {
31
+ cwd: dirname(packagePath),
32
+ type: "file"
33
+ });
34
+ if (!workspacePath) {
35
+ return void 0;
36
+ }
37
+ const workspaceData = await readYaml(workspacePath);
38
+ const workspacePackages = Array.isArray(workspaceData.packages) ? workspaceData.packages : [];
39
+ if (!isPackageInWorkspace(workspacePath, packagePath, workspacePackages)) {
40
+ return void 0;
41
+ }
42
+ const catalogs = {};
43
+ if (workspaceData.catalog && typeof workspaceData.catalog === "object") {
44
+ catalogs.catalog = workspaceData.catalog;
45
+ }
46
+ if (workspaceData.catalogs && typeof workspaceData.catalogs === "object") {
47
+ catalogs.catalogs = workspaceData.catalogs;
48
+ }
49
+ return Object.keys(catalogs).length > 0 ? catalogs : void 0;
50
+ };
51
+ const readPnpmCatalogsSync = (packagePath) => {
52
+ const workspacePath = findUpSync("pnpm-workspace.yaml", {
53
+ cwd: dirname(packagePath),
54
+ type: "file"
55
+ });
56
+ if (!workspacePath) {
57
+ return void 0;
58
+ }
59
+ const workspaceData = readYamlSync(workspacePath);
60
+ const workspacePackages = Array.isArray(workspaceData.packages) ? workspaceData.packages : [];
61
+ if (!isPackageInWorkspace(workspacePath, packagePath, workspacePackages)) {
62
+ return void 0;
63
+ }
64
+ const catalogs = {};
65
+ if (workspaceData.catalog && typeof workspaceData.catalog === "object") {
66
+ catalogs.catalog = workspaceData.catalog;
67
+ }
68
+ if (workspaceData.catalogs && typeof workspaceData.catalogs === "object") {
69
+ catalogs.catalogs = workspaceData.catalogs;
70
+ }
71
+ return Object.keys(catalogs).length > 0 ? catalogs : void 0;
72
+ };
73
+ const resolveCatalogReference = (packageName, versionSpec, catalogs) => {
74
+ if (versionSpec === "catalog:") {
75
+ return catalogs.catalog?.[packageName];
76
+ }
77
+ if (versionSpec.startsWith("catalog:")) {
78
+ const catalogName = versionSpec.slice(8);
79
+ return catalogs.catalogs?.[catalogName]?.[packageName];
80
+ }
81
+ return void 0;
82
+ };
83
+ const resolveDependenciesCatalogReferences = (dependencies, catalogs) => {
84
+ for (const [packageName, versionSpec] of Object.entries(dependencies)) {
85
+ if (typeof versionSpec !== "string") {
86
+ continue;
87
+ }
88
+ const resolvedVersion = resolveCatalogReference(packageName, versionSpec, catalogs);
89
+ if (resolvedVersion) {
90
+ dependencies[packageName] = resolvedVersion;
91
+ }
92
+ }
93
+ };
94
+ const resolveCatalogReferences = (packageJson, catalogs) => {
95
+ const dependencyFields = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
96
+ for (const field of dependencyFields) {
97
+ if (!packageJson[field] || typeof packageJson[field] !== "object") {
98
+ continue;
99
+ }
100
+ const dependencies = packageJson[field];
101
+ resolveDependenciesCatalogReferences(dependencies, catalogs);
102
+ }
103
+ };
104
+
105
+ export { isPackageInWorkspace, readPnpmCatalogs, readPnpmCatalogsSync, resolveCatalogReference, resolveCatalogReferences, resolveDependenciesCatalogReferences };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/package",
3
- "version": "5.0.0-alpha.4",
3
+ "version": "5.0.0-alpha.5",
4
4
  "description": "A comprehensive package management utility that helps you find root directories, monorepos, package managers, and parse package.json, package.yaml, and package.json5 files with advanced features like catalog resolution.",
5
5
  "keywords": [
6
6
  "anolilab",
@@ -97,13 +97,15 @@
97
97
  ],
98
98
  "dependencies": {
99
99
  "@antfu/install-pkg": "^1.1.0",
100
- "@visulima/fs": "5.0.0-alpha.4",
101
- "@visulima/path": "3.0.0-alpha.5",
100
+ "@visulima/fs": "5.0.0-alpha.5",
101
+ "@visulima/path": "3.0.0-alpha.6",
102
102
  "json5": "^2.2.3",
103
103
  "normalize-package-data": "^8.0.0",
104
- "type-fest": "^5.4.4",
105
- "yaml": "^2.8.2"
104
+ "type-fest": "5.5.0",
105
+ "yaml": "2.8.3"
106
106
  },
107
+ "peerDependencies": {},
108
+ "optionalDependencies": {},
107
109
  "engines": {
108
110
  "node": ">=22.13 <=25.x"
109
111
  },
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var a=(t,e)=>o(t,"name",{value:e,configurable:!0});import{findPackageManagerSync as n}from"../package-manager.js";var c=Object.defineProperty,i=a((t,e)=>c(t,"name",{value:e,configurable:!0}),"t");class g extends Error{static{a(this,"u")}static{i(this,"PackageNotFoundError")}constructor(e,r){if(typeof e=="string"&&(e=[e]),e.length===0){super("Package was not found.");return}if(r===void 0)try{r=n().packageManager}catch{}r===void 0&&(r="npm"),super(`Package '${e.join(" ")}' was not found. Please install it using '${r} install ${e.join(" ")}'`)}get code(){return"PACKAGE_NOT_FOUND"}set code(e){throw new Error("Cannot overwrite code PACKAGE_NOT_FOUND")}get name(){return"PackageNotFoundError"}set name(e){throw new Error("Cannot overwrite name of PackageNotFoundError")}}export{g as default};