cli: update deps

This commit is contained in:
Aman Varshney
2025-07-12 21:47:34 +05:30
parent fcc1da8742
commit bd136792df
235 changed files with 22411 additions and 63 deletions

View File

@@ -0,0 +1,36 @@
export type RemotePattern = {
protocol?: "http" | "https";
hostname: string;
port?: string;
pathname: string;
search?: string;
};
export type LocalPattern = {
pathname: string;
search?: string;
};
/**
* Fetches an images.
*
* Local images (starting with a '/' as fetched using the passed fetcher).
* Remote images should match the configured remote patterns or a 404 response is returned.
*/
export declare function fetchImage(fetcher: Fetcher | undefined, imageUrl: string, ctx: ExecutionContext): Promise<Response | undefined>;
export declare function matchRemotePattern(pattern: RemotePattern, url: URL): boolean;
export declare function matchLocalPattern(pattern: LocalPattern, url: URL): boolean;
/**
* Detects the content type by looking at the first few bytes of a file
*
* Based on https://github.com/vercel/next.js/blob/72c9635/packages/next/src/server/image-optimizer.ts#L155
*
* @param buffer The image bytes
* @returns a content type of undefined for unsupported content
*/
export declare function detectContentType(buffer: Uint8Array): "image/svg+xml" | "image/jpeg" | "image/png" | "image/gif" | "image/webp" | "image/avif" | "image/x-icon" | "image/x-icns" | "image/tiff" | "image/bmp" | undefined;
declare global {
var __IMAGES_REMOTE_PATTERNS__: RemotePattern[];
var __IMAGES_LOCAL_PATTERNS__: LocalPattern[];
var __IMAGES_ALLOW_SVG__: boolean;
var __IMAGES_CONTENT_SECURITY_POLICY__: string;
var __IMAGES_CONTENT_DISPOSITION__: string;
}

View File

@@ -0,0 +1,176 @@
/**
* Fetches an images.
*
* Local images (starting with a '/' as fetched using the passed fetcher).
* Remote images should match the configured remote patterns or a 404 response is returned.
*/
export async function fetchImage(fetcher, imageUrl, ctx) {
// https://github.com/vercel/next.js/blob/d76f0b1/packages/next/src/server/image-optimizer.ts#L208
if (!imageUrl || imageUrl.length > 3072 || imageUrl.startsWith("//")) {
return getUrlErrorResponse();
}
// Local
if (imageUrl.startsWith("/")) {
let pathname;
let url;
try {
// We only need pathname and search
url = new URL(imageUrl, "http://n");
pathname = decodeURIComponent(url.pathname);
}
catch {
return getUrlErrorResponse();
}
if (/\/_next\/image($|\/)/.test(pathname)) {
return getUrlErrorResponse();
}
// If localPatterns are not defined all local images are allowed.
if (__IMAGES_LOCAL_PATTERNS__.length > 0 &&
!__IMAGES_LOCAL_PATTERNS__.some((p) => matchLocalPattern(p, url))) {
return getUrlErrorResponse();
}
return fetcher?.fetch(`http://assets.local${imageUrl}`);
}
// Remote
let url;
try {
url = new URL(imageUrl);
}
catch {
return getUrlErrorResponse();
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
return getUrlErrorResponse();
}
// The remotePatterns is used to allow images from specific remote external paths and block all others.
if (!__IMAGES_REMOTE_PATTERNS__.some((p) => matchRemotePattern(p, url))) {
return getUrlErrorResponse();
}
const imgResponse = await fetch(imageUrl, { cf: { cacheEverything: true } });
if (!imgResponse.body) {
return imgResponse;
}
const buffer = new ArrayBuffer(32);
try {
let contentType;
// body1 is eventually used for the response
// body2 is used to detect the content type
const [body1, body2] = imgResponse.body.tee();
const reader = body2.getReader({ mode: "byob" });
const { value } = await reader.read(new Uint8Array(buffer));
// Release resources by calling `reader.cancel()`
// `ctx.waitUntil` keeps the runtime running until the promise settles without having to wait here.
ctx.waitUntil(reader.cancel());
if (value) {
contentType = detectContentType(value);
}
if (!contentType) {
// Fallback to the sanitized upstream header when the type can not be detected
// https://github.com/vercel/next.js/blob/d76f0b1/packages/next/src/server/image-optimizer.ts#L748
const header = imgResponse.headers.get("content-type") ?? "";
if (header.startsWith("image/") && !header.includes(",")) {
contentType = header;
}
}
if (contentType && !(contentType === SVG && !__IMAGES_ALLOW_SVG__)) {
const headers = new Headers(imgResponse.headers);
headers.set("content-type", contentType);
headers.set("content-disposition", __IMAGES_CONTENT_DISPOSITION__);
headers.set("content-security-policy", __IMAGES_CONTENT_SECURITY_POLICY__);
return new Response(body1, { ...imgResponse, headers });
}
return new Response('"url" parameter is valid but image type is not allowed', {
status: 400,
});
}
catch {
return new Response('"url" parameter is valid but upstream response is invalid', {
status: 400,
});
}
}
export function matchRemotePattern(pattern, url) {
// https://github.com/vercel/next.js/blob/d76f0b1/packages/next/src/shared/lib/match-remote-pattern.ts
if (pattern.protocol !== undefined &&
pattern.protocol.replace(/:$/, "") !== url.protocol.replace(/:$/, "")) {
return false;
}
if (pattern.port !== undefined && pattern.port !== url.port) {
return false;
}
if (pattern.hostname === undefined || !new RegExp(pattern.hostname).test(url.hostname)) {
return false;
}
if (pattern.search !== undefined && pattern.search !== url.search) {
return false;
}
// Should be the same as writeImagesManifest()
return new RegExp(pattern.pathname).test(url.pathname);
}
export function matchLocalPattern(pattern, url) {
// https://github.com/vercel/next.js/blob/d76f0b1/packages/next/src/shared/lib/match-local-pattern.ts
if (pattern.search !== undefined && pattern.search !== url.search) {
return false;
}
return new RegExp(pattern.pathname).test(url.pathname);
}
/**
* @returns same error as Next.js when the url query parameter is not accepted.
*/
function getUrlErrorResponse() {
return new Response(`"url" parameter is not allowed`, { status: 400 });
}
const AVIF = "image/avif";
const WEBP = "image/webp";
const PNG = "image/png";
const JPEG = "image/jpeg";
const GIF = "image/gif";
const SVG = "image/svg+xml";
const ICO = "image/x-icon";
const ICNS = "image/x-icns";
const TIFF = "image/tiff";
const BMP = "image/bmp";
/**
* Detects the content type by looking at the first few bytes of a file
*
* Based on https://github.com/vercel/next.js/blob/72c9635/packages/next/src/server/image-optimizer.ts#L155
*
* @param buffer The image bytes
* @returns a content type of undefined for unsupported content
*/
export function detectContentType(buffer) {
if ([0xff, 0xd8, 0xff].every((b, i) => buffer[i] === b)) {
return JPEG;
}
if ([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((b, i) => buffer[i] === b)) {
return PNG;
}
if ([0x47, 0x49, 0x46, 0x38].every((b, i) => buffer[i] === b)) {
return GIF;
}
if ([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50].every((b, i) => !b || buffer[i] === b)) {
return WEBP;
}
if ([0x3c, 0x3f, 0x78, 0x6d, 0x6c].every((b, i) => buffer[i] === b)) {
return SVG;
}
if ([0x3c, 0x73, 0x76, 0x67].every((b, i) => buffer[i] === b)) {
return SVG;
}
if ([0, 0, 0, 0, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66].every((b, i) => !b || buffer[i] === b)) {
return AVIF;
}
if ([0x00, 0x00, 0x01, 0x00].every((b, i) => buffer[i] === b)) {
return ICO;
}
if ([0x69, 0x63, 0x6e, 0x73].every((b, i) => buffer[i] === b)) {
return ICNS;
}
if ([0x49, 0x49, 0x2a, 0x00].every((b, i) => buffer[i] === b)) {
return TIFF;
}
if ([0x42, 0x4d].every((b, i) => buffer[i] === b)) {
return BMP;
}
}
/* eslint-enable no-var */

View File

@@ -0,0 +1,15 @@
/**
* Initialization for the workerd runtime.
*
* The file must be imported at the top level the worker.
*/
/**
* Executes the handler with the Cloudflare context.
*/
export declare function runWithCloudflareRequestContext(request: Request, env: CloudflareEnv, ctx: ExecutionContext, handler: () => Promise<Response>): Promise<Response>;
declare global {
var __BUILD_TIMESTAMP_MS__: number;
var __NEXT_BASE_PATH__: string;
var __ASSETS_RUN_WORKER_FIRST__: boolean | string[] | undefined;
var __DEPLOYMENT_ID__: string;
}

View File

@@ -0,0 +1,122 @@
/**
* Initialization for the workerd runtime.
*
* The file must be imported at the top level the worker.
*/
import { AsyncLocalStorage } from "node:async_hooks";
import process from "node:process";
import stream from "node:stream";
// @ts-expect-error: resolved by wrangler build
import * as nextEnvVars from "./next-env.mjs";
const cloudflareContextALS = new AsyncLocalStorage();
// Note: this symbol needs to be kept in sync with `src/api/get-cloudflare-context.ts`
Object.defineProperty(globalThis, Symbol.for("__cloudflare-context__"), {
get() {
return cloudflareContextALS.getStore();
},
});
/**
* Executes the handler with the Cloudflare context.
*/
export async function runWithCloudflareRequestContext(request, env, ctx, handler) {
init(request, env);
return cloudflareContextALS.run({ env, ctx, cf: request.cf }, handler);
}
let initialized = false;
/**
* Initializes the runtime on the first call,
* no-op on subsequent invocations.
*/
function init(request, env) {
if (initialized) {
return;
}
initialized = true;
const url = new URL(request.url);
initRuntime();
populateProcessEnv(url, env);
}
function initRuntime() {
// Some packages rely on `process.version` and `process.versions.node` (i.e. Jose@4)
// TODO: Remove when https://github.com/unjs/unenv/pull/493 is merged
Object.assign(process, { version: process.version || "v22.14.0" });
// @ts-expect-error Node type does not match workerd
Object.assign(process.versions, { node: "22.14.0", ...process.versions });
globalThis.__dirname ??= "";
globalThis.__filename ??= "";
// Some packages rely on `import.meta.url` but it is undefined in workerd
// For example it causes a bunch of issues, and will make even import crash with payload
import.meta.url ??= "file:///worker.js";
// Do not crash on cache not supported
// https://github.com/cloudflare/workerd/pull/2434
// compatibility flag "cache_option_enabled" -> does not support "force-cache"
const __original_fetch = globalThis.fetch;
globalThis.fetch = (input, init) => {
if (init) {
delete init.cache;
}
return __original_fetch(input, init);
};
const CustomRequest = class extends globalThis.Request {
constructor(input, init) {
if (init) {
delete init.cache;
// https://github.com/cloudflare/workerd/issues/2746
// https://github.com/cloudflare/workerd/issues/3245
Object.defineProperty(init, "body", {
// @ts-ignore
value: init.body instanceof stream.Readable ? ReadableStream.from(init.body) : init.body,
});
}
super(input, init);
}
};
Object.assign(globalThis, {
Request: CustomRequest,
__BUILD_TIMESTAMP_MS__,
__NEXT_BASE_PATH__,
__ASSETS_RUN_WORKER_FIRST__,
// The external middleware will use the convertTo function of the `edge` converter
// by default it will try to fetch the request, but since we are running everything in the same worker
// we need to use the request as is.
__dangerous_ON_edge_converter_returns_request: true,
});
}
/**
* Populate process.env with:
* - the environment variables and secrets from the cloudflare platform
* - the variables from Next .env* files
* - the origin resolver information
*/
function populateProcessEnv(url, env) {
for (const [key, value] of Object.entries(env)) {
if (typeof value === "string") {
process.env[key] = value;
}
}
const mode = env.NEXTJS_ENV ?? "production";
if (nextEnvVars[mode]) {
for (const key in nextEnvVars[mode]) {
process.env[key] ??= nextEnvVars[mode][key];
}
}
// Set the default Origin for the origin resolver.
// This is only needed for an external middleware bundle
process.env.OPEN_NEXT_ORIGIN = JSON.stringify({
default: {
host: url.hostname,
protocol: url.protocol.slice(0, -1),
port: url.port,
},
});
/* We need to set this environment variable to make redirects work properly in preview mode.
* Next sets this in standalone mode during `startServer`. Without this the protocol would always be `https` here:
* https://github.com/vercel/next.js/blob/6b1e48080e896e0d44a05fe009cb79d2d3f91774/packages/next/src/server/app-render/action-handler.ts#L307-L316
*/
process.env.__NEXT_PRIVATE_ORIGIN = url.origin;
// `__DEPLOYMENT_ID__` is a string (passed via ESBuild).
if (__DEPLOYMENT_ID__) {
process.env.DEPLOYMENT_ID = __DEPLOYMENT_ID__;
}
}
/* eslint-enable no-var */

View File

@@ -0,0 +1,2 @@
declare const _default: {};
export default _default;

View File

@@ -0,0 +1 @@
export default {};

View File

@@ -0,0 +1 @@
export declare function loadEnvConfig(): void;

View File

@@ -0,0 +1 @@
export function loadEnvConfig() { }

View File

@@ -0,0 +1 @@
export default fetch;

View File

@@ -0,0 +1 @@
export default fetch;

View File

@@ -0,0 +1,2 @@
declare const _default: {};
export default _default;

View File

@@ -0,0 +1,2 @@
throw "OpenNext shim";
export default {};

View File

@@ -0,0 +1,28 @@
/** Name of the env var containing the mapping */
export declare const DEPLOYMENT_MAPPING_ENV_NAME = "CF_DEPLOYMENT_MAPPING";
/** Version used for the latest worker */
export declare const CURRENT_VERSION_ID = "current";
/**
* Routes the request to the requested deployment.
*
* A specific deployment can be requested via:
* - the `dpl` search parameter for assets
* - the `x-deployment-id` for other requests
*
* When a specific deployment is requested, we route to that deployment via the preview URLs.
* See https://developers.cloudflare.com/workers/configuration/previews/
*
* When the requested deployment is not supported a 400 response is returned.
*
* Notes:
* - The re-routing is only active for the deployed version of the app (on a custom domain)
* - Assets are also handled when `run_worker_first` is enabled.
* See https://developers.cloudflare.com/workers/static-assets/binding/#run_worker_first
*
* @param request
* @returns
*/
export declare function maybeGetSkewProtectionResponse(request: Request): Promise<Response> | Response | undefined;
declare global {
var __SKEW_PROTECTION_ENABLED__: boolean;
}

View File

@@ -0,0 +1,57 @@
import process from "node:process";
/** Name of the env var containing the mapping */
export const DEPLOYMENT_MAPPING_ENV_NAME = "CF_DEPLOYMENT_MAPPING";
/** Version used for the latest worker */
export const CURRENT_VERSION_ID = "current";
/**
* Routes the request to the requested deployment.
*
* A specific deployment can be requested via:
* - the `dpl` search parameter for assets
* - the `x-deployment-id` for other requests
*
* When a specific deployment is requested, we route to that deployment via the preview URLs.
* See https://developers.cloudflare.com/workers/configuration/previews/
*
* When the requested deployment is not supported a 400 response is returned.
*
* Notes:
* - The re-routing is only active for the deployed version of the app (on a custom domain)
* - Assets are also handled when `run_worker_first` is enabled.
* See https://developers.cloudflare.com/workers/static-assets/binding/#run_worker_first
*
* @param request
* @returns
*/
export function maybeGetSkewProtectionResponse(request) {
// no early return as esbuild would not treeshake the code.
if (__SKEW_PROTECTION_ENABLED__) {
const url = new URL(request.url);
// Skew protection is only active for the latest version of the app served on a custom domain.
if (url.hostname === "localhost" || url.hostname.endsWith(".workers.dev")) {
return undefined;
}
const requestDeploymentId = request.headers.get("x-deployment-id") ?? url.searchParams.get("dpl");
if (!requestDeploymentId || requestDeploymentId === process.env.DEPLOYMENT_ID) {
// The request does not specify a deployment id or it is the current deployment id
return undefined;
}
const mapping = process.env[DEPLOYMENT_MAPPING_ENV_NAME]
? JSON.parse(process.env[DEPLOYMENT_MAPPING_ENV_NAME])
: {};
if (!(requestDeploymentId in mapping)) {
// Unknown deployment id, serve the current version
return undefined;
}
const version = mapping[requestDeploymentId];
if (!version || version === CURRENT_VERSION_ID) {
return undefined;
}
const versionDomain = version.split("-")[0];
const hostname = `${versionDomain}-${process.env.CF_WORKER_NAME}.${process.env.CF_PREVIEW_DOMAIN}.workers.dev`;
url.hostname = hostname;
const requestToOlderDeployment = new Request(url, request);
return fetch(requestToOlderDeployment);
}
}
/* eslint-enable no-var */

View File

@@ -0,0 +1,7 @@
export { DOQueueHandler } from "./.build/durable-objects/queue.js";
export { DOShardedTagCache } from "./.build/durable-objects/sharded-tag-cache.js";
export { BucketCachePurge } from "./.build/durable-objects/bucket-cache-purge.js";
declare const _default: {
fetch(request: Request<unknown, IncomingRequestCfProperties<unknown>>, env: CloudflareEnv, ctx: ExecutionContext): Promise<any>;
};
export default _default;

View File

@@ -0,0 +1,50 @@
//@ts-expect-error: Will be resolved by wrangler build
import { fetchImage } from "./cloudflare/images.js";
//@ts-expect-error: Will be resolved by wrangler build
import { runWithCloudflareRequestContext } from "./cloudflare/init.js";
//@ts-expect-error: Will be resolved by wrangler build
import { maybeGetSkewProtectionResponse } from "./cloudflare/skew-protection.js";
// @ts-expect-error: Will be resolved by wrangler build
import { handler as middlewareHandler } from "./middleware/handler.mjs";
//@ts-expect-error: Will be resolved by wrangler build
export { DOQueueHandler } from "./.build/durable-objects/queue.js";
//@ts-expect-error: Will be resolved by wrangler build
export { DOShardedTagCache } from "./.build/durable-objects/sharded-tag-cache.js";
//@ts-expect-error: Will be resolved by wrangler build
export { BucketCachePurge } from "./.build/durable-objects/bucket-cache-purge.js";
export default {
async fetch(request, env, ctx) {
return runWithCloudflareRequestContext(request, env, ctx, async () => {
const response = maybeGetSkewProtectionResponse(request);
if (response) {
return response;
}
const url = new URL(request.url);
// Serve images in development.
// Note: "/cdn-cgi/image/..." requests do not reach production workers.
if (url.pathname.startsWith("/cdn-cgi/image/")) {
const m = url.pathname.match(/\/cdn-cgi\/image\/.+?\/(?<url>.+)$/);
if (m === null) {
return new Response("Not Found!", { status: 404 });
}
const imageUrl = m.groups.url;
return imageUrl.match(/^https?:\/\//)
? fetch(imageUrl, { cf: { cacheEverything: true } })
: env.ASSETS?.fetch(new URL(`/${imageUrl}`, url));
}
// Fallback for the Next default image loader.
if (url.pathname === `${globalThis.__NEXT_BASE_PATH__}/_next/image`) {
const imageUrl = url.searchParams.get("url") ?? "";
return await fetchImage(env.ASSETS, imageUrl, ctx);
}
// - `Request`s are handled by the Next server
const reqOrResp = await middlewareHandler(request, env, ctx);
if (reqOrResp instanceof Response) {
return reqOrResp;
}
// @ts-expect-error: resolved by wrangler build
const { handler } = await import("./server-functions/default/handler.mjs");
return handler(reqOrResp, env, ctx);
});
},
};