foster-oss 0.0.0-stage → 0.2.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.
@@ -0,0 +1,148 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import semver from "semver";
4
+ import { detectLockfiles, readDependencies } from "./lockfile.js";
5
+ const DEP_FIELDS = ["dependencies", "devDependencies", "optionalDependencies"];
6
+ export function detectManager(dir) {
7
+ const locks = detectLockfiles(dir);
8
+ for (const m of ["pnpm", "yarn", "npm"]) {
9
+ if (locks.some((l) => l.manager === m))
10
+ return m;
11
+ }
12
+ return existsSync(join(dir, "package.json")) ? "npm" : null;
13
+ }
14
+ function overrideContainer(pkg, manager) {
15
+ if (manager === "pnpm") {
16
+ const pnpm = (pkg.pnpm ??= {});
17
+ return { field: "pnpm.overrides", obj: (pnpm.overrides ??= {}) };
18
+ }
19
+ if (manager === "yarn")
20
+ return { field: "resolutions", obj: (pkg.resolutions ??= {}) };
21
+ return { field: "overrides", obj: (pkg.overrides ??= {}) };
22
+ }
23
+ /**
24
+ * Point every dependency that has a released drop-in patch (Foster or another provider) at the patched package, using an npm alias
25
+ * ("npm:@foster-oss/ip@2.0.1-foster.1"). Code keeps importing the original name; only the bytes change.
26
+ * Direct dependencies are rewritten in place (npm rejects overrides that conflict with direct deps);
27
+ * transitive ones get an override/resolution entry.
28
+ */
29
+ export function applyFixes(dirInput, findings, opts = {}) {
30
+ const dir = resolve(dirInput);
31
+ const manager = detectManager(dir);
32
+ const result = { dir, manager, changes: [], skipped: [], written: false };
33
+ const patchable = findings.filter((f) => f.kind === "patch-available" && f.patch);
34
+ for (const f of patchable) {
35
+ if (f.dependency.ecosystem !== "npm") {
36
+ result.skipped.push({
37
+ package: `${f.dependency.name}@${f.dependency.version}`,
38
+ reason: "automatic fixes are npm-only for now; see the patch folder for manual pip/uv instructions",
39
+ });
40
+ }
41
+ }
42
+ const npmPatchable = patchable.filter((f) => f.dependency.ecosystem === "npm");
43
+ if (npmPatchable.length === 0)
44
+ return result;
45
+ if (!manager) {
46
+ result.skipped.push({ package: "*", reason: "no package.json found" });
47
+ return result;
48
+ }
49
+ const pkgPath = join(dir, "package.json");
50
+ const raw = readFileSync(pkgPath, "utf8");
51
+ const hasBom = raw.charCodeAt(0) === 0xfeff;
52
+ const original = hasBom ? raw.slice(1) : raw;
53
+ const pkg = JSON.parse(original);
54
+ // Every installed version of every npm package, so an override never reaches a copy that is not affected.
55
+ const installed = new Map();
56
+ for (const lock of detectLockfiles(dir).filter((l) => l.ecosystem === "npm")) {
57
+ for (const d of readDependencies(dir, lock)) {
58
+ const set = installed.get(d.name) ?? new Set();
59
+ set.add(d.version);
60
+ installed.set(d.name, set);
61
+ }
62
+ }
63
+ const byName = new Map();
64
+ for (const f of npmPatchable) {
65
+ const list = byName.get(f.dependency.name) ?? [];
66
+ list.push(f);
67
+ byName.set(f.dependency.name, list);
68
+ }
69
+ for (const [name, group] of byName) {
70
+ for (const f of group) {
71
+ const version = f.dependency.version;
72
+ const target = `npm:${f.patch.replacement.name}@${f.patch.replacement.version}`;
73
+ // A direct dependency is rewritten only where its declared range is what installed this exact version;
74
+ // a safe "ip": "^3.0.0" must never be pointed back at a 2.x patch.
75
+ const directFields = DEP_FIELDS.filter((field) => {
76
+ const spec = pkg[field]?.[name];
77
+ return spec !== undefined && semver.validRange(spec) !== null && semver.satisfies(version, spec, { includePrerelease: true });
78
+ });
79
+ if (directFields.length > 0) {
80
+ for (const field of directFields) {
81
+ const deps = pkg[field];
82
+ const from = deps[name];
83
+ if (from === target)
84
+ continue;
85
+ deps[name] = target;
86
+ result.changes.push({ package: name, field, key: name, from, to: target, applied: true });
87
+ }
88
+ continue;
89
+ }
90
+ const { field, obj } = overrideContainer(pkg, manager);
91
+ let key = `${name}@${version}`;
92
+ if (manager === "yarn") {
93
+ // Yarn resolutions cannot target one resolved version, so only override when every installed copy is affected.
94
+ const all = installed.get(name) ?? new Set([version]);
95
+ const affected = new Set(group.map((g) => g.dependency.version));
96
+ if ([...all].some((v) => !affected.has(v))) {
97
+ result.skipped.push({ package: `${name}@${version}`, reason: "yarn resolutions would also replace unaffected copies of this package; fix by hand" });
98
+ continue;
99
+ }
100
+ key = name;
101
+ }
102
+ const existing = obj[key];
103
+ const existingValue = typeof existing === "object" && existing !== null ? existing["."] : existing;
104
+ if (existingValue === target)
105
+ continue;
106
+ if (existing !== undefined && !opts.force) {
107
+ result.changes.push({ package: name, field, key, from: existingValue ?? JSON.stringify(existing), to: target, applied: false, note: "existing override kept; rerun with --force to replace it" });
108
+ continue;
109
+ }
110
+ if (typeof existing === "object" && existing !== null) {
111
+ // npm nested override: keep the child overrides, replace only the package itself.
112
+ existing["."] = target;
113
+ }
114
+ else {
115
+ obj[key] = target;
116
+ }
117
+ result.changes.push({ package: name, field, key, from: existingValue, to: target, applied: true });
118
+ if (manager === "yarn")
119
+ break; // one name-level resolution covers every copy
120
+ }
121
+ }
122
+ const applied = result.changes.some((c) => c.applied);
123
+ if (applied && !opts.dryRun) {
124
+ writeFileSync(pkgPath, (hasBom ? "" : "") + stringifyLike(original, pkg));
125
+ result.written = true;
126
+ }
127
+ return result;
128
+ }
129
+ /** Re-serialise JSON keeping the original indentation and trailing newline. */
130
+ export function stringifyLike(original, value) {
131
+ const indentMatch = original.match(/^[ \t]+(?=")/m);
132
+ const indent = indentMatch ? indentMatch[0] : " ";
133
+ const eol = original.includes("\r\n") ? "\r\n" : "\n";
134
+ let out = JSON.stringify(value, null, indent);
135
+ if (eol === "\r\n")
136
+ out = out.replace(/\n/g, "\r\n");
137
+ return original.endsWith("\n") ? out + eol : out;
138
+ }
139
+ export function installCommand(manager) {
140
+ switch (manager) {
141
+ case "pnpm":
142
+ return "pnpm install";
143
+ case "yarn":
144
+ return "yarn install";
145
+ default:
146
+ return "npm install";
147
+ }
148
+ }
@@ -0,0 +1,17 @@
1
+ export declare function fosterVersion(): string;
2
+ /** ecosyste.ms blocks anonymous default user agents, so every request identifies Foster. */
3
+ export declare function userAgent(): string;
4
+ export declare class HttpError extends Error {
5
+ readonly status: number;
6
+ readonly url: string;
7
+ constructor(status: number, url: string, message: string);
8
+ }
9
+ export interface FetchJsonOptions {
10
+ method?: "GET" | "POST";
11
+ body?: unknown;
12
+ timeoutMs?: number;
13
+ retries?: number;
14
+ }
15
+ export declare function fetchJson<T>(url: string, opts?: FetchJsonOptions): Promise<T>;
16
+ /** Run async work over items with a fixed concurrency limit, preserving order. */
17
+ export declare function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]>;
@@ -0,0 +1,84 @@
1
+ import { readFileSync } from "node:fs";
2
+ let cachedVersion;
3
+ export function fosterVersion() {
4
+ if (cachedVersion)
5
+ return cachedVersion;
6
+ try {
7
+ const pkg = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
8
+ cachedVersion = pkg.version ?? "0.0.0";
9
+ }
10
+ catch {
11
+ cachedVersion = "0.0.0";
12
+ }
13
+ return cachedVersion;
14
+ }
15
+ /** ecosyste.ms blocks anonymous default user agents, so every request identifies Foster. */
16
+ export function userAgent() {
17
+ return `foster-oss/${fosterVersion()} (+https://github.com/foster-oss/foster)`;
18
+ }
19
+ export class HttpError extends Error {
20
+ status;
21
+ url;
22
+ constructor(status, url, message) {
23
+ super(message);
24
+ this.status = status;
25
+ this.url = url;
26
+ this.name = "HttpError";
27
+ }
28
+ }
29
+ export async function fetchJson(url, opts = {}) {
30
+ const { method = "GET", body, timeoutMs = 30_000, retries = 2 } = opts;
31
+ let lastError;
32
+ for (let attempt = 0; attempt <= retries; attempt++) {
33
+ try {
34
+ const res = await fetch(url, {
35
+ method,
36
+ headers: {
37
+ "User-Agent": userAgent(),
38
+ Accept: "application/json",
39
+ ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
40
+ },
41
+ body: body !== undefined ? JSON.stringify(body) : undefined,
42
+ signal: AbortSignal.timeout(timeoutMs),
43
+ });
44
+ if (res.status === 404) {
45
+ throw new HttpError(404, url, `Not found: ${url}`);
46
+ }
47
+ if (res.status === 429 || res.status >= 500) {
48
+ lastError = new HttpError(res.status, url, `HTTP ${res.status} from ${url}`);
49
+ await sleep(500 * 2 ** attempt);
50
+ continue;
51
+ }
52
+ if (!res.ok) {
53
+ throw new HttpError(res.status, url, `HTTP ${res.status} from ${url}`);
54
+ }
55
+ return (await res.json());
56
+ }
57
+ catch (err) {
58
+ if (err instanceof HttpError && err.status !== 429 && err.status < 500)
59
+ throw err;
60
+ lastError = err;
61
+ if (attempt < retries)
62
+ await sleep(500 * 2 ** attempt);
63
+ }
64
+ }
65
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
66
+ }
67
+ function sleep(ms) {
68
+ return new Promise((resolve) => setTimeout(resolve, ms));
69
+ }
70
+ /** Run async work over items with a fixed concurrency limit, preserving order. */
71
+ export async function mapLimit(items, limit, fn) {
72
+ const results = new Array(items.length);
73
+ let next = 0;
74
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
75
+ while (true) {
76
+ const i = next++;
77
+ if (i >= items.length)
78
+ return;
79
+ results[i] = await fn(items[i], i);
80
+ }
81
+ });
82
+ await Promise.all(workers);
83
+ return results;
84
+ }
@@ -0,0 +1,51 @@
1
+ import type { Dependency, Ecosystem } from "./types.js";
2
+ export type NodeManager = "npm" | "pnpm" | "yarn";
3
+ export type LockfileKind = "package-lock" | "pnpm-lock" | "yarn-lock" | "requirements" | "uv-lock" | "poetry-lock" | "pipfile-lock" | "cargo-lock" | "go-mod" | "gemfile-lock" | "composer-lock";
4
+ export interface LockfileInfo {
5
+ file: string;
6
+ kind: LockfileKind;
7
+ ecosystem: Ecosystem;
8
+ manager?: NodeManager;
9
+ }
10
+ export declare function detectLockfiles(dir: string): LockfileInfo[];
11
+ /** Read a text file, dropping a UTF-8 byte order mark (common on Windows) so JSON.parse accepts it. */
12
+ export declare function readText(path: string): string;
13
+ /** Names listed directly in package.json, used to mark direct dependencies. */
14
+ export declare function directNpmNames(dir: string): Set<string>;
15
+ export declare function readDependencies(dir: string, lock: LockfileInfo): Dependency[];
16
+ /** Poetry's poetry.lock (TOML): [[package]] tables with name and version. */
17
+ export declare function parsePoetryLock(text: string): [string, string][];
18
+ /** Pipenv's Pipfile.lock (JSON): "default" and "develop" maps of name → { version: "==1.2.3" }. */
19
+ export declare function parsePipfileLock(text: string): [string, string][];
20
+ /** Cargo.lock: registry packages only (workspace members and git/path deps have no registry source). */
21
+ export declare function parseCargoLock(text: string): [string, string][];
22
+ /** Dependency names declared in Cargo.toml ([dependencies], [dev-dependencies], [build-dependencies], target tables). */
23
+ export declare function directCargoNames(dir: string): Set<string>;
24
+ /**
25
+ * go.mod: the require directives list the full module graph needed for the build since Go 1.17;
26
+ * `// indirect` marks transitive ones. `replace` directives are honoured for module path and version.
27
+ */
28
+ export declare function parseGoMod(text: string): {
29
+ pairs: [string, string][];
30
+ direct: Set<string>;
31
+ };
32
+ /** Gemfile.lock: gems under the GEM specs section; DEPENDENCIES lists the direct ones. */
33
+ export declare function parseGemfileLock(text: string): {
34
+ pairs: [string, string][];
35
+ direct: Set<string>;
36
+ };
37
+ /** composer.lock: "packages" and "packages-dev"; versions may carry a leading "v". */
38
+ export declare function parseComposerLock(text: string): [string, string][];
39
+ export declare function directComposerNames(dir: string): Set<string>;
40
+ /** package-lock.json / npm-shrinkwrap.json, lockfileVersion 1, 2 and 3. */
41
+ export declare function parsePackageLock(text: string): [string, string][];
42
+ /** Split "name@version" where name may be scoped ("@scope/name@1.0.0"). */
43
+ export declare function splitNameVersion(spec: string): [string, string] | null;
44
+ /** pnpm-lock.yaml, lockfile versions 5.x, 6.x and 9.x. */
45
+ export declare function parsePnpmLock(text: string): [string, string][];
46
+ /** yarn.lock, both classic (v1) and berry (v2+). */
47
+ export declare function parseYarnLock(text: string): [string, string][];
48
+ /** requirements.txt: only exact pins (name==version) are resolvable without running pip. */
49
+ export declare function parseRequirements(text: string): [string, string][];
50
+ /** uv.lock (TOML): read name/version pairs from [[package]] tables. */
51
+ export declare function parseUvLock(text: string): [string, string][];