@hogsend/cli 0.0.1
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/LICENSE +93 -0
- package/dist/bin.js +231 -0
- package/dist/bin.js.map +1 -0
- package/dist/index.js +115 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -0
- package/src/__tests__/eject.test.ts +163 -0
- package/src/bin.ts +140 -0
- package/src/eject.ts +189 -0
- package/src/index.ts +7 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Elastic License 2.0 (ELv2)
|
|
2
|
+
|
|
3
|
+
Copyright 2025 Doug Silkstone and Hogsend contributors
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
8
|
+
|
|
9
|
+
## Copyright License
|
|
10
|
+
|
|
11
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
12
|
+
non-sublicensable, non-transferable license to use, copy, distribute, make
|
|
13
|
+
available, and prepare derivative works of the software, in each case subject to
|
|
14
|
+
the limitations and conditions below.
|
|
15
|
+
|
|
16
|
+
## Limitations
|
|
17
|
+
|
|
18
|
+
You may not provide the software to third parties as a hosted or managed
|
|
19
|
+
service, where the service provides users with access to any substantial set of
|
|
20
|
+
the features or functionality of the software.
|
|
21
|
+
|
|
22
|
+
You may not move, change, disable, or circumvent the license key functionality
|
|
23
|
+
in the software, and you may not remove or obscure any functionality in the
|
|
24
|
+
software that is protected by the license key.
|
|
25
|
+
|
|
26
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices
|
|
27
|
+
of the licensor in the software. Any use of the licensor's trademarks is subject
|
|
28
|
+
to applicable law.
|
|
29
|
+
|
|
30
|
+
## Patents
|
|
31
|
+
|
|
32
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
33
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
34
|
+
sale, import and have imported the software, in each case subject to the
|
|
35
|
+
limitations and conditions in this license. This license does not cover any
|
|
36
|
+
patent claims that you cause to be infringed by modifications or additions to
|
|
37
|
+
the software. If you or your company make any written claim that the software
|
|
38
|
+
infringes or contributes to infringement of any patent, your patent license for
|
|
39
|
+
the software granted under these terms ends immediately. If your company makes
|
|
40
|
+
such a claim, your patent license ends immediately for work on behalf of your
|
|
41
|
+
company.
|
|
42
|
+
|
|
43
|
+
## Notices
|
|
44
|
+
|
|
45
|
+
You must ensure that anyone who gets a copy of any part of the software from you
|
|
46
|
+
also gets a copy of these terms.
|
|
47
|
+
|
|
48
|
+
If you modify the software, you must include in any modified copies of the
|
|
49
|
+
software prominent notices stating that you have modified the software.
|
|
50
|
+
|
|
51
|
+
## No Other Rights
|
|
52
|
+
|
|
53
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
54
|
+
these terms.
|
|
55
|
+
|
|
56
|
+
## Termination
|
|
57
|
+
|
|
58
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
59
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
60
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
61
|
+
later than 30 days after you receive that notice, your licenses will be
|
|
62
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
63
|
+
reinstatement, any additional violation of these terms will cause your licenses
|
|
64
|
+
to terminate automatically and permanently.
|
|
65
|
+
|
|
66
|
+
## No Liability
|
|
67
|
+
|
|
68
|
+
*As far as the law allows, the software comes as is, without any warranty or
|
|
69
|
+
condition, and the licensor will not be liable to you for any damages arising out
|
|
70
|
+
of these terms or the use or nature of the software, under any kind of legal
|
|
71
|
+
claim.*
|
|
72
|
+
|
|
73
|
+
## Definitions
|
|
74
|
+
|
|
75
|
+
The **licensor** is the entity offering these terms, and the **software** is the
|
|
76
|
+
software the licensor makes available under these terms, including any portion
|
|
77
|
+
of it.
|
|
78
|
+
|
|
79
|
+
**you** refers to the individual or entity agreeing to these terms.
|
|
80
|
+
|
|
81
|
+
**your company** is any legal entity, sole proprietorship, or other kind of
|
|
82
|
+
organization that you work for, plus all organizations that have control over,
|
|
83
|
+
are under the control of, or are under common control with that organization.
|
|
84
|
+
**control** means ownership of substantially all the assets of an entity, or the
|
|
85
|
+
power to direct its management and policies by vote, contract, or otherwise.
|
|
86
|
+
Control can be direct or indirect.
|
|
87
|
+
|
|
88
|
+
**your licenses** are all the licenses granted to you for the software under
|
|
89
|
+
these terms.
|
|
90
|
+
|
|
91
|
+
**use** means anything you do with the software requiring one of your licenses.
|
|
92
|
+
|
|
93
|
+
**trademark** means trademarks, service marks, and similar rights.
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/bin.ts
|
|
4
|
+
import { existsSync as existsSync2, realpathSync } from "fs";
|
|
5
|
+
import { createRequire } from "module";
|
|
6
|
+
import { dirname, join as join2, sep as sep2 } from "path";
|
|
7
|
+
import { parseArgs } from "util";
|
|
8
|
+
|
|
9
|
+
// src/eject.ts
|
|
10
|
+
import { existsSync } from "fs";
|
|
11
|
+
import { cp, readFile, rm, stat, writeFile } from "fs/promises";
|
|
12
|
+
import { basename, join, relative, sep } from "path";
|
|
13
|
+
var EjectError = class extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "EjectError";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
var EXCLUDED_NAMES = /* @__PURE__ */ new Set([
|
|
20
|
+
"node_modules",
|
|
21
|
+
"dist",
|
|
22
|
+
".turbo",
|
|
23
|
+
".changeset",
|
|
24
|
+
"CHANGELOG.md"
|
|
25
|
+
]);
|
|
26
|
+
async function readPackageJson(file) {
|
|
27
|
+
const raw = await readFile(file, "utf8");
|
|
28
|
+
return JSON.parse(raw);
|
|
29
|
+
}
|
|
30
|
+
async function writePackageJson(file, value) {
|
|
31
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}
|
|
32
|
+
`, "utf8");
|
|
33
|
+
}
|
|
34
|
+
async function eject(opts) {
|
|
35
|
+
const { pkg, consumerRoot, sourceDir, force = false } = opts;
|
|
36
|
+
const vendorName = basename(pkg);
|
|
37
|
+
const vendorPath = join(consumerRoot, "vendor", vendorName);
|
|
38
|
+
const consumerPkgPath = join(consumerRoot, "package.json");
|
|
39
|
+
const consumerPkg = await readPackageJson(consumerPkgPath);
|
|
40
|
+
let depMap;
|
|
41
|
+
let depSpecBefore;
|
|
42
|
+
if (consumerPkg.dependencies?.[pkg] !== void 0) {
|
|
43
|
+
depMap = "dependencies";
|
|
44
|
+
depSpecBefore = consumerPkg.dependencies[pkg];
|
|
45
|
+
} else if (consumerPkg.devDependencies?.[pkg] !== void 0) {
|
|
46
|
+
depMap = "devDependencies";
|
|
47
|
+
depSpecBefore = consumerPkg.devDependencies[pkg];
|
|
48
|
+
}
|
|
49
|
+
if (!depMap || depSpecBefore === void 0) {
|
|
50
|
+
throw new EjectError(
|
|
51
|
+
`${pkg} is not a dependency of the consumer package.json`
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
if (existsSync(vendorPath)) {
|
|
55
|
+
if (!force) {
|
|
56
|
+
throw new EjectError(
|
|
57
|
+
`vendor/${vendorName} already exists; pass --force to overwrite`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
await rm(vendorPath, { recursive: true, force: true });
|
|
61
|
+
}
|
|
62
|
+
let copiedFiles = 0;
|
|
63
|
+
await cp(sourceDir, vendorPath, {
|
|
64
|
+
recursive: true,
|
|
65
|
+
filter: (source) => {
|
|
66
|
+
const rel = relative(sourceDir, source);
|
|
67
|
+
if (rel === "") {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
const segments = rel.split(sep);
|
|
71
|
+
const name = basename(rel);
|
|
72
|
+
if (segments.some((segment) => EXCLUDED_NAMES.has(segment))) {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
if (name.endsWith(".test.ts")) {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
copiedFiles = await countFiles(vendorPath);
|
|
82
|
+
const vendoredPkgPath = join(vendorPath, "package.json");
|
|
83
|
+
const vendoredPkg = await readPackageJson(vendoredPkgPath);
|
|
84
|
+
if (vendoredPkg.private === true) {
|
|
85
|
+
delete vendoredPkg.private;
|
|
86
|
+
}
|
|
87
|
+
await writePackageJson(vendoredPkgPath, vendoredPkg);
|
|
88
|
+
const depSpecAfter = `file:./vendor/${vendorName}`;
|
|
89
|
+
consumerPkg[depMap][pkg] = depSpecAfter;
|
|
90
|
+
await writePackageJson(consumerPkgPath, consumerPkg);
|
|
91
|
+
return {
|
|
92
|
+
pkg,
|
|
93
|
+
vendorPath,
|
|
94
|
+
depSpecBefore,
|
|
95
|
+
depSpecAfter,
|
|
96
|
+
copiedFiles,
|
|
97
|
+
followUp: "pnpm install"
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
async function countFiles(dir) {
|
|
101
|
+
const { readdir } = await import("fs/promises");
|
|
102
|
+
let count = 0;
|
|
103
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
104
|
+
for (const entry of entries) {
|
|
105
|
+
const full = join(dir, entry.name);
|
|
106
|
+
if (entry.isDirectory()) {
|
|
107
|
+
count += await countFiles(full);
|
|
108
|
+
} else if (entry.isFile()) {
|
|
109
|
+
count += 1;
|
|
110
|
+
} else {
|
|
111
|
+
const info = await stat(full);
|
|
112
|
+
if (info.isFile()) {
|
|
113
|
+
count += 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return count;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/bin.ts
|
|
121
|
+
var USAGE = `hogsend \u2014 Hogsend project CLI
|
|
122
|
+
|
|
123
|
+
Usage:
|
|
124
|
+
hogsend eject <package> [--force] [--cwd <dir>]
|
|
125
|
+
|
|
126
|
+
Commands:
|
|
127
|
+
eject <package> Copy a @hogsend/* package's source into vendor/<name> and
|
|
128
|
+
rewrite the consumer dependency to file:./vendor/<name>.
|
|
129
|
+
Every other dependency keeps upgrading via pnpm up.
|
|
130
|
+
|
|
131
|
+
Options:
|
|
132
|
+
--force Overwrite an existing vendor/<name>.
|
|
133
|
+
--cwd <dir> Consumer repo root (defaults to the current directory).
|
|
134
|
+
-h, --help Show this help.
|
|
135
|
+
|
|
136
|
+
After ejecting, run: pnpm install`;
|
|
137
|
+
var RED = "\x1B[31m";
|
|
138
|
+
var RESET = "\x1B[0m";
|
|
139
|
+
function fail(message) {
|
|
140
|
+
process.stderr.write(`${RED}error${RESET} ${message}
|
|
141
|
+
`);
|
|
142
|
+
process.exit(1);
|
|
143
|
+
}
|
|
144
|
+
function resolveSourceDir(pkg, consumerRoot) {
|
|
145
|
+
const direct = join2(consumerRoot, "node_modules", pkg, "package.json");
|
|
146
|
+
if (existsSync2(direct)) {
|
|
147
|
+
return dirname(realpathSync(direct));
|
|
148
|
+
}
|
|
149
|
+
const require2 = createRequire(`${consumerRoot}${sep2}`);
|
|
150
|
+
try {
|
|
151
|
+
const entry = require2.resolve(pkg);
|
|
152
|
+
let dir = dirname(entry);
|
|
153
|
+
while (dir !== dirname(dir)) {
|
|
154
|
+
const candidate = join2(dir, "package.json");
|
|
155
|
+
if (existsSync2(candidate)) {
|
|
156
|
+
return dir;
|
|
157
|
+
}
|
|
158
|
+
dir = dirname(dir);
|
|
159
|
+
}
|
|
160
|
+
} catch {
|
|
161
|
+
}
|
|
162
|
+
fail(
|
|
163
|
+
`cannot resolve ${pkg} from ${consumerRoot}. Is it installed? Run pnpm install first.`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
async function runEject(args) {
|
|
167
|
+
const { values, positionals } = parseArgs({
|
|
168
|
+
args,
|
|
169
|
+
allowPositionals: true,
|
|
170
|
+
options: {
|
|
171
|
+
force: { type: "boolean", default: false },
|
|
172
|
+
cwd: { type: "string" },
|
|
173
|
+
help: { type: "boolean", short: "h", default: false }
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
if (values.help) {
|
|
177
|
+
process.stdout.write(`${USAGE}
|
|
178
|
+
`);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
const pkg = positionals[0];
|
|
182
|
+
if (!pkg) {
|
|
183
|
+
fail("eject requires a package name, e.g. hogsend eject @hogsend/engine");
|
|
184
|
+
}
|
|
185
|
+
const consumerRoot = values.cwd ?? process.cwd();
|
|
186
|
+
const sourceDir = resolveSourceDir(pkg, consumerRoot);
|
|
187
|
+
try {
|
|
188
|
+
const result = await eject({
|
|
189
|
+
pkg,
|
|
190
|
+
consumerRoot,
|
|
191
|
+
sourceDir,
|
|
192
|
+
force: values.force
|
|
193
|
+
});
|
|
194
|
+
process.stdout.write(
|
|
195
|
+
`Ejected ${result.pkg}
|
|
196
|
+
copied ${result.copiedFiles} files -> ${result.vendorPath}
|
|
197
|
+
dependency ${result.depSpecBefore} -> ${result.depSpecAfter}
|
|
198
|
+
|
|
199
|
+
Now run: ${result.followUp}
|
|
200
|
+
`
|
|
201
|
+
);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (error instanceof EjectError) {
|
|
204
|
+
fail(error.message);
|
|
205
|
+
}
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
async function main() {
|
|
210
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
211
|
+
if (!command || command === "--help" || command === "-h") {
|
|
212
|
+
process.stdout.write(`${USAGE}
|
|
213
|
+
`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
switch (command) {
|
|
217
|
+
case "eject":
|
|
218
|
+
await runEject(rest);
|
|
219
|
+
break;
|
|
220
|
+
default:
|
|
221
|
+
fail(`unknown command "${command}"
|
|
222
|
+
|
|
223
|
+
${USAGE}`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
main().catch((error) => {
|
|
227
|
+
process.stderr.write(`${RED}error${RESET} ${String(error)}
|
|
228
|
+
`);
|
|
229
|
+
process.exit(1);
|
|
230
|
+
});
|
|
231
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts","../src/eject.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, sep } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { EjectError, eject } from \"./eject.js\";\n\nconst USAGE = `hogsend — Hogsend project CLI\n\nUsage:\n hogsend eject <package> [--force] [--cwd <dir>]\n\nCommands:\n eject <package> Copy a @hogsend/* package's source into vendor/<name> and\n rewrite the consumer dependency to file:./vendor/<name>.\n Every other dependency keeps upgrading via pnpm up.\n\nOptions:\n --force Overwrite an existing vendor/<name>.\n --cwd <dir> Consumer repo root (defaults to the current directory).\n -h, --help Show this help.\n\nAfter ejecting, run: pnpm install`;\n\nconst RED = \"\\x1b[31m\";\nconst RESET = \"\\x1b[0m\";\n\nfunction fail(message: string): never {\n process.stderr.write(`${RED}error${RESET} ${message}\\n`);\n process.exit(1);\n}\n\n/**\n * Resolves the on-disk source directory for an installed package from the\n * consumer root. Works for pnpm's `.pnpm` layout and workspace symlinks.\n *\n * Strategy 1 (primary): probe `<consumerRoot>/node_modules/<pkg>/package.json`\n * directly, following the symlink to its real location. This is the common\n * layout and — unlike `require.resolve(\"<pkg>/package.json\")` — is NOT blocked\n * by the package's `exports` map (most packages don't expose `./package.json`).\n *\n * Strategy 2 (fallback): resolve the package's main entry via `createRequire`\n * and walk up to the nearest directory that contains a package.json whose\n * `name` matches.\n */\nfunction resolveSourceDir(pkg: string, consumerRoot: string): string {\n const direct = join(consumerRoot, \"node_modules\", pkg, \"package.json\");\n if (existsSync(direct)) {\n // realpath follows pnpm/workspace symlinks to the actual source dir.\n return dirname(realpathSync(direct));\n }\n\n const require = createRequire(`${consumerRoot}${sep}`);\n try {\n // Resolving the entry point works even when `./package.json` is not an\n // exported subpath; we then walk up to the package root.\n const entry = require.resolve(pkg);\n let dir = dirname(entry);\n while (dir !== dirname(dir)) {\n const candidate = join(dir, \"package.json\");\n if (existsSync(candidate)) {\n return dir;\n }\n dir = dirname(dir);\n }\n } catch {\n // fall through to the failure below\n }\n\n fail(\n `cannot resolve ${pkg} from ${consumerRoot}. Is it installed? Run pnpm install first.`,\n );\n}\n\nasync function runEject(args: string[]): Promise<void> {\n const { values, positionals } = parseArgs({\n args,\n allowPositionals: true,\n options: {\n force: { type: \"boolean\", default: false },\n cwd: { type: \"string\" },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n });\n\n if (values.help) {\n process.stdout.write(`${USAGE}\\n`);\n return;\n }\n\n const pkg = positionals[0];\n if (!pkg) {\n fail(\"eject requires a package name, e.g. hogsend eject @hogsend/engine\");\n }\n\n const consumerRoot = values.cwd ?? process.cwd();\n const sourceDir = resolveSourceDir(pkg, consumerRoot);\n\n try {\n const result = await eject({\n pkg,\n consumerRoot,\n sourceDir,\n force: values.force,\n });\n process.stdout.write(\n `Ejected ${result.pkg}\\n` +\n ` copied ${result.copiedFiles} files -> ${result.vendorPath}\\n` +\n ` dependency ${result.depSpecBefore} -> ${result.depSpecAfter}\\n` +\n `\\nNow run: ${result.followUp}\\n`,\n );\n } catch (error) {\n if (error instanceof EjectError) {\n fail(error.message);\n }\n throw error;\n }\n}\n\nasync function main(): Promise<void> {\n const [command, ...rest] = process.argv.slice(2);\n\n if (!command || command === \"--help\" || command === \"-h\") {\n process.stdout.write(`${USAGE}\\n`);\n return;\n }\n\n switch (command) {\n case \"eject\":\n await runEject(rest);\n break;\n default:\n fail(`unknown command \"${command}\"\\n\\n${USAGE}`);\n }\n}\n\nmain().catch((error) => {\n process.stderr.write(`${RED}error${RESET} ${String(error)}\\n`);\n process.exit(1);\n});\n","import { existsSync } from \"node:fs\";\nimport { cp, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { basename, join, relative, sep } from \"node:path\";\n\n/** Options for {@link eject}. */\nexport interface EjectOptions {\n /** Scoped package name to eject, e.g. \"@hogsend/engine\". */\n pkg: string;\n /** Consumer repo root (the dir containing the consumer package.json). */\n consumerRoot: string;\n /**\n * Where the package source currently lives (the workspace/registry copy).\n * In-monorepo: <repoRoot>/packages/<name>. In a scaffolded app it is the\n * resolved node_modules path. The caller resolves this; eject() never\n * guesses it.\n */\n sourceDir: string;\n /** Overwrite an existing vendor/<name>. */\n force?: boolean;\n}\n\n/** Result of a successful {@link eject}. */\nexport interface EjectResult {\n pkg: string;\n /** Absolute path to vendor/<name>. */\n vendorPath: string;\n /** The dep spec before the rewrite, e.g. \"workspace:^\". */\n depSpecBefore: string;\n /** The dep spec after the rewrite, \"file:./vendor/<name>\". */\n depSpecAfter: string;\n /** Number of files copied into vendor/<name>. */\n copiedFiles: number;\n /** The install command the operator must run next. */\n followUp: string;\n}\n\n/** Typed failure thrown by {@link eject} for expected, user-facing errors. */\nexport class EjectError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"EjectError\";\n }\n}\n\n/** Directory/file names excluded from the vendor copy. */\nconst EXCLUDED_NAMES = new Set([\n \"node_modules\",\n \"dist\",\n \".turbo\",\n \".changeset\",\n \"CHANGELOG.md\",\n]);\n\ninterface PackageJson {\n private?: boolean;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n}\n\ntype DepMap = \"dependencies\" | \"devDependencies\";\n\nasync function readPackageJson(file: string): Promise<PackageJson> {\n const raw = await readFile(file, \"utf8\");\n return JSON.parse(raw) as PackageJson;\n}\n\nasync function writePackageJson(\n file: string,\n value: PackageJson,\n): Promise<void> {\n await writeFile(file, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n}\n\n/**\n * Pure eject: copies a single package's source into the consumer's\n * `vendor/<name>` and rewrites only that consumer dependency to a\n * `file:./vendor/<name>` link. Every other dependency is left untouched, so\n * the rest of the `@hogsend/*` set keeps upgrading via `pnpm up`.\n *\n * This function performs filesystem operations only — it never runs an install\n * and never resolves `sourceDir` itself, which keeps it hermetically testable.\n */\nexport async function eject(opts: EjectOptions): Promise<EjectResult> {\n const { pkg, consumerRoot, sourceDir, force = false } = opts;\n\n // 1. Resolve names.\n const vendorName = basename(pkg);\n const vendorPath = join(consumerRoot, \"vendor\", vendorName);\n\n // 2. Validate the consumer dependency exists (before any side effects).\n const consumerPkgPath = join(consumerRoot, \"package.json\");\n const consumerPkg = await readPackageJson(consumerPkgPath);\n let depMap: DepMap | undefined;\n let depSpecBefore: string | undefined;\n if (consumerPkg.dependencies?.[pkg] !== undefined) {\n depMap = \"dependencies\";\n depSpecBefore = consumerPkg.dependencies[pkg];\n } else if (consumerPkg.devDependencies?.[pkg] !== undefined) {\n depMap = \"devDependencies\";\n depSpecBefore = consumerPkg.devDependencies[pkg];\n }\n if (!depMap || depSpecBefore === undefined) {\n throw new EjectError(\n `${pkg} is not a dependency of the consumer package.json`,\n );\n }\n\n // 3. Guard the vendor dir.\n if (existsSync(vendorPath)) {\n if (!force) {\n throw new EjectError(\n `vendor/${vendorName} already exists; pass --force to overwrite`,\n );\n }\n await rm(vendorPath, { recursive: true, force: true });\n }\n\n // 4. Copy source with an exclude filter. Returning false for a directory\n // prunes the whole subtree (Node 22 fs.cp filter semantics).\n let copiedFiles = 0;\n await cp(sourceDir, vendorPath, {\n recursive: true,\n filter: (source) => {\n const rel = relative(sourceDir, source);\n if (rel === \"\") {\n return true;\n }\n const segments = rel.split(sep);\n const name = basename(rel);\n // Exclude any path segment that is an excluded name (prunes subtrees).\n if (segments.some((segment) => EXCLUDED_NAMES.has(segment))) {\n return false;\n }\n if (name.endsWith(\".test.ts\")) {\n return false;\n }\n return true;\n },\n });\n\n // Count copied files (directories excluded) for the result summary.\n copiedFiles = await countFiles(vendorPath);\n\n // 5. Sanitize the vendored package.json.\n const vendoredPkgPath = join(vendorPath, \"package.json\");\n const vendoredPkg = await readPackageJson(vendoredPkgPath);\n if (vendoredPkg.private === true) {\n delete vendoredPkg.private;\n }\n await writePackageJson(vendoredPkgPath, vendoredPkg);\n\n // 6. Rewrite the consumer dep in place (preserving key order).\n const depSpecAfter = `file:./vendor/${vendorName}`;\n // biome-ignore lint/style/noNonNullAssertion: depMap validated above.\n consumerPkg[depMap]![pkg] = depSpecAfter;\n await writePackageJson(consumerPkgPath, consumerPkg);\n\n // 7. Return the result.\n return {\n pkg,\n vendorPath,\n depSpecBefore,\n depSpecAfter,\n copiedFiles,\n followUp: \"pnpm install\",\n };\n}\n\n/** Recursively counts regular files under a directory. */\nasync function countFiles(dir: string): Promise<number> {\n const { readdir } = await import(\"node:fs/promises\");\n let count = 0;\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n count += await countFiles(full);\n } else if (entry.isFile()) {\n count += 1;\n } else {\n const info = await stat(full);\n if (info.isFile()) {\n count += 1;\n }\n }\n }\n return count;\n}\n"],"mappings":";;;AACA,SAAS,cAAAA,aAAY,oBAAoB;AACzC,SAAS,qBAAqB;AAC9B,SAAS,SAAS,QAAAC,OAAM,OAAAC,YAAW;AACnC,SAAS,iBAAiB;;;ACJ1B,SAAS,kBAAkB;AAC3B,SAAS,IAAI,UAAU,IAAI,MAAM,iBAAiB;AAClD,SAAS,UAAU,MAAM,UAAU,WAAW;AAmCvC,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGA,IAAM,iBAAiB,oBAAI,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWD,eAAe,gBAAgB,MAAoC;AACjE,QAAM,MAAM,MAAM,SAAS,MAAM,MAAM;AACvC,SAAO,KAAK,MAAM,GAAG;AACvB;AAEA,eAAe,iBACb,MACA,OACe;AACf,QAAM,UAAU,MAAM,GAAG,KAAK,UAA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AAW,aAAa,OAAO,UAAU;AAAA,eAC5C,OAAO,aAAa,OAAO,OAAO,YAAY;AAAA;AAAA,WAChD,OAAO,QAAQ;AAAA;AAAA,IACjC;AAAA,EACF,SAAS,OAAO;AACd,QAAI,iBAAiB,YAAY;AAC/B,WAAK,MAAM,OAAO;AAAA,IACpB;AACA,UAAM;AAAA,EACR;AACF;AAEA,eAAe,OAAsB;AACnC,QAAM,CAAC,SAAS,GAAG,IAAI,IAAI,QAAQ,KAAK,MAAM,CAAC;AAE/C,MAAI,CAAC,WAAW,YAAY,YAAY,YAAY,MAAM;AACxD,YAAQ,OAAO,MAAM,GAAG,KAAK;AAAA,CAAI;AACjC;AAAA,EACF;AAEA,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,YAAM,SAAS,IAAI;AACnB;AAAA,IACF;AACE,WAAK,oBAAoB,OAAO;AAAA;AAAA,EAAQ,KAAK,EAAE;AAAA,EACnD;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,OAAO,MAAM,GAAG,GAAG,QAAQ,KAAK,IAAI,OAAO,KAAK,CAAC;AAAA,CAAI;AAC7D,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","join","sep","join","existsSync","require","sep"]}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// src/eject.ts
|
|
2
|
+
import { existsSync } from "fs";
|
|
3
|
+
import { cp, readFile, rm, stat, writeFile } from "fs/promises";
|
|
4
|
+
import { basename, join, relative, sep } from "path";
|
|
5
|
+
var EjectError = class extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "EjectError";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
var EXCLUDED_NAMES = /* @__PURE__ */ new Set([
|
|
12
|
+
"node_modules",
|
|
13
|
+
"dist",
|
|
14
|
+
".turbo",
|
|
15
|
+
".changeset",
|
|
16
|
+
"CHANGELOG.md"
|
|
17
|
+
]);
|
|
18
|
+
async function readPackageJson(file) {
|
|
19
|
+
const raw = await readFile(file, "utf8");
|
|
20
|
+
return JSON.parse(raw);
|
|
21
|
+
}
|
|
22
|
+
async function writePackageJson(file, value) {
|
|
23
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}
|
|
24
|
+
`, "utf8");
|
|
25
|
+
}
|
|
26
|
+
async function eject(opts) {
|
|
27
|
+
const { pkg, consumerRoot, sourceDir, force = false } = opts;
|
|
28
|
+
const vendorName = basename(pkg);
|
|
29
|
+
const vendorPath = join(consumerRoot, "vendor", vendorName);
|
|
30
|
+
const consumerPkgPath = join(consumerRoot, "package.json");
|
|
31
|
+
const consumerPkg = await readPackageJson(consumerPkgPath);
|
|
32
|
+
let depMap;
|
|
33
|
+
let depSpecBefore;
|
|
34
|
+
if (consumerPkg.dependencies?.[pkg] !== void 0) {
|
|
35
|
+
depMap = "dependencies";
|
|
36
|
+
depSpecBefore = consumerPkg.dependencies[pkg];
|
|
37
|
+
} else if (consumerPkg.devDependencies?.[pkg] !== void 0) {
|
|
38
|
+
depMap = "devDependencies";
|
|
39
|
+
depSpecBefore = consumerPkg.devDependencies[pkg];
|
|
40
|
+
}
|
|
41
|
+
if (!depMap || depSpecBefore === void 0) {
|
|
42
|
+
throw new EjectError(
|
|
43
|
+
`${pkg} is not a dependency of the consumer package.json`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
if (existsSync(vendorPath)) {
|
|
47
|
+
if (!force) {
|
|
48
|
+
throw new EjectError(
|
|
49
|
+
`vendor/${vendorName} already exists; pass --force to overwrite`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
await rm(vendorPath, { recursive: true, force: true });
|
|
53
|
+
}
|
|
54
|
+
let copiedFiles = 0;
|
|
55
|
+
await cp(sourceDir, vendorPath, {
|
|
56
|
+
recursive: true,
|
|
57
|
+
filter: (source) => {
|
|
58
|
+
const rel = relative(sourceDir, source);
|
|
59
|
+
if (rel === "") {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
const segments = rel.split(sep);
|
|
63
|
+
const name = basename(rel);
|
|
64
|
+
if (segments.some((segment) => EXCLUDED_NAMES.has(segment))) {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
if (name.endsWith(".test.ts")) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
copiedFiles = await countFiles(vendorPath);
|
|
74
|
+
const vendoredPkgPath = join(vendorPath, "package.json");
|
|
75
|
+
const vendoredPkg = await readPackageJson(vendoredPkgPath);
|
|
76
|
+
if (vendoredPkg.private === true) {
|
|
77
|
+
delete vendoredPkg.private;
|
|
78
|
+
}
|
|
79
|
+
await writePackageJson(vendoredPkgPath, vendoredPkg);
|
|
80
|
+
const depSpecAfter = `file:./vendor/${vendorName}`;
|
|
81
|
+
consumerPkg[depMap][pkg] = depSpecAfter;
|
|
82
|
+
await writePackageJson(consumerPkgPath, consumerPkg);
|
|
83
|
+
return {
|
|
84
|
+
pkg,
|
|
85
|
+
vendorPath,
|
|
86
|
+
depSpecBefore,
|
|
87
|
+
depSpecAfter,
|
|
88
|
+
copiedFiles,
|
|
89
|
+
followUp: "pnpm install"
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
async function countFiles(dir) {
|
|
93
|
+
const { readdir } = await import("fs/promises");
|
|
94
|
+
let count = 0;
|
|
95
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
96
|
+
for (const entry of entries) {
|
|
97
|
+
const full = join(dir, entry.name);
|
|
98
|
+
if (entry.isDirectory()) {
|
|
99
|
+
count += await countFiles(full);
|
|
100
|
+
} else if (entry.isFile()) {
|
|
101
|
+
count += 1;
|
|
102
|
+
} else {
|
|
103
|
+
const info = await stat(full);
|
|
104
|
+
if (info.isFile()) {
|
|
105
|
+
count += 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return count;
|
|
110
|
+
}
|
|
111
|
+
export {
|
|
112
|
+
EjectError,
|
|
113
|
+
eject
|
|
114
|
+
};
|
|
115
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/eject.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { cp, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { basename, join, relative, sep } from \"node:path\";\n\n/** Options for {@link eject}. */\nexport interface EjectOptions {\n /** Scoped package name to eject, e.g. \"@hogsend/engine\". */\n pkg: string;\n /** Consumer repo root (the dir containing the consumer package.json). */\n consumerRoot: string;\n /**\n * Where the package source currently lives (the workspace/registry copy).\n * In-monorepo: <repoRoot>/packages/<name>. In a scaffolded app it is the\n * resolved node_modules path. The caller resolves this; eject() never\n * guesses it.\n */\n sourceDir: string;\n /** Overwrite an existing vendor/<name>. */\n force?: boolean;\n}\n\n/** Result of a successful {@link eject}. */\nexport interface EjectResult {\n pkg: string;\n /** Absolute path to vendor/<name>. */\n vendorPath: string;\n /** The dep spec before the rewrite, e.g. \"workspace:^\". */\n depSpecBefore: string;\n /** The dep spec after the rewrite, \"file:./vendor/<name>\". */\n depSpecAfter: string;\n /** Number of files copied into vendor/<name>. */\n copiedFiles: number;\n /** The install command the operator must run next. */\n followUp: string;\n}\n\n/** Typed failure thrown by {@link eject} for expected, user-facing errors. */\nexport class EjectError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"EjectError\";\n }\n}\n\n/** Directory/file names excluded from the vendor copy. */\nconst EXCLUDED_NAMES = new Set([\n \"node_modules\",\n \"dist\",\n \".turbo\",\n \".changeset\",\n \"CHANGELOG.md\",\n]);\n\ninterface PackageJson {\n private?: boolean;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n [key: string]: unknown;\n}\n\ntype DepMap = \"dependencies\" | \"devDependencies\";\n\nasync function readPackageJson(file: string): Promise<PackageJson> {\n const raw = await readFile(file, \"utf8\");\n return JSON.parse(raw) as PackageJson;\n}\n\nasync function writePackageJson(\n file: string,\n value: PackageJson,\n): Promise<void> {\n await writeFile(file, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n}\n\n/**\n * Pure eject: copies a single package's source into the consumer's\n * `vendor/<name>` and rewrites only that consumer dependency to a\n * `file:./vendor/<name>` link. Every other dependency is left untouched, so\n * the rest of the `@hogsend/*` set keeps upgrading via `pnpm up`.\n *\n * This function performs filesystem operations only — it never runs an install\n * and never resolves `sourceDir` itself, which keeps it hermetically testable.\n */\nexport async function eject(opts: EjectOptions): Promise<EjectResult> {\n const { pkg, consumerRoot, sourceDir, force = false } = opts;\n\n // 1. Resolve names.\n const vendorName = basename(pkg);\n const vendorPath = join(consumerRoot, \"vendor\", vendorName);\n\n // 2. Validate the consumer dependency exists (before any side effects).\n const consumerPkgPath = join(consumerRoot, \"package.json\");\n const consumerPkg = await readPackageJson(consumerPkgPath);\n let depMap: DepMap | undefined;\n let depSpecBefore: string | undefined;\n if (consumerPkg.dependencies?.[pkg] !== undefined) {\n depMap = \"dependencies\";\n depSpecBefore = consumerPkg.dependencies[pkg];\n } else if (consumerPkg.devDependencies?.[pkg] !== undefined) {\n depMap = \"devDependencies\";\n depSpecBefore = consumerPkg.devDependencies[pkg];\n }\n if (!depMap || depSpecBefore === undefined) {\n throw new EjectError(\n `${pkg} is not a dependency of the consumer package.json`,\n );\n }\n\n // 3. Guard the vendor dir.\n if (existsSync(vendorPath)) {\n if (!force) {\n throw new EjectError(\n `vendor/${vendorName} already exists; pass --force to overwrite`,\n );\n }\n await rm(vendorPath, { recursive: true, force: true });\n }\n\n // 4. Copy source with an exclude filter. Returning false for a directory\n // prunes the whole subtree (Node 22 fs.cp filter semantics).\n let copiedFiles = 0;\n await cp(sourceDir, vendorPath, {\n recursive: true,\n filter: (source) => {\n const rel = relative(sourceDir, source);\n if (rel === \"\") {\n return true;\n }\n const segments = rel.split(sep);\n const name = basename(rel);\n // Exclude any path segment that is an excluded name (prunes subtrees).\n if (segments.some((segment) => EXCLUDED_NAMES.has(segment))) {\n return false;\n }\n if (name.endsWith(\".test.ts\")) {\n return false;\n }\n return true;\n },\n });\n\n // Count copied files (directories excluded) for the result summary.\n copiedFiles = await countFiles(vendorPath);\n\n // 5. Sanitize the vendored package.json.\n const vendoredPkgPath = join(vendorPath, \"package.json\");\n const vendoredPkg = await readPackageJson(vendoredPkgPath);\n if (vendoredPkg.private === true) {\n delete vendoredPkg.private;\n }\n await writePackageJson(vendoredPkgPath, vendoredPkg);\n\n // 6. Rewrite the consumer dep in place (preserving key order).\n const depSpecAfter = `file:./vendor/${vendorName}`;\n // biome-ignore lint/style/noNonNullAssertion: depMap validated above.\n consumerPkg[depMap]![pkg] = depSpecAfter;\n await writePackageJson(consumerPkgPath, consumerPkg);\n\n // 7. Return the result.\n return {\n pkg,\n vendorPath,\n depSpecBefore,\n depSpecAfter,\n copiedFiles,\n followUp: \"pnpm install\",\n };\n}\n\n/** Recursively counts regular files under a directory. */\nasync function countFiles(dir: string): Promise<number> {\n const { readdir } = await import(\"node:fs/promises\");\n let count = 0;\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n count += await countFiles(full);\n } else if (entry.isFile()) {\n count += 1;\n } else {\n const info = await stat(full);\n if (info.isFile()) {\n count += 1;\n }\n }\n }\n return count;\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,IAAI,UAAU,IAAI,MAAM,iBAAiB;AAClD,SAAS,UAAU,MAAM,UAAU,WAAW;AAmCvC,IAAM,aAAN,cAAyB,MAAM;AAAA,EACpC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAGA,IAAM,iBAAiB,oBAAI,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWD,eAAe,gBAAgB,MAAoC;AACjE,QAAM,MAAM,MA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;AAC3D,eAAO;AAAA,MACT;AACA,UAAI,KAAK,SAAS,UAAU,GAAG;AAC7B,eAAO;AAAA,MACT;AACA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AAGD,gBAAc,MAAM,WAAW,UAAU;AAGzC,QAAM,kBAAkB,KAAK,YAAY,cAAc;AACvD,QAAM,cAAc,MAAM,gBAAgB,eAAe;AACzD,MAAI,YAAY,YAAY,MAAM;AAChC,WAAO,YAAY;AAAA,EACrB;AACA,QAAM,iBAAiB,iBAAiB,WAAW;AAGnD,QAAM,eAAe,iBAAiB,UAAU;AAEhD,cAAY,MAAM,EAAG,GAAG,IAAI;AAC5B,QAAM,iBAAiB,iBAAiB,WAAW;AAGnD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;AAGA,eAAe,WAAW,KAA8B;AACtD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,aAAkB;AACnD,MAAI,QAAQ;AACZ,QAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;AAC1D,aAAW,SAAS,SAAS;AAC3B,UAAM,OAAO,KAAK,KAAK,MAAM,IAAI;AACjC,QAAI,MAAM,YAAY,GAAG;AACvB,eAAS,MAAM,WAAW,IAAI;AAAA,IAChC,WAAW,MAAM,OAAO,GAAG;AACzB,eAAS;AAAA,IACX,OAAO;AACL,YAAM,OAAO,MAAM,KAAK,IAAI;AAC5B,UAAI,KAAK,OAAO,GAAG;AACjB,iBAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hogsend/cli",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/dougwithseismic/hogsend.git",
|
|
9
|
+
"directory": "packages/cli"
|
|
10
|
+
},
|
|
11
|
+
"main": "./src/index.ts",
|
|
12
|
+
"types": "./src/index.ts",
|
|
13
|
+
"bin": {
|
|
14
|
+
"hogsend": "./dist/bin.js"
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./src/index.ts",
|
|
18
|
+
"./eject": "./src/eject.ts"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"src",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^25.9.1",
|
|
30
|
+
"tsup": "^8.5.1",
|
|
31
|
+
"tsx": "^4.22.4",
|
|
32
|
+
"vitest": "^4.1.7",
|
|
33
|
+
"@repo/typescript-config": "0.0.0"
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsup",
|
|
40
|
+
"check-types": "tsc --noEmit",
|
|
41
|
+
"lint": "biome check .",
|
|
42
|
+
"clean": "rm -rf node_modules dist .turbo",
|
|
43
|
+
"test": "vitest run"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
6
|
+
import { eject } from "../eject.js";
|
|
7
|
+
|
|
8
|
+
const PKG = "@hogsend/engine";
|
|
9
|
+
|
|
10
|
+
let root: string;
|
|
11
|
+
let sourceDir: string;
|
|
12
|
+
let consumerRoot: string;
|
|
13
|
+
|
|
14
|
+
async function writeJson(file: string, value: unknown): Promise<void> {
|
|
15
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function readJson<T = Record<string, unknown>>(file: string): Promise<T> {
|
|
19
|
+
return JSON.parse(await readFile(file, "utf8")) as T;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function fabricateSource(): Promise<void> {
|
|
23
|
+
await mkdir(join(sourceDir, "src", "lib"), { recursive: true });
|
|
24
|
+
await mkdir(join(sourceDir, "node_modules"), { recursive: true });
|
|
25
|
+
await mkdir(join(sourceDir, "dist"), { recursive: true });
|
|
26
|
+
await writeJson(join(sourceDir, "package.json"), {
|
|
27
|
+
name: "@hogsend/engine",
|
|
28
|
+
version: "0.0.1",
|
|
29
|
+
private: true,
|
|
30
|
+
type: "module",
|
|
31
|
+
exports: { ".": "./src/index.ts" },
|
|
32
|
+
dependencies: { "@hogsend/core": "workspace:^" },
|
|
33
|
+
});
|
|
34
|
+
await writeFile(join(sourceDir, "src", "index.ts"), "export {};\n", "utf8");
|
|
35
|
+
await writeFile(
|
|
36
|
+
join(sourceDir, "src", "lib", "db.ts"),
|
|
37
|
+
"export const db = 1;\n",
|
|
38
|
+
"utf8",
|
|
39
|
+
);
|
|
40
|
+
await writeFile(
|
|
41
|
+
join(sourceDir, "src", "foo.test.ts"),
|
|
42
|
+
"// a test file\n",
|
|
43
|
+
"utf8",
|
|
44
|
+
);
|
|
45
|
+
await writeFile(
|
|
46
|
+
join(sourceDir, "node_modules", "junk.js"),
|
|
47
|
+
"module.exports = {};\n",
|
|
48
|
+
"utf8",
|
|
49
|
+
);
|
|
50
|
+
await writeFile(join(sourceDir, "dist", "old.js"), "// stale\n", "utf8");
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function fabricateConsumer(
|
|
54
|
+
deps: Record<string, string> = {
|
|
55
|
+
"@hogsend/engine": "workspace:^",
|
|
56
|
+
"@hogsend/core": "workspace:^",
|
|
57
|
+
},
|
|
58
|
+
): Promise<void> {
|
|
59
|
+
await mkdir(consumerRoot, { recursive: true });
|
|
60
|
+
await writeJson(join(consumerRoot, "package.json"), {
|
|
61
|
+
name: "consumer-app",
|
|
62
|
+
version: "0.0.0",
|
|
63
|
+
type: "module",
|
|
64
|
+
dependencies: deps,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
beforeEach(async () => {
|
|
69
|
+
root = await mkdtemp(join(tmpdir(), "hogsend-eject-"));
|
|
70
|
+
sourceDir = join(root, "src-pkg");
|
|
71
|
+
consumerRoot = join(root, "consumer");
|
|
72
|
+
await fabricateSource();
|
|
73
|
+
await fabricateConsumer();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
afterEach(async () => {
|
|
77
|
+
await rm(root, { recursive: true, force: true });
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe("eject", () => {
|
|
81
|
+
it("copies the right files into vendor/<name>", async () => {
|
|
82
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
83
|
+
expect(
|
|
84
|
+
existsSync(join(consumerRoot, "vendor", "engine", "src", "index.ts")),
|
|
85
|
+
).toBe(true);
|
|
86
|
+
expect(
|
|
87
|
+
existsSync(join(consumerRoot, "vendor", "engine", "src", "lib", "db.ts")),
|
|
88
|
+
).toBe(true);
|
|
89
|
+
expect(
|
|
90
|
+
existsSync(join(consumerRoot, "vendor", "engine", "package.json")),
|
|
91
|
+
).toBe(true);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it("honors excludes (node_modules, dist, *.test.ts)", async () => {
|
|
95
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
96
|
+
expect(
|
|
97
|
+
existsSync(join(consumerRoot, "vendor", "engine", "node_modules")),
|
|
98
|
+
).toBe(false);
|
|
99
|
+
expect(existsSync(join(consumerRoot, "vendor", "engine", "dist"))).toBe(
|
|
100
|
+
false,
|
|
101
|
+
);
|
|
102
|
+
expect(
|
|
103
|
+
existsSync(join(consumerRoot, "vendor", "engine", "src", "foo.test.ts")),
|
|
104
|
+
).toBe(false);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("rewrites only the target consumer dep, leaving others untouched", async () => {
|
|
108
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
109
|
+
const pkg = await readJson(join(consumerRoot, "package.json"));
|
|
110
|
+
const deps = pkg.dependencies as Record<string, string>;
|
|
111
|
+
expect(deps["@hogsend/engine"]).toBe("file:./vendor/engine");
|
|
112
|
+
expect(deps["@hogsend/core"]).toBe("workspace:^");
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("sanitizes the vendored package.json", async () => {
|
|
116
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
117
|
+
const vendored = await readJson(
|
|
118
|
+
join(consumerRoot, "vendor", "engine", "package.json"),
|
|
119
|
+
);
|
|
120
|
+
expect("private" in vendored).toBe(false);
|
|
121
|
+
expect(vendored.name).toBe("@hogsend/engine");
|
|
122
|
+
const deps = vendored.dependencies as Record<string, string>;
|
|
123
|
+
expect(deps["@hogsend/core"]).toBe("workspace:^");
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("returns the expected result shape", async () => {
|
|
127
|
+
const result = await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
128
|
+
expect(result.depSpecBefore).toBe("workspace:^");
|
|
129
|
+
expect(result.depSpecAfter).toBe("file:./vendor/engine");
|
|
130
|
+
expect(result.followUp).toBe("pnpm install");
|
|
131
|
+
expect(result.copiedFiles).toBeGreaterThanOrEqual(3);
|
|
132
|
+
expect(result.vendorPath).toBe(join(consumerRoot, "vendor", "engine"));
|
|
133
|
+
expect(result.pkg).toBe(PKG);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("refuses to clobber an existing vendor dir without force", async () => {
|
|
137
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
138
|
+
await expect(eject({ pkg: PKG, consumerRoot, sourceDir })).rejects.toThrow(
|
|
139
|
+
/already exists/,
|
|
140
|
+
);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("overwrites with force and drops files removed from source", async () => {
|
|
144
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir });
|
|
145
|
+
// Remove a file from source between runs.
|
|
146
|
+
await rm(join(sourceDir, "src", "lib", "db.ts"));
|
|
147
|
+
await eject({ pkg: PKG, consumerRoot, sourceDir, force: true });
|
|
148
|
+
expect(
|
|
149
|
+
existsSync(join(consumerRoot, "vendor", "engine", "src", "lib", "db.ts")),
|
|
150
|
+
).toBe(false);
|
|
151
|
+
expect(
|
|
152
|
+
existsSync(join(consumerRoot, "vendor", "engine", "src", "index.ts")),
|
|
153
|
+
).toBe(true);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("errors loudly when the package is not a dependency", async () => {
|
|
157
|
+
await fabricateConsumer({ "@hogsend/core": "workspace:^" });
|
|
158
|
+
await expect(eject({ pkg: PKG, consumerRoot, sourceDir })).rejects.toThrow(
|
|
159
|
+
/not a dependency/,
|
|
160
|
+
);
|
|
161
|
+
expect(existsSync(join(consumerRoot, "vendor"))).toBe(false);
|
|
162
|
+
});
|
|
163
|
+
});
|
package/src/bin.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { dirname, join, sep } from "node:path";
|
|
5
|
+
import { parseArgs } from "node:util";
|
|
6
|
+
import { EjectError, eject } from "./eject.js";
|
|
7
|
+
|
|
8
|
+
const USAGE = `hogsend — Hogsend project CLI
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
hogsend eject <package> [--force] [--cwd <dir>]
|
|
12
|
+
|
|
13
|
+
Commands:
|
|
14
|
+
eject <package> Copy a @hogsend/* package's source into vendor/<name> and
|
|
15
|
+
rewrite the consumer dependency to file:./vendor/<name>.
|
|
16
|
+
Every other dependency keeps upgrading via pnpm up.
|
|
17
|
+
|
|
18
|
+
Options:
|
|
19
|
+
--force Overwrite an existing vendor/<name>.
|
|
20
|
+
--cwd <dir> Consumer repo root (defaults to the current directory).
|
|
21
|
+
-h, --help Show this help.
|
|
22
|
+
|
|
23
|
+
After ejecting, run: pnpm install`;
|
|
24
|
+
|
|
25
|
+
const RED = "\x1b[31m";
|
|
26
|
+
const RESET = "\x1b[0m";
|
|
27
|
+
|
|
28
|
+
function fail(message: string): never {
|
|
29
|
+
process.stderr.write(`${RED}error${RESET} ${message}\n`);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Resolves the on-disk source directory for an installed package from the
|
|
35
|
+
* consumer root. Works for pnpm's `.pnpm` layout and workspace symlinks.
|
|
36
|
+
*
|
|
37
|
+
* Strategy 1 (primary): probe `<consumerRoot>/node_modules/<pkg>/package.json`
|
|
38
|
+
* directly, following the symlink to its real location. This is the common
|
|
39
|
+
* layout and — unlike `require.resolve("<pkg>/package.json")` — is NOT blocked
|
|
40
|
+
* by the package's `exports` map (most packages don't expose `./package.json`).
|
|
41
|
+
*
|
|
42
|
+
* Strategy 2 (fallback): resolve the package's main entry via `createRequire`
|
|
43
|
+
* and walk up to the nearest directory that contains a package.json whose
|
|
44
|
+
* `name` matches.
|
|
45
|
+
*/
|
|
46
|
+
function resolveSourceDir(pkg: string, consumerRoot: string): string {
|
|
47
|
+
const direct = join(consumerRoot, "node_modules", pkg, "package.json");
|
|
48
|
+
if (existsSync(direct)) {
|
|
49
|
+
// realpath follows pnpm/workspace symlinks to the actual source dir.
|
|
50
|
+
return dirname(realpathSync(direct));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const require = createRequire(`${consumerRoot}${sep}`);
|
|
54
|
+
try {
|
|
55
|
+
// Resolving the entry point works even when `./package.json` is not an
|
|
56
|
+
// exported subpath; we then walk up to the package root.
|
|
57
|
+
const entry = require.resolve(pkg);
|
|
58
|
+
let dir = dirname(entry);
|
|
59
|
+
while (dir !== dirname(dir)) {
|
|
60
|
+
const candidate = join(dir, "package.json");
|
|
61
|
+
if (existsSync(candidate)) {
|
|
62
|
+
return dir;
|
|
63
|
+
}
|
|
64
|
+
dir = dirname(dir);
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
// fall through to the failure below
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
fail(
|
|
71
|
+
`cannot resolve ${pkg} from ${consumerRoot}. Is it installed? Run pnpm install first.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function runEject(args: string[]): Promise<void> {
|
|
76
|
+
const { values, positionals } = parseArgs({
|
|
77
|
+
args,
|
|
78
|
+
allowPositionals: true,
|
|
79
|
+
options: {
|
|
80
|
+
force: { type: "boolean", default: false },
|
|
81
|
+
cwd: { type: "string" },
|
|
82
|
+
help: { type: "boolean", short: "h", default: false },
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
if (values.help) {
|
|
87
|
+
process.stdout.write(`${USAGE}\n`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const pkg = positionals[0];
|
|
92
|
+
if (!pkg) {
|
|
93
|
+
fail("eject requires a package name, e.g. hogsend eject @hogsend/engine");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const consumerRoot = values.cwd ?? process.cwd();
|
|
97
|
+
const sourceDir = resolveSourceDir(pkg, consumerRoot);
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
const result = await eject({
|
|
101
|
+
pkg,
|
|
102
|
+
consumerRoot,
|
|
103
|
+
sourceDir,
|
|
104
|
+
force: values.force,
|
|
105
|
+
});
|
|
106
|
+
process.stdout.write(
|
|
107
|
+
`Ejected ${result.pkg}\n` +
|
|
108
|
+
` copied ${result.copiedFiles} files -> ${result.vendorPath}\n` +
|
|
109
|
+
` dependency ${result.depSpecBefore} -> ${result.depSpecAfter}\n` +
|
|
110
|
+
`\nNow run: ${result.followUp}\n`,
|
|
111
|
+
);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error instanceof EjectError) {
|
|
114
|
+
fail(error.message);
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function main(): Promise<void> {
|
|
121
|
+
const [command, ...rest] = process.argv.slice(2);
|
|
122
|
+
|
|
123
|
+
if (!command || command === "--help" || command === "-h") {
|
|
124
|
+
process.stdout.write(`${USAGE}\n`);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
switch (command) {
|
|
129
|
+
case "eject":
|
|
130
|
+
await runEject(rest);
|
|
131
|
+
break;
|
|
132
|
+
default:
|
|
133
|
+
fail(`unknown command "${command}"\n\n${USAGE}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
main().catch((error) => {
|
|
138
|
+
process.stderr.write(`${RED}error${RESET} ${String(error)}\n`);
|
|
139
|
+
process.exit(1);
|
|
140
|
+
});
|
package/src/eject.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { cp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { basename, join, relative, sep } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Options for {@link eject}. */
|
|
6
|
+
export interface EjectOptions {
|
|
7
|
+
/** Scoped package name to eject, e.g. "@hogsend/engine". */
|
|
8
|
+
pkg: string;
|
|
9
|
+
/** Consumer repo root (the dir containing the consumer package.json). */
|
|
10
|
+
consumerRoot: string;
|
|
11
|
+
/**
|
|
12
|
+
* Where the package source currently lives (the workspace/registry copy).
|
|
13
|
+
* In-monorepo: <repoRoot>/packages/<name>. In a scaffolded app it is the
|
|
14
|
+
* resolved node_modules path. The caller resolves this; eject() never
|
|
15
|
+
* guesses it.
|
|
16
|
+
*/
|
|
17
|
+
sourceDir: string;
|
|
18
|
+
/** Overwrite an existing vendor/<name>. */
|
|
19
|
+
force?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Result of a successful {@link eject}. */
|
|
23
|
+
export interface EjectResult {
|
|
24
|
+
pkg: string;
|
|
25
|
+
/** Absolute path to vendor/<name>. */
|
|
26
|
+
vendorPath: string;
|
|
27
|
+
/** The dep spec before the rewrite, e.g. "workspace:^". */
|
|
28
|
+
depSpecBefore: string;
|
|
29
|
+
/** The dep spec after the rewrite, "file:./vendor/<name>". */
|
|
30
|
+
depSpecAfter: string;
|
|
31
|
+
/** Number of files copied into vendor/<name>. */
|
|
32
|
+
copiedFiles: number;
|
|
33
|
+
/** The install command the operator must run next. */
|
|
34
|
+
followUp: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Typed failure thrown by {@link eject} for expected, user-facing errors. */
|
|
38
|
+
export class EjectError extends Error {
|
|
39
|
+
constructor(message: string) {
|
|
40
|
+
super(message);
|
|
41
|
+
this.name = "EjectError";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Directory/file names excluded from the vendor copy. */
|
|
46
|
+
const EXCLUDED_NAMES = new Set([
|
|
47
|
+
"node_modules",
|
|
48
|
+
"dist",
|
|
49
|
+
".turbo",
|
|
50
|
+
".changeset",
|
|
51
|
+
"CHANGELOG.md",
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
interface PackageJson {
|
|
55
|
+
private?: boolean;
|
|
56
|
+
dependencies?: Record<string, string>;
|
|
57
|
+
devDependencies?: Record<string, string>;
|
|
58
|
+
[key: string]: unknown;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
type DepMap = "dependencies" | "devDependencies";
|
|
62
|
+
|
|
63
|
+
async function readPackageJson(file: string): Promise<PackageJson> {
|
|
64
|
+
const raw = await readFile(file, "utf8");
|
|
65
|
+
return JSON.parse(raw) as PackageJson;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function writePackageJson(
|
|
69
|
+
file: string,
|
|
70
|
+
value: PackageJson,
|
|
71
|
+
): Promise<void> {
|
|
72
|
+
await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Pure eject: copies a single package's source into the consumer's
|
|
77
|
+
* `vendor/<name>` and rewrites only that consumer dependency to a
|
|
78
|
+
* `file:./vendor/<name>` link. Every other dependency is left untouched, so
|
|
79
|
+
* the rest of the `@hogsend/*` set keeps upgrading via `pnpm up`.
|
|
80
|
+
*
|
|
81
|
+
* This function performs filesystem operations only — it never runs an install
|
|
82
|
+
* and never resolves `sourceDir` itself, which keeps it hermetically testable.
|
|
83
|
+
*/
|
|
84
|
+
export async function eject(opts: EjectOptions): Promise<EjectResult> {
|
|
85
|
+
const { pkg, consumerRoot, sourceDir, force = false } = opts;
|
|
86
|
+
|
|
87
|
+
// 1. Resolve names.
|
|
88
|
+
const vendorName = basename(pkg);
|
|
89
|
+
const vendorPath = join(consumerRoot, "vendor", vendorName);
|
|
90
|
+
|
|
91
|
+
// 2. Validate the consumer dependency exists (before any side effects).
|
|
92
|
+
const consumerPkgPath = join(consumerRoot, "package.json");
|
|
93
|
+
const consumerPkg = await readPackageJson(consumerPkgPath);
|
|
94
|
+
let depMap: DepMap | undefined;
|
|
95
|
+
let depSpecBefore: string | undefined;
|
|
96
|
+
if (consumerPkg.dependencies?.[pkg] !== undefined) {
|
|
97
|
+
depMap = "dependencies";
|
|
98
|
+
depSpecBefore = consumerPkg.dependencies[pkg];
|
|
99
|
+
} else if (consumerPkg.devDependencies?.[pkg] !== undefined) {
|
|
100
|
+
depMap = "devDependencies";
|
|
101
|
+
depSpecBefore = consumerPkg.devDependencies[pkg];
|
|
102
|
+
}
|
|
103
|
+
if (!depMap || depSpecBefore === undefined) {
|
|
104
|
+
throw new EjectError(
|
|
105
|
+
`${pkg} is not a dependency of the consumer package.json`,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// 3. Guard the vendor dir.
|
|
110
|
+
if (existsSync(vendorPath)) {
|
|
111
|
+
if (!force) {
|
|
112
|
+
throw new EjectError(
|
|
113
|
+
`vendor/${vendorName} already exists; pass --force to overwrite`,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
await rm(vendorPath, { recursive: true, force: true });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 4. Copy source with an exclude filter. Returning false for a directory
|
|
120
|
+
// prunes the whole subtree (Node 22 fs.cp filter semantics).
|
|
121
|
+
let copiedFiles = 0;
|
|
122
|
+
await cp(sourceDir, vendorPath, {
|
|
123
|
+
recursive: true,
|
|
124
|
+
filter: (source) => {
|
|
125
|
+
const rel = relative(sourceDir, source);
|
|
126
|
+
if (rel === "") {
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
const segments = rel.split(sep);
|
|
130
|
+
const name = basename(rel);
|
|
131
|
+
// Exclude any path segment that is an excluded name (prunes subtrees).
|
|
132
|
+
if (segments.some((segment) => EXCLUDED_NAMES.has(segment))) {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
if (name.endsWith(".test.ts")) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
return true;
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// Count copied files (directories excluded) for the result summary.
|
|
143
|
+
copiedFiles = await countFiles(vendorPath);
|
|
144
|
+
|
|
145
|
+
// 5. Sanitize the vendored package.json.
|
|
146
|
+
const vendoredPkgPath = join(vendorPath, "package.json");
|
|
147
|
+
const vendoredPkg = await readPackageJson(vendoredPkgPath);
|
|
148
|
+
if (vendoredPkg.private === true) {
|
|
149
|
+
delete vendoredPkg.private;
|
|
150
|
+
}
|
|
151
|
+
await writePackageJson(vendoredPkgPath, vendoredPkg);
|
|
152
|
+
|
|
153
|
+
// 6. Rewrite the consumer dep in place (preserving key order).
|
|
154
|
+
const depSpecAfter = `file:./vendor/${vendorName}`;
|
|
155
|
+
// biome-ignore lint/style/noNonNullAssertion: depMap validated above.
|
|
156
|
+
consumerPkg[depMap]![pkg] = depSpecAfter;
|
|
157
|
+
await writePackageJson(consumerPkgPath, consumerPkg);
|
|
158
|
+
|
|
159
|
+
// 7. Return the result.
|
|
160
|
+
return {
|
|
161
|
+
pkg,
|
|
162
|
+
vendorPath,
|
|
163
|
+
depSpecBefore,
|
|
164
|
+
depSpecAfter,
|
|
165
|
+
copiedFiles,
|
|
166
|
+
followUp: "pnpm install",
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Recursively counts regular files under a directory. */
|
|
171
|
+
async function countFiles(dir: string): Promise<number> {
|
|
172
|
+
const { readdir } = await import("node:fs/promises");
|
|
173
|
+
let count = 0;
|
|
174
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
175
|
+
for (const entry of entries) {
|
|
176
|
+
const full = join(dir, entry.name);
|
|
177
|
+
if (entry.isDirectory()) {
|
|
178
|
+
count += await countFiles(full);
|
|
179
|
+
} else if (entry.isFile()) {
|
|
180
|
+
count += 1;
|
|
181
|
+
} else {
|
|
182
|
+
const info = await stat(full);
|
|
183
|
+
if (info.isFile()) {
|
|
184
|
+
count += 1;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return count;
|
|
189
|
+
}
|