Socket
Socket
Sign inDemoInstall

@netlify/plugin-nextjs

Package Overview
Dependencies
Maintainers
23
Versions
257
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@netlify/plugin-nextjs - npm Package Compare versions

Comparing version 5.1.2 to 5.2.0

dist/esm-chunks/package-ZBRSUKN7.js

125

dist/build/advanced-api-routes.js

@@ -8,6 +8,123 @@

import {
ApiRouteType,
getAPIRoutesConfigs
} from "../esm-chunks/chunk-BG455SFE.js";
import "../esm-chunks/chunk-5JVNISGM.js";
__require
} from "../esm-chunks/chunk-5JVNISGM.js";
// src/build/advanced-api-routes.ts
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
var ApiRouteType = /* @__PURE__ */ ((ApiRouteType2) => {
ApiRouteType2["SCHEDULED"] = "experimental-scheduled";
ApiRouteType2["BACKGROUND"] = "experimental-background";
return ApiRouteType2;
})(ApiRouteType || {});
async function getAPIRoutesConfigs(ctx) {
const functionsConfigManifestPath = join(
ctx.publishDir,
"server",
"functions-config-manifest.json"
);
if (!existsSync(functionsConfigManifestPath)) {
return [];
}
const functionsConfigManifest = JSON.parse(
await readFile(functionsConfigManifestPath, "utf-8")
);
const appDir = ctx.resolveFromSiteDir(".");
const pagesDir = join(appDir, "pages");
const srcPagesDir = join(appDir, "src", "pages");
const { pageExtensions } = ctx.requiredServerFiles.config;
return Promise.all(
Object.keys(functionsConfigManifest.functions).map(async (apiRoute) => {
const filePath = getSourceFileForPage(apiRoute, [pagesDir, srcPagesDir], pageExtensions);
const sharedFields = {
apiRoute,
filePath,
config: {}
};
if (filePath) {
const config = await extractConfigFromFile(filePath, appDir);
return {
...sharedFields,
config
};
}
return sharedFields;
})
);
}
var SOURCE_FILE_EXTENSIONS = ["js", "jsx", "ts", "tsx"];
var getSourceFileForPage = (page, roots, pageExtensions = SOURCE_FILE_EXTENSIONS) => {
for (const root of roots) {
for (const extension of pageExtensions) {
const file = join(root, `${page}.${extension}`);
if (existsSync(file)) {
return file;
}
const fileAtFolderIndex = join(root, page, `index.${extension}`);
if (existsSync(fileAtFolderIndex)) {
return fileAtFolderIndex;
}
}
}
};
var findModuleFromBase = ({
paths,
candidates
}) => {
for (const candidate of candidates) {
try {
const modulePath = __require.resolve(candidate, { paths });
if (modulePath) {
return modulePath;
}
} catch {
}
}
for (const candidate of candidates) {
try {
const modulePath = __require.resolve(candidate);
if (modulePath) {
return modulePath;
}
} catch {
}
}
return null;
};
var extractConstValue;
var parseModule;
var extractConfigFromFile = async (apiFilePath, appDir) => {
if (!apiFilePath || !existsSync(apiFilePath)) {
return {};
}
const extractConstValueModulePath = findModuleFromBase({
paths: [appDir],
candidates: ["next/dist/build/analysis/extract-const-value"]
});
const parseModulePath = findModuleFromBase({
paths: [appDir],
candidates: ["next/dist/build/analysis/parse-module"]
});
if (!extractConstValueModulePath || !parseModulePath) {
return {};
}
if (!extractConstValue && extractConstValueModulePath) {
extractConstValue = __require(extractConstValueModulePath);
}
if (!parseModule && parseModulePath) {
parseModule = __require(parseModulePath).parseModule;
}
const { extractExportedConstValue } = extractConstValue;
const fileContent = await readFile(apiFilePath, "utf8");
if (!fileContent.includes("config")) {
return {};
}
const ast = await parseModule(apiFilePath, fileContent);
try {
return extractExportedConstValue(ast, "config");
} catch {
return {};
}
};
export {

@@ -14,0 +131,0 @@ ApiRouteType,

@@ -7,7 +7,28 @@

import {
restoreBuildCache,
saveBuildCache
} from "../esm-chunks/chunk-72ZI2IVI.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/build/cache.ts
import { existsSync } from "node:fs";
import { rm } from "node:fs/promises";
import { join } from "node:path";
var saveBuildCache = async (ctx) => {
const { cache } = ctx.utils;
const cacheDir = join(ctx.publishDir, "cache");
if (existsSync(cacheDir)) {
await rm(join(cacheDir, "fetch-cache"), { recursive: true, force: true });
await cache.save(cacheDir);
console.log("Next.js cache saved");
} else {
console.log("No Next.js cache to save");
}
};
var restoreBuildCache = async (ctx) => {
const { cache } = ctx.utils;
const cacheDir = join(ctx.publishDir, "cache");
if (await cache.restore(cacheDir)) {
console.log("Next.js cache restored");
} else {
console.log("No Next.js cache to restore");
}
};
export {

@@ -14,0 +35,0 @@ restoreBuildCache,

@@ -8,10 +8,236 @@

import {
copyFetchContent,
copyPrerenderedContent
} from "../../esm-chunks/chunk-MRD3XSKD.js";
import "../../esm-chunks/chunk-TYCYFZ22.js";
import "../../esm-chunks/chunk-PDPDW32D.js";
import "../../esm-chunks/chunk-Y3K5Q6FP.js";
import "../../esm-chunks/chunk-VZNKO4OO.js";
import "../../esm-chunks/chunk-5JVNISGM.js";
require_out
} from "../../esm-chunks/chunk-VZNKO4OO.js";
import {
wrapTracer
} from "../../esm-chunks/chunk-PDPDW32D.js";
import {
init_esm,
trace
} from "../../esm-chunks/chunk-Y3K5Q6FP.js";
import {
__toESM
} from "../../esm-chunks/chunk-5JVNISGM.js";
// src/build/content/prerendered.ts
init_esm();
import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
var import_fast_glob = __toESM(require_out(), 1);
// node_modules/yocto-queue/index.js
var Node = class {
value;
next;
constructor(value) {
this.value = value;
}
};
var Queue = class {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
clear() {
this.#head = void 0;
this.#tail = void 0;
this.#size = 0;
}
get size() {
return this.#size;
}
*[Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
};
// node_modules/p-limit/index.js
function pLimit(concurrency) {
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
throw new TypeError("Expected `concurrency` to be a number from 1 and up");
}
const queue = new Queue();
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.size > 0) {
queue.dequeue()();
}
};
const run = async (fn, resolve, args) => {
activeCount++;
const result = (async () => fn(...args))();
resolve(result);
try {
await result;
} catch {
}
next();
};
const enqueue = (fn, resolve, args) => {
queue.enqueue(run.bind(void 0, fn, resolve, args));
(async () => {
await Promise.resolve();
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
}
})();
};
const generator = (fn, ...args) => new Promise((resolve) => {
enqueue(fn, resolve, args);
});
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount
},
pendingCount: {
get: () => queue.size
},
clearQueue: {
value: () => {
queue.clear();
}
}
});
return generator;
}
// src/build/content/prerendered.ts
import { encodeBlobKey } from "../../shared/blobkey.js";
var tracer = wrapTracer(trace.getTracer("Next runtime"));
var writeCacheEntry = async (route, value, lastModified, ctx) => {
const path = join(ctx.blobDir, await encodeBlobKey(route));
const entry = JSON.stringify({
lastModified,
value
});
await writeFile(path, entry, "utf-8");
};
var routeToFilePath = (path) => path === "/" ? "/index" : path;
var buildPagesCacheValue = async (path) => ({
kind: "PAGE",
html: await readFile(`${path}.html`, "utf-8"),
pageData: JSON.parse(await readFile(`${path}.json`, "utf-8")),
postponed: void 0,
headers: void 0,
status: void 0
});
var buildAppCacheValue = async (path) => {
const meta = JSON.parse(await readFile(`${path}.meta`, "utf-8"));
const rsc = await readFile(`${path}.rsc`, "utf-8").catch(
() => readFile(`${path}.prefetch.rsc`, "utf-8")
);
if (!meta.status && rsc.includes("NEXT_NOT_FOUND")) {
meta.status = 404;
}
return {
kind: "PAGE",
html: await readFile(`${path}.html`, "utf-8"),
pageData: rsc,
...meta
};
};
var buildRouteCacheValue = async (path, initialRevalidateSeconds) => ({
kind: "ROUTE",
body: await readFile(`${path}.body`, "base64"),
...JSON.parse(await readFile(`${path}.meta`, "utf-8")),
revalidate: initialRevalidateSeconds
});
var buildFetchCacheValue = async (path) => ({
kind: "FETCH",
...JSON.parse(await readFile(path, "utf-8"))
});
var copyPrerenderedContent = async (ctx) => {
return tracer.withActiveSpan("copyPrerenderedContent", async () => {
try {
await mkdir(ctx.blobDir, { recursive: true });
const manifest = await ctx.getPrerenderManifest();
const limitConcurrentPrerenderContentHandling = pLimit(10);
await Promise.all(
Object.entries(manifest.routes).map(
([route, meta]) => limitConcurrentPrerenderContentHandling(async () => {
const lastModified = meta.initialRevalidateSeconds ? Date.now() - 31536e6 : Date.now();
const key = routeToFilePath(route);
let value;
switch (true) {
case (meta.dataRoute?.endsWith("/default.rsc") && !existsSync(join(ctx.publishDir, "server/app", `${key}.html`))):
return;
case meta.dataRoute?.endsWith(".json"):
if (manifest.notFoundRoutes.includes(route)) {
return;
}
value = await buildPagesCacheValue(join(ctx.publishDir, "server/pages", key));
break;
case meta.dataRoute?.endsWith(".rsc"):
value = await buildAppCacheValue(join(ctx.publishDir, "server/app", key));
break;
case meta.dataRoute === null:
value = await buildRouteCacheValue(
join(ctx.publishDir, "server/app", key),
meta.initialRevalidateSeconds
);
break;
default:
throw new Error(`Unrecognized content: ${route}`);
}
await writeCacheEntry(key, value, lastModified, ctx);
})
)
);
if (existsSync(join(ctx.publishDir, `server/app/_not-found.html`))) {
const lastModified = Date.now();
const key = "/404";
const value = await buildAppCacheValue(join(ctx.publishDir, "server/app/_not-found"));
await writeCacheEntry(key, value, lastModified, ctx);
}
} catch (error) {
ctx.failBuild("Failed assembling prerendered content for upload", error);
}
});
};
var copyFetchContent = async (ctx) => {
try {
const paths = await (0, import_fast_glob.glob)(["!(*.*)"], {
cwd: join(ctx.publishDir, "cache/fetch-cache"),
extglob: true
});
await Promise.all(
paths.map(async (key) => {
const lastModified = Date.now() - 31536e6;
const path = join(ctx.publishDir, "cache/fetch-cache", key);
const value = await buildFetchCacheValue(path);
await writeCacheEntry(key, value, lastModified, ctx);
})
);
} catch (error) {
ctx.failBuild("Failed assembling fetch content for upload", error);
}
};
export {

@@ -18,0 +244,0 @@ copyFetchContent,

@@ -8,16 +8,261 @@

import {
copyNextDependencies,
copyNextServerCode,
getPatchesToApply,
verifyHandlerDirStructure,
writeTagsManifest
} from "../../esm-chunks/chunk-4BNHE6TP.js";
import "../../esm-chunks/chunk-PDPDW32D.js";
import "../../esm-chunks/chunk-Y3K5Q6FP.js";
import "../../esm-chunks/chunk-VZNKO4OO.js";
import "../../esm-chunks/chunk-K7BTUM7O.js";
import "../../esm-chunks/chunk-PJG75HGC.js";
import "../../esm-chunks/chunk-BG455SFE.js";
import "../../esm-chunks/chunk-UYKENJEU.js";
import "../../esm-chunks/chunk-5JVNISGM.js";
require_out
} from "../../esm-chunks/chunk-VZNKO4OO.js";
import {
wrapTracer
} from "../../esm-chunks/chunk-PDPDW32D.js";
import {
init_esm,
trace
} from "../../esm-chunks/chunk-Y3K5Q6FP.js";
import {
require_semver
} from "../../esm-chunks/chunk-PJG75HGC.js";
import {
__toESM
} from "../../esm-chunks/chunk-5JVNISGM.js";
// src/build/content/server.ts
init_esm();
import { existsSync } from "node:fs";
import {
cp,
mkdir,
readFile,
readdir,
readlink,
symlink,
writeFile,
access
} from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join, resolve, sep } from "node:path";
import { sep as posixSep, join as posixJoin } from "node:path/posix";
var import_fast_glob = __toESM(require_out(), 1);
var import_semver = __toESM(require_semver(), 1);
import { RUN_CONFIG } from "../../run/constants.js";
import { verifyNextVersion } from "../verification.js";
var tracer = wrapTracer(trace.getTracer("Next runtime"));
var toPosixPath = (path) => path.split(sep).join(posixSep);
function isError(error) {
return error instanceof Error;
}
var copyNextServerCode = async (ctx) => {
await tracer.withActiveSpan("copyNextServerCode", async () => {
const reqServerFilesPath = join(
ctx.standaloneRootDir,
ctx.relativeAppDir,
ctx.requiredServerFiles.config.distDir,
"required-server-files.json"
);
try {
await access(reqServerFilesPath);
} catch (error) {
if (isError(error) && error.code === "ENOENT") {
ctx.failBuild(
`Failed creating server handler. required-server-files.json file not found at expected location "${reqServerFilesPath}". Your repository setup is currently not yet supported.`
);
} else {
throw error;
}
}
const reqServerFiles = JSON.parse(await readFile(reqServerFilesPath, "utf-8"));
if (toPosixPath(ctx.distDir).replace(new RegExp(`^${ctx.relativeAppDir}/?`), "") !== reqServerFiles.config.distDir) {
reqServerFiles.config.distDir = ctx.nextDistDir;
await writeFile(reqServerFilesPath, JSON.stringify(reqServerFiles));
}
await mkdir(ctx.serverHandlerDir, { recursive: true });
await writeFile(
join(ctx.serverHandlerDir, RUN_CONFIG),
JSON.stringify(reqServerFiles.config),
"utf-8"
);
const srcDir = join(ctx.standaloneDir, ctx.nextDistDir);
const nextFolder = toPosixPath(ctx.distDir) === toPosixPath(ctx.buildConfig.distDir) ? ctx.distDir : ctx.nextDistDir;
const destDir = join(ctx.serverHandlerDir, nextFolder);
const paths = await (0, import_fast_glob.default)(
[`*`, `server/*`, `server/chunks/*`, `server/edge-chunks/*`, `server/+(app|pages)/**/*.js`],
{
cwd: srcDir,
extglob: true
}
);
await Promise.all(
paths.map(async (path) => {
const srcPath = join(srcDir, path);
const destPath = join(destDir, path);
if (path === "server/middleware-manifest.json") {
try {
await replaceMiddlewareManifest(srcPath, destPath);
} catch (error) {
throw new Error("Could not patch middleware manifest file", { cause: error });
}
return;
}
await cp(srcPath, destPath, { recursive: true, force: true });
})
);
});
};
async function recreateNodeModuleSymlinks(src, dest, org) {
const dirents = await readdir(join(src, org || ""), { withFileTypes: true });
await Promise.all(
dirents.map(async (dirent) => {
if (dirent.name.startsWith("@")) {
return recreateNodeModuleSymlinks(src, dest, dirent.name);
}
if (dirent.isSymbolicLink()) {
const symlinkSrc = join(dest, org || "", dirent.name);
const symlinkTarget = await readlink(join(src, org || "", dirent.name));
const symlinkDest = join(dest, org || "", symlinkTarget);
if (existsSync(symlinkDest) && !existsSync(symlinkSrc)) {
if (org) {
await mkdir(join(dest, org), { recursive: true });
}
await symlink(symlinkTarget, symlinkSrc);
}
}
})
);
}
var nextInternalModuleReplacements = [
{
// standalone is loading expensive Telemetry module that is not actually used
// so this replace that module with lightweight no-op shim that doesn't load additional modules
// see https://github.com/vercel/next.js/pull/63574 that removed need for this shim
ongoing: false,
minVersion: "13.5.0-canary.0",
// perf released in https://github.com/vercel/next.js/releases/tag/v14.2.0-canary.43
maxVersion: "14.2.0-canary.42",
nextModule: "next/dist/telemetry/storage.js",
shimModule: "./next-shims/telemetry-storage.cjs"
}
];
function getPatchesToApply(nextVersion, patches = nextInternalModuleReplacements) {
return patches.filter((patch) => {
if ((0, import_semver.lt)(nextVersion, patch.minVersion)) {
return false;
}
if (patch.ongoing) {
if ((0, import_semver.prerelease)(nextVersion) || process.env.NETLIFY_NEXT_FORCE_APPLY_ONGOING_PATCHES) {
return true;
}
return (0, import_semver.lte)(nextVersion, patch.maxStableVersion);
}
return (0, import_semver.lte)(nextVersion, patch.maxVersion);
});
}
async function patchNextModules(ctx, nextVersion, serverHandlerRequireResolve) {
const moduleReplacementsToApply = getPatchesToApply(nextVersion);
if (moduleReplacementsToApply.length !== 0) {
await Promise.all(
moduleReplacementsToApply.map(async ({ nextModule, shimModule }) => {
try {
const nextModulePath = serverHandlerRequireResolve(nextModule);
const shimModulePath = posixJoin(ctx.pluginDir, "dist", "build", "content", shimModule);
await cp(shimModulePath, nextModulePath, { force: true });
} catch {
}
})
);
}
}
var copyNextDependencies = async (ctx) => {
await tracer.withActiveSpan("copyNextDependencies", async () => {
const entries = await readdir(ctx.standaloneDir);
const promises = entries.map(async (entry) => {
if (entry === "package.json" || entry === ctx.nextDistDir) {
return;
}
const src = join(ctx.standaloneDir, entry);
const dest = join(ctx.serverHandlerDir, entry);
await cp(src, dest, { recursive: true, verbatimSymlinks: true, force: true });
if (entry === "node_modules") {
await recreateNodeModuleSymlinks(ctx.resolveFromSiteDir("node_modules"), dest);
}
});
const rootSrcDir = join(ctx.standaloneRootDir, "node_modules");
const rootDestDir = join(ctx.serverHandlerRootDir, "node_modules");
if (existsSync(rootSrcDir) && ctx.standaloneRootDir !== ctx.standaloneDir) {
promises.push(
cp(rootSrcDir, rootDestDir, { recursive: true, verbatimSymlinks: true }).then(
() => recreateNodeModuleSymlinks(resolve("node_modules"), rootDestDir)
)
);
}
await Promise.all(promises);
const serverHandlerRequire = createRequire(posixJoin(ctx.serverHandlerDir, ":internal:"));
let nextVersion;
try {
const { version } = serverHandlerRequire("next/package.json");
if (version) {
nextVersion = version;
}
} catch {
}
if (nextVersion) {
verifyNextVersion(ctx, nextVersion);
await patchNextModules(ctx, nextVersion, serverHandlerRequire.resolve);
}
try {
const nextEntryAbsolutePath = serverHandlerRequire.resolve("next");
const nextRequire = createRequire(nextEntryAbsolutePath);
nextRequire.resolve("styled-jsx");
} catch {
throw new Error(
"node_modules are not installed correctly, if you are using pnpm please set the public hoist pattern to: `public-hoist-pattern[]=*`.\nRefer to your docs for more details: https://docs.netlify.com/integrations/frameworks/next-js/overview/#pnpm-support"
);
}
});
};
var writeTagsManifest = async (ctx) => {
const manifest = await ctx.getPrerenderManifest();
const routes = Object.entries(manifest.routes).map(async ([route, definition]) => {
let tags;
if (definition.dataRoute?.endsWith(".rsc")) {
const path = join(ctx.publishDir, `server/app/${route === "/" ? "/index" : route}.meta`);
try {
const file = await readFile(path, "utf-8");
const meta = JSON.parse(file);
tags = meta.headers["x-next-cache-tags"];
} catch {
if (!definition.dataRoute?.endsWith("/default.rsc")) {
console.log(`Unable to read cache tags for: ${path}`);
}
}
}
if (definition.dataRoute?.endsWith(".json")) {
tags = `_N_T_${route}`;
}
if (definition.dataRoute === null) {
tags = definition.initialHeaders?.["x-next-cache-tags"];
}
return [route, tags];
});
await writeFile(
join(ctx.serverHandlerDir, ".netlify/tags-manifest.json"),
JSON.stringify(Object.fromEntries(await Promise.all(routes))),
"utf-8"
);
};
var replaceMiddlewareManifest = async (sourcePath, destPath) => {
await mkdir(dirname(destPath), { recursive: true });
const data = await readFile(sourcePath, "utf8");
const manifest = JSON.parse(data);
const newManifest = {
...manifest,
middleware: {}
};
const newData = JSON.stringify(newManifest);
await writeFile(destPath, newData);
};
var verifyHandlerDirStructure = async (ctx) => {
const runConfig = JSON.parse(await readFile(join(ctx.serverHandlerDir, RUN_CONFIG), "utf-8"));
const expectedBuildIDPath = join(ctx.serverHandlerDir, runConfig.distDir, "BUILD_ID");
if (!existsSync(expectedBuildIDPath)) {
ctx.failBuild(
`Failed creating server handler. BUILD_ID file not found at expected location "${expectedBuildIDPath}".`
);
}
};
export {

@@ -24,0 +269,0 @@ copyNextDependencies,

@@ -8,13 +8,98 @@

import {
copyStaticAssets,
copyStaticContent,
copyStaticExport,
publishStaticDir,
unpublishStaticDir
} from "../../esm-chunks/chunk-V2T6NUOM.js";
import "../../esm-chunks/chunk-TYCYFZ22.js";
import "../../esm-chunks/chunk-PDPDW32D.js";
import "../../esm-chunks/chunk-Y3K5Q6FP.js";
import "../../esm-chunks/chunk-VZNKO4OO.js";
import "../../esm-chunks/chunk-5JVNISGM.js";
require_out
} from "../../esm-chunks/chunk-VZNKO4OO.js";
import {
wrapTracer
} from "../../esm-chunks/chunk-PDPDW32D.js";
import {
init_esm,
trace
} from "../../esm-chunks/chunk-Y3K5Q6FP.js";
import {
__toESM
} from "../../esm-chunks/chunk-5JVNISGM.js";
// src/build/content/static.ts
init_esm();
import { existsSync } from "node:fs";
import { cp, mkdir, rename, rm } from "node:fs/promises";
import { basename, join } from "node:path";
var import_fast_glob = __toESM(require_out(), 1);
import { encodeBlobKey } from "../../shared/blobkey.js";
var tracer = wrapTracer(trace.getTracer("Next runtime"));
var copyStaticContent = async (ctx) => {
return tracer.withActiveSpan("copyStaticContent", async () => {
const srcDir = join(ctx.publishDir, "server/pages");
const destDir = ctx.blobDir;
const paths = await (0, import_fast_glob.default)("**/*.+(html|json)", {
cwd: srcDir,
extglob: true
});
try {
await Promise.all(
paths.filter((path) => !paths.includes(`${path.slice(0, -5)}.json`)).map(async (path) => {
await cp(join(srcDir, path), join(destDir, await encodeBlobKey(path)), {
recursive: true,
force: true
});
})
);
} catch (error) {
ctx.failBuild("Failed assembling static pages for upload", error);
}
});
};
var copyStaticAssets = async (ctx) => {
return tracer.withActiveSpan("copyStaticAssets", async (span) => {
try {
await rm(ctx.staticDir, { recursive: true, force: true });
const { basePath } = await ctx.getRoutesManifest();
if (existsSync(ctx.resolveFromSiteDir("public"))) {
await cp(ctx.resolveFromSiteDir("public"), join(ctx.staticDir, basePath), {
recursive: true
});
}
if (existsSync(join(ctx.publishDir, "static"))) {
await cp(join(ctx.publishDir, "static"), join(ctx.staticDir, basePath, "_next/static"), {
recursive: true
});
}
} catch (error) {
span.end();
ctx.failBuild("Failed copying static assets", error);
}
});
};
var copyStaticExport = async (ctx) => {
await tracer.withActiveSpan("copyStaticExport", async () => {
if (!ctx.exportDetail?.outDirectory) {
ctx.failBuild("Export directory not found");
}
try {
await rm(ctx.staticDir, { recursive: true, force: true });
await cp(ctx.exportDetail.outDirectory, ctx.staticDir, { recursive: true });
} catch (error) {
ctx.failBuild("Failed copying static export", error);
}
});
};
var publishStaticDir = async (ctx) => {
try {
await rm(ctx.tempPublishDir, { recursive: true, force: true });
await mkdir(basename(ctx.tempPublishDir), { recursive: true });
await rename(ctx.publishDir, ctx.tempPublishDir);
await rename(ctx.staticDir, ctx.publishDir);
} catch (error) {
ctx.failBuild("Failed publishing static content", error instanceof Error ? { error } : {});
}
};
var unpublishStaticDir = async (ctx) => {
try {
if (existsSync(ctx.tempPublishDir)) {
await rename(ctx.publishDir, ctx.staticDir);
await rename(ctx.tempPublishDir, ctx.publishDir);
}
} catch {
}
};
export {

@@ -21,0 +106,0 @@ copyStaticAssets,

@@ -8,9 +8,515 @@

import {
createEdgeHandlers
} from "../../esm-chunks/chunk-UTQSBE5O.js";
import "../../esm-chunks/chunk-VZNKO4OO.js";
import "../../esm-chunks/chunk-L6OM53B6.js";
import "../../esm-chunks/chunk-5JVNISGM.js";
require_out
} from "../../esm-chunks/chunk-VZNKO4OO.js";
import {
__commonJS,
__toESM
} from "../../esm-chunks/chunk-5JVNISGM.js";
// node_modules/path-to-regexp/dist/index.js
var require_dist = __commonJS({
"node_modules/path-to-regexp/dist/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pathToRegexp = exports.tokensToRegexp = exports.regexpToFunction = exports.match = exports.tokensToFunction = exports.compile = exports.parse = void 0;
function lexer(str) {
var tokens = [];
var i = 0;
while (i < str.length) {
var char = str[i];
if (char === "*" || char === "+" || char === "?") {
tokens.push({ type: "MODIFIER", index: i, value: str[i++] });
continue;
}
if (char === "\\") {
tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
continue;
}
if (char === "{") {
tokens.push({ type: "OPEN", index: i, value: str[i++] });
continue;
}
if (char === "}") {
tokens.push({ type: "CLOSE", index: i, value: str[i++] });
continue;
}
if (char === ":") {
var name = "";
var j = i + 1;
while (j < str.length) {
var code = str.charCodeAt(j);
if (
// `0-9`
code >= 48 && code <= 57 || // `A-Z`
code >= 65 && code <= 90 || // `a-z`
code >= 97 && code <= 122 || // `_`
code === 95
) {
name += str[j++];
continue;
}
break;
}
if (!name)
throw new TypeError("Missing parameter name at ".concat(i));
tokens.push({ type: "NAME", index: i, value: name });
i = j;
continue;
}
if (char === "(") {
var count = 1;
var pattern = "";
var j = i + 1;
if (str[j] === "?") {
throw new TypeError('Pattern cannot start with "?" at '.concat(j));
}
while (j < str.length) {
if (str[j] === "\\") {
pattern += str[j++] + str[j++];
continue;
}
if (str[j] === ")") {
count--;
if (count === 0) {
j++;
break;
}
} else if (str[j] === "(") {
count++;
if (str[j + 1] !== "?") {
throw new TypeError("Capturing groups are not allowed at ".concat(j));
}
}
pattern += str[j++];
}
if (count)
throw new TypeError("Unbalanced pattern at ".concat(i));
if (!pattern)
throw new TypeError("Missing pattern at ".concat(i));
tokens.push({ type: "PATTERN", index: i, value: pattern });
i = j;
continue;
}
tokens.push({ type: "CHAR", index: i, value: str[i++] });
}
tokens.push({ type: "END", index: i, value: "" });
return tokens;
}
function parse(str, options) {
if (options === void 0) {
options = {};
}
var tokens = lexer(str);
var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a;
var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
var result = [];
var key = 0;
var i = 0;
var path = "";
var tryConsume = function(type) {
if (i < tokens.length && tokens[i].type === type)
return tokens[i++].value;
};
var mustConsume = function(type) {
var value2 = tryConsume(type);
if (value2 !== void 0)
return value2;
var _a2 = tokens[i], nextType = _a2.type, index = _a2.index;
throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
};
var consumeText = function() {
var result2 = "";
var value2;
while (value2 = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR")) {
result2 += value2;
}
return result2;
};
while (i < tokens.length) {
var char = tryConsume("CHAR");
var name = tryConsume("NAME");
var pattern = tryConsume("PATTERN");
if (name || pattern) {
var prefix = char || "";
if (prefixes.indexOf(prefix) === -1) {
path += prefix;
prefix = "";
}
if (path) {
result.push(path);
path = "";
}
result.push({
name: name || key++,
prefix,
suffix: "",
pattern: pattern || defaultPattern,
modifier: tryConsume("MODIFIER") || ""
});
continue;
}
var value = char || tryConsume("ESCAPED_CHAR");
if (value) {
path += value;
continue;
}
if (path) {
result.push(path);
path = "";
}
var open = tryConsume("OPEN");
if (open) {
var prefix = consumeText();
var name_1 = tryConsume("NAME") || "";
var pattern_1 = tryConsume("PATTERN") || "";
var suffix = consumeText();
mustConsume("CLOSE");
result.push({
name: name_1 || (pattern_1 ? key++ : ""),
pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
prefix,
suffix,
modifier: tryConsume("MODIFIER") || ""
});
continue;
}
mustConsume("END");
}
return result;
}
exports.parse = parse;
function compile(str, options) {
return tokensToFunction(parse(str, options), options);
}
exports.compile = compile;
function tokensToFunction(tokens, options) {
if (options === void 0) {
options = {};
}
var reFlags = flags(options);
var _a = options.encode, encode = _a === void 0 ? function(x) {
return x;
} : _a, _b = options.validate, validate = _b === void 0 ? true : _b;
var matches = tokens.map(function(token) {
if (typeof token === "object") {
return new RegExp("^(?:".concat(token.pattern, ")$"), reFlags);
}
});
return function(data) {
var path = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === "string") {
path += token;
continue;
}
var value = data ? data[token.name] : void 0;
var optional = token.modifier === "?" || token.modifier === "*";
var repeat = token.modifier === "*" || token.modifier === "+";
if (Array.isArray(value)) {
if (!repeat) {
throw new TypeError('Expected "'.concat(token.name, '" to not repeat, but got an array'));
}
if (value.length === 0) {
if (optional)
continue;
throw new TypeError('Expected "'.concat(token.name, '" to not be empty'));
}
for (var j = 0; j < value.length; j++) {
var segment = encode(value[j], token);
if (validate && !matches[i].test(segment)) {
throw new TypeError('Expected all "'.concat(token.name, '" to match "').concat(token.pattern, '", but got "').concat(segment, '"'));
}
path += token.prefix + segment + token.suffix;
}
continue;
}
if (typeof value === "string" || typeof value === "number") {
var segment = encode(String(value), token);
if (validate && !matches[i].test(segment)) {
throw new TypeError('Expected "'.concat(token.name, '" to match "').concat(token.pattern, '", but got "').concat(segment, '"'));
}
path += token.prefix + segment + token.suffix;
continue;
}
if (optional)
continue;
var typeOfMessage = repeat ? "an array" : "a string";
throw new TypeError('Expected "'.concat(token.name, '" to be ').concat(typeOfMessage));
}
return path;
};
}
exports.tokensToFunction = tokensToFunction;
function match(str, options) {
var keys = [];
var re = pathToRegexp2(str, keys, options);
return regexpToFunction(re, keys, options);
}
exports.match = match;
function regexpToFunction(re, keys, options) {
if (options === void 0) {
options = {};
}
var _a = options.decode, decode = _a === void 0 ? function(x) {
return x;
} : _a;
return function(pathname) {
var m = re.exec(pathname);
if (!m)
return false;
var path = m[0], index = m.index;
var params = /* @__PURE__ */ Object.create(null);
var _loop_1 = function(i2) {
if (m[i2] === void 0)
return "continue";
var key = keys[i2 - 1];
if (key.modifier === "*" || key.modifier === "+") {
params[key.name] = m[i2].split(key.prefix + key.suffix).map(function(value) {
return decode(value, key);
});
} else {
params[key.name] = decode(m[i2], key);
}
};
for (var i = 1; i < m.length; i++) {
_loop_1(i);
}
return { path, index, params };
};
}
exports.regexpToFunction = regexpToFunction;
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
}
function flags(options) {
return options && options.sensitive ? "" : "i";
}
function regexpToRegexp(path, keys) {
if (!keys)
return path;
var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
var index = 0;
var execResult = groupsRegex.exec(path.source);
while (execResult) {
keys.push({
// Use parenthesized substring match if available, index otherwise
name: execResult[1] || index++,
prefix: "",
suffix: "",
modifier: "",
pattern: ""
});
execResult = groupsRegex.exec(path.source);
}
return path;
}
function arrayToRegexp(paths, keys, options) {
var parts = paths.map(function(path) {
return pathToRegexp2(path, keys, options).source;
});
return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options));
}
function stringToRegexp(path, keys, options) {
return tokensToRegexp(parse(path, options), keys, options);
}
function tokensToRegexp(tokens, keys, options) {
if (options === void 0) {
options = {};
}
var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function(x) {
return x;
} : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
var delimiterRe = "[".concat(escapeString(delimiter), "]");
var route = start ? "^" : "";
for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
var token = tokens_1[_i];
if (typeof token === "string") {
route += escapeString(encode(token));
} else {
var prefix = escapeString(encode(token.prefix));
var suffix = escapeString(encode(token.suffix));
if (token.pattern) {
if (keys)
keys.push(token);
if (prefix || suffix) {
if (token.modifier === "+" || token.modifier === "*") {
var mod = token.modifier === "*" ? "?" : "";
route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod);
} else {
route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier);
}
} else {
if (token.modifier === "+" || token.modifier === "*") {
route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")");
} else {
route += "(".concat(token.pattern, ")").concat(token.modifier);
}
}
} else {
route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier);
}
}
}
if (end) {
if (!strict)
route += "".concat(delimiterRe, "?");
route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")");
} else {
var endToken = tokens[tokens.length - 1];
var isEndDelimited = typeof endToken === "string" ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1 : endToken === void 0;
if (!strict) {
route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?");
}
if (!isEndDelimited) {
route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")");
}
}
return new RegExp(route, flags(options));
}
exports.tokensToRegexp = tokensToRegexp;
function pathToRegexp2(path, keys, options) {
if (path instanceof RegExp)
return regexpToRegexp(path, keys);
if (Array.isArray(path))
return arrayToRegexp(path, keys, options);
return stringToRegexp(path, keys, options);
}
exports.pathToRegexp = pathToRegexp2;
}
});
// src/build/functions/edge.ts
var import_fast_glob = __toESM(require_out(), 1);
var import_path_to_regexp = __toESM(require_dist(), 1);
import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { EDGE_HANDLER_NAME } from "../plugin-context.js";
var writeEdgeManifest = async (ctx, manifest) => {
await mkdir(ctx.edgeFunctionsDir, { recursive: true });
await writeFile(join(ctx.edgeFunctionsDir, "manifest.json"), JSON.stringify(manifest, null, 2));
};
var copyRuntime = async (ctx, handlerDirectory) => {
const files = await (0, import_fast_glob.glob)("edge-runtime/**/*", {
cwd: ctx.pluginDir,
ignore: ["**/*.test.ts"],
dot: true
});
await Promise.all(
files.map(
(path) => cp(join(ctx.pluginDir, path), join(handlerDirectory, path), { recursive: true })
)
);
};
var augmentMatchers = (matchers, ctx) => {
if (!ctx.buildConfig.i18n) {
return matchers;
}
return matchers.flatMap((matcher) => {
if (matcher.originalSource && matcher.locale !== false) {
return [
matcher,
{
...matcher,
regexp: (0, import_path_to_regexp.pathToRegexp)(matcher.originalSource).source
}
];
}
return matcher;
});
};
var writeHandlerFile = async (ctx, { matchers, name }) => {
const nextConfig = ctx.buildConfig;
const handlerName = getHandlerName({ name });
const handlerDirectory = join(ctx.edgeFunctionsDir, handlerName);
const handlerRuntimeDirectory = join(handlerDirectory, "edge-runtime");
await copyRuntime(ctx, handlerDirectory);
await writeFile(
join(handlerRuntimeDirectory, "matchers.json"),
JSON.stringify(augmentMatchers(matchers, ctx))
);
const minimalNextConfig = {
basePath: nextConfig.basePath,
i18n: nextConfig.i18n,
trailingSlash: nextConfig.trailingSlash,
skipMiddlewareUrlNormalize: nextConfig.skipMiddlewareUrlNormalize
};
await writeFile(
join(handlerRuntimeDirectory, "next.config.json"),
JSON.stringify(minimalNextConfig)
);
await writeFile(
join(handlerDirectory, `${handlerName}.js`),
`
import {handleMiddleware} from './edge-runtime/middleware.ts';
import handler from './server/${name}.js';
export default (req, context) => handleMiddleware(req, context, handler);
`
);
};
var copyHandlerDependencies = async (ctx, { name, files, wasm }) => {
const srcDir = join(ctx.standaloneDir, ctx.nextDistDir);
const destDir = join(ctx.edgeFunctionsDir, getHandlerName({ name }));
const edgeRuntimeDir = join(ctx.pluginDir, "edge-runtime");
const shimPath = join(edgeRuntimeDir, "shim/index.js");
const shim = await readFile(shimPath, "utf8");
const parts = [shim];
if (wasm?.length) {
parts.push(
`import { decode as _base64Decode } from "../edge-runtime/vendor/deno.land/std@0.175.0/encoding/base64.ts";`
);
for (const wasmChunk of wasm ?? []) {
const data = await readFile(join(srcDir, wasmChunk.filePath));
parts.push(
`const ${wasmChunk.name} = _base64Decode(${JSON.stringify(
data.toString("base64")
)}).buffer`
);
}
}
for (const file of files) {
const entrypoint = await readFile(join(srcDir, file), "utf8");
parts.push(`;// Concatenated file: ${file}
`, entrypoint);
}
const exports = `export default _ENTRIES["middleware_${name}"].default;`;
await mkdir(dirname(join(destDir, `server/${name}.js`)), { recursive: true });
await writeFile(join(destDir, `server/${name}.js`), [...parts, exports].join("\n"));
};
var createEdgeHandler = async (ctx, definition) => {
await copyHandlerDependencies(ctx, definition);
await writeHandlerFile(ctx, definition);
};
var getHandlerName = ({ name }) => `${EDGE_HANDLER_NAME}-${name.replace(/\W/g, "-")}`;
var buildHandlerDefinition = (ctx, { name, matchers, page }) => {
const fun = getHandlerName({ name });
const funName = name.endsWith("middleware") ? "Next.js Middleware Handler" : `Next.js Edge Handler: ${page}`;
const cache = name.endsWith("middleware") ? void 0 : "manual";
const generator = `${ctx.pluginName}@${ctx.pluginVersion}`;
return augmentMatchers(matchers, ctx).map((matcher) => ({
function: fun,
name: funName,
pattern: matcher.regexp,
cache,
generator
}));
};
var createEdgeHandlers = async (ctx) => {
await rm(ctx.edgeFunctionsDir, { recursive: true, force: true });
const nextManifest = await ctx.getMiddlewareManifest();
const nextDefinitions = [
...Object.values(nextManifest.middleware)
// ...Object.values(nextManifest.functions)
];
await Promise.all(nextDefinitions.map((def) => createEdgeHandler(ctx, def)));
const netlifyDefinitions = nextDefinitions.flatMap((def) => buildHandlerDefinition(ctx, def));
const netlifyManifest = {
version: 1,
functions: netlifyDefinitions
};
await writeEdgeManifest(ctx, netlifyManifest);
};
export {
createEdgeHandlers
};

