lockfile-subset 1.0.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tmokmss
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,108 @@
1
+ # lockfile-subset
2
+
3
+ Extract a subset of `package-lock.json` for specified packages and their transitive dependencies.
4
+
5
+ ## Why?
6
+
7
+ When using bundlers like esbuild with `--external`, you need to ship those external packages separately (e.g., in a Docker multi-stage build or Lambda layer). Getting the exact right set of dependencies is surprisingly hard:
8
+
9
+ | Approach | Problem |
10
+ |---|---|
11
+ | Manually copy `node_modules` dirs | Breaks when transitive deps change (e.g., Prisma v6 added new deps) |
12
+ | `npm install <pkg>` in runner stage | Resolves versions independently — may differ from your lockfile |
13
+ | `npm ci --omit=dev` | Installs *all* prod dependencies, not just the ones you need |
14
+
15
+ **lockfile-subset** solves this by extracting a precise subset from your existing `package-lock.json` — only the packages you specify and their transitive dependencies, with versions exactly matching the original lockfile.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install -g lockfile-subset
21
+ # or use directly with npx
22
+ npx lockfile-subset
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```bash
28
+ # Extract @prisma/client and sharp with their transitive deps
29
+ lockfile-subset @prisma/client sharp
30
+
31
+ # Specify output directory
32
+ lockfile-subset @prisma/client sharp -o /standalone
33
+
34
+ # Use a different lockfile path
35
+ lockfile-subset @prisma/client sharp --lockfile /build/package-lock.json
36
+
37
+ # Generate + install in one step
38
+ lockfile-subset @prisma/client sharp -o /standalone --install
39
+
40
+ # Preview without writing files
41
+ lockfile-subset prisma --dry-run
42
+ ```
43
+
44
+ This generates a minimal `package.json` and `package-lock.json` in the output directory. Then run `npm ci` to install exactly those packages at the exact versions from your original lockfile.
45
+
46
+ ### Dockerfile example
47
+
48
+ ```dockerfile
49
+ # === Builder ===
50
+ FROM node AS builder
51
+ WORKDIR /build
52
+ COPY package*.json ./
53
+ RUN npm ci
54
+
55
+ COPY . .
56
+ RUN npx esbuild src/index.ts --bundle --outdir=dist \
57
+ --external:@prisma/client --external:sharp
58
+
59
+ # Generate subset lockfile + install
60
+ RUN npx lockfile-subset @prisma/client sharp \
61
+ -o /standalone --install
62
+
63
+ # === Runner ===
64
+ FROM node AS runner
65
+ WORKDIR /app
66
+
67
+ # Only the packages you need, at exact lockfile versions
68
+ COPY --from=builder /standalone/node_modules ./node_modules
69
+ COPY --from=builder /build/dist ./dist
70
+
71
+ CMD ["node", "dist/index.js"]
72
+ ```
73
+
74
+ ### Options
75
+
76
+ ```
77
+ lockfile-subset <packages...> [options]
78
+
79
+ Arguments:
80
+ packages Package names to extract (space-separated)
81
+
82
+ Options:
83
+ --lockfile, -l <path> Path to project directory (default: .)
84
+ --output, -o <dir> Output directory (default: ./lockfile-subset-output)
85
+ --no-optional Exclude optional dependencies
86
+ --install Run npm ci after generating the subset
87
+ --dry-run Print the result without writing files
88
+ --version, -v Show version
89
+ --help, -h Show help
90
+ ```
91
+
92
+ ## How it works
93
+
94
+ 1. Loads your `package-lock.json` using [`@npmcli/arborist`](https://github.com/npm/cli/tree/latest/workspaces/arborist) (npm's own dependency resolver)
95
+ 2. Starting from the specified packages, walks the dependency tree via BFS to collect all transitive dependencies
96
+ 3. Copies the matching entries from the original lockfile — no re-resolution, no version drift
97
+ 4. Outputs a minimal `package.json` + `package-lock.json` ready for `npm ci`
98
+
99
+ Dev dependencies of each package are excluded from traversal. Optional dependencies are included by default (use `--no-optional` to exclude).
100
+
101
+ ## Limitations
102
+
103
+ - **npm only** — pnpm and yarn have different lockfile formats. pnpm users can use `pnpm deploy`; yarn users can use `yarn workspaces focus`.
104
+ - **Platform-specific optional deps** — Packages like `sharp` have OS/arch-specific optional dependencies (e.g., `@img/sharp-linux-x64`). If your lockfile was generated on macOS but you run `npm ci` on Linux (e.g., in Docker), those Linux-specific packages may be missing from the lockfile. In that case, generate the lockfile on the target platform, or use `npm install` instead of `npm ci`.
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,2 @@
1
+
2
+ export { };
package/dist/index.mjs ADDED
@@ -0,0 +1,191 @@
1
+ #!/usr/bin/env node
2
+ import { join, resolve } from "path";
3
+ import { execSync } from "child_process";
4
+ import { createRequire } from "module";
5
+ import Arborist from "@npmcli/arborist";
6
+ import { mkdirSync, writeFileSync } from "fs";
7
+ //#region src/extract.ts
8
+ async function extractSubset({ projectPath, packageNames, includeOptional = true }) {
9
+ const tree = await new Arborist({ path: projectPath }).loadVirtual();
10
+ const keep = /* @__PURE__ */ new Set();
11
+ for (const name of packageNames) {
12
+ const edge = tree.edgesOut.get(name);
13
+ if (!edge?.to) throw new Error(`Package "${name}" not found in lockfile`);
14
+ const queue = [edge.to];
15
+ while (queue.length > 0) {
16
+ const node = queue.shift();
17
+ if (keep.has(node)) continue;
18
+ keep.add(node);
19
+ for (const e of node.edgesOut.values()) {
20
+ if (e.type === "dev") continue;
21
+ if (e.type === "optional" && !includeOptional) continue;
22
+ if (e.to && !keep.has(e.to)) queue.push(e.to);
23
+ }
24
+ }
25
+ }
26
+ const dependencies = {};
27
+ for (const name of packageNames) dependencies[name] = tree.edgesOut.get(name).to.version;
28
+ const subsetPackages = {};
29
+ subsetPackages[""] = {
30
+ name: "lockfile-subset-output",
31
+ version: "1.0.0",
32
+ dependencies
33
+ };
34
+ const originalPackages = tree.meta.data.packages;
35
+ for (const node of keep) {
36
+ const location = node.location;
37
+ if (originalPackages[location]) subsetPackages[location] = originalPackages[location];
38
+ }
39
+ const collected = [...keep].map((node) => ({
40
+ name: node.name,
41
+ version: node.version,
42
+ location: node.location
43
+ }));
44
+ return {
45
+ packageJson: {
46
+ name: "lockfile-subset-output",
47
+ version: "1.0.0",
48
+ dependencies
49
+ },
50
+ lockfileJson: {
51
+ name: "lockfile-subset-output",
52
+ version: "1.0.0",
53
+ lockfileVersion: 3,
54
+ requires: true,
55
+ packages: subsetPackages
56
+ },
57
+ collected
58
+ };
59
+ }
60
+ //#endregion
61
+ //#region src/write.ts
62
+ function writeOutput(outputDir, result) {
63
+ mkdirSync(outputDir, { recursive: true });
64
+ writeFileSync(join(outputDir, "package.json"), JSON.stringify(result.packageJson, null, 2) + "\n");
65
+ writeFileSync(join(outputDir, "package-lock.json"), JSON.stringify(result.lockfileJson, null, 2) + "\n");
66
+ }
67
+ //#endregion
68
+ //#region src/index.ts
69
+ const { version: VERSION } = createRequire(import.meta.url)("../package.json");
70
+ function parseArgs(argv) {
71
+ const args = {
72
+ packages: [],
73
+ lockfile: ".",
74
+ output: "./lockfile-subset-output",
75
+ includeOptional: true,
76
+ install: false,
77
+ dryRun: false,
78
+ help: false,
79
+ version: false
80
+ };
81
+ let i = 0;
82
+ while (i < argv.length) {
83
+ const arg = argv[i];
84
+ switch (arg) {
85
+ case "--lockfile":
86
+ case "-l":
87
+ args.lockfile = argv[++i];
88
+ break;
89
+ case "--output":
90
+ case "-o":
91
+ args.output = argv[++i];
92
+ break;
93
+ case "--no-optional":
94
+ args.includeOptional = false;
95
+ break;
96
+ case "--install":
97
+ args.install = true;
98
+ break;
99
+ case "--dry-run":
100
+ args.dryRun = true;
101
+ break;
102
+ case "--help":
103
+ case "-h":
104
+ args.help = true;
105
+ break;
106
+ case "--version":
107
+ case "-v":
108
+ args.version = true;
109
+ break;
110
+ default:
111
+ if (arg.startsWith("-")) {
112
+ console.error(`Unknown option: ${arg}`);
113
+ process.exit(1);
114
+ }
115
+ args.packages.push(arg);
116
+ }
117
+ i++;
118
+ }
119
+ return args;
120
+ }
121
+ const HELP = `
122
+ lockfile-subset <packages...> [options]
123
+
124
+ Extract a subset of package-lock.json for specified packages and their transitive dependencies.
125
+
126
+ Arguments:
127
+ packages Package names to extract (one or more, space-separated)
128
+
129
+ Options:
130
+ --lockfile, -l <path> Path to project dir or package-lock.json (default: .)
131
+ --output, -o <dir> Output directory (default: ./lockfile-subset-output)
132
+ --no-optional Exclude optional dependencies
133
+ --install Run npm ci after generating the subset
134
+ --dry-run Print the result without writing files
135
+ --version, -v Show version
136
+ --help, -h Show this help
137
+
138
+ Examples:
139
+ lockfile-subset prisma sharp
140
+ lockfile-subset prisma sharp -o /lambda-standalone
141
+ lockfile-subset prisma sharp --lockfile /build/package-lock.json
142
+ lockfile-subset prisma sharp -o /lambda-standalone --install
143
+ lockfile-subset prisma --dry-run
144
+ `.trim();
145
+ async function main() {
146
+ const args = parseArgs(process.argv.slice(2));
147
+ if (args.version) {
148
+ console.log(VERSION);
149
+ return;
150
+ }
151
+ if (args.help) {
152
+ console.log(HELP);
153
+ return;
154
+ }
155
+ if (args.packages.length === 0) {
156
+ console.error("Error: At least one package name is required.\n");
157
+ console.log(HELP);
158
+ process.exit(1);
159
+ }
160
+ const projectPath = resolve(args.lockfile);
161
+ const outputDir = resolve(args.output);
162
+ const result = await extractSubset({
163
+ projectPath,
164
+ packageNames: args.packages,
165
+ includeOptional: args.includeOptional
166
+ });
167
+ console.log(`Collected ${result.collected.length} packages (${args.packages.length} direct, ${result.collected.length - args.packages.length} transitive)`);
168
+ if (args.dryRun) {
169
+ console.log("\n--- package.json ---");
170
+ console.log(JSON.stringify(result.packageJson, null, 2));
171
+ console.log("\n--- package-lock.json ---");
172
+ console.log(JSON.stringify(result.lockfileJson, null, 2));
173
+ return;
174
+ }
175
+ writeOutput(outputDir, result);
176
+ console.log(`Written to ${outputDir}`);
177
+ if (args.install) {
178
+ console.log("Running npm ci...");
179
+ execSync("npm ci", {
180
+ cwd: outputDir,
181
+ stdio: "inherit"
182
+ });
183
+ console.log("Done.");
184
+ }
185
+ }
186
+ main().catch((err) => {
187
+ console.error(`Error: ${err.message}`);
188
+ process.exit(1);
189
+ });
190
+ //#endregion
191
+ export {};
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "lockfile-subset",
3
+ "version": "1.0.0",
4
+ "description": "Extract a subset of package-lock.json for specified packages and their transitive dependencies",
5
+ "type": "module",
6
+ "bin": {
7
+ "lockfile-subset": "./dist/index.mjs"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsdown",
14
+ "test": "vitest run",
15
+ "test:watch": "vitest"
16
+ },
17
+ "keywords": [
18
+ "npm",
19
+ "lockfile",
20
+ "package-lock",
21
+ "subset",
22
+ "docker",
23
+ "dependencies"
24
+ ],
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/tmokmss/lockfile-subset.git"
28
+ },
29
+ "license": "MIT",
30
+ "devDependencies": {
31
+ "@semantic-release/changelog": "^6.0.3",
32
+ "@semantic-release/git": "^10.0.1",
33
+ "@types/node": "^25.5.0",
34
+ "@types/npmcli__arborist": "^6.3.3",
35
+ "semantic-release": "^25.0.3",
36
+ "tsdown": "^0.21.4",
37
+ "typescript": "^5.9.3",
38
+ "vitest": "^4.1.0"
39
+ },
40
+ "dependencies": {
41
+ "@npmcli/arborist": "^9.4.2"
42
+ }
43
+ }