create project

This commit is contained in:
ismailsosic
2022-12-27 12:05:56 +01:00
parent 2a33a2d3de
commit cd2143287c
16035 changed files with 2489703 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
import curry from "next/dist/compiled/lodash.curry";
import { COMPILER_NAMES } from "../../../../shared/lib/constants";
export const base = curry(function base(ctx, config) {
config.mode = ctx.isDevelopment ? "development" : "production";
config.name = ctx.isServer ? ctx.isEdgeRuntime ? COMPILER_NAMES.edgeServer : COMPILER_NAMES.server : COMPILER_NAMES.client;
// @ts-ignore TODO webpack 5 typings
config.target = !ctx.targetWeb ? "node12.22" : ctx.isEdgeRuntime ? [
"web",
"es6"
] : [
"web",
"es5"
];
// https://webpack.js.org/configuration/devtool/#development
if (ctx.isDevelopment) {
if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) {
config.devtool = false;
} else {
// `eval-source-map` provides full-fidelity source maps for the
// original source, including columns and original variable names.
// This is desirable so the in-browser debugger can correctly pause
// and show scoped variables with their original names.
config.devtool = "eval-source-map";
}
} else {
if (ctx.isEdgeRuntime || // Enable browser sourcemaps:
(ctx.productionBrowserSourceMaps && ctx.isClient)) {
config.devtool = "source-map";
} else {
config.devtool = false;
}
}
if (!config.module) {
config.module = {
rules: []
};
}
// TODO: add codemod for "Should not import the named export" with JSON files
// config.module.strictExportPresence = !isWebpack5
return config;
});
//# sourceMappingURL=base.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/config/blocks/base.ts"],"names":["curry","COMPILER_NAMES","base","ctx","config","mode","isDevelopment","name","isServer","isEdgeRuntime","edgeServer","server","client","target","targetWeb","process","env","__NEXT_TEST_MODE","__NEXT_TEST_WITH_DEVTOOL","devtool","productionBrowserSourceMaps","isClient","module","rules"],"mappings":"AAAA,OAAOA,KAAK,MAAM,iCAAiC,CAAA;AAEnD,SAASC,cAAc,QAAQ,kCAAkC,CAAA;AAGjE,OAAO,MAAMC,IAAI,GAAGF,KAAK,CAAC,SAASE,IAAI,CACrCC,GAAyB,EACzBC,MAA6B,EAC7B;IACAA,MAAM,CAACC,IAAI,GAAGF,GAAG,CAACG,aAAa,GAAG,aAAa,GAAG,YAAY;IAC9DF,MAAM,CAACG,IAAI,GAAGJ,GAAG,CAACK,QAAQ,GACtBL,GAAG,CAACM,aAAa,GACfR,cAAc,CAACS,UAAU,GACzBT,cAAc,CAACU,MAAM,GACvBV,cAAc,CAACW,MAAM;IAEzB,oCAAoC;IACpCR,MAAM,CAACS,MAAM,GAAG,CAACV,GAAG,CAACW,SAAS,GAC1B,WAAW,GACXX,GAAG,CAACM,aAAa,GACjB;QAAC,KAAK;QAAE,KAAK;KAAC,GACd;QAAC,KAAK;QAAE,KAAK;KAAC;IAElB,4DAA4D;IAC5D,IAAIN,GAAG,CAACG,aAAa,EAAE;QACrB,IAAIS,OAAO,CAACC,GAAG,CAACC,gBAAgB,IAAI,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB,EAAE;YACzEd,MAAM,CAACe,OAAO,GAAG,KAAK;SACvB,MAAM;YACL,+DAA+D;YAC/D,kEAAkE;YAClE,mEAAmE;YACnE,uDAAuD;YACvDf,MAAM,CAACe,OAAO,GAAG,iBAAiB;SACnC;KACF,MAAM;QACL,IACEhB,GAAG,CAACM,aAAa,IACjB,6BAA6B;QAC7B,CAACN,GAAG,CAACiB,2BAA2B,IAAIjB,GAAG,CAACkB,QAAQ,CAAC,EACjD;YACAjB,MAAM,CAACe,OAAO,GAAG,YAAY;SAC9B,MAAM;YACLf,MAAM,CAACe,OAAO,GAAG,KAAK;SACvB;KACF;IAED,IAAI,CAACf,MAAM,CAACkB,MAAM,EAAE;QAClBlB,MAAM,CAACkB,MAAM,GAAG;YAAEC,KAAK,EAAE,EAAE;SAAE;KAC9B;IAED,6EAA6E;IAC7E,mDAAmD;IAEnD,OAAOnB,MAAM,CAAA;CACd,CAAC,CAAA"}

View File

@@ -0,0 +1,474 @@
import path from "path";
import curry from "next/dist/compiled/lodash.curry";
import { loader, plugin } from "../../helpers";
import { pipe } from "../../utils";
import { getCssModuleLoader, getGlobalCssLoader } from "./loaders";
import { getNextFontLoader } from "./loaders/next-font";
import { getCustomDocumentError, getGlobalImportError, getGlobalModuleImportError, getLocalModuleImportError } from "./messages";
import { getPostCssPlugins } from "./plugins";
import { nonNullable } from "../../../../../lib/non-nullable";
import { WEBPACK_LAYERS } from "../../../../../lib/constants";
// RegExps for all Style Sheet variants
export const regexLikeCss = /\.(css|scss|sass)$/;
// RegExps for Style Sheets
const regexCssGlobal = /(?<!\.module)\.css$/;
const regexCssModules = /\.module\.css$/;
// RegExps for Syntactically Awesome Style Sheets
const regexSassGlobal = /(?<!\.module)\.(scss|sass)$/;
const regexSassModules = /\.module\.(scss|sass)$/;
/**
* Mark a rule as removable if built-in CSS support is disabled
*/ function markRemovable(r) {
Object.defineProperty(r, Symbol.for("__next_css_remove"), {
enumerable: false,
value: true
});
return r;
}
let postcssInstancePromise;
export async function lazyPostCSS(rootDirectory, supportedBrowsers, disablePostcssPresetEnv) {
if (!postcssInstancePromise) {
postcssInstancePromise = (async ()=>{
const postcss = require("postcss");
// @ts-ignore backwards compat
postcss.plugin = function postcssPlugin(name, initializer) {
function creator(...args) {
let transformer = initializer(...args);
transformer.postcssPlugin = name;
// transformer.postcssVersion = new Processor().version
return transformer;
}
let cache;
Object.defineProperty(creator, "postcss", {
get () {
if (!cache) cache = creator();
return cache;
}
});
creator.process = function(css1, processOpts, pluginOpts) {
return postcss([
creator(pluginOpts)
]).process(css1, processOpts);
};
return creator;
};
// @ts-ignore backwards compat
postcss.vendor = {
/**
* Returns the vendor prefix extracted from an input string.
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/ prefix: function prefix(prop) {
const match = prop.match(/^(-\w+-)/);
if (match) {
return match[0];
}
return "";
},
/**
* Returns the input string stripped of its vendor prefix.
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/ unprefixed: function unprefixed(/**
* String with or without vendor prefix.
*/ prop) {
return prop.replace(/^-\w+-/, "");
}
};
const postCssPlugins = await getPostCssPlugins(rootDirectory, supportedBrowsers, disablePostcssPresetEnv);
return {
postcss,
postcssWithPlugins: postcss(postCssPlugins)
};
})();
}
return postcssInstancePromise;
}
export const css = curry(async function css(ctx, config) {
const { prependData: sassPrependData , additionalData: sassAdditionalData , ...sassOptions } = ctx.sassOptions;
const lazyPostCSSInitializer = ()=>lazyPostCSS(ctx.rootDirectory, ctx.supportedBrowsers, ctx.experimental.disablePostcssPresetEnv);
const sassPreprocessors = [
// First, process files with `sass-loader`: this inlines content, and
// compiles away the proprietary syntax.
{
loader: require.resolve("next/dist/compiled/sass-loader"),
options: {
// Source maps are required so that `resolve-url-loader` can locate
// files original to their source directory.
sourceMap: true,
sassOptions,
additionalData: sassPrependData || sassAdditionalData
}
},
// Then, `sass-loader` will have passed-through CSS imports as-is instead
// of inlining them. Because they were inlined, the paths are no longer
// correct.
// To fix this, we use `resolve-url-loader` to rewrite the CSS
// imports to real file paths.
{
loader: require.resolve("../../../loaders/resolve-url-loader/index"),
options: {
postcss: lazyPostCSSInitializer,
// Source maps are not required here, but we may as well emit
// them.
sourceMap: true
}
},
];
const fns = [];
// Resolve the configured font loaders, the resolved files are noop files that next-font-loader will match
let fontLoaders = ctx.experimental.fontLoaders ? ctx.experimental.fontLoaders.map(({ loader: fontLoader , options })=>[
path.join(require.resolve(fontLoader), "../target.css"),
options,
]) : undefined;
fontLoaders == null ? void 0 : fontLoaders.forEach(([fontLoaderPath, fontLoaderOptions])=>{
// Matches the resolved font loaders noop files to run next-font-loader
fns.push(loader({
oneOf: [
markRemovable({
sideEffects: false,
test: fontLoaderPath,
use: getNextFontLoader(ctx, lazyPostCSSInitializer, fontLoaderOptions)
}),
]
}));
});
// CSS cannot be imported in _document. This comes before everything because
// global CSS nor CSS modules work in said file.
fns.push(loader({
oneOf: [
markRemovable({
test: regexLikeCss,
// Use a loose regex so we don't have to crawl the file system to
// find the real file name (if present).
issuer: /pages[\\/]_document\./,
use: {
loader: "error-loader",
options: {
reason: getCustomDocumentError()
}
}
}),
]
}));
const shouldIncludeExternalCSSImports = !!ctx.experimental.craCompat || !!ctx.transpilePackages;
// CSS modules & SASS modules support. They are allowed to be imported in anywhere.
fns.push(// CSS Modules should never have side effects. This setting will
// allow unused CSS to be removed from the production build.
// We ensure this by disallowing `:global()` CSS at the top-level
// via the `pure` mode in `css-loader`.
loader({
oneOf: [
// For app dir, it has to match one of the 2 layers and then apply a
// specific loader.
ctx.hasAppDir && !ctx.isProduction ? markRemovable({
sideEffects: false,
test: regexCssModules,
issuerLayer: {
or: [
WEBPACK_LAYERS.server,
WEBPACK_LAYERS.client
]
},
use: [
require.resolve("../../../loaders/next-flight-css-dev-loader"),
...getCssModuleLoader(ctx, lazyPostCSSInitializer),
]
}) : null,
ctx.hasAppDir && !ctx.isServer ? markRemovable({
sideEffects: false,
test: regexCssModules,
use: [
require.resolve("../../../loaders/next-flight-css-dev-loader"),
...getCssModuleLoader(ctx, lazyPostCSSInitializer),
]
}) : null,
markRemovable({
sideEffects: false,
test: regexCssModules,
use: getCssModuleLoader(ctx, lazyPostCSSInitializer)
}),
].filter(nonNullable)
}), // Opt-in support for Sass (using .scss or .sass extensions).
// Sass Modules should never have side effects. This setting will
// allow unused Sass to be removed from the production build.
// We ensure this by disallowing `:global()` Sass at the top-level
// via the `pure` mode in `css-loader`.
loader({
oneOf: [
// For app dir, we match both server and client layers.
ctx.hasAppDir && !ctx.isProduction ? markRemovable({
sideEffects: false,
test: regexSassModules,
issuerLayer: {
or: [
WEBPACK_LAYERS.server,
WEBPACK_LAYERS.client
]
},
use: [
require.resolve("../../../loaders/next-flight-css-dev-loader"),
...getCssModuleLoader(ctx, lazyPostCSSInitializer, sassPreprocessors),
]
}) : null,
ctx.hasAppDir && !ctx.isServer ? markRemovable({
sideEffects: false,
test: regexSassModules,
use: [
require.resolve("../../../loaders/next-flight-css-dev-loader"),
...getCssModuleLoader(ctx, lazyPostCSSInitializer, sassPreprocessors),
]
}) : null,
markRemovable({
sideEffects: false,
test: regexSassModules,
use: getCssModuleLoader(ctx, lazyPostCSSInitializer, sassPreprocessors)
}),
].filter(nonNullable)
}), // Throw an error for CSS Modules used outside their supported scope
loader({
oneOf: [
markRemovable({
test: [
regexCssModules,
regexSassModules
],
use: {
loader: "error-loader",
options: {
reason: getLocalModuleImportError()
}
}
}),
]
}));
// Global CSS and SASS support.
if (ctx.isServer) {
fns.push(loader({
oneOf: [
ctx.hasAppDir && !ctx.isProduction ? markRemovable({
sideEffects: true,
test: [
regexCssGlobal,
regexSassGlobal
],
issuerLayer: {
or: [
WEBPACK_LAYERS.server,
WEBPACK_LAYERS.client
]
},
use: require.resolve("../../../loaders/next-flight-css-dev-loader")
}) : null,
markRemovable({
// CSS imports have side effects, even on the server side.
sideEffects: true,
test: [
regexCssGlobal,
regexSassGlobal
],
use: require.resolve("next/dist/compiled/ignore-loader")
}),
].filter(nonNullable)
}));
} else {
// They are allowed to be loaded when any of the following is true:
// - hasAppDir: If the issuerLayer is RSC
// - If the CSS file is located in `node_modules`
// - If the CSS file is located in another package in a monorepo (outside of the current rootDir)
// - If the issuer is pages/_app (matched later)
const allowedExternalCSSImports = {
and: [
{
or: [
/node_modules/,
{
not: [
ctx.rootDirectory
]
},
]
},
]
};
fns.push(loader({
oneOf: [
ctx.hasAppDir ? markRemovable({
sideEffects: true,
test: regexCssGlobal,
use: [
require.resolve("../../../loaders/next-flight-css-dev-loader"),
...getGlobalCssLoader(ctx, lazyPostCSSInitializer),
]
}) : null,
ctx.hasAppDir ? markRemovable({
sideEffects: true,
test: regexSassGlobal,
use: [
require.resolve("../../../loaders/next-flight-css-dev-loader"),
...getGlobalCssLoader(ctx, lazyPostCSSInitializer, sassPreprocessors),
]
}) : null,
!ctx.hasAppDir ? markRemovable({
sideEffects: true,
test: regexCssGlobal,
include: allowedExternalCSSImports,
issuer: shouldIncludeExternalCSSImports ? undefined : {
and: [
ctx.rootDirectory
],
not: [
/node_modules/
]
},
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer)
}) : null,
!ctx.hasAppDir ? markRemovable({
sideEffects: true,
test: regexSassGlobal,
include: allowedExternalCSSImports,
issuer: shouldIncludeExternalCSSImports ? undefined : {
and: [
ctx.rootDirectory
],
not: [
/node_modules/
]
},
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer, sassPreprocessors)
}) : null,
].filter(nonNullable)
}));
if (ctx.customAppFile) {
fns.push(loader({
oneOf: [
markRemovable({
sideEffects: true,
test: regexCssGlobal,
issuer: {
and: [
ctx.customAppFile
]
},
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer)
}),
]
}), loader({
oneOf: [
markRemovable({
sideEffects: true,
test: regexSassGlobal,
issuer: {
and: [
ctx.customAppFile
]
},
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer, sassPreprocessors)
}),
]
}));
}
}
// Throw an error for Global CSS used inside of `node_modules`
if (!shouldIncludeExternalCSSImports) {
fns.push(loader({
oneOf: [
markRemovable({
test: [
regexCssGlobal,
regexSassGlobal
],
issuer: {
and: [
/node_modules/
]
},
use: {
loader: "error-loader",
options: {
reason: getGlobalModuleImportError()
}
}
}),
]
}));
}
// Throw an error for Global CSS used outside of our custom <App> file
fns.push(loader({
oneOf: [
markRemovable({
test: [
regexCssGlobal,
regexSassGlobal
],
issuer: ctx.hasAppDir ? {
// If it's inside the app dir, but not importing from a layout file,
// throw an error.
and: [
ctx.rootDirectory
],
not: [
/layout\.(js|mjs|jsx|ts|tsx)$/
]
} : undefined,
use: {
loader: "error-loader",
options: {
reason: getGlobalImportError()
}
}
}),
]
}));
if (ctx.isClient) {
// Automatically transform references to files (i.e. url()) into URLs
// e.g. url(./logo.svg)
fns.push(loader({
oneOf: [
markRemovable({
// This should only be applied to CSS files
issuer: regexLikeCss,
// Exclude extensions that webpack handles by default
exclude: [
/\.(js|mjs|jsx|ts|tsx)$/,
/\.html$/,
/\.json$/,
/\.webpack\[[^\]]+\]$/,
],
// `asset/resource` always emits a URL reference, where `asset`
// might inline the asset as a data URI
type: "asset/resource"
}),
]
}));
}
// Enable full mini-css-extract-plugin hmr for prod mode pages or app dir
if (ctx.isClient && (ctx.isProduction || ctx.hasAppDir)) {
// Extract CSS as CSS file(s) in the client-side production bundle.
const MiniCssExtractPlugin = require("../../../plugins/mini-css-extract-plugin").default;
fns.push(plugin(// @ts-ignore webpack 5 compat
new MiniCssExtractPlugin({
filename: ctx.isProduction ? "static/css/[contenthash].css" : "static/css/[name].css",
chunkFilename: ctx.isProduction ? "static/css/[contenthash].css" : "static/css/[name].css",
// Next.js guarantees that CSS order "doesn't matter", due to imposed
// restrictions:
// 1. Global CSS can only be defined in a single entrypoint (_app)
// 2. CSS Modules generate scoped class names by default and cannot
// include Global CSS (:global() selector).
//
// While not a perfect guarantee (e.g. liberal use of `:global()`
// selector), this assumption is required to code-split CSS.
//
// If this warning were to trigger, it'd be unactionable by the user,
// but likely not valid -- so we disable it.
ignoreOrder: true
})));
}
const fn = pipe(...fns);
return fn(config);
});
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
export function getClientStyleLoader({ hasAppDir , isDevelopment , assetPrefix }) {
// Keep next-style-loader for development mode in `pages/`
if (isDevelopment && !hasAppDir) {
return {
loader: "next-style-loader",
options: {
insert: function(element) {
// By default, style-loader injects CSS into the bottom
// of <head>. This causes ordering problems between dev
// and prod. To fix this, we render a <noscript> tag as
// an anchor for the styles to be placed before. These
// styles will be applied _before_ <style jsx global>.
// These elements should always exist. If they do not,
// this code should fail.
var anchorElement = document.querySelector("#__next_css__DO_NOT_USE__");
var parentNode = anchorElement.parentNode// Normally <head>
;
// Each style tag should be placed right before our
// anchor. By inserting before and not after, we do not
// need to track the last inserted element.
parentNode.insertBefore(element, anchorElement);
}
}
};
}
const MiniCssExtractPlugin = require("../../../../plugins/mini-css-extract-plugin").default;
return {
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: `${assetPrefix}/_next/`,
esModule: false
}
};
}
//# sourceMappingURL=client.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/client.ts"],"names":["getClientStyleLoader","hasAppDir","isDevelopment","assetPrefix","loader","options","insert","element","anchorElement","document","querySelector","parentNode","insertBefore","MiniCssExtractPlugin","require","default","publicPath","esModule"],"mappings":"AAEA,OAAO,SAASA,oBAAoB,CAAC,EACnCC,SAAS,CAAA,EACTC,aAAa,CAAA,EACbC,WAAW,CAAA,EAKZ,EAA0B;IACzB,0DAA0D;IAC1D,IAAID,aAAa,IAAI,CAACD,SAAS,EAAE;QAC/B,OAAO;YACLG,MAAM,EAAE,mBAAmB;YAC3BC,OAAO,EAAE;gBACPC,MAAM,EAAE,SAAUC,OAAa,EAAE;oBAC/B,uDAAuD;oBACvD,uDAAuD;oBACvD,uDAAuD;oBACvD,sDAAsD;oBACtD,sDAAsD;oBAEtD,sDAAsD;oBACtD,yBAAyB;oBACzB,IAAIC,aAAa,GAAGC,QAAQ,CAACC,aAAa,CACxC,2BAA2B,CAC5B,AAAC;oBACF,IAAIC,UAAU,GAAGH,aAAa,CAACG,UAAU,AAAC,AAAC,kBAAkB;oBAAnB;oBAE1C,mDAAmD;oBACnD,uDAAuD;oBACvD,2CAA2C;oBAC3CA,UAAU,CAACC,YAAY,CAACL,OAAO,EAAEC,aAAa,CAAC;iBAChD;aACF;SACF,CAAA;KACF;IAED,MAAMK,oBAAoB,GACxBC,OAAO,CAAC,6CAA6C,CAAC,CAACC,OAAO;IAChE,OAAO;QACLX,MAAM,EAAES,oBAAoB,CAACT,MAAM;QACnCC,OAAO,EAAE;YACPW,UAAU,EAAE,CAAC,EAAEb,WAAW,CAAC,OAAO,CAAC;YACnCc,QAAQ,EAAE,KAAK;SAChB;KACF,CAAA;CACF"}

View File

@@ -0,0 +1,11 @@
export function cssFileResolve(url, _resourcePath, urlImports) {
if (url.startsWith("/")) {
return false;
}
if (!urlImports && /^[a-z][a-z0-9+.-]*:/i.test(url)) {
return false;
}
return true;
}
//# sourceMappingURL=file-resolve.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/file-resolve.ts"],"names":["cssFileResolve","url","_resourcePath","urlImports","startsWith","test"],"mappings":"AAAA,OAAO,SAASA,cAAc,CAC5BC,GAAW,EACXC,aAAqB,EACrBC,UAAe,EACf;IACA,IAAIF,GAAG,CAACG,UAAU,CAAC,GAAG,CAAC,EAAE;QACvB,OAAO,KAAK,CAAA;KACb;IACD,IAAI,CAACD,UAAU,IAAI,uBAAuBE,IAAI,CAACJ,GAAG,CAAC,EAAE;QACnD,OAAO,KAAK,CAAA;KACb;IACD,OAAO,IAAI,CAAA;CACZ"}

View File

@@ -0,0 +1,22 @@
import loaderUtils from "next/dist/compiled/loader-utils3";
import path from "path";
const regexLikeIndexModule = /(?<!pages[\\/])index\.module\.(scss|sass|css)$/;
export function getCssModuleLocalIdent(context, _, exportName, options) {
const relativePath = path.relative(context.rootContext, context.resourcePath).replace(/\\+/g, "/");
// Generate a more meaningful name (parent folder) when the user names the
// file `index.module.css`.
const fileNameOrFolder = regexLikeIndexModule.test(relativePath) ? "[folder]" : "[name]";
// Generate a hash to make the class name unique.
const hash = loaderUtils.getHashDigest(Buffer.from(`filePath:${relativePath}#className:${exportName}`), "md5", "base64", 5);
// Have webpack interpolate the `[folder]` or `[name]` to its real value.
return loaderUtils.interpolateName(context, fileNameOrFolder + "_" + exportName + "__" + hash, options).replace(// Webpack name interpolation returns `about.module_root__2oFM9` for
// `.root {}` inside a file named `about.module.css`. Let's simplify
// this.
/\.module_/, "_")// Replace invalid symbols with underscores instead of escaping
// https://mathiasbynens.be/notes/css-escapes#identifiers-strings
.replace(/[^a-zA-Z0-9-_]/g, "_")// "they cannot start with a digit, two hyphens, or a hyphen followed by a digit [sic]"
// https://www.w3.org/TR/CSS21/syndata.html#characters
.replace(/^(\d|--|-\d)/, "__$1");
}
//# sourceMappingURL=getCssModuleLocalIdent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/getCssModuleLocalIdent.ts"],"names":["loaderUtils","path","regexLikeIndexModule","getCssModuleLocalIdent","context","_","exportName","options","relativePath","relative","rootContext","resourcePath","replace","fileNameOrFolder","test","hash","getHashDigest","Buffer","from","interpolateName"],"mappings":"AAAA,OAAOA,WAAW,MAAM,kCAAkC,CAAA;AAC1D,OAAOC,IAAI,MAAM,MAAM,CAAA;AAGvB,MAAMC,oBAAoB,mDAAmD;AAE7E,OAAO,SAASC,sBAAsB,CACpCC,OAAkC,EAClCC,CAAM,EACNC,UAAkB,EAClBC,OAAe,EACf;IACA,MAAMC,YAAY,GAAGP,IAAI,CACtBQ,QAAQ,CAACL,OAAO,CAACM,WAAW,EAAEN,OAAO,CAACO,YAAY,CAAC,CACnDC,OAAO,SAAS,GAAG,CAAC;IAEvB,0EAA0E;IAC1E,2BAA2B;IAC3B,MAAMC,gBAAgB,GAAGX,oBAAoB,CAACY,IAAI,CAACN,YAAY,CAAC,GAC5D,UAAU,GACV,QAAQ;IAEZ,iDAAiD;IACjD,MAAMO,IAAI,GAAGf,WAAW,CAACgB,aAAa,CACpCC,MAAM,CAACC,IAAI,CAAC,CAAC,SAAS,EAAEV,YAAY,CAAC,WAAW,EAAEF,UAAU,CAAC,CAAC,CAAC,EAC/D,KAAK,EACL,QAAQ,EACR,CAAC,CACF;IAED,yEAAyE;IACzE,OACEN,WAAW,CACRmB,eAAe,CACdf,OAAO,EACPS,gBAAgB,GAAG,GAAG,GAAGP,UAAU,GAAG,IAAI,GAAGS,IAAI,EACjDR,OAAO,CACR,CACAK,OAAO,CACN,oEAAoE;IACpE,oEAAoE;IACpE,QAAQ;iBAER,GAAG,CACJ,AACD,+DAA+D;IAC/D,iEAAiE;KAChEA,OAAO,oBAAoB,GAAG,CAAC,AAChC,uFAAuF;IACvF,sDAAsD;KACrDA,OAAO,iBAAiB,MAAM,CAAC,CACnC;CACF"}

View File

