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
3 changes: 3 additions & 0 deletions packages/cli/script/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
requireAliasPlugin,
} from "./lib/require-alias-plugin.js";
import { buildSplitBundle } from "./lib/split-bundle.js";
import { umdRequirePlugin } from "./lib/umd-require-plugin.js";
import { zodEnglishLocalesPlugin } from "./lib/zod-locales-plugin.js";
import { zodV3StubPlugin } from "./lib/zod-v3-stub-plugin.js";
import { textImportPlugin } from "./text-import-plugin.js";
Expand Down Expand Up @@ -202,6 +203,8 @@ const BUNDLE_OPTIONS = {
zodV3StubPlugin,
// `_require()` → `require()`, so esbuild bundles the lazy requires
requireAliasPlugin,
// `function (require, …)` UMD factories (simple-plist) → bundled requires
umdRequirePlugin,
],
} satisfies BuildOptions;

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/script/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
requireAliasPlugin,
} from "./lib/require-alias-plugin.js";
import { buildSplitBundle, removeBundleOutputs } from "./lib/split-bundle.js";
import { umdRequirePlugin } from "./lib/umd-require-plugin.js";
import { zodEnglishLocalesPlugin } from "./lib/zod-locales-plugin.js";
import { zodV3StubPlugin } from "./lib/zod-v3-stub-plugin.js";
import { buildCoreDeclarations, SDK_TYPES_PATH } from "./sdk-declarations.js";
Expand Down Expand Up @@ -106,6 +107,7 @@ const plugins: Plugin[] = [
zodV3StubPlugin,
textImportPlugin,
requireAliasPlugin,
umdRequirePlugin,
];