@@ -8,16 +8,135 @@

import {
createServerHandler
} from "../../esm-chunks/chunk-HESS57SH.js";
import "../../esm-chunks/chunk-4BNHE6TP.js";
import "../../esm-chunks/chunk-PDPDW32D.js";
import "../../esm-chunks/chunk-Y3K5Q6FP.js";
import "../../esm-chunks/chunk-VZNKO4OO.js";
import "../../esm-chunks/chunk-L6OM53B6.js";
import "../../esm-chunks/chunk-K7BTUM7O.js";
import "../../esm-chunks/chunk-PJG75HGC.js";
import "../../esm-chunks/chunk-BG455SFE.js";
import "../../esm-chunks/chunk-UYKENJEU.js";
import "../../esm-chunks/chunk-5JVNISGM.js";
require_out
} from "../../esm-chunks/chunk-VZNKO4OO.js";
import {
wrapTracer
} from "../../esm-chunks/chunk-PDPDW32D.js";
import {
init_esm,
trace
} from "../../esm-chunks/chunk-Y3K5Q6FP.js";
import {
__toESM
} from "../../esm-chunks/chunk-5JVNISGM.js";
// src/build/functions/server.ts
init_esm();
import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join, relative } from "node:path";
import { join as posixJoin } from "node:path/posix";
var import_fast_glob = __toESM(require_out(), 1);
import {
copyNextDependencies,
copyNextServerCode,
verifyHandlerDirStructure,
writeTagsManifest
} from "../content/server.js";
import { SERVER_HANDLER_NAME } from "../plugin-context.js";
var tracer = wrapTracer(trace.getTracer("Next runtime"));
var copyHandlerDependencies = async (ctx) => {
await tracer.withActiveSpan("copyHandlerDependencies", async (span) => {
const promises = [];
const { included_files: includedFiles = [] } = ctx.netlifyConfig.functions?.["*"] || {};
includedFiles.push(
posixJoin(ctx.relativeAppDir, ".env"),
posixJoin(ctx.relativeAppDir, ".env.production"),
posixJoin(ctx.relativeAppDir, ".env.local"),
posixJoin(ctx.relativeAppDir, ".env.production.local")
);
span.setAttribute("next.includedFiles", includedFiles.join(","));
const resolvedFiles = await Promise.all(
includedFiles.map((globPattern) => (0, import_fast_glob.glob)(globPattern, { cwd: process.cwd() }))
);
for (const filePath of resolvedFiles.flat()) {
promises.push(
cp(
join(process.cwd(), filePath),
// the serverHandlerDir is aware of the dist dir.
// The distDir must not be the package path therefore we need to rely on the
// serverHandlerDir instead of the serverHandlerRootDir
// therefore we need to remove the package path from the filePath
join(ctx.serverHandlerDir, relative(ctx.relativeAppDir, filePath)),
{
recursive: true,
force: true
}
)
);
}
const fileList = await (0, import_fast_glob.glob)("dist/**/*", { cwd: ctx.pluginDir });
for (const filePath of fileList) {
promises.push(
cp(join(ctx.pluginDir, filePath), join(ctx.serverHandlerDir, ".netlify", filePath), {
recursive: true,
force: true
})
);
}
await Promise.all(promises);
});
};
var writeHandlerManifest = async (ctx) => {
await writeFile(
join(ctx.serverHandlerRootDir, `${SERVER_HANDLER_NAME}.json`),
JSON.stringify({
config: {
name: "Next.js Server Handler",
generator: `${ctx.pluginName}@${ctx.pluginVersion}`,
nodeBundler: "none",
// the folders can vary in monorepos based on the folder structure of the user so we have to glob all
includedFiles: ["**"],
includedFilesBasePath: ctx.serverHandlerRootDir
},
version: 1
}),
"utf-8"
);
};
var writePackageMetadata = async (ctx) => {
await writeFile(
join(ctx.serverHandlerRootDir, "package.json"),
JSON.stringify({ type: "module" })
);
};
var applyTemplateVariables = (template, variables) => {
return Object.entries(variables).reduce((acc, [key, value]) => {
return acc.replaceAll(key, value);
}, template);
};
var getHandlerFile = async (ctx) => {
const templatesDir = join(ctx.pluginDir, "dist/build/templates");
const templateVariables = {
"{{useRegionalBlobs}}": ctx.useRegionalBlobs.toString()
};
if (ctx.relativeAppDir.length !== 0) {
const template = await readFile(join(templatesDir, "handler-monorepo.tmpl.js"), "utf-8");
templateVariables["{{cwd}}"] = posixJoin(ctx.lambdaWorkingDirectory);
templateVariables["{{nextServerHandler}}"] = posixJoin(ctx.nextServerHandler);
return applyTemplateVariables(template, templateVariables);
}
return applyTemplateVariables(
await readFile(join(templatesDir, "handler.tmpl.js"), "utf-8"),
templateVariables
);
};
var writeHandlerFile = async (ctx) => {
const handler = await getHandlerFile(ctx);
await writeFile(join(ctx.serverHandlerRootDir, `${SERVER_HANDLER_NAME}.mjs`), handler);
};
var createServerHandler = async (ctx) => {
await tracer.withActiveSpan("createServerHandler", async () => {
await rm(ctx.serverFunctionsDir, { recursive: true, force: true });
await mkdir(join(ctx.serverHandlerDir, ".netlify"), { recursive: true });
await copyNextServerCode(ctx);
await copyNextDependencies(ctx);
await writeTagsManifest(ctx);
await copyHandlerDependencies(ctx);
await writeHandlerManifest(ctx);
await writePackageMetadata(ctx);
await writeHandlerFile(ctx);
await verifyHandlerDirStructure(ctx);
});
};
export {
createServerHandler
};

