Skip to content

Commit

Permalink
fix: disallow imports in _worker.js (cloudflare#1629)
Browse files Browse the repository at this point in the history
* fix: disallow imports in _worker.js

Fixes: cloudflare#1214

This does not actually prevent the user from importing things (could be modified to do so)

It currently just logs an error to console.

* chore: prettier

* draft: start to add tests

* apply changes

* Update packages/wrangler/src/pages/dev.tsx

Co-authored-by: Greg Brimble <[email protected]>

* mark test as todo

Co-authored-by: Greg Brimble <[email protected]>
  • Loading branch information
Skye-31 and GregBrimble authored Aug 8, 2022
1 parent f1c97c8 commit 06915ff
Show file tree
Hide file tree
Showing 8 changed files with 175 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/rotten-timers-do.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

fix: disallow imports in \_worker.js (https://github.com/cloudflare/wrangler2/issues/1214)
33 changes: 33 additions & 0 deletions fixtures/pages-workerjs-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "pages-workerjs-app",
"version": "0.0.0",
"private": true,
"sideEffects": false,
"scripts": {
"dev": "npx wrangler pages dev ./workerjs-test --port 8792",
"test": "npx jest --forceExit --verbose",
"test:ci": "npx jest --forceExit"
},
"jest": {
"restoreMocks": true,
"testRegex": ".*.(test|spec)\\.[jt]sx?$",
"testTimeout": 30000,
"transform": {
"^.+\\.c?(t|j)sx?$": [
"esbuild-jest",
{
"sourcemap": true
}
]
},
"transformIgnorePatterns": [
"node_modules/(?!find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
]
},
"devDependencies": {
"undici": "^5.5.1"
},
"engines": {
"node": ">=14"
}
}
69 changes: 69 additions & 0 deletions fixtures/pages-workerjs-app/tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { spawn } from "child_process";
import * as path from "path";
import patchConsole from "patch-console";
import { fetch } from "undici";
// import { mockConsoleMethods } from "../../../packages/wrangler/src/__tests__/helpers/mock-console";
import type { ChildProcess } from "child_process";
import type { Response } from "undici";

const waitUntilReady = async (url: string): Promise<Response> => {
let response: Response | undefined = undefined;

while (response === undefined) {
await new Promise((resolvePromise) => setTimeout(resolvePromise, 500));

try {
response = await fetch(url);
} catch (err) {}
}

return response as Response;
};

const isWindows = process.platform === "win32";

describe("Pages _worker.js", () => {
let wranglerProcess: ChildProcess;

// const std = mockConsoleMethods();
beforeEach(() => {
wranglerProcess = spawn("npm", ["run", "dev"], {
shell: isWindows,
cwd: path.resolve(__dirname, "../"),
env: { BROWSER: "none", ...process.env },
});
wranglerProcess.stdout?.on("data", (chunk) => {
console.log(chunk.toString());
});
wranglerProcess.stderr?.on("data", (chunk) => {
console.log(chunk.toString());
});
});

afterEach(async () => {
patchConsole(() => {});

await new Promise((resolve, reject) => {
wranglerProcess.once("exit", (code) => {
if (!code) {
resolve(code);
} else {
reject(code);
}
});
wranglerProcess.kill("SIGTERM");
});
});

it("renders static pages", async () => {
const response = await waitUntilReady("http://127.0.0.1:8792/");
const text = await response.text();
expect(text).toContain("test");
});

it.todo("shows an error for the import in _worker.js");
// it("shows an error for the import in _worker.js", async () => {
// const _ = await waitUntilReady("http://127.0.0.1:8792/");
// expect(std.err).toMatchInlineSnapshot(`""`);
// });
});
10 changes: 10 additions & 0 deletions fixtures/pages-workerjs-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ES2020",
"esModuleInterop": true,
"module": "CommonJS",
"lib": ["ES2020"],
"types": ["jest"],
"moduleResolution": "node"
}
}
7 changes: 7 additions & 0 deletions fixtures/pages-workerjs-app/workerjs-test/_worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import text from "./other-script";

export default {
async fetch() {
return new Response(text);
},
};
1 change: 1 addition & 0 deletions fixtures/pages-workerjs-app/workerjs-test/other-script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default "test";
19 changes: 19 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions packages/wrangler/src/pages/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { watch } from "chokidar";
import { build as workerJsBuild } from "esbuild";
import { unstable_dev } from "../api";
import { FatalError } from "../errors";
import { logger } from "../logger";
import * as metrics from "../metrics";
import { buildFunctions } from "./build";
import { SECONDS_TO_WAIT_FOR_PROXY } from "./constants";
import { CLEANUP, CLEANUP_CALLBACKS, pagesBetaWarning } from "./utils";
import type { Plugin } from "esbuild";
import type { ArgumentsCamelCase, Argv } from "yargs";

type PagesDevArgs = {
Expand Down Expand Up @@ -228,6 +230,23 @@ export const Handler = async ({
if (!existsSync(scriptPath)) {
logger.log("No functions. Shimming...");
scriptPath = resolve(__dirname, "../templates/pages-shim.ts");
} else {
const runBuild = async () => {
try {
await workerJsBuild({
entryPoints: [scriptPath],
write: false,
plugins: [blockWorkerJsImports],
});
} catch {}
};
await runBuild();
watch([scriptPath], {
persistent: true,
ignoreInitial: true,
}).on("all", async () => {
await runBuild();
});
}
}

Expand Down Expand Up @@ -431,3 +450,15 @@ async function spawnProxyProcess({

return port;
}

const blockWorkerJsImports: Plugin = {
name: "block-worker-js-imports",
setup(build) {
build.onResolve({ filter: /.*/g }, (_args) => {
logger.error(
`_worker.js is importing from another file. This will throw an error if deployed.\nYou should bundle your Worker or remove the import if it is unused.`
);
return null;
});
},
};

0 comments on commit 06915ff

Please sign in to comment.