if (process.env["SENTRY_AUTH_TOKEN"]) {
Expand Down
48 changes: 48 additions & 0 deletions packages/cli/script/lib/umd-require-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* esbuild plugin that lets esbuild bundle the `require()` calls inside
* TypeScript-emitted UMD modules.
*
* `simple-plist` (a dependency of `xcode`, which the Apple and React Native
* wizards import) wraps each file in a UMD factory that receives `require`
* as a parameter: `factory(require, exports)`, then
* `function (require, exports) { require("bplist-creator") }`. esbuild only
* resolves calls to the free `require`, so it leaves these as runtime
* `require()` calls. The npm package ships no dependencies and the
* single-file binary can only `require` built-ins, so both crashed with
* "Cannot find module 'bplist-creator'" as soon as the wizard started.
*
* Renaming the factory's parameter makes the calls inside refer to the
* module's own `require`, which esbuild resolves and bundles. A file that
* matches the filter but no longer has the UMD header fails the build, so a
* dependency upgrade can't silently bring the crash back.
*
* Shared by the CLI bundles (`script/bundle.ts`, `script/build.ts`).
*/

import { readFile } from "node:fs/promises";
import type { Plugin } from "esbuild";

/** Files that use the TypeScript UMD wrapper with a `require` parameter. */
export const UMD_REQUIRE_FILTER =
/[\\/]node_modules[\\/]simple-plist[\\/]dist[\\/][^\\/]+\.js$/;

/** TypeScript's UMD factory signature, with or without the `exports` param. */
const UMD_FACTORY_RE = /\(function \(require(?=[,)])/;

export const umdRequirePlugin: Plugin = {
name: "umd-require",
setup(build) {
build.onLoad({ filter: UMD_REQUIRE_FILTER }, async (args) => {
const source = await readFile(args.path, "utf-8");
if (!UMD_FACTORY_RE.test(source)) {
throw new Error(
`umd-require: ${args.path} no longer has a UMD factory with a \`require\` parameter. Update UMD_REQUIRE_FILTER in script/lib/umd-require-plugin.ts.`,
);
}
return {
contents: source.replace(UMD_FACTORY_RE, "(function (_umdRequire"),
loader: "js",
};
});
},
};
45 changes: 43 additions & 2 deletions packages/cli/test/e2e/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

import { spawn } from "node:child_process";
import { existsSync, readdirSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { beforeAll, describe, expect, test } from "vitest";
import { hasWizardRunner, INTEGRATION_IDS } from "../../src/lib/wizard/run.js";
import { BUNDLE_BIN_PATH, ensureBundleBuilt } from "./bundle-setup.js";

function noop(): void {
Expand All @@ -20,14 +22,17 @@ function noop(): void {
async function spawnCollect(
cmd: string,
args: string[],
opts?: { cwd?: string; env?: NodeJS.ProcessEnv },
opts?: { cwd?: string; env?: NodeJS.ProcessEnv; closeStdin?: boolean },
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const proc = spawn(cmd, args, {
cwd: opts?.cwd,
env: opts?.env,
stdio: ["pipe", "pipe", "pipe"],
});
proc.on("error", noop);
if (opts?.closeStdin) {
proc.stdin.end();
}

let stdout = "";
let stderr = "";
Expand Down Expand Up @@ -261,4 +266,40 @@ describe("npm bundle", () => {
// Not every command: well under half of the CLI's chunks
expect(readChunks.length).toBeLessThan(chunks.length / 2);
}, 15_000);

// Each wizard is a lazy chunk, and a dependency that esbuild leaves as a
// runtime require() only fails once that chunk loads. `xcode` → `simple-plist`
// left `require("bplist-creator")` unbundled, so `reactNative` and `ios`
// crashed on start while `--version` and unit tests (run from source) passed.
test.each(INTEGRATION_IDS.filter(hasWizardRunner))(
"wizard %s starts without missing modules",
async (integration) => {
// An empty directory, and no terminal: the wizard shows its intro,
// then stops at the first question. Spotlight skips the Sentry login.
const cwd = await mkdtemp(join(tmpdir(), "sentry-wizard-smoke-"));
try {
const { stdout, stderr } = await spawnCollect(
"node",
[BUNDLE_BIN_PATH, "wizard", integration],
{
cwd,
closeStdin: true,
env: {
...process.env,
SENTRY_SPOTLIGHT: "1",
SENTRY_CLI_NO_TELEMETRY: "1",
},
},
);
const output = stdout + stderr;
expect(output).not.toContain("Cannot find module");
expect(output).not.toContain("MODULE_NOT_FOUND");
expect(output).not.toContain("ERR_UNKNOWN_BUILTIN_MODULE");
expect(output).toMatch(/Sentry .*Wizard/);
} finally {
await rm(cwd, { recursive: true, force: true });
}
},
15_000,
);
});
66 changes: 66 additions & 0 deletions packages/cli/test/script/umd-require-plugin.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* Tests for the esbuild plugin that bundles the `require()` calls inside
* `simple-plist`'s UMD factories.
*
* Bundles `xcode` (which the Apple and React Native wizards import) the way
* the CLI does, writes it outside any `node_modules`, and loads it, as the
* npm package and the single-file binary do.
*/

import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { build, type Plugin } from "esbuild";
import { afterAll, describe, expect, test } from "vitest";
import { umdRequirePlugin } from "../../script/lib/umd-require-plugin.js";

const require = createRequire(import.meta.url);
const CLI_DIR = join(dirname(fileURLToPath(import.meta.url)), "../..");

const outDir = mkdtempSync(join(tmpdir(), "umd-require-"));
afterAll(() => rmSync(outDir, { recursive: true, force: true }));

/** Bundle `require("xcode")` with `plugins` and return the output path. */
async function bundleXcode(
name: string,
plugins: Plugin[],
): Promise<{ file: string; inputs: string[] }> {
const result = await build({
stdin: {
contents: 'module.exports = require("xcode");',
resolveDir: CLI_DIR,
loader: "js",
},
bundle: true,
write: false,
platform: "node",
format: "cjs",
metafile: true,
logLevel: "silent",
plugins,
});
const file = join(outDir, `${name}.cjs`);
writeFileSync(file, result.outputFiles[0]?.text ?? "");
return { file, inputs: Object.keys(result.metafile.inputs) };
}

describe("umdRequirePlugin", () => {
test("bundles simple-plist's dependencies, so xcode loads standalone", async () => {
const { file, inputs } = await bundleXcode("with-plugin", [
umdRequirePlugin,
]);

expect(inputs.some((input) => input.includes("bplist-creator"))).toBe(true);
expect(inputs.some((input) => input.includes("bplist-parser"))).toBe(true);
const xcode = require(file) as { project: unknown };
expect(typeof xcode.project).toBe("function");
});

test("without it, xcode fails to load standalone", async () => {
const { file } = await bundleXcode("without-plugin", []);

expect(() => require(file)).toThrow(/Cannot find module/);
});
});
Loading