Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 28 additions & 28 deletions dist/azure/index.mjs

Large diffs are not rendered by default.

52 changes: 26 additions & 26 deletions dist/gitlab/index.mjs

Large diffs are not rendered by default.

121 changes: 63 additions & 58 deletions dist/index.mjs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"zod": "^4.0.0"
},
"devDependencies": {
"@cloudflare/oxlint-config": "^0.2.0",
"@e18e/eslint-plugin": "^0.8.1",
"@types/node": "^24.0.0",
"fallow": "3.33.1",
Expand Down
295 changes: 76 additions & 219 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

36 changes: 20 additions & 16 deletions src/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ vi.mock("@actions/core", () => ({
exportVariable: vi.fn(),
}));

vi.mock("node:fs", async () => {
const actual = await vi.importActual<typeof import("node:fs")>("node:fs");
vi.mock(import("node:fs"), async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
existsSync: vi.fn(),
Expand Down Expand Up @@ -106,7 +106,7 @@ describe("configAuthentication", () => {

configAuthentication("https://registry.npmjs.org/");

const written = vi.mocked(writeFileSync).mock.calls[0]![1] as string;
const written = vi.mocked(writeFileSync).mock.calls[0][1];
expect(written).toContain("always-auth=true");
expect(written).not.toContain("https://old.reg/");
expect(written).toContain("registry=https://registry.npmjs.org/");
Expand All @@ -124,7 +124,7 @@ describe("configAuthentication", () => {

configAuthentication("https://registry.npmjs.org/");

const written = vi.mocked(writeFileSync).mock.calls[0]![1] as string;
const written = vi.mocked(writeFileSync).mock.calls[0][1];
expect(written).not.toContain("old-token");
expect(written).toContain("other-config=true");
expect(written).toContain("//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}");
Expand All @@ -136,7 +136,7 @@ describe("configAuthentication", () => {

configAuthentication("https://registry.npmjs.org/");

const written = vi.mocked(writeFileSync).mock.calls[0]![1] as string;
const written = vi.mocked(writeFileSync).mock.calls[0][1];
expect(written).toContain("always-auth=true");
expect(written).not.toContain("https://old.reg/");
});
Expand All @@ -146,7 +146,7 @@ describe("configAuthentication", () => {

configAuthentication("https://npm.pkg.github.com.evil.example");

const written = vi.mocked(writeFileSync).mock.calls[0]![1] as string;
const written = vi.mocked(writeFileSync).mock.calls[0][1];
// Should NOT have scoped registry — the host doesn't match exactly
expect(written).not.toContain("@voidzero-dev:");
});
Expand Down Expand Up @@ -188,6 +188,14 @@ describe("configAuthentication", () => {
});
});

function mockNoNpmrc(): void {
vi.mocked(readFileSync).mockImplementation(() => {
const err = Object.assign(new Error("ENOENT"), { code: "ENOENT" });
throw err;
});
vi.mocked(existsSync).mockReturnValue(false);
}

describe("propagateProjectNpmrcAuth", () => {
const runnerTemp = resolve("/tmp/runner");
const projectDir = resolve("/workspace/project");
Expand All @@ -196,8 +204,12 @@ describe("propagateProjectNpmrcAuth", () => {

function mockNpmrc(content: string, supplemental?: string): void {
vi.mocked(readFileSync).mockImplementation((p) => {
if (p === npmrcPath) return content;
if (p === supplementalPath && supplemental !== undefined) return supplemental;
if (p === npmrcPath) {
return content;
}
if (p === supplementalPath && supplemental !== undefined) {
return supplemental;
}
const err = Object.assign(new Error("ENOENT"), { code: "ENOENT" });
throw err;
});
Expand All @@ -206,14 +218,6 @@ describe("propagateProjectNpmrcAuth", () => {
);
}

function mockNoNpmrc(): void {
vi.mocked(readFileSync).mockImplementation(() => {
const err = Object.assign(new Error("ENOENT"), { code: "ENOENT" });
throw err;
});
vi.mocked(existsSync).mockReturnValue(false);
}

beforeEach(() => {
vi.stubEnv("RUNNER_TEMP", runnerTemp);
});
Expand Down
44 changes: 24 additions & 20 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { readFileSync, writeFileSync } from "node:fs";
import { readFileIfExists } from "./ci/fs.js";
import { writeFileSync } from "node:fs";
import { EOL } from "node:os";
import { join, resolve } from "node:path";
import { debug, exportVariable, info } from "@actions/core";
Expand All @@ -22,15 +23,6 @@ function buildAuthLine(registryUrl: string): string {
return `${stripProtocol(registryUrl)}:_authToken=${NODE_AUTH_TOKEN_REF}`;
}

function readNpmrc(path: string): string | undefined {
try {
return readFileSync(path, "utf8");
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
throw err;
}
}

/**
* Configure npm registry authentication by writing a .npmrc file.
* Ported from actions/setup-node's authutil.ts.
Expand Down Expand Up @@ -65,13 +57,17 @@ function writeRegistryToFile(registryUrl: string, fileLocation: string, scope?:

const authPrefix = stripProtocol(registryUrl).toLowerCase();

const lines: string[] = [];
const existing = readNpmrc(fileLocation);
const lines: Array<string> = [];
const existing = readFileIfExists(fileLocation);
if (existing !== undefined) {
for (const line of existing.split(LINE_BREAK_RE)) {
const lower = line.toLowerCase();
if (lower.startsWith(`${scopePrefix}registry`)) continue;
if (lower.startsWith(authPrefix) && lower.includes("_authtoken")) continue;
if (lower.startsWith(`${scopePrefix}registry`)) {
continue;
}
if (lower.startsWith(authPrefix) && lower.includes("_authtoken")) {
continue;
}
lines.push(line);
}
}
Expand All @@ -94,9 +90,15 @@ const RUNTIME_ENV_ALLOWLIST = new Set(["GITHUB_TOKEN"]);
const ALWAYS_RESERVED = new Set(["PATH", "HOME", "USERPROFILE", "TMPDIR", "CI"]);

function isReservedEnvVar(name: string): boolean {
if (ALWAYS_RESERVED.has(name)) return true;
if (name.startsWith("RUNNER_")) return true;
if (name.startsWith("GITHUB_")) return !RUNTIME_ENV_ALLOWLIST.has(name);
if (ALWAYS_RESERVED.has(name)) {
return true;
}
if (name.startsWith("RUNNER_")) {
return true;
}
if (name.startsWith("GITHUB_")) {
return !RUNTIME_ENV_ALLOWLIST.has(name);
}
return false;
}

Expand All @@ -109,8 +111,10 @@ function isReservedEnvVar(name: string): boolean {
*/
export function propagateProjectNpmrcAuth(projectDir: string): void {
const npmrcPath = join(projectDir, ".npmrc");
const content = readNpmrc(npmrcPath);
if (content === undefined) return;
const content = readFileIfExists(npmrcPath);
if (content === undefined) {
return;
}

const { envVarRefs } = analyzeProjectNpmrc(content);

Expand All @@ -127,6 +131,6 @@ export function propagateProjectNpmrcAuth(projectDir: string): void {
`Detected project .npmrc at ${npmrcPath}. Propagating auth env vars: ${propagatable.join(", ")}`,
);
for (const name of propagatable) {
exportVariable(name, process.env[name]!);
exportVariable(name, process.env[name]);
}
}
8 changes: 4 additions & 4 deletions src/azure/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { escapeLoggingCommandData } from "./commands.js";
describe("escapeLoggingCommandData", () => {
it("escapes characters that could terminate logging commands", () => {
expect(escapeLoggingCommandData("plain/path")).toBe("plain/path");
expect(escapeLoggingCommandData("C:\\Users\\dev")).toBe("C:\\Users\\dev");
expect(escapeLoggingCommandData(String.raw`C:\Users\dev`)).toBe(String.raw`C:\Users\dev`);
expect(escapeLoggingCommandData("a%b")).toBe("a%AZP25b");
expect(escapeLoggingCommandData("a;b")).toBe("a%3Bb");
expect(escapeLoggingCommandData("a]b")).toBe("a%5Db");
Expand All @@ -17,12 +17,12 @@ describe("escapeLoggingCommandData", () => {
describe("Azure logging commands", () => {
it("renders prependpath and setvariable commands", async () => {
const { prependPath, setVariable } = await import("./commands.js");
const stdout: string[] = [];
const stdout: Array<string> = [];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = ((chunk: string | Uint8Array) => {
process.stdout.write = (chunk: string | Uint8Array) => {
stdout.push(String(chunk));
return true;
}) as typeof process.stdout.write;
};

try {
prependPath("/tmp/vp/bin");
Expand Down
12 changes: 9 additions & 3 deletions src/azure/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,15 @@ export function setVariable(
options: { isOutput?: boolean; isReadonly?: boolean; isSecret?: boolean } = {},
): void {
const parts = [`variable=${name}`];
if (options.isOutput) parts.push("isOutput=true");
if (options.isReadonly) parts.push("isReadonly=true");
if (options.isSecret) parts.push("issecret=true");
if (options.isOutput) {
parts.push("isOutput=true");
}
if (options.isReadonly) {
parts.push("isReadonly=true");
}
if (options.isSecret) {
parts.push("issecret=true");
}
process.stdout.write(
`##vso[task.setvariable ${parts.join(";")}]${escapeLoggingCommandData(value)}\n`,
);
Expand Down
4 changes: 2 additions & 2 deletions src/azure/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe("Azure lifecycle", () => {
expect(run).toHaveBeenCalledWith("vp", ["env", "use", "22.23.1"], { cwd: process.cwd() });
});
it("runs prepare in install → cache order", async () => {
const calls: string[] = [];
const calls: Array<string> = [];
await runPrepare(
{
SETUP_VP_VERSION: "latest",
Expand Down Expand Up @@ -70,7 +70,7 @@ describe("Azure lifecycle", () => {
});

it("runs finalize in auth → sfw → install → version order", async () => {
const calls: string[] = [];
const calls: Array<string> = [];
await runFinalize(
{
SETUP_VP_RUN_INSTALL: "true",
Expand Down
44 changes: 24 additions & 20 deletions src/azure/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mkdirSync } from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { fail, matchesEntrypoint } from "../ci/entrypoint.js";
import { packageManagerArgs } from "../ci/package-manager.js";
import { createVersionResolver } from "../ci/version-file.js";
import { createNodeVersionResolver } from "../ci/node-version-file.js";
Expand Down Expand Up @@ -55,11 +55,6 @@ const defaultPorts: AzurePorts = {
logInfo,
};

function fail(message: string): never {
console.error(`setup-vp: ${message}`);
process.exit(1);
}

export async function runPrepare(
env: NodeJS.ProcessEnv = process.env,
ports: AzurePorts = defaultPorts,
Expand Down Expand Up @@ -134,7 +129,9 @@ export async function runPrepare(
}
}

if (!inputs.cache) return;
if (!inputs.cache) {
return;
}

const metadata = ports.prepareCacheMetadata({
projectDir,
Expand Down Expand Up @@ -171,16 +168,19 @@ export async function runFinalize(
const authVariables = analyzeProjectNpmrc(npmrc).envVarRefs;
authVariables.add("NODE_AUTH_TOKEN");
for (const name of authVariables) {
if (!isReservedAuthVariable(name) && UNEXPANDED_MACRO_RE.test(env[name] || ""))
if (!isReservedAuthVariable(name) && UNEXPANDED_MACRO_RE.test(env[name] || "")) {
delete env[name];
}
}

ports.configureAuth(
inputs.registryUrl,
inputs.scope,
env,
(name, value) => {
if (name === "NODE_AUTH_TOKEN" || value === undefined) return;
if (name === "NODE_AUTH_TOKEN" || value === undefined) {
return;
}
ports.setVariable(name, value, {
isSecret: name !== "NPM_CONFIG_USERCONFIG" && name !== "PNPM_CONFIG_USERCONFIG",
});
Expand All @@ -195,20 +195,26 @@ export async function runFinalize(
vitePlusVersion: env.SETUP_VP_RESOLVED_VERSION || inputs.version,
logWarning: ports.logWarning,
exportVariable: (name, value) => {
if (value === undefined) return;
if (name === "PATH") ports.prependPath(value.split(path.delimiter)[0]!);
else ports.setVariable(name, value);
if (value === undefined) {
return;
}
if (name === "PATH") {
ports.prependPath(value.split(path.delimiter)[0]);
} else {
ports.setVariable(name, value);
}
},
});
if (runInstallEntries.length > 0) {
await ports.runInstall(runInstallEntries, projectDir, installCommand, env);
}

const versionOutput = ports.getCommandOutput("vp", ["--version"], { cwd: projectDir });
if (!versionOutput)
if (!versionOutput) {
throw new Error(
"Failed to verify Vite+ installation: vp --version failed or returned no output.",
);
}
ports.logInfo(versionOutput);
const installedVersion = ports.parseInstalledVpVersion(versionOutput);
ports.setVariable("SETUP_VP_INSTALLED_VERSION", installedVersion);
Expand All @@ -228,7 +234,7 @@ export async function runFinalize(
ports.setVariable("packageManagerVersion", current.packageManagerVersion, { isOutput: true });
}

export async function main(phase: AzurePhase): Promise<void> {
export async function main(phase: string): Promise<void> {
if (phase === "prepare") {
await runPrepare();
return;
Expand All @@ -241,15 +247,13 @@ export async function main(phase: AzurePhase): Promise<void> {
}

export function isEntrypoint(argvPath = process.argv[1], moduleUrl = import.meta.url): boolean {
return Boolean(argvPath && moduleUrl === pathToFileURL(path.resolve(argvPath)).href);
return matchesEntrypoint(argvPath, moduleUrl);
}

if (isEntrypoint()) {
const phase = process.argv[2];
if (!phase) fail('missing phase argument; expected "prepare" or "finalize"');
try {
await main(phase as AzurePhase);
} catch (error) {
fail(error instanceof Error ? error.message : String(error));
if (!phase) {
fail('missing phase argument; expected "prepare" or "finalize"');
}
await main(phase).catch(fail);
}
6 changes: 4 additions & 2 deletions src/azure/inputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe("parseAzureInputs", () => {
});

describe("resolveProjectDirFromInputs", () => {
const tempDirs: string[] = [];
const tempDirs: Array<string> = [];

it("resolves workingDirectory against the Azure workspace root", () => {
const root = mkdtempSync(path.join(tmpdir(), "setup-vp-azure-"));
Expand All @@ -71,6 +71,8 @@ describe("resolveProjectDirFromInputs", () => {
});

expect(projectDir).toBe(child);
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
});
Loading
Loading