New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

wrangler

Package Overview
Dependencies
Maintainers
1
Versions
4355
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

wrangler - npm Package Compare versions

Comparing version

to
0.0.0-1b2aa916f

config-schema.json

125

bin/wrangler.js
#!/usr/bin/env node
const { spawn } = require("child_process");
const path = require("path");
const fs = require("fs");
const os = require("os");
const MIN_NODE_VERSION = "16.7.0";
const debug =
process.env["WRANGLER_LOG"] === "debug"
? (...args) => console.log(...args)
: () => {};
const MIN_NODE_VERSION = "18.0.0";

@@ -23,3 +17,3 @@ let wranglerProcess;

console.error(
`Wrangler requires at least node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}. Please update your version of node.js.
`Wrangler requires at least Node.js v${MIN_NODE_VERSION}. You are using v${process.versions.node}. Please update your version of Node.js.

@@ -32,26 +26,2 @@ Consider using a Node.js version manager such as https://volta.sh/ or https://github.com/nvm-sh/nvm.`

let pathToCACerts = process.env.NODE_EXTRA_CA_CERTS;
if (pathToCACerts) {
// TODO:
// - should we log a warning here?
// - maybe we can generate a certificate that concatenates with ours?
//
// I do think it'll be rare that someone wants to add a cert AND
// use Cloudflare WARP, but let's wait till the situation actually
// arises before we do anything about it
} else {
const osTempDir = os.tmpdir();
const certDir = path.join(osTempDir, "wrangler-cert");
const certPath = path.join(certDir, "Cloudflare_CA.pem");
// copy cert to the system temp dir if needed
if (!fs.existsSync(certPath)) {
fs.mkdirSync(certDir, { recursive: true });
fs.writeFileSync(
certPath,
fs.readFileSync(path.join(__dirname, "../Cloudflare_CA.pem"), "utf-8")
);
}
pathToCACerts = certPath;
}
return spawn(

@@ -67,73 +37,20 @@ process.execPath,

{
stdio: "inherit",
env: {
...process.env,
NODE_EXTRA_CA_CERTS: pathToCACerts,
},
stdio: ["inherit", "inherit", "inherit", "ipc"],
}
).on("exit", (code) =>
process.exit(code === undefined || code === null ? 0 : code)
);
}
/**
* Runs a locally-installed version of wrangler, delegating from this version.
* @throws {MODULE_NOT_FOUND} if there isn't a locally installed version of wrangler.
*/
function runDelegatedWrangler() {
const packageJsonPath = require.resolve("wrangler/package.json", {
paths: [process.cwd()],
});
const {
bin: { wrangler: binaryPath },
version,
} = JSON.parse(fs.readFileSync(packageJsonPath));
const resolvedBinaryPath = path.resolve(packageJsonPath, "..", binaryPath);
debug(`Delegating to locally-installed version of wrangler @ v${version}`);
// this call to `spawn` is simpler because the delegated version will do all
// of the other work.
return spawn(
process.execPath,
[resolvedBinaryPath, ...process.argv.slice(2)],
{
stdio: "inherit",
}
).on("exit", (code) =>
process.exit(code === undefined || code === null ? 0 : code)
);
}
/**
* Indicates if this invocation of `wrangler` should delegate
* to a locally-installed version.
*/
function shouldDelegate() {
try {
// `require.resolve` will throw if it can't find
// a locally-installed version of `wrangler`
const delegatedPackageJson = require.resolve("wrangler/package.json", {
paths: [process.cwd()],
)
.on("exit", (code) =>
process.exit(code === undefined || code === null ? 0 : code)
)
.on("message", (message) => {
if (process.send) {
process.send(message);
}
})
.on("disconnect", () => {
if (process.disconnect) {
process.disconnect();
}
});
const thisPackageJson = path.resolve(__dirname, "..", "package.json");
// if it's the same path, then we're already a local install -- no need to delegate
return thisPackageJson !== delegatedPackageJson;
} catch (e) {
// there's no local version to delegate to -- `require.resolve` threw
return false;
}
}
async function main() {
wranglerProcess = shouldDelegate() ? runDelegatedWrangler() : runWrangler();
}
process.on("SIGINT", () => {
wranglerProcess && wranglerProcess.kill();
});
process.on("SIGTERM", () => {
wranglerProcess && wranglerProcess.kill();
});
// semiver implementation via https://github.com/lukeed/semiver/blob/ae7eebe6053c96be63032b14fb0b68e2553fcac4/src/index.js

@@ -171,2 +88,10 @@

void main();
if (module === require.main) {
wranglerProcess = runWrangler();
process.on("SIGINT", () => {
wranglerProcess && wranglerProcess.kill();
});
process.on("SIGTERM", () => {
wranglerProcess && wranglerProcess.kill();
});
}

354

package.json
{
"name": "wrangler",
"version": "0.0.0-1b232aaf",
"description": "Command-line interface for all things Cloudflare Workers",
"keywords": [
"wrangler",
"cloudflare",
"workers",
"cloudflare workers",
"edge",
"compute",
"serverless",
"serverless application",
"serverless module",
"wasm",
"web",
"assembly",
"webassembly",
"rust",
"emscripten",
"typescript",
"graphql",
"router",
"http",
"cli"
],
"homepage": "https://github.com/cloudflare/wrangler2#readme",
"bugs": {
"url": "https://github.com/cloudflare/wrangler2/issues"
},
"license": "MIT OR Apache-2.0",
"author": "wrangler@cloudflare.com",
"main": "wrangler-dist/cli.js",
"types": "wrangler-dist/cli.d.ts",
"bin": {
"wrangler": "./bin/wrangler.js",
"wrangler2": "./bin/wrangler.js"
},
"files": [
"src",
"bin",
"miniflare-config-stubs",
"miniflare-dist",
"wrangler-dist",
"templates",
"vendor",
"import_meta_url.js",
"kv-asset-handler.js",
"Cloudflare_CA.pem"
],
"scripts": {
"build": "npm run clean && npm run bundle && npm run emit-types",
"bundle": "node -r esbuild-register scripts/bundle.ts",
"check:type": "tsc",
"clean": "rm -rf wrangler-dist miniflare-dist emitted-types",
"dev": "npm run clean && concurrently -c black,blue --kill-others-on-fail false 'npm run bundle -- --watch' 'npm run check:type -- --watch --preserveWatchOutput'",
"emit-types": "tsc -p tsconfig.emit.json && node -r esbuild-register scripts/emit-types.ts",
"prepublishOnly": "SOURCEMAPS=false npm run build",
"start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
"test": "jest --silent=false --verbose=true",
"test-watch": "npm run test -- --runInBand --testTimeout=50000 --watch",
"test:ci": "npm run test -- --verbose=true --coverage"
},
"jest": {
"coverageReporters": [
"json",
"html",
"text",
"cobertura"
],
"moduleNameMapper": {
"clipboardy": "<rootDir>/src/__tests__/helpers/clipboardy-mock.js",
"miniflare/cli": "<rootDir>/../../node_modules/miniflare/dist/src/cli.js"
},
"restoreMocks": true,
"setupFilesAfterEnv": [
"<rootDir>/src/__tests__/jest.setup.ts"
],
"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|p-timeout|p-queue|yocto-queue|path-exists|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream|get-port|supports-color|pretty-bytes)"
]
},
"dependencies": {
"@cloudflare/kv-asset-handler": "^0.2.0",
"@esbuild-plugins/node-globals-polyfill": "^0.1.1",
"@esbuild-plugins/node-modules-polyfill": "^0.1.4",
"blake3-wasm": "^2.1.5",
"chokidar": "^3.5.3",
"esbuild": "0.14.51",
"miniflare": "^2.6.0",
"nanoid": "^3.3.3",
"path-to-regexp": "^6.2.0",
"selfsigned": "^2.0.1",
"source-map": "^0.7.4",
"xxhash-wasm": "^1.0.1"
},
"devDependencies": {
"@iarna/toml": "^3.0.0",
"@microsoft/api-extractor": "^7.28.3",
"@types/command-exists": "^1.2.0",
"@types/express": "^4.17.13",
"@types/glob-to-regexp": "0.4.1",
"@types/mime": "^2.0.3",
"@types/prompts": "^2.0.14",
"@types/react": "^17.0.37",
"@types/serve-static": "^1.13.10",
"@types/signal-exit": "^3.0.1",
"@types/supports-color": "^8.1.1",
"@types/ws": "^8.5.3",
"@types/yargs": "^17.0.10",
"@webcontainer/env": "^1.0.1",
"body-parser": "^1.20.0",
"clipboardy": "^3.0.0",
"cmd-shim": "^4.1.0",
"command-exists": "^1.2.9",
"concurrently": "^7.2.2",
"create-cloudflare": "^1.0.0",
"devtools-protocol": "^0.0.955664",
"dotenv": "^16.0.0",
"execa": "^6.1.0",
"express": "^4.18.1",
"faye-websocket": "^0.11.4",
"finalhandler": "^1.2.0",
"find-up": "^6.3.0",
"get-port": "^6.1.2",
"glob-to-regexp": "0.4.1",
"http-terminator": "^3.2.0",
"ignore": "^5.2.0",
"ink": "^3.2.0",
"ink-select-input": "^4.2.1",
"ink-spinner": "^4.0.3",
"ink-table": "^3.0.0",
"ink-testing-library": "^2.1.0",
"ink-text-input": "^4.0.3",
"is-ci": "^3.0.1",
"jest-fetch-mock": "^3.0.3",
"jest-websocket-mock": "^2.3.0",
"mime": "^3.0.0",
"open": "^8.4.0",
"p-queue": "^7.2.0",
"pretty-bytes": "^6.0.0",
"prompts": "^2.4.2",
"react": "^17.0.2",
"react-error-boundary": "^3.1.4",
"serve-static": "^1.15.0",
"signal-exit": "^3.0.7",
"supports-color": "^9.2.2",
"timeago.js": "^4.0.2",
"tmp-promise": "^3.0.3",
"ts-dedent": "^2.2.0",
"undici": "^5.5.1",
"update-check": "^1.5.4",
"ws": "^8.5.0",
"xdg-app-paths": "^7.3.0",
"yargs": "^17.4.1"
},
"optionalDependencies": {
"fsevents": "~2.3.2"
},
"engines": {
"node": ">=16.7.0"
}
}
"name": "wrangler",
"version": "0.0.0-1b2aa916f",
"description": "Command-line interface for all things Cloudflare Workers",
"keywords": [
"wrangler",
"cloudflare",
"workers",
"cloudflare workers",
"edge",
"compute",
"serverless",
"serverless application",
"serverless module",
"wasm",
"web",
"assembly",
"webassembly",
"rust",
"emscripten",
"typescript",
"graphql",
"router",
"http",
"cli"
],
"homepage": "https://github.com/cloudflare/workers-sdk#readme",
"bugs": {
"url": "https://github.com/cloudflare/workers-sdk/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/cloudflare/workers-sdk.git",
"directory": "packages/wrangler"
},
"license": "MIT OR Apache-2.0",
"author": "wrangler@cloudflare.com",
"main": "wrangler-dist/cli.js",
"types": "wrangler-dist/cli.d.ts",
"bin": {
"wrangler": "./bin/wrangler.js",
"wrangler2": "./bin/wrangler.js"
},
"files": [
"bin",
"miniflare-dist",
"wrangler-dist",
"templates",
"kv-asset-handler.js",
"config-schema.json"
],
"dependencies": {
"@cloudflare/unenv-preset": "2.0.2",
"blake3-wasm": "2.1.5",
"esbuild": "0.24.2",
"path-to-regexp": "6.3.0",
"unenv": "2.0.0-rc.14",
"workerd": "1.20250310.0",
"miniflare": "0.0.0-1b2aa916f",
"@cloudflare/kv-asset-handler": "0.4.0"
},
"devDependencies": {
"@aws-sdk/client-s3": "^3.721.0",
"@cloudflare/types": "6.18.4",
"@cloudflare/workers-types": "^4.20250310.0",
"@cspotcode/source-map-support": "0.8.1",
"@iarna/toml": "^3.0.0",
"@microsoft/api-extractor": "^7.47.0",
"@sentry/node": "^7.86.0",
"@sentry/types": "^7.86.0",
"@sentry/utils": "^7.86.0",
"@types/command-exists": "^1.2.0",
"@types/glob-to-regexp": "^0.4.1",
"@types/is-ci": "^3.0.0",
"@types/javascript-time-ago": "^2.0.3",
"@types/mime": "^3.0.4",
"@types/minimatch": "^5.1.2",
"@types/node": "^18.19.75",
"@types/node-forge": "^1.3.11",
"@types/prompts": "^2.0.14",
"@types/resolve": "^1.20.6",
"@types/shell-quote": "^1.7.2",
"@types/signal-exit": "^3.0.1",
"@types/supports-color": "^8.1.1",
"@types/ws": "^8.5.7",
"@types/yargs": "^17.0.22",
"@vitest/ui": "~3.0.5",
"@webcontainer/env": "^1.1.0",
"chalk": "^5.2.0",
"chokidar": "^4.0.1",
"cli-table3": "^0.6.3",
"cmd-shim": "^4.1.0",
"command-exists": "^1.2.9",
"concurrently": "^8.2.2",
"date-fns": "^4.1.0",
"devtools-protocol": "^0.0.1182435",
"dotenv": "^16.3.1",
"execa": "^6.1.0",
"find-up": "^6.3.0",
"get-port": "^7.0.0",
"glob-to-regexp": "^0.4.1",
"https-proxy-agent": "7.0.2",
"is-ci": "^3.0.1",
"itty-time": "^1.0.6",
"javascript-time-ago": "^2.5.4",
"md5-file": "5.0.0",
"mime": "^3.0.0",
"minimatch": "^5.1.0",
"mock-socket": "^9.3.1",
"msw": "2.4.3",
"node-forge": "^1.3.1",
"open": "^8.4.0",
"p-queue": "^7.2.0",
"patch-console": "^1.0.0",
"pretty-bytes": "^6.0.0",
"prompts": "^2.4.2",
"resolve": "^1.22.8",
"rimraf": "^5.0.10",
"selfsigned": "^2.0.1",
"semiver": "^1.1.0",
"shell-quote": "^1.8.1",
"signal-exit": "^3.0.7",
"source-map": "^0.6.1",
"strip-ansi": "^7.1.0",
"supports-color": "^9.2.2",
"timeago.js": "^4.0.2",
"ts-dedent": "^2.2.0",
"ts-json-schema-generator": "^1.5.0",
"typescript": "^5.7.2",
"undici": "^5.28.5",
"update-check": "^1.5.4",
"vitest": "~3.0.5",
"vitest-websocket-mock": "^0.4.0",
"ws": "8.18.0",
"xdg-app-paths": "^8.3.0",
"xxhash-wasm": "^1.0.1",
"yargs": "^17.7.2",
"@cloudflare/cli": "1.1.1",
"@cloudflare/pages-shared": "^0.13.14",
"@cloudflare/workers-shared": "0.0.0-1b2aa916f",
"@cloudflare/workers-tsconfig": "0.0.0",
"@cloudflare/eslint-config-worker": "1.1.0"
},
"peerDependencies": {
"@cloudflare/workers-types": "^4.20250310.0"
},
"peerDependenciesMeta": {
"@cloudflare/workers-types": {
"optional": true
}
},
"optionalDependencies": {
"fsevents": "~2.3.2",
"sharp": "^0.33.5"
},
"engines": {
"node": ">=18.0.0"
},
"volta": {
"extends": "../../package.json"
},
"workers-sdk": {
"prerelease": true
},
"scripts": {
"assert-git-version": "node -r esbuild-register scripts/assert-git-version.ts",
"build": "pnpm run clean && pnpm run bundle && pnpm run emit-types && pnpm run generate-json-schema",
"bundle": "node -r esbuild-register scripts/bundle.ts",
"check:lint": "eslint . --max-warnings=0",
"check:type": "tsc -p ./tsconfig.json && tsc -p ./templates/tsconfig.json",
"clean": "rimraf wrangler-dist miniflare-dist emitted-types",
"dev": "pnpm run clean && concurrently -c black,blue --kill-others-on-fail false \"pnpm run bundle --watch\" \"pnpm run check:type --watch --preserveWatchOutput\"",
"emit-types": "tsc -p tsconfig.emit.json && node -r esbuild-register scripts/emit-types.ts",
"generate-json-schema": "pnpm exec ts-json-schema-generator --no-type-check --path src/config/config.ts --type RawConfig --out config-schema.json",
"start": "pnpm run bundle && cross-env NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
"test": "dotenv -- pnpm run assert-git-version && dotenv -- vitest",
"test:ci": "pnpm run test run",
"test:debug": "pnpm run test --silent=false --verbose=true",
"test:e2e": "dotenv -- vitest -c ./e2e/vitest.config.mts",
"test:watch": "pnpm run test --testTimeout=50000 --watch",
"type:tests": "tsc -p ./src/__tests__/tsconfig.json && tsc -p ./e2e/tsconfig.json"
}
}
<h1 align="center"> ⛅️ wrangler </h1>
<section align="center" id="shieldio-badges">
<a href="https://www.npmjs.com/package/wrangler"><img alt="npm" src="https://img.shields.io/npm/dw/wrangler?style=flat-square"></a>
<img alt="GitHub contributors" src="https://img.shields.io/github/contributors/cloudflare/wrangler2?style=flat-square">
<img alt="GitHub commit activity (branch)" src="https://img.shields.io/github/commit-activity/w/cloudflare/wrangler2/main?style=flat-square">
<a href="https://discord.gg/CloudflareDev"><img alt="Discord" src="https://img.shields.io/discord/595317990191398933?color=%23F48120&style=flat-square"></a>
<img alt="GitHub contributors" src="https://img.shields.io/github/contributors/cloudflare/workers-sdk?style=flat-square">
<img alt="GitHub commit activity (branch)" src="https://img.shields.io/github/commit-activity/w/cloudflare/workers-sdk/main?style=flat-square">
<a href="https://discord.cloudflare.com"><img alt="Discord" src="https://img.shields.io/discord/595317990191398933?color=%23F48120&style=flat-square"></a>
</section>
> This package is for wrangler v2.x, released first in May 2022. If you're looking for v1.x of the `@cloudflare/wrangler` package, visit https://www.npmjs.com/package/@cloudflare/wrangler / https://github.com/cloudflare/wrangler.
`wrangler` is a command line tool for building [Cloudflare Workers](https://workers.cloudflare.com/).

@@ -15,64 +13,60 @@

To get started quickly with a Hello World worker, run the command below:
```bash
# Make a javascript file
echo "export default { fetch() { return new Response('hello world') } }" > index.js
# try it out
npx wrangler dev index.js
# and then publish it
npx wrangler publish index.js --name my-worker
# visit https://my-worker.<your workers subdomain>.workers.dev
npx wrangler init my-worker -y
```
## Create a Project
For more info, visit our [Getting Started](https://developers.cloudflare.com/workers/get-started/guide/) guide.
```bash
# Generate a new project
npx wrangler init my-worker
# try it out
cd my-worker && npm run start
# and then publish it
npm run deploy
```
<details><summary>Wrangler System Requirements</summary>
## Installation:
We support running the Wrangler CLI with the [Current, Active, and Maintenance](https://nodejs.org/en/about/previous-releases) versions of Node.js. Your Worker will always be executed in `workerd`, the open source Cloudflare Workers runtime.
```bash
$ npm install wrangler --save-dev
```
Wrangler is only supported on macOS 13.5+, Windows 11, and Linux distros that support glib 2.35. This follows [`workerd`'s OS support policy](https://github.com/cloudflare/workerd?tab=readme-ov-file#running-workerd).
## Configuration:
</details>
Wrangler is configured via a `wrangler.toml` file in the project root. When utilizing the `wrangler init` command, a `wrangler.toml` file will be created for you.
## Documentation
example:
For the latest Wrangler documentation, [click here](https://developers.cloudflare.com/workers/wrangler/).
To read more about Workers in general:
- [Getting Started](https://developers.cloudflare.com/workers/get-started/guide/)
- [How Workers works](https://developers.cloudflare.com/workers/reference/how-workers-works/)
- [Observability](https://developers.cloudflare.com/workers/observability/)
- [Platform](https://developers.cloudflare.com/workers/platform/)
## Configuration
Wrangler is configured via a `wrangler.toml` or `wrangler.json` file in the project root. An example configuration generated by `npx wrangler init` or `npx create cloudflare` is as follows:
```toml
main = "./src/index.ts" # init w/ TypeScript
name = "my-worker"
compatibility_date = "YYY-MM-DD"
main = "./src/index.ts"
compatibility_date = "YYYY-MM-DD"
```
for more detailed information about configuration, see the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration)
For more detailed information about configuration, refer to the [documentation](https://developers.cloudflare.com/workers/wrangler/configuration/).
## Commands
### `wrangler init [name]`
### Workers
Creates a Worker project. For details on configuration keys and values, refer to the [documentation](https://developers.cloudflare.com/workers/wrangler/commands/#init).
#### `wrangler dev`
### `wrangler dev`
Start a local development server, with live reloading and devtools.
### `wrangler publish`
#### `wrangler deploy`
Publish the given script to the worldwide Cloudflare network.
Publish the given script to Cloudflare's global network.
For more commands and options, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/commands).
For more commands and options, refer to the [documentation](https://developers.cloudflare.com/workers/wrangler/commands/).
## Pages
### Pages
### `wrangler pages dev [directory] [-- command]`
#### `wrangler pages dev [directory]`
Either serves a static build asset directory, or proxies itself in front of a command.
Serves a static build asset directory.

@@ -82,9 +76,1 @@ Builds and runs functions from a `./functions` directory or uses a `_worker.js` file inside the static build asset directory.

For more commands and options, refer to the [documentation](https://developers.cloudflare.com/pages/platform/functions#develop-and-preview-locally) or run `wrangler pages dev --help`.
## Documentation
For the latest Wrangler documentation, [click here](https://developers.cloudflare.com/workers/wrangler/).
```
```
const urls = new Set();
export function checkedFetch(request, init) {
const url = new URL(
(typeof request === "string" ? new Request(request, init) : request).url
);
function checkURL(request, init) {
const url =
request instanceof URL
? request
: new URL(
(typeof request === "string"
? new Request(request, init)
: request
).url
);
if (url.port && url.port !== "443" && url.protocol === "https:") {

@@ -12,7 +18,14 @@ if (!urls.has(url.toString())) {

`WARNING: known issue with \`fetch()\` requests to custom HTTPS ports in published Workers:\n` +
` - ${url.toString()} - the custom port will be ignored when the Worker is published using the \`wrangler publish\` command.\n`
` - ${url.toString()} - the custom port will be ignored when the Worker is published using the \`wrangler deploy\` command.\n`
);
}
}
return globalThis.fetch(request, init);
}
globalThis.fetch = new Proxy(globalThis.fetch, {
apply(target, thisArg, argArray) {
const [request, init] = argArray;
checkURL(request, init);
return Reflect.apply(target, thisArg, argArray);
},
});

@@ -8,3 +8,3 @@ /**

* - Update the Cron trigger in wrangler.toml (see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers)
* - Run `wrangler publish --name my-worker` to publish your worker
* - Run `wrangler deploy --name my-worker` to deploy your worker
*

@@ -11,0 +11,0 @@ * Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/

@@ -12,5 +12,5 @@ /**

export default {
async fetch(request) {
async fetch(request, env, ctx) {
return new Response("Hello World!");
},
};

@@ -6,3 +6,3 @@ /**

* - Open a browser tab at http://localhost:8787/ to see your worker in action
* - Run `wrangler publish src/index.ts --name my-worker` to publish your worker
* - Run `wrangler deploy src/index.ts --name my-worker` to deploy your worker
*

@@ -21,2 +21,5 @@ * Learn more at https://developers.cloudflare.com/workers/

// MY_BUCKET: R2Bucket;
//
// Example binding to a Service. Learn more at https://developers.cloudflare.com/workers/runtime-apis/service-bindings/
// MY_SERVICE: Fetcher;
}

@@ -23,0 +26,0 @@

// This Worker is used as a default when no Pages Functions are present.
// It proxies the request directly on to the asset server binding.
export default {
export default <ExportedHandler<{ ASSETS: Fetcher }>>{
async fetch(request, env, context) {

@@ -6,0 +6,0 @@ const response = await env.ASSETS.fetch(request.url, request);

import { match } from "path-to-regexp";
//note: this explicitly does not include the * character, as pages requires this
const escapeRegex = /[.+?^${}()|[\]\\]/g;
type HTTPMethod =

@@ -19,2 +22,3 @@ | "HEAD"

waitUntil: (promise: Promise<unknown>) => void;
passThroughOnException: () => void;
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;

@@ -30,2 +34,3 @@ env: Env & { ASSETS: { fetch: typeof fetch } };

waitUntil: (promise: Promise<unknown>) => void;
passThroughOnException: () => void;
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;

@@ -41,3 +46,3 @@ env: Env & { ASSETS: { fetch: typeof fetch } };

P extends string = string,
Data extends Record<string, unknown> = Record<string, unknown>
Data extends Record<string, unknown> = Record<string, unknown>,
> = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;

@@ -49,3 +54,3 @@

Data extends Record<string, unknown> = Record<string, unknown>,
PluginArgs = unknown
PluginArgs = unknown,
> = (

@@ -74,4 +79,9 @@ context: EventPluginContext<Env, P, Data, PluginArgs>

const routeMatcher = match(route.routePath, { end: false });
const mountMatcher = match(route.mountPath, { end: false });
// replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
end: false,
});
const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
end: false,
});
const matchResult = routeMatcher(relativePathname);

@@ -96,4 +106,8 @@ const mountMatchResult = mountMatcher(relativePathname);

const routeMatcher = match(route.routePath, { end: true });
const mountMatcher = match(route.mountPath, { end: false });
const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
end: true,
});
const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
end: false,
});
const matchResult = routeMatcher(relativePathname);

@@ -114,10 +128,12 @@ const mountMatchResult = mountMatcher(relativePathname);

export default function (pluginArgs) {
export default function (pluginArgs: unknown) {
const onRequest: PagesPluginFunction = async (workerContext) => {
let { request } = workerContext;
const { env, next, data } = workerContext;
const { env, next } = workerContext;
let { data } = workerContext;
const url = new URL(request.url);
// TODO: Replace this with something actually legible.
const relativePathname = `/${
url.pathname.split(workerContext.functionPath)[1] || ""
url.pathname.replace(workerContext.functionPath, "") || ""
}`.replace(/^\/\//, "/");

@@ -128,3 +144,7 @@

if (input !== undefined) {
request = new Request(input, init);
let url = input;
if (typeof input === "string") {
url = new URL(input, request.url).toString();
}
request = new Request(url, init);
}

@@ -137,10 +157,21 @@

const context = {
request,
request: new Request(request.clone()),
functionPath: workerContext.functionPath + path,
next: pluginNext,
params,
data,
get data() {
return data;
},
set data(value) {
if (typeof value !== "object" || value === null) {
throw new Error("context.data must be an object");
}
// user has overriden context.data, so we need to merge it with the existing data
data = value;
},
pluginArgs,
env,
waitUntil: workerContext.waitUntil.bind(workerContext),
passThroughOnException:
workerContext.passThroughOnException.bind(workerContext),
};

@@ -150,9 +181,5 @@

// https://fetch.spec.whatwg.org/#null-body-status
return new Response(
[101, 204, 205, 304].includes(response.status) ? null : response.body,
{ ...response, headers: new Headers(response.headers) }
);
return cloneResponse(response);
} else {
return next();
return next(request);
}

@@ -166,1 +193,9 @@ };

}
// This makes a Response mutable
const cloneResponse = (response: Response) =>
// https://fetch.spec.whatwg.org/#null-body-status
new Response(
[101, 204, 205, 304].includes(response.status) ? null : response.body,
response
);
import { match } from "path-to-regexp";
//note: this explicitly does not include the * character, as pages requires this
const escapeRegex = /[.+?^${}()|[\]\\]/g;
type HTTPMethod =

@@ -19,2 +22,3 @@ | "HEAD"

waitUntil: (promise: Promise<unknown>) => void;
passThroughOnException: () => void;
next: (input?: Request | string, init?: RequestInit) => Promise<Response>;

@@ -29,3 +33,3 @@ env: Env & { ASSETS: { fetch: typeof fetch } };

P extends string = string,
Data extends Record<string, unknown> = Record<string, unknown>
Data extends Record<string, unknown> = Record<string, unknown>,
> = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;

@@ -55,2 +59,3 @@ /* end @cloudflare/workers-types */

waitUntil: (promise: Promise<unknown>) => void;
passThroughOnException: () => void;
};

@@ -67,4 +72,9 @@

const routeMatcher = match(route.routePath, { end: false });
const mountMatcher = match(route.mountPath, { end: false });
// replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
end: false,
});
const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
end: false,
});
const matchResult = routeMatcher(requestPath);

@@ -88,5 +98,8 @@ const mountMatchResult = mountMatcher(requestPath);

}
const routeMatcher = match(route.routePath, { end: true });
const mountMatcher = match(route.mountPath, { end: false });
const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
end: true,
});
const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
end: false,
});
const matchResult = routeMatcher(requestPath);

@@ -108,5 +121,12 @@ const mountMatchResult = mountMatcher(requestPath);

export default {
async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
async fetch(
originalRequest: Request,
env: FetchEnv,
workerContext: WorkerContext
) {
let request = originalRequest;
const handlerIterator = executeRequest(request);
const data = {}; // arbitrary data the user can set between functions
let data = {}; // arbitrary data the user can set between functions
let isFailOpen = false;
const next = async (input?: RequestInfo, init?: RequestInit) => {

@@ -130,5 +150,17 @@ if (input !== undefined) {

params,
data,
get data() {
return data;
},
set data(value) {
if (typeof value !== "object" || value === null) {
throw new Error("context.data must be an object");
}
// user has overriden context.data, so we need to merge it with the existing data
data = value;
},
env,
waitUntil: workerContext.waitUntil.bind(workerContext),
passThroughOnException: () => {
isFailOpen = true;
},
};

@@ -155,5 +187,10 @@

try {
return next();
} catch (err) {
return new Response("Internal Error", { status: 500 });
return await next();
} catch (error) {
if (isFailOpen) {
const response = await env[__FALLBACK_SERVICE__].fetch(request);
return cloneResponse(response);
}
throw error;
}

@@ -160,0 +197,0 @@ },

{
"extends": "@cloudflare/workers-tsconfig/tsconfig.json",
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": [
"es2021"
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
"jsx": "react" /* Specify what JSX code is generated. */,
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "es2022" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
"types": [
"@cloudflare/workers-types"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true /* Enable importing .json files */,
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"noEmit": true /* Disable emitting files from a compilation. */,
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
"types": ["@cloudflare/workers-types"]
},
"include": ["**/*.ts"],
"exclude": [
"__tests__",
"./init-tests/**",
// Note: `startDevWorker` and `middleware` should also be included but some work is needed
// for that first (see: https://github.com/cloudflare/workers-sdk/issues/8303)
"startDevWorker",
"middleware"
]
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display