File size: 11,627 Bytes
d4f7e1d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | #!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, posix, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(scriptDir, "..");
const codingAgentDir = join(repoRoot, "packages/coding-agent");
const rootLockfilePath = join(repoRoot, "package-lock.json");
const shrinkwrapPath = join(codingAgentDir, "npm-shrinkwrap.json");
const internalPackagePrefix = "@earendil-works/pi-";
const internalPackageNames = new Set(["@earendil-works/chord"]);
const allowedInstallScriptPackages = new Map([
["@google/genai@2.21.0", "preinstall is a no-op in the published package"],
["esbuild@0.28.2", "postinstall selects and verifies the platform-specific esbuild binary"],
["protobufjs@7.6.6", "postinstall only warns about protobufjs version scheme mismatches"],
]);
const args = new Set(process.argv.slice(2));
const checkOnly = args.has("--check");
for (const arg of args) {
if (arg !== "--check") {
console.error(`Unknown argument: ${arg}`);
process.exit(1);
}
}
function readJson(path) {
return JSON.parse(readFileSync(path, "utf8"));
}
function packageDependencies(entry) {
return {
...(entry.dependencies ?? {}),
...(entry.optionalDependencies ?? {}),
};
}
function sortedObject(object) {
return Object.fromEntries(Object.entries(object).sort(([a], [b]) => a.localeCompare(b)));
}
function sortedPackageEntry(entry) {
const fieldOrder = [
"name",
"version",
"resolved",
"integrity",
"license",
"dependencies",
"optionalDependencies",
"peerDependencies",
"peerDependenciesMeta",
"bin",
"engines",
"os",
"cpu",
"libc",
"optional",
"hasInstallScript",
"deprecated",
"funding",
];
const sorted = {};
for (const field of fieldOrder) {
if (entry[field] !== undefined) {
sorted[field] = entry[field];
}
}
for (const [field, value] of Object.entries(entry).sort(([a], [b]) => a.localeCompare(b))) {
if (sorted[field] === undefined) {
sorted[field] = value;
}
}
return sorted;
}
function copyLockEntry(entry) {
const copied = { ...entry };
delete copied.dev;
delete copied.devOptional;
delete copied.extraneous;
delete copied.link;
return sortedPackageEntry(copied);
}
function copyPackageJsonEntry(packageJson, options) {
const entry = options.includeName
? { name: packageJson.name, version: packageJson.version }
: { version: packageJson.version };
for (const field of [
"license",
"dependencies",
"optionalDependencies",
"peerDependencies",
"peerDependenciesMeta",
"bin",
"engines",
"os",
"cpu",
"libc",
]) {
if (packageJson[field] !== undefined) {
entry[field] = packageJson[field];
}
}
return sortedPackageEntry(entry);
}
function packageNameFromLockPath(lockPath) {
const marker = "node_modules/";
const index = lockPath.lastIndexOf(marker);
if (index === -1) {
return undefined;
}
const parts = lockPath.slice(index + marker.length).split("/");
if (parts[0]?.startsWith("@")) {
return `${parts[0]}/${parts[1]}`;
}
return parts[0];
}
function registryTarballUrl(packageName, version) {
const tarballName = packageName.startsWith("@") ? packageName.split("/")[1] : packageName;
return `https://registry.npmjs.org/${packageName}/-/${tarballName}-${version}.tgz`;
}
function getInternalWorkspaces(lockPackages) {
const workspaces = new Map();
for (const [lockPath, entry] of Object.entries(lockPackages)) {
if (!lockPath.startsWith("packages/") || lockPath.includes("/node_modules/") || !entry.name || !entry.version) {
continue;
}
if (!entry.name.startsWith(internalPackagePrefix) && !internalPackageNames.has(entry.name)) {
continue;
}
workspaces.set(entry.name, {
lockPath,
packageJson: readJson(join(repoRoot, lockPath, "package.json")),
});
}
return workspaces;
}
function resolveExternalDependency(lockPackages, packageName, fromLockPath) {
const candidateDirs = [];
let current = fromLockPath;
while (current) {
candidateDirs.push(current);
const parent = posix.dirname(current);
if (parent === "." || parent === current) {
break;
}
current = parent;
}
candidateDirs.push("");
const tried = new Set();
for (const directory of candidateDirs) {
const candidate = directory ? `${directory}/node_modules/${packageName}` : `node_modules/${packageName}`;
if (tried.has(candidate)) {
continue;
}
tried.add(candidate);
const entry = lockPackages[candidate];
if (entry && !entry.link) {
return candidate;
}
}
const suffix = `node_modules/${packageName}`;
const matches = Object.entries(lockPackages)
.filter(([lockPath, entry]) => !entry.link && (lockPath === suffix || lockPath.endsWith(`/${suffix}`)))
.map(([lockPath]) => lockPath);
if (matches.length === 1) {
return matches[0];
}
throw new Error(
`Cannot resolve ${packageName} from ${fromLockPath || "root"}. ` +
(matches.length > 1 ? `Matches: ${matches.join(", ")}` : "No matching lockfile entry found."),
);
}
function addInternalWorkspace(shrinkwrapPackages, addedPaths, queue, name, workspace) {
const packageJson = workspace.packageJson;
const outputPath = `node_modules/${name}`;
const entry = copyPackageJsonEntry(packageJson, { includeName: false });
entry.resolved = registryTarballUrl(name, packageJson.version);
shrinkwrapPackages[outputPath] = sortedPackageEntry(entry);
addedPaths.add(outputPath);
for (const dependencyName of Object.keys(packageDependencies(packageJson))) {
queue.push({
name: dependencyName,
sourceFrom: workspace.lockPath,
sourceBase: workspace.lockPath,
outputBase: outputPath,
});
}
}
function addExternalPackage(lockPackages, shrinkwrapPackages, addedPaths, queue, item) {
const sourceLockPath = resolveExternalDependency(lockPackages, item.name, item.sourceFrom);
const outputLockPath =
item.sourceBase && sourceLockPath.startsWith(`${item.sourceBase}/`)
? [item.outputBase, sourceLockPath.slice(item.sourceBase.length + 1)].filter(Boolean).join("/")
: sourceLockPath;
if (addedPaths.has(outputLockPath)) {
return;
}
const entry = lockPackages[sourceLockPath];
shrinkwrapPackages[outputLockPath] = copyLockEntry(entry);
addedPaths.add(outputLockPath);
for (const dependencyName of Object.keys(packageDependencies(entry))) {
queue.push({
name: dependencyName,
sourceFrom: sourceLockPath,
sourceBase: item.sourceBase,
outputBase: item.outputBase,
});
}
}
function validateShrinkwrap(shrinkwrap, internalNames) {
const errors = [];
const includedPaths = new Set(Object.keys(shrinkwrap.packages));
const includedPackageNames = new Set();
const seenAllowedInstallScriptPackages = new Set();
for (const [lockPath, entry] of Object.entries(shrinkwrap.packages)) {
const packageName = packageNameFromLockPath(lockPath);
if (packageName) {
includedPackageNames.add(packageName);
}
if (entry.link) {
errors.push(`${lockPath} is a link entry`);
}
if (typeof entry.resolved === "string" && /^(file:|link:|workspace:|\.\.?\/|\/)/.test(entry.resolved)) {
errors.push(`${lockPath} has a local resolved value: ${entry.resolved}`);
}
if (entry.hasInstallScript) {
if (!packageName || !entry.version) {
errors.push(`${lockPath || "root"} has install scripts but no package name/version`);
} else {
const packageId = `${packageName}@${entry.version}`;
if (allowedInstallScriptPackages.has(packageId)) {
seenAllowedInstallScriptPackages.add(packageId);
} else {
errors.push(
`${lockPath} has install scripts (${packageId}). Review it and add it to allowedInstallScriptPackages if intentional.`,
);
}
}
}
}
for (const packageId of allowedInstallScriptPackages.keys()) {
if (!seenAllowedInstallScriptPackages.has(packageId)) {
errors.push(`allowed install-script package ${packageId} is no longer present; remove it from the allowlist`);
}
}
for (const name of internalNames) {
if (!includedPackageNames.has(name)) {
errors.push(`internal dependency ${name} is missing`);
}
}
for (const [lockPath, entry] of Object.entries(shrinkwrap.packages)) {
for (const dependencyName of Object.keys(packageDependencies(entry))) {
const dependencyIncluded = [...includedPaths].some(
(candidate) => candidate === `node_modules/${dependencyName}` || candidate.endsWith(`/node_modules/${dependencyName}`),
);
if (!dependencyIncluded) {
errors.push(`${lockPath || "root"} dependency ${dependencyName} is missing`);
}
}
}
const platformPackageCount = Object.values(shrinkwrap.packages).filter((entry) => entry.os || entry.cpu || entry.libc).length;
if (platformPackageCount === 0) {
errors.push("no platform-specific optional dependency entries found");
}
if (errors.length > 0) {
throw new Error(`Generated shrinkwrap failed validation:\n${errors.map((error) => ` - ${error}`).join("\n")}`);
}
}
function generateShrinkwrap() {
const rootLock = readJson(rootLockfilePath);
if (rootLock.lockfileVersion !== 3 || !rootLock.packages) {
throw new Error("package-lock.json must be lockfileVersion 3 and contain a packages map");
}
const lockPackages = rootLock.packages;
const codingAgentPackage = readJson(join(codingAgentDir, "package.json"));
const internalWorkspaces = getInternalWorkspaces(lockPackages);
const shrinkwrapPackages = {
"": copyPackageJsonEntry(codingAgentPackage, { includeName: true }),
};
const addedPaths = new Set([""]);
const internalNames = new Set();
const queue = Object.keys(packageDependencies(codingAgentPackage)).map((name) => ({
name,
sourceFrom: "packages/coding-agent",
sourceBase: "packages/coding-agent",
outputBase: "",
}));
while (queue.length > 0) {
const item = queue.shift();
if (!item) {
break;
}
const workspace = internalWorkspaces.get(item.name);
if (workspace) {
const outputPath = `node_modules/${item.name}`;
internalNames.add(item.name);
if (!addedPaths.has(outputPath)) {
addInternalWorkspace(shrinkwrapPackages, addedPaths, queue, item.name, workspace);
}
continue;
}
addExternalPackage(lockPackages, shrinkwrapPackages, addedPaths, queue, item);
}
const shrinkwrap = {
name: codingAgentPackage.name,
version: codingAgentPackage.version,
lockfileVersion: 3,
requires: true,
packages: sortedObject(shrinkwrapPackages),
};
validateShrinkwrap(shrinkwrap, internalNames);
return shrinkwrap;
}
try {
const shrinkwrap = generateShrinkwrap();
const content = `${JSON.stringify(shrinkwrap, null, "\t")}\n`;
if (checkOnly) {
if (!existsSync(shrinkwrapPath)) {
console.error("packages/coding-agent/npm-shrinkwrap.json is missing.");
console.error("Run: npm run shrinkwrap:coding-agent");
process.exit(1);
}
const current = readFileSync(shrinkwrapPath, "utf8");
if (current !== content) {
console.error("packages/coding-agent/npm-shrinkwrap.json is out of date.");
console.error("Run: npm run shrinkwrap:coding-agent");
process.exit(1);
}
console.log("packages/coding-agent/npm-shrinkwrap.json is up to date.");
} else {
writeFileSync(shrinkwrapPath, content);
const packageCount = Object.keys(shrinkwrap.packages).length - 1;
const platformPackageCount = Object.values(shrinkwrap.packages).filter((entry) => entry.os || entry.cpu || entry.libc).length;
console.log(
`Wrote packages/coding-agent/npm-shrinkwrap.json (${packageCount} packages, ${platformPackageCount} platform-specific).`,
);
}
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
}
|