@@ -8,7 +8,1630 @@

import {
setImageConfig
} from "../esm-chunks/chunk-MCEOSJH6.js";
import "../esm-chunks/chunk-5JVNISGM.js";
__commonJS,
__require,
__toESM
} from "../esm-chunks/chunk-5JVNISGM.js";
// node_modules/picomatch/lib/constants.js
var require_constants = __commonJS({
"node_modules/picomatch/lib/constants.js"(exports, module) {
"use strict";
var WIN_SLASH = "\\\\/";
var WIN_NO_SLASH = `[^${WIN_SLASH}]`;
var DOT_LITERAL = "\\.";
var PLUS_LITERAL = "\\+";
var QMARK_LITERAL = "\\?";
var SLASH_LITERAL = "\\/";
var ONE_CHAR = "(?=.)";
var QMARK = "[^/]";
var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
var START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
var NO_DOT = `(?!${DOT_LITERAL})`;
var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
var STAR = `${QMARK}*?`;
var SEP = "/";
var POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR,
SEP
};
var WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
SEP: "\\"
};
var POSIX_REGEX_SOURCE = {
alnum: "a-zA-Z0-9",
alpha: "a-zA-Z",
ascii: "\\x00-\\x7F",
blank: " \\t",
cntrl: "\\x00-\\x1F\\x7F",
digit: "0-9",
graph: "\\x21-\\x7E",
lower: "a-z",
print: "\\x20-\\x7E ",
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
space: " \\t\\r\\n\\v\\f",
upper: "A-Z",
word: "A-Za-z0-9_",
xdigit: "A-Fa-f0-9"
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
// Digits
CHAR_0: 48,
/* 0 */
CHAR_9: 57,
/* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65,
/* A */
CHAR_LOWERCASE_A: 97,
/* a */
CHAR_UPPERCASE_Z: 90,
/* Z */
CHAR_LOWERCASE_Z: 122,
/* z */
CHAR_LEFT_PARENTHESES: 40,
/* ( */
CHAR_RIGHT_PARENTHESES: 41,
/* ) */
CHAR_ASTERISK: 42,
/* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38,
/* & */
CHAR_AT: 64,
/* @ */
CHAR_BACKWARD_SLASH: 92,
/* \ */
CHAR_CARRIAGE_RETURN: 13,
/* \r */
CHAR_CIRCUMFLEX_ACCENT: 94,
/* ^ */
CHAR_COLON: 58,
/* : */
CHAR_COMMA: 44,
/* , */
CHAR_DOT: 46,
/* . */
CHAR_DOUBLE_QUOTE: 34,
/* " */
CHAR_EQUAL: 61,
/* = */
CHAR_EXCLAMATION_MARK: 33,
/* ! */
CHAR_FORM_FEED: 12,
/* \f */
CHAR_FORWARD_SLASH: 47,
/* / */
CHAR_GRAVE_ACCENT: 96,
/* ` */
CHAR_HASH: 35,
/* # */
CHAR_HYPHEN_MINUS: 45,
/* - */
CHAR_LEFT_ANGLE_BRACKET: 60,
/* < */
CHAR_LEFT_CURLY_BRACE: 123,
/* { */
CHAR_LEFT_SQUARE_BRACKET: 91,
/* [ */
CHAR_LINE_FEED: 10,
/* \n */
CHAR_NO_BREAK_SPACE: 160,
/* \u00A0 */
CHAR_PERCENT: 37,
/* % */
CHAR_PLUS: 43,
/* + */
CHAR_QUESTION_MARK: 63,
/* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62,
/* > */
CHAR_RIGHT_CURLY_BRACE: 125,
/* } */
CHAR_RIGHT_SQUARE_BRACKET: 93,
/* ] */
CHAR_SEMICOLON: 59,
/* ; */
CHAR_SINGLE_QUOTE: 39,
/* ' */
CHAR_SPACE: 32,
/* */
CHAR_TAB: 9,
/* \t */
CHAR_UNDERSCORE: 95,
/* _ */
CHAR_VERTICAL_LINE: 124,
/* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
/* \uFEFF */
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars) {
return {
"!": { type: "negate", open: "(?:(?!(?:", close: `))${chars.STAR})` },
"?": { type: "qmark", open: "(?:", close: ")?" },
"+": { type: "plus", open: "(?:", close: ")+" },
"*": { type: "star", open: "(?:", close: ")*" },
"@": { type: "at", open: "(?:", close: ")" }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
}
});
// node_modules/picomatch/lib/utils.js
var require_utils = __commonJS({
"node_modules/picomatch/lib/utils.js"(exports) {
"use strict";
var {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require_constants();
exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
exports.removeBackslashes = (str) => {
return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
return match === "\\" ? "" : match;
});
};
exports.supportsLookbehinds = () => {
if (typeof process !== "undefined") {
const segs = process.version.slice(1).split(".").map(Number);
if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
return true;
}
}
return false;
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1)
return input;
if (input[idx - 1] === "\\")
return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state.prefix = "./";
}
return output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
const prepend = options.contains ? "" : "^";
const append = options.contains ? "" : "$";
let output = `${prepend}(?:${input})${append}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
exports.basename = (path, { windows } = {}) => {
const segs = path.split(windows ? /[\\/]/ : "/");
const last = segs[segs.length - 1];
if (last === "") {
return segs[segs.length - 2];
}
return last;
};
}
});
// node_modules/picomatch/lib/scan.js
var require_scan = __commonJS({
"node_modules/picomatch/lib/scan.js"(exports, module) {
"use strict";
var utils = require_utils();
var {
CHAR_ASTERISK,
/* * */
CHAR_AT,
/* @ */
CHAR_BACKWARD_SLASH,
/* \ */
CHAR_COMMA,
/* , */
CHAR_DOT,
/* . */
CHAR_EXCLAMATION_MARK,
/* ! */
CHAR_FORWARD_SLASH,
/* / */
CHAR_LEFT_CURLY_BRACE,
/* { */
CHAR_LEFT_PARENTHESES,
/* ( */
CHAR_LEFT_SQUARE_BRACKET,
/* [ */
CHAR_PLUS,
/* + */
CHAR_QUESTION_MARK,
/* ? */
CHAR_RIGHT_CURLY_BRACE,
/* } */
CHAR_RIGHT_PARENTHESES,
/* ) */
CHAR_RIGHT_SQUARE_BRACKET
/* ] */
} = require_constants();
var isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
var depth = (token) => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
var scan = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = { value: "", depth: 0, isGlob: false };
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) {
braceEscaped = true;
}
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: "", depth: 0, isGlob: false };
if (finished === true)
continue;
if (prev === CHAR_DOT && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK)
isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
break;
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = "";
let glob = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = "";
glob = str;
} else {
base = str;
}
if (base && base !== "" && base !== "/" && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
base = base.slice(0, -1);
}
}
if (opts.unescape === true) {
if (glob)
glob = utils.removeBackslashes(glob);
if (base && backslashes === true) {
base = utils.removeBackslashes(base);
}
}
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== "") {
parts.push(value);
}
prevIndex = i;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan;
}
});
// node_modules/picomatch/lib/parse.js
var require_parse = __commonJS({
"node_modules/picomatch/lib/parse.js"(exports, module) {
"use strict";
var constants = require_constants();
var utils = require_utils();
var {
MAX_LENGTH,
POSIX_REGEX_SOURCE,
REGEX_NON_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_BACKREF,
REPLACEMENTS
} = constants;
var expandRange = (args, options) => {
if (typeof options.expandRange === "function") {
return options.expandRange(...args, options);
}
args.sort();
const value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch (ex) {
return args.map((v) => utils.escapeRegex(v)).join("..");
}
return value;
};
var syntaxError = (type, char) => {
return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
};
var parse = (input, options) => {
if (typeof input !== "string") {
throw new TypeError("Expected a string");
}
input = REPLACEMENTS[input] || input;
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
let len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
const bos = { type: "bos", value: "", output: opts.prepend || "" };
const tokens = [bos];
const capture = opts.capture ? "" : "?:";
const PLATFORM_CHARS = constants.globChars(opts.windows);
const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
const {
DOT_LITERAL,
PLUS_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK,
QMARK_NO_DOT,
STAR,
START_ANCHOR
} = PLATFORM_CHARS;
const globstar = (opts2) => {
return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
const nodot = opts.dot ? "" : NO_DOT;
const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
let star = opts.bash === true ? globstar(opts) : STAR;
if (opts.capture) {
star = `(${star})`;
}
if (typeof opts.noext === "boolean") {
opts.noextglob = opts.noext;
}
const state = {
input,
index: -1,
start: 0,
dot: opts.dot === true,
consumed: "",
output: "",
prefix: "",
backtrack: false,
negated: false,
brackets: 0,
braces: 0,
parens: 0,
quotes: 0,
globstar: false,
tokens
};
input = utils.removePrefix(input, state);
len = input.length;
const extglobs = [];
const braces = [];
const stack = [];
let prev = bos;
let value;
const eos = () => state.index === len - 1;
const peek = state.peek = (n = 1) => input[state.index + n];
const advance = state.advance = () => input[++state.index] || "";
const remaining = () => input.slice(state.index + 1);
const consume = (value2 = "", num = 0) => {
state.consumed += value2;
state.index += num;
};
const append = (token) => {
state.output += token.output != null ? token.output : token.value;
consume(token.value);
};
const negate = () => {
let count = 1;
while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
advance();
state.start++;
count++;
}
if (count % 2 === 0) {
return false;
}
state.negated = true;
state.start++;
return true;
};
const increment = (type) => {
state[type]++;
stack.push(type);
};
const decrement = (type) => {
state[type]--;
stack.pop();
};
const push = (tok) => {
if (prev.type === "globstar") {
const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
state.output = state.output.slice(0, -prev.output.length);
prev.type = "star";
prev.value = "*";
prev.output = star;
state.output += prev.output;
}
}
if (extglobs.length && tok.type !== "paren") {
extglobs[extglobs.length - 1].inner += tok.value;
}
if (tok.value || tok.output)
append(tok);
if (prev && prev.type === "text" && tok.type === "text") {
prev.value += tok.value;
prev.output = (prev.output || "") + tok.value;
return;
}
tok.prev = prev;
tokens.push(tok);
prev = tok;
};
const extglobOpen = (type, value2) => {
const token = { ...EXTGLOB_CHARS[value2], conditions: 1, inner: "" };
token.prev = prev;
token.parens = state.parens;
token.output = state.output;
const output = (opts.capture ? "(" : "") + token.open;
increment("parens");
push({ type, value: value2, output: state.output ? "" : ONE_CHAR });
push({ type: "paren", extglob: true, value: advance(), output });
extglobs.push(token);
};
const extglobClose = (token) => {
let output = token.close + (opts.capture ? ")" : "");
let rest;
if (token.type === "negate") {
let extglobStar = star;
if (token.inner && token.inner.length > 1 && token.inner.includes("/")) {
extglobStar = globstar(opts);
}
if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
output = token.close = `)$))${extglobStar}`;
}
if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
const expression = parse(rest, { ...options, fastpaths: false }).output;
output = token.close = `)${expression})${extglobStar})`;
}
if (token.prev.type === "bos") {
state.negatedExtglob = true;
}
}
push({ type: "paren", extglob: true, value, output });
decrement("parens");
};
if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
let backslashes = false;
let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
if (first === "\\") {
backslashes = true;
return m;
}
if (first === "?") {
if (esc) {
return esc + first + (rest ? QMARK.repeat(rest.length) : "");
}
if (index === 0) {
return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : "");
}
return QMARK.repeat(chars.length);
}
if (first === ".") {
return DOT_LITERAL.repeat(chars.length);
}
if (first === "*") {
if (esc) {
return esc + first + (rest ? star : "");
}
return star;
}
return esc ? m : `\\${m}`;
});
if (backslashes === true) {
if (opts.unescape === true) {
output = output.replace(/\\/g, "");
} else {
output = output.replace(/\\+/g, (m) => {
return m.length % 2 === 0 ? "\\\\" : m ? "\\" : "";
});
}
}
if (output === input && opts.contains === true) {
state.output = input;
return state;
}
state.output = utils.wrapOutput(output, state, options);
return state;
}
while (!eos()) {
value = advance();
if (value === "\0") {
continue;
}
if (value === "\\") {
const next = peek();
if (next === "/" && opts.bash !== true) {
continue;
}
if (next === "." || next === ";") {
continue;
}
if (!next) {
value += "\\";
push({ type: "text", value });
continue;
}
const match = /^\\+/.exec(remaining());
let slashes = 0;
if (match && match[0].length > 2) {
slashes = match[0].length;
state.index += slashes;
if (slashes % 2 !== 0) {
value += "\\";
}
}
if (opts.unescape === true) {
value = advance();
} else {
value += advance();
}
if (state.brackets === 0) {
push({ type: "text", value });
continue;
}
}
if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
if (opts.posix !== false && value === ":") {
const inner = prev.value.slice(1);
if (inner.includes("[")) {
prev.posix = true;
if (inner.includes(":")) {
const idx = prev.value.lastIndexOf("[");
const pre = prev.value.slice(0, idx);
const rest2 = prev.value.slice(idx + 2);
const posix = POSIX_REGEX_SOURCE[rest2];
if (posix) {
prev.value = pre + posix;
state.backtrack = true;
advance();
if (!bos.output && tokens.indexOf(prev) === 1) {
bos.output = ONE_CHAR;
}
continue;
}
}
}
}
if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") {
value = `\\${value}`;
}
if (value === "]" && (prev.value === "[" || prev.value === "[^")) {
value = `\\${value}`;
}
if (opts.posix === true && value === "!" && prev.value === "[") {
value = "^";
}
prev.value += value;
append({ value });
continue;
}
if (state.quotes === 1 && value !== '"') {
value = utils.escapeRegex(value);
prev.value += value;
append({ value });
continue;
}
if (value === '"') {
state.quotes = state.quotes === 1 ? 0 : 1;
if (opts.keepQuotes === true) {
push({ type: "text", value });
}
continue;
}
if (value === "(") {
increment("parens");
push({ type: "paren", value });
continue;
}
if (value === ")") {
if (state.parens === 0 && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "("));
}
const extglob = extglobs[extglobs.length - 1];
if (extglob && state.parens === extglob.parens + 1) {
extglobClose(extglobs.pop());
continue;
}
push({ type: "paren", value, output: state.parens ? ")" : "\\)" });
decrement("parens");
continue;
}
if (value === "[") {
if (opts.nobracket === true || !remaining().includes("]")) {
if (opts.nobracket !== true && opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("closing", "]"));
}
value = `\\${value}`;
} else {
increment("brackets");
}
push({ type: "bracket", value });
continue;
}
if (value === "]") {
if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
push({ type: "text", value, output: `\\${value}` });
continue;
}
if (state.brackets === 0) {
if (opts.strictBrackets === true) {
throw new SyntaxError(syntaxError("opening", "["));
}
push({ type: "text", value, output: `\\${value}` });
continue;
}
decrement("brackets");
const prevValue = prev.value.slice(1);
if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) {
value = `/${value}`;
}
prev.value += value;
append({ value });
if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
continue;
}
const escaped = utils.escapeRegex(prev.value);
state.output = state.output.slice(0, -prev.value.length);
if (opts.literalBrackets === true) {
state.output += escaped;
prev.value = escaped;
continue;
}
prev.value = `(${capture}${escaped}|${prev.value})`;
state.output += prev.value;
continue;
}
if (value === "{" && opts.nobrace !== true) {
increment("braces");
const open = {
type: "brace",
value,
output: "(",
outputIndex: state.output.length,
tokensIndex: state.tokens.length
};
braces.push(open);
push(open);
continue;
}
if (value === "}") {
const brace = braces[braces.length - 1];
if (opts.nobrace === true || !brace) {
push({ type: "text", value, output: value });
continue;
}
let output = ")";
if (brace.dots === true) {
const arr = tokens.slice();
const range = [];
for (let i = arr.length - 1; i >= 0; i--) {
tokens.pop();
if (arr[i].type === "brace") {
break;
}
if (arr[i].type !== "dots") {
range.unshift(arr[i].value);
}
}
output = expandRange(range, opts);
state.backtrack = true;
}
if (brace.comma !== true && brace.dots !== true) {
const out = state.output.slice(0, brace.outputIndex);
const toks = state.tokens.slice(brace.tokensIndex);
brace.value = brace.output = "\\{";
value = output = "\\}";
state.output = out;
for (const t of toks) {
state.output += t.output || t.value;
}
}
push({ type: "brace", value, output });
decrement("braces");
braces.pop();
continue;
}
if (value === "|") {
if (extglobs.length > 0) {
extglobs[extglobs.length - 1].conditions++;
}
push({ type: "text", value });
continue;
}
if (value === ",") {
let output = value;
const brace = braces[braces.length - 1];
if (brace && stack[stack.length - 1] === "braces") {
brace.comma = true;
output = "|";
}
push({ type: "comma", value, output });
continue;
}
if (value === "/") {
if (prev.type === "dot" && state.index === state.start + 1) {
state.start = state.index + 1;
state.consumed = "";
state.output = "";
tokens.pop();
prev = bos;
continue;
}
push({ type: "slash", value, output: SLASH_LITERAL });
continue;
}
if (value === ".") {
if (state.braces > 0 && prev.type === "dot") {
if (prev.value === ".")
prev.output = DOT_LITERAL;
const brace = braces[braces.length - 1];
prev.type = "dots";
prev.output += value;
prev.value += value;
brace.dots = true;
continue;
}
if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
push({ type: "text", value, output: DOT_LITERAL });
continue;
}
push({ type: "dot", value, output: DOT_LITERAL });
continue;
}
if (value === "?") {
const isGroup = prev && prev.value === "(";
if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("qmark", value);
continue;
}
if (prev && prev.type === "paren") {
const next = peek();
let output = value;
if (next === "<" && !utils.supportsLookbehinds()) {
throw new Error("Node.js v10 or higher is required for regex lookbehinds");
}
if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) {
output = `\\${value}`;
}
push({ type: "text", value, output });
continue;
}
if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
push({ type: "qmark", value, output: QMARK_NO_DOT });
continue;
}
push({ type: "qmark", value, output: QMARK });
continue;
}
if (value === "!") {
if (opts.noextglob !== true && peek() === "(") {
if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
extglobOpen("negate", value);
continue;
}
}
if (opts.nonegate !== true && state.index === 0) {
negate();
continue;
}
}
if (value === "+") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
extglobOpen("plus", value);
continue;
}
if (prev && prev.value === "(" || opts.regex === false) {
push({ type: "plus", value, output: PLUS_LITERAL });
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
push({ type: "plus", value });
continue;
}
push({ type: "plus", value: PLUS_LITERAL });
continue;
}
if (value === "@") {
if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
push({ type: "at", extglob: true, value, output: "" });
continue;
}
push({ type: "text", value });
continue;
}
if (value !== "*") {
if (value === "$" || value === "^") {
value = `\\${value}`;
}
const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
if (match) {
value += match[0];
state.index += match[0].length;
}
push({ type: "text", value });
continue;
}
if (prev && (prev.type === "globstar" || prev.star === true)) {
prev.type = "star";
prev.star = true;
prev.value += value;
prev.output = star;
state.backtrack = true;
state.globstar = true;
consume(value);
continue;
}
let rest = remaining();
if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
extglobOpen("star", value);
continue;
}
if (prev.type === "star") {
if (opts.noglobstar === true) {
consume(value);
continue;
}
const prior = prev.prev;
const before = prior.prev;
const isStart = prior.type === "slash" || prior.type === "bos";
const afterStar = before && (before.type === "star" || before.type === "globstar");
if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
push({ type: "star", value, output: "" });
continue;
}
const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
push({ type: "star", value, output: "" });
continue;
}
while (rest.slice(0, 3) === "/**") {
const after = input[state.index + 4];
if (after && after !== "/") {
break;
}
rest = rest.slice(3);
consume("/**", 3);
}
if (prior.type === "bos" && eos()) {
prev.type = "globstar";
prev.value += value;
prev.output = globstar(opts);
state.output = prev.output;
state.globstar = true;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
prev.value += value;
state.globstar = true;
state.output += prior.output + prev.output;
consume(value);
continue;
}
if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
const end = rest[1] !== void 0 ? "|$" : "";
state.output = state.output.slice(0, -(prior.output + prev.output).length);
prior.output = `(?:${prior.output}`;
prev.type = "globstar";
prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
prev.value += value;
state.output += prior.output + prev.output;
state.globstar = true;
consume(value + advance());
push({ type: "slash", value: "/", output: "" });
continue;
}
if (prior.type === "bos" && rest[0] === "/") {
prev.type = "globstar";
prev.value += value;
prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
state.output = prev.output;
state.globstar = true;
consume(value + advance());
push({ type: "slash", value: "/", output: "" });
continue;
}
state.output = state.output.slice(0, -prev.output.length);
prev.type = "globstar";
prev.output = globstar(opts);
prev.value += value;
state.output += prev.output;
state.globstar = true;
consume(value);
continue;
}
const token = { type: "star", value, output: star };
if (opts.bash === true) {
token.output = ".*?";
if (prev.type === "bos" || prev.type === "slash") {
token.output = nodot + token.output;
}
push(token);
continue;
}
if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
token.output = value;
push(token);
continue;
}
if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
if (prev.type === "dot") {
state.output += NO_DOT_SLASH;
prev.output += NO_DOT_SLASH;
} else if (opts.dot === true) {
state.output += NO_DOTS_SLASH;
prev.output += NO_DOTS_SLASH;
} else {
state.output += nodot;
prev.output += nodot;
}
if (peek() !== "*") {
state.output += ONE_CHAR;
prev.output += ONE_CHAR;
}
}
push(token);
}
while (state.brackets > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", "]"));
state.output = utils.escapeLast(state.output, "[");
decrement("brackets");
}
while (state.parens > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", ")"));
state.output = utils.escapeLast(state.output, "(");
decrement("parens");
}
while (state.braces > 0) {
if (opts.strictBrackets === true)
throw new SyntaxError(syntaxError("closing", "}"));
state.output = utils.escapeLast(state.output, "{");
decrement("braces");
}
if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) {
push({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL}?` });
}
if (state.backtrack === true) {
state.output = "";
for (const token of state.tokens) {
state.output += token.output != null ? token.output : token.value;
if (token.suffix) {
state.output += token.suffix;
}
}
}
return state;
};
parse.fastpaths = (input, options) => {
const opts = { ...options };
const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
const len = input.length;
if (len > max) {
throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
}
input = REPLACEMENTS[input] || input;
const {
DOT_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOTS_SLASH,
STAR,
START_ANCHOR
} = constants.globChars(opts.windows);
const nodot = opts.dot ? NO_DOTS : NO_DOT;
const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
const capture = opts.capture ? "" : "?:";
const state = { negated: false, prefix: "" };
let star = opts.bash === true ? ".*?" : STAR;
if (opts.capture) {
star = `(${star})`;
}
const globstar = (opts2) => {
if (opts2.noglobstar === true)
return star;
return `(${capture}(?:(?!${START_ANCHOR}${opts2.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
};
const create = (str) => {
switch (str) {
case "*":
return `${nodot}${ONE_CHAR}${star}`;
case ".*":
return `${DOT_LITERAL}${ONE_CHAR}${star}`;
case "*.*":
return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case "*/*":
return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
case "**":
return nodot + globstar(opts);
case "**/*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
case "**/*.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
case "**/.*":
return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
default: {
const match = /^(.*?)\.(\w+)$/.exec(str);
if (!match)
return;
const source2 = create(match[1]);
if (!source2)
return;
return source2 + DOT_LITERAL + match[2];
}
}
};
const output = utils.removePrefix(input, state);
let source = create(output);
if (source && opts.strictSlashes !== true) {
source += `${SLASH_LITERAL}?`;
}
return source;
};
module.exports = parse;
}
});
// node_modules/picomatch/lib/picomatch.js
var require_picomatch = __commonJS({
"node_modules/picomatch/lib/picomatch.js"(exports, module) {
"use strict";
var scan = require_scan();
var parse = require_parse();
var utils = require_utils();
var constants = require_constants();
var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
var picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map((input) => picomatch(input, options, returnState));
const arrayMatcher = (str) => {
for (const isMatch of fns) {
const state2 = isMatch(str);
if (state2)
return state2;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === "" || typeof glob !== "string" && !isState) {
throw new TypeError("Expected pattern to be a non-empty string");
}
const opts = options || {};
const posix = opts.windows;
const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
const result = { glob, state, regex, posix, input, output, match, isMatch };
if (typeof opts.onResult === "function") {
opts.onResult(result);
}
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === "function") {
opts.onIgnore(result);
}
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === "function") {
opts.onMatch(result);
}
return returnObject ? result : true;
};
if (returnState) {
matcher.state = state;
}
return matcher;
};
picomatch.test = (input, regex, options, { glob, posix } = {}) => {
if (typeof input !== "string") {
throw new TypeError("Expected input to be a string");
}
if (input === "") {
return { isMatch: false, output: "" };
}
const opts = options || {};
const format = opts.format || (posix ? utils.toPosixSlashes : null);
let match = input === glob;
let output = match && format ? format(input) : input;
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex, options, posix);
} else {
match = regex.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
picomatch.matchBase = (input, glob, options) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(utils.basename(input));
};
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern))
return pattern.map((p) => picomatch.parse(p, options));
return parse(pattern, { ...options, fastpaths: false });
};
picomatch.scan = (input, options) => scan(input, options);
picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
const opts = options || {};
const prepend = opts.contains ? "" : "^";
const append = opts.contains ? "" : "$";
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
const regex = picomatch.toRegex(source, options);
if (returnState === true) {
regex.state = state;
}
return regex;
};
picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== "string") {
throw new TypeError("Expected a non-empty string");
}
let parsed = { negated: false, fastpaths: true };
if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) {
parsed.output = parse.fastpaths(input, options);
}
if (!parsed.output) {
parsed = parse(input, options);
}
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
} catch (err) {
if (options && options.debug === true)
throw err;
return /$^/;
}
};
picomatch.constants = constants;
module.exports = picomatch;
}
});
// node_modules/picomatch/index.js
var require_picomatch2 = __commonJS({
"node_modules/picomatch/index.js"(exports, module) {
"use strict";
var os = __require("os");
var pico = require_picomatch();
var isWindows = os.platform() === "win32";
function picomatch(glob, options, returnState = false) {
if (options && (options.windows === null || options.windows === void 0)) {
options = { ...options, windows: isWindows };
}
return pico(glob, options, returnState);
}
module.exports = picomatch;
module.exports.test = pico.test;
module.exports.matchBase = pico.matchBase;
module.exports.isMatch = pico.isMatch;
module.exports.parse = pico.parse;
module.exports.scan = pico.scan;
module.exports.compileRe = pico.compileRe;
module.exports.toRegex = pico.toRegex;
module.exports.makeRe = pico.makeRe;
}
});
// src/build/image-cdn.ts
var import_picomatch = __toESM(require_picomatch2(), 1);
function generateRegexFromPattern(pattern) {
return (0, import_picomatch.makeRe)(pattern).source;
}
var setImageConfig = async (ctx) => {
const {
images: { domains, remotePatterns, path: imageEndpointPath, loader: imageLoader }
} = await ctx.buildConfig;
if (imageLoader !== "default") {
return;
}
ctx.netlifyConfig.redirects.push(
{
from: imageEndpointPath,
// w and q are too short to be used as params with id-length rule
// but we are forced to do so because of the next/image loader decides on their names
// eslint-disable-next-line id-length
query: { url: ":url", w: ":width", q: ":quality" },
to: "/.netlify/images?url=:url&w=:width&q=:quality",
status: 200
},
// when migrating from @netlify/plugin-nextjs@4 image redirect to ipx might be cached in the browser
{
from: "/_ipx/*",
// w and q are too short to be used as params with id-length rule
// but we are forced to do so because of the next/image loader decides on their names
// eslint-disable-next-line id-length
query: { url: ":url", w: ":width", q: ":quality" },
to: "/.netlify/images?url=:url&w=:width&q=:quality",
status: 200
}
);
if (remotePatterns?.length !== 0 || domains?.length !== 0) {
ctx.netlifyConfig.images ||= { remote_images: [] };
ctx.netlifyConfig.images.remote_images ||= [];
if (remotePatterns && remotePatterns.length !== 0) {
for (const remotePattern of remotePatterns) {
let { protocol, hostname, port, pathname } = remotePattern;
if (pathname) {
pathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
}
const combinedRemotePattern = `${protocol ?? "http?(s)"}://${hostname}${port ? `:${port}` : ""}${pathname ?? "/**"}`;
try {
ctx.netlifyConfig.images.remote_images.push(
generateRegexFromPattern(combinedRemotePattern)
);
} catch (error) {
ctx.failBuild(
`Failed to generate Image CDN remote image regex from Next.js remote pattern: ${JSON.stringify(
{ remotePattern, combinedRemotePattern },
null,
2
)}`,
error
);
}
}
}
if (domains && domains.length !== 0) {
for (const domain of domains) {
const patternFromDomain = `http?(s)://${domain}/**`;
try {
ctx.netlifyConfig.images.remote_images.push(generateRegexFromPattern(patternFromDomain));
} catch (error) {
ctx.failBuild(
`Failed to generate Image CDN remote image regex from Next.js domain: ${JSON.stringify(
{ domain, patternFromDomain },
null,
2
)}`,
error
);
}
}
}
}
};
export {
setImageConfig
};