@@ -0,0 +1,39 @@
import { getClientStyleLoader } from "./client";
import { cssFileResolve } from "./file-resolve";
export function getGlobalCssLoader(ctx, postcss, preProcessors = []) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development more or production mode style
// loader
loaders.push(getClientStyleLoader({
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
// Resolve CSS `@import`s and `url()`s
loaders.push({
loader: require.resolve("../../../../loaders/css-loader/src"),
options: {
postcss,
importLoaders: 1 + preProcessors.length,
// Next.js controls CSS Modules eligibility:
modules: false,
url: (url, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports)
}
});
// Compile CSS
loaders.push({
loader: require.resolve("../../../../loaders/postcss-loader/src"),
options: {
postcss
}
});
loaders.push(// Webpack loaders run like a stack, so we need to reverse the natural
// order of preprocessors.
...preProcessors.slice().reverse());
return loaders;
}
//# sourceMappingURL=global.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/global.ts"],"names":["getClientStyleLoader","cssFileResolve","getGlobalCssLoader","ctx","postcss","preProcessors","loaders","isClient","push","hasAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","length","modules","url","resourcePath","experimental","urlImports","import","_","slice","reverse"],"mappings":"AAGA,SAASA,oBAAoB,QAAQ,UAAU,CAAA;AAC/C,SAASC,cAAc,QAAQ,gBAAgB,CAAA;AAE/C,OAAO,SAASC,kBAAkB,CAChCC,GAAyB,EACzBC,OAAY,EACZC,aAAgD,GAAG,EAAE,EAC3B;IAC1B,MAAMC,OAAO,GAA6B,EAAE;IAE5C,IAAIH,GAAG,CAACI,QAAQ,EAAE;QAChB,4DAA4D;QAC5D,SAAS;QACTD,OAAO,CAACE,IAAI,CACVR,oBAAoB,CAAC;YACnBS,SAAS,EAAEN,GAAG,CAACM,SAAS;YACxBC,aAAa,EAAEP,GAAG,CAACO,aAAa;YAChCC,WAAW,EAAER,GAAG,CAACQ,WAAW;SAC7B,CAAC,CACH;KACF;IAED,sCAAsC;IACtCL,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAEC,OAAO,CAACC,OAAO,CAAC,oCAAoC,CAAC;QAC7DC,OAAO,EAAE;YACPX,OAAO;YACPY,aAAa,EAAE,CAAC,GAAGX,aAAa,CAACY,MAAM;YACvC,4CAA4C;YAC5CC,OAAO,EAAE,KAAK;YACdC,GAAG,EAAE,CAACA,GAAW,EAAEC,YAAoB,GACrCnB,cAAc,CAACkB,GAAG,EAAEC,YAAY,EAAEjB,GAAG,CAACkB,YAAY,CAACC,UAAU,CAAC;YAChEC,MAAM,EAAE,CAACJ,GAAW,EAAEK,CAAM,EAAEJ,YAAoB,GAChDnB,cAAc,CAACkB,GAAG,EAAEC,YAAY,EAAEjB,GAAG,CAACkB,YAAY,CAACC,UAAU,CAAC;SACjE;KACF,CAAC;IAEF,cAAc;IACdhB,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAEC,OAAO,CAACC,OAAO,CAAC,wCAAwC,CAAC;QACjEC,OAAO,EAAE;YACPX,OAAO;SACR;KACF,CAAC;IAEFE,OAAO,CAACE,IAAI,CACV,sEAAsE;IACtE,0BAA0B;OACvBH,aAAa,CAACoB,KAAK,EAAE,CAACC,OAAO,EAAE,CACnC;IAED,OAAOpB,OAAO,CAAA;CACf"}

View File

@@ -0,0 +1,4 @@
export * from "./global";
export * from "./modules";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,WAAW,CAAA"}

View File

@@ -0,0 +1,55 @@
import { getClientStyleLoader } from "./client";
import { cssFileResolve } from "./file-resolve";
import { getCssModuleLocalIdent } from "./getCssModuleLocalIdent";
export function getCssModuleLoader(ctx, postcss, preProcessors = []) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development more or production mode style
// loader
loaders.push(getClientStyleLoader({
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
// Resolve CSS `@import`s and `url()`s
loaders.push({
loader: require.resolve("../../../../loaders/css-loader/src"),
options: {
postcss,
importLoaders: 1 + preProcessors.length,
// Use CJS mode for backwards compatibility:
esModule: false,
url: (url, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
modules: {
// Do not transform class names (CJS mode backwards compatibility):
exportLocalsConvention: "asIs",
// Server-side (Node.js) rendering support:
exportOnlyLocals: ctx.isServer,
// Disallow global style exports so we can code-split CSS and
// not worry about loading order.
mode: "pure",
// Generate a friendly production-ready name so it's
// reasonably understandable. The same name is used for
// development.
// TODO: Consider making production reduce this to a single
// character?
getLocalIdent: getCssModuleLocalIdent
}
}
});
// Compile CSS
loaders.push({
loader: require.resolve("../../../../loaders/postcss-loader/src"),
options: {
postcss
}
});
loaders.push(// Webpack loaders run like a stack, so we need to reverse the natural
// order of preprocessors.
...preProcessors.slice().reverse());
return loaders;
}
//# sourceMappingURL=modules.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/modules.ts"],"names":["getClientStyleLoader","cssFileResolve","getCssModuleLocalIdent","getCssModuleLoader","ctx","postcss","preProcessors","loaders","isClient","push","hasAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","length","esModule","url","resourcePath","experimental","urlImports","import","_","modules","exportLocalsConvention","exportOnlyLocals","isServer","mode","getLocalIdent","slice","reverse"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAU,CAAA;AAC/C,SAASC,cAAc,QAAQ,gBAAgB,CAAA;AAC/C,SAASC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ACdK,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAEC,OAAO,CAACC,OAAO,CAAC,wCAAwC,CAAC;QACjEC,OAAO,EAAE;YACPX,OAAO;SACR;KACF,CAAC;IAEFE,OAAO,CAACE,IAAI,CACV,sEAAsE;IACtE,0BAA0B;OACvBH,aAAa,CAAC0B,KAAK,EAAE,CAACC,OAAO,EAAE,CACnC;IAED,OAAO1B,OAAO,CAAA;CACf"}

View File

@@ -0,0 +1,52 @@
import { getClientStyleLoader } from "./client";
import { cssFileResolve } from "./file-resolve";
export function getNextFontLoader(ctx, postcss, fontLoaderOptions) {
const loaders = [];
if (ctx.isClient) {
// Add appropriate development mode or production mode style
// loader
loaders.push(getClientStyleLoader({
hasAppDir: ctx.hasAppDir,
isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix
}));
}
loaders.push({
loader: require.resolve("../../../../loaders/css-loader/src"),
options: {
postcss,
importLoaders: 1,
// Use CJS mode for backwards compatibility:
esModule: false,
url: (url, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url, _, resourcePath)=>cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
modules: {
// Do not transform class names (CJS mode backwards compatibility):
exportLocalsConvention: "asIs",
// Server-side (Node.js) rendering support:
exportOnlyLocals: ctx.isServer,
// Disallow global style exports so we can code-split CSS and
// not worry about loading order.
mode: "pure",
getLocalIdent: (_context, _localIdentName, exportName, _options, meta)=>{
// hash from next-font-loader
return `__${exportName}_${meta.fontFamilyHash}`;
}
},
fontLoader: true
}
});
loaders.push({
loader: "next-font-loader",
options: {
isDev: ctx.isDevelopment,
isServer: ctx.isServer,
assetPrefix: ctx.assetPrefix,
fontLoaderOptions,
postcss
}
});
return loaders;
}
//# sourceMappingURL=next-font.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/config/blocks/css/loaders/next-font.ts"],"names":["getClientStyleLoader","cssFileResolve","getNextFontLoader","ctx","postcss","fontLoaderOptions","loaders","isClient","push","hasAppDir","isDevelopment","assetPrefix","loader","require","resolve","options","importLoaders","esModule","url","resourcePath","experimental","urlImports","import","_","modules","exportLocalsConvention","exportOnlyLocals","isServer","mode","getLocalIdent","_context","_localIdentName","exportName","_options","meta","fontFamilyHash","fontLoader","isDev"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,UAAU,CAAA;AAC/C,SAASC,cAAc,QAAQ,gBAAgB,CAAA;AAE/C,OAAO,SAASC,iBAAiB,CAC/BC,GAAyB,EACzBC,OAAY,EACZC,iBAAsB,EACI;IAC1B,MAAMC,OAAO,GAA6B,EAAE;IAE5C,IAAIH,GAAG,CAACI,QAAQ,EAAE;QAChB,4DAA4D;QAC5D,SAAS;QACTD,OAAO,CAACE,IAAI,CACVR,oBAAoB,CAAC;YACnBS,SAAS,EAAEN,GAAG,CAACM,SAAS;YACxBC,aAAa,EAAEP,GAAG,CAACO,aAAa;YAChCC,WAAW,EAAER,GAAG,CAACQ,WAAW;SAC7B,CAAC,CACH;KACF;IAEDL,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAEC,OAAO,CAACC,OAAO,CAAC,oCAAoC,CAAC;QAC7DC,OAAO,EAAE;YACPX,OAAO;YACPY,aAAa,EAAE,CAAC;YAChB,4CAA4C;YAC5CC,QAAQ,EAAE,KAAK;YACfC,GAAG,EAAE,CAACA,GAAW,EAAEC,YAAoB,GACrClB,cAAc,CAACiB,GAAG,EAAEC,YAAY,EAAEhB,GAAG,CAACiB,YAAY,CAACC,UAAU,CAAC;YAChEC,MAAM,EAAE,CAACJ,GAAW,EAAEK,CAAM,EAAEJ,YAAoB,GAChDlB,cAAc,CAACiB,GAAG,EAAEC,YAAY,EAAEhB,GAAG,CAACiB,YAAY,CAACC,UAAU,CAAC;YAChEG,OAAO,EAAE;gBACP,mEAAmE;gBACnEC,sBAAsB,EAAE,MAAM;gBAC9B,2CAA2C;gBAC3CC,gBAAgB,EAAEvB,GAAG,CAACwB,QAAQ;gBAC9B,6DAA6D;gBAC7D,iCAAiC;gBACjCC,IAAI,EAAE,MAAM;gBACZC,aAAa,EAAE,CACbC,QAAa,EACbC,eAAoB,EACpBC,UAAkB,EAClBC,QAAa,EACbC,IAAS,GACN;oBACH,6BAA6B;oBAC7B,OAAO,CAAC,EAAE,EAAEF,UAAU,CAAC,CAAC,EAAEE,IAAI,CAACC,cAAc,CAAC,CAAC,CAAA;iBAChD;aACF;YACDC,UAAU,EAAE,IAAI;SACjB;KACF,CAAC;IAEF9B,OAAO,CAACE,IAAI,CAAC;QACXI,MAAM,EAAE,kBAAkB;QAC1BG,OAAO,EAAE;YACPsB,KAAK,EAAElC,GAAG,CAACO,aAAa;YACxBiB,QAAQ,EAAExB,GAAG,CAACwB,QAAQ;YACtBhB,WAAW,EAAER,GAAG,CAACQ,WAAW;YAC5BN,iBAAiB;YACjBD,OAAO;SACR;KACF,CAAC;IAEF,OAAOE,OAAO,CAAA;CACf"}

View File

@@ -0,0 +1,15 @@
import chalk from "next/dist/compiled/chalk";
export function getGlobalImportError() {
return `Global CSS ${chalk.bold("cannot")} be imported from files other than your ${chalk.bold("Custom <App>")}. Due to the Global nature of stylesheets, and to avoid conflicts, Please move all first-party global CSS imports to ${chalk.cyan("pages/_app.js")}. Or convert the import to Component-Level CSS (CSS Modules).\nRead more: https://nextjs.org/docs/messages/css-global`;
}
export function getGlobalModuleImportError() {
return `Global CSS ${chalk.bold("cannot")} be imported from within ${chalk.bold("node_modules")}.\nRead more: https://nextjs.org/docs/messages/css-npm`;
}
export function getLocalModuleImportError() {
return `CSS Modules ${chalk.bold("cannot")} be imported from within ${chalk.bold("node_modules")}.\nRead more: https://nextjs.org/docs/messages/css-modules-npm`;
}
export function getCustomDocumentError() {
return `CSS ${chalk.bold("cannot")} be imported within ${chalk.cyan("pages/_document.js")}. Please move global styles to ${chalk.cyan("pages/_app.js")}.`;
}
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/config/blocks/css/messages.ts"],"names":["chalk","getGlobalImportError","bold","cyan","getGlobalModuleImportError","getLocalModuleImportError","getCustomDocumentError"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAE5C,OAAO,SAASC,oBAAoB,GAAG;IACrC,OAAO,CAAC,WAAW,EAAED,KAAK,CAACE,IAAI,CAC7B,QAAQ,CACT,CAAC,wCAAwC,EAAEF,KAAK,CAACE,IAAI,CACpD,cAAc,CACf,CAAC,qHAAqH,EAAEF,KAAK,CAACG,IAAI,CACjI,eAAe,CAChB,CAAC,qHAAqH,CAAC,CAAA;CACzH;AAED,OAAO,SAASC,0BAA0B,GAAG;IAC3C,OAAO,CAAC,WAAW,EAAEJ,KAAK,CAACE,IAAI,CAC7B,QAAQ,CACT,CAAC,yBAAyB,EAAEF,KAAK,CAACE,IAAI,CACrC,cAAc,CACf,CAAC,sDAAsD,CAAC,CAAA;CAC1D;AAED,OAAO,SAASG,yBAAyB,GAAG;IAC1C,OAAO,CAAC,YAAY,EAAEL,KAAK,CAACE,IAAI,CAC9B,QAAQ,CACT,CAAC,yBAAyB,EAAEF,KAAK,CAACE,IAAI,CACrC,cAAc,CACf,CAAC,8DAA8D,CAAC,CAAA;CAClE;AAED,OAAO,SAASI,sBAAsB,GAAG;IACvC,OAAO,CAAC,IAAI,EAAEN,KAAK,CAACE,IAAI,CAAC,QAAQ,CAAC,CAAC,oBAAoB,EAAEF,KAAK,CAACG,IAAI,CACjE,oBAAoB,CACrB,CAAC,+BAA+B,EAAEH,KAAK,CAACG,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAA;CAClE"}

View File

@@ -0,0 +1,152 @@
import chalk from "next/dist/compiled/chalk";
import { findConfig } from "../../../../../lib/find-config";
const genericErrorText = "Malformed PostCSS Configuration";
function getError_NullConfig(pluginName) {
return `${chalk.red.bold("Error")}: Your PostCSS configuration for '${pluginName}' cannot have ${chalk.bold("null")} configuration.\nTo disable '${pluginName}', pass ${chalk.bold("false")}, otherwise, pass ${chalk.bold("true")} or a configuration object.`;
}
function isIgnoredPlugin(pluginPath) {
const ignoredRegex = /(?:^|[\\/])(postcss-modules-values|postcss-modules-scope|postcss-modules-extract-imports|postcss-modules-local-by-default|postcss-modules)(?:[\\/]|$)/i;
const match = ignoredRegex.exec(pluginPath);
if (match == null) {
return false;
}
const plugin = match.pop();
console.warn(`${chalk.yellow.bold("Warning")}: Please remove the ${chalk.underline(plugin)} plugin from your PostCSS configuration. ` + `This plugin is automatically configured by Next.js.\n` + "Read more: https://nextjs.org/docs/messages/postcss-ignored-plugin");
return true;
}
const createLazyPostCssPlugin = (fn)=>{
let result = undefined;
const plugin = (...args)=>{
if (result === undefined) result = fn();
if (result.postcss === true) {
return result(...args);
} else if (result.postcss) {
return result.postcss;
}
return result;
};
plugin.postcss = true;
return plugin;
};
async function loadPlugin(dir, pluginName, options) {
if (options === false || isIgnoredPlugin(pluginName)) {
return false;
}
if (options == null) {
console.error(getError_NullConfig(pluginName));
throw new Error(genericErrorText);
}
const pluginPath = require.resolve(pluginName, {
paths: [
dir
]
});
if (isIgnoredPlugin(pluginPath)) {
return false;
} else if (options === true) {
return createLazyPostCssPlugin(()=>require(pluginPath));
} else {
if (typeof options === "object" && Object.keys(options).length === 0) {
return createLazyPostCssPlugin(()=>require(pluginPath));
}
return createLazyPostCssPlugin(()=>require(pluginPath)(options));
}
}
function getDefaultPlugins(supportedBrowsers, disablePostcssPresetEnv) {
return [
require.resolve("next/dist/compiled/postcss-flexbugs-fixes"),
disablePostcssPresetEnv ? false : [
require.resolve("next/dist/compiled/postcss-preset-env"),
{
browsers: supportedBrowsers ?? [
"defaults"
],
autoprefixer: {
// Disable legacy flexbox support
flexbox: "no-2009"
},
// Enable CSS features that have shipped to the
// web platform, i.e. in 2+ browsers unflagged.
stage: 3,
features: {
"custom-properties": false
}
},
],
].filter(Boolean);
}
export async function getPostCssPlugins(dir, supportedBrowsers, disablePostcssPresetEnv = false) {
let config = await findConfig(dir, "postcss");
if (config == null) {
config = {
plugins: getDefaultPlugins(supportedBrowsers, disablePostcssPresetEnv)
};
}
if (typeof config === "function") {
throw new Error(`Your custom PostCSS configuration may not export a function. Please export a plain object instead.\n` + "Read more: https://nextjs.org/docs/messages/postcss-function");
}
// Warn user about configuration keys which are not respected
const invalidKey = Object.keys(config).find((key)=>key !== "plugins");
if (invalidKey) {
console.warn(`${chalk.yellow.bold("Warning")}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` + `Please remove this configuration value.`);
}
// Enforce the user provided plugins if the configuration file is present
let plugins = config.plugins;
if (plugins == null || typeof plugins !== "object") {
throw new Error(`Your custom PostCSS configuration must export a \`plugins\` key.`);
}
if (!Array.isArray(plugins)) {
// Capture variable so TypeScript is happy
const pc = plugins;
plugins = Object.keys(plugins).reduce((acc, curr)=>{
const p = pc[curr];
if (typeof p === "undefined") {
console.error(getError_NullConfig(curr));
throw new Error(genericErrorText);
}
acc.push([
curr,
p
]);
return acc;
}, []);
}
const parsed = [];
plugins.forEach((plugin)=>{
if (plugin == null) {
console.warn(`${chalk.yellow.bold("Warning")}: A ${chalk.bold("null")} PostCSS plugin was provided. This entry will be ignored.`);
} else if (typeof plugin === "string") {
parsed.push([
plugin,
true
]);
} else if (Array.isArray(plugin)) {
const pluginName = plugin[0];
const pluginConfig = plugin[1];
if (typeof pluginName === "string" && (typeof pluginConfig === "boolean" || typeof pluginConfig === "object" || typeof pluginConfig === "string")) {
parsed.push([
pluginName,
pluginConfig
]);
} else {
if (typeof pluginName !== "string") {
console.error(`${chalk.red.bold("Error")}: A PostCSS Plugin must be provided as a ${chalk.bold("string")}. Instead, we got: '${pluginName}'.\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
} else {
console.error(`${chalk.red.bold("Error")}: A PostCSS Plugin was passed as an array but did not provide its configuration ('${pluginName}').\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
}
throw new Error(genericErrorText);
}
} else if (typeof plugin === "function") {
console.error(`${chalk.red.bold("Error")}: A PostCSS Plugin was passed as a function using require(), but it must be provided as a ${chalk.bold("string")}.\nRead more: https://nextjs.org/docs/messages/postcss-shape`);
throw new Error(genericErrorText);
} else {
console.error(`${chalk.red.bold("Error")}: An unknown PostCSS plugin was provided (${plugin}).\n` + "Read more: https://nextjs.org/docs/messages/postcss-shape");
throw new Error(genericErrorText);
}
});
const resolved = await Promise.all(parsed.map((p)=>loadPlugin(dir, p[0], p[1])));
const filtered = resolved.filter(Boolean);
return filtered;
}
//# sourceMappingURL=plugins.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import curry from "next/dist/compiled/lodash.curry";
import { nextImageLoaderRegex } from "../../../../webpack-config";
import { loader } from "../../helpers";
import { pipe } from "../../utils";
import { getCustomDocumentImageError } from "./messages";
export const images = curry(async function images(_ctx, config) {
const fns = [
loader({
oneOf: [
{
test: nextImageLoaderRegex,
use: {
loader: "error-loader",
options: {
reason: getCustomDocumentImageError()
}
},
issuer: /pages[\\/]_document\./
},
]
}),
];
const fn = pipe(...fns);
return fn(config);
});
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/config/blocks/images/index.ts"],"names":["curry","nextImageLoaderRegex","loader","pipe","getCustomDocumentImageError","images","_ctx","config","fns","oneOf","test","use","options","reason","issuer","fn"],"mappings":"AAAA,OAAOA,KAAK,MAAM,iCAAiC,CAAA;AAEnD,SAASC,oBAAoB,QAAQ,4BAA4B,CAAA;AACjE,SAASC,MAAM,QAAQ,eAAe,CAAA;AACtC,SAAgDC,IAAI,QAAQ,aAAa,CAAA;AACzE,SAASC,2BAA2B,QAAQ,YAAY,CAAA;AAExD,OAAO,MAAMC,MAAM,GAAGL,KAAK,CAAC,eAAeK,MAAM,CAC/CC,IAA0B,EAC1BC,MAA6B,EAC7B;IACA,MAAMC,GAAG,GAAsB;QAC7BN,MAAM,CAAC;YACLO,KAAK,EAAE;gBACL;oBACEC,IAAI,EAAET,oBAAoB;oBAC1BU,GAAG,EAAE;wBACHT,MAAM,EAAE,cAAc;wBACtBU,OAAO,EAAE;4BACPC,MAAM,EAAET,2BAA2B,EAAE;yBACtC;qBACF;oBACDU,MAAM,yBAAyB;iBAChC;aACF;SACF,CAAC;KACH;IAED,MAAMC,EAAE,GAAGZ,IAAI,IAAIK,GAAG,CAAC;IACvB,OAAOO,EAAE,CAACR,MAAM,CAAC,CAAA;CAClB,CAAC,CAAA"}

View File

@@ -0,0 +1,6 @@
import chalk from "next/dist/compiled/chalk";
export function getCustomDocumentImageError() {
return `Images ${chalk.bold("cannot")} be imported within ${chalk.cyan("pages/_document.js")}. Please move image imports that need to be displayed on every page into ${chalk.cyan("pages/_app.js")}.\nRead more: https://nextjs.org/docs/messages/custom-document-image-import`;
}
//# sourceMappingURL=messages.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/config/blocks/images/messages.ts"],"names":["chalk","getCustomDocumentImageError","bold","cyan"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAE5C,OAAO,SAASC,2BAA2B,GAAG;IAC5C,OAAO,CAAC,OAAO,EAAED,KAAK,CAACE,IAAI,CAAC,QAAQ,CAAC,CAAC,oBAAoB,EAAEF,KAAK,CAACG,IAAI,CACpE,oBAAoB,CACrB,CAAC,yEAAyE,EAAEH,KAAK,CAACG,IAAI,CACrF,eAAe,CAChB,CAAC,2EAA2E,CAAC,CAAA;CAC/E"}

View File

@@ -0,0 +1,47 @@
import curry from "next/dist/compiled/lodash.curry";
export const loader = curry(function loader(rule, config) {
var ref;
if (!config.module) {
config.module = {
rules: []
};
}
if (rule.oneOf) {
var ref1;
const existing = (ref1 = config.module.rules) == null ? void 0 : ref1.find((arrayRule)=>arrayRule && typeof arrayRule === "object" && arrayRule.oneOf);
if (existing && typeof existing === "object") {
existing.oneOf.push(...rule.oneOf);
return config;
}
}
(ref = config.module.rules) == null ? void 0 : ref.push(rule);
return config;
});
export const unshiftLoader = curry(function unshiftLoader(rule, config) {
var ref;
if (!config.module) {
config.module = {
rules: []
};
}
if (rule.oneOf) {
var ref2;
const existing = (ref2 = config.module.rules) == null ? void 0 : ref2.find((arrayRule)=>arrayRule && typeof arrayRule === "object" && arrayRule.oneOf);
if (existing && typeof existing === "object") {
var ref3;
(ref3 = existing.oneOf) == null ? void 0 : ref3.unshift(...rule.oneOf);
return config;
}
}
(ref = config.module.rules) == null ? void 0 : ref.unshift(rule);
return config;
});
export const plugin = curry(function plugin(p, config) {
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push(p);
return config;
});
//# sourceMappingURL=helpers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/config/helpers.ts"],"names":["curry","loader","rule","config","module","rules","oneOf","existing","find","arrayRule","push","unshiftLoader","unshift","plugin","p","plugins"],"mappings":"AAAA,OAAOA,KAAK,MAAM,iCAAiC,CAAA;AAGnD,OAAO,MAAMC,MAAM,GAAGD,KAAK,CAAC,SAASC,MAAM,CACzCC,IAAyB,EACzBC,MAA6B,EAC7B;QAgBAA,GAAmB;IAfnB,IAAI,CAACA,MAAM,CAACC,MAAM,EAAE;QAClBD,MAAM,CAACC,MAAM,GAAG;YAAEC,KAAK,EAAE,EAAE;SAAE;KAC9B;IAED,IAAIH,IAAI,CAACI,KAAK,EAAE;YACGH,IAAmB;QAApC,MAAMI,QAAQ,GAAGJ,CAAAA,IAAmB,GAAnBA,MAAM,CAACC,MAAM,CAACC,KAAK,SAAM,GAAzBF,KAAAA,CAAyB,GAAzBA,IAAmB,CAAEK,IAAI,CACxC,CAACC,SAAS,GACRA,SAAS,IAAI,OAAOA,SAAS,KAAK,QAAQ,IAAIA,SAAS,CAACH,KAAK,CAChE;QACD,IAAIC,QAAQ,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;YAC5CA,QAAQ,CAACD,KAAK,CAAEI,IAAI,IAAIR,IAAI,CAACI,KAAK,CAAC;YACnC,OAAOH,MAAM,CAAA;SACd;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CAACA,MAAM,CAACY,OAAO,EAAE;QACnBZ,MAAM,CAACY,OAAO,GAAG,EAAE;KACpB;IACDZ,MAAM,CAACY,OAAO,CAACL,IAAI,CAACI,CAAC,CAAC;IACtB,OAAOX,MAAM,CAAA;CACd,CAAC,CAAA"}

View File

@@ -0,0 +1,35 @@
import { base } from "./blocks/base";
import { css } from "./blocks/css";
import { images } from "./blocks/images";
import { pipe } from "./utils";
export async function buildConfiguration(config, { hasAppDir , supportedBrowsers , rootDirectory , customAppFile , isDevelopment , isServer , isEdgeRuntime , targetWeb , assetPrefix , sassOptions , productionBrowserSourceMaps , future , transpilePackages , experimental , disableStaticImages }) {
const ctx = {
hasAppDir,
supportedBrowsers,
rootDirectory,
customAppFile,
isDevelopment,
isProduction: !isDevelopment,
isServer,
isEdgeRuntime,
isClient: !isServer,
targetWeb,
assetPrefix: assetPrefix ? assetPrefix.endsWith("/") ? assetPrefix.slice(0, -1) : assetPrefix : "",
sassOptions,
productionBrowserSourceMaps,
transpilePackages,
future,
experimental
};
let fns = [
base(ctx),
css(ctx)
];
if (!disableStaticImages) {
fns.push(images(ctx));
}
const fn = pipe(...fns);
return fn(config);
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/config/index.ts"],"names":["base","css","images","pipe","buildConfiguration","config","hasAppDir","supportedBrowsers","rootDirectory","customAppFile","isDevelopment","isServer","isEdgeRuntime","targetWeb","assetPrefix","sassOptions","productionBrowserSourceMaps","future","transpilePackages","experimental","disableStaticImages","ctx","isProduction","isClient","endsWith","slice","fns","push","fn"],"mappings":"AAIA,SAASA,IAAI,QAAQ,eAAe,CAAA;AACpC,SAASC,GAAG,QAAQ,cAAc,CAAA;AAClC,SAASC,MAAM,QAAQ,iBAAiB,CAAA;AACxC,SAASC,IAAI,QAAQ,SAAS,CAAA;AAE9B,OAAO,eAAeC,kBAAkB,CACtCC,MAA6B,EAC7B,EACEC,SAAS,CAAA,EACTC,iBAAiB,CAAA,EACjBC,aAAa,CAAA,EACbC,aAAa,CAAA,EACbC,aAAa,CAAA,EACbC,QAAQ,CAAA,EACRC,aAAa,CAAA,EACbC,SAAS,CAAA,EACTC,WAAW,CAAA,EACXC,WAAW,CAAA,EACXC,2BAA2B,CAAA,EAC3BC,MAAM,CAAA,EACNC,iBAAiB,CAAA,EACjBC,YAAY,CAAA,EACZC,mBAAmB,CAAA,EAiBpB,EAC+B;IAChC,MAAMC,GAAG,GAAyB;QAChCf,SAAS;QACTC,iBAAiB;QACjBC,aAAa;QACbC,aAAa;QACbC,aAAa;QACbY,YAAY,EAAE,CAACZ,aAAa;QAC5BC,QAAQ;QACRC,aAAa;QACbW,QAAQ,EAAE,CAACZ,QAAQ;QACnBE,SAAS;QACTC,WAAW,EAAEA,WAAW,GACpBA,WAAW,CAACU,QAAQ,CAAC,GAAG,CAAC,GACvBV,WAAW,CAACW,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GACxBX,WAAW,GACb,EAAE;QACNC,WAAW;QACXC,2BAA2B;QAC3BE,iBAAiB;QACjBD,MAAM;QACNE,YAAY;KACb;IAED,IAAIO,GAAG,GAAG;QAAC1B,IAAI,CAACqB,GAAG,CAAC;QAAEpB,GAAG,CAACoB,GAAG,CAAC;KAAC;IAC/B,IAAI,CAACD,mBAAmB,EAAE;QACxBM,GAAG,CAACC,IAAI,CAACzB,MAAM,CAACmB,GAAG,CAAC,CAAC;KACtB;IACD,MAAMO,EAAE,GAAGzB,IAAI,IAAIuB,GAAG,CAAC;IACvB,OAAOE,EAAE,CAACvB,MAAM,CAAC,CAAA;CAClB"}

View File

@@ -0,0 +1,3 @@
export const pipe = (...fns)=>(param)=>fns.reduce(async (result, next)=>next(await result), param);
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/config/utils.ts"],"names":["pipe","fns","param","reduce","result","next"],"mappings":"AAgCA,OAAO,MAAMA,IAAI,GACf,CAAI,GAAGC,GAAG,AAAiC,GAC3C,CAACC,KAAQ,GACPD,GAAG,CAACE,MAAM,CACR,OAAOC,MAAsB,EAAEC,IAAI,GAAKA,IAAI,CAAC,MAAMD,MAAM,CAAC,EAC1DF,KAAK,CACN,CAAA"}

View File

@@ -0,0 +1,22 @@
export default class CssSyntaxError extends Error {
constructor(error){
super(error);
const { reason , line , column } = error;
this.name = "CssSyntaxError";
// Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
// We don't need `plugin` and `file` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
this.message += `(${line}:${column}) `;
}
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
// We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
};
//# sourceMappingURL=CssSyntaxError.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/css-loader/src/CssSyntaxError.js"],"names":["CssSyntaxError","Error","constructor","error","reason","line","column","name","message","code","showSourceCode","stack"],"mappings":"AAAA,eAAe,MAAMA,cAAc,SAASC,KAAK;IAC/CC,YAAYC,KAAK,CAAE;QACjB,KAAK,CAACA,KAAK,CAAC;QAEZ,MAAM,EAAEC,MAAM,CAAA,EAAEC,IAAI,CAAA,EAAEC,MAAM,CAAA,EAAE,GAAGH,KAAK;QAEtC,IAAI,CAACI,IAAI,GAAG,gBAAgB;QAE5B,wFAAwF;QACxF,gDAAgD;QAChD,IAAI,CAACC,OAAO,GAAG,CAAC,EAAE,IAAI,CAACD,IAAI,CAAC,IAAI,CAAC;QAEjC,IAAI,OAAOF,IAAI,KAAK,WAAW,EAAE;YAC/B,IAAI,CAACG,OAAO,IAAI,CAAC,CAAC,EAAEH,IAAI,CAAC,CAAC,EAAEC,MAAM,CAAC,EAAE,CAAC;SACvC;QAED,IAAI,CAACE,OAAO,IAAI,CAAC,EAAEJ,MAAM,CAAC,CAAC;QAE3B,MAAMK,IAAI,GAAGN,KAAK,CAACO,cAAc,EAAE;QAEnC,IAAID,IAAI,EAAE;YACR,IAAI,CAACD,OAAO,IAAI,CAAC,IAAI,EAAEC,IAAI,CAAC,EAAE,CAAC;SAChC;QAED,wIAAwI;QACxI,IAAI,CAACE,KAAK,GAAG,KAAK;KACnB;CACF,CAAA"}

View File

@@ -0,0 +1,79 @@
/*
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ const preserveCamelCase = (string, locale)=>{
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for(let i = 0; i < string.length; i++){
const character = string[i];
if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
string = string.slice(0, i) + "-" + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
string = string.slice(0, i - 1) + "-" + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
}
}
return string;
};
const preserveConsecutiveUppercase = (input)=>{
return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, (m1)=>m1.toLowerCase());
};
const postProcess = (input, options)=>{
return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1)=>p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, (m)=>m.toLocaleUpperCase(options.locale));
};
const camelCase = (input, options)=>{
if (!(typeof input === "string" || Array.isArray(input))) {
throw new TypeError("Expected the input to be `string | string[]`");
}
options = {
pascalCase: false,
preserveConsecutiveUppercase: false,
...options
};
if (Array.isArray(input)) {
input = input.map((x)=>x.trim()).filter((x)=>x.length).join("-");
} else {
input = input.trim();
}
if (input.length === 0) {
return "";
}
if (input.length === 1) {
return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
}
const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
if (hasUpperCase) {
input = preserveCamelCase(input, options.locale);
}
input = input.replace(/^[_.\- ]+/, "");
if (options.preserveConsecutiveUppercase) {
input = preserveConsecutiveUppercase(input);
} else {
input = input.toLocaleLowerCase();
}
if (options.pascalCase) {
input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
}
return postProcess(input, options);
};
export default camelCase;
//# sourceMappingURL=camelcase.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/css-loader/src/camelcase.js"],"names":["preserveCamelCase","string","locale","isLastCharLower","isLastCharUpper","isLastLastCharUpper","i","length","character","test","slice","toLocaleLowerCase","toLocaleUpperCase","preserveConsecutiveUppercase","input","replace","m1","toLowerCase","postProcess","options","_","p1","m","camelCase","Array","isAr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AA;KACV;IAED,IAAIO,KAAK,CAACP,MAAM,KAAK,CAAC,EAAE;QACtB,OAAOY,OAAO,CAACQ,UAAU,GACrBb,KAAK,CAACF,iBAAiB,CAACO,OAAO,CAACjB,MAAM,CAAC,GACvCY,KAAK,CAACH,iBAAiB,CAACQ,OAAO,CAACjB,MAAM,CAAC,CAAA;KAC5C;IAED,MAAM+B,YAAY,GAAGnB,KAAK,KAAKA,KAAK,CAACH,iBAAiB,CAACQ,OAAO,CAACjB,MAAM,CAAC;IAEtE,IAAI+B,YAAY,EAAE;QAChBnB,KAAK,GAAGd,iBAAiB,CAACc,KAAK,EAAEK,OAAO,CAACjB,MAAM,CAAC;KACjD;IAEDY,KAAK,GAAGA,KAAK,CAACC,OAAO,cAAc,EAAE,CAAC;IAEtC,IAAII,OAAO,CAACN,4BAA4B,EAAE;QACxCC,KAAK,GAAGD,4BAA4B,CAACC,KAAK,CAAC;KAC5C,MAAM;QACLA,KAAK,GAAGA,KAAK,CAACH,iBAAiB,EAAE;KAClC;IAED,IAAIQ,OAAO,CAACQ,UAAU,EAAE;QACtBb,KAAK,GAAGA,KAAK,CAACoB,MAAM,CAAC,CAAC,CAAC,CAACtB,iBAAiB,CAACO,OAAO,CAACjB,MAAM,CAAC,GAAGY,KAAK,CAACJ,KAAK,CAAC,CAAC,CAAC;KAC3E;IAED,OAAOQ,WAAW,CAACJ,KAAK,EAAEK,OAAO,CAAC,CAAA;CACnC;AAED,eAAeI,SAAS,CAAA"}

View File

@@ -0,0 +1,247 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ import CssSyntaxError from "./CssSyntaxError";
import Warning from "../../postcss-loader/src/Warning";
import { stringifyRequest } from "../../../stringify-request";
const moduleRegExp = /\.module\.\w+$/i;
function getModulesOptions(rawOptions, loaderContext) {
const { resourcePath } = loaderContext;
if (typeof rawOptions.modules === "undefined") {
const isModules = moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules === "boolean" && rawOptions.modules === false) {
return false;
}
let modulesOptions = {
compileType: rawOptions.icss ? "icss" : "module",
auto: true,
mode: "local",
exportGlobals: false,
localIdentName: "[hash:base64]",
localIdentContext: loaderContext.rootContext,
localIdentHashPrefix: "",
// eslint-disable-next-line no-undefined
localIdentRegExp: undefined,
namedExport: false,
exportLocalsConvention: "asIs",
exportOnlyLocals: false
};
if (typeof rawOptions.modules === "boolean" || typeof rawOptions.modules === "string") {
modulesOptions.mode = typeof rawOptions.modules === "string" ? rawOptions.modules : "local";
} else {
if (rawOptions.modules) {
if (typeof rawOptions.modules.auto === "boolean") {
const isModules = rawOptions.modules.auto && moduleRegExp.test(resourcePath);
if (!isModules) {
return false;
}
} else if (rawOptions.modules.auto instanceof RegExp) {
const isModules = rawOptions.modules.auto.test(resourcePath);
if (!isModules) {
return false;
}
} else if (typeof rawOptions.modules.auto === "function") {
const isModule = rawOptions.modules.auto(resourcePath);
if (!isModule) {
return false;
}
}
if (rawOptions.modules.namedExport === true && typeof rawOptions.modules.exportLocalsConvention === "undefined") {
modulesOptions.exportLocalsConvention = "camelCaseOnly";
}
}
modulesOptions = {
...modulesOptions,
...rawOptions.modules || {}
};
}
if (typeof modulesOptions.mode === "function") {
modulesOptions.mode = modulesOptions.mode(loaderContext.resourcePath);
}
if (modulesOptions.namedExport === true) {
if (rawOptions.esModule === false) {
throw new Error('The "modules.namedExport" option requires the "esModules" option to be enabled');
}
if (modulesOptions.exportLocalsConvention !== "camelCaseOnly") {
throw new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly"');
}
}
return modulesOptions;
}
function normalizeOptions(rawOptions, loaderContext) {
if (rawOptions.icss) {
loaderContext.emitWarning(new Error('The "icss" option is deprecated, use "modules.compileType: "icss"" instead'));
}
const modulesOptions = getModulesOptions(rawOptions, loaderContext);
return {
url: typeof rawOptions.url === "undefined" ? true : rawOptions.url,
import: typeof rawOptions.import === "undefined" ? true : rawOptions.import,
modules: modulesOptions,
// TODO remove in the next major release
icss: typeof rawOptions.icss === "undefined" ? false : rawOptions.icss,
sourceMap: typeof rawOptions.sourceMap === "boolean" ? rawOptions.sourceMap : loaderContext.sourceMap,
importLoaders: typeof rawOptions.importLoaders === "string" ? parseInt(rawOptions.importLoaders, 10) : rawOptions.importLoaders,
esModule: typeof rawOptions.esModule === "undefined" ? true : rawOptions.esModule,
fontLoader: rawOptions.fontLoader
};
}
export default async function loader(content, map, meta) {
const rawOptions = this.getOptions();
const plugins = [];
const callback = this.async();
const loaderSpan = this.currentTraceSpan.traceChild("css-loader");
loaderSpan.traceAsyncFn(async ()=>{
let options;
try {
options = normalizeOptions(rawOptions, this);
} catch (error) {
throw error;
}
const { postcss } = await rawOptions.postcss();
const { shouldUseModulesPlugins , shouldUseImportPlugin , shouldUseURLPlugin , shouldUseIcssPlugin , getPreRequester , getExportCode , getFilter , getImportCode , getModuleCode , getModulesPlugins , normalizeSourceMap , sort , } = require("./utils");
const { icssParser , importParser , urlParser } = require("./plugins");
const replacements = [];
// if it's a font loader next-font-loader will have exports that should be exported as is
const exports = options.fontLoader ? meta.exports : [];
if (shouldUseModulesPlugins(options)) {
plugins.push(...getModulesPlugins(options, this, meta));
}
const importPluginImports = [];
const importPluginApi = [];
if (shouldUseImportPlugin(options)) {
const resolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [
".css"
],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
],
restrictions: [
/\.css$/i
]
});
plugins.push(importParser({
imports: importPluginImports,
api: importPluginApi,
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.import, this.resourcePath),
resolver,
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
}));
}
const urlPluginImports = [];
if (shouldUseURLPlugin(options)) {
const urlResolver = this.getResolve({
conditionNames: [
"asset"
],
mainFields: [
"asset"
],
mainFiles: [],
extensions: []
});
plugins.push(urlParser({
imports: urlPluginImports,
replacements,
context: this.context,
rootContext: this.rootContext,
filter: getFilter(options.url, this.resourcePath),
resolver: urlResolver,
urlHandler: (url)=>stringifyRequest(this, url)
}));
}
const icssPluginImports = [];
const icssPluginApi = [];
if (shouldUseIcssPlugin(options)) {
const icssResolver = this.getResolve({
conditionNames: [
"style"
],
extensions: [],
mainFields: [
"css",
"style",
"main",
"..."
],
mainFiles: [
"index",
"..."
]
});
plugins.push(icssParser({
imports: icssPluginImports,
api: icssPluginApi,
replacements,
exports,
context: this.context,
rootContext: this.rootContext,
resolver: icssResolver,
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
}));
}
// Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
if (meta) {
const { ast } = meta;
if (ast && ast.type === "postcss") {
// eslint-disable-next-line no-param-reassign
content = ast.root;
loaderSpan.setAttribute("astUsed", "true");
}
}
const { resourcePath } = this;
let result;
try {
result = await postcss(plugins).process(content, {
from: resourcePath,
to: resourcePath,
map: options.sourceMap ? {
prev: map ? normalizeSourceMap(map, resourcePath) : null,
inline: false,
annotation: false
} : false
});
} catch (error1) {
if (error1.file) {
this.addDependency(error1.file);
}
throw error1.name === "CssSyntaxError" ? new CssSyntaxError(error1) : error1;
}
for (const warning of result.warnings()){
this.emitWarning(new Warning(warning));
}
const imports = [].concat(icssPluginImports.sort(sort)).concat(importPluginImports.sort(sort)).concat(urlPluginImports.sort(sort));
const api = [].concat(importPluginApi.sort(sort)).concat(icssPluginApi.sort(sort));
if (options.modules.exportOnlyLocals !== true) {
imports.unshift({
importName: "___CSS_LOADER_API_IMPORT___",
url: stringifyRequest(this, require.resolve("./runtime/api"))
});
}
const importCode = getImportCode(imports, options);
const moduleCode = getModuleCode(result, api, replacements, options, this);
const exportCode = getExportCode(exports, replacements, options);
return `${importCode}${moduleCode}${exportCode}`;
}).then((code)=>{
callback(null, code);
}, (err)=>{
callback(err);
});
};
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import importParser from "./postcss-import-parser";
import icssParser from "./postcss-icss-parser";
import urlParser from "./postcss-url-parser";
export { importParser, icssParser, urlParser };
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/plugins/index.js"],"names":["importParser","icssParser","urlParser"],"mappings":"AAAA,OAAOA,YAAY,MAAM,yBAAyB,CAAA;AAClD,OAAOC,UAAU,MAAM,uBAAuB,CAAA;AAC9C,OAAOC,SAAS,MAAM,sBAAsB,CAAA;AAE5C,SAASF,YAAY,EAAEC,UAAU,EAAEC,SAAS,GAAE"}

View File

@@ -0,0 +1,97 @@
import { extractICSS, replaceValueSymbols, replaceSymbols } from "next/dist/compiled/icss-utils";
import { normalizeUrl, resolveRequests, requestify } from "../utils";
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-icss-parser",
async OnceExit (root) {
const importReplacements = Object.create(null);
const { icssImports , icssExports } = extractICSS(root);
const imports = new Map();
const tasks = [];
// eslint-disable-next-line guard-for-in
for(const url in icssImports){
const tokens = icssImports[url];
if (Object.keys(tokens).length === 0) {
continue;
}
let normalizedUrl = url;
let prefix = "";
const queryParts = normalizedUrl.split("!");
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join("!");
}
const request = requestify(normalizeUrl(normalizedUrl, true), options.rootContext);
const doResolve = async ()=>{
const { resolver , context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
normalizedUrl,
request
]),
]);
if (!resolvedUrl) {
return;
}
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
prefix,
tokens
};
};
tasks.push(doResolve());
}
const results = await Promise.all(tasks);
for(let index = 0; index <= results.length - 1; index++){
const item = results[index];
if (!item) {
continue;
}
const newUrl = item.prefix ? `${item.prefix}!${item.url}` : item.url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_ICSS_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
type: "icss_import",
importName,
url: options.urlHandler(newUrl),
icss: true,
index
});
options.api.push({
importName,
dedupe: true,
index
});
}
for (const [replacementIndex, token] of Object.keys(item.tokens).entries()){
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
const localName = item.tokens[token];
importReplacements[token] = replacementName;
options.replacements.push({
replacementName,
importName,
localName
});
}
}
if (Object.keys(importReplacements).length > 0) {
replaceSymbols(root, importReplacements);
}
for (const name of Object.keys(icssExports)){
const value = replaceValueSymbols(icssExports[name], importReplacements);
options.exports.push({
name,
value
});
}
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-icss-parser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/plugins/postcss-icss-parser.js"],"names":["extractICSS","replaceValueSymbols","replaceSymbols","normalizeUrl","resolveRequests","requestify","plugin","options","postcssPlugin","OnceExit","root","importReplacements","Object","create","icssImports","icssExports","imports","Map","tasks","url","tokens","keys","length","normalizedUrl","prefix","queryParts","split","pop","join","request","rootContext","doResolve","resolver","context","resolvedUrl","Set","push","results","Promise","all","index","item","newUrl","importKey","importName","get","size","set","type","urlHandler","icss","api","dedupe","replacementIndex","token","entries","replacementName","localName","replacements","name","value","exports","postcss"],"mappings":"AAAA,SACEA,WAAW,EACXC,mBAAmB,EACnBC,cAAc,QACT,+BAA+B,CAAA;AAEtC,SAASC,YAAY,EAAEC,eAAe,EAAEC,UAAU,QAAQ,UAAU,CAAA;AAEpE,MAAMC,MAAM,GAAG,CAACC,OAAO,GAAG,EAAE,GAAK;IAC/B,OAAO;QACLC,aAAa,EAAE,qBAAqB;QACpC,MAAMC,QAAQ,EAACC,IAAI,EAAE;YACnB,MAAMC,kBAAkB,GAAGC,MAAM,CAACC,MAAM,CAAC,IAAI,CAAC;YAC9C,MAAM,EAAEC,WAAW,CAAA,EAAEC,WAAW,CAAA,EAAE,GAAGf,WAAW,CAACU,IA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AAgB,CAAC,GAAG,CAAC;oBAC/F,MAAMI,SAAS,GAAGhB,IAAI,CAACrB,MAAM,CAACkC,KAAK,CAAC;oBAEpC3C,kBAAkB,CAAC2C,KAAK,CAAC,GAAGE,eAAe;oBAE3CjD,OAAO,CAACmD,YAAY,CAACtB,IAAI,CAAC;wBAAEoB,eAAe;wBAAEZ,UAAU;wBAAEa,SAAS;qBAAE,CAAC;iBACtE;aACF;YAED,IAAI7C,MAAM,CAACS,IAAI,CAACV,kBAAkB,CAAC,CAACW,MAAM,GAAG,CAAC,EAAE;gBAC9CpB,cAAc,CAACQ,IAAI,EAAEC,kBAAkB,CAAC;aACzC;YAED,KAAK,MAAMgD,IAAI,IAAI/C,MAAM,CAACS,IAAI,CAACN,WAAW,CAAC,CAAE;gBAC3C,MAAM6C,KAAK,GAAG3D,mBAAmB,CAACc,WAAW,CAAC4C,IAAI,CAAC,EAAEhD,kBAAkB,CAAC;gBAExEJ,OAAO,CAACsD,OAAO,CAACzB,IAAI,CAAC;oBAAEuB,IAAI;oBAAEC,KAAK;iBAAE,CAAC;aACtC;SACF;KACF,CAAA;CACF;AAEDtD,MAAM,CAACwD,OAAO,GAAG,IAAI;AAErB,eAAexD,MAAM,CAAA"}

View File

@@ -0,0 +1,191 @@
import valueParser from "next/dist/compiled/postcss-value-parser";
import { normalizeUrl, resolveRequests, isUrlRequestable, requestify, WEBPACK_IGNORE_COMMENT_REGEXP } from "../utils";
function parseNode(atRule, key) {
// Convert only top-level @import
if (atRule.parent.type !== "root") {
return;
}
if (atRule.raws && atRule.raws.afterName && atRule.raws.afterName.trim().length > 0) {
const lastCommentIndex = atRule.raws.afterName.lastIndexOf("/*");
const matched = atRule.raws.afterName.slice(lastCommentIndex).match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
const prevNode = atRule.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
return;
}
}
// Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
const error = new Error("It looks like you didn't end your @import statement correctly. Child nodes are attached to it.");
error.node = atRule;
throw error;
}
const { nodes: paramsNodes } = valueParser(atRule[key]);
// No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (paramsNodes.length === 0 || paramsNodes[0].type !== "string" && paramsNodes[0].type !== "function") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
let isStringValue;
let url;
if (paramsNodes[0].type === "string") {
isStringValue = true;
url = paramsNodes[0].value;
} else {
// Invalid function - `@import nourl(test.css);`
if (paramsNodes[0].value.toLowerCase() !== "url") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
isStringValue = paramsNodes[0].nodes.length !== 0 && paramsNodes[0].nodes[0].type === "string";
url = isStringValue ? paramsNodes[0].nodes[0].value : valueParser.stringify(paramsNodes[0].nodes);
}
url = normalizeUrl(url, isStringValue);
const isRequestable = isUrlRequestable(url);
let prefix;
if (isRequestable) {
const queryParts = url.split("!");
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
}
// Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
const mediaNodes = paramsNodes.slice(1);
let media;
if (mediaNodes.length > 0) {
media = valueParser.stringify(mediaNodes).trim().toLowerCase();
}
// eslint-disable-next-line consistent-return
return {
atRule,
prefix,
url,
media,
isRequestable
};
}
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-import-parser",
prepare (result) {
const parsedAtRules = [];
return {
AtRule: {
import (atRule) {
let parsedAtRule;
try {
parsedAtRule = parseNode(atRule, "params", result);
} catch (error) {
result.warn(error.message, {
node: error.node
});
}
if (!parsedAtRule) {
return;
}
parsedAtRules.push(parsedAtRule);
}
},
async OnceExit () {
if (parsedAtRules.length === 0) {
return;
}
const resolvedAtRules = await Promise.all(parsedAtRules.map(async (parsedAtRule)=>{
const { atRule , isRequestable , prefix , url , media } = parsedAtRule;
if (options.filter) {
const needKeep = await options.filter(url, media);
if (!needKeep) {
return;
}
}
if (isRequestable) {
const request = requestify(url, options.rootContext);
const { resolver , context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
request,
url
]),
]);
if (!resolvedUrl) {
return;
}
if (resolvedUrl === options.resourcePath) {
atRule.remove();
return;
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
media,
prefix,
isRequestable
};
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url,
media,
prefix,
isRequestable
};
}));
const urlToNameMap = new Map();
for(let index = 0; index <= resolvedAtRules.length - 1; index++){
const resolvedAtRule = resolvedAtRules[index];
if (!resolvedAtRule) {
continue;
}
const { url , isRequestable , media } = resolvedAtRule;
if (!isRequestable) {
options.api.push({
url,
media,
index
});
continue;
}
const { prefix } = resolvedAtRule;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "rule_import",
importName,
url: options.urlHandler(newUrl),
index
});
}
options.api.push({
importName,
media,
index
});
}
}
};
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-import-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,312 @@
import valueParser from "next/dist/compiled/postcss-value-parser";
import { resolveRequests, normalizeUrl, requestify, isUrlRequestable, isDataUrl, WEBPACK_IGNORE_COMMENT_REGEXP } from "../utils";
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
if (index === 0 && typeof inBetween !== "undefined") {
return inBetween;
}
let prevValueNode = nodes[index - 1];
if (!prevValueNode) {
// eslint-disable-next-line consistent-return
return;
}
if (prevValueNode.type === "space") {
if (!nodes[index - 2]) {
// eslint-disable-next-line consistent-return
return;
}
prevValueNode = nodes[index - 2];
}
if (prevValueNode.type !== "comment") {
// eslint-disable-next-line consistent-return
return;
}
const matched = prevValueNode.value.match(WEBPACK_IGNORE_COMMENT_REGEXP);
return matched && matched[2] === "true";
}
function shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL) {
if (url.length === 0) {
result.warn(`Unable to find uri in '${declaration.toString()}'`, {
node: declaration
});
return false;
}
if (isDataUrl(url) && isSupportDataURLInNewURL) {
try {
decodeURIComponent(url);
} catch (ignoreError) {
return false;
}
return true;
}
if (!isUrlRequestable(url)) {
return false;
}
return true;
}
function parseDeclaration(declaration, key, result, isSupportDataURLInNewURL) {
if (!needParseDeclaration.test(declaration[key])) {
return;
}
const parsed = valueParser(declaration.raws && declaration.raws.value && declaration.raws.value.raw ? declaration.raws.value.raw : declaration[key]);
let inBetween;
if (declaration.raws && declaration.raws.between) {
const lastCommentIndex = declaration.raws.between.lastIndexOf("/*");
const matched = declaration.raws.between.slice(lastCommentIndex).match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
inBetween = matched[2] === "true";
}
}
let isIgnoreOnDeclaration = false;
const prevNode = declaration.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
isIgnoreOnDeclaration = matched[2] === "true";
}
}
let needIgnore;
const parsedURLs = [];
parsed.walk((valueNode, index, valueNodes)=>{
if (valueNode.type !== "function") {
return;
}
if (isUrlFunc.test(valueNode.value)) {
needIgnore = getWebpackIgnoreCommentValue(index, valueNodes, inBetween);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
return;
}
const { nodes } = valueNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : valueParser.stringify(nodes);
url = normalizeUrl(url, isStringValue);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(valueNode),
prefix,
url,
needQuotes: false
});
// eslint-disable-next-line consistent-return
return false;
} else if (isImageSetFunc.test(valueNode.value)) {
for (const [innerIndex, nNode] of valueNode.nodes.entries()){
const { type , value } = nNode;
if (type === "function" && isUrlFunc.test(value)) {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
continue;
}
const { nodes } = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : valueParser.stringify(nodes);
url = normalizeUrl(url, isStringValue);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(nNode),
prefix,
url,
needQuotes: false
});
} else if (type === "string") {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
continue;
}
let url = normalizeUrl(value, true);
// Do not traverse inside `url`
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: nNode,
prefix,
url,
needQuotes: true
});
}
}
// Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
// eslint-disable-next-line consistent-return
return parsedURLs;
}
const plugin = (options = {})=>{
return {
postcssPlugin: "postcss-url-parser",
prepare (result) {
const parsedDeclarations = [];
return {
Declaration (declaration) {
const { isSupportDataURLInNewURL } = options;
const parsedURL = parseDeclaration(declaration, "value", result, isSupportDataURLInNewURL);
if (!parsedURL) {
return;
}
parsedDeclarations.push(...parsedURL);
},
async OnceExit () {
if (parsedDeclarations.length === 0) {
return;
}
const resolvedDeclarations = await Promise.all(parsedDeclarations.map(async (parsedDeclaration)=>{
const { url } = parsedDeclaration;
if (options.filter) {
const needKeep = await options.filter(url);
if (!needKeep) {
// eslint-disable-next-line consistent-return
return;
}
}
if (isDataUrl(url)) {
// eslint-disable-next-line consistent-return
return parsedDeclaration;
}
const splittedUrl = url.split(/(\?)?#/);
const [pathname, query, hashOrQuery] = splittedUrl;
let hash = query ? "?" : "";
hash += hashOrQuery ? `#${hashOrQuery}` : "";
const { needToResolveURL , rootContext } = options;
const request = requestify(pathname, rootContext, needToResolveURL);
if (!needToResolveURL) {
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: request,
hash
};
}
const { resolver , context } = options;
const resolvedUrl = await resolveRequests(resolver, context, [
...new Set([
request,
url
]),
]);
if (!resolvedUrl) {
// eslint-disable-next-line consistent-return
return;
}
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: resolvedUrl,
hash
};
}));
const urlToNameMap = new Map();
const urlToReplacementMap = new Map();
let hasUrlImportHelper = false;
for(let index = 0; index <= resolvedDeclarations.length - 1; index++){
const item = resolvedDeclarations[index];
if (!item) {
continue;
}
if (!hasUrlImportHelper) {
options.imports.push({
type: "get_url_import",
importName: "___CSS_LOADER_GET_URL_IMPORT___",
url: options.urlHandler(require.resolve("../runtime/getUrl.js")),
index: -1
});
hasUrlImportHelper = true;
}
const { url , prefix } = item;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "url",
importName,
url: options.needToResolveURL ? options.urlHandler(newUrl) : JSON.stringify(newUrl),
index
});
}
const { hash , needQuotes } = item;
const replacementKey = JSON.stringify({
newUrl,
hash,
needQuotes
});
let replacementName = urlToReplacementMap.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`;
urlToReplacementMap.set(replacementKey, replacementName);
options.replacements.push({
replacementName,
importName,
hash,
needQuotes
});
}
// eslint-disable-next-line no-param-reassign
item.node.type = "word";
// eslint-disable-next-line no-param-reassign
item.node.value = replacementName;
// eslint-disable-next-line no-param-reassign
item.declaration.value = item.parsed.toString();
}
}
};
}
};
};
plugin.postcss = true;
export default plugin;
//# sourceMappingURL=postcss-url-parser.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,87 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ // css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function(useSourceMap) {
var list = [] // return the list of modules as css string
;
list.toString = function toString() {
return this.map(function(item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join("");
} // import a list of modules into the list
;
// eslint-disable-next-line func-names
list.i = function(modules, mediaQuery, dedupe) {
if (typeof modules === "string") {
// eslint-disable-next-line no-param-reassign
modules = [
[
null,
modules,
""
]
];
}
var alreadyImportedModules = {};
if (dedupe) {
for(var i = 0; i < this.length; i++){
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for(var _i = 0; _i < modules.length; _i++){
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || "" // eslint-disable-next-line prefer-destructuring
;
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === "function") {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function(source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */");
});
return [
content
].concat(sourceURLs).concat([
sourceMapping
]).join("\n");
}
return [
content
].join("\n");
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
//# sourceMappingURL=api.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/runtime/api.js"],"names":["module","exports","useSourceMap","list","toString","map","item","content","cssWithMappingToString","concat","join","i","modules","mediaQuery","dedupe","alreadyImportedModules","length","id","_i","push","cssMapping","btoa","sourceMapping","toComment","sourceURLs","sources","source","sourceRoot","sourceMap","base64","unescape","encodeURIComponent","JSON","stringify","data"],"mappings":"AAAA;;;EAGE,CACF,4CAA4C;AAC5C,sCAAsC;AACtCA,MAAM,CAACC,OAAO,GAAG,SAAUC,YAAY,EAAE;IACvC,IAAIC,IAAI,GAAG,EAAE,CAAC,2CAA2C;IAA5C;IAEbA,IAAI,CAACC,QAAQ,GAAG,SAASA,QAAQ,GAAG;QAClC,OAAO,IAAI,CAACC,GAAG,CAAC,SAAUC,IAAI,EAAE;YAC9B,IAAIC,OAAO,GAAGC,sBAAsB,CAACF,IAAI,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,SAAS,CAACL,SAAS,CAAC,CAAC,CAAC,CAAC;IAC1E,IAAIM,IAAI,GACN,8DAA8D,CAACzB,MAAM,CACnEoB,MAAM,CACP;IACH,OAAO,MAAM,CAACpB,MAAM,CAACyB,IAAI,EAAE,KAAK,CAAC,CAAA;CAClC"}

View File

@@ -0,0 +1,25 @@
module.exports = function(url, options) {
if (!options) {
// eslint-disable-next-line no-param-reassign
options = {};
} // eslint-disable-next-line no-underscore-dangle, no-param-reassign
url = url && url.__esModule ? url.default : url;
if (typeof url !== "string") {
return url;
} // If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
// eslint-disable-next-line no-param-reassign
url = url.slice(1, -1);
}
if (options.hash) {
// eslint-disable-next-line no-param-reassign
url += options.hash;
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || options.needQuotes) {
return '"'.concat(url.replace(/"/g, '\\"').replace(/\n/g, "\\n"), '"');
}
return url;
};
//# sourceMappingURL=getUrl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../../build/webpack/loaders/css-loader/src/runtime/getUrl.js"],"names":["module","exports","url","options","__esModule","default","test","slice","hash","needQuotes","concat","replace"],"mappings":"AAAAA,MAAM,CAACC,OAAO,GAAG,SAAUC,GAAG,EAAEC,OAAO,EAAE;IACvC,IAAI,CAACA,OAAO,EAAE;QACZ,6CAA6C;QAC7CA,OAAO,GAAG,EAAE;KACb,CAAC,mEAAmE;IAErED,GAAG,GAAGA,GAAG,IAAIA,GAAG,CAACE,UAAU,GAAGF,GAAG,CAACG,OAAO,GAAGH,GAAG;IAE/C,IAAI,OAAOA,GAAG,KAAK,QAAQ,EAAE;QAC3B,OAAOA,GAAG,CAAA;KACX,CAAC,mDAAmD;IAErD,IAAI,eAAeI,IAAI,CAACJ,GAAG,CAAC,EAAE;QAC5B,6CAA6C;QAC7CA,GAAG,GAAGA,GAAG,CAACK,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;KACvB;IAED,IAAIJ,OAAO,CAACK,IAAI,EAAE;QAChB,6CAA6C;QAC7CN,GAAG,IAAIC,OAAO,CAACK,IAAI;KACpB,CAAC,yBAAyB;IAC3B,kDAAkD;IAElD,IAAI,cAAcF,IAAI,CAACJ,GAAG,CAAC,IAAIC,OAAO,CAACM,UAAU,EAAE;QACjD,OAAO,GAAG,CAACC,MAAM,CAACR,GAAG,CAACS,OAAO,OAAO,KAAK,CAAC,CAACA,OAAO,QAAQ,KAAK,CAAC,EAAE,GAAG,CAAC,CAAA;KACvE;IAED,OAAOT,GAAG,CAAA;CACX"}

View File

@@ -0,0 +1,364 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/ import { fileURLToPath } from "url";
import path from "path";
import { urlToRequest } from "next/dist/compiled/loader-utils3";
import modulesValues from "next/dist/compiled/postcss-modules-values";
import localByDefault from "next/dist/compiled/postcss-modules-local-by-default";
import extractImports from "next/dist/compiled/postcss-modules-extract-imports";
import modulesScope from "next/dist/compiled/postcss-modules-scope";
import camelCase from "./camelcase";
const whitespace = "[\\x20\\t\\r\\n\\f]";
const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, "ig");
const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
function unescape(str) {
return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace)=>{
const high = `0x${escaped}` - 0x10000;
/* eslint-disable line-comment-position */ // NaN means non-codepoint
// Workaround erroneous numeric interpretation of +"0x"
// eslint-disable-next-line no-self-compare
return high !== high || escapedWhitespace ? escaped : high < 0 ? String.fromCharCode(high + 0x10000) : // eslint-disable-next-line no-bitwise
String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
/* eslint-enable line-comment-position */ });
}
function normalizePath(file) {
return path.sep === "\\" ? file.replace(/\\/g, "/") : file;
}
function fixedEncodeURIComponent(str) {
return str.replace(/[!'()*]/g, (c)=>`%${c.charCodeAt(0).toString(16)}`);
}
function normalizeUrl(url, isStringValue) {
let normalizedUrl = url;
if (isStringValue && /\\(\n|\r\n|\r|\f)/.test(normalizedUrl)) {
normalizedUrl = normalizedUrl.replace(/\\(\n|\r\n|\r|\f)/g, "");
}
if (matchNativeWin32Path.test(url)) {
try {
normalizedUrl = decodeURIComponent(normalizedUrl);
} catch (error) {
// Ignores invalid and broken URLs and try to resolve them as is
}
return normalizedUrl;
}
normalizedUrl = unescape(normalizedUrl);
if (isDataUrl(url)) {
return fixedEncodeURIComponent(normalizedUrl);
}
try {
normalizedUrl = decodeURI(normalizedUrl);
} catch (error) {
// Ignores invalid and broken URLs and try to resolve them as is
}
return normalizedUrl;
}
function requestify(url, rootContext) {
if (/^file:/i.test(url)) {
return fileURLToPath(url);
}
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return url;
}
return url.charAt(0) === "/" ? urlToRequest(url, rootContext) : urlToRequest(url);
}
function getFilter(filter, resourcePath) {
return (...args)=>{
if (typeof filter === "function") {
return filter(...args, resourcePath);
}
return true;
};
}
function shouldUseImportPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.import === "boolean") {
return options.import;
}
return true;
}
function shouldUseURLPlugin(options) {
if (options.modules.exportOnlyLocals) {
return false;
}
if (typeof options.url === "boolean") {
return options.url;
}
return true;
}
function shouldUseModulesPlugins(options) {
return options.modules.compileType === "module";
}
function shouldUseIcssPlugin(options) {
return options.icss === true || Boolean(options.modules);
}
function getModulesPlugins(options, loaderContext, meta) {
const { mode , getLocalIdent , localIdentName , localIdentContext , localIdentHashPrefix , localIdentRegExp , } = options.modules;
let plugins = [];
try {
plugins = [
modulesValues,
localByDefault({
mode
}),
extractImports(),
modulesScope({
generateScopedName (exportName) {
return getLocalIdent(loaderContext, localIdentName, exportName, {
context: localIdentContext,
hashPrefix: localIdentHashPrefix,
regExp: localIdentRegExp
}, meta);
},
exportGlobals: options.modules.exportGlobals
}),
];
} catch (error) {
loaderContext.emitError(error);
}
return plugins;
}
const IS_NATIVE_WIN32_PATH = /^[a-z]:[/\\]|^\\\\/i;
const ABSOLUTE_SCHEME = /^[a-z0-9+\-.]+:/i;
function getURLType(source) {
if (source[0] === "/") {
if (source[1] === "/") {
return "scheme-relative";
}
return "path-absolute";
}
if (IS_NATIVE_WIN32_PATH.test(source)) {
return "path-absolute";
}
return ABSOLUTE_SCHEME.test(source) ? "absolute" : "path-relative";
}
function normalizeSourceMap(map, resourcePath) {
let newMap = map;
// Some loader emit source map as string
// Strip any JSON XSSI avoidance prefix from the string (as documented in the source maps specification), and then parse the string as JSON.
if (typeof newMap === "string") {
newMap = JSON.parse(newMap);
}
delete newMap.file;
const { sourceRoot } = newMap;
delete newMap.sourceRoot;
if (newMap.sources) {
// Source maps should use forward slash because it is URLs (https://github.com/mozilla/source-map/issues/91)
// We should normalize path because previous loaders like `sass-loader` using backslash when generate source map
newMap.sources = newMap.sources.map((source)=>{
// Non-standard syntax from `postcss`
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
// Do no touch `scheme-relative` and `absolute` URLs
if (sourceType === "path-relative" || sourceType === "path-absolute") {
const absoluteSource = sourceType === "path-relative" && sourceRoot ? path.resolve(sourceRoot, normalizePath(source)) : normalizePath(source);
return path.relative(path.dirname(resourcePath), absoluteSource);
}
return source;
});
}
return newMap;
}
function getPreRequester({ loaders , loaderIndex }) {
const cache = Object.create(null);
return (number)=>{
if (cache[number]) {
return cache[number];
}
if (number === false) {
cache[number] = "";
} else {
const loadersRequest = loaders.slice(loaderIndex, loaderIndex + 1 + (typeof number !== "number" ? 0 : number)).map((x)=>x.request).join("!");
cache[number] = `-!${loadersRequest}!`;
}
return cache[number];
};
}
function getImportCode(imports, options) {
let code = "";
for (const item of imports){
const { importName , url , icss } = item;
if (options.esModule) {
if (icss && options.modules.namedExport) {
code += `import ${options.modules.exportOnlyLocals ? "" : `${importName}, `}* as ${importName}_NAMED___ from ${url};\n`;
} else {
code += `import ${importName} from ${url};\n`;
}
} else {
code += `var ${importName} = require(${url});\n`;
}
}
return code ? `// Imports\n${code}` : "";
}
function normalizeSourceMapForRuntime(map, loaderContext) {
const resultMap = map ? map.toJSON() : null;
if (resultMap) {
delete resultMap.file;
resultMap.sourceRoot = "";
resultMap.sources = resultMap.sources.map((source)=>{
// Non-standard syntax from `postcss`
if (source.indexOf("<") === 0) {
return source;
}
const sourceType = getURLType(source);
if (sourceType !== "path-relative") {
return source;
}
const resourceDirname = path.dirname(loaderContext.resourcePath);
const absoluteSource = path.resolve(resourceDirname, source);
const contextifyPath = normalizePath(path.relative(loaderContext.rootContext, absoluteSource));
return `webpack://${contextifyPath}`;
});
}
return JSON.stringify(resultMap);
}
function getModuleCode(result, api, replacements, options, loaderContext) {
if (options.modules.exportOnlyLocals === true) {
return "";
}
const sourceMapValue = options.sourceMap ? `,${normalizeSourceMapForRuntime(result.map, loaderContext)}` : "";
let code = JSON.stringify(result.css);
let beforeCode = `var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(${options.sourceMap});\n`;
for (const item of api){
const { url , media , dedupe } = item;
beforeCode += url ? `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${media ? `, ${JSON.stringify(media)}` : ""}]);\n` : `___CSS_LOADER_EXPORT___.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ""}${dedupe ? ", true" : ""});\n`;
}
for (const item1 of replacements){
const { replacementName , importName , localName } = item1;
if (localName) {
code = code.replace(new RegExp(replacementName, "g"), ()=>options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify(camelCase(localName))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`);
} else {
const { hash , needQuotes } = item1;
const getUrlOptions = [].concat(hash ? [
`hash: ${JSON.stringify(hash)}`
] : []).concat(needQuotes ? "needQuotes: true" : []);
const preparedOptions = getUrlOptions.length > 0 ? `, { ${getUrlOptions.join(", ")} }` : "";
beforeCode += `var ${replacementName} = ___CSS_LOADER_GET_URL_IMPORT___(${importName}${preparedOptions});\n`;
code = code.replace(new RegExp(replacementName, "g"), ()=>`" + ${replacementName} + "`);
}
}
return `${beforeCode}// Module\n___CSS_LOADER_EXPORT___.push([module.id, ${code}, ""${sourceMapValue}]);\n`;
}
function dashesCamelCase(str) {
return str.replace(/-+(\w)/g, (match, firstLetter)=>firstLetter.toUpperCase());
}
function getExportCode(exports, replacements, options) {
let code = "// Exports\n";
let localsCode = "";
const addExportToLocalsCode = (name, value)=>{
if (options.modules.namedExport) {
localsCode += `export const ${camelCase(name)} = ${JSON.stringify(value)};\n`;
} else {
if (localsCode) {
localsCode += `,\n`;
}
localsCode += `\t${JSON.stringify(name)}: ${JSON.stringify(value)}`;
}
};
for (const { name: name1 , value: value1 } of exports){
switch(options.modules.exportLocalsConvention){
case "camelCase":
{
addExportToLocalsCode(name1, value1);
const modifiedName = camelCase(name1);
if (modifiedName !== name1) {
addExportToLocalsCode(modifiedName, value1);
}
break;
}
case "camelCaseOnly":
{
addExportToLocalsCode(camelCase(name1), value1);
break;
}
case "dashes":
{
addExportToLocalsCode(name1, value1);
const modifiedName = dashesCamelCase(name1);
if (modifiedName !== name1) {
addExportToLocalsCode(modifiedName, value1);
}
break;
}
case "dashesOnly":
{
addExportToLocalsCode(dashesCamelCase(name1), value1);
break;
}
case "asIs":
default:
addExportToLocalsCode(name1, value1);
break;
}
}
for (const item of replacements){
const { replacementName , localName } = item;
if (localName) {
const { importName } = item;
localsCode = localsCode.replace(new RegExp(replacementName, "g"), ()=>{
if (options.modules.namedExport) {
return `" + ${importName}_NAMED___[${JSON.stringify(camelCase(localName))}] + "`;
} else if (options.modules.exportOnlyLocals) {
return `" + ${importName}[${JSON.stringify(localName)}] + "`;
}
return `" + ${importName}.locals[${JSON.stringify(localName)}] + "`;
});
} else {
localsCode = localsCode.replace(new RegExp(replacementName, "g"), ()=>`" + ${replacementName} + "`);
}
}
if (options.modules.exportOnlyLocals) {
code += options.modules.namedExport ? localsCode : `${options.esModule ? "export default" : "module.exports ="} {\n${localsCode}\n};\n`;
return code;
}
if (localsCode) {
code += options.modules.namedExport ? localsCode : `___CSS_LOADER_EXPORT___.locals = {\n${localsCode}\n};\n`;
}
code += `${options.esModule ? "export default" : "module.exports ="} ___CSS_LOADER_EXPORT___;\n`;
return code;
}
async function resolveRequests(resolve, context, possibleRequests) {
return resolve(context, possibleRequests[0]).then((result)=>{
return result;
}).catch((error)=>{
const [, ...tailPossibleRequests] = possibleRequests;
if (tailPossibleRequests.length === 0) {
throw error;
}
return resolveRequests(resolve, context, tailPossibleRequests);
});
}
function isUrlRequestable(url) {
// Protocol-relative URLs
if (/^\/\//.test(url)) {
return false;
}
// `file:` protocol
if (/^file:/i.test(url)) {
return true;
}
// Absolute URLs
if (/^[a-z][a-z0-9+.-]*:/i.test(url)) {
return true;
}
// `#` URLs
if (/^#/.test(url)) {
return false;
}
return true;
}
function sort(a, b) {
return a.index - b.index;
}
function isDataUrl(url) {
if (/^data:/i.test(url)) {
return true;
}
return false;
}
export { isDataUrl, shouldUseModulesPlugins, shouldUseImportPlugin, shouldUseURLPlugin, shouldUseIcssPlugin, normalizeUrl, requestify, getFilter, getModulesPlugins, normalizeSourceMap, getPreRequester, getImportCode, getModuleCode, getExportCode, resolveRequests, isUrlRequestable, sort, };
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
import chalk from "next/dist/compiled/chalk";
import path from "path";
const ErrorLoader = function() {
var ref, ref1, ref2;
// @ts-ignore exists
const options = this.getOptions() || {};
const { reason ="An unknown error has occurred" } = options;
// @ts-expect-error
const resource = ((ref = this._module) == null ? void 0 : (ref1 = ref.issuer) == null ? void 0 : ref1.resource) ?? null;
const context = this.rootContext ?? ((ref2 = this._compiler) == null ? void 0 : ref2.context);
const issuer = resource ? context ? path.relative(context, resource) : resource : null;
const err = new Error(reason + (issuer ? `\nLocation: ${chalk.cyan(issuer)}` : ""));
this.emitError(err);
};
export default ErrorLoader;
//# sourceMappingURL=error-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/error-loader.ts"],"names":["chalk","path","ErrorLoader","options","getOptions","reason","resource","_module","issuer","context","rootContext","_compiler","relative","err","Error","cyan","emitError"],"mappings":"AAAA,OAAOA,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,IAAI,MAAM,MAAM,CAAA;AAGvB,MAAMC,WAAW,GAAqC,WAAY;QAO/C,GAAY,QACO,IAAc;IAPlD,oBAAoB;IACpB,MAAMC,OAAO,GAAG,IAAI,CAACC,UAAU,EAAE,IAAK,EAAE,AAAQ;IAEhD,MAAM,EAAEC,MAAM,EAAG,+BAA+B,CAAA,EAAE,GAAGF,OAAO;IAE5D,mBAAmB;IACnB,MAAMG,QAAQ,GAAG,CAAA,CAAA,GAAY,GAAZ,IAAI,CAACC,OAAO,SAAQ,GAApB,KAAA,CAAoB,GAApB,QAAA,GAAY,CAAEC,MAAM,SAAA,GAApB,KAAA,CAAoB,QAAEF,QAAQ,AAAV,CAAA,IAAc,IAAI;IACvD,MAAMG,OAAO,GAAG,IAAI,CAACC,WAAW,IAAI,CAAA,CAAA,IAAc,GAAd,IAAI,CAACC,SAAS,SAAS,GAAvB,KAAA,CAAuB,GAAvB,IAAc,CAAEF,OAAO,CAAA;IAE3D,MAAMD,MAAM,GAAGF,QAAQ,GACnBG,OAAO,GACLR,IAAI,CAACW,QAAQ,CAACH,OAAO,EAAEH,QAAQ,CAAC,GAChCA,QAAQ,GACV,IAAI;IAER,MAAMO,GAAG,GAAG,IAAIC,KAAK,CACnBT,MAAM,GAAG,CAACG,MAAM,GAAG,CAAC,YAAY,EAAER,KAAK,CAACe,IAAI,CAACP,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAC7D;IACD,IAAI,CAACQ,SAAS,CAACH,GAAG,CAAC;CACpB;AAED,eAAeX,WAAW,CAAA"}

View File

@@ -0,0 +1,8 @@
/**
* A getter for module build info that casts to the type it should have.
* We also expose here types to make easier to use it.
*/ export function getModuleBuildInfo(webpackModule) {
return webpackModule.buildInfo;
}
//# sourceMappingURL=get-module-build-info.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/get-module-build-info.ts"],"names":["getModuleBuildInfo","webpackModule","buildInfo"],"mappings":"AAMA;;;GAGG,CACH,OAAO,SAASA,kBAAkB,CAACC,aAA6B,EAAE;IAChE,OAAOA,aAAa,CAACC,SAAS,CAY7B;CACF"}

View File

@@ -0,0 +1,191 @@
import chalk from "next/dist/compiled/chalk";
import { NODE_RESOLVE_OPTIONS } from "../../webpack-config";
import { getModuleBuildInfo } from "./get-module-build-info";
import { sep } from "path";
import { verifyRootLayout } from "../../../lib/verifyRootLayout";
import * as Log from "../../../build/output/log";
import { APP_DIR_ALIAS } from "../../../lib/constants";
const FILE_TYPES = {
layout: "layout",
template: "template",
error: "error",
loading: "loading",
head: "head",
"not-found": "not-found"
};
const GLOBAL_ERROR_FILE_TYPE = "global-error";
const PAGE_SEGMENT = "page$";
async function createTreeCodeFromPath({ pagePath , resolve , resolveParallelSegments }) {
const splittedPath = pagePath.split(/[\\/]/);
const appDirPrefix = splittedPath[0];
const pages = [];
let rootLayout;
let globalError;
async function createSubtreePropsFromSegmentPath(segments) {
const segmentPath = segments.join("/");
// Existing tree are the children of the current segment
const props = {};
// We need to resolve all parallel routes in this level.
const parallelSegments = [];
if (segments.length === 0) {
parallelSegments.push([
"children",
""
]);
} else {
parallelSegments.push(...resolveParallelSegments(segmentPath));
}
for (const [parallelKey, parallelSegment] of parallelSegments){
if (parallelSegment === PAGE_SEGMENT) {
const matchedPagePath = `${appDirPrefix}${segmentPath}/page`;
const resolvedPagePath = await resolve(matchedPagePath);
if (resolvedPagePath) pages.push(resolvedPagePath);
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[parallelKey] = `['', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(resolvedPagePath)}), ${JSON.stringify(resolvedPagePath)}]}]`;
continue;
}
const parallelSegmentPath = segmentPath + "/" + parallelSegment;
const subtree = await createSubtreePropsFromSegmentPath([
...segments,
parallelSegment,
]);
// `page` is not included here as it's added above.
const filePaths = await Promise.all(Object.values(FILE_TYPES).map(async (file)=>{
return [
file,
await resolve(`${appDirPrefix}${parallelSegmentPath}/${file}`),
];
}));
if (!rootLayout) {
var ref;
rootLayout = (ref = filePaths.find(([type, path])=>type === "layout" && !!path)) == null ? void 0 : ref[1];
}
if (!globalError) {
globalError = await resolve(`${appDirPrefix}${parallelSegmentPath}/${GLOBAL_ERROR_FILE_TYPE}`);
}
props[parallelKey] = `[
'${parallelSegment}',
${subtree},
{
${filePaths.filter(([, filePath])=>filePath !== undefined).map(([file, filePath])=>{
if (filePath === undefined) {
return "";
}
return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(filePath)}), ${JSON.stringify(filePath)}],`;
}).join("\n")}
}
]`;
}
return `{
${Object.entries(props).map(([key, value])=>`${key}: ${value}`).join(",\n")}
}`;
}
const tree = await createSubtreePropsFromSegmentPath([]);
return [
`const tree = ${tree}.children;`,
pages,
rootLayout,
globalError
];
}
function createAbsolutePath(appDir, pathToTurnAbsolute) {
return pathToTurnAbsolute// Replace all POSIX path separators with the current OS path separator
.replace(/\//g, sep).replace(/^private-next-app-dir/, appDir);
}
const nextAppLoader = async function nextAppLoader() {
const { name , appDir , appPaths , pagePath , pageExtensions , rootDir , tsconfigPath , isDev , } = this.getOptions() || {};
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.route = {
page: name.replace(/^app/, ""),
absolutePagePath: createAbsolutePath(appDir, pagePath)
};
const extensions = pageExtensions.map((extension)=>`.${extension}`);
const resolveOptions = {
...NODE_RESOLVE_OPTIONS,
extensions
};
const resolve = this.getResolve(resolveOptions);
const normalizedAppPaths = typeof appPaths === "string" ? [
appPaths
] : appPaths || [];
const resolveParallelSegments = (pathname)=>{
const matched = {};
for (const path of normalizedAppPaths){
if (path.startsWith(pathname + "/")) {
const rest = path.slice(pathname.length + 1).split("/");
let matchedSegment = rest[0];
// It is the actual page, mark it sepcially.
if (rest.length === 1 && matchedSegment === "page") {
matchedSegment = PAGE_SEGMENT;
}
const matchedKey = matchedSegment.startsWith("@") ? matchedSegment.slice(1) : "children";
matched[matchedKey] = matchedSegment;
}
}
return Object.entries(matched);
};
const resolver = async (pathname)=>{
try {
const resolved = await resolve(this.rootContext, pathname);
this.addDependency(resolved);
return resolved;
} catch (err) {
const absolutePath = createAbsolutePath(appDir, pathname);
for (const ext of extensions){
const absolutePathWithExtension = `${absolutePath}${ext}`;
this.addMissingDependency(absolutePathWithExtension);
}
if (err.message.includes("Can't resolve")) {
return undefined;
}
throw err;
}
};
const [treeCode, pages, rootLayout, globalError] = await createTreeCodeFromPath({
pagePath,
resolve: resolver,
resolveParallelSegments
});
if (!rootLayout) {
const errorMessage = `${chalk.bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ""))} doesn't have a root layout. To fix this error, make sure every page has a root layout.`;
if (!isDev) {
// If we're building and missing a root layout, exit the build
Log.error(errorMessage);
process.exit(1);
} else {
// In dev we'll try to create a root layout
const createdRootLayout = await verifyRootLayout({
appDir: appDir,
dir: rootDir,
tsconfigPath: tsconfigPath,
pagePath,
pageExtensions
});
if (!createdRootLayout) {
throw new Error(errorMessage);
}
}
}
const result = `
export ${treeCode}
export const pages = ${JSON.stringify(pages)}
export { default as AppRouter } from 'next/dist/client/components/app-router'
export { default as LayoutRouter } from 'next/dist/client/components/layout-router'
export { default as RenderFromTemplateContext } from 'next/dist/client/components/render-from-template-context'
export { default as GlobalError } from ${JSON.stringify(globalError || "next/dist/client/components/error-boundary")}
export { staticGenerationAsyncStorage } from 'next/dist/client/components/static-generation-async-storage'
export { requestAsyncStorage } from 'next/dist/client/components/request-async-storage'
export * as serverHooks from 'next/dist/client/components/hooks-server-context'
export { renderToReadableStream } from 'next/dist/compiled/react-server-dom-webpack/server.browser'
export const __next_app_webpack_require__ = __webpack_require__
`;
return result;
};
export default nextAppLoader;
//# sourceMappingURL=next-app-loader.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { stringifyRequest } from "../stringify-request";
// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
function nextClientPagesLoader() {
const pagesLoaderSpan = this.currentTraceSpan.traceChild("next-client-pages-loader");
return pagesLoaderSpan.traceFn(()=>{
const { absolutePagePath , page } = this.getOptions();
pagesLoaderSpan.setAttribute("absolutePagePath", absolutePagePath);
const stringifiedPageRequest = stringifyRequest(this, absolutePagePath);
const stringifiedPage = JSON.stringify(page);
return `
(window.__NEXT_P = window.__NEXT_P || []).push([
${stringifiedPage},
function () {
return require(${stringifiedPageRequest});
}
]);
if(module.hot) {
module.hot.dispose(function () {
window.__NEXT_P.push([${stringifiedPage}])
});
}
`;
});
}
export default nextClientPagesLoader;
//# sourceMappingURL=next-client-pages-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-client-pages-loader.ts"],"names":["stringifyRequest","nextClientPagesLoader","pagesLoaderSpan","currentTraceSpan","traceChild","traceFn","absolutePagePath","page","getOptions","setAttribute","stringifiedPageRequest","stringifiedPage","JSON","stringify"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,sBAAsB,CAAA;AAOvD,8FAA8F;AAC9F,SAASC,qBAAqB,GAAY;IACxC,MAAMC,eAAe,GAAG,IAAI,CAACC,gBAAgB,CAACC,UAAU,CACtD,0BAA0B,CAC3B;IAED,OAAOF,eAAe,CAACG,OAAO,CAAC,IAAM;QACnC,MAAM,EAAEC,gBAAgB,CAAA,EAAEC,IAAI,CAAA,EAAE,GAC9B,IAAI,CAACC,UAAU,EAAE,AAA4B;QAE/CN,eAAe,CAACO,YAAY,CAAC,kBAAkB,EAAEH,gBAAgB,CAAC;QAElE,MAAMI,sBAAsB,GAAGV,gBAAgB,CAAC,IAAI,EAAEM,gBAAgB,CAAC;QACvE,MAAMK,eAAe,GAAGC,IAAI,CAACC,SAAS,CAACN,IAAI,CAAC;QAE5C,OAAO,CAAC;;MAEN,EAAEI,eAAe,CAAC;;uBAED,EAAED,sBAAsB,CAAC;;;;;8BAKlB,EAAEC,eAAe,CAAC;;;EAG9C,CAAC,CAAA;KACA,CAAC,CAAA;CACH;AAED,eAAeV,qBAAqB,CAAA"}

View File

@@ -0,0 +1,33 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import { stringifyRequest } from "../stringify-request";
export default function middlewareLoader() {
const { absolutePagePath , page , rootDir } = this.getOptions();
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeApiFunction = {
page: page || "/"
};
buildInfo.rootDir = rootDir;
return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
enhanceGlobals()
var mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default;
if (typeof handler !== 'function') {
throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
page: ${JSON.stringify(page)},
handler,
})
}
`;
};
//# sourceMappingURL=next-edge-function-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-edge-function-loader.ts"],"names":["getModuleBuildInfo","stringifyRequest","middlewareLoader","absolutePagePath","page","rootDir","getOptions","stringifiedPagePath","buildInfo","_module","nextEdgeApiFunction","JSON","stringify"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,SAASC,gBAAgB,QAAQ,sBAAsB,CAAA;AAQvD,eAAe,SAASC,gBAAgB,GAAY;IAClD,MAAM,EAAEC,gBAAgB,CAAA,EAAEC,IAAI,CAAA,EAAEC,OAAO,CAAA,EAAE,GACvC,IAAI,CAACC,UAAU,EAAE;IACnB,MAAMC,mBAAmB,GAAGN,gBAAgB,CAAC,IAAI,EAAEE,gBAAgB,CAAC;IACpE,MAAMK,SAAS,GAAGR,kBAAkB,CAAC,IAAI,CAACS,OAAO,CAAC;IAClDD,SAAS,CAACE,mBAAmB,GAAG;QAC9BN,IAAI,EAAEA,IAAI,IAAI,GAAG;KAClB;IACDI,SAAS,CAACH,OAAO,GAAGA,OAAO;IAE3B,OAAO,CAAC;;;;;0BAKgB,EAAEE,mBAAmB,CAAC;;;;mDAIG,EAAEH,IAAI,CAAC;;;;;;oBAMtC,EAAEO,IAAI,CAACC,SAAS,CAACR,IAAI,CAAC,CAAC;;;;IAIvC,CAAC,CAAA;CACJ,CAAA"}

View File

@@ -0,0 +1,97 @@
import { getModuleBuildInfo } from "../get-module-build-info";
import { stringifyRequest } from "../../stringify-request";
/*
For pages SSR'd at the edge, we bundle them with the ESM version of Next in order to
benefit from the better tree-shaking and thus, smaller bundle sizes.
The absolute paths for _app, _error and _document, used in this loader, link to the regular CJS modules.
They are generated in `createPagesMapping` where we don't have access to `isEdgeRuntime`,
so we have to do it here. It's not that bad because it keeps all references to ESM modules magic in this place.
*/ function swapDistFolderWithEsmDistFolder(path) {
return path.replace("next/dist/pages", "next/dist/esm/pages");
}
export default async function edgeSSRLoader() {
const { dev , page , buildId , absolutePagePath , absoluteAppPath , absoluteDocumentPath , absolute500Path , absoluteErrorPath , isServerComponent , stringifiedConfig , appDirLoader: appDirLoaderBase64 , pagesType , sriEnabled , hasFontLoaders , } = this.getOptions();
const appDirLoader = Buffer.from(appDirLoaderBase64 || "", "base64").toString();
const isAppDir = pagesType === "app";
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeSSR = {
isServerComponent: isServerComponent === "true",
page: page,
isAppDir
};
buildInfo.route = {
page,
absolutePagePath
};
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const stringifiedAppPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteAppPath));
const stringifiedErrorPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteErrorPath));
const stringifiedDocumentPath = stringifyRequest(this, swapDistFolderWithEsmDistFolder(absoluteDocumentPath));
const stringified500Path = absolute500Path ? stringifyRequest(this, absolute500Path) : null;
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}${isAppDir ? "?__edge_ssr_entry__" : ""}`;
const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
enhanceGlobals()
const pageType = ${JSON.stringify(pagesType)}
${isAppDir ? `
import { renderToHTMLOrFlight as appRenderToHTML } from 'next/dist/esm/server/app-render'
import * as pageMod from ${JSON.stringify(pageModPath)}
const Document = null
const pagesRenderToHTML = null
const appMod = null
const errorMod = null
const error500Mod = null
` : `
import Document from ${stringifiedDocumentPath}
import { renderToHTML as pagesRenderToHTML } from 'next/dist/esm/server/render'
import * as pageMod from ${stringifiedPagePath}
import * as appMod from ${stringifiedAppPath}
import * as errorMod from ${stringifiedErrorPath}
${stringified500Path ? `import * as error500Mod from ${stringified500Path}` : `const error500Mod = null`}
const appRenderToHTML = null
`}
const buildManifest = self.__BUILD_MANIFEST
const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST
const rscManifest = self.__RSC_MANIFEST
const rscCssManifest = self.__RSC_CSS_MANIFEST
const subresourceIntegrityManifest = ${sriEnabled ? "self.__SUBRESOURCE_INTEGRITY_MANIFEST" : "undefined"}
const fontLoaderManifest = ${hasFontLoaders ? "self.__FONT_LOADER_MANIFEST" : "undefined"}
const render = getRender({
pageType,
dev: ${dev},
page: ${JSON.stringify(page)},
appMod,
pageMod,
errorMod,
error500Mod,
Document,
buildManifest,
appRenderToHTML,
pagesRenderToHTML,
reactLoadableManifest,
serverComponentManifest: ${isServerComponent} ? rscManifest : null,
serverCSSManifest: ${isServerComponent} ? rscCssManifest : null,
subresourceIntegrityManifest,
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
fontLoaderManifest,
})
export const ComponentMod = pageMod
export default function(opts) {
return adapter({
...opts,
handler: render
})
}`;
return transformed;
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-edge-ssr-loader/index.ts"],"names":["getModuleBuildInfo","stringifyRequest","swapDistFolderWithEsmDistFolder","path","replace","edgeSSRLoader","dev","page","buildId","absolutePagePath","absoluteAppPath","absoluteDocumentPath","absolute500Path","absoluteErrorPath","isServerComponent","stringifiedConfig","appDirLoader","appDirLoaderBase64","pagesType","sriEnabled","hasFontLoaders","getOptions","Buffer","from","toString","isAppDir","buildInfo","_module","nextEdgeSSR","route","stringifiedPagePath","stringifiedAppPath","stringifiedErrorPath","stringifiedDocumentPath","stringified500Path","pageModPath","substring","length","transformed","JSON","stringify"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,0BAA0B,CAAA;AAC7D,SAASC,gBAAgB,QAAQ,yBAAyB,CAAA;AAmB1D;;;;;;;EAOE,CACF,SAASC,+BAA+B,CAACC,IAAY,EAAE;IACrD,OAAOA,IAAI,CAACC,OAAO,CAAC,iBAAiB,EAAE,qBAAqB,CAAC,CAAA;CAC9D;AAED,eAAe,eAAeC,aAAa,GAAY;IACrD,MAAM,EACJC,GAAG,CAAA,EACHC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPC,gBAAgB,CAAA,EAChBC,eAAe,CAAA,EACfC,oBAAoB,CAAA,EACpBC,eAAe,CAAA,EACfC,iBAAiB,CAAA,EACjBC,iBAAiB,CAAA,EACjBC,iBAAiB,CAAA,EACjBC,YAAY,EAAEC,kBAAkB,CAAA,EAChCC,SAAS,CAAA,EACTC,UAAU,CAAA,EACVC,cAAc,CAAA,IACf,GAAG,IAAI,CAACC,UAAU,EAAE;IAErB,MAAML,YAAY,GAAGM,MAAM,CAACC,IAAI,CAC9BN,kBAAkB,IAAI,EAAE,EACxB,QAAQ,CACT,CAACO,QAAQ,EAAE;IACZ,MAAMC,QAAQ,GAAGP,SAAS,KAAK,KAAK;IAEpC,MAAMQ,SAAS,GAAG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d,CAAC,6BAA6B,EAAEA,kBAAkB,CAAC,CAAC,GACpD,CAAC,wBAAwB,CAAC,CAC/B;;IAEH,CAAC,CACA;;;;;;yCAMoC,EACnCf,UAAU,GAAG,uCAAuC,GAAG,WAAW,CACnE;+BAC0B,EACzBC,cAAc,GAAG,6BAA6B,GAAG,WAAW,CAC7D;;;;WAIM,EAAEd,GAAG,CAAC;YACL,EAAEiC,IAAI,CAACC,SAAS,CAACjC,IAAI,CAAC,CAAC;;;;;;;;;;+BAUJ,EAAEO,iBAAiB,CAAC;yBAC1B,EAAEA,iBAAiB,CAAC;;cAE/B,EAAEC,iBAAiB,CAAC;eACnB,EAAEwB,IAAI,CAACC,SAAS,CAAChC,OAAO,CAAC,CAAC;;;;;;;;;;;KAWpC,CAAC;IAEJ,OAAO8B,WAAW,CAAA;CACnB,CAAA"}

View File

@@ -0,0 +1,84 @@
import WebServer from "../../../../server/web-server";
import { WebNextRequest, WebNextResponse } from "../../../../server/base-http/web";
import { SERVER_RUNTIME } from "../../../../lib/constants";
export function getRender({ dev , page , appMod , pageMod , errorMod , error500Mod , pagesType , Document , buildManifest , reactLoadableManifest , appRenderToHTML , pagesRenderToHTML , serverComponentManifest , subresourceIntegrityManifest , serverCSSManifest , config , buildId , fontLoaderManifest }) {
const isAppPath = pagesType === "app";
const baseLoadComponentResult = {
dev,
buildManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
fontLoaderManifest,
Document,
App: appMod == null ? void 0 : appMod.default
};
const server = new WebServer({
dev,
conf: config,
minimalMode: true,
webServerConfig: {
page,
pagesType,
extendRenderOpts: {
buildId,
runtime: SERVER_RUNTIME.experimentalEdge,
supportsDynamicHTML: true,
disableOptimizedLoading: true,
serverComponentManifest,
serverCSSManifest
},
appRenderToHTML,
pagesRenderToHTML,
loadComponent: async (pathname)=>{
if (isAppPath) return null;
if (pathname === page) {
return {
...baseLoadComponentResult,
Component: pageMod.default,
pageConfig: pageMod.config || {},
getStaticProps: pageMod.getStaticProps,
getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths,
ComponentMod: pageMod,
pathname
};
}
// If there is a custom 500 page, we need to handle it separately.
if (pathname === "/500" && error500Mod) {
return {
...baseLoadComponentResult,
Component: error500Mod.default,
pageConfig: error500Mod.config || {},
getStaticProps: error500Mod.getStaticProps,
getServerSideProps: error500Mod.getServerSideProps,
getStaticPaths: error500Mod.getStaticPaths,
ComponentMod: error500Mod,
pathname
};
}
if (pathname === "/_error") {
return {
...baseLoadComponentResult,
Component: errorMod.default,
pageConfig: errorMod.config || {},
getStaticProps: errorMod.getStaticProps,
getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths,
ComponentMod: errorMod,
pathname
};
}
return null;
}
}
});
const requestHandler = server.getRequestHandler();
return async function render(request) {
const extendedReq = new WebNextRequest(request);
const extendedRes = new WebNextResponse();
requestHandler(extendedReq, extendedRes);
return await extendedRes.toResponse();
};
}
//# sourceMappingURL=render.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-edge-ssr-loader/render.ts"],"names":["WebServer","WebNextRequest","WebNextResponse","SERVER_RUNTIME","getRender","dev","page","appMod","pageMod","errorMod","error500Mod","pagesType","Document","buildManifest","reactLoadableManifest","appRenderToHTML","pagesRenderToHTML","serverComponentManifest","subresourceIntegrityManifest","serverCSSManifest","config","buildId","fontLoaderManifest","isAppPath","baseLoadComponentResult","App","default","server","conf","minimalMode","webServerConfig","extendRenderOpts","runtime","experimentalEdge","supportsDynamicHTML","disableOptimizedLoading","loadComponent","pathname","Component","pageConfig","getStaticProps","getServerSideProps","getStaticPaths","ComponentMod","requestHandler","getRequestHandler","render","request","extendedReq","extendedRes","toResponse"],"mappings":"AAOA,OAAOA,SAAS,MAAM,+BAA+B,CAAA;AACrD,SACEC,cAAc,EACdC,eAAe,QACV,kCAAkC,CAAA;AACzC,SAASC,cAAc,QAAQ,2BAA2B,CAAA;AAE1D,OAAO,SAASC,SAAS,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Ae,EAAE;QACzC0C,cAAc,CAACI,WAAW,EAAEC,WAAW,CAAC;QACxC,OAAO,MAAMA,WAAW,CAACC,UAAU,EAAE,CAAA;KACtC,CAAA;CACF"}

View File

@@ -0,0 +1,26 @@
import { RSC_MODULE_TYPES } from "../../../shared/lib/constants";
import { getModuleBuildInfo } from "./get-module-build-info";
import { regexCSS } from "./utils";
export default async function transformSource() {
let { modules , server } = this.getOptions();
const isServer = server === "true";
if (!Array.isArray(modules)) {
modules = modules ? [
modules
] : [];
}
const requests = modules;
const code = requests// Filter out css files on the server
.filter((request)=>isServer ? !regexCSS.test(request) : true).map((request)=>regexCSS.test(request) ? `(() => import(/* webpackMode: "lazy" */ ${JSON.stringify(request)}))` : `import(/* webpackMode: "eager" */ ${JSON.stringify(request)})`).join(";\n");
const buildInfo = getModuleBuildInfo(this._module);
const resolve = this.getResolve();
// Resolve to absolute resource url for flight manifest to collect and use to determine client components
const resolvedRequests = await Promise.all(requests.map(async (r)=>await resolve(this.rootContext, r)));
buildInfo.rsc = {
type: RSC_MODULE_TYPES.client,
requests: resolvedRequests
};
return code;
};
//# sourceMappingURL=next-flight-client-entry-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-flight-client-entry-loader.ts"],"names":["RSC_MODULE_TYPES","getModuleBuildInfo","regexCSS","transformSource","modules","server","getOptions","isServer","Array","isArray","requests","code","filter","request","test","map","JSON","stringify","join","buildInfo","_module","resolve","getResolve","resolvedRequests","Promise","all","r","rootContext","rsc","type","client"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,+BAA+B,CAAA;AAChE,SAASC,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,SAASC,QAAQ,QAAQ,SAAS,CAAA;AAWlC,eAAe,eAAeC,eAAe,GAA6B;IACxE,IAAI,EAAEC,OAAO,CAAA,EAAEC,MAAM,CAAA,EAAE,GACrB,IAAI,CAACC,UAAU,EAAE;IACnB,MAAMC,QAAQ,GAAGF,MAAM,KAAK,MAAM;IAElC,IAAI,CAACG,KAAK,CAACC,OAAO,CAACL,OAAO,CAAC,EAAE;QAC3BA,OAAO,GAAGA,OAAO,GAAG;YAACA,OAAO;SAAC,GAAG,EAAE;KACnC;IAED,MAAMM,QAAQ,GAAGN,OAAO,AAAY;IACpC,MAAMO,IAAI,GAAGD,QAAQ,AACnB,qCAAqC;KACpCE,MAAM,CAAC,CAACC,OAAO,GAAMN,QAAQ,GAAG,CAACL,QAAQ,CAACY,IAAI,CAACD,OAAO,CAAC,GAAG,IAAI,AAAC,CAAC,CAChEE,GAAG,CAAC,CAACF,OAAO,GACXX,QAAQ,CAACY,IAAI,CAACD,OAAO,CAAC,GAClB,CAAC,wCAAwC,EAAEG,IAAI,CAACC,SAAS,CAACJ,OAAO,CAAC,CAAC,EAAE,CAAC,GACtE,CAAC,kCAAkC,EAAEG,IAAI,CAACC,SAAS,CAACJ,OAAO,CAAC,CAAC,CAAC,CAAC,CACpE,CACAK,IAAI,CAAC,KAAK,CAAC;IAEd,MAAMC,SAAS,GAAGlB,kBAAkB,CAAC,IAAI,CAACmB,OAAO,CAAC;IAClD,MAAMC,OAAO,GAAG,IAAI,CAACC,UAAU,EAAE;IAEjC,yGAAyG;IACzG,MAAMC,gBAAgB,GAAG,MAAMC,OAAO,CAACC,GAAG,CACxCf,QAAQ,CAACK,GAAG,CAAC,OAAOW,CAAC,GAAK,MAAML,OAAO,CAAC,IAAI,CAACM,WAAW,EAAED,CAAC,CAAC,CAAC,CAC9D;IAEDP,SAAS,CAACS,GAAG,GAAG;QACdC,IAAI,EAAE7B,gBAAgB,CAAC8B,MAAM;QAC7BpB,QAAQ,EAAEa,gBAAgB;KAC3B;IAED,OAAOZ,IAAI,CAAA;CACZ,CAAA"}

View File

@@ -0,0 +1,27 @@
/**
* For server-side CSS imports, we need to ignore the actual module content but
* still trigger the hot-reloading diff mechanism. So here we put the content
* inside a comment.
*/ import crypto from "crypto";
export function pitch() {
if (process.env.NODE_ENV !== "production") {
const content = this.fs.readFileSync(this.resourcePath);
this.data.__checksum = crypto.createHash("sha256").update(typeof content === "string" ? Buffer.from(content) : content).digest().toString("hex");
}
}
const NextServerCSSLoader = function(content) {
this.cacheable && this.cacheable();
// Only add the checksum during development.
if (process.env.NODE_ENV !== "production") {
const isCSSModule = this.resourcePath.match(/\.module\.(css|sass|scss)$/);
const checksum = crypto.createHash("sha256").update(this.data.__checksum + (typeof content === "string" ? Buffer.from(content) : content)).digest().toString("hex").substring(0, 12);
if (isCSSModule) {
return content + "\nmodule.exports.__checksum = " + JSON.stringify(checksum);
}
return `export default ${JSON.stringify(checksum)}`;
}
return content;
};
export default NextServerCSSLoader;
//# sourceMappingURL=next-flight-css-dev-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-flight-css-dev-loader.ts"],"names":["crypto","pitch","process","env","NODE_ENV","content","fs","readFileSync","resourcePath","data","__checksum","createHash","update","Buffer","from","digest","toString","NextServerCSSLoader","cacheable","isCSSModule","match","checksum","substring","JSON","stringify"],"mappings":"AAAA;;;;GAIG,CAEH,OAAOA,MAAM,MAAM,QAAQ,CAAA;AAE3B,OAAO,SAASC,KAAK,GAAY;IAC/B,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACzC,MAAMC,OAAO,GAAG,IAAI,CAACC,EAAE,CAACC,YAAY,CAAC,IAAI,CAACC,YAAY,CAAC;QACvD,IAAI,CAACC,IAAI,CAACC,UAAU,GAAGV,MAAM,CAC1BW,UAAU,CAAC,QAAQ,CAAC,CACpBC,MAAM,CAAC,OAAOP,OAAO,KAAK,QAAQ,GAAGQ,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,GAAGA,OAAO,CAAC,CACpEU,MAAM,EAAE,CACRC,QAAQ,CAAC,KAAK,CAAC;KACnB;CACF;AAED,MAAMC,mBAAmB,GAAG,SAAqBZ,OAAe,EAAE;IAChE,IAAI,CAACa,SAAS,IAAI,IAAI,CAACA,SAAS,EAAE;IAElC,4CAA4C;IAC5C,IAAIhB,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACzC,MAAMe,WAAW,GAAG,IAAI,CAACX,YAAY,CAACY,KAAK,8BAA8B;QACzE,MAAMC,QAAQ,GAAGrB,MAAM,CACpBW,UAAU,CAAC,QAAQ,CAAC,CACpBC,MAAM,CACL,IAAI,CAACH,IAAI,CAACC,UAAU,GAClB,CAAC,OAAOL,OAAO,KAAK,QAAQ,GAAGQ,MAAM,CAACC,IAAI,CAACT,OAAO,CAAC,GAAGA,OAAO,CAAC,CACjE,CACAU,MAAM,EAAE,CACRC,QAAQ,CAAC,KAAK,CAAC,CACfM,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC;QAEnB,IAAIH,WAAW,EAAE;YACf,OACEd,OAAO,GAAG,gCAAgC,GAAGkB,IAAI,CAACC,SAAS,CAACH,QAAQ,CAAC,CACtE;SACF;QAED,OAAO,CAAC,eAAe,EAAEE,IAAI,CAACC,SAAS,CAACH,QAAQ,CAAC,CAAC,CAAC,CAAA;KACpD;IAED,OAAOhB,OAAO,CAAA;CACf;AAED,eAAeY,mBAAmB,CAAA"}

View File

@@ -0,0 +1,29 @@
import { RSC_MODULE_TYPES } from "../../../../shared/lib/constants";
import { warnOnce } from "../../../../shared/lib/utils/warn-once";
import { getRSCModuleType } from "../../../analysis/get-page-static-info";
import { getModuleBuildInfo } from "../get-module-build-info";
const noopHeadPath = require.resolve("next/dist/client/components/noop-head");
export default async function transformSource(source, sourceMap) {
var ref;
// Avoid buffer to be consumed
if (typeof source !== "string") {
throw new Error("Expected source to have been transformed to a string.");
}
const callback = this.async();
const buildInfo = getModuleBuildInfo(this._module);
const rscType = getRSCModuleType(source);
// Assign the RSC meta information to buildInfo.
// Exclude next internal files which are not marked as client files
buildInfo.rsc = {
type: rscType
};
if (((ref = buildInfo.rsc) == null ? void 0 : ref.type) === RSC_MODULE_TYPES.client) {
return callback(null, source, sourceMap);
}
if (noopHeadPath === this.resourcePath) {
warnOnce(`Warning: You're using \`next/head\` inside app directory, please migrate to \`head.js\`. Checkout https://beta.nextjs.org/docs/api-reference/file-conventions/head for details.`);
}
return callback(null, source, sourceMap);
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-flight-loader/index.ts"],"names":["RSC_MODULE_TYPES","warnOnce","getRSCModuleType","getModuleBuildInfo","noopHeadPath","require","resolve","transformSource","source","sourceMap","buildInfo","Error","callback","async","_module","rscType","rsc","type","client","resourcePath"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,kCAAkC,CAAA;AACnE,SAASC,QAAQ,QAAQ,wCAAwC,CAAA;AACjE,SAASC,gBAAgB,QAAQ,wCAAwC,CAAA;AACzE,SAASC,kBAAkB,QAAQ,0BAA0B,CAAA;AAE7D,MAAMC,YAAY,GAAGC,OAAO,CAACC,OAAO,CAAC,uCAAuC,CAAC;AAE7E,eAAe,eAAeC,eAAe,CAE3CC,MAAc,EACdC,SAAc,EACd;QAcIC,GAAa;IAbjB,8BAA8B;IAC9B,IAAI,OAAOF,MAAM,KAAK,QAAQ,EAAE;QAC9B,MAAM,IAAIG,KAAK,CAAC,uDAAuD,CAAC,CAAA;KACzE;IAED,MAAMC,QAAQ,GAAG,IAAI,CAACC,KAAK,EAAE;IAC7B,MAAMH,SAAS,GAAGP,kBAAkB,CAAC,IAAI,CAACW,OAAO,CAAC;IAClD,MAAMC,OAAO,GAAGb,gBAAgB,CAACM,MAAM,CAAC;IAExC,gDAAgD;IAChD,mEAAmE;IACnEE,SAAS,CAACM,GAAG,GAAG;QAAEC,IAAI,EAAEF,OAAO;KAAE;IAEjC,IAAIL,CAAAA,CAAAA,GAAa,GAAbA,SAAS,CAACM,GAAG,SAAM,GAAnBN,KAAAA,CAAmB,GAAnBA,GAAa,CAAEO,IAAI,CAAA,KAAKjB,gBAAgB,CAACkB,MAAM,EAAE;QACnD,OAAON,QAAQ,CAAC,IAAI,EAAEJ,MAAM,EAAEC,SAAS,CAAC,CAAA;KACzC;IAED,IAAIL,YAAY,KAAK,IAAI,CAACe,YAAY,EAAE;QACtClB,QAAQ,CACN,CAAC,+KAA+K,CAAC,CAClL;KACF;IACD,OAAOW,QAAQ,CAAC,IAAI,EAAEJ,MAAM,EAAEC,SAAS,CAAC,CAAA;CACzC,CAAA"}

View File

@@ -0,0 +1,94 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ // Modified from https://github.com/facebook/react/blob/main/packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js
const MODULE_REFERENCE = Symbol.for("react.module.reference");
const PROMISE_PROTOTYPE = Promise.prototype;
const proxyHandlers = {
get: function(target, name, _receiver) {
switch(name){
// These names are read by the Flight runtime if you end up using the exports object.
case "$$typeof":
// These names are a little too common. We should probably have a way to
// have the Flight runtime extract the inner target instead.
return target.$$typeof;
case "filepath":
return target.filepath;
case "name":
return target.name;
case "async":
return target.async;
// We need to special case this because createElement reads it if we pass this
// reference.
case "defaultProps":
return undefined;
case "__esModule":
// Something is conditionally checking which export to use. We'll pretend to be
// an ESM compat module but then we'll check again on the client.
target.default = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
// This a placeholder value that tells the client to conditionally use the
// whole object or just the default export.
name: "",
async: target.async
};
return true;
case "then":
if (!target.async) {
// If this module is expected to return a Promise (such as an AsyncModule) then
// we should resolve that with a client reference that unwraps the Promise on
// the client.
const then = function then(resolve, _reject) {
const moduleReference = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: "*",
async: true
};
return Promise.resolve(resolve(new Proxy(moduleReference, proxyHandlers)));
};
// If this is not used as a Promise but is treated as a reference to a `.then`
// export then we should treat it as a reference to that name.
then.$$typeof = MODULE_REFERENCE;
then.filepath = target.filepath;
// then.name is conveniently already "then" which is the export name we need.
// This will break if it's minified though.
return then;
}
break;
default:
break;
}
let cachedReference = target[name];
if (!cachedReference) {
cachedReference = target[name] = {
$$typeof: MODULE_REFERENCE,
filepath: target.filepath,
name: name,
async: target.async
};
}
return cachedReference;
},
getPrototypeOf (_target) {
// Pretend to be a Promise in case anyone asks.
return PROMISE_PROTOTYPE;
},
set: function() {
throw new Error("Cannot assign to a client module from a server module.");
}
};
export function createProxy(moduleId) {
const moduleReference = {
$$typeof: MODULE_REFERENCE,
filepath: moduleId,
name: "*",
async: false
};
return new Proxy(moduleReference, proxyHandlers);
}
//# sourceMappingURL=module-proxy.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-flight-loader/module-proxy.ts"],"names":["MODULE_REFERENCE","Symbol","for","PROMISE_PROTOTYPE","Promise","prototype","proxyHandlers","get","target","name","_receiver","$$typeof","filepath","async","undefined","default","then","resolve","_reject","moduleReference","Proxy","cachedReference","getPrototypeOf","_target","set","Error","createProxy","moduleId"],"mappings":"AAAA;;;;;GAKG,CAEH,oIAAoI;AAEpI,MAAMA,gBAAgB,GAAGC,MAAM,CAACC,GAAG,CAAC,wBAAwB,CAAC;AAC7D,MAAMC,iBAAiB,GAAGC,OAAO,CAACC,SAAS;AAE3C,MAAMC,aAAa,GAAyB;IAC1CC,GAAG,EAAE,SAAUC,MAAW,EAAEC,IAAY,EAAEC,SAAc,EAAE;QACxD,OAAQD,IAAI;YACV,qFAAqF;YACrF,KAAK,UAAU;gBACb,wEAAwE;gBACxE,4DAA4D;gBAC5D,OAAOD,MAAM,CAACG,QAAQ,CAAA;YACxB,KAAK,UAAU;gBACb,OAAOH,MAAM,CAACI,QAAQ,CAAA;YACxB,KAAK,MAAM;gBACT,OAAOJ,MAAM,CAACC,IAAI,CAAA;YACpB,KAAK,OAAO;gBACV,OAAOD,MAAM,CAACK,KAAK,CAAA;YACrB,8EAA8E;YAC9E,aAAa;YACb,KAAK,cAAc;gBACjB,OAAOC,SAAS,CAAA;YAClB,KAAK,YAAY;gBACf,+EAA+E;gBAC/E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D,OAAOQ,eAAe,CAAA;KACvB;IACDC,cAAc,EAACC,OAAe,EAAE;QAC9B,+CAA+C;QAC/C,OAAOpB,iBAAiB,CAAA;KACzB;IACDqB,GAAG,EAAE,WAAY;QACf,MAAM,IAAIC,KAAK,CAAC,wDAAwD,CAAC,CAAA;KAC1E;CACF;AAED,OAAO,SAASC,WAAW,CAACC,QAAgB,EAAE;IAC5C,MAAMR,eAAe,GAAG;QACtBR,QAAQ,EAAEX,gBAAgB;QAC1BY,QAAQ,EAAEe,QAAQ;QAClBlB,IAAI,EAAE,GAAG;QACTI,KAAK,EAAE,KAAK;KACb;IACD,OAAO,IAAIO,KAAK,CAACD,eAAe,EAAEb,aAAa,CAAC,CAAA;CACjD"}

View File

@@ -0,0 +1,91 @@
import { promises as fs } from "fs";
import path from "path";
import chalk from "next/dist/compiled/chalk";
import loaderUtils from "next/dist/compiled/loader-utils3";
import postcssNextFontPlugin from "./postcss-next-font";
import { promisify } from "util";
import { CONFIG_FILES } from "../../../../shared/lib/constants";
export default async function nextFontLoader() {
const fontLoaderSpan = this.currentTraceSpan.traceChild("next-font-loader");
return fontLoaderSpan.traceAsyncFn(async ()=>{
const callback = this.async();
// next-swc next_font_loaders turns each font loader call into JSON
const { path: relativeFilePathFromRoot , import: functionName , arguments: data , variableName , } = JSON.parse(this.resourceQuery.slice(1));
// Throw error if @next/font is used in _document.js
if (/pages[\\/]_document\./.test(relativeFilePathFromRoot)) {
const err = new Error(`${chalk.bold("Cannot")} be used within ${chalk.cyan("pages/_document.js")}.`);
err.name = "NextFontError";
callback(err);
return;
}
const { isDev , isServer , assetPrefix , fontLoaderOptions , postcss: getPostcss , } = this.getOptions();
const nextConfigPaths = CONFIG_FILES.map((config)=>path.join(this.rootContext, config));
// Add next.config.js as a dependency, loaders must rerun in case options changed
await Promise.all(nextConfigPaths.map(async (configPath)=>{
const hasConfig = await fs.access(configPath).then(()=>true, ()=>false);
if (hasConfig) {
this.addDependency(configPath);
} else {
this.addMissingDependency(configPath);
}
}));
const emitFontFile = (content, ext, preload)=>{
const opts = {
context: this.rootContext,
content
};
const interpolatedName = loaderUtils.interpolateName(this, // Font files ending with .p.(woff|woff2|eot|ttf|otf) are preloaded
`static/media/[hash]${preload ? ".p" : ""}.${ext}`, opts);
const outputPath = `${assetPrefix}/_next/${interpolatedName}`;
if (!isServer) {
this.emitFile(interpolatedName, content, null);
}
return outputPath;
};
try {
const fontLoader = require(path.join(this.resourcePath, "../loader.js")).default;
let { css , fallbackFonts , adjustFontFallback , weight , style , variable } = await fontLoader({
functionName,
variableName,
data,
config: fontLoaderOptions,
emitFontFile,
resolve: (src)=>promisify(this.resolve)(path.dirname(path.join(this.rootContext, relativeFilePathFromRoot)), src.startsWith(".") ? src : `./${src}`),
isDev,
isServer,
loaderContext: this
});
const { postcss } = await getPostcss();
// Exports will be exported as is from css-loader instead of a CSS module export
const exports = [];
const fontFamilyHash = loaderUtils.getHashDigest(Buffer.from(css), "md5", "hex", 6);
// Add CSS classes, exports and make the font-family localy scoped by turning it unguessable
const result = await postcss(postcssNextFontPlugin({
exports,
fontFamilyHash,
fallbackFonts,
weight,
style,
adjustFontFallback,
variable
})).process(css, {
from: undefined
});
// Reuse ast in css-loader
const ast = {
type: "postcss",
version: result.processor.version,
root: result.root
};
callback(null, result.css, null, {
exports,
ast,
fontFamilyHash
});
} catch (err) {
callback(err);
}
});
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-font-loader/index.ts"],"names":["promises","fs","path","chalk","loaderUtils","postcssNextFontPlugin","promisify","CONFIG_FILES","nextFontLoader","fontLoaderSpan","currentTraceSpan","traceChild","traceAsyncFn","callback","async","relativeFilePathFromRoot","import","functionName","arguments","data","variableName","JSON","parse","resourceQuery","slice","test","err","Error","bold","cyan","name","isDev","isServer","assetPrefix","fontLoaderOptions","postcss","getPostcss","getOptions","nextConfigPaths","map","config","join","rootContext","Promise","all","configPath","hasConfig","access","then","addDependency","addMissingDependency","emitFontFile","content","ext","preload","opts","context","interpolatedName","interpolateName","outputPath","emitFile","fontLoader","require","resourcePath","default","css","fallbackFonts","adjustFontFallback","weight","style","variable","resolve","src","dirname","startsWith","loaderContext","exports","fontFamilyHash","getHashDigest","Buffer","from","result","process","undefined","ast","type","version","processor","root"],"mappings":"AAEA,SAASA,QAAQ,IAAIC,EAAE,QAAQ,IAAI,CAAA;AACnC,OAAOC,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,KAAK,MAAM,0BAA0B,CAAA;AAC5C,OAAOC,WAAW,MAAM,kCAAkC,CAAA;AAC1D,OAAOC,qBAAqB,MAAM,qBAAqB,CAAA;AACvD,SAASC,SAAS,QAAQ,MAAM,CAAA;AAChC,SAASC,YAAY,QAAQ,kCAAkC,CAAA;AAE/D,eAAe,eAAeC,cAAc,GAAY;IACtD,MAAMC,cAAc,GAAG,IAAI,CAACC,gBAAgB,CAACC,UAAU,CAAC,kBAAkB,CAAC;IAC3E,OAAOF,cAAc,CAACG,YAAY,CAAC,UAAY;QAC7C,MAAMC,QAAQ,GAAG,IAAI,CAACC,KAAK,EAAE;QAE7B,mEAAmE;QACnE,MAAM,EACJZ,IAAI,EAAEa,wBAAwB,CAAA,EAC9BC,MAAM,EAAEC,YAAY,CAAA,EACpBC,SAAS,EAAEC,IAAI,CAAA,EACfC,YAAY,CAAA,IACb,GAAGC,IAAI,CAACC,KAAK,CAAC,IAAI,CAACC,aAAa,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC;QAE3C,oDAAoD;QACpD,IAAI,wBAAwBC,IAAI,CAACV,wBAAwB,CAAC,EAAE;YAC1D,MAAMW,GAAG,GAAG,IAAIC,KAAK,CACnB,CAAC,EAAExB,KAAK,CAACyB,IAAI,CAAC,QAAQ,CAAC,CAAC,gBAAgB,EAAEzB,KAAK,CAAC0B,IAAI,CAClD,oBAAoB,CACrB,CAAC,CAAC,CAAC,CACL;YACDH,GAAG,CAACI,IAAI,GAAG,eAAe;YAC1BjB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AO,CAACjB,GAAG,EAAE;gBACbe,IAAI,EAAEG,SAAS;aAChB,CAAC;YAEF,0BAA0B;YAC1B,MAAMC,GAAG,GAAG;gBACVC,IAAI,EAAE,SAAS;gBACfC,OAAO,EAAEL,MAAM,CAACM,SAAS,CAACD,OAAO;gBACjCE,IAAI,EAAEP,MAAM,CAACO,IAAI;aAClB;YACD3E,QAAQ,CAAC,IAAI,EAAEoE,MAAM,CAAChB,GAAG,EAAE,IAAI,EAAE;gBAC/BW,OAAO;gBACPQ,GAAG;gBACHP,cAAc;aACf,CAAC;SACH,CAAC,OAAOnD,GAAG,EAAO;YACjBb,QAAQ,CAACa,GAAG,CAAC;SACd;KACF,CAAC,CAAA;CACH,CAAA"}

View File

@@ -0,0 +1,134 @@
import postcss from "postcss";
const postcssNextFontPlugin = ({ exports , fontFamilyHash , fallbackFonts =[] , adjustFontFallback , variable , weight , style })=>{
return {
postcssPlugin: "postcss-next-font",
Once (root) {
let fontFamily;
const normalizeFamily = (family)=>{
return family.replace(/['"]/g, "");
};
const formatFamily = (family)=>{
// Turn the font family unguessable to make it localy scoped
return `'__${family.replace(/ /g, "_")}_${fontFamilyHash}'`;
};
// Hash font-family names
for (const node of root.nodes){
if (node.type === "atrule" && node.name === "font-face") {
const familyNode = node.nodes.find((decl)=>decl.prop === "font-family");
if (!familyNode) {
continue;
}
if (!fontFamily) {
fontFamily = normalizeFamily(familyNode.value);
}
familyNode.value = formatFamily(fontFamily);
}
}
if (!fontFamily) {
throw new Error("Font loaders must return one or more @font-face's");
}
// Add fallback font with override values
let adjustFontFallbackFamily;
if (adjustFontFallback) {
adjustFontFallbackFamily = formatFamily(`${fontFamily} Fallback`);
const fallbackFontFace = postcss.atRule({
name: "font-face"
});
const { fallbackFont , ascentOverride , descentOverride , lineGapOverride , sizeAdjust , } = adjustFontFallback;
fallbackFontFace.nodes = [
new postcss.Declaration({
prop: "font-family",
value: adjustFontFallbackFamily
}),
new postcss.Declaration({
prop: "src",
value: `local("${fallbackFont}")`
}),
...ascentOverride ? [
new postcss.Declaration({
prop: "ascent-override",
value: ascentOverride
}),
] : [],
...descentOverride ? [
new postcss.Declaration({
prop: "descent-override",
value: descentOverride
}),
] : [],
...lineGapOverride ? [
new postcss.Declaration({
prop: "line-gap-override",
value: lineGapOverride
}),
] : [],
...sizeAdjust ? [
new postcss.Declaration({
prop: "size-adjust",
value: sizeAdjust
}),
] : [],
];
root.nodes.push(fallbackFontFace);
}
// Variable fonts can define ranges of values
const isRange = (value)=>value.trim().includes(" ");
const formattedFontFamilies = [
formatFamily(fontFamily),
...adjustFontFallbackFamily ? [
adjustFontFallbackFamily
] : [],
...fallbackFonts,
].join(", ");
// Add class with family, weight and style
const classRule = new postcss.Rule({
selector: ".className"
});
classRule.nodes = [
new postcss.Declaration({
prop: "font-family",
value: formattedFontFamilies
}),
...weight && !isRange(weight) ? [
new postcss.Declaration({
prop: "font-weight",
value: weight
}),
] : [],
...style && !isRange(style) ? [
new postcss.Declaration({
prop: "font-style",
value: style
}),
] : [],
];
root.nodes.push(classRule);
// Add class that defines a variable with the font family
if (variable) {
const varialbeRule = new postcss.Rule({
selector: ".variable"
});
varialbeRule.nodes = [
new postcss.Declaration({
prop: variable,
value: formattedFontFamilies
}),
];
root.nodes.push(varialbeRule);
}
// Export @font-face values as is
exports.push({
name: "style",
value: {
fontFamily: formattedFontFamilies,
fontWeight: !Number.isNaN(Number(weight)) ? Number(weight) : undefined,
fontStyle: style && !isRange(style) ? style : undefined
}
});
}
};
};
postcssNextFontPlugin.postcss = true;
export default postcssNextFontPlugin;
//# sourceMappingURL=postcss-next-font.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-font-loader/postcss-next-font.ts"],"names":["postcss","postcssNextFontPlugin","exports","fontFamilyHash","fallbackFonts","adjustFontFallback","variable","weight","style","postcssPlugin","Once","root","fontFamily","normalizeFamily","family","replace","formatFamily","node","nodes","type","name","familyNode","find","decl","prop","value","Error","adjustFontFallbackFamily","fallbackFontFace","atRule","fallbackFont","ascentOverride","descentOverride","lineGapOverride","sizeAdjust","Declaration","push","isRange","trim","includes","formattedFontFamilies","join","classRule","Rule","selector","varialbeRule","fontWeight","Number","isNaN","undefined","fontStyle"],"mappings":"AACA,OAAOA,OAAO,MAAuB,SAAS,CAAA;AAE9C,MAAMC,qBAAqB,GAAG,CAAC,EAC7BC,OAAO,CAAA,EACPC,cAAc,CAAA,EACdC,aAAa,EAAG,EAAE,CAAA,EAClBC,kBAAkB,CAAA,EAClBC,QAAQ,CAAA,EACRC,MAAM,CAAA,EACNC,KAAK,CAAA,EASN,GAAK;IACJ,OAAO;QACLC,aAAa,EAAE,mBAAmB;QAClCC,IAAI,EAACC,IAAS,EAAE;YACd,IAAIC,UAAU,AAAoB;YAElC,MAAMC,eAAe,GAAG,CAACC,MAAc,GAAK;gBAC1C,OAAOA,MAAM,CAACC,OAAO,UAAU,EAAE,CAAC,CAAA;aACnC;YAED,MAAMC,YAAY,GAAG,CAACF,MAAc,GAAK;gBACvC,4DAA4D;gBAC5D,OAAO,CAAC,GAAG,EAAEA,MAAM,CAACC,OAAO,OAAO,GAAG,CAAC,CAAC,CAAC,EAAEZ,cAAc,CAAC,CAAC,CAAC,CAAA;aAC5D;YAED,yBAAyB;YACzB,KAAK,MAAMc,IAAI,IAAIN,IAAI,CAACO,KAAK,CAAE;gBAC7B,IAAID,IAAI,CAACE,IAAI,KAAK,QAAQ,IAAIF,IAAI,CAACG,IAAI,KAAK,WAAW,EAAE;oBACvD,MAAMC,UAAU,GAAGJ,IAAI,CAACC,KAAK,CAACI,IAAI,CAChC,CAACC,IAAiB,GAAKA,IAAI,CAACC,IAAI,KAAK,aAAa,CACnD;oBACD,IAAI,CAACH,UAAU,EAAE;wBACf,SAAQ;qBACT;oBAED,IAAI,CAACT,UAAU,EAAE;wBACfA,UAAU,GAAGC,eAAe,CAACQ,UAAU,CAACI,KAAK,CAAC;qBAC/C;oBAEDJ,UAAU,CAACI,KAAK,GAAGT,Y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Z,MAAMuC,YAAY,GAAG,IAAI7C,OAAO,CAAC2C,IAAI,CAAC;oBAAEC,QAAQ,EAAE,WAAW;iBAAE,CAAC;gBAChEC,YAAY,CAAC3B,KAAK,GAAG;oBACnB,IAAIlB,OAAO,CAACmC,WAAW,CAAC;wBACtBX,IAAI,EAAElB,QAAQ;wBACdmB,KAAK,EAAEe,qBAAqB;qBAC7B,CAAC;iBACH;gBACD7B,IAAI,CAACO,KAAK,CAACkB,IAAI,CAACS,YAAY,CAAC;aAC9B;YAED,iCAAiC;YACjC3C,OAAO,CAACkC,IAAI,CAAC;gBACXhB,IAAI,EAAE,OAAO;gBACbK,KAAK,EAAE;oBACLb,UAAU,EAAE4B,qBAAqB;oBACjCM,UAAU,EAAE,CAACC,MAAM,CAACC,KAAK,CAACD,MAAM,CAACxC,MAAM,CAAC,CAAC,GACrCwC,MAAM,CAACxC,MAAM,CAAC,GACd0C,SAAS;oBACbC,SAAS,EAAE1C,KAAK,IAAI,CAAC6B,OAAO,CAAC7B,KAAK,CAAC,GAAGA,KAAK,GAAGyC,SAAS;iBACxD;aACF,CAAC;SACH;KACF,CAAA;CACF;AAEDhD,qBAAqB,CAACD,OAAO,GAAG,IAAI;AAEpC,eAAeC,qBAAqB,CAAA"}

View File

@@ -0,0 +1,93 @@
import isAnimated from "next/dist/compiled/is-animated";
import loaderUtils from "next/dist/compiled/loader-utils3";
import { optimizeImage, getImageSize } from "../../../server/image-optimizer";
const BLUR_IMG_SIZE = 8;
const BLUR_QUALITY = 70;
const VALID_BLUR_EXT = [
"jpeg",
"png",
"webp",
"avif"
] // should match next/client/image.tsx
;
function nextImageLoader(content) {
const imageLoaderSpan = this.currentTraceSpan.traceChild("next-image-loader");
return imageLoaderSpan.traceAsyncFn(async ()=>{
const options = this.getOptions();
const { isServer , isDev , assetPrefix , basePath } = options;
const context = this.rootContext;
const opts = {
context,
content
};
const interpolatedName = loaderUtils.interpolateName(this, "/static/media/[name].[hash:8].[ext]", opts);
const outputPath = assetPrefix + "/_next" + interpolatedName;
let extension = loaderUtils.interpolateName(this, "[ext]", opts);
if (extension === "jpg") {
extension = "jpeg";
}
const imageSizeSpan = imageLoaderSpan.traceChild("image-size-calculation");
const imageSize = await imageSizeSpan.traceAsyncFn(()=>getImageSize(content, extension).catch((err)=>err));
if (imageSize instanceof Error) {
const err = imageSize;
err.name = "InvalidImageFormatError";
throw err;
}
let blurDataURL;
let blurWidth;
let blurHeight;
if (VALID_BLUR_EXT.includes(extension)) {
// Shrink the image's largest dimension
if (imageSize.width >= imageSize.height) {
blurWidth = BLUR_IMG_SIZE;
blurHeight = Math.max(Math.round(imageSize.height / imageSize.width * BLUR_IMG_SIZE), 1);
} else {
blurWidth = Math.max(Math.round(imageSize.width / imageSize.height * BLUR_IMG_SIZE), 1);
blurHeight = BLUR_IMG_SIZE;
}
if (isDev) {
// During `next dev`, we don't want to generate blur placeholders with webpack
// because it can delay starting the dev server. Instead, we inline a
// special url to lazily generate the blur placeholder at request time.
const prefix = "http://localhost";
const url = new URL(`${basePath || ""}/_next/image`, prefix);
url.searchParams.set("url", outputPath);
url.searchParams.set("w", String(blurWidth));
url.searchParams.set("q", String(BLUR_QUALITY));
blurDataURL = url.href.slice(prefix.length);
} else {
const resizeImageSpan = imageLoaderSpan.traceChild("image-resize");
const resizedImage = await resizeImageSpan.traceAsyncFn(()=>{
if (isAnimated(content)) {
return content;
}
return optimizeImage({
buffer: content,
width: blurWidth,
height: blurHeight,
contentType: `image/${extension}`,
quality: BLUR_QUALITY
});
});
const blurDataURLSpan = imageLoaderSpan.traceChild("image-base64-tostring");
blurDataURL = blurDataURLSpan.traceFn(()=>`data:image/${extension};base64,${resizedImage.toString("base64")}`);
}
}
const stringifiedData = imageLoaderSpan.traceChild("image-data-stringify").traceFn(()=>JSON.stringify({
src: outputPath,
height: imageSize.height,
width: imageSize.width,
blurDataURL,
blurWidth,
blurHeight
}));
if (isServer) {
this.emitFile(`../${isDev ? "" : "../"}${interpolatedName}`, content, null);
}
return `export default ${stringifiedData};`;
});
}
export const raw = true;
export default nextImageLoader;
//# sourceMappingURL=next-image-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-image-loader.ts"],"names":["isAnimated","loaderUtils","optimizeImage","getImageSize","BLUR_IMG_SIZE","BLUR_QUALITY","VALID_BLUR_EXT","nextImageLoader","content","imageLoaderSpan","currentTraceSpan","traceChild","traceAsyncFn","options","getOptions","isServer","isDev","assetPrefix","basePath","context","rootContext","opts","interpolatedName","interpolateName","outputPath","extension","imageSizeSpan","imageSize","catch","err","Error","name","blurDataURL","blurWidth","blurHeight","includes","width","height","Math","max","round","prefix","url","URL","searchParams","set","String","href","slice","length","resizeImageSpan","resizedImage","buffer","contentType","quality","blurDataURLSpan","traceFn","toString","stringifiedData","JSON","stringify","src","emitFile","raw"],"mappings":"AAAA,OAAOA,UAAU,MAAM,gCAAgC,CAAA;AACvD,OAAOC,WAAW,MAAM,kCAAkC,CAAA;AAC1D,SAASC,aAAa,EAAEC,YAAY,QAAQ,iCAAiC,CAAA;AAE7E,MAAMC,aAAa,GAAG,CAAC;AACvB,MAAMC,YAAY,GAAG,EAAE;AACvB,MAAMC,cAAc,GAAG;IAAC,MAAM;IAAE,KAAK;IAAE,MAAM;IAAE,MAAM;CAAC,CAAC,qCAAqC;AAAtC;AAStD,SAASC,eAAe,CAAYC,OAAe,EAAE;IACnD,MAAMC,eAAe,GAAG,IAAI,CAACC,gBAAgB,CAACC,UAAU,CAAC,mBAAmB,CAAC;IAC7E,OAAOF,eAAe,CAACG,YAAY,CAAC,UAAY;QAC9C,MAAMC,OAAO,GAAY,IAAI,CAACC,UAAU,EAAE;QAC1C,MAAM,EAAEC,QAAQ,CAAA,EAAEC,KAAK,CAAA,EAAEC,WAAW,CAAA,EAAEC,QAAQ,CAAA,EAAE,GAAGL,OAAO;QAC1D,MAAMM,OAAO,GAAG,IAAI,CAACC,WAAW;QAChC,MAAMC,IAAI,GAAG;YAAEF,OAAO;YA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S,CAAC,QAAQ,EAAE0B,YAAY,CAACM,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CACtE;aACF;SACF;QAED,MAAMC,eAAe,GAAGjD,eAAe,CACpCE,UAAU,CAAC,sBAAsB,CAAC,CAClC6C,OAAO,CAAC,IACPG,IAAI,CAACC,SAAS,CAAC;gBACbC,GAAG,EAAErC,UAAU;gBACfa,MAAM,EAAEV,SAAS,CAACU,MAAM;gBACxBD,KAAK,EAAET,SAAS,CAACS,KAAK;gBACtBJ,WAAW;gBACXC,SAAS;gBACTC,UAAU;aACX,CAAC,CACH;QAEH,IAAInB,QAAQ,EAAE;YACZ,IAAI,CAAC+C,QAAQ,CACX,CAAC,GAAG,EAAE9C,KAAK,GAAG,EAAE,GAAG,KAAK,CAAC,EAAEM,gBAAgB,CAAC,CAAC,EAC7Cd,OAAO,EACP,IAAI,CACL;SACF;QAED,OAAO,CAAC,eAAe,EAAEkD,eAAe,CAAC,CAAC,CAAC,CAAA;KAC5C,CAAC,CAAA;CACH;AACD,OAAO,MAAMK,GAAG,GAAG,IAAI,CAAA;AACvB,eAAexD,eAAe,CAAA"}

View File

@@ -0,0 +1,19 @@
import loaderUtils from "next/dist/compiled/loader-utils3";
import { getModuleBuildInfo } from "./get-module-build-info";
export default function MiddlewareAssetLoader(source) {
const name = loaderUtils.interpolateName(this, "[name].[hash].[ext]", {
context: this.rootContext,
content: source
});
const filePath = `edge-chunks/asset_${name}`;
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextAssetMiddlewareBinding = {
filePath: `server/${filePath}`,
name
};
this.emitFile(filePath, source);
return `module.exports = ${JSON.stringify(`blob:${name}`)}`;
};
export const raw = true;
//# sourceMappingURL=next-middleware-asset-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-middleware-asset-loader.ts"],"names":["loaderUtils","getModuleBuildInfo","MiddlewareAssetLoader","source","name","interpolateName","context","rootContext","content","filePath","buildInfo","_module","nextAssetMiddlewareBinding","emitFile","JSON","stringify","raw"],"mappings":"AAAA,OAAOA,WAAW,MAAM,kCAAkC,CAAA;AAC1D,SAASC,kBAAkB,QAAQ,yBAAyB,CAAA;AAE5D,eAAe,SAASC,qBAAqB,CAAYC,MAAc,EAAE;IACvE,MAAMC,IAAI,GAAGJ,WAAW,CAACK,eAAe,CAAC,IAAI,EAAE,qBAAqB,EAAE;QACpEC,OAAO,EAAE,IAAI,CAACC,WAAW;QACzBC,OAAO,EAAEL,MAAM;KAChB,CAAC;IACF,MAAMM,QAAQ,GAAG,CAAC,kBAAkB,EAAEL,IAAI,CAAC,CAAC;IAC5C,MAAMM,SAAS,GAAGT,kBAAkB,CAAC,IAAI,CAACU,OAAO,CAAC;IAClDD,SAAS,CAACE,0BAA0B,GAAG;QACrCH,QAAQ,EAAE,CAAC,OAAO,EAAEA,QAAQ,CAAC,CAAC;QAC9BL,IAAI;KACL;IACD,IAAI,CAACS,QAAQ,CAACJ,QAAQ,EAAEN,MAAM,CAAC;IAC/B,OAAO,CAAC,iBAAiB,EAAEW,IAAI,CAACC,SAAS,CAAC,CAAC,KAAK,EAAEX,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;CAC5D,CAAA;AAED,OAAO,MAAMY,GAAG,GAAG,IAAI,CAAA"}

View File

@@ -0,0 +1,44 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import { stringifyRequest } from "../stringify-request";
import { MIDDLEWARE_LOCATION_REGEXP } from "../../../lib/constants";
// matchers can have special characters that break the loader params
// parsing so we base64 encode/decode the string
export function encodeMatchers(matchers) {
return Buffer.from(JSON.stringify(matchers)).toString("base64");
}
export function decodeMatchers(encodedMatchers) {
return JSON.parse(Buffer.from(encodedMatchers, "base64").toString());
}
export default function middlewareLoader() {
const { absolutePagePath , page , rootDir , matchers: encodedMatchers , } = this.getOptions();
const matchers = encodedMatchers ? decodeMatchers(encodedMatchers) : undefined;
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextEdgeMiddleware = {
matchers,
page: page.replace(new RegExp(`/${MIDDLEWARE_LOCATION_REGEXP}$`), "") || "/"
};
buildInfo.rootDir = rootDir;
return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
enhanceGlobals()
var mod = require(${stringifiedPagePath})
var handler = mod.middleware || mod.default;
if (typeof handler !== 'function') {
throw new Error('The Middleware "pages${page}" must export a \`middleware\` or a \`default\` function');
}
export default function (opts) {
return adapter({
...opts,
page: ${JSON.stringify(page)},
handler,
})
}
`;
};
//# sourceMappingURL=next-middleware-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-middleware-loader.ts"],"names":["getModuleBuildInfo","stringifyRequest","MIDDLEWARE_LOCATION_REGEXP","encodeMatchers","matchers","Buffer","from","JSON","stringify","toString","decodeMatchers","encodedMatchers","parse","middlewareLoader","absolutePagePath","page","rootDir","getOptions","undefined","stringifiedPagePath","buildInfo","_module","nextEdgeMiddleware","replace","RegExp"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,SAASC,gBAAgB,QAAQ,sBAAsB,CAAA;AACvD,SAASC,0BAA0B,QAAQ,wBAAwB,CAAA;AASnE,oEAAoE;AACpE,gDAAgD;AAChD,OAAO,SAASC,cAAc,CAACC,QAA6B,EAAE;IAC5D,OAAOC,MAAM,CAACC,IAAI,CAACC,IAAI,CAACC,SAAS,CAACJ,QAAQ,CAAC,CAAC,CAACK,QAAQ,CAAC,QAAQ,CAAC,CAAA;CAChE;AAED,OAAO,SAASC,cAAc,CAACC,eAAuB,EAAE;IACtD,OAAOJ,IAAI,CAACK,KAAK,CACfP,MAAM,CAACC,IAAI,CAACK,eAAe,EAAE,QAAQ,CAAC,CAACF,QAAQ,EAAE,CAClD,CAAuB;CACzB;AAED,eAAe,SAASI,gBAAgB,GAAY;IAClD,MAAM,EACJC,gBAAgB,CAAA,EAChBC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPZ,QAAQ,EAAEO,eAAe,CAAA,IAC1B,GAA4B,IAAI,CAACM,UAAU,EAAE;IAC9C,MAAMb,QAAQ,GAAGO,eAAe,GAAGD,cAAc,CAACC,eAAe,CAAC,GAAGO,SAAS;IAC9E,MAAMC,mBAAmB,GAAGlB,gBAAgB,CAAC,IAAI,EAAEa,gBAAgB,CAAC;IACpE,MAAMM,SAAS,GAAGpB,kBAAkB,CAAC,IAAI,CAACqB,OAAO,CAAC;IAClDD,SAAS,CAACE,kBAAkB,GAAG;QAC7BlB,QAAQ;QACRW,IAAI,EACFA,IAAI,CAACQ,OAAO,CAAC,IAAIC,MAAM,CAAC,CAAC,CAAC,EAAEtB,0BAA0B,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG;KACzE;IACDkB,SAAS,CAACJ,OAAO,GAAGA,OAAO;IAE3B,OAAO,CAAC;;;;;0BAKgB,EAAEG,mBAAmB,CAAC;;;;gDAIA,EAAEJ,IAAI,CAAC;;;;;;oBAMnC,EAAER,IAAI,CAACC,SAAS,CAACO,IAAI,CAAC,CAAC;;;;IAIvC,CAAC,CAAA;CACJ,CAAA"}

View File

@@ -0,0 +1,19 @@
import { getModuleBuildInfo } from "./get-module-build-info";
import crypto from "crypto";
function sha1(source) {
return crypto.createHash("sha1").update(source).digest("hex");
}
export default function MiddlewareWasmLoader(source) {
const name = `wasm_${sha1(source)}`;
const filePath = `edge-chunks/${name}.wasm`;
const buildInfo = getModuleBuildInfo(this._module);
buildInfo.nextWasmMiddlewareBinding = {
filePath: `server/${filePath}`,
name
};
this.emitFile(`/${filePath}`, source, null);
return `module.exports = ${name};`;
};
export const raw = true;
//# sourceMappingURL=next-middleware-wasm-loader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../build/webpack/loaders/next-middleware-wasm-loader.ts"],"names":["getModuleBuildInfo","crypto","sha1","source","createHash","update","digest","MiddlewareWasmLoader","name","filePath","buildInfo","_module","nextWasmMiddlewareBinding","emitFile","raw"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,yBAAyB,CAAA;AAC5D,OAAOC,MAAM,MAAM,QAAQ,CAAA;AAE3B,SAASC,IAAI,CAACC,MAAuB,EAAE;IACrC,OAAOF,MAAM,CAACG,UAAU,CAAC,MAAM,CAAC,CAACC,MAAM,CAACF,MAAM,CAAC,CAACG,MAAM,CAAC,KAAK,CAAC,CAAA;CAC9D;AAED,eAAe,SAASC,oBAAoB,CAAYJ,MAAc,EAAE;IACtE,MAAMK,IAAI,GAAG,CAAC,KAAK,EAAEN,IAAI,CAACC,MAAM,CAAC,CAAC,CAAC;IACnC,MAAMM,QAAQ,GAAG,CAAC,YAAY,EAAED,IAAI,CAAC,KAAK,CAAC;IAC3C,MAAME,SAAS,GAAGV,kBAAkB,CAAC,IAAI,CAACW,OAAO,CAAC;IAClDD,SAAS,CAACE,yBAAyB,GAAG;QAAEH,QAAQ,EAAE,CAAC,OAAO,EAAEA,QAAQ,CAAC,CAAC;QAAED,IAAI;KAAE;IAC9E,IAAI,CAACK,QAAQ,CAAC,CAAC,CAAC,EAAEJ,QAAQ,CAAC,CAAC,EAAEN,MAAM,EAAE,IAAI,CAAC;IAC3C,OAAO,CAAC,iBAAiB,EAAEK,IAAI,CAAC,CAAC,CAAC,CAAA;CACnC,CAAA;AAED,OAAO,MAAMM,GAAG,GAAG,IAAI,CAAA"}

View File

@@ -0,0 +1,42 @@
import { parse as parseUrl } from "url";
import { IncomingMessage, ServerResponse } from "http";
import { apiResolver } from "../../../../server/api-utils/node";
import { getUtils, vercelHeader } from "./utils";
import { DecodeError } from "../../../../shared/lib/utils";
import { NodeNextResponse, NodeNextRequest } from "../../../../server/base-http/node";
export function getApiHandler(ctx) {
const { pageModule , encodedPreviewProps , pageIsDynamic } = ctx;
const { handleRewrites , handleBasePath , dynamicRouteMatcher , normalizeDynamicRouteParams , } = getUtils(ctx);
return async (rawReq, rawRes)=>{
const req = rawReq instanceof IncomingMessage ? new NodeNextRequest(rawReq) : rawReq;
const res = rawRes instanceof ServerResponse ? new NodeNextResponse(rawRes) : rawRes;
try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = req.headers[vercelHeader];
const parsedUrl = parseUrl(req.url, true);
handleRewrites(req, parsedUrl);
if (parsedUrl.query.nextInternalLocale) {
delete parsedUrl.query.nextInternalLocale;
}
handleBasePath(req, parsedUrl);
let params = {};
if (pageIsDynamic) {
const result = normalizeDynamicRouteParams(trustQuery ? parsedUrl.query : dynamicRouteMatcher(parsedUrl.pathname));
params = result.params;
}
await apiResolver(req.originalRequest, res.originalResponse, Object.assign({}, parsedUrl.query, params), await pageModule, encodedPreviewProps, true);
} catch (err) {
console.error(err);
if (err instanceof DecodeError) {
res.statusCode = 400;
res.body("Bad Request").send();
} else {
// Throw the error to crash the serverless function
throw err;
}
}
};
}
//# sourceMappingURL=api-handler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-serverless-loader/api-handler.ts"],"names":["parse","parseUrl","IncomingMessage","ServerResponse","apiResolver","getUtils","vercelHeader","DecodeError","NodeNextResponse","NodeNextRequest","getApiHandler","ctx","pageModule","encodedPreviewProps","pageIsDynamic","handleRewrites","handleBasePath","dynamicRouteMatcher","normalizeDynamicRouteParams","rawReq","rawRes","req","res","trustQuery","headers","parsedUrl","url","query","nextInternalLocale","params","result","pathname","originalRequest","originalResponse","Object","assign","err","console","error","statusCode","body","send"],"mappings":"AAAA,SAASA,KAAK,IAAIC,QAAQ,QAAQ,KAAK,CAAA;AACvC,SAASC,eAAe,EAAEC,cAAc,QAAQ,MAAM,CAAA;AACtD,SAASC,WAAW,QAAQ,mCAAmC,CAAA;AAC/D,SAASC,QAAQ,EAAEC,YAAY,QAA8B,SAAS,CAAA;AACtE,SAASC,WAAW,QAAQ,8BAA8B,CAAA;AAC1D,SACEC,gBAAgB,EAChBC,eAAe,QACV,mCAAmC,CAAA;AAE1C,OAAO,SAASC,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AAS,CAACE,KAAK,EAAEE,MAAM,CAAC,EAC1C,MAAMjB,UAAU,EAChBC,mBAAmB,EACnB,IAAI,CACL;SACF,CAAC,OAAOuB,GAAG,EAAE;YACZC,OAAO,CAACC,KAAK,CAACF,GAAG,CAAC;YAElB,IAAIA,GAAG,YAAY7B,WAAW,EAAE;gBAC9Be,GAAG,CAACiB,UAAU,GAAG,GAAG;gBACpBjB,GAAG,CAACkB,IAAI,CAAC,aAAa,CAAC,CAACC,IAAI,EAAE;aAC/B,MAAM;gBACL,mDAAmD;gBACnD,MAAML,GAAG,CAAA;aACV;SACF;KACF,CAAA;CACF"}

View File

@@ -0,0 +1,134 @@
import devalue from "next/dist/compiled/devalue";
import { join } from "path";
import { parse } from "querystring";
import { isAPIRoute } from "../../../../lib/is-api-route";
import { isDynamicRoute } from "../../../../shared/lib/router/utils";
import { escapeStringRegexp } from "../../../../shared/lib/escape-regexp";
import { BUILD_MANIFEST, ROUTES_MANIFEST, REACT_LOADABLE_MANIFEST } from "../../../../shared/lib/constants";
import { stringifyRequest } from "../../stringify-request";
const nextServerlessLoader = function() {
const { distDir , absolutePagePath , page , buildId , canonicalBase , assetPrefix , absoluteAppPath , absoluteDocumentPath , absoluteErrorPath , absolute404Path , generateEtags , poweredByHeader , basePath , runtimeConfig , previewProps , loadedEnvFiles , i18n , } = typeof this.query === "string" ? parse(this.query.slice(1)) : this.query;
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, "/");
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(/\\/g, "/");
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, "/");
const escapedBuildId = escapeStringRegexp(buildId);
const pageIsDynamicRoute = isDynamicRoute(page);
const encodedPreviewProps = devalue(JSON.parse(previewProps));
const envLoading = `
const { processEnv } = require('@next/env')
processEnv(${Buffer.from(loadedEnvFiles, "base64").toString()})
`;
const runtimeConfigImports = runtimeConfig ? `
const { setConfig } = require('next/config')
` : "";
const runtimeConfigSetter = runtimeConfig ? `
const runtimeConfig = ${runtimeConfig}
setConfig(runtimeConfig)
` : "const runtimeConfig = {}";
if (isAPIRoute(page)) {
return `
${envLoading}
${runtimeConfigImports}
${/*
this needs to be called first so its available for any other imports
*/ runtimeConfigSetter}
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import { getApiHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/api-handler'
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const apiHandler = getApiHandler({
pageModule: require(${stringifyRequest(this, absolutePagePath)}),
rewrites: rewrites,
i18n: ${i18n || "undefined"},
page: "${page}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export default apiHandler
`;
} else {
return `
import 'next/dist/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}'
import buildManifest from '${buildManifest}'
import reactLoadableManifest from '${reactLoadableManifest}'
${envLoading}
${runtimeConfigImports}
${// this needs to be called first so its available for any other imports
runtimeConfigSetter}
import { getPageHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/page-handler'
const documentModule = require(${stringifyRequest(this, absoluteDocumentPath)})
const appMod = require(${stringifyRequest(this, absoluteAppPath)})
let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
const compMod = require(${stringifyRequest(this, absolutePagePath)})
const Component = compMod.default || compMod.then && compMod.then(mod => mod.default)
export default Component
export const getStaticProps = compMod['getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['getStaticProp' + 's'])
export const getStaticPaths = compMod['getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['getStaticPath' + 's'])
export const getServerSideProps = compMod['getServerSideProp' + 's'] || compMod.then && compMod.then(mod => mod['getServerSideProp' + 's'])
// kept for detecting legacy exports
export const unstable_getStaticParams = compMod['unstable_getStaticParam' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticParam' + 's'])
export const unstable_getStaticProps = compMod['unstable_getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticProp' + 's'])
export const unstable_getStaticPaths = compMod['unstable_getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticPath' + 's'])
export const unstable_getServerProps = compMod['unstable_getServerProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getServerProp' + 's'])
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
export const _app = App
const rewrites = Array.isArray(routesManifest.rewrites)
? {
afterFiles: routesManifest.rewrites
}
: routesManifest.rewrites
const { renderReqToHTML, render } = getPageHandler({
pageModule: compMod,
pageComponent: Component,
pageConfig: config,
appModule: App,
documentModule: documentModule,
errorModule: require(${stringifyRequest(this, absoluteErrorPath)}),
notFoundModule: ${absolute404Path ? `require(${stringifyRequest(this, absolute404Path)})` : undefined},
pageGetStaticProps: getStaticProps,
pageGetStaticPaths: getStaticPaths,
pageGetServerSideProps: getServerSideProps,
assetPrefix: "${assetPrefix}",
canonicalBase: "${canonicalBase}",
generateEtags: ${generateEtags || "false"},
poweredByHeader: ${poweredByHeader || "false"},
runtimeConfig,
buildManifest,
reactLoadableManifest,
rewrites: rewrites,
i18n: ${i18n || "undefined"},
page: "${page}",
buildId: "${buildId}",
escapedBuildId: "${escapedBuildId}",
basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}
})
export { renderReqToHTML, render }
`;
}
};
export default nextServerlessLoader;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-serverless-loader/index.ts"],"names":["devalue","join","parse","isAPIRoute","isDynamicRoute","escapeStringRegexp","BUILD_MANIFEST","ROUTES_MANIFEST","REACT_LOADABLE_MANIFEST","stringifyRequest","nextServerlessLoader","distDir","absolutePagePath","page","buildId","canonicalBase","assetPrefix","absoluteAppPath","absoluteDocumentPath","absoluteErrorPath","absolute404Path","generateEtags","poweredByHeader","basePath","runtimeConfig","previewProps","loadedEnvFiles","i18n","query","slice","buildManifest","replace","reactLoadableManifest","routesManifest","escapedBuildId","pageIsDynamicRoute","encodedPreviewProps","JSON","envLoading","Buffer","from","toString","runtimeConfigImports","runtimeConfigSetter","undefined"],"mappings":"AAAA,OAAOA,OAAO,MAAM,4BAA4B,CAAA;AAChD,SAASC,IAAI,QAAQ,MAAM,CAAA;AAC3B,SAASC,KAAK,QAAQ,aAAa,CAAA;AAEnC,SAASC,UAAU,QAAQ,8BAA8B,CAAA;AACzD,SAASC,cAAc,QAAQ,qCAAqC,CAAA;AACpE,SAASC,kBAAkB,QAAQ,sCAAsC,CAAA;AAEzE,SACEC,cAAc,EACdC,eAAe,EACfC,uBAAuB,QAClB,kCAAkC,CAAA;AACzC,SAASC,gBAAgB,QAAQ,yBAAyB,CAAA;AAsB1D,MAAMC,oBAAoB,GAAqC,WAAY;IACzE,MAAM,EACJC,OAAO,CAAA,EACPC,gBAAgB,CAAA,EAChBC,IAAI,CAAA,EACJC,OAAO,CAAA,EACPC,aAAa,CAAA,EACbC,WAAW,CAAA,EACXC,eAAe,CAAA,EACfC,oBAAoB,CAAA,EACpBC,iBAAiB,CAAA,EACjBC,eAAe,CAAA,EACfC,aAAa,CAAA,EACbC,eAAe,CAAA,EACfC,QAAQ,CAAA,EACRC,aAAa,CAAA,EACbC,YAAY,CAAA,EACZC,cAAc,CAAA,EACdC,IAAI,CAAA,IACL,GACC,OAAO,IAAI,CAACC,KAAK,KAAK,QAAQ,GAAG1B,KAAK,CAAC,IAAI,CAAC0B,KAAK,CAACC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAACD,KAAK,AAClE;IAER,MAAME,aAAa,GAAG7B,IAAI,CAACU,OAAO,EAAEL,cAAc,CAAC,CAACyB,OAAO,QAAQ,GAAG,CAAC;IACvE,MAAMC,qBAAqB,GAAG/B,IAAI,CAACU,OAAO,EAAEH,uBAAuB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B,CAAC;MACvB,EACE,uEAAuE;QACvEC,mBAAmB,CACpB;;;qCAG8B,EAAElC,gBAAgB,CAC/C,IAAI,EACJS,oBAAoB,CACrB,CAAC;;6BAEqB,EAAET,gBAAgB,CAAC,IAAI,EAAEQ,eAAe,CAAC,CAAC;;;8BAGzC,EAAER,gBAAgB,CAAC,IAAI,EAAEG,gBAAgB,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA6B5C,EAAEH,gBAAgB,CAAC,IAAI,EAAEU,iBAAiB,CAAC,CAAC;wBACjD,EACdC,eAAe,GACX,CAAC,QAAQ,EAAEX,gBAAgB,CAAC,IAAI,EAAEW,eAAe,CAAC,CAAC,CAAC,CAAC,GACrDwB,SAAS,CACd;;;;;sBAKa,EAAE5B,WAAW,CAAC;wBACZ,EAAED,aAAa,CAAC;uBACjB,EAAEM,aAAa,IAAI,OAAO,CAAC;yBACzB,EAAEC,eAAe,IAAI,OAAO,CAAC;;;;;;;cAOxC,EAAEK,IAAI,IAAI,WAAW,CAAC;eACrB,EAAEd,IAAI,CAAC;kBACJ,EAAEC,OAAO,CAAC;yBACH,EAAEoB,cAAc,CAAC;mBACvB,EAAEX,QAAQ,CAAC;uBACP,EAAEY,kBAAkB,CAAC;6BACf,EAAEC,mBAAmB,CAAC;;;IAG/C,CAAC,CAAA;KACF;CACF;AAED,eAAe1B,oBAAoB,CAAA"}

View File

@@ -0,0 +1,327 @@
import { parse as parseUrl, format as formatUrl } from "url";
import { DecodeError, isResSent } from "../../../../shared/lib/utils";
import { sendRenderResult } from "../../../../server/send-payload";
import { getUtils, vercelHeader } from "./utils";
import { renderToHTML } from "../../../../server/render";
import { tryGetPreviewData } from "../../../../server/api-utils/node";
import { denormalizePagePath } from "../../../../shared/lib/page-path/denormalize-page-path";
import { setLazyProp, getCookieParser } from "../../../../server/api-utils";
import { getRedirectStatus } from "../../../../lib/redirect-status";
import getRouteNoAssetPath from "../../../../shared/lib/router/utils/get-route-from-asset-path";
import { PERMANENT_REDIRECT_STATUS } from "../../../../shared/lib/constants";
import RenderResult from "../../../../server/render-result";
import isError from "../../../../lib/is-error";
export function getPageHandler(ctx) {
const { page , pageComponent , pageConfig , pageGetStaticProps , pageGetStaticPaths , pageGetServerSideProps , appModule , documentModule , errorModule , notFoundModule , encodedPreviewProps , pageIsDynamic , generateEtags , poweredByHeader , runtimeConfig , buildManifest , reactLoadableManifest , i18n , buildId , basePath , assetPrefix , canonicalBase , escapedBuildId , } = ctx;
const { handleLocale , handleRewrites , handleBasePath , defaultRouteRegex , dynamicRouteMatcher , interpolateDynamicPath , getParamsFromRouteMatches , normalizeDynamicRouteParams , normalizeVercelUrl , } = getUtils(ctx);
async function renderReqToHTML(req, res, renderMode, _renderOpts, _params) {
let Component;
let App;
let config;
let Document;
let Error;
let notFoundMod;
let getStaticProps;
let getStaticPaths;
let getServerSideProps;
[getStaticProps, getServerSideProps, getStaticPaths, Component, App, config, { default: Document }, { default: Error }, notFoundMod, ] = await Promise.all([
pageGetStaticProps,
pageGetServerSideProps,
pageGetStaticPaths,
pageComponent,
appModule,
pageConfig,
documentModule,
errorModule,
notFoundModule,
]);
const fromExport = renderMode === "export" || renderMode === true;
const nextStartMode = renderMode === "passthrough";
let hasValidParams = true;
setLazyProp({
req: req
}, "cookies", getCookieParser(req.headers));
const options = {
App,
Document,
ComponentMod: {
default: Component
},
buildManifest,
getStaticProps,
getServerSideProps,
getStaticPaths,
reactLoadableManifest,
canonicalBase,
buildId,
assetPrefix,
runtimeConfig: (runtimeConfig || {}).publicRuntimeConfig || {},
previewProps: encodedPreviewProps,
env: process.env,
basePath,
supportsDynamicHTML: false,
..._renderOpts
};
let _nextData = false;
let defaultLocale = i18n == null ? void 0 : i18n.defaultLocale;
let detectedLocale = i18n == null ? void 0 : i18n.defaultLocale;
let parsedUrl;
try {
var ref;
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = !getStaticProps && req.headers[vercelHeader];
parsedUrl = parseUrl(req.url, true);
let routeNoAssetPath = parsedUrl.pathname;
if (basePath) {
routeNoAssetPath = routeNoAssetPath.replace(new RegExp(`^${basePath}`), "") || "/";
}
const origQuery = Object.assign({}, parsedUrl.query);
handleRewrites(req, parsedUrl);
handleBasePath(req, parsedUrl);
// remove ?amp=1 from request URL if rendering for export
if (fromExport && parsedUrl.query.amp) {
const queryNoAmp = Object.assign({}, origQuery);
delete queryNoAmp.amp;
req.url = formatUrl({
...parsedUrl,
search: undefined,
query: queryNoAmp
});
}
if (parsedUrl.pathname.match(/_next\/data/)) {
_nextData = page !== "/_error";
parsedUrl.pathname = getRouteNoAssetPath(parsedUrl.pathname.replace(new RegExp(`/_next/data/${escapedBuildId}/`), "/"), ".json");
routeNoAssetPath = parsedUrl.pathname;
}
const localeResult = handleLocale(req, res, parsedUrl, routeNoAssetPath, fromExport || nextStartMode);
defaultLocale = (localeResult == null ? void 0 : localeResult.defaultLocale) || defaultLocale;
detectedLocale = (localeResult == null ? void 0 : localeResult.detectedLocale) || detectedLocale;
routeNoAssetPath = (localeResult == null ? void 0 : localeResult.routeNoAssetPath) || routeNoAssetPath;
if (parsedUrl.query.nextInternalLocale) {
detectedLocale = parsedUrl.query.nextInternalLocale;
delete parsedUrl.query.nextInternalLocale;
}
const renderOpts = Object.assign({
Component,
pageConfig: config,
nextExport: fromExport,
isDataReq: _nextData,
locales: i18n == null ? void 0 : i18n.locales,
locale: detectedLocale,
defaultLocale,
domainLocales: i18n == null ? void 0 : i18n.domains,
optimizeCss: process.env.__NEXT_OPTIMIZE_CSS,
nextScriptWorkers: process.env.__NEXT_SCRIPT_WORKERS,
crossOrigin: process.env.__NEXT_CROSS_ORIGIN
}, options);
if (page === "/_error" && !res.statusCode) {
res.statusCode = 404;
}
let params = {};
if (!fromExport && pageIsDynamic) {
const result = normalizeDynamicRouteParams(trustQuery ? parsedUrl.query : dynamicRouteMatcher(parsedUrl.pathname));
hasValidParams = result.hasValidParams;
params = result.params;
}
let nowParams = null;
if (pageIsDynamic && !hasValidParams && ((ref = req.headers) == null ? void 0 : ref["x-now-route-matches"])) {
nowParams = getParamsFromRouteMatches(req, renderOpts, detectedLocale);
}
// make sure to set renderOpts to the correct params e.g. _params
// if provided from worker or params if we're parsing them here
renderOpts.params = _params || params;
normalizeVercelUrl(req, !!trustQuery);
// normalize request URL/asPath for fallback/revalidate pages since the
// proxy sets the request URL to the output's path for fallback pages
if (pageIsDynamic && nowParams && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url);
_parsedUrl.pathname = interpolateDynamicPath(_parsedUrl.pathname, nowParams);
parsedUrl.pathname = _parsedUrl.pathname;
req.url = formatUrl(_parsedUrl);
}
// make sure to normalize asPath for revalidate and _next/data requests
// since the asPath should match what is shown on the client
if (!fromExport && (getStaticProps || getServerSideProps)) {
// don't include dynamic route params in query while normalizing
// asPath
if (pageIsDynamic && defaultRouteRegex) {
delete parsedUrl.search;
for (const param of Object.keys(defaultRouteRegex.groups)){
delete origQuery[param];
}
}
parsedUrl.pathname = denormalizePagePath(parsedUrl.pathname);
renderOpts.resolvedUrl = formatUrl({
...parsedUrl,
query: origQuery
});
// For getServerSideProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on asPath
renderOpts.resolvedAsPath = getServerSideProps ? formatUrl({
...parsedUrl,
pathname: routeNoAssetPath,
query: origQuery
}) : renderOpts.resolvedUrl;
}
const isFallback = parsedUrl.query.__nextFallback;
const previewData = tryGetPreviewData(req, res, options.previewProps);
const isPreviewMode = previewData !== false;
if (process.env.__NEXT_OPTIMIZE_FONTS) {
renderOpts.optimizeFonts = process.env.__NEXT_OPTIMIZE_FONTS;
/**
* __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
* font-stylesheet-gathering-plugin
*/ // @ts-ignore
renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__;
}
let result = await renderToHTML(req, res, page, Object.assign({}, getStaticProps ? {
...parsedUrl.query.amp ? {
amp: "1"
} : {}
} : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? {
__nextFallback: "true"
} : {}), renderOpts);
if (!renderMode) {
if (_nextData || getStaticProps || getServerSideProps) {
if (renderOpts.isNotFound) {
res.statusCode = 404;
if (_nextData) {
res.end('{"notFound":true}');
return null;
}
const NotFoundComponent = notFoundMod ? notFoundMod.default : Error;
const errPathname = notFoundMod ? "/404" : "/_error";
const result2 = await renderToHTML(req, res, errPathname, parsedUrl.query, Object.assign({}, options, {
getStaticProps: notFoundMod ? notFoundMod.getStaticProps : undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: NotFoundComponent,
err: undefined,
locale: detectedLocale,
locales: i18n == null ? void 0 : i18n.locales,
defaultLocale: i18n == null ? void 0 : i18n.defaultLocale
}));
sendRenderResult({
req,
res,
result: result2 ?? RenderResult.empty,
type: "html",
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || page === "/404",
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate
}
});
return null;
} else if (renderOpts.isRedirect && !_nextData) {
const redirect = {
destination: renderOpts.pageData.pageProps.__N_REDIRECT,
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS,
basePath: renderOpts.pageData.pageProps.__N_REDIRECT_BASE_PATH
};
const statusCode = getRedirectStatus(redirect);
if (basePath && redirect.basePath !== false && redirect.destination.startsWith("/")) {
redirect.destination = `${basePath}${redirect.destination}`;
}
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader("Refresh", `0;url=${redirect.destination}`);
}
res.statusCode = statusCode;
res.setHeader("Location", redirect.destination);
res.end(redirect.destination);
return null;
} else {
sendRenderResult({
req,
res,
result: _nextData ? RenderResult.fromStatic(JSON.stringify(renderOpts.pageData)) : result ?? RenderResult.empty,
type: _nextData ? "json" : "html",
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || renderOpts.is404Page,
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate
}
});
return null;
}
}
} else if (isPreviewMode) {
res.setHeader("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
}
if (renderMode) return {
html: result,
renderOpts
};
return result ? result.toUnchunkedString() : null;
} catch (err) {
if (!parsedUrl) {
parsedUrl = parseUrl(req.url, true);
}
if (isError(err) && err.code === "ENOENT") {
res.statusCode = 404;
} else if (err instanceof DecodeError) {
res.statusCode = 400;
} else {
console.error("Unhandled error during request:", err);
// Backwards compat (call getInitialProps in custom error):
try {
await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: err,
// Short-circuit rendering:
isDataReq: true
}));
} catch (underErrorErr) {
console.error("Failed call /_error subroutine, continuing to crash function:", underErrorErr);
}
// Throw the error to crash the serverless function
if (isResSent(res)) {
console.error("!!! WARNING !!!");
console.error("Your function crashed, but closed the response before allowing the function to exit.\\n" + "This may cause unexpected behavior for the next request.");
console.error("!!! WARNING !!!");
}
throw err;
}
const result2 = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: res.statusCode === 404 ? undefined : err
}));
return result2 ? result2.toUnchunkedString() : null;
}
}
return {
renderReqToHTML,
render: async function render(req, res) {
try {
const html = await renderReqToHTML(req, res);
if (html) {
sendRenderResult({
req,
res,
result: RenderResult.fromStatic(html),
type: "html",
generateEtags,
poweredByHeader
});
}
} catch (err) {
console.error(err);
// Throw the error to crash the serverless function
throw err;
}
}
};
}
//# sourceMappingURL=page-handler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,361 @@
import { format as formatUrl, parse as parseUrl } from "url";
import { parse as parseQs } from "querystring";
import { normalizeLocalePath } from "../../../../shared/lib/i18n/normalize-locale-path";
import { getPathMatch } from "../../../../shared/lib/router/utils/path-match";
import { getNamedRouteRegex } from "../../../../shared/lib/router/utils/route-regex";
import { getRouteMatcher } from "../../../../shared/lib/router/utils/route-matcher";
import { matchHas, prepareDestination } from "../../../../shared/lib/router/utils/prepare-destination";
import { acceptLanguage } from "../../../../server/accept-header";
import { detectLocaleCookie } from "../../../../shared/lib/i18n/detect-locale-cookie";
import { detectDomainLocale } from "../../../../shared/lib/i18n/detect-domain-locale";
import { denormalizePagePath } from "../../../../shared/lib/page-path/denormalize-page-path";
import cookie from "next/dist/compiled/cookie";
import { TEMPORARY_REDIRECT_STATUS } from "../../../../shared/lib/constants";
import { addRequestMeta } from "../../../../server/request-meta";
import { removeTrailingSlash } from "../../../../shared/lib/router/utils/remove-trailing-slash";
import { normalizeRscPath } from "../../../../shared/lib/router/utils/app-paths";
export const vercelHeader = "x-vercel-id";
export function normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex) {
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url, true);
delete _parsedUrl.search;
for (const param of paramKeys || Object.keys(defaultRouteRegex.groups)){
delete _parsedUrl.query[param];
}
req.url = formatUrl(_parsedUrl);
}
}
export function interpolateDynamicPath(pathname, params, defaultRouteRegex) {
if (!defaultRouteRegex) return pathname;
for (const param of Object.keys(defaultRouteRegex.groups)){
const { optional , repeat } = defaultRouteRegex.groups[param];
let builtParam = `[${repeat ? "..." : ""}${param}]`;
if (optional) {
builtParam = `[${builtParam}]`;
}
const paramIdx = pathname.indexOf(builtParam);
if (paramIdx > -1) {
let paramValue;
const value = params[param];
if (Array.isArray(value)) {
paramValue = value.map((v)=>v && encodeURIComponent(v)).join("/");
} else if (value) {
paramValue = encodeURIComponent(value);
} else {
paramValue = "";
}
pathname = pathname.slice(0, paramIdx) + paramValue + pathname.slice(paramIdx + builtParam.length);
}
}
return pathname;
}
export function getUtils({ page , i18n , basePath , rewrites , pageIsDynamic , trailingSlash }) {
let defaultRouteRegex;
let dynamicRouteMatcher;
let defaultRouteMatches;
if (pageIsDynamic) {
defaultRouteRegex = getNamedRouteRegex(page);
dynamicRouteMatcher = getRouteMatcher(defaultRouteRegex);
defaultRouteMatches = dynamicRouteMatcher(page);
}
function handleRewrites(req, parsedUrl) {
const rewriteParams = {};
let fsPathname = parsedUrl.pathname;
const matchesPage = ()=>{
const fsPathnameNoSlash = removeTrailingSlash(fsPathname || "");
return fsPathnameNoSlash === removeTrailingSlash(page) || (dynamicRouteMatcher == null ? void 0 : dynamicRouteMatcher(fsPathnameNoSlash));
};
const checkRewrite = (rewrite)=>{
const matcher = getPathMatch(rewrite.source + (trailingSlash ? "(/)?" : ""), {
removeUnnamedParams: true,
strict: true
});
let params = matcher(parsedUrl.pathname);
if ((rewrite.has || rewrite.missing) && params) {
const hasParams = matchHas(req, parsedUrl.query, rewrite.has, rewrite.missing);
if (hasParams) {
Object.assign(params, hasParams);
} else {
params = false;
}
}
if (params) {
const { parsedDestination , destQuery } = prepareDestination({
appendParamsToQuery: true,
destination: rewrite.destination,
params: params,
query: parsedUrl.query
});
// if the rewrite destination is external break rewrite chain
if (parsedDestination.protocol) {
return true;
}
Object.assign(rewriteParams, destQuery, params);
Object.assign(parsedUrl.query, parsedDestination.query);
delete parsedDestination.query;
Object.assign(parsedUrl, parsedDestination);
fsPathname = parsedUrl.pathname;
if (basePath) {
fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), "") || "/";
}
if (i18n) {
const destLocalePathResult = normalizeLocalePath(fsPathname, i18n.locales);
fsPathname = destLocalePathResult.pathname;
parsedUrl.query.nextInternalLocale = destLocalePathResult.detectedLocale || params.nextInternalLocale;
}
if (fsPathname === page) {
return true;
}
if (pageIsDynamic && dynamicRouteMatcher) {
const dynamicParams = dynamicRouteMatcher(fsPathname);
if (dynamicParams) {
parsedUrl.query = {
...parsedUrl.query,
...dynamicParams
};
return true;
}
}
}
return false;
};
for (const rewrite1 of rewrites.beforeFiles || []){
checkRewrite(rewrite1);
}
if (fsPathname !== page) {
let finished = false;
for (const rewrite of rewrites.afterFiles || []){
finished = checkRewrite(rewrite);
if (finished) break;
}
if (!finished && !matchesPage()) {
for (const rewrite of rewrites.fallback || []){
finished = checkRewrite(rewrite);
if (finished) break;
}
}
}
return rewriteParams;
}
function handleBasePath(req, parsedUrl) {
// always strip the basePath if configured since it is required
req.url = req.url.replace(new RegExp(`^${basePath}`), "") || "/";
parsedUrl.pathname = parsedUrl.pathname.replace(new RegExp(`^${basePath}`), "") || "/";
}
function getParamsFromRouteMatches(req, renderOpts, detectedLocale) {
return getRouteMatcher(function() {
const { groups , routeKeys } = defaultRouteRegex;
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
exec: (str)=>{
const obj = parseQs(str);
const matchesHasLocale = i18n && detectedLocale && obj["1"] === detectedLocale;
// favor named matches if available
const routeKeyNames = Object.keys(routeKeys || {});
const filterLocaleItem = (val)=>{
if (i18n) {
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are
// filtered
const isCatchAll = Array.isArray(val);
const _val = isCatchAll ? val[0] : val;
if (typeof _val === "string" && i18n.locales.some((item)=>{
if (item.toLowerCase() === _val.toLowerCase()) {
detectedLocale = item;
renderOpts.locale = detectedLocale;
return true;
}
return false;
})) {
// remove the locale item from the match
if (isCatchAll) {
val.splice(0, 1);
}
// the value is only a locale item and
// shouldn't be added
return isCatchAll ? val.length === 0 : true;
}
}
return false;
};
if (routeKeyNames.every((name)=>obj[name])) {
return routeKeyNames.reduce((prev, keyName)=>{
const paramName = routeKeys == null ? void 0 : routeKeys[keyName];
if (paramName && !filterLocaleItem(obj[keyName])) {
prev[groups[paramName].pos] = obj[keyName];
}
return prev;
}, {});
}
return Object.keys(obj).reduce((prev, key)=>{
if (!filterLocaleItem(obj[key])) {
let normalizedKey = key;
if (matchesHasLocale) {
normalizedKey = parseInt(key, 10) - 1 + "";
}
return Object.assign(prev, {
[normalizedKey]: obj[key]
});
}
return prev;
}, {});
}
},
groups
};
}())(req.headers["x-now-route-matches"]);
}
function normalizeDynamicRouteParams(params, ignoreOptional) {
let hasValidParams = true;
if (!defaultRouteRegex) return {
params,
hasValidParams: false
};
params = Object.keys(defaultRouteRegex.groups).reduce((prev, key)=>{
let value = params[key];
if (typeof value === "string") {
value = normalizeRscPath(value, true);
}
if (Array.isArray(value)) {
value = value.map((val)=>{
if (typeof val === "string") {
val = normalizeRscPath(val, true);
}
return val;
});
}
// if the value matches the default value we can't rely
// on the parsed params, this is used to signal if we need
// to parse x-now-route-matches or not
const defaultValue = defaultRouteMatches[key];
const isOptional = defaultRouteRegex.groups[key].optional;
const isDefaultValue = Array.isArray(defaultValue) ? defaultValue.some((defaultVal)=>{
return Array.isArray(value) ? value.some((val)=>val.includes(defaultVal)) : value == null ? void 0 : value.includes(defaultVal);
}) : value == null ? void 0 : value.includes(defaultValue);
if (isDefaultValue || typeof value === "undefined" && !(isOptional && ignoreOptional)) {
hasValidParams = false;
}
// non-provided optional values should be undefined so normalize
// them to undefined
if (isOptional && (!value || Array.isArray(value) && value.length === 1 && // fallback optional catch-all SSG pages have
// [[...paramName]] for the root path on Vercel
(value[0] === "index" || value[0] === `[[...${key}]]`))) {
value = undefined;
delete params[key];
}
// query values from the proxy aren't already split into arrays
// so make sure to normalize catch-all values
if (value && typeof value === "string" && defaultRouteRegex.groups[key].repeat) {
value = value.split("/");
}
if (value) {
prev[key] = value;
}
return prev;
}, {});
return {
params,
hasValidParams
};
}
function handleLocale(req, res, parsedUrl, routeNoAssetPath, shouldNotRedirect) {
if (!i18n) return;
const pathname = parsedUrl.pathname || "/";
let defaultLocale = i18n.defaultLocale;
let detectedLocale = detectLocaleCookie(req, i18n.locales);
let acceptPreferredLocale;
try {
acceptPreferredLocale = i18n.localeDetection !== false ? acceptLanguage(req.headers["accept-language"], i18n.locales) : detectedLocale;
} catch (_) {
acceptPreferredLocale = detectedLocale;
}
const { host } = req.headers || {};
// remove port from host and remove port if present
const hostname = host && host.split(":")[0].toLowerCase();
const detectedDomain = detectDomainLocale(i18n.domains, hostname);
if (detectedDomain) {
defaultLocale = detectedDomain.defaultLocale;
detectedLocale = defaultLocale;
addRequestMeta(req, "__nextIsLocaleDomain", true);
}
// if not domain specific locale use accept-language preferred
detectedLocale = detectedLocale || acceptPreferredLocale;
let localeDomainRedirect;
const localePathResult = normalizeLocalePath(pathname, i18n.locales);
routeNoAssetPath = normalizeLocalePath(routeNoAssetPath, i18n.locales).pathname;
if (localePathResult.detectedLocale) {
detectedLocale = localePathResult.detectedLocale;
req.url = formatUrl({
...parsedUrl,
pathname: localePathResult.pathname
});
addRequestMeta(req, "__nextStrippedLocale", true);
parsedUrl.pathname = localePathResult.pathname;
}
// If a detected locale is a domain specific locale and we aren't already
// on that domain and path prefix redirect to it to prevent duplicate
// content from multiple domains
if (detectedDomain) {
const localeToCheck = localePathResult.detectedLocale ? detectedLocale : acceptPreferredLocale;
const matchedDomain = detectDomainLocale(i18n.domains, undefined, localeToCheck);
if (matchedDomain && matchedDomain.domain !== detectedDomain.domain) {
localeDomainRedirect = `http${matchedDomain.http ? "" : "s"}://${matchedDomain.domain}/${localeToCheck === matchedDomain.defaultLocale ? "" : localeToCheck}`;
}
}
const denormalizedPagePath = denormalizePagePath(pathname);
const detectedDefaultLocale = !detectedLocale || detectedLocale.toLowerCase() === defaultLocale.toLowerCase();
const shouldStripDefaultLocale = false;
// detectedDefaultLocale &&
// denormalizedPagePath.toLowerCase() === \`/\${i18n.defaultLocale.toLowerCase()}\`
const shouldAddLocalePrefix = !detectedDefaultLocale && denormalizedPagePath === "/";
detectedLocale = detectedLocale || i18n.defaultLocale;
if (!shouldNotRedirect && !req.headers[vercelHeader] && i18n.localeDetection !== false && (localeDomainRedirect || shouldAddLocalePrefix || shouldStripDefaultLocale)) {
// set the NEXT_LOCALE cookie when a user visits the default locale
// with the locale prefix so that they aren't redirected back to
// their accept-language preferred locale
if (shouldStripDefaultLocale && acceptPreferredLocale !== defaultLocale) {
const previous = res.getHeader("set-cookie");
res.setHeader("set-cookie", [
...typeof previous === "string" ? [
previous
] : Array.isArray(previous) ? previous : [],
cookie.serialize("NEXT_LOCALE", defaultLocale, {
httpOnly: true,
path: "/"
}),
]);
}
res.setHeader("Location", formatUrl({
// make sure to include any query values when redirecting
...parsedUrl,
pathname: localeDomainRedirect ? localeDomainRedirect : shouldStripDefaultLocale ? basePath || "/" : `${basePath}/${detectedLocale}`
}));
res.statusCode = TEMPORARY_REDIRECT_STATUS;
res.end();
return;
}
detectedLocale = localePathResult.detectedLocale || detectedDomain && detectedDomain.defaultLocale || defaultLocale;
return {
defaultLocale,
detectedLocale,
routeNoAssetPath
};
}
return {
handleLocale,
handleRewrites,
handleBasePath,
defaultRouteRegex,
dynamicRouteMatcher,
defaultRouteMatches,
getParamsFromRouteMatches,
normalizeDynamicRouteParams,
normalizeVercelUrl: (req, trustQuery, paramKeys)=>normalizeVercelUrl(req, trustQuery, paramKeys, pageIsDynamic, defaultRouteRegex),
interpolateDynamicPath: (pathname, params)=>interpolateDynamicPath(pathname, params, defaultRouteRegex)
};
}
//# sourceMappingURL=utils.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,208 @@
import path from "path";
import isEqualLocals from "./runtime/isEqualLocals";
import { stringifyRequest } from "../../stringify-request";
const loaderApi = ()=>{};
loaderApi.pitch = function loader(request) {
const loaderSpan = this.currentTraceSpan.traceChild("next-style-loader");
return loaderSpan.traceFn(()=>{
const options = this.getOptions();
const insert = typeof options.insert === "undefined" ? '"head"' : typeof options.insert === "string" ? JSON.stringify(options.insert) : options.insert.toString();
const injectType = options.injectType || "styleTag";
const esModule = typeof options.esModule !== "undefined" ? options.esModule : false;
delete options.esModule;
switch(injectType){
case "linkTag":
{
const hmrCode = this.hot ? `
if (module.hot) {
module.hot.accept(
${stringifyRequest(this, `!!${request}`)},
function() {
${esModule ? "update(content);" : `content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
update(content);`}
}
);
module.hot.dispose(function() {
update();
});
}` : "";
return `${esModule ? `import api from ${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoLinkTag.js")}`)};
import content from ${stringifyRequest(this, `!!${request}`)};` : `var api = require(${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoLinkTag.js")}`)});
var content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;`}
var options = ${JSON.stringify(options)};
options.insert = ${insert};
var update = api(content, options);
${hmrCode}
${esModule ? "export default {}" : ""}`;
}
case "lazyStyleTag":
case "lazySingletonStyleTag":
{
const isSingleton = injectType === "lazySingletonStyleTag";
const hmrCode = this.hot ? `
if (module.hot) {
if (!content.locals || module.hot.invalidate) {
var isEqualLocals = ${isEqualLocals.toString()};
var oldLocals = content.locals;
module.hot.accept(
${stringifyRequest(this, `!!${request}`)},
function () {
${esModule ? `if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
if (update && refs > 0) {
update(content);
}` : `content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
if (update && refs > 0) {
update(content);
}`}
}
)
}
module.hot.dispose(function() {
if (update) {
update();
}
});
}` : "";
return `${esModule ? `import api from ${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)};
import content from ${stringifyRequest(this, `!!${request}`)};` : `var api = require(${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)});
var content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (typeof content === 'string') {
content = [[module.id, content, '']];
}`}
var refs = 0;
var update;
var options = ${JSON.stringify(options)};
options.insert = ${insert};
options.singleton = ${isSingleton};
var exported = {};
exported.locals = content.locals || {};
exported.use = function() {
if (!(refs++)) {
update = api(content, options);
}
return exported;
};
exported.unuse = function() {
if (refs > 0 && !--refs) {
update();
update = null;
}
};
${hmrCode}
${esModule ? "export default" : "module.exports ="} exported;`;
}
case "styleTag":
case "singletonStyleTag":
default:
{
const isSingleton = injectType === "singletonStyleTag";
const hmrCode = this.hot ? `
if (module.hot) {
if (!content.locals || module.hot.invalidate) {
var isEqualLocals = ${isEqualLocals.toString()};
var oldLocals = content.locals;
module.hot.accept(
${stringifyRequest(this, `!!${request}`)},
function () {
${esModule ? `if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
update(content);` : `content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (typeof content === 'string') {
content = [[module.id, content, '']];
}
if (!isEqualLocals(oldLocals, content.locals)) {
module.hot.invalidate();
return;
}
oldLocals = content.locals;
update(content);`}
}
)
}
module.hot.dispose(function() {
update();
});
}` : "";
return `${esModule ? `import api from ${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)};
import content from ${stringifyRequest(this, `!!${request}`)};` : `var api = require(${stringifyRequest(this, `!${path.join(__dirname, "runtime/injectStylesIntoStyleTag.js")}`)});
var content = require(${stringifyRequest(this, `!!${request}`)});
content = content.__esModule ? content.default : content;
if (typeof content === 'string') {
content = [[module.id, content, '']];
}`}
var options = ${JSON.stringify(options)};
options.insert = ${insert};
options.singleton = ${isSingleton};
var update = api(content, options);
${hmrCode}
${esModule ? "export default" : "module.exports ="} content.locals || {};`;
}
}
});
};
module.exports = loaderApi;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../build/webpack/loaders/next-style-loader/index.js"],"names":["path","isEqualLocals","stringifyRequest","loaderApi","pitch","loader","request","loaderSpan","currentTraceSpan","traceChild","traceFn","options","getOptions","insert","JSON","stringify","toString","injectType","esModule","hmrCode","hot","join","__dirname","isSingleton","module","exports"],"mappings":"AAAA,OAAOA,IAAI,MAAM,MAAM,CAAA;AACvB,OAAOC,aAAa,MAAM,yBAAyB,CAAA;AACnD,SAASC,gBAAgB,QAAQ,yBAAyB,CAAA;AAE1D,MAAMC,SAAS,GAAG,IAAM,EAAE;AAE1BA,SAAS,CAACC,KAAK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I,EACJ,CAAC,CAAC,EAAEF,IAAI,CAACqB,IAAI,CACXC,SAAS,EACT,qCAAqC,CACtC,CAAC,CAAC,CACJ,CAAC;gCACgB,EAAEpB,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAEI,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAC7D,CAAC,kBAAkB,EAAEJ,gBAAgB,CACnC,IAAI,EACJ,CAAC,CAAC,EAAEF,IAAI,CAACqB,IAAI,CACXC,SAAS,EACT,qCAAqC,CACtC,CAAC,CAAC,CACJ,CAAC;kCACkB,EAAEpB,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,EAAEI,OAAO,CAAC,CAAC,CAAC,CAAC;;;;;;aAM9D,CAAC,CACL;;cAEK,EAAEQ,IAAI,CAACC,SAAS,CAACJ,OAAO,CAAC,CAAC;;iBAEvB,EAAEE,MAAM,CAAC;oBACN,EAAEU,WAAW,CAAC;;;;AAIlC,EAAEJ,OAAO,CAAC;;AAEV,EAAED,QAAQ,GAAG,gBAAgB,GAAG,kBAAkB,CAAC,sBAAsB,CAAC,CAAA;iBACnE;SACF;KACF,CAAC,CAAA;CACH;AAEDM,MAAM,CAACC,OAAO,GAAGtB,SAAS"}

View File

@@ -0,0 +1,56 @@
const getTarget = function getTarget() {
const memo = {};
return function memorize(target) {
if (typeof memo[target] === "undefined") {
let styleTarget = document.querySelector(target);
// Special case to return head of iframe instead of iframe itself
if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch (e) {
// istanbul ignore next
styleTarget = null;
}
}
memo[target] = styleTarget;
}
return memo[target];
};
}();
module.exports = (url, options)=>{
options = options || {};
options.attributes = typeof options.attributes === "object" ? options.attributes : {};
if (typeof options.attributes.nonce === "undefined") {
const nonce = // eslint-disable-next-line no-undef
typeof __webpack_nonce__ !== "undefined" ? __webpack_nonce__ : null;
if (nonce) {
options.attributes.nonce = nonce;
}
}
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
Object.keys(options.attributes).forEach((key)=>{
link.setAttribute(key, options.attributes[key]);
});
if (typeof options.insert === "function") {
options.insert(link);
} else {
const target = getTarget(options.insert || "head");
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
}
target.appendChild(link);
}
return (newUrl)=>{
if (typeof newUrl === "string") {
link.href = newUrl;
} else {
link.parentNode.removeChild(link);
}
};
};
//# sourceMappingURL=injectStylesIntoLinkTag.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../../build/webpack/loaders/next-style-loader/runtime/injectStylesIntoLinkTag.js"],"names":["getTarget","memo","memorize","target","styleTarget","document","querySelector","window","HTMLIFrameElement","contentDocument","head","e","module","exports","url","options","attributes","nonce","__webpack_nonce__","link","createElement","rel","href","Object","keys","forEach","key","setAttribute","insert","Error","appendChild","newUrl","parentNode","removeChild"],"mappings":"AAAA,MAAMA,SAAS,GAAG,AAAC,SAASA,SAAS,GAAG;IACtC,MAAMC,IAAI,GAAG,EAAE;IAEf,OAAO,SAASC,QAAQ,CAACC,MAAM,EAAE;QAC/B,IAAI,OAAOF,IAAI,CAACE,MAAM,CAAC,KAAK,WAAW,EAAE;YACvC,IAAIC,WAAW,GAAGC,QAAQ,CAACC,aAAa,CAACH,MAAM,CAAC;YAEhD,iEAAiE;YACjE,IACEI,MAAM,CAACC,iBAAiB,IACxBJ,WAAW,YAAYG,MAAM,CAACC,iBAAiB,EAC/C;gBACA,IAAI;oBACF,8DAA8D;oBAC9D,mCAAmC;oBACnCJ,WAAW,GAAGA,WAAW,CAACK,eAAe,CAACC,IAAI;iBAC/C,CAAC,OAAOC,CAAC,EAAE;oBACV,uBAAuB;oBACvBP,WAAW,GAAG,IAAI;iBACnB;aACF;YAEDH,IAAI,CAACE,MAAM,CAAC,GAAGC,WAAW;SAC3B;QAED,OAAOH,IAAI,CAACE,MAAM,C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CAACG,IAAI,GAAGS,MAAM;SACnB,MAAM;YACLZ,IAAI,CAACa,UAAU,CAACC,WAAW,CAACd,IAAI,CAAC;SAClC;KACF,CAAA;CACF"}

View File

@@ -0,0 +1,216 @@
const isOldIE = function isOldIE() {
let memo;
return function memorize() {
if (typeof memo === "undefined") {
// Test for IE <= 9 as proposed by Browserhacks
// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
// Tests for existence of standard globals is to allow style-loader
// to operate correctly into non-standard environments
// @see https://github.com/webpack-contrib/style-loader/issues/177
memo = Boolean(window && document && document.all && !window.atob);
}
return memo;
};
}();
const getTarget = function getTarget() {
const memo = {};
return function memorize(target) {
if (typeof memo[target] === "undefined") {
let styleTarget = document.querySelector(target);
// Special case to return head of iframe instead of iframe itself
if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch (e) {
// istanbul ignore next
styleTarget = null;
}
}
memo[target] = styleTarget;
}
return memo[target];
};
}();
const stylesInDom = [];
function getIndexByIdentifier(identifier) {
let result = -1;
for(let i = 0; i < stylesInDom.length; i++){
if (stylesInDom[i].identifier === identifier) {
result = i;
break;
}
}
return result;
}
function modulesToDom(list, options) {
const idCountMap = {};
const identifiers = [];
for(let i = 0; i < list.length; i++){
const item = list[i];
const id = options.base ? item[0] + options.base : item[0];
const count = idCountMap[id] || 0;
const identifier = id + " " + count.toString();
idCountMap[id] = count + 1;
const index = getIndexByIdentifier(identifier);
const obj = {
css: item[1],
media: item[2],
sourceMap: item[3]
};
if (index !== -1) {
stylesInDom[index].references++;
stylesInDom[index].updater(obj);
} else {
stylesInDom.push({
identifier: identifier,
updater: addStyle(obj, options),
references: 1
});
}
identifiers.push(identifier);
}
return identifiers;
}
function insertStyleElement(options) {
const style = document.createElement("style");
const attributes = options.attributes || {};
if (typeof attributes.nonce === "undefined") {
const nonce = // eslint-disable-next-line no-undef
typeof __webpack_nonce__ !== "undefined" ? __webpack_nonce__ : null;
if (nonce) {
attributes.nonce = nonce;
}
}
Object.keys(attributes).forEach(function(key) {
style.setAttribute(key, attributes[key]);
});
if (typeof options.insert === "function") {
options.insert(style);
} else {
const target = getTarget(options.insert || "head");
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
}
target.appendChild(style);
}
return style;
}
function removeStyleElement(style) {
// istanbul ignore if
if (style.parentNode === null) {
return false;
}
style.parentNode.removeChild(style);
}
/* istanbul ignore next */ const replaceText = function replaceText() {
const textStore = [];
return function replace(index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join("\n");
};
}();
function applyToSingletonTag(style, index, remove, obj) {
const css = remove ? "" : obj.media ? "@media " + obj.media + " {" + obj.css + "}" : obj.css;
// For old IE
/* istanbul ignore if */ if (style.styleSheet) {
style.styleSheet.cssText = replaceText(index, css);
} else {
const cssNode = document.createTextNode(css);
const childNodes = style.childNodes;
if (childNodes[index]) {
style.removeChild(childNodes[index]);
}
if (childNodes.length) {
style.insertBefore(cssNode, childNodes[index]);
} else {
style.appendChild(cssNode);
}
}
}
function applyToTag(style, options, obj) {
let css = obj.css;
const media = obj.media;
const sourceMap = obj.sourceMap;
if (media) {
style.setAttribute("media", media);
} else {
style.removeAttribute("media");
}
if (sourceMap && typeof btoa !== "undefined") {
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
// For old IE
/* istanbul ignore if */ if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
while(style.firstChild){
style.removeChild(style.firstChild);
}
style.appendChild(document.createTextNode(css));
}
}
let singleton = null;
let singletonCounter = 0;
function addStyle(obj, options) {
let style;
let update;
let remove;
if (options.singleton) {
const styleIndex = singletonCounter++;
style = singleton || (singleton = insertStyleElement(options));
update = applyToSingletonTag.bind(null, style, styleIndex, false);
remove = applyToSingletonTag.bind(null, style, styleIndex, true);
} else {
style = insertStyleElement(options);
update = applyToTag.bind(null, style, options);
remove = function() {
removeStyleElement(style);
};
}
update(obj);
return function updateStyle(newObj) {
if (newObj) {
if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {
return;
}
update(obj = newObj);
} else {
remove();
}
};
}
module.exports = function(list, options) {
options = options || {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (!options.singleton && typeof options.singleton !== "boolean") {
options.singleton = isOldIE();
}
list = list || [];
let lastIdentifiers = modulesToDom(list, options);
return function update(newList) {
newList = newList || [];
if (Object.prototype.toString.call(newList) !== "[object Array]") {
return;
}
for(let i = 0; i < lastIdentifiers.length; i++){
const identifier = lastIdentifiers[i];
const index = getIndexByIdentifier(identifier);
stylesInDom[index].references--;
}
const newLastIdentifiers = modulesToDom(newList, options);
for(let i1 = 0; i1 < lastIdentifiers.length; i1++){
const identifier = lastIdentifiers[i1];
const index = getIndexByIdentifier(identifier);
if (stylesInDom[index].references === 0) {
stylesInDom[index].updater();
stylesInDom.splice(index, 1);
}
}
lastIdentifiers = newLastIdentifiers;
};
};
//# sourceMappingURL=injectStylesIntoStyleTag.js.map

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More