@@ -7,8 +7,239 @@

import {
EDGE_HANDLER_NAME,
PluginContext,
SERVER_HANDLER_NAME
} from "../esm-chunks/chunk-L6OM53B6.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/build/plugin-context.ts
import { existsSync, readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
var MODULE_DIR = fileURLToPath(new URL(".", import.meta.url));
var PLUGIN_DIR = join(MODULE_DIR, "../..");
var DEFAULT_PUBLISH_DIR = ".next";
var SERVER_HANDLER_NAME = "___netlify-server-handler";
var EDGE_HANDLER_NAME = "___netlify-edge-handler";
var PluginContext = class {
utils;
netlifyConfig;
pluginName;
pluginVersion;
constants;
packageJSON;
/** Absolute path of the next runtime plugin directory */
pluginDir = PLUGIN_DIR;
get relPublishDir() {
return this.constants.PUBLISH_DIR ?? join(this.constants.PACKAGE_PATH || "", DEFAULT_PUBLISH_DIR);
}
/** Temporary directory for stashing the build output */
get tempPublishDir() {
return this.resolveFromPackagePath(".netlify/.next");
}
/** Absolute path of the publish directory */
get publishDir() {
return resolve(this.relPublishDir);
}
/**
* Relative package path in non monorepo setups this is an empty string
* This path is provided by Next.js RequiredServerFiles manifest
* @example ''
* @example 'apps/my-app'
*/
get relativeAppDir() {
return this.requiredServerFiles.relativeAppDir ?? "";
}
/**
* The working directory inside the lambda that is used for monorepos to execute the serverless function
*/
get lambdaWorkingDirectory() {
return join("/var/task", this.distDirParent);
}
/**
* Retrieves the root of the `.next/standalone` directory
*/
get standaloneRootDir() {
return join(this.publishDir, "standalone");
}
/**
* The resolved relative next dist directory defaults to `.next`,
* but can be configured through the next.config.js. For monorepos this will include the packagePath
* If we need just the plain dist dir use the `nextDistDir`
*/
get distDir() {
const dir = this.buildConfig.distDir ?? DEFAULT_PUBLISH_DIR;
return relative(process.cwd(), resolve(this.relativeAppDir, dir));
}
/** Represents the parent directory of the .next folder or custom distDir */
get distDirParent() {
return join(this.distDir, "..");
}
/** The `.next` folder or what the custom dist dir is set to */
get nextDistDir() {
return relative(this.distDirParent, this.distDir);
}
/** Retrieves the `.next/standalone/` directory monorepo aware */
get standaloneDir() {
return join(this.standaloneRootDir, this.distDirParent);
}
/**
* Absolute path of the directory that is published and deployed to the Netlify CDN
* Will be swapped with the publish directory
* `.netlify/static`
*/
get staticDir() {
return this.resolveFromPackagePath(".netlify/static");
}
/**
* Absolute path of the directory that will be deployed to the blob store
* region aware: `.netlify/deploy/v1/blobs/deploy`
* default: `.netlify/blobs/deploy`
*/
get blobDir() {
if (this.useRegionalBlobs) {
return this.resolveFromPackagePath(".netlify/deploy/v1/blobs/deploy");
}
return this.resolveFromPackagePath(".netlify/blobs/deploy");
}
get buildVersion() {
return this.constants.NETLIFY_BUILD_VERSION || "v0.0.0";
}
get useRegionalBlobs() {
return false;
}
/**
* Absolute path of the directory containing the files for the serverless lambda function
* `.netlify/functions-internal`
*/
get serverFunctionsDir() {
return this.resolveFromPackagePath(".netlify/functions-internal");
}
/** Absolute path of the server handler */
get serverHandlerRootDir() {
return join(this.serverFunctionsDir, SERVER_HANDLER_NAME);
}
get serverHandlerDir() {
if (this.relativeAppDir.length === 0) {
return this.serverHandlerRootDir;
}
return join(this.serverHandlerRootDir, this.distDirParent);
}
get nextServerHandler() {
if (this.relativeAppDir.length !== 0) {
return join(this.lambdaWorkingDirectory, ".netlify/dist/run/handlers/server.js");
}
return "./.netlify/dist/run/handlers/server.js";
}
/**
* Absolute path of the directory containing the files for deno edge functions
* `.netlify/edge-functions`
*/
get edgeFunctionsDir() {
return this.resolveFromPackagePath(".netlify/edge-functions");
}
/** Absolute path of the edge handler */
get edgeHandlerDir() {
return join(this.edgeFunctionsDir, EDGE_HANDLER_NAME);
}
constructor(options) {
this.packageJSON = JSON.parse(readFileSync(join(PLUGIN_DIR, "package.json"), "utf-8"));
this.pluginName = this.packageJSON.name;
this.pluginVersion = this.packageJSON.version;
this.constants = options.constants;
this.utils = options.utils;
this.netlifyConfig = options.netlifyConfig;
}
/** Resolves a path correctly with mono repository awareness for .netlify directories mainly */
resolveFromPackagePath(...args) {
return resolve(this.constants.PACKAGE_PATH || "", ...args);
}
/** Resolves a path correctly from site directory */
resolveFromSiteDir(...args) {
return resolve(this.requiredServerFiles.appDir, ...args);
}
/** Get the next prerender-manifest.json */
async getPrerenderManifest() {
return JSON.parse(await readFile(join(this.publishDir, "prerender-manifest.json"), "utf-8"));
}
/**
* Uses various heuristics to try to find the .next dir.
* Works by looking for BUILD_ID, so requires the site to have been built
*/
findDotNext() {
for (const dir of [
// The publish directory
this.publishDir,
// In the root
resolve(DEFAULT_PUBLISH_DIR),
// The sibling of the publish directory
resolve(this.publishDir, "..", DEFAULT_PUBLISH_DIR),
// In the package dir
resolve(this.constants.PACKAGE_PATH || "", DEFAULT_PUBLISH_DIR)
]) {
if (existsSync(join(dir, "BUILD_ID"))) {
return dir;
}
}
return false;
}
/**
* Get Next.js middleware config from the build output
*/
async getMiddlewareManifest() {
return JSON.parse(
await readFile(join(this.publishDir, "server/middleware-manifest.json"), "utf-8")
);
}
// don't make private as it is handy inside testing to override the config
_requiredServerFiles = null;
/** Get RequiredServerFiles manifest from build output **/
get requiredServerFiles() {
if (!this._requiredServerFiles) {
let requiredServerFilesJson = join(this.publishDir, "required-server-files.json");
if (!existsSync(requiredServerFilesJson)) {
const dotNext = this.findDotNext();
if (dotNext) {
requiredServerFilesJson = join(dotNext, "required-server-files.json");
}
}
this._requiredServerFiles = JSON.parse(
readFileSync(requiredServerFilesJson, "utf-8")
);
}
return this._requiredServerFiles;
}
#exportDetail = null;
/** Get metadata when output = export */
get exportDetail() {
if (this.buildConfig.output !== "export") {
return null;
}
if (!this.#exportDetail) {
const detailFile = join(
this.requiredServerFiles.appDir,
this.buildConfig.distDir,
"export-detail.json"
);
if (!existsSync(detailFile)) {
return null;
}
try {
this.#exportDetail = JSON.parse(readFileSync(detailFile, "utf-8"));
} catch {
}
}
return this.#exportDetail;
}
/** Get Next Config from build output **/
get buildConfig() {
return this.requiredServerFiles.config;
}
/**
* Get Next.js routes manifest from the build output
*/
async getRoutesManifest() {
return JSON.parse(await readFile(join(this.publishDir, "routes-manifest.json"), "utf-8"));
}
/** Fails a build with a message and an optional error */
failBuild(message, error) {
return this.utils.build.failBuild(message, error instanceof Error ? { error } : void 0);
}
};
export {

@@ -15,0 +246,0 @@ EDGE_HANDLER_NAME,

@@ -10,2 +10,5 @@ import {

// Set feature flag for regional blobs
process.env.USE_REGIONAL_BLOBS = '{{useRegionalBlobs}}'
let cachedHandler

@@ -12,0 +15,0 @@ export default async function (req, context) {

@@ -9,2 +9,5 @@ import {

// Set feature flag for regional blobs
process.env.USE_REGIONAL_BLOBS = '{{useRegionalBlobs}}'
export default async function handler(req, context) {

@@ -11,0 +14,0 @@ if (process.env.NETLIFY_OTLP_TRACE_EXPORTER_URL) {

@@ -8,10 +8,83 @@

import {
verifyBuildConfig,
verifyNextVersion,
verifyNoAdvancedAPIRoutes,
verifyPublishDir
} from "../esm-chunks/chunk-K7BTUM7O.js";
import "../esm-chunks/chunk-PJG75HGC.js";
import "../esm-chunks/chunk-BG455SFE.js";
import "../esm-chunks/chunk-5JVNISGM.js";
require_semver
} from "../esm-chunks/chunk-PJG75HGC.js";
import {
__toESM
} from "../esm-chunks/chunk-5JVNISGM.js";
// src/build/verification.ts
var import_semver = __toESM(require_semver(), 1);
import { existsSync } from "node:fs";
import { join } from "node:path";
import { ApiRouteType, getAPIRoutesConfigs } from "./advanced-api-routes.js";
var SUPPORTED_NEXT_VERSIONS = ">=13.5.0";
function verifyPublishDir(ctx) {
if (!existsSync(ctx.publishDir)) {
ctx.failBuild(
`Your publish directory was not found at: ${ctx.publishDir}. Please check your build settings`
);
}
if (ctx.publishDir === ctx.resolveFromPackagePath("")) {
ctx.failBuild(
`Your publish directory cannot be the same as the base directory of your site. Please check your build settings`
);
}
try {
ctx.buildConfig;
} catch {
ctx.failBuild(
"Your publish directory does not contain expected Next.js build output. Please check your build settings"
);
}
if (ctx.buildConfig.output === "standalone" || ctx.buildConfig.output === void 0) {
if (!existsSync(join(ctx.publishDir, "BUILD_ID"))) {
ctx.failBuild(
"Your publish directory does not contain expected Next.js build output. Please check your build settings"
);
}
if (!existsSync(ctx.standaloneRootDir)) {
ctx.failBuild(
`Your publish directory does not contain expected Next.js build output. Please make sure you are using Next.js version (${SUPPORTED_NEXT_VERSIONS})`
);
}
}
if (ctx.buildConfig.output === "export") {
if (!ctx.exportDetail?.success) {
ctx.failBuild(`Your export failed to build. Please check your build settings`);
}
if (!existsSync(ctx.exportDetail?.outDirectory)) {
ctx.failBuild(
`Your export directory was not found at: ${ctx.exportDetail?.outDirectory}. Please check your build settings`
);
}
}
}
function verifyNextVersion(ctx, nextVersion) {
if (!(0, import_semver.satisfies)(nextVersion, SUPPORTED_NEXT_VERSIONS, { includePrerelease: true })) {
ctx.failBuild(
`@netlify/plugin-next@5 requires Next.js version ${SUPPORTED_NEXT_VERSIONS}, but found ${nextVersion}. Please upgrade your project's Next.js version.`
);
}
}
function verifyBuildConfig(ctx) {
if (ctx.buildConfig.experimental.ppr) {
console.log(
`Partial prerendering is not yet fully supported on Netlify, see https://ntl.fyi/nextjs-ppr for details`
);
}
}
async function verifyNoAdvancedAPIRoutes(ctx) {
const apiRoutesConfigs = await getAPIRoutesConfigs(ctx);
const unsupportedAPIRoutes = apiRoutesConfigs.filter((apiRouteConfig) => {
return apiRouteConfig.config.type === ApiRouteType.BACKGROUND || apiRouteConfig.config.type === ApiRouteType.SCHEDULED;
});
if (unsupportedAPIRoutes.length !== 0) {
ctx.failBuild(
`@netlify/plugin-next@5 does not support advanced API routes. The following API routes should be migrated to Netlify background or scheduled functions:
${unsupportedAPIRoutes.map((apiRouteConfig) => ` - ${apiRouteConfig.apiRoute} (type: "${apiRouteConfig.config.type}")`).join("\n")}
Refer to https://ntl.fyi/next-scheduled-bg-function-migration as migration example.`
);
}
}
export {

@@ -18,0 +91,0 @@ verifyBuildConfig,

61

dist/index.js

@@ -8,8 +8,15 @@

import {
createServerHandler
} from "./esm-chunks/chunk-HESS57SH.js";
wrapTracer
} from "./esm-chunks/chunk-PDPDW32D.js";
import {
copyPrerenderedContent
} from "./esm-chunks/chunk-MRD3XSKD.js";
import "./esm-chunks/chunk-4BNHE6TP.js";
init_esm,
trace
} from "./esm-chunks/chunk-Y3K5Q6FP.js";
import "./esm-chunks/chunk-5JVNISGM.js";
// src/index.ts
init_esm();
import { rm } from "fs/promises";
import { restoreBuildCache, saveBuildCache } from "./build/cache.js";
import { copyPrerenderedContent } from "./build/content/prerendered.js";
import {

@@ -21,38 +28,19 @@ copyStaticAssets,

unpublishStaticDir
} from "./esm-chunks/chunk-V2T6NUOM.js";
import "./esm-chunks/chunk-TYCYFZ22.js";
} from "./build/content/static.js";
import { createEdgeHandlers } from "./build/functions/edge.js";
import { createServerHandler } from "./build/functions/server.js";
import { setImageConfig } from "./build/image-cdn.js";
import { PluginContext } from "./build/plugin-context.js";
import {
wrapTracer
} from "./esm-chunks/chunk-PDPDW32D.js";
import {
init_esm,
trace
} from "./esm-chunks/chunk-Y3K5Q6FP.js";
import {
createEdgeHandlers
} from "./esm-chunks/chunk-UTQSBE5O.js";
import "./esm-chunks/chunk-VZNKO4OO.js";
import {
restoreBuildCache,
saveBuildCache
} from "./esm-chunks/chunk-72ZI2IVI.js";
import {
setImageConfig
} from "./esm-chunks/chunk-MCEOSJH6.js";
import {
PluginContext
} from "./esm-chunks/chunk-L6OM53B6.js";
import {
verifyBuildConfig,
verifyNoAdvancedAPIRoutes,
verifyPublishDir
} from "./esm-chunks/chunk-K7BTUM7O.js";
import "./esm-chunks/chunk-PJG75HGC.js";
import "./esm-chunks/chunk-BG455SFE.js";
import "./esm-chunks/chunk-UYKENJEU.js";
import "./esm-chunks/chunk-5JVNISGM.js";
// src/index.ts
init_esm();
} from "./build/verification.js";
var tracer = wrapTracer(trace.getTracer("Next.js runtime"));
var onPreDev = async (options) => {
await tracer.withActiveSpan("onPreDev", async () => {
const context = new PluginContext(options);
await rm(context.blobDir, { recursive: true, force: true });
});
};
var onPreBuild = async (options) => {

@@ -113,3 +101,4 @@ await tracer.withActiveSpan("onPreBuild", async () => {

onPreBuild,
onPreDev,
onSuccess
};

@@ -7,9 +7,28 @@

import {
getRunConfig,
getTagsManifest,
setRunConfig
} from "../esm-chunks/chunk-3SUDZQ7L.js";
import "../esm-chunks/chunk-UYKENJEU.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/run/config.ts
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { PLUGIN_DIR, RUN_CONFIG } from "./constants.js";
var getRunConfig = async () => {
return JSON.parse(await readFile(resolve(PLUGIN_DIR, RUN_CONFIG), "utf-8"));
};
var setRunConfig = (config) => {
const cacheHandler = join(PLUGIN_DIR, ".netlify/dist/run/handlers/cache.cjs");
if (!existsSync(cacheHandler)) {
throw new Error(`Cache handler not found at ${cacheHandler}`);
}
config.experimental = {
...config.experimental,
incrementalCacheHandlerPath: cacheHandler
};
config.cacheHandler = cacheHandler;
config.cacheMaxMemorySize = 0;
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(config);
};
var getTagsManifest = async () => {
return JSON.parse(await readFile(resolve(PLUGIN_DIR, ".netlify/tags-manifest.json"), "utf-8"));
};
export {

@@ -16,0 +35,0 @@ getRunConfig,

@@ -7,8 +7,10 @@

import {
MODULE_DIR,
PLUGIN_DIR,
RUN_CONFIG
} from "../esm-chunks/chunk-UYKENJEU.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/run/constants.ts
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
var MODULE_DIR = fileURLToPath(new URL(".", import.meta.url));
var PLUGIN_DIR = resolve(`${MODULE_DIR}../../..`);
var RUN_CONFIG = "run-config.json";
export {

@@ -15,0 +17,0 @@ MODULE_DIR,

@@ -7,11 +7,201 @@

import {
adjustDateHeader,
setCacheControlHeaders,
setCacheStatusHeader,
setCacheTagsHeaders,
setVaryHeaders
} from "../esm-chunks/chunk-PMRBBOBY.js";
import "../esm-chunks/chunk-TYCYFZ22.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/run/headers.ts
import { encodeBlobKey } from "../shared/blobkey.js";
import { getRegionalBlobStore } from "./regional-blob-store.cjs";
var ALL_VARIATIONS = Symbol.for("ALL_VARIATIONS");
var NetlifyVaryKeys = /* @__PURE__ */ new Set(["header", "language", "cookie", "query", "country"]);
var isNetlifyVaryKey = (key) => NetlifyVaryKeys.has(key);
var generateNetlifyVaryValues = ({
header,
language,
cookie,
query,
country
}) => {
const values = [];
if (query.length !== 0) {
if (query.includes(ALL_VARIATIONS)) {
values.push(`query`);
} else {
values.push(`query=${query.join(`|`)}`);
}
}
if (header.length !== 0) {
values.push(`header=${header.join(`|`)}`);
}
if (language.length !== 0) {
values.push(`language=${language.join(`|`)}`);
}
if (cookie.length !== 0) {
values.push(`cookie=${cookie.join(`|`)}`);
}
if (country.length !== 0) {
values.push(`country=${country.join(`|`)}`);
}
return values.join(",");
};
var getHeaderValueArray = (header) => {
return header.split(",").map((value) => value.trim());
};
var omitHeaderValues = (header, values) => {
const headerValues = getHeaderValueArray(header);
const filteredValues = headerValues.filter(
(value) => !values.some((val) => value.startsWith(val))
);
return filteredValues.join(", ");
};
var mapHeaderValues = (header, callback) => {
const headerValues = getHeaderValueArray(header);
const mappedValues = headerValues.map(callback);
return mappedValues.join(", ");
};
var setVaryHeaders = (headers, request, { basePath, i18n }) => {
const netlifyVaryValues = {
header: ["x-nextjs-data"],
language: [],
cookie: ["__prerender_bypass", "__next_preview_data"],
query: [],
country: []
};
const vary = headers.get("vary");
if (vary !== null) {
netlifyVaryValues.header.push(...getHeaderValueArray(vary));
}
const path = new URL(request.url).pathname;
const locales = i18n && i18n.localeDetection !== false ? i18n.locales : [];
if (locales.length > 1 && (path === "/" || path === basePath)) {
netlifyVaryValues.language.push(...locales);
netlifyVaryValues.cookie.push(`NEXT_LOCALE`);
}
const userNetlifyVary = headers.get("netlify-vary");
if (userNetlifyVary) {
const directives = getHeaderValueArray(userNetlifyVary);
for (const directive of directives) {
const [key, value] = directive.split("=");
if (key === "query" && !value) {
netlifyVaryValues.query.push(ALL_VARIATIONS);
} else if (value && isNetlifyVaryKey(key)) {
netlifyVaryValues[key].push(...value.split("|"));
}
}
}
headers.set(`netlify-vary`, generateNetlifyVaryValues(netlifyVaryValues));
};
var adjustDateHeader = async ({
headers,
request,
span,
tracer,
requestContext
}) => {
const cacheState = headers.get("x-nextjs-cache");
const isServedFromCache = cacheState === "HIT" || cacheState === "STALE";
span.setAttributes({
"x-nextjs-cache": cacheState ?? void 0,
isServedFromCache
});
if (!isServedFromCache) {
return;
}
const key = new URL(request.url).pathname;
let lastModified;
if (requestContext.responseCacheGetLastModified) {
lastModified = requestContext.responseCacheGetLastModified;
} else {
span.recordException(
new Error("lastModified not found in requestContext, falling back to trying blobs")
);
span.setAttributes({
severity: "alert",
warning: true
});
const blobStore = getRegionalBlobStore({ consistency: "strong" });
const blobKey = await encodeBlobKey(key);
lastModified = await tracer.withActiveSpan(
"get cache to calculate date header",
async (getBlobForDateSpan) => {
getBlobForDateSpan.setAttributes({
key,
blobKey
});
const blob = await blobStore.get(blobKey, { type: "json" }) ?? {};
getBlobForDateSpan.addEvent(blob ? "Cache hit" : "Cache miss");
return blob.lastModified;
}
);
}
if (!lastModified) {
span.recordException(
new Error(
"lastModified not found in either requestContext or blobs, date header for cached response is not set"
)
);
span.setAttributes({
severity: "alert",
warning: true
});
return;
}
const lastModifiedDate = new Date(lastModified);
headers.set("x-nextjs-date", headers.get("date") ?? lastModifiedDate.toUTCString());
headers.set("date", lastModifiedDate.toUTCString());
};
var setCacheControlHeaders = (headers, request, requestContext) => {
if (typeof requestContext.routeHandlerRevalidate !== "undefined" && ["GET", "HEAD"].includes(request.method) && !headers.has("cdn-cache-control") && !headers.has("netlify-cdn-cache-control")) {
const cdnCacheControl = (
// if we are serving already stale response, instruct edge to not attempt to cache that response
headers.get("x-nextjs-cache") === "STALE" ? "public, max-age=0, must-revalidate" : `s-maxage=${requestContext.routeHandlerRevalidate === false ? 31536e3 : requestContext.routeHandlerRevalidate}, stale-while-revalidate=31536000`
);
headers.set("netlify-cdn-cache-control", cdnCacheControl);
return;
}
const cacheControl = headers.get("cache-control");
if (cacheControl !== null && ["GET", "HEAD"].includes(request.method) && !headers.has("cdn-cache-control") && !headers.has("netlify-cdn-cache-control")) {
const browserCacheControl = omitHeaderValues(cacheControl, [
"s-maxage",
"stale-while-revalidate"
]);
const cdnCacheControl = (
// if we are serving already stale response, instruct edge to not attempt to cache that response
headers.get("x-nextjs-cache") === "STALE" ? "public, max-age=0, must-revalidate" : mapHeaderValues(
cacheControl,
(value) => value === "stale-while-revalidate" ? "stale-while-revalidate=31536000" : value
)
);
headers.set("cache-control", browserCacheControl || "public, max-age=0, must-revalidate");
headers.set("netlify-cdn-cache-control", cdnCacheControl);
return;
}
if (cacheControl === null && !headers.has("cdn-cache-control") && !headers.has("netlify-cdn-cache-control") && requestContext.usedFsRead) {
headers.set("cache-control", "public, max-age=0, must-revalidate");
headers.set("netlify-cdn-cache-control", `max-age=31536000`);
}
};
function getCanonicalPathFromCacheKey(cacheKey) {
return cacheKey === "/index" ? "/" : cacheKey;
}
var setCacheTagsHeaders = (headers, request, manifest, requestContext) => {
const path = getCanonicalPathFromCacheKey(requestContext.responseCacheKey) ?? new URL(request.url).pathname;
const tags = manifest[path];
if (tags !== void 0) {
headers.set("netlify-cache-tag", tags);
}
};
var NEXT_CACHE_TO_CACHE_STATUS = {
HIT: `hit`,
MISS: `fwd=miss`,
STALE: `hit; fwd=stale`
};
var setCacheStatusHeader = (headers) => {
const nextCache = headers.get("x-nextjs-cache");
if (typeof nextCache === "string") {
if (nextCache in NEXT_CACHE_TO_CACHE_STATUS) {
const cacheStatus = NEXT_CACHE_TO_CACHE_STATUS[nextCache];
headers.set("cache-status", `"Next.js"; ${cacheStatus}`);
}
headers.delete("x-nextjs-cache");
}
};
export {

@@ -18,0 +208,0 @@ adjustDateHeader,

@@ -7,8 +7,22 @@

import {
nextResponseProxy
} from "../esm-chunks/chunk-RL4K4CVH.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/run/revalidate.ts
var nextResponseProxy = (res, requestContext) => {
return new Proxy(res, {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get(target, key) {
const originalValue = target[key];
if (key === "revalidate") {
return async function newRevalidate(...args) {
requestContext.didPagesRouterOnDemandRevalidate = true;
return originalValue?.apply(target, args);
};
}
return originalValue;
}
});
};
export {
nextResponseProxy
};

@@ -8,5 +8,96 @@

import {
import_internal
} from "../esm-chunks/chunk-HYBEXB2Z.js";
import "../esm-chunks/chunk-5JVNISGM.js";
__commonJS,
__require,
__toESM
} from "../esm-chunks/chunk-5JVNISGM.js";
// node_modules/@netlify/functions/dist/lib/system_logger.js
var require_system_logger = __commonJS({
"node_modules/@netlify/functions/dist/lib/system_logger.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.systemLogger = exports.LogLevel = void 0;
var process_1 = __require("process");
var systemLogTag = "__nfSystemLog";
var serializeError = (error) => {
const cause = error?.cause instanceof Error ? serializeError(error.cause) : error.cause;
return {
error: error.message,
error_cause: cause,
error_stack: error.stack
};
};
var LogLevel2;
(function(LogLevel3) {
LogLevel3[LogLevel3["Debug"] = 1] = "Debug";
LogLevel3[LogLevel3["Log"] = 2] = "Log";
LogLevel3[LogLevel3["Error"] = 3] = "Error";
})(LogLevel2 = exports.LogLevel || (exports.LogLevel = {}));
var SystemLogger = class _SystemLogger {
fields;
logLevel;
constructor(fields = {}, logLevel = LogLevel2.Log) {
this.fields = fields;
this.logLevel = logLevel;
}
doLog(logger, message) {
if (process_1.env.NETLIFY_DEV && !process_1.env.NETLIFY_ENABLE_SYSTEM_LOGGING) {
return;
}
logger(systemLogTag, JSON.stringify({ msg: message, fields: this.fields }));
}
log(message) {
if (this.logLevel > LogLevel2.Log) {
return;
}
this.doLog(console.log, message);
}
debug(message) {
if (this.logLevel > LogLevel2.Debug) {
return;
}
this.doLog(console.debug, message);
}
error(message) {
if (this.logLevel > LogLevel2.Error) {
return;
}
this.doLog(console.error, message);
}
withLogLevel(level) {
return new _SystemLogger(this.fields, level);
}
withFields(fields) {
return new _SystemLogger({
...this.fields,
...fields
}, this.logLevel);
}
withError(error) {
const fields = error instanceof Error ? serializeError(error) : { error };
return this.withFields(fields);
}
};
exports.systemLogger = new SystemLogger();
}
});
// node_modules/@netlify/functions/dist/internal.js
var require_internal = __commonJS({
"node_modules/@netlify/functions/dist/internal.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogLevel = exports.systemLogger = void 0;
var system_logger_js_1 = require_system_logger();
Object.defineProperty(exports, "systemLogger", { enumerable: true, get: function() {
return system_logger_js_1.systemLogger;
} });
Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
return system_logger_js_1.LogLevel;
} });
}
});
// src/run/systemlog.ts
var import_internal = __toESM(require_internal(), 1);
var export_LogLevel = import_internal.LogLevel;

@@ -13,0 +104,0 @@ var export_logger = import_internal.systemLogger;

@@ -7,8 +7,20 @@

import {
encodeBlobKey
} from "../esm-chunks/chunk-TYCYFZ22.js";
import "../esm-chunks/chunk-5JVNISGM.js";
// src/shared/blobkey.ts
import { Buffer } from "node:buffer";
import { webcrypto as crypto } from "node:crypto";
var maxLength = 180;
async function encodeBlobKey(key) {
const buffer = Buffer.from(key);
const base64 = buffer.toString("base64url");
if (base64.length <= maxLength) {
return base64;
}
const digest = await crypto.subtle.digest("SHA-256", buffer);
const hash = Buffer.from(digest).toString("base64url");
return `${base64.slice(0, maxLength - hash.length - 1)}-${hash}`;
}
export {
encodeBlobKey
};
{
"name": "@netlify/plugin-nextjs",
"version": "5.1.2",
"version": "5.2.0",
"description": "Run Next.js seamlessly on Netlify",

@@ -5,0 +5,0 @@ "main": "./dist/index.js",

Sorry, the diff of this file is not supported yet

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

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc