.
This commit is contained in:
Generated
Vendored
+22
@@ -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
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/css-loader/src/CssSyntaxError.ts"],"sourcesContent":["export default class CssSyntaxError extends Error {\n stack: any\n constructor(error: any) {\n super(error)\n\n const { reason, line, column } = error\n\n this.name = 'CssSyntaxError'\n\n // Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132\n // We don't need `plugin` and `file` properties.\n this.message = `${this.name}\\n\\n`\n\n if (typeof line !== 'undefined') {\n this.message += `(${line}:${column}) `\n }\n\n this.message += reason\n\n const code = error.showSourceCode()\n\n if (code) {\n this.message += `\\n\\n${code}\\n`\n }\n\n // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror\n this.stack = false\n }\n}\n"],"names":["CssSyntaxError","Error","constructor","error","reason","line","column","name","message","code","showSourceCode","stack"],"mappings":"AAAA,eAAe,MAAMA,uBAAuBC;IAE1CC,YAAYC,KAAU,CAAE;QACtB,KAAK,CAACA;QAEN,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAE,GAAGH;QAEjC,IAAI,CAACI,IAAI,GAAG;QAEZ,wFAAwF;QACxF,gDAAgD;QAChD,IAAI,CAACC,OAAO,GAAG,GAAG,IAAI,CAACD,IAAI,CAAC,IAAI,CAAC;QAEjC,IAAI,OAAOF,SAAS,aAAa;YAC/B,IAAI,CAACG,OAAO,IAAI,CAAC,CAAC,EAAEH,KAAK,CAAC,EAAEC,OAAO,EAAE,CAAC;QACxC;QAEA,IAAI,CAACE,OAAO,IAAIJ;QAEhB,MAAMK,OAAON,MAAMO,cAAc;QAEjC,IAAID,MAAM;YACR,IAAI,CAACD,OAAO,IAAI,CAAC,IAAI,EAAEC,KAAK,EAAE,CAAC;QACjC;QAEA,wIAAwI;QACxI,IAAI,CAACE,KAAK,GAAG;IACf;AACF","ignoreList":[0]}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
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 Object.defineProperty(new TypeError('Expected the input to be `string | string[]`'), "__NEXT_ERROR_CODE", {
|
||||
value: "E613",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
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
|
||||
+1
File diff suppressed because one or more lines are too long
+273
@@ -0,0 +1,273 @@
|
||||
/*
|
||||
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: '',
|
||||
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 Object.defineProperty(new Error('The "modules.namedExport" option requires the "esModules" option to be enabled'), "__NEXT_ERROR_CODE", {
|
||||
value: "E103",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
if (modulesOptions.exportLocalsConvention !== 'camelCaseOnly') {
|
||||
throw Object.defineProperty(new Error('The "modules.namedExport" option requires the "modules.exportLocalsConvention" option to be "camelCaseOnly"'), "__NEXT_ERROR_CODE", {
|
||||
value: "E23",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
return modulesOptions;
|
||||
}
|
||||
function normalizeOptions(rawOptions, loaderContext) {
|
||||
if (rawOptions.icss) {
|
||||
loaderContext.emitWarning(Object.defineProperty(new Error('The "icss" option is deprecated, use "modules.compileType: "icss"" instead'), "__NEXT_ERROR_CODE", {
|
||||
value: "E476",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
}));
|
||||
}
|
||||
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),
|
||||
deploymentId: rawOptions.deploymentId
|
||||
}));
|
||||
}
|
||||
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') {
|
||||
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 (error) {
|
||||
if (error.file) {
|
||||
this.addDependency(error.file);
|
||||
}
|
||||
throw error.name === 'CssSyntaxError' ? Object.defineProperty(new CssSyntaxError(error), "__NEXT_ERROR_CODE", {
|
||||
value: "E394",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
}) : error;
|
||||
}
|
||||
for (const warning of result.warnings()){
|
||||
this.emitWarning(Object.defineProperty(new Warning(warning), "__NEXT_ERROR_CODE", {
|
||||
value: "E394",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
}));
|
||||
}
|
||||
const imports = [
|
||||
...icssPluginImports.sort(sort),
|
||||
...importPluginImports.sort(sort),
|
||||
...urlPluginImports.sort(sort)
|
||||
];
|
||||
const api = [
|
||||
...importPluginApi.sort(sort),
|
||||
...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
|
||||
+1
File diff suppressed because one or more lines are too long
+6
@@ -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
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../../src/build/webpack/loaders/css-loader/src/plugins/index.ts"],"sourcesContent":["import importParser from './postcss-import-parser'\nimport icssParser from './postcss-icss-parser'\nimport urlParser from './postcss-url-parser'\n\nexport { importParser, icssParser, urlParser }\n"],"names":["importParser","icssParser","urlParser"],"mappings":"AAAA,OAAOA,kBAAkB,0BAAyB;AAClD,OAAOC,gBAAgB,wBAAuB;AAC9C,OAAOC,eAAe,uBAAsB;AAE5C,SAASF,YAAY,EAAEC,UAAU,EAAEC,SAAS,GAAE","ignoreList":[0]}
|
||||
Generated
Vendored
+95
@@ -0,0 +1,95 @@
|
||||
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 = [];
|
||||
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;
|
||||
}
|
||||
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
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+206
@@ -0,0 +1,206 @@
|
||||
import valueParser from 'next/dist/compiled/postcss-value-parser';
|
||||
import { normalizeUrl, resolveRequests, isUrlRequestable, requestify, // @ts-expect-error TODO: this export doesn't exist? Double check.
|
||||
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 = Object.defineProperty(new Error("It looks like you didn't end your @import statement correctly. Child nodes are attached to it."), "__NEXT_ERROR_CODE", {
|
||||
value: "E341",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
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 = Object.defineProperty(new Error(`Unable to find uri in "${atRule.toString()}"`), "__NEXT_ERROR_CODE", {
|
||||
value: "E215",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
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 = Object.defineProperty(new Error(`Unable to find uri in "${atRule.toString()}"`), "__NEXT_ERROR_CODE", {
|
||||
value: "E215",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
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 = Object.defineProperty(new Error(`Unable to find uri in "${atRule.toString()}"`), "__NEXT_ERROR_CODE", {
|
||||
value: "E215",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
error.node = atRule;
|
||||
throw error;
|
||||
}
|
||||
const mediaNodes = paramsNodes.slice(1);
|
||||
let media;
|
||||
if (mediaNodes.length > 0) {
|
||||
media = valueParser.stringify(mediaNodes).trim().toLowerCase();
|
||||
}
|
||||
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 {
|
||||
// @ts-expect-error TODO: there is no third argument?
|
||||
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();
|
||||
return {
|
||||
url: resolvedUrl,
|
||||
media,
|
||||
prefix,
|
||||
isRequestable
|
||||
};
|
||||
}
|
||||
atRule.remove();
|
||||
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
|
||||
node_modules/next/dist/esm/build/webpack/loaders/css-loader/src/plugins/postcss-import-parser.js.map
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+300
@@ -0,0 +1,300 @@
|
||||
import valueParser from 'next/dist/compiled/postcss-value-parser';
|
||||
import { resolveRequests, normalizeUrl, requestify, isUrlRequestable, isDataUrl, // @ts-expect-error TODO: this export doesn't exist? Double check.
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
if (prevValueNode.type === 'space') {
|
||||
if (!nodes[index - 2]) {
|
||||
return;
|
||||
}
|
||||
prevValueNode = nodes[index - 2];
|
||||
}
|
||||
if (prevValueNode.type !== 'comment') {
|
||||
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) {
|
||||
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)) {
|
||||
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
|
||||
});
|
||||
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) {
|
||||
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)) {
|
||||
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) {
|
||||
needIgnore = undefined;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let url = normalizeUrl(value, true);
|
||||
// Do not traverse inside `url`
|
||||
if (!shouldHandleURL(url, declaration, result, isSupportDataURLInNewURL)) {
|
||||
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`
|
||||
return false;
|
||||
}
|
||||
});
|
||||
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) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isDataUrl(url)) {
|
||||
return parsedDeclaration;
|
||||
}
|
||||
const [pathname, query, hashOrQuery] = url.split(/(\?)?#/, 3);
|
||||
let hash = '';
|
||||
// Build query string with deployment ID before the hash fragment
|
||||
if (query || options.deploymentId) {
|
||||
hash += '?';
|
||||
}
|
||||
if (options.deploymentId) {
|
||||
hash += `dpl=${options.deploymentId}`;
|
||||
}
|
||||
hash += hashOrQuery ? `#${hashOrQuery}` : '';
|
||||
const { needToResolveURL, rootContext } = options;
|
||||
const request = requestify(pathname, rootContext, // @ts-expect-error TODO: only 2 arguments allowed.
|
||||
needToResolveURL);
|
||||
if (!needToResolveURL) {
|
||||
return {
|
||||
...parsedDeclaration,
|
||||
url: request,
|
||||
hash
|
||||
};
|
||||
}
|
||||
const { resolver, context } = options;
|
||||
const resolvedUrl = await resolveRequests(resolver, context, [
|
||||
...new Set([
|
||||
request,
|
||||
url
|
||||
])
|
||||
]);
|
||||
if (!resolvedUrl) {
|
||||
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
|
||||
});
|
||||
}
|
||||
item.node.type = 'word';
|
||||
item.node.value = replacementName;
|
||||
item.declaration.value = item.parsed.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
};
|
||||
plugin.postcss = true;
|
||||
export default plugin;
|
||||
|
||||
//# sourceMappingURL=postcss-url-parser.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+82
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/ // css base code, injected by the css-loader
|
||||
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
|
||||
;
|
||||
// @ts-expect-error TODO: fix type
|
||||
list.i = function(modules, mediaQuery, dedupe) {
|
||||
if (typeof modules === 'string') {
|
||||
modules = [
|
||||
[
|
||||
null,
|
||||
modules,
|
||||
''
|
||||
]
|
||||
];
|
||||
}
|
||||
var alreadyImportedModules = {};
|
||||
if (dedupe) {
|
||||
for(var i = 0; i < this.length; i++){
|
||||
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] || '';
|
||||
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) {
|
||||
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
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../../src/build/webpack/loaders/css-loader/src/runtime/api.ts"],"sourcesContent":["/*\n MIT License http://www.opensource.org/licenses/mit-license.php\n Author Tobias Koppers @sokra\n*/\n// css base code, injected by the css-loader\nmodule.exports = function (useSourceMap: any) {\n var list: any[] = [] // return the list of modules as css string\n\n list.toString = function toString() {\n return this.map(function (item) {\n var content = cssWithMappingToString(item, useSourceMap)\n\n if (item[2]) {\n return '@media '.concat(item[2], ' {').concat(content, '}')\n }\n\n return content\n }).join('')\n } // import a list of modules into the list\n\n // @ts-expect-error TODO: fix type\n list.i = function (modules: any, mediaQuery: any, dedupe: any) {\n if (typeof modules === 'string') {\n modules = [[null, modules, '']]\n }\n\n var alreadyImportedModules: any = {}\n\n if (dedupe) {\n for (var i = 0; i < this.length; i++) {\n var id = this[i][0]\n\n if (id != null) {\n alreadyImportedModules[id] = true\n }\n }\n }\n\n for (var _i = 0; _i < modules.length; _i++) {\n var item: any = [].concat(modules[_i])\n\n if (dedupe && alreadyImportedModules[item[0]]) {\n continue\n }\n\n if (mediaQuery) {\n if (!item[2]) {\n item[2] = mediaQuery\n } else {\n item[2] = ''.concat(mediaQuery, ' and ').concat(item[2])\n }\n }\n\n list.push(item)\n }\n }\n\n return list\n}\n\nfunction cssWithMappingToString(item: any, useSourceMap: any) {\n var content = item[1] || ''\n\n var cssMapping = item[3]\n\n if (!cssMapping) {\n return content\n }\n\n if (useSourceMap && typeof btoa === 'function') {\n var sourceMapping = toComment(cssMapping)\n var sourceURLs = cssMapping.sources.map(function (source: string) {\n return '/*# sourceURL='\n .concat(cssMapping.sourceRoot || '')\n .concat(source, ' */')\n })\n return [content].concat(sourceURLs).concat([sourceMapping]).join('\\n')\n }\n\n return [content].join('\\n')\n} // Adapted from convert-source-map (MIT)\n\nfunction toComment(sourceMap: any) {\n var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))))\n var data =\n 'sourceMappingURL=data:application/json;charset=utf-8;base64,'.concat(\n base64\n )\n return '/*# '.concat(data, ' */')\n}\n"],"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;;;AAGA,GACA,4CAA4C;AAC5CA,OAAOC,OAAO,GAAG,SAAUC,YAAiB;IAC1C,IAAIC,OAAc,EAAE,CAAC,2CAA2C;;IAEhEA,KAAKC,QAAQ,GAAG,SAASA;QACvB,OAAO,IAAI,CAACC,GAAG,CAAC,SAAUC,IAAI;YAC5B,IAAIC,UAAUC,uBAAuBF,MAAMJ;YAE3C,IAAII,IAAI,CAAC,EAAE,EAAE;gBACX,OAAO,UAAUG,MAAM,CAACH,IAAI,CAAC,EAAE,EAAE,MAAMG,MAAM,CAACF,SAAS;YACzD;YAEA,OAAOA;QACT,GAAGG,IAAI,CAAC;IACV,EAAE,yCAAyC;;IAE3C,kCAAkC;IAClCP,KAAKQ,CAAC,GAAG,SAAUC,OAAY,EAAEC,UAAe,EAAEC,MAAW;QAC3D,IAAI,OAAOF,YAAY,UAAU;YAC/BA,UAAU;gBAAC;oBAAC;oBAAMA;oBAAS;iBAAG;aAAC;QACjC;QAEA,IAAIG,yBAA8B,CAAC;QAEnC,IAAID,QAAQ;YACV,IAAK,IAAIH,IAAI,GAAGA,IAAI,IAAI,CAACK,MAAM,EAAEL,IAAK;gBACpC,IAAIM,KAAK,IAAI,CAACN,EAAE,CAAC,EAAE;gBAEnB,IAAIM,MAAM,MAAM;oBACdF,sBAAsB,CAACE,GAAG,GAAG;gBAC/B;YACF;QACF;QAEA,IAAK,IAAIC,KAAK,GAAGA,KAAKN,QAAQI,MAAM,EAAEE,KAAM;YAC1C,IAAIZ,OAAY,EAAE,CAACG,MAAM,CAACG,OAAO,CAACM,GAAG;YAErC,IAAIJ,UAAUC,sBAAsB,CAACT,IAAI,CAAC,EAAE,CAAC,EAAE;gBAC7C;YACF;YAEA,IAAIO,YAAY;gBACd,IAAI,CAACP,IAAI,CAAC,EAAE,EAAE;oBACZA,IAAI,CAAC,EAAE,GAAGO;gBACZ,OAAO;oBACLP,IAAI,CAAC,EAAE,GAAG,GAAGG,MAAM,CAACI,YAAY,SAASJ,MAAM,CAACH,IAAI,CAAC,EAAE;gBACzD;YACF;YAEAH,KAAKgB,IAAI,CAACb;QACZ;IACF;IAEA,OAAOH;AACT;AAEA,SAASK,uBAAuBF,IAAS,EAAEJ,YAAiB;IAC1D,IAAIK,UAAUD,IAAI,CAAC,EAAE,IAAI;IAEzB,IAAIc,aAAad,IAAI,CAAC,EAAE;IAExB,IAAI,CAACc,YAAY;QACf,OAAOb;IACT;IAEA,IAAIL,gBAAgB,OAAOmB,SAAS,YAAY;QAC9C,IAAIC,gBAAgBC,UAAUH;QAC9B,IAAII,aAAaJ,WAAWK,OAAO,CAACpB,GAAG,CAAC,SAAUqB,MAAc;YAC9D,OAAO,iBACJjB,MAAM,CAACW,WAAWO,UAAU,IAAI,IAChClB,MAAM,CAACiB,QAAQ;QACpB;QACA,OAAO;YAACnB;SAAQ,CAACE,MAAM,CAACe,YAAYf,MAAM,CAAC;YAACa;SAAc,EAAEZ,IAAI,CAAC;IACnE;IAEA,OAAO;QAACH;KAAQ,CAACG,IAAI,CAAC;AACxB,EAAE,wCAAwC;AAE1C,SAASa,UAAUK,SAAc;IAC/B,IAAIC,SAASR,KAAKS,SAASC,mBAAmBC,KAAKC,SAAS,CAACL;IAC7D,IAAIM,OACF,+DAA+DzB,MAAM,CACnEoB;IAEJ,OAAO,OAAOpB,MAAM,CAACyB,MAAM;AAC7B","ignoreList":[0]}
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
module.exports = function(url, options) {
|
||||
if (!options) {
|
||||
options = {};
|
||||
}
|
||||
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)) {
|
||||
url = url.slice(1, -1);
|
||||
}
|
||||
if (options.hash) {
|
||||
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
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../../src/build/webpack/loaders/css-loader/src/runtime/getUrl.ts"],"sourcesContent":["module.exports = function (url: any, options: any) {\n if (!options) {\n options = {}\n }\n\n url = url && url.__esModule ? url.default : url\n\n if (typeof url !== 'string') {\n return url\n } // If url is already wrapped in quotes, remove them\n\n if (/^['\"].*['\"]$/.test(url)) {\n url = url.slice(1, -1)\n }\n\n if (options.hash) {\n url += options.hash\n } // Should url be wrapped?\n // See https://drafts.csswg.org/css-values-3/#urls\n\n if (/[\"'() \\t\\n]/.test(url) || options.needQuotes) {\n return '\"'.concat(url.replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n'), '\"')\n }\n\n return url\n}\n"],"names":["module","exports","url","options","__esModule","default","test","slice","hash","needQuotes","concat","replace"],"mappings":"AAAAA,OAAOC,OAAO,GAAG,SAAUC,GAAQ,EAAEC,OAAY;IAC/C,IAAI,CAACA,SAAS;QACZA,UAAU,CAAC;IACb;IAEAD,MAAMA,OAAOA,IAAIE,UAAU,GAAGF,IAAIG,OAAO,GAAGH;IAE5C,IAAI,OAAOA,QAAQ,UAAU;QAC3B,OAAOA;IACT,EAAE,mDAAmD;IAErD,IAAI,eAAeI,IAAI,CAACJ,MAAM;QAC5BA,MAAMA,IAAIK,KAAK,CAAC,GAAG,CAAC;IACtB;IAEA,IAAIJ,QAAQK,IAAI,EAAE;QAChBN,OAAOC,QAAQK,IAAI;IACrB,EAAE,yBAAyB;IAC3B,kDAAkD;IAElD,IAAI,cAAcF,IAAI,CAACJ,QAAQC,QAAQM,UAAU,EAAE;QACjD,OAAO,IAAIC,MAAM,CAACR,IAAIS,OAAO,CAAC,MAAM,OAAOA,OAAO,CAAC,OAAO,QAAQ;IACpE;IAEA,OAAOT;AACT","ignoreList":[0]}
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
/*
|
||||
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';
|
||||
import { normalizePath } from '../../../../../lib/normalize-path';
|
||||
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;
|
||||
// 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) : String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
|
||||
});
|
||||
}
|
||||
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.startsWith('<')) {
|
||||
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.startsWith('<')) {
|
||||
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 item of replacements){
|
||||
const { replacementName, importName, localName } = item;
|
||||
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 } = item;
|
||||
const getUrlOptions = [
|
||||
...hash ? [
|
||||
`hash: ${JSON.stringify(hash)}`
|
||||
] : [],
|
||||
...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, value } of exports){
|
||||
switch(options.modules.exportLocalsConvention){
|
||||
case 'camelCase':
|
||||
{
|
||||
addExportToLocalsCode(name, value);
|
||||
const modifiedName = camelCase(name);
|
||||
if (modifiedName !== name) {
|
||||
addExportToLocalsCode(modifiedName, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'camelCaseOnly':
|
||||
{
|
||||
addExportToLocalsCode(camelCase(name), value);
|
||||
break;
|
||||
}
|
||||
case 'dashes':
|
||||
{
|
||||
addExportToLocalsCode(name, value);
|
||||
const modifiedName = dashesCamelCase(name);
|
||||
if (modifiedName !== name) {
|
||||
addExportToLocalsCode(modifiedName, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'dashesOnly':
|
||||
{
|
||||
addExportToLocalsCode(dashesCamelCase(name), value);
|
||||
break;
|
||||
}
|
||||
case 'asIs':
|
||||
default:
|
||||
addExportToLocalsCode(name, value);
|
||||
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, // For lightningcss-loader
|
||||
normalizeSourceMapForRuntime, dashesCamelCase, };
|
||||
|
||||
//# sourceMappingURL=utils.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+128
@@ -0,0 +1,128 @@
|
||||
/* @ts-check */ /**
|
||||
* Style injection mechanism for Next.js devtools with shadow DOM support
|
||||
* Handles caching of style elements when the nextjs-portal shadow root is not available
|
||||
*/ // Global cache for style elements when shadow root is not available
|
||||
if (typeof window !== 'undefined') {
|
||||
window._nextjsDevtoolsStyleCache = window._nextjsDevtoolsStyleCache || {
|
||||
pendingElements: [],
|
||||
isObserving: false,
|
||||
lastInsertedElement: null,
|
||||
cachedShadowRoot: null
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @returns {ShadowRoot | null}
|
||||
*/ function getShadowRoot() {
|
||||
const cache = window._nextjsDevtoolsStyleCache;
|
||||
// Return cached shadow root if available
|
||||
if (cache.cachedShadowRoot) {
|
||||
return cache.cachedShadowRoot;
|
||||
}
|
||||
// Query the DOM and cache the result if found
|
||||
const portal = document.querySelector('nextjs-portal');
|
||||
const shadowRoot = (portal == null ? void 0 : portal.shadowRoot) || null;
|
||||
if (shadowRoot) {
|
||||
cache.cachedShadowRoot = shadowRoot;
|
||||
}
|
||||
return shadowRoot;
|
||||
}
|
||||
/**
|
||||
* @param {HTMLElement} element
|
||||
* @param {ShadowRoot} shadowRoot
|
||||
*/ function insertElementIntoShadowRoot(element, shadowRoot) {
|
||||
const cache = window._nextjsDevtoolsStyleCache;
|
||||
if (!cache.lastInsertedElement) {
|
||||
shadowRoot.insertBefore(element, shadowRoot.firstChild);
|
||||
} else if (cache.lastInsertedElement.nextSibling) {
|
||||
shadowRoot.insertBefore(element, cache.lastInsertedElement.nextSibling);
|
||||
} else {
|
||||
shadowRoot.appendChild(element);
|
||||
}
|
||||
cache.lastInsertedElement = element;
|
||||
}
|
||||
function flushCachedElements() {
|
||||
const cache = window._nextjsDevtoolsStyleCache;
|
||||
const shadowRoot = getShadowRoot();
|
||||
if (!shadowRoot) {
|
||||
return;
|
||||
}
|
||||
cache.pendingElements.forEach((element)=>{
|
||||
insertElementIntoShadowRoot(element, shadowRoot);
|
||||
});
|
||||
cache.pendingElements = [];
|
||||
}
|
||||
function startObservingForPortal() {
|
||||
const cache = window._nextjsDevtoolsStyleCache;
|
||||
if (cache.isObserving) {
|
||||
return;
|
||||
}
|
||||
cache.isObserving = true;
|
||||
// First check if the portal already exists
|
||||
const shadowRoot = getShadowRoot() // This will cache it if found
|
||||
;
|
||||
if (shadowRoot) {
|
||||
flushCachedElements();
|
||||
return;
|
||||
}
|
||||
// Set up MutationObserver to watch for the portal element
|
||||
const observer = new MutationObserver((mutations)=>{
|
||||
if (mutations.length === 0) {
|
||||
return;
|
||||
}
|
||||
// Check all mutations and all added nodes
|
||||
for (const mutation of mutations){
|
||||
if (mutation.addedNodes.length === 0) continue;
|
||||
for (const addedNode of mutation.addedNodes){
|
||||
if (addedNode.nodeType !== Node.ELEMENT_NODE) continue;
|
||||
const mutationNode = addedNode;
|
||||
let portalNode = null;
|
||||
if (// app router: body > script[data-nextjs-dev-overlay] > nextjs-portal
|
||||
mutationNode.tagName === 'SCRIPT' && mutationNode.getAttribute('data-nextjs-dev-overlay')) {
|
||||
portalNode = mutationNode.firstChild;
|
||||
} else if (// pages router: body > nextjs-portal
|
||||
mutationNode.tagName === 'NEXTJS-PORTAL') {
|
||||
portalNode = mutationNode;
|
||||
}
|
||||
if (portalNode) {
|
||||
// Wait until shadow root is available
|
||||
const checkShadowRoot = ()=>{
|
||||
if (getShadowRoot()) {
|
||||
flushCachedElements();
|
||||
observer.disconnect();
|
||||
cache.isObserving = false;
|
||||
} else {
|
||||
// Try again after a short delay
|
||||
setTimeout(checkShadowRoot, 20);
|
||||
}
|
||||
};
|
||||
checkShadowRoot();
|
||||
return; // Exit early once we find a portal
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @param {HTMLElement} element
|
||||
*/ function insertAtTop(element) {
|
||||
// Add special recognizable data prop to element
|
||||
element.setAttribute('data-nextjs-dev-tool-style', 'true');
|
||||
const shadowRoot = getShadowRoot();
|
||||
if (shadowRoot) {
|
||||
// Shadow root is available, insert directly
|
||||
insertElementIntoShadowRoot(element, shadowRoot);
|
||||
} else {
|
||||
// Shadow root not available, cache the element
|
||||
const cache = window._nextjsDevtoolsStyleCache;
|
||||
cache.pendingElements.push(element);
|
||||
// Start observing for the portal if not already observing
|
||||
startObservingForPortal();
|
||||
}
|
||||
}
|
||||
module.exports = insertAtTop;
|
||||
|
||||
//# sourceMappingURL=devtool-style-inject.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+4
@@ -0,0 +1,4 @@
|
||||
const EmptyLoader = ()=>'export default {}';
|
||||
export default EmptyLoader;
|
||||
|
||||
//# sourceMappingURL=empty-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/empty-loader.ts"],"sourcesContent":["import type { webpack } from 'next/dist/compiled/webpack/webpack'\n\nconst EmptyLoader: webpack.LoaderDefinitionFunction = () => 'export default {}'\nexport default EmptyLoader\n"],"names":["EmptyLoader"],"mappings":"AAEA,MAAMA,cAAgD,IAAM;AAC5D,eAAeA,YAAW","ignoreList":[0]}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { cyan } from '../../../lib/picocolors';
|
||||
import path from 'path';
|
||||
const ErrorLoader = function() {
|
||||
var _this__module_issuer, _this__module, _this__compiler;
|
||||
// @ts-ignore exists
|
||||
const options = this.getOptions() || {};
|
||||
const { reason = 'An unknown error has occurred' } = options;
|
||||
// @ts-expect-error
|
||||
const resource = ((_this__module = this._module) == null ? void 0 : (_this__module_issuer = _this__module.issuer) == null ? void 0 : _this__module_issuer.resource) ?? null;
|
||||
const context = this.rootContext ?? ((_this__compiler = this._compiler) == null ? void 0 : _this__compiler.context);
|
||||
const issuer = resource ? context ? path.relative(context, resource) : resource : null;
|
||||
const err = Object.defineProperty(new Error(reason + (issuer ? `\nLocation: ${cyan(issuer)}` : '')), "__NEXT_ERROR_CODE", {
|
||||
value: "E339",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
this.emitError(err);
|
||||
};
|
||||
export default ErrorLoader;
|
||||
|
||||
//# sourceMappingURL=error-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/error-loader.ts"],"sourcesContent":["import { cyan } from '../../../lib/picocolors'\nimport path from 'path'\nimport type { webpack } from 'next/dist/compiled/webpack/webpack'\n\nconst ErrorLoader: webpack.LoaderDefinitionFunction = function () {\n // @ts-ignore exists\n const options = this.getOptions() || ({} as any)\n\n const { reason = 'An unknown error has occurred' } = options\n\n // @ts-expect-error\n const resource = this._module?.issuer?.resource ?? null\n const context = this.rootContext ?? this._compiler?.context\n\n const issuer = resource\n ? context\n ? path.relative(context, resource)\n : resource\n : null\n\n const err = new Error(reason + (issuer ? `\\nLocation: ${cyan(issuer)}` : ''))\n this.emitError(err)\n}\n\nexport default ErrorLoader\n"],"names":["cyan","path","ErrorLoader","options","getOptions","reason","resource","_module","issuer","context","rootContext","_compiler","relative","err","Error","emitError"],"mappings":"AAAA,SAASA,IAAI,QAAQ,0BAAyB;AAC9C,OAAOC,UAAU,OAAM;AAGvB,MAAMC,cAAgD;QAOnC,sBAAA,eACmB;IAPpC,oBAAoB;IACpB,MAAMC,UAAU,IAAI,CAACC,UAAU,MAAO,CAAC;IAEvC,MAAM,EAAEC,SAAS,+BAA+B,EAAE,GAAGF;IAErD,mBAAmB;IACnB,MAAMG,WAAW,EAAA,gBAAA,IAAI,CAACC,OAAO,sBAAZ,uBAAA,cAAcC,MAAM,qBAApB,qBAAsBF,QAAQ,KAAI;IACnD,MAAMG,UAAU,IAAI,CAACC,WAAW,MAAI,kBAAA,IAAI,CAACC,SAAS,qBAAd,gBAAgBF,OAAO;IAE3D,MAAMD,SAASF,WACXG,UACER,KAAKW,QAAQ,CAACH,SAASH,YACvBA,WACF;IAEJ,MAAMO,MAAM,qBAAiE,CAAjE,IAAIC,MAAMT,SAAUG,CAAAA,SAAS,CAAC,YAAY,EAAER,KAAKQ,SAAS,GAAG,EAAC,IAA9D,qBAAA;eAAA;oBAAA;sBAAA;IAAgE;IAC5E,IAAI,CAACO,SAAS,CAACF;AACjB;AAEA,eAAeX,YAAW","ignoreList":[0]}
|
||||
+8
@@ -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
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/get-module-build-info.ts"],"sourcesContent":["import type {\n ProxyConfig,\n ProxyMatcher,\n RSCModuleType,\n} from '../../analysis/get-page-static-info'\nimport type { webpack } from 'next/dist/compiled/webpack/webpack'\n\nexport type ModuleBuildInfo = {\n nextEdgeMiddleware?: EdgeMiddlewareMeta\n nextEdgeApiFunction?: EdgeMiddlewareMeta\n nextEdgeSSR?: EdgeSSRMeta\n nextWasmMiddlewareBinding?: AssetBinding\n nextAssetMiddlewareBinding?: AssetBinding\n usingIndirectEval?: boolean | Set<string>\n route?: RouteMeta\n importLocByPath?: Map<string, any>\n rootDir?: string\n rsc?: RSCMeta\n}\n\n/**\n * A getter for module build info that casts to the type it should have.\n * We also expose here types to make easier to use it.\n */\nexport function getModuleBuildInfo(webpackModule: webpack.Module) {\n return webpackModule.buildInfo as ModuleBuildInfo\n}\n\n/**\n * Location info for a server action (1-indexed line and column)\n */\nexport interface ServerActionLocation {\n line: number\n col: number\n}\n\n/**\n * Server action info including name and optional source location\n */\nexport interface ServerActionInfo {\n name: string\n loc?: ServerActionLocation\n}\n\nexport interface RSCMeta {\n type: RSCModuleType\n /** Map of action ID to export name (old format) or action info (new format with location) */\n actionIds?: Record<string, string | ServerActionInfo>\n clientRefs?: string[]\n clientEntryType?: 'cjs' | 'auto'\n isClientRef?: boolean\n requests?: string[] // client requests in flight client entry\n}\n\nexport interface RouteMeta {\n page: string\n absolutePagePath: string\n preferredRegion: string | string[] | undefined\n middlewareConfig: ProxyConfig\n // references to other modules that this route needs\n // e.g. related routes, not-found routes, etc\n relatedModules?: string[]\n}\n\nexport interface EdgeMiddlewareMeta {\n page: string\n matchers?: ProxyMatcher[]\n}\n\nexport interface EdgeSSRMeta {\n isServerComponent: boolean\n isAppDir?: boolean\n page: string\n}\n\nexport interface AssetBinding {\n filePath: string\n name: string\n}\n"],"names":["getModuleBuildInfo","webpackModule","buildInfo"],"mappings":"AAoBA;;;CAGC,GACD,OAAO,SAASA,mBAAmBC,aAA6B;IAC9D,OAAOA,cAAcC,SAAS;AAChC","ignoreList":[0]}
|
||||
Generated
Vendored
+125
@@ -0,0 +1,125 @@
|
||||
import camelCase from '../../css-loader/src/camelcase';
|
||||
import { dashesCamelCase, normalizeSourceMapForRuntime } from '../../css-loader/src/utils';
|
||||
export 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}` : '';
|
||||
}
|
||||
export 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 item of replacements){
|
||||
const { replacementName, importName, localName } = item;
|
||||
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 } = item;
|
||||
const getUrlOptions = [
|
||||
...hash ? [
|
||||
`hash: ${JSON.stringify(hash)}`
|
||||
] : [],
|
||||
...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`;
|
||||
}
|
||||
export 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, value } of exports){
|
||||
switch(options.modules.exportLocalsConvention){
|
||||
case 'camelCase':
|
||||
{
|
||||
addExportToLocalsCode(name, value);
|
||||
const modifiedName = camelCase(name);
|
||||
if (modifiedName !== name) {
|
||||
addExportToLocalsCode(modifiedName, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'camelCaseOnly':
|
||||
{
|
||||
addExportToLocalsCode(camelCase(name), value);
|
||||
break;
|
||||
}
|
||||
case 'dashes':
|
||||
{
|
||||
addExportToLocalsCode(name, value);
|
||||
const modifiedName = dashesCamelCase(name);
|
||||
if (modifiedName !== name) {
|
||||
addExportToLocalsCode(modifiedName, value);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'dashesOnly':
|
||||
{
|
||||
addExportToLocalsCode(dashesCamelCase(name), value);
|
||||
break;
|
||||
}
|
||||
case 'asIs':
|
||||
default:
|
||||
addExportToLocalsCode(name, value);
|
||||
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;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=codegen.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
import { LightningCssLoader } from './loader';
|
||||
export { LightningCssMinifyPlugin } from './minify';
|
||||
export default LightningCssLoader;
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/lightningcss-loader/src/index.ts"],"sourcesContent":["import { LightningCssLoader } from './loader'\n\nexport { LightningCssMinifyPlugin } from './minify'\nexport default LightningCssLoader\n"],"names":["LightningCssLoader","LightningCssMinifyPlugin"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,WAAU;AAE7C,SAASC,wBAAwB,QAAQ,WAAU;AACnD,eAAeD,mBAAkB","ignoreList":[0]}
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
export var ECacheKey = /*#__PURE__*/ function(ECacheKey) {
|
||||
ECacheKey["loader"] = "loader";
|
||||
ECacheKey["minify"] = "minify";
|
||||
return ECacheKey;
|
||||
}({});
|
||||
|
||||
//# sourceMappingURL=interface.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/lightningcss-loader/src/interface.ts"],"sourcesContent":["export enum ECacheKey {\n loader = 'loader',\n minify = 'minify',\n}\n"],"names":["ECacheKey"],"mappings":"AAAA,OAAO,IAAA,AAAKA,mCAAAA;;;WAAAA;MAGX","ignoreList":[0]}
|
||||
Generated
Vendored
+416
@@ -0,0 +1,416 @@
|
||||
import { getTargets } from './utils';
|
||||
import { getImportCode, getModuleCode, getExportCode } from './codegen';
|
||||
import { getFilter, getPreRequester, isDataUrl, isUrlRequestable, requestify, resolveRequests } from '../../css-loader/src/utils';
|
||||
import { stringifyRequest } from '../../../stringify-request';
|
||||
import { ECacheKey } from './interface';
|
||||
import { getBindingsSync } from '../../../../../build/swc';
|
||||
import { installBindings } from '../../../../../build/swc/install-bindings';
|
||||
const encoder = new TextEncoder();
|
||||
function createUrlAndImportVisitor(visitorOptions, apis, imports, replacements, replacedUrls, replacedImportUrls) {
|
||||
const importUrlToNameMap = new Map();
|
||||
let hasUrlImportHelper = false;
|
||||
const urlToNameMap = new Map();
|
||||
const urlToReplacementMap = new Map();
|
||||
let urlIndex = -1;
|
||||
let importUrlIndex = -1;
|
||||
function handleUrl(u) {
|
||||
let url = u.url;
|
||||
const needKeep = visitorOptions.urlFilter(url);
|
||||
if (!needKeep) {
|
||||
return u;
|
||||
}
|
||||
if (isDataUrl(url)) {
|
||||
return u;
|
||||
}
|
||||
urlIndex++;
|
||||
replacedUrls.set(urlIndex, url);
|
||||
url = `__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${urlIndex}__`;
|
||||
const [, query, hashOrQuery] = url.split(/(\?)?#/, 3);
|
||||
const queryParts = url.split('!');
|
||||
let prefix;
|
||||
if (queryParts.length > 1) {
|
||||
url = queryParts.pop();
|
||||
prefix = queryParts.join('!');
|
||||
}
|
||||
let hash = query ? '?' : '';
|
||||
hash += hashOrQuery ? `#${hashOrQuery}` : '';
|
||||
if (!hasUrlImportHelper) {
|
||||
imports.push({
|
||||
type: 'get_url_import',
|
||||
importName: '___CSS_LOADER_GET_URL_IMPORT___',
|
||||
url: JSON.stringify(require.resolve('../../css-loader/src/runtime/getUrl.js')),
|
||||
index: -1
|
||||
});
|
||||
hasUrlImportHelper = true;
|
||||
}
|
||||
const newUrl = prefix ? `${prefix}!${url}` : url;
|
||||
let importName = urlToNameMap.get(newUrl);
|
||||
if (!importName) {
|
||||
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
|
||||
urlToNameMap.set(newUrl, importName);
|
||||
imports.push({
|
||||
type: 'url',
|
||||
importName,
|
||||
url: JSON.stringify(newUrl),
|
||||
index: urlIndex
|
||||
});
|
||||
}
|
||||
// This should be true for string-urls in image-set
|
||||
const needQuotes = false;
|
||||
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);
|
||||
replacements.push({
|
||||
replacementName,
|
||||
importName,
|
||||
hash,
|
||||
needQuotes
|
||||
});
|
||||
}
|
||||
return {
|
||||
loc: u.loc,
|
||||
url: replacementName
|
||||
};
|
||||
}
|
||||
return {
|
||||
Rule: {
|
||||
import (node) {
|
||||
if (visitorOptions.importFilter) {
|
||||
const needKeep = visitorOptions.importFilter(node.value.url, node.value.media);
|
||||
if (!needKeep) {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
let url = node.value.url;
|
||||
importUrlIndex++;
|
||||
replacedImportUrls.set(importUrlIndex, url);
|
||||
url = `__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${importUrlIndex}__`;
|
||||
// TODO: Use identical logic as valueParser.stringify()
|
||||
const media = node.value.media.mediaQueries.length ? JSON.stringify(node.value.media.mediaQueries) : undefined;
|
||||
const isRequestable = isUrlRequestable(url);
|
||||
let prefix;
|
||||
if (isRequestable) {
|
||||
const queryParts = url.split('!');
|
||||
if (queryParts.length > 1) {
|
||||
url = queryParts.pop();
|
||||
prefix = queryParts.join('!');
|
||||
}
|
||||
}
|
||||
if (!isRequestable) {
|
||||
apis.push({
|
||||
url,
|
||||
media
|
||||
});
|
||||
// Bug of lightningcss
|
||||
return {
|
||||
type: 'ignored',
|
||||
value: ''
|
||||
};
|
||||
}
|
||||
const newUrl = prefix ? `${prefix}!${url}` : url;
|
||||
let importName = importUrlToNameMap.get(newUrl);
|
||||
if (!importName) {
|
||||
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importUrlToNameMap.size}___`;
|
||||
importUrlToNameMap.set(newUrl, importName);
|
||||
const importUrl = visitorOptions.urlHandler(newUrl);
|
||||
imports.push({
|
||||
type: 'rule_import',
|
||||
importName,
|
||||
url: importUrl
|
||||
});
|
||||
}
|
||||
apis.push({
|
||||
importName,
|
||||
media
|
||||
});
|
||||
// Bug of lightningcss
|
||||
return {
|
||||
type: 'ignored',
|
||||
value: ''
|
||||
};
|
||||
}
|
||||
},
|
||||
Url (node) {
|
||||
return handleUrl(node);
|
||||
}
|
||||
};
|
||||
}
|
||||
function createIcssVisitor({ apis, imports, replacements, replacedUrls, urlHandler }) {
|
||||
let index = -1;
|
||||
let replacementIndex = -1;
|
||||
return {
|
||||
Declaration: {
|
||||
composes (node) {
|
||||
if (node.property === 'unparsed') {
|
||||
return;
|
||||
}
|
||||
const specifier = node.value.from;
|
||||
if ((specifier == null ? void 0 : specifier.type) !== 'file') {
|
||||
return;
|
||||
}
|
||||
let url = specifier.value;
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
index++;
|
||||
replacedUrls.set(index, url);
|
||||
url = `__NEXT_LIGHTNINGCSS_LOADER_ICSS_URL_REPLACE_${index}__`;
|
||||
const importName = `___CSS_LOADER_ICSS_IMPORT_${imports.length}___`;
|
||||
imports.push({
|
||||
type: 'icss_import',
|
||||
importName,
|
||||
icss: true,
|
||||
url: urlHandler(url),
|
||||
index
|
||||
});
|
||||
apis.push({
|
||||
importName,
|
||||
dedupe: true,
|
||||
index
|
||||
});
|
||||
const newNames = [];
|
||||
for (const localName of node.value.names){
|
||||
replacementIndex++;
|
||||
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
|
||||
replacements.push({
|
||||
replacementName,
|
||||
importName,
|
||||
localName
|
||||
});
|
||||
newNames.push(replacementName);
|
||||
}
|
||||
return {
|
||||
property: 'composes',
|
||||
value: {
|
||||
loc: node.value.loc,
|
||||
names: newNames,
|
||||
from: specifier
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
const LOADER_NAME = `lightningcss-loader`;
|
||||
export async function LightningCssLoader(source, prevMap) {
|
||||
var _options_modules, _options_lightningCssFeatures, _options_lightningCssFeatures1;
|
||||
const done = this.async();
|
||||
const options = this.getOptions();
|
||||
// Install bindings early so they are definitely available to the loader.
|
||||
// When run by webpack in next this is already done with correct configuration so this is a no-op.
|
||||
// In turbopack loaders are run in a subprocess so it may or may not be done.
|
||||
await installBindings();
|
||||
const { implementation, targets: userTargets, ...opts } = options;
|
||||
options.modules ??= {};
|
||||
if (implementation && typeof implementation.transformCss !== 'function') {
|
||||
done(Object.defineProperty(new TypeError(`[${LOADER_NAME}]: options.implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E1033",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (options.postcss) {
|
||||
var _postcssWithPlugins_plugins;
|
||||
const { postcssWithPlugins } = await options.postcss();
|
||||
if ((postcssWithPlugins == null ? void 0 : (_postcssWithPlugins_plugins = postcssWithPlugins.plugins) == null ? void 0 : _postcssWithPlugins_plugins.length) > 0) {
|
||||
throw Object.defineProperty(new Error(`[${LOADER_NAME}]: experimental.useLightningcss does not work with postcss plugins. Please remove 'useLightningcss: true' from your configuration.`), "__NEXT_ERROR_CODE", {
|
||||
value: "E999",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
const exports = [];
|
||||
const imports = [];
|
||||
const icssImports = [];
|
||||
const apis = [];
|
||||
const replacements = [];
|
||||
if (((_options_modules = options.modules) == null ? void 0 : _options_modules.exportOnlyLocals) !== true) {
|
||||
imports.unshift({
|
||||
type: 'api_import',
|
||||
importName: '___CSS_LOADER_API_IMPORT___',
|
||||
url: stringifyRequest(this, require.resolve('../../css-loader/src/runtime/api'))
|
||||
});
|
||||
}
|
||||
const transform = (implementation == null ? void 0 : implementation.transformCss) ?? getBindingsSync().css.lightning.transform;
|
||||
const replacedUrls = new Map();
|
||||
const icssReplacedUrls = new Map();
|
||||
const replacedImportUrls = new Map();
|
||||
const urlImportVisitor = createUrlAndImportVisitor({
|
||||
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders ?? 0) + url),
|
||||
urlFilter: getFilter(options.url, this.resourcePath),
|
||||
importFilter: getFilter(options.import, this.resourcePath),
|
||||
context: this.context
|
||||
}, apis, imports, replacements, replacedUrls, replacedImportUrls);
|
||||
const icssVisitor = createIcssVisitor({
|
||||
apis,
|
||||
imports: icssImports,
|
||||
replacements,
|
||||
replacedUrls: icssReplacedUrls,
|
||||
urlHandler: (url)=>stringifyRequest(this, getPreRequester(this)(options.importLoaders) + url)
|
||||
});
|
||||
// This works by returned visitors are not conflicting.
|
||||
// naive workaround for composeVisitors, as we do not directly depends on lightningcss's npm pkg
|
||||
// but next-swc provides bindings
|
||||
const visitor = {
|
||||
...urlImportVisitor,
|
||||
...icssVisitor
|
||||
};
|
||||
// Compute feature include/exclude masks from user config.
|
||||
// Default: always transpile nesting (bit 0). User `include` adds flags,
|
||||
// user `exclude` removes them from both include and exclude masks.
|
||||
const featureNamesToMask = getBindingsSync().css.lightning.featureNamesToMask;
|
||||
const userIncludeMask = ((_options_lightningCssFeatures = options.lightningCssFeatures) == null ? void 0 : _options_lightningCssFeatures.include) ? featureNamesToMask(options.lightningCssFeatures.include) : 0;
|
||||
const userExcludeMask = ((_options_lightningCssFeatures1 = options.lightningCssFeatures) == null ? void 0 : _options_lightningCssFeatures1.exclude) ? featureNamesToMask(options.lightningCssFeatures.exclude) : 0;
|
||||
const includeMask = (1 | userIncludeMask) & ~userExcludeMask // 1 = Features.Nesting
|
||||
;
|
||||
try {
|
||||
const { code, map, exports: moduleExports } = transform({
|
||||
...opts,
|
||||
visitor,
|
||||
cssModules: options.modules ? {
|
||||
pattern: process.env.__NEXT_TEST_MODE ? '[name]__[local]' : '[name]__[hash]__[local]'
|
||||
} : undefined,
|
||||
filename: this.resourcePath,
|
||||
code: encoder.encode(source),
|
||||
sourceMap: this.sourceMap,
|
||||
targets: getTargets({
|
||||
targets: userTargets,
|
||||
key: ECacheKey.loader
|
||||
}),
|
||||
inputSourceMap: this.sourceMap && prevMap ? JSON.stringify(prevMap) : undefined,
|
||||
include: includeMask,
|
||||
exclude: userExcludeMask
|
||||
});
|
||||
let cssCodeAsString = code.toString();
|
||||
if (moduleExports) {
|
||||
for(const name in moduleExports){
|
||||
if (Object.prototype.hasOwnProperty.call(moduleExports, name)) {
|
||||
const v = moduleExports[name];
|
||||
let value = v.name;
|
||||
for (const compose of v.composes){
|
||||
value += ` ${compose.name}`;
|
||||
}
|
||||
exports.push({
|
||||
name,
|
||||
value
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (replacedUrls.size !== 0) {
|
||||
const urlResolver = this.getResolve({
|
||||
conditionNames: [
|
||||
'asset'
|
||||
],
|
||||
mainFields: [
|
||||
'asset'
|
||||
],
|
||||
mainFiles: [],
|
||||
extensions: []
|
||||
});
|
||||
for (const [index, url] of replacedUrls.entries()){
|
||||
const [pathname, , ] = url.split(/(\?)?#/, 3);
|
||||
const request = requestify(pathname, this.rootContext);
|
||||
const resolvedUrl = await resolveRequests(urlResolver, this.context, [
|
||||
...new Set([
|
||||
request,
|
||||
url
|
||||
])
|
||||
]);
|
||||
for (const importItem of imports){
|
||||
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_URL_REPLACE_${index}__`, resolvedUrl ?? url);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (replacedImportUrls.size !== 0) {
|
||||
const importResolver = this.getResolve({
|
||||
conditionNames: [
|
||||
'style'
|
||||
],
|
||||
extensions: [
|
||||
'.css'
|
||||
],
|
||||
mainFields: [
|
||||
'css',
|
||||
'style',
|
||||
'main',
|
||||
'...'
|
||||
],
|
||||
mainFiles: [
|
||||
'index',
|
||||
'...'
|
||||
],
|
||||
restrictions: [
|
||||
/\.css$/i
|
||||
]
|
||||
});
|
||||
for (const [index, url] of replacedImportUrls.entries()){
|
||||
const [pathname, , ] = url.split(/(\?)?#/, 3);
|
||||
const request = requestify(pathname, this.rootContext);
|
||||
const resolvedUrl = await resolveRequests(importResolver, this.context, [
|
||||
...new Set([
|
||||
request,
|
||||
url
|
||||
])
|
||||
]);
|
||||
for (const importItem of imports){
|
||||
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_IMPORT_URL_REPLACE_${index}__`, resolvedUrl ?? url);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (icssReplacedUrls.size !== 0) {
|
||||
const icssResolver = this.getResolve({
|
||||
conditionNames: [
|
||||
'style'
|
||||
],
|
||||
extensions: [],
|
||||
mainFields: [
|
||||
'css',
|
||||
'style',
|
||||
'main',
|
||||
'...'
|
||||
],
|
||||
mainFiles: [
|
||||
'index',
|
||||
'...'
|
||||
]
|
||||
});
|
||||
for (const [index, url] of icssReplacedUrls.entries()){
|
||||
const [pathname, , ] = url.split(/(\?)?#/, 3);
|
||||
const request = requestify(pathname, this.rootContext);
|
||||
const resolvedUrl = await resolveRequests(icssResolver, this.context, [
|
||||
...new Set([
|
||||
url,
|
||||
request
|
||||
])
|
||||
]);
|
||||
for (const importItem of icssImports){
|
||||
importItem.url = importItem.url.replace(`__NEXT_LIGHTNINGCSS_LOADER_ICSS_URL_REPLACE_${index}__`, resolvedUrl ?? url);
|
||||
}
|
||||
}
|
||||
}
|
||||
imports.push(...icssImports);
|
||||
const importCode = getImportCode(imports, options);
|
||||
const moduleCode = getModuleCode({
|
||||
css: cssCodeAsString,
|
||||
map
|
||||
}, apis, replacements, options, this);
|
||||
const exportCode = getExportCode(exports, replacements, options);
|
||||
const esCode = `${importCode}${moduleCode}${exportCode}`;
|
||||
done(null, esCode, map && JSON.parse(map.toString()));
|
||||
} catch (error) {
|
||||
console.error('lightningcss-loader error', error);
|
||||
done(error);
|
||||
}
|
||||
}
|
||||
export const raw = true;
|
||||
|
||||
//# sourceMappingURL=loader.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+86
@@ -0,0 +1,86 @@
|
||||
// @ts-ignore
|
||||
import { ModuleFilenameHelpers } from 'next/dist/compiled/webpack/webpack';
|
||||
import { webpack } from 'next/dist/compiled/webpack/webpack';
|
||||
// @ts-ignore
|
||||
import { RawSource, SourceMapSource } from 'next/dist/compiled/webpack-sources3';
|
||||
import { ECacheKey } from './interface';
|
||||
import { getTargets } from './utils';
|
||||
import { Buffer } from 'buffer';
|
||||
import { getBindingsSync } from '../../../../../build/swc';
|
||||
const PLUGIN_NAME = 'lightning-css-minify';
|
||||
const CSS_FILE_REG = /\.css(?:\?.*)?$/i;
|
||||
export class LightningCssMinifyPlugin {
|
||||
constructor(opts = {}){
|
||||
const { implementation, ...otherOpts } = opts;
|
||||
if (implementation && typeof implementation.transformCss !== 'function') {
|
||||
throw Object.defineProperty(new TypeError(`[LightningCssMinifyPlugin]: implementation.transformCss must be an 'lightningcss' transform function. Received ${typeof implementation.transformCss}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E561",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
this.transform = implementation == null ? void 0 : implementation.transformCss;
|
||||
this.options = otherOpts;
|
||||
}
|
||||
apply(compiler) {
|
||||
const meta = JSON.stringify({
|
||||
name: '@next/lightningcss-loader',
|
||||
version: '0.0.0',
|
||||
options: this.options
|
||||
});
|
||||
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation)=>{
|
||||
compilation.hooks.chunkHash.tap(PLUGIN_NAME, (_, hash)=>hash.update(meta));
|
||||
compilation.hooks.processAssets.tapPromise({
|
||||
name: PLUGIN_NAME,
|
||||
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
|
||||
additionalAssets: true
|
||||
}, async ()=>await this.transformAssets(compilation));
|
||||
compilation.hooks.statsPrinter.tap(PLUGIN_NAME, (statsPrinter)=>{
|
||||
statsPrinter.hooks.print.for('asset.info.minimized')// @ts-ignore
|
||||
.tap(PLUGIN_NAME, (minimized, { green, formatFlag })=>{
|
||||
// @ts-ignore
|
||||
return minimized ? green(formatFlag('minimized')) : undefined;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
async transformAssets(compilation) {
|
||||
const { options: { devtool } } = compilation.compiler;
|
||||
if (!this.transform) {
|
||||
this.transform = getBindingsSync().css.lightning.transform;
|
||||
}
|
||||
const sourcemap = this.options.sourceMap === undefined ? devtool && devtool.includes('source-map') : this.options.sourceMap;
|
||||
const { include, exclude, test: testRegExp, targets: userTargets, ...transformOptions } = this.options;
|
||||
const assets = compilation.getAssets().filter((asset)=>// Filter out already minimized
|
||||
!asset.info.minimized && // Filter out by file type
|
||||
(testRegExp || CSS_FILE_REG).test(asset.name) && ModuleFilenameHelpers.matchObject({
|
||||
include,
|
||||
exclude
|
||||
}, asset.name));
|
||||
await Promise.all(assets.map(async (asset)=>{
|
||||
const { source, map } = asset.source.sourceAndMap();
|
||||
const sourceAsString = source.toString();
|
||||
const code = typeof source === 'string' ? Buffer.from(source) : source;
|
||||
const targets = getTargets({
|
||||
targets: userTargets,
|
||||
key: ECacheKey.minify
|
||||
});
|
||||
const result = await this.transform({
|
||||
filename: asset.name,
|
||||
code,
|
||||
minify: true,
|
||||
sourceMap: sourcemap,
|
||||
targets,
|
||||
...transformOptions
|
||||
});
|
||||
const codeString = result.code.toString();
|
||||
compilation.updateAsset(asset.name, // @ts-ignore
|
||||
sourcemap ? new SourceMapSource(codeString, asset.name, JSON.parse(result.map.toString()), sourceAsString, map, true) : new RawSource(codeString), {
|
||||
...asset.info,
|
||||
minimized: true
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=minify.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
let targetsCache = {};
|
||||
/**
|
||||
* Convert a version number to a single 24-bit number
|
||||
*
|
||||
* https://github.com/lumeland/lume/blob/4cc75599006df423a14befc06d3ed8493c645b09/plugins/lightningcss.ts#L160
|
||||
*/ function version(major, minor = 0, patch = 0) {
|
||||
return major << 16 | minor << 8 | patch;
|
||||
}
|
||||
function parseVersion(v) {
|
||||
return v.split('.').reduce((acc, val)=>{
|
||||
if (!acc) {
|
||||
return null;
|
||||
}
|
||||
const parsed = parseInt(val, 10);
|
||||
if (isNaN(parsed)) {
|
||||
return null;
|
||||
}
|
||||
acc.push(parsed);
|
||||
return acc;
|
||||
}, []);
|
||||
}
|
||||
function browserslistToTargets(targets) {
|
||||
return targets.reduce((acc, value)=>{
|
||||
const [name, v] = value.split(' ');
|
||||
const parsedVersion = parseVersion(v);
|
||||
if (!parsedVersion) {
|
||||
return acc;
|
||||
}
|
||||
const versionDigit = version(parsedVersion[0], parsedVersion[1], parsedVersion[2]);
|
||||
if (name === 'and_qq' || name === 'and_uc' || name === 'baidu' || name === 'bb' || name === 'kaios' || name === 'op_mini') {
|
||||
return acc;
|
||||
}
|
||||
if (acc[name] == null || versionDigit < acc[name]) {
|
||||
acc[name] = versionDigit;
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
export const getTargets = (opts)=>{
|
||||
const cache = targetsCache[opts.key];
|
||||
if (cache) {
|
||||
return cache;
|
||||
}
|
||||
const result = browserslistToTargets(opts.targets ?? []);
|
||||
return targetsCache[opts.key] = result;
|
||||
};
|
||||
|
||||
//# sourceMappingURL=utils.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../../src/build/webpack/loaders/lightningcss-loader/src/utils.ts"],"sourcesContent":["let targetsCache: Record<string, any> = {}\n\n/**\n * Convert a version number to a single 24-bit number\n *\n * https://github.com/lumeland/lume/blob/4cc75599006df423a14befc06d3ed8493c645b09/plugins/lightningcss.ts#L160\n */\nfunction version(major: number, minor = 0, patch = 0): number {\n return (major << 16) | (minor << 8) | patch\n}\n\nfunction parseVersion(v: string) {\n return v.split('.').reduce(\n (acc, val) => {\n if (!acc) {\n return null\n }\n\n const parsed = parseInt(val, 10)\n if (isNaN(parsed)) {\n return null\n }\n acc.push(parsed)\n return acc\n },\n [] as Array<number> | null\n )\n}\n\nfunction browserslistToTargets(targets: Array<string>) {\n return targets.reduce(\n (acc, value) => {\n const [name, v] = value.split(' ')\n const parsedVersion = parseVersion(v)\n\n if (!parsedVersion) {\n return acc\n }\n const versionDigit = version(\n parsedVersion[0],\n parsedVersion[1],\n parsedVersion[2]\n )\n\n if (\n name === 'and_qq' ||\n name === 'and_uc' ||\n name === 'baidu' ||\n name === 'bb' ||\n name === 'kaios' ||\n name === 'op_mini'\n ) {\n return acc\n }\n\n if (acc[name] == null || versionDigit < acc[name]) {\n acc[name] = versionDigit\n }\n\n return acc\n },\n {} as Record<string, number>\n )\n}\n\nexport const getTargets = (opts: { targets?: string[]; key: any }) => {\n const cache = targetsCache[opts.key]\n if (cache) {\n return cache\n }\n\n const result = browserslistToTargets(opts.targets ?? [])\n return (targetsCache[opts.key] = result)\n}\n"],"names":["targetsCache","version","major","minor","patch","parseVersion","v","split","reduce","acc","val","parsed","parseInt","isNaN","push","browserslistToTargets","targets","value","name","parsedVersion","versionDigit","getTargets","opts","cache","key","result"],"mappings":"AAAA,IAAIA,eAAoC,CAAC;AAEzC;;;;CAIC,GACD,SAASC,QAAQC,KAAa,EAAEC,QAAQ,CAAC,EAAEC,QAAQ,CAAC;IAClD,OAAO,AAACF,SAAS,KAAOC,SAAS,IAAKC;AACxC;AAEA,SAASC,aAAaC,CAAS;IAC7B,OAAOA,EAAEC,KAAK,CAAC,KAAKC,MAAM,CACxB,CAACC,KAAKC;QACJ,IAAI,CAACD,KAAK;YACR,OAAO;QACT;QAEA,MAAME,SAASC,SAASF,KAAK;QAC7B,IAAIG,MAAMF,SAAS;YACjB,OAAO;QACT;QACAF,IAAIK,IAAI,CAACH;QACT,OAAOF;IACT,GACA,EAAE;AAEN;AAEA,SAASM,sBAAsBC,OAAsB;IACnD,OAAOA,QAAQR,MAAM,CACnB,CAACC,KAAKQ;QACJ,MAAM,CAACC,MAAMZ,EAAE,GAAGW,MAAMV,KAAK,CAAC;QAC9B,MAAMY,gBAAgBd,aAAaC;QAEnC,IAAI,CAACa,eAAe;YAClB,OAAOV;QACT;QACA,MAAMW,eAAenB,QACnBkB,aAAa,CAAC,EAAE,EAChBA,aAAa,CAAC,EAAE,EAChBA,aAAa,CAAC,EAAE;QAGlB,IACED,SAAS,YACTA,SAAS,YACTA,SAAS,WACTA,SAAS,QACTA,SAAS,WACTA,SAAS,WACT;YACA,OAAOT;QACT;QAEA,IAAIA,GAAG,CAACS,KAAK,IAAI,QAAQE,eAAeX,GAAG,CAACS,KAAK,EAAE;YACjDT,GAAG,CAACS,KAAK,GAAGE;QACd;QAEA,OAAOX;IACT,GACA,CAAC;AAEL;AAEA,OAAO,MAAMY,aAAa,CAACC;IACzB,MAAMC,QAAQvB,YAAY,CAACsB,KAAKE,GAAG,CAAC;IACpC,IAAID,OAAO;QACT,OAAOA;IACT;IAEA,MAAME,SAASV,sBAAsBO,KAAKN,OAAO,IAAI,EAAE;IACvD,OAAQhB,YAAY,CAACsB,KAAKE,GAAG,CAAC,GAAGC;AACnC,EAAC","ignoreList":[0]}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import path from 'path';
|
||||
import { stringify } from 'querystring';
|
||||
import { STATIC_METADATA_IMAGES } from '../../../../lib/metadata/is-metadata-route';
|
||||
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants';
|
||||
const METADATA_TYPE = 'metadata';
|
||||
const NUMERIC_SUFFIX_ARRAY = Array(10).fill(0);
|
||||
// Produce all compositions with filename (icon, apple-icon, etc.) with extensions (png, jpg, etc.)
|
||||
async function enumMetadataFiles(dir, filename, extensions, { metadataResolver, // When set to true, possible filename without extension could: icon, icon0, ..., icon9
|
||||
numericSuffix }) {
|
||||
const collectedFiles = [];
|
||||
// Collect <filename>.<ext>, <filename>[].<ext>
|
||||
const possibleFileNames = [
|
||||
filename
|
||||
].concat(numericSuffix ? NUMERIC_SUFFIX_ARRAY.map((_, index)=>filename + index) : []);
|
||||
for (const name of possibleFileNames){
|
||||
const resolved = await metadataResolver(dir, name, extensions);
|
||||
collectedFiles.push(...resolved);
|
||||
}
|
||||
return collectedFiles;
|
||||
}
|
||||
export async function createStaticMetadataFromRoute(resolvedDir, { segment, metadataResolver, isRootLayoutOrRootPage, pageExtensions, basePath }) {
|
||||
let hasStaticMetadataFiles = false;
|
||||
const staticImagesMetadata = {
|
||||
icon: [],
|
||||
apple: [],
|
||||
twitter: [],
|
||||
openGraph: [],
|
||||
manifest: undefined
|
||||
};
|
||||
async function collectIconModuleIfExists(type) {
|
||||
if (type === 'manifest') {
|
||||
const staticManifestExtension = [
|
||||
'webmanifest',
|
||||
'json'
|
||||
];
|
||||
const manifestFile = await enumMetadataFiles(resolvedDir, 'manifest', staticManifestExtension.concat(pageExtensions), {
|
||||
metadataResolver,
|
||||
numericSuffix: false
|
||||
});
|
||||
if (manifestFile.length > 0) {
|
||||
hasStaticMetadataFiles = true;
|
||||
const { name, ext } = path.parse(manifestFile[0]);
|
||||
const extension = staticManifestExtension.includes(ext.slice(1)) ? ext.slice(1) : 'webmanifest';
|
||||
staticImagesMetadata.manifest = JSON.stringify(`${basePath}/${name}.${extension}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const isFavicon = type === 'favicon';
|
||||
const resolvedMetadataFiles = await enumMetadataFiles(resolvedDir, STATIC_METADATA_IMAGES[type].filename, [
|
||||
...STATIC_METADATA_IMAGES[type].extensions,
|
||||
...isFavicon ? [] : pageExtensions
|
||||
], {
|
||||
metadataResolver,
|
||||
numericSuffix: !isFavicon
|
||||
});
|
||||
resolvedMetadataFiles.sort((a, b)=>a.localeCompare(b)).forEach((filepath)=>{
|
||||
const imageModuleImportSource = `next-metadata-image-loader?${stringify({
|
||||
type,
|
||||
segment,
|
||||
basePath,
|
||||
pageExtensions
|
||||
})}!${filepath}?${WEBPACK_RESOURCE_QUERIES.metadata}`;
|
||||
const imageModule = `(async (props) => (await import(/* webpackMode: "eager" */ ${JSON.stringify(imageModuleImportSource)})).default(props))`;
|
||||
hasStaticMetadataFiles = true;
|
||||
if (type === 'favicon') {
|
||||
staticImagesMetadata.icon.unshift(imageModule);
|
||||
} else {
|
||||
staticImagesMetadata[type].push(imageModule);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Intentionally make these serial to reuse directory access cache.
|
||||
await collectIconModuleIfExists('icon');
|
||||
await collectIconModuleIfExists('apple');
|
||||
await collectIconModuleIfExists('openGraph');
|
||||
await collectIconModuleIfExists('twitter');
|
||||
if (isRootLayoutOrRootPage) {
|
||||
await collectIconModuleIfExists('favicon');
|
||||
await collectIconModuleIfExists('manifest');
|
||||
}
|
||||
return hasStaticMetadataFiles ? staticImagesMetadata : null;
|
||||
}
|
||||
export function createMetadataExportsCode(metadata) {
|
||||
return metadata ? `${METADATA_TYPE}: {
|
||||
icon: [${metadata.icon.join(',')}],
|
||||
apple: [${metadata.apple.join(',')}],
|
||||
openGraph: [${metadata.openGraph.join(',')}],
|
||||
twitter: [${metadata.twitter.join(',')}],
|
||||
manifest: ${metadata.manifest ? metadata.manifest : 'undefined'}
|
||||
}` : '';
|
||||
}
|
||||
|
||||
//# sourceMappingURL=discover.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+144
@@ -0,0 +1,144 @@
|
||||
import { resolveArray } from '../../../../lib/metadata/generate/utils';
|
||||
// convert robots data to txt string
|
||||
export function resolveRobots(data) {
|
||||
let content = '';
|
||||
const rules = Array.isArray(data.rules) ? data.rules : [
|
||||
data.rules
|
||||
];
|
||||
for (const rule of rules){
|
||||
const userAgent = resolveArray(rule.userAgent || [
|
||||
'*'
|
||||
]);
|
||||
for (const agent of userAgent){
|
||||
content += `User-Agent: ${agent}\n`;
|
||||
}
|
||||
if (rule.allow) {
|
||||
const allow = resolveArray(rule.allow);
|
||||
for (const item of allow){
|
||||
content += `Allow: ${item}\n`;
|
||||
}
|
||||
}
|
||||
if (rule.disallow) {
|
||||
const disallow = resolveArray(rule.disallow);
|
||||
for (const item of disallow){
|
||||
content += `Disallow: ${item}\n`;
|
||||
}
|
||||
}
|
||||
if (rule.crawlDelay) {
|
||||
content += `Crawl-delay: ${rule.crawlDelay}\n`;
|
||||
}
|
||||
content += '\n';
|
||||
}
|
||||
if (data.host) {
|
||||
content += `Host: ${data.host}\n`;
|
||||
}
|
||||
if (data.sitemap) {
|
||||
const sitemap = resolveArray(data.sitemap);
|
||||
// TODO-METADATA: support injecting sitemap url into robots.txt
|
||||
sitemap.forEach((item)=>{
|
||||
content += `Sitemap: ${item}\n`;
|
||||
});
|
||||
}
|
||||
return content;
|
||||
}
|
||||
// TODO-METADATA: support multi sitemap files
|
||||
// convert sitemap data to xml string
|
||||
export function resolveSitemap(data) {
|
||||
const hasAlternates = data.some((item)=>Object.keys(item.alternates ?? {}).length > 0);
|
||||
const hasImages = data.some((item)=>{
|
||||
var _item_images;
|
||||
return Boolean((_item_images = item.images) == null ? void 0 : _item_images.length);
|
||||
});
|
||||
const hasVideos = data.some((item)=>{
|
||||
var _item_videos;
|
||||
return Boolean((_item_videos = item.videos) == null ? void 0 : _item_videos.length);
|
||||
});
|
||||
let content = '';
|
||||
content += '<?xml version="1.0" encoding="UTF-8"?>\n';
|
||||
content += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
|
||||
if (hasImages) {
|
||||
content += ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
|
||||
}
|
||||
if (hasVideos) {
|
||||
content += ' xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"';
|
||||
}
|
||||
if (hasAlternates) {
|
||||
content += ' xmlns:xhtml="http://www.w3.org/1999/xhtml">\n';
|
||||
} else {
|
||||
content += '>\n';
|
||||
}
|
||||
for (const item of data){
|
||||
var _item_alternates, _item_images, _item_videos;
|
||||
content += '<url>\n';
|
||||
content += `<loc>${item.url}</loc>\n`;
|
||||
const languages = (_item_alternates = item.alternates) == null ? void 0 : _item_alternates.languages;
|
||||
if (languages && Object.keys(languages).length) {
|
||||
// Since sitemap is separated from the page rendering, there's not metadataBase accessible yet.
|
||||
// we give the default setting that won't effect the languages resolving.
|
||||
for(const language in languages){
|
||||
content += `<xhtml:link rel="alternate" hreflang="${language}" href="${languages[language]}" />\n`;
|
||||
}
|
||||
}
|
||||
if ((_item_images = item.images) == null ? void 0 : _item_images.length) {
|
||||
for (const image of item.images){
|
||||
content += `<image:image>\n<image:loc>${image}</image:loc>\n</image:image>\n`;
|
||||
}
|
||||
}
|
||||
if ((_item_videos = item.videos) == null ? void 0 : _item_videos.length) {
|
||||
for (const video of item.videos){
|
||||
let videoFields = [
|
||||
`<video:video>`,
|
||||
`<video:title>${video.title}</video:title>`,
|
||||
`<video:thumbnail_loc>${video.thumbnail_loc}</video:thumbnail_loc>`,
|
||||
`<video:description>${video.description}</video:description>`,
|
||||
video.content_loc && `<video:content_loc>${video.content_loc}</video:content_loc>`,
|
||||
video.player_loc && `<video:player_loc>${video.player_loc}</video:player_loc>`,
|
||||
video.duration && `<video:duration>${video.duration}</video:duration>`,
|
||||
video.view_count && `<video:view_count>${video.view_count}</video:view_count>`,
|
||||
video.tag && `<video:tag>${video.tag}</video:tag>`,
|
||||
video.rating && `<video:rating>${video.rating}</video:rating>`,
|
||||
video.expiration_date && `<video:expiration_date>${video.expiration_date}</video:expiration_date>`,
|
||||
video.publication_date && `<video:publication_date>${video.publication_date}</video:publication_date>`,
|
||||
video.family_friendly && `<video:family_friendly>${video.family_friendly}</video:family_friendly>`,
|
||||
video.requires_subscription && `<video:requires_subscription>${video.requires_subscription}</video:requires_subscription>`,
|
||||
video.live && `<video:live>${video.live}</video:live>`,
|
||||
video.restriction && `<video:restriction relationship="${video.restriction.relationship}">${video.restriction.content}</video:restriction>`,
|
||||
video.platform && `<video:platform relationship="${video.platform.relationship}">${video.platform.content}</video:platform>`,
|
||||
video.uploader && `<video:uploader${video.uploader.info && ` info="${video.uploader.info}"`}>${video.uploader.content}</video:uploader>`,
|
||||
`</video:video>\n`
|
||||
].filter(Boolean);
|
||||
content += videoFields.join('\n');
|
||||
}
|
||||
}
|
||||
if (item.lastModified) {
|
||||
const serializedDate = item.lastModified instanceof Date ? item.lastModified.toISOString() : item.lastModified;
|
||||
content += `<lastmod>${serializedDate}</lastmod>\n`;
|
||||
}
|
||||
if (item.changeFrequency) {
|
||||
content += `<changefreq>${item.changeFrequency}</changefreq>\n`;
|
||||
}
|
||||
if (typeof item.priority === 'number') {
|
||||
content += `<priority>${item.priority}</priority>\n`;
|
||||
}
|
||||
content += '</url>\n';
|
||||
}
|
||||
content += '</urlset>\n';
|
||||
return content;
|
||||
}
|
||||
export function resolveManifest(data) {
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
export function resolveRouteData(data, fileType) {
|
||||
if (fileType === 'robots') {
|
||||
return resolveRobots(data);
|
||||
}
|
||||
if (fileType === 'sitemap') {
|
||||
return resolveSitemap(data);
|
||||
}
|
||||
if (fileType === 'manifest') {
|
||||
return resolveManifest(data);
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
//# sourceMappingURL=resolve-route-data.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+4
@@ -0,0 +1,4 @@
|
||||
// TODO-APP: check if this can be narrowed.
|
||||
export { };
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/metadata/types.ts"],"sourcesContent":["// TODO-APP: check if this can be narrowed.\nexport type ModuleGetter = () => any\n\nexport type ModuleTuple = [getModule: ModuleGetter, filePath: string]\n\n// Contain the collecting image module paths\nexport type CollectingMetadata = {\n icon: string[]\n apple: string[]\n twitter: string[]\n openGraph: string[]\n manifest?: string\n}\n\n// Contain the collecting evaluated image module\nexport type CollectedMetadata = {\n icon: ModuleGetter[]\n apple: ModuleGetter[]\n twitter: ModuleGetter[] | null\n openGraph: ModuleGetter[] | null\n manifest?: string\n}\n\nexport type MetadataImageModule = {\n url: string\n type?: string\n alt?: string\n} & (\n | { sizes?: string }\n | {\n width?: number\n height?: number\n }\n)\n\nexport type PossibleImageFileNameConvention =\n | 'icon'\n | 'apple'\n | 'favicon'\n | 'twitter'\n | 'openGraph'\n\nexport type PossibleStaticMetadataFileNameConvention =\n | PossibleImageFileNameConvention\n | 'manifest'\n"],"names":[],"mappings":"AAAA,2CAA2C;AA0C3C,WAEc","ignoreList":[0]}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import path from 'path';
|
||||
/**
|
||||
* This loader is to create special re-exports from a specific file.
|
||||
* For example, the following loader:
|
||||
*
|
||||
* modularize-import-loader?name=Arrow&from=Arrow&as=default&join=./icons/Arrow!lucide-react
|
||||
*
|
||||
* will be used to create a re-export of:
|
||||
*
|
||||
* export { Arrow as default } from "join(resolve_path('lucide-react'), '/icons/Arrow')"
|
||||
*
|
||||
* This works even if there's no export field in the package.json of the package.
|
||||
*/ export default function transformSource() {
|
||||
const { name, from, as, join } = this.getOptions();
|
||||
const { resourcePath } = this;
|
||||
const fullPath = join ? path.join(path.dirname(resourcePath), join) : resourcePath;
|
||||
return `
|
||||
export {
|
||||
${from === 'default' ? 'default' : name} as ${as === 'default' ? 'default' : name}
|
||||
} from ${JSON.stringify(fullPath)}
|
||||
`;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=modularize-import-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/modularize-import-loader.ts"],"sourcesContent":["import path from 'path'\n\nexport type ModularizeImportLoaderOptions = {\n name: string\n join?: string\n from: 'default' | 'named'\n as: 'default' | 'named'\n}\n\n/**\n * This loader is to create special re-exports from a specific file.\n * For example, the following loader:\n *\n * modularize-import-loader?name=Arrow&from=Arrow&as=default&join=./icons/Arrow!lucide-react\n *\n * will be used to create a re-export of:\n *\n * export { Arrow as default } from \"join(resolve_path('lucide-react'), '/icons/Arrow')\"\n *\n * This works even if there's no export field in the package.json of the package.\n */\nexport default function transformSource(this: any) {\n const { name, from, as, join }: ModularizeImportLoaderOptions =\n this.getOptions()\n const { resourcePath } = this\n const fullPath = join\n ? path.join(path.dirname(resourcePath), join)\n : resourcePath\n\n return `\nexport {\n ${from === 'default' ? 'default' : name} as ${\n as === 'default' ? 'default' : name\n }\n} from ${JSON.stringify(fullPath)}\n`\n}\n"],"names":["path","transformSource","name","from","as","join","getOptions","resourcePath","fullPath","dirname","JSON","stringify"],"mappings":"AAAA,OAAOA,UAAU,OAAM;AASvB;;;;;;;;;;;CAWC,GACD,eAAe,SAASC;IACtB,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAEC,EAAE,EAAEC,IAAI,EAAE,GAC5B,IAAI,CAACC,UAAU;IACjB,MAAM,EAAEC,YAAY,EAAE,GAAG,IAAI;IAC7B,MAAMC,WAAWH,OACbL,KAAKK,IAAI,CAACL,KAAKS,OAAO,CAACF,eAAeF,QACtCE;IAEJ,OAAO,CAAC;;EAER,EAAEJ,SAAS,YAAY,YAAYD,KAAK,IAAI,EAC1CE,OAAO,YAAY,YAAYF,KAChC;OACI,EAAEQ,KAAKC,SAAS,CAACH,UAAU;AAClC,CAAC;AACD","ignoreList":[0]}
|
||||
Generated
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
import path from 'path';
|
||||
import { stringify } from 'querystring';
|
||||
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants';
|
||||
import { DEFAULT_METADATA_ROUTE_EXTENSIONS, isMetadataRouteFile } from '../../../../lib/metadata/is-metadata-route';
|
||||
import { AppBundlePathNormalizer } from '../../../../server/normalizers/built/app/app-bundle-path-normalizer';
|
||||
import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer';
|
||||
import { loadEntrypoint } from '../../../load-entrypoint';
|
||||
import { getFilenameAndExtension } from '../next-metadata-route-loader';
|
||||
export async function createAppRouteCode({ appDir, name, page, pagePath, resolveAppRoute, pageExtensions, nextConfigOutput }) {
|
||||
// routePath is the path to the route handler file,
|
||||
// but could be aliased e.g. private-next-app-dir/favicon.ico
|
||||
const routePath = pagePath.replace(/[\\/]/, '/');
|
||||
// This, when used with the resolver will give us the pathname to the built
|
||||
// route handler file.
|
||||
let resolvedPagePath = await resolveAppRoute(routePath);
|
||||
if (!resolvedPagePath) {
|
||||
throw Object.defineProperty(new Error(`Invariant: could not resolve page path for ${name} at ${routePath}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E281",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
// If this is a metadata route file, then we need to use the metadata-loader
|
||||
// for the route to ensure that the route is generated.
|
||||
const fileBaseName = path.parse(resolvedPagePath).name;
|
||||
const appDirRelativePath = resolvedPagePath.slice(appDir.length);
|
||||
const isMetadataEntryFile = isMetadataRouteFile(appDirRelativePath, DEFAULT_METADATA_ROUTE_EXTENSIONS, true);
|
||||
if (isMetadataEntryFile) {
|
||||
const { ext } = getFilenameAndExtension(resolvedPagePath);
|
||||
const isDynamicRouteExtension = pageExtensions.includes(ext);
|
||||
resolvedPagePath = `next-metadata-route-loader?${stringify({
|
||||
filePath: resolvedPagePath,
|
||||
isDynamicRouteExtension: isDynamicRouteExtension ? '1' : '0'
|
||||
})}!?${WEBPACK_RESOURCE_QUERIES.metadataRoute}`;
|
||||
}
|
||||
const pathname = new AppPathnameNormalizer().normalize(page);
|
||||
const bundlePath = new AppBundlePathNormalizer().normalize(page);
|
||||
return await loadEntrypoint('app-route', {
|
||||
VAR_USERLAND: resolvedPagePath,
|
||||
VAR_DEFINITION_PAGE: page,
|
||||
VAR_DEFINITION_PATHNAME: pathname,
|
||||
VAR_DEFINITION_FILENAME: fileBaseName,
|
||||
VAR_DEFINITION_BUNDLE_PATH: bundlePath,
|
||||
VAR_RESOLVED_PAGE_PATH: resolvedPagePath
|
||||
}, {
|
||||
nextConfigOutput: JSON.stringify(nextConfigOutput)
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=create-app-route-code.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+778
@@ -0,0 +1,778 @@
|
||||
import { UNDERSCORE_GLOBAL_ERROR_ROUTE, UNDERSCORE_NOT_FOUND_ROUTE } from '../../../../shared/lib/constants';
|
||||
import { UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY, UNDERSCORE_NOT_FOUND_ROUTE_ENTRY } from '../../../../shared/lib/entry-constants';
|
||||
import path from 'path';
|
||||
import { bold } from '../../../../lib/picocolors';
|
||||
import { getModuleBuildInfo } from '../get-module-build-info';
|
||||
import { verifyRootLayout } from '../../../../lib/verify-root-layout';
|
||||
import * as Log from '../../../output/log';
|
||||
import { APP_DIR_ALIAS } from '../../../../lib/constants';
|
||||
import { createMetadataExportsCode, createStaticMetadataFromRoute } from '../metadata/discover';
|
||||
import { promises as fs } from 'fs';
|
||||
import { isAppRouteRoute } from '../../../../lib/is-app-route-route';
|
||||
import { AppPathnameNormalizer } from '../../../../server/normalizers/built/app/app-pathname-normalizer';
|
||||
import { isAppBuiltinPage } from '../../../utils';
|
||||
import { loadEntrypoint } from '../../../load-entrypoint';
|
||||
import { isGroupSegment, DEFAULT_SEGMENT_KEY, PAGE_SEGMENT_KEY } from '../../../../shared/lib/segment';
|
||||
import { getFilesInDir } from '../../../../lib/get-files-in-dir';
|
||||
import { PARALLEL_ROUTE_DEFAULT_PATH } from '../../../../client/components/builtin/default';
|
||||
import { PARALLEL_ROUTE_DEFAULT_NULL_PATH } from '../../../../client/components/builtin/default-null';
|
||||
import { createAppRouteCode } from './create-app-route-code';
|
||||
import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error';
|
||||
import { isInterceptionRouteAppPath } from '../../../../shared/lib/router/utils/interception-routes';
|
||||
import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths';
|
||||
import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep';
|
||||
import { installBindings } from '../../../swc/install-bindings';
|
||||
const HTTP_ACCESS_FALLBACKS = {
|
||||
'not-found': 'not-found',
|
||||
forbidden: 'forbidden',
|
||||
unauthorized: 'unauthorized'
|
||||
};
|
||||
const defaultHTTPAccessFallbackPaths = {
|
||||
'not-found': 'next/dist/client/components/builtin/not-found.js',
|
||||
forbidden: 'next/dist/client/components/builtin/forbidden.js',
|
||||
unauthorized: 'next/dist/client/components/builtin/unauthorized.js'
|
||||
};
|
||||
const FILE_TYPES = {
|
||||
layout: 'layout',
|
||||
template: 'template',
|
||||
error: 'error',
|
||||
loading: 'loading',
|
||||
'global-error': 'global-error',
|
||||
'global-not-found': 'global-not-found',
|
||||
...HTTP_ACCESS_FALLBACKS
|
||||
};
|
||||
const GLOBAL_ERROR_FILE_TYPE = 'global-error';
|
||||
const GLOBAL_NOT_FOUND_FILE_TYPE = 'global-not-found';
|
||||
const PAGE_SEGMENT = 'page$';
|
||||
const PARALLEL_VIRTUAL_SEGMENT = 'slot$';
|
||||
const defaultGlobalErrorPath = 'next/dist/client/components/builtin/global-error.js';
|
||||
const defaultNotFoundPath = 'next/dist/client/components/builtin/not-found.js';
|
||||
const defaultEmptyStubPath = 'next/dist/client/components/builtin/empty-stub.js';
|
||||
const defaultLayoutPath = 'next/dist/client/components/builtin/layout.js';
|
||||
const defaultGlobalNotFoundPath = 'next/dist/client/components/builtin/global-not-found.js';
|
||||
const appErrorPath = 'next/dist/client/components/builtin/app-error.js';
|
||||
const normalizeParallelKey = (key)=>key.startsWith('@') ? key.slice(1) : key;
|
||||
const isCatchAllSegment = (segment)=>segment.startsWith('[...') || segment.startsWith('[[...');
|
||||
const isDynamicSegment = (segment)=>segment.startsWith('[') && segment.endsWith(']');
|
||||
const isDirectory = async (pathname)=>{
|
||||
try {
|
||||
const stat = await fs.stat(pathname);
|
||||
return stat.isDirectory();
|
||||
} catch (err) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
async function createTreeCodeFromPath(pagePath, { page, resolveDir, resolver, resolveParallelSegments, hasChildRoutesForSegment, getStaticSiblingSegments, metadataResolver, pageExtensions, basePath, collectedDeclarations, isGlobalNotFoundEnabled, isDev }) {
|
||||
const splittedPath = pagePath.split(/[\\/]/, 1);
|
||||
const isNotFoundRoute = page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY;
|
||||
const isAppErrorRoute = page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY;
|
||||
const isDefaultNotFound = isAppBuiltinPage(pagePath);
|
||||
const appDirPrefix = isDefaultNotFound ? APP_DIR_ALIAS : splittedPath[0];
|
||||
let rootLayout;
|
||||
let globalError = defaultGlobalErrorPath;
|
||||
let globalNotFound = defaultNotFoundPath;
|
||||
async function resolveAdjacentParallelSegments(segmentPath) {
|
||||
const absoluteSegmentPath = resolveDir(`${appDirPrefix}${segmentPath}`);
|
||||
if (!absoluteSegmentPath) {
|
||||
return [];
|
||||
}
|
||||
const segmentIsDirectory = await isDirectory(absoluteSegmentPath);
|
||||
if (!segmentIsDirectory) {
|
||||
return [];
|
||||
}
|
||||
// We need to resolve all parallel routes in this level.
|
||||
const files = await fs.opendir(absoluteSegmentPath);
|
||||
const parallelSegments = [
|
||||
'children'
|
||||
];
|
||||
for await (const dirent of files){
|
||||
// Make sure name starts with "@" and is a directory.
|
||||
if (dirent.isDirectory() && dirent.name.charCodeAt(0) === 64) {
|
||||
parallelSegments.push(dirent.name);
|
||||
}
|
||||
}
|
||||
return parallelSegments;
|
||||
}
|
||||
async function createSubtreePropsFromSegmentPath(segments, nestedCollectedDeclarations) {
|
||||
const segmentPath = segments.join('/');
|
||||
// Existing tree are the children of the current segment
|
||||
const props = {};
|
||||
// Root layer could be 1st layer of normal routes
|
||||
const isRootLayer = segments.length === 0;
|
||||
const isRootLayoutOrRootPage = segments.length <= 1;
|
||||
// We need to resolve all parallel routes in this level.
|
||||
const parallelSegments = [];
|
||||
if (isRootLayer) {
|
||||
parallelSegments.push([
|
||||
'children',
|
||||
''
|
||||
]);
|
||||
} else {
|
||||
parallelSegments.push(...resolveParallelSegments(segmentPath));
|
||||
}
|
||||
let metadata = null;
|
||||
const routerDirPath = `${appDirPrefix}${segmentPath}`;
|
||||
const resolvedRouteDir = resolveDir(routerDirPath);
|
||||
if (resolvedRouteDir && // Do not collect metadata for app-error route as it's for generating pure static 500.html
|
||||
!normalizePathSep(pagePath).endsWith(appErrorPath)) {
|
||||
metadata = await createStaticMetadataFromRoute(resolvedRouteDir, {
|
||||
basePath,
|
||||
segment: segmentPath,
|
||||
metadataResolver,
|
||||
isRootLayoutOrRootPage,
|
||||
pageExtensions
|
||||
});
|
||||
}
|
||||
for (const [parallelKey, parallelSegment] of parallelSegments){
|
||||
// if parallelSegment is the page segment (ie, `page$` and not ['page$']), it gets loaded into the __PAGE__ slot
|
||||
// as it's the page for the current route.
|
||||
if (parallelSegment === PAGE_SEGMENT) {
|
||||
const matchedPagePath = `${appDirPrefix}${segmentPath}${parallelKey === 'children' ? '' : `/${parallelKey}`}/page`;
|
||||
const resolvedPagePath = await resolver(matchedPagePath);
|
||||
if (resolvedPagePath) {
|
||||
const varName = `page${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
varName,
|
||||
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[normalizeParallelKey(parallelKey)] = `['${PAGE_SEGMENT_KEY}', {}, {
|
||||
page: [${varName}, ${JSON.stringify(resolvedPagePath)}],
|
||||
${createMetadataExportsCode(metadata)}
|
||||
}]`;
|
||||
continue;
|
||||
} else {
|
||||
throw Object.defineProperty(new Error(`Can't resolve ${matchedPagePath}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E1007",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
// if the parallelSegment was not matched to the __PAGE__ slot, then it's a parallel route at this level.
|
||||
// the code below recursively traverses the parallel slots directory to match the corresponding __PAGE__ for each parallel slot
|
||||
// while also filling in layout/default/etc files into the loader tree at each segment level.
|
||||
const subSegmentPath = [
|
||||
...segments
|
||||
];
|
||||
if (parallelKey !== 'children') {
|
||||
// A `children` parallel key should have already been processed in the above segment
|
||||
// So we exclude it when constructing the subsegment path for the remaining segment levels
|
||||
subSegmentPath.push(parallelKey);
|
||||
}
|
||||
const normalizedParallelSegment = Array.isArray(parallelSegment) ? parallelSegment[0] : parallelSegment;
|
||||
if (normalizedParallelSegment !== PAGE_SEGMENT && normalizedParallelSegment !== PARALLEL_VIRTUAL_SEGMENT) {
|
||||
// If we don't have a page segment, nor a special $children marker, it means we need to traverse the next directory
|
||||
// (ie, `normalizedParallelSegment` would correspond with the folder that contains the next level of pages/layout/etc)
|
||||
// we push it to the subSegmentPath so that we can fill in the loader tree for that segment.
|
||||
subSegmentPath.push(normalizedParallelSegment);
|
||||
}
|
||||
const parallelSegmentPath = subSegmentPath.join('/');
|
||||
// Fill in the loader tree for all of the special files types (layout, default, etc) at this level
|
||||
// `page` is not included here as it's added above.
|
||||
const filePathEntries = await Promise.all(Object.values(FILE_TYPES).map(async (file)=>{
|
||||
return [
|
||||
file,
|
||||
await resolver(`${appDirPrefix}${// TODO-APP: parallelSegmentPath sometimes ends in `/` but sometimes it doesn't. This should be consistent.
|
||||
parallelSegmentPath.endsWith('/') ? parallelSegmentPath : parallelSegmentPath + '/'}${file}`)
|
||||
];
|
||||
}));
|
||||
const filePaths = new Map(filePathEntries);
|
||||
// Resolve global-* convention files at the root layer
|
||||
if (isRootLayer) {
|
||||
const resolvedGlobalErrorPath = await resolver(`${appDirPrefix}/${GLOBAL_ERROR_FILE_TYPE}`);
|
||||
if (resolvedGlobalErrorPath) {
|
||||
globalError = resolvedGlobalErrorPath;
|
||||
}
|
||||
// TODO(global-not-found): remove this flag assertion condition
|
||||
// once global-not-found is stable
|
||||
if (isGlobalNotFoundEnabled) {
|
||||
const resolvedGlobalNotFoundPath = await resolver(`${appDirPrefix}/${GLOBAL_NOT_FOUND_FILE_TYPE}`);
|
||||
if (resolvedGlobalNotFoundPath) {
|
||||
globalNotFound = resolvedGlobalNotFoundPath;
|
||||
}
|
||||
// Add global-not-found to root layer's filePaths, so that it's always available,
|
||||
// by default it's the built-in global-not-found.js
|
||||
filePaths.set(GLOBAL_NOT_FOUND_FILE_TYPE, globalNotFound);
|
||||
}
|
||||
}
|
||||
// Add global-error to ALL layers' filePaths, so that it's always available.
|
||||
// By default it's the built-in global-error.js, or user's custom one if defined.
|
||||
filePaths.set(GLOBAL_ERROR_FILE_TYPE, globalError);
|
||||
let definedFilePaths = Array.from(filePaths.entries()).filter(([, filePath])=>filePath !== undefined);
|
||||
// Add default access fallback as root fallback if not present
|
||||
const existedConventionNames = new Set(definedFilePaths.map(([type])=>type));
|
||||
// If the first layer is a group route, we treat it as root layer
|
||||
const isFirstLayerGroupRoute = segments.length === 1 && subSegmentPath.filter((seg)=>isGroupSegment(seg)).length === 1;
|
||||
if (isRootLayer || isFirstLayerGroupRoute) {
|
||||
const accessFallbackTypes = Object.keys(defaultHTTPAccessFallbackPaths);
|
||||
for (const type of accessFallbackTypes){
|
||||
const hasRootFallbackFile = await resolver(`${appDirPrefix}/${FILE_TYPES[type]}`);
|
||||
const hasLayerFallbackFile = existedConventionNames.has(type);
|
||||
// If you already have a root access error fallback, don't insert default access error boundary to group routes root
|
||||
if (// Is treated as root layout and without boundary
|
||||
!(hasRootFallbackFile && isFirstLayerGroupRoute) && // Does not have a fallback boundary file
|
||||
!hasLayerFallbackFile) {
|
||||
const defaultFallbackPath = defaultHTTPAccessFallbackPaths[type];
|
||||
if (!(isDefaultNotFound && type === 'not-found')) {
|
||||
definedFilePaths.push([
|
||||
type,
|
||||
defaultFallbackPath
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!rootLayout) {
|
||||
var _definedFilePaths_find;
|
||||
const layoutPath = (_definedFilePaths_find = definedFilePaths.find(([type])=>type === 'layout')) == null ? void 0 : _definedFilePaths_find[1];
|
||||
rootLayout = layoutPath;
|
||||
// When `global-not-found` is disabled, we insert a default layout if
|
||||
// root layout is presented. This logic and the default layout will be removed
|
||||
// once `global-not-found` is stabilized.
|
||||
if (!isGlobalNotFoundEnabled && isDefaultNotFound && !layoutPath && !rootLayout) {
|
||||
rootLayout = defaultLayoutPath;
|
||||
definedFilePaths.push([
|
||||
'layout',
|
||||
rootLayout
|
||||
]);
|
||||
}
|
||||
}
|
||||
let parallelSegmentKey = Array.isArray(parallelSegment) ? parallelSegment[0] : parallelSegment;
|
||||
// normalize the parallel segment key to remove any special markers that we inserted in the
|
||||
// earlier logic (such as children$ and page$). These should never appear in the loader tree, and
|
||||
// should instead be the corresponding segment keys (ie `__PAGE__`) or the `children` parallel route.
|
||||
parallelSegmentKey = parallelSegmentKey === PARALLEL_VIRTUAL_SEGMENT || parallelSegmentKey === PAGE_SEGMENT ? '(__SLOT__)' : parallelSegmentKey;
|
||||
const normalizedParallelKey = normalizeParallelKey(parallelKey);
|
||||
let subtreeCode;
|
||||
// If it's root not found page, set not-found boundary as children page
|
||||
if (isNotFoundRoute) {
|
||||
if (normalizedParallelKey === 'children') {
|
||||
var _definedFilePaths_find1;
|
||||
const matchedGlobalNotFound = isGlobalNotFoundEnabled ? ((_definedFilePaths_find1 = definedFilePaths.find(([type])=>type === GLOBAL_NOT_FOUND_FILE_TYPE)) == null ? void 0 : _definedFilePaths_find1[1]) ?? defaultGlobalNotFoundPath : undefined;
|
||||
// If custom global-not-found.js is defined, use global-not-found.js
|
||||
if (matchedGlobalNotFound) {
|
||||
const varName = `notFound${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
varName,
|
||||
matchedGlobalNotFound
|
||||
]);
|
||||
const layoutName = `layout${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
layoutName,
|
||||
defaultEmptyStubPath
|
||||
]);
|
||||
subtreeCode = `{
|
||||
children: [${JSON.stringify(UNDERSCORE_NOT_FOUND_ROUTE)}, {
|
||||
children: ['${PAGE_SEGMENT_KEY}', {}, {
|
||||
layout: [
|
||||
${varName},
|
||||
${JSON.stringify(matchedGlobalNotFound)}
|
||||
],
|
||||
page: [
|
||||
${layoutName},
|
||||
${JSON.stringify(defaultEmptyStubPath)}
|
||||
]
|
||||
}]
|
||||
}, {}]
|
||||
}`;
|
||||
} else {
|
||||
var _definedFilePaths_find2;
|
||||
// If custom not-found.js is found, use it and layout to compose the page,
|
||||
// and fallback to built-in not-found component if doesn't exist.
|
||||
const notFoundPath = ((_definedFilePaths_find2 = definedFilePaths.find(([type])=>type === 'not-found')) == null ? void 0 : _definedFilePaths_find2[1]) ?? defaultNotFoundPath;
|
||||
const varName = `notFound${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
varName,
|
||||
notFoundPath
|
||||
]);
|
||||
subtreeCode = `{
|
||||
children: [${JSON.stringify(UNDERSCORE_NOT_FOUND_ROUTE.slice(1))}, {
|
||||
children: ['${PAGE_SEGMENT_KEY}', {}, {
|
||||
page: [
|
||||
${varName},
|
||||
${JSON.stringify(notFoundPath)}
|
||||
]
|
||||
}]
|
||||
}, {}]
|
||||
}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If it's app-error route, set app-error as children page
|
||||
if (isAppErrorRoute) {
|
||||
const varName = `appError${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
varName,
|
||||
appErrorPath
|
||||
]);
|
||||
subtreeCode = `{
|
||||
children: [${JSON.stringify(UNDERSCORE_GLOBAL_ERROR_ROUTE.slice(1))}, {
|
||||
children: ['${PAGE_SEGMENT_KEY}', {}, {
|
||||
page: [
|
||||
${varName},
|
||||
${JSON.stringify(appErrorPath)}
|
||||
]
|
||||
}]
|
||||
}, {}]
|
||||
}`;
|
||||
}
|
||||
// For 404 route
|
||||
// if global-not-found is in definedFilePaths, remove root layout for /_not-found,
|
||||
// and change it to global-not-found route.
|
||||
// TODO: remove this once global-not-found is stable.
|
||||
if (isNotFoundRoute && isGlobalNotFoundEnabled) {
|
||||
var _definedFilePaths_find3;
|
||||
definedFilePaths = definedFilePaths.filter(([type])=>type !== 'layout');
|
||||
// Replace the layout to global-not-found
|
||||
definedFilePaths.push([
|
||||
'layout',
|
||||
((_definedFilePaths_find3 = definedFilePaths.find(([type])=>type === GLOBAL_NOT_FOUND_FILE_TYPE)) == null ? void 0 : _definedFilePaths_find3[1]) ?? defaultGlobalNotFoundPath
|
||||
]);
|
||||
}
|
||||
if (isAppErrorRoute) {
|
||||
definedFilePaths = definedFilePaths.filter(([type])=>type !== 'layout');
|
||||
}
|
||||
const modulesCode = `{
|
||||
${definedFilePaths.map(([file, filePath])=>{
|
||||
const varName = `module${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
varName,
|
||||
filePath
|
||||
]);
|
||||
return `'${file}': [${varName}, ${JSON.stringify(filePath)}],`;
|
||||
}).join('\n')}
|
||||
${createMetadataExportsCode(metadata)}
|
||||
}`;
|
||||
if (!subtreeCode) {
|
||||
const { treeCode: pageSubtreeCode } = await createSubtreePropsFromSegmentPath(subSegmentPath, nestedCollectedDeclarations);
|
||||
subtreeCode = pageSubtreeCode;
|
||||
}
|
||||
// Compute static siblings for dynamic segments. In dev mode, routes are
|
||||
// compiled on-demand so we don't know all siblings; pass null.
|
||||
const staticSiblingsCode = isDev ? 'null' : `${JSON.stringify(getStaticSiblingSegments(parallelSegmentPath))}`;
|
||||
props[normalizedParallelKey] = `[
|
||||
'${parallelSegmentKey}',
|
||||
${subtreeCode},
|
||||
${modulesCode},
|
||||
${staticSiblingsCode}
|
||||
]`;
|
||||
}
|
||||
const adjacentParallelSegments = await resolveAdjacentParallelSegments(segmentPath);
|
||||
for (const adjacentParallelSegment of adjacentParallelSegments){
|
||||
if (!props[normalizeParallelKey(adjacentParallelSegment)]) {
|
||||
const actualSegment = adjacentParallelSegment === 'children' ? '' : `/${adjacentParallelSegment}`;
|
||||
// Use the default path if it's found, otherwise if it's a children
|
||||
// slot, then use the fallback (which triggers a `notFound()`). If this
|
||||
// isn't a children slot, then throw an error, as it produces a silent
|
||||
// 404 if we'd used the fallback.
|
||||
const fullSegmentPath = `${appDirPrefix}${segmentPath}${actualSegment}`;
|
||||
let defaultPath = await resolver(`${fullSegmentPath}/default`);
|
||||
if (!defaultPath) {
|
||||
if (adjacentParallelSegment === 'children') {
|
||||
// When we host applications on Vercel, the status code affects the
|
||||
// underlying behavior of the route, which when we are missing the
|
||||
// children slot of an interception route, will yield a full 404
|
||||
// response for the RSC request instead. For this reason, we expect
|
||||
// that if a default file is missing when we're rendering an
|
||||
// interception route, we instead always render null for the default
|
||||
// slot to avoid the full 404 response.
|
||||
if (isInterceptionRouteAppPath(page)) {
|
||||
defaultPath = PARALLEL_ROUTE_DEFAULT_NULL_PATH;
|
||||
} else {
|
||||
defaultPath = PARALLEL_ROUTE_DEFAULT_PATH;
|
||||
}
|
||||
} else {
|
||||
// Check if we're inside a catch-all route (i.e., the parallel route is a child
|
||||
// of a catch-all segment). Only skip validation if the slot is UNDER a catch-all.
|
||||
// For example:
|
||||
// /[...catchAll]/@slot - isInsideCatchAll = true (skip validation) ✓
|
||||
// /@slot/[...catchAll] - isInsideCatchAll = false (require default) ✓
|
||||
// The catch-all provides fallback behavior, so default.js is not required.
|
||||
const isInsideCatchAll = segments.some(isCatchAllSegment);
|
||||
// Check if this is a leaf segment (no child routes).
|
||||
// Leaf segments don't need default.js because there are no child routes
|
||||
// that could cause the parallel slot to unmatch. For example:
|
||||
// /repo-overview/@slot/page with no child routes - isLeafSegment = true (skip validation) ✓
|
||||
// /repo-overview/@slot/page with /repo-overview/child/page - isLeafSegment = false (require default) ✓
|
||||
// This also handles route groups correctly by filtering them out.
|
||||
const isLeafSegment = !hasChildRoutesForSegment(segmentPath);
|
||||
if (!isInsideCatchAll && !isLeafSegment) {
|
||||
// Replace internal webpack alias with user-facing directory name
|
||||
const userFacingPath = fullSegmentPath.replace(APP_DIR_ALIAS, 'app');
|
||||
throw new MissingDefaultParallelRouteError(userFacingPath, adjacentParallelSegment);
|
||||
}
|
||||
defaultPath = PARALLEL_ROUTE_DEFAULT_PATH;
|
||||
}
|
||||
}
|
||||
const varName = `default${nestedCollectedDeclarations.length}`;
|
||||
nestedCollectedDeclarations.push([
|
||||
varName,
|
||||
defaultPath
|
||||
]);
|
||||
props[normalizeParallelKey(adjacentParallelSegment)] = `[
|
||||
'${DEFAULT_SEGMENT_KEY}',
|
||||
{},
|
||||
{
|
||||
defaultPage: [${varName}, ${JSON.stringify(defaultPath)}],
|
||||
}
|
||||
]`;
|
||||
}
|
||||
}
|
||||
return {
|
||||
treeCode: `{
|
||||
${Object.entries(props).map(([key, value])=>`${key}: ${value}`).join(',\n')}
|
||||
}`
|
||||
};
|
||||
}
|
||||
const { treeCode } = await createSubtreePropsFromSegmentPath([], collectedDeclarations);
|
||||
return {
|
||||
treeCode: `${treeCode}.children;`,
|
||||
rootLayout,
|
||||
globalError,
|
||||
globalNotFound
|
||||
};
|
||||
}
|
||||
function createAbsolutePath(appDir, pathToTurnAbsolute) {
|
||||
return pathToTurnAbsolute// Replace all POSIX path separators with the current OS path separator
|
||||
.replace(/\//g, path.sep).replace(/^private-next-app-dir/, appDir);
|
||||
}
|
||||
const filesInDirMapMap = new WeakMap();
|
||||
const nextAppLoader = async function nextAppLoader() {
|
||||
// install native bindings early so they are always available.
|
||||
// When run by webpack, next will have already done this, so this will be fast,
|
||||
// but if run by turbopack in a subprocess it is required. In that case we cannot pass the
|
||||
// `useWasmBinary` flag, but that is ok since turbopack doesn't currently support wasm.
|
||||
await installBindings();
|
||||
const loaderOptions = this.getOptions();
|
||||
const { name, appDir, appPaths, allNormalizedAppPaths: allNormalizedAppPathsOption, pagePath, pageExtensions, rootDir, tsconfigPath, isDev, nextConfigOutput, preferredRegion, basePath, middlewareConfig: middlewareConfigBase64 } = loaderOptions;
|
||||
const isGlobalNotFoundEnabled = !!loaderOptions.isGlobalNotFoundEnabled;
|
||||
// Update FILE_TYPES on the very top-level of the loader
|
||||
if (!isGlobalNotFoundEnabled) {
|
||||
// @ts-expect-error this delete is only necessary while experimental
|
||||
delete FILE_TYPES['global-not-found'];
|
||||
}
|
||||
const buildInfo = getModuleBuildInfo(this._module);
|
||||
const collectedDeclarations = [];
|
||||
// Use the page from loaderOptions directly instead of deriving it from name.
|
||||
// The name (bundlePath) may have been normalized with normalizePagePath()
|
||||
// which is designed for Pages Router and incorrectly duplicates /index paths
|
||||
// (e.g., /index/page -> /index/index/page). The page parameter contains the
|
||||
// correct unnormalized value.
|
||||
const page = loaderOptions.page;
|
||||
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, 'base64').toString());
|
||||
buildInfo.route = {
|
||||
page,
|
||||
absolutePagePath: createAbsolutePath(appDir, pagePath),
|
||||
preferredRegion,
|
||||
middlewareConfig,
|
||||
relatedModules: []
|
||||
};
|
||||
const extensions = typeof pageExtensions === 'string' ? [
|
||||
pageExtensions
|
||||
] : pageExtensions.map((extension)=>`.${extension}`);
|
||||
const normalizedAppPaths = typeof appPaths === 'string' ? [
|
||||
appPaths
|
||||
] : appPaths || [];
|
||||
// All normalized app paths for computing static siblings across route groups
|
||||
const allNormalizedAppPaths = allNormalizedAppPathsOption ?? [];
|
||||
const resolveParallelSegments = (pathname)=>{
|
||||
const matched = {};
|
||||
let existingChildrenPath;
|
||||
for (const appPath of normalizedAppPaths){
|
||||
if (appPath.startsWith(pathname + '/')) {
|
||||
const rest = appPath.slice(pathname.length + 1).split('/');
|
||||
// It is the actual page, mark it specially.
|
||||
if (rest.length === 1 && rest[0] === 'page') {
|
||||
existingChildrenPath = appPath;
|
||||
matched.children = PAGE_SEGMENT;
|
||||
continue;
|
||||
}
|
||||
const isParallelRoute = rest[0].startsWith('@');
|
||||
if (isParallelRoute) {
|
||||
if (rest.length === 2 && rest[1] === 'page') {
|
||||
// We found a parallel route at this level. We don't want to mark it explicitly as the page segment,
|
||||
// as that should be matched to the `children` slot. Instead, we use an array, to signal to `createSubtreePropsFromSegmentPath`
|
||||
// that it needs to recursively fill in the loader tree code for the parallel route at the appropriate levels.
|
||||
matched[rest[0]] = [
|
||||
PAGE_SEGMENT
|
||||
];
|
||||
continue;
|
||||
}
|
||||
// If it was a parallel route but we weren't able to find the page segment (ie, maybe the page is nested further)
|
||||
// we first insert a special marker to ensure that we still process layout/default/etc at the slot level prior to continuing
|
||||
// on to the page segment.
|
||||
matched[rest[0]] = [
|
||||
PARALLEL_VIRTUAL_SEGMENT,
|
||||
...rest.slice(1)
|
||||
];
|
||||
continue;
|
||||
}
|
||||
if (existingChildrenPath && matched.children !== rest[0]) {
|
||||
// If we get here, it means we already set a `page` segment earlier in the loop,
|
||||
// meaning we already matched a page to the `children` parallel segment.
|
||||
const isIncomingParallelPage = appPath.includes('@');
|
||||
const hasCurrentParallelPage = existingChildrenPath.includes('@');
|
||||
if (isIncomingParallelPage) {
|
||||
continue;
|
||||
} else if (!hasCurrentParallelPage && !isIncomingParallelPage) {
|
||||
// Both the current `children` and the incoming `children` are regular pages.
|
||||
throw Object.defineProperty(new Error(`You cannot have two parallel pages that resolve to the same path. Please check ${existingChildrenPath} and ${appPath}. Refer to the route group docs for more information: https://nextjs.org/docs/app/building-your-application/routing/route-groups`), "__NEXT_ERROR_CODE", {
|
||||
value: "E28",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
existingChildrenPath = appPath;
|
||||
matched.children = rest[0];
|
||||
}
|
||||
}
|
||||
return Object.entries(matched);
|
||||
};
|
||||
const hasChildRoutesForSegment = (segmentPath)=>{
|
||||
const pathPrefix = segmentPath ? `${segmentPath}/` : '';
|
||||
for (const appPath of normalizedAppPaths){
|
||||
if (appPath.startsWith(pathPrefix)) {
|
||||
var _routeSegments_;
|
||||
const rest = appPath.slice(pathPrefix.length).split('/');
|
||||
// Filter out route groups to get the actual route segments
|
||||
// Route groups (e.g., "(group)") don't contribute to the URL path
|
||||
const routeSegments = rest.filter((segment)=>!isGroupSegment(segment));
|
||||
// If it's just 'page' at this level, skip (not a child route)
|
||||
if (routeSegments.length === 1 && routeSegments[0] === 'page') {
|
||||
continue;
|
||||
}
|
||||
// If the first segment (after filtering route groups) is a parallel route, skip
|
||||
if ((_routeSegments_ = routeSegments[0]) == null ? void 0 : _routeSegments_.startsWith('@')) {
|
||||
continue;
|
||||
}
|
||||
// If we have more than just 'page', then there are child routes
|
||||
// Examples:
|
||||
// ['child', 'page'] -> true (has child route)
|
||||
// ['page'] -> false (already filtered above)
|
||||
// ['grandchild', 'deeper', 'page'] -> true (has nested child routes)
|
||||
if (routeSegments.length > 1 || routeSegments.length === 1 && routeSegments[0] !== 'page') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
/**
|
||||
* For a given segment path (in file system space, e.g., "(group)/products/[id]"),
|
||||
* find all static sibling segments at the same URL path level.
|
||||
*
|
||||
* This accounts for route groups - siblings may exist in different parts of the
|
||||
* file system tree but at the same URL level.
|
||||
*
|
||||
* For example:
|
||||
* /app/(marketing)/products/sale/page.tsx -> /products/sale
|
||||
* /app/(shop)/products/[id]/page.tsx -> /products/[id]
|
||||
*
|
||||
* When called with "(shop)/products/[id]", this would return ['sale'].
|
||||
*
|
||||
* TODO: This function, along with resolveParallelSegments and
|
||||
* hasChildRoutesForSegment, repeatedly scans normalizedAppPaths. A more
|
||||
* optimal approach would build an intermediate tree structure first
|
||||
* (representing the URL namespace with route groups collapsed), then derive
|
||||
* all this information in a single pass. The Turbopack implementation
|
||||
* already uses a more tree-oriented approach (DirectoryTree ->
|
||||
* AppPageLoaderTree), so this is less urgent to refactor given Turbopack is
|
||||
* the canonical implementation going forward.
|
||||
*/ const getStaticSiblingSegments = (segmentPath)=>{
|
||||
// Normalize the current path to URL space
|
||||
// Add a trailing /page so normalizeAppPath strips it properly
|
||||
const currentUrlPath = normalizeAppPath(segmentPath + '/page');
|
||||
const currentUrlSegments = currentUrlPath.split('/').filter(Boolean);
|
||||
// If the path is empty (root level), there are no siblings
|
||||
if (currentUrlSegments.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const currentSegment = currentUrlSegments[currentUrlSegments.length - 1];
|
||||
const parentUrlPath = currentUrlSegments.length === 1 ? '/' : '/' + currentUrlSegments.slice(0, -1).join('/');
|
||||
// The URL level at which we're looking for siblings (0-indexed)
|
||||
const siblingLevel = currentUrlSegments.length - 1;
|
||||
// Only compute siblings for dynamic segments
|
||||
if (!isDynamicSegment(currentSegment)) {
|
||||
return [];
|
||||
}
|
||||
// Use a Set to avoid duplicates (multiple paths may share the same sibling segment)
|
||||
const siblings = new Set();
|
||||
for (const appPath of allNormalizedAppPaths){
|
||||
// Normalize each path to URL space (strip route groups, parallel routes, and /page suffix)
|
||||
const urlPath = normalizeAppPath(appPath);
|
||||
const urlSegments = urlPath.split('/').filter(Boolean);
|
||||
// Path must have at least enough segments to reach the sibling level
|
||||
if (urlSegments.length <= siblingLevel) {
|
||||
continue;
|
||||
}
|
||||
// Check if the parent path matches (all segments before the sibling level)
|
||||
const pathParent = siblingLevel === 0 ? '/' : '/' + urlSegments.slice(0, siblingLevel).join('/');
|
||||
if (pathParent !== parentUrlPath) {
|
||||
continue;
|
||||
}
|
||||
// Get the segment at the same level as the current segment
|
||||
const segmentAtLevel = urlSegments[siblingLevel];
|
||||
// Check if this is a sibling: different segment and static
|
||||
if (segmentAtLevel !== currentSegment && !isDynamicSegment(segmentAtLevel)) {
|
||||
siblings.add(segmentAtLevel);
|
||||
}
|
||||
}
|
||||
return Array.from(siblings);
|
||||
};
|
||||
const resolveDir = (pathToResolve)=>{
|
||||
return createAbsolutePath(appDir, pathToResolve);
|
||||
};
|
||||
const resolveAppRoute = (pathToResolve)=>{
|
||||
return createAbsolutePath(appDir, pathToResolve);
|
||||
};
|
||||
// Cached checker to see if a file exists in a given directory.
|
||||
// This can be more efficient than checking them with `fs.stat` one by one
|
||||
// because all the thousands of files are likely in a few possible directories.
|
||||
// Note that it should only be cached for this compilation, not globally.
|
||||
const fileExistsInDirectory = async (dirname, fileName)=>{
|
||||
// I don't think we should ever hit this code path, but if we do we should handle it gracefully.
|
||||
if (this._compilation === undefined) {
|
||||
try {
|
||||
return (await getFilesInDir(dirname).catch(()=>new Set())).has(fileName);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const map = filesInDirMapMap.get(this._compilation) || new Map();
|
||||
if (!filesInDirMapMap.has(this._compilation)) {
|
||||
filesInDirMapMap.set(this._compilation, map);
|
||||
}
|
||||
if (!map.has(dirname)) {
|
||||
map.set(dirname, getFilesInDir(dirname).catch(()=>new Set()));
|
||||
}
|
||||
return (await map.get(dirname) || new Set()).has(fileName);
|
||||
};
|
||||
const resolver = async (pathname)=>{
|
||||
const absolutePath = createAbsolutePath(appDir, pathname);
|
||||
const filenameIndex = absolutePath.lastIndexOf(path.sep);
|
||||
const dirname = absolutePath.slice(0, filenameIndex);
|
||||
const filename = absolutePath.slice(filenameIndex + 1);
|
||||
const checks = await Promise.all(extensions.map(async (ext)=>{
|
||||
const absolutePathWithExtension = `${absolutePath}${ext}`;
|
||||
const exists = await fileExistsInDirectory(dirname, `${filename}${ext}`);
|
||||
// Call `addMissingDependency` for all files even if they didn't match,
|
||||
// because they might be added or removed during development.
|
||||
this.addMissingDependency(absolutePathWithExtension);
|
||||
return exists ? absolutePathWithExtension : undefined;
|
||||
}));
|
||||
return checks.find((result)=>result);
|
||||
};
|
||||
const metadataResolver = async (dirname, filename, exts)=>{
|
||||
const absoluteDir = createAbsolutePath(appDir, dirname);
|
||||
const checks = await Promise.all(exts.map(async (ext)=>{
|
||||
// Compared to `resolver` above the exts do not have the `.` included already, so it's added here.
|
||||
const filenameWithExt = `${filename}.${ext}`;
|
||||
const absolutePathWithExtension = `${absoluteDir}${path.sep}${filenameWithExt}`;
|
||||
const exists = await fileExistsInDirectory(dirname, filenameWithExt);
|
||||
// Call `addMissingDependency` for all files even if they didn't match,
|
||||
// because they might be added or removed during development.
|
||||
this.addMissingDependency(absolutePathWithExtension);
|
||||
return exists ? absolutePathWithExtension : undefined;
|
||||
}));
|
||||
return checks.filter((result)=>result !== undefined);
|
||||
};
|
||||
if (isAppRouteRoute(name)) {
|
||||
return createAppRouteCode({
|
||||
appDir,
|
||||
// TODO: investigate if the local `page` is the same as the loaderOptions.page
|
||||
page: loaderOptions.page,
|
||||
name,
|
||||
pagePath,
|
||||
resolveAppRoute,
|
||||
pageExtensions,
|
||||
nextConfigOutput
|
||||
});
|
||||
}
|
||||
let treeCodeResult = await createTreeCodeFromPath(pagePath, {
|
||||
page,
|
||||
resolveDir,
|
||||
resolver,
|
||||
metadataResolver,
|
||||
resolveParallelSegments,
|
||||
hasChildRoutesForSegment,
|
||||
getStaticSiblingSegments,
|
||||
loaderContext: this,
|
||||
pageExtensions,
|
||||
basePath,
|
||||
collectedDeclarations,
|
||||
isGlobalNotFoundEnabled,
|
||||
isDev: !!isDev
|
||||
});
|
||||
const isGlobalNotFoundPath = page === UNDERSCORE_NOT_FOUND_ROUTE_ENTRY && !!treeCodeResult.globalNotFound && isGlobalNotFoundEnabled;
|
||||
const isAppErrorRoute = page === UNDERSCORE_GLOBAL_ERROR_ROUTE_ENTRY;
|
||||
if (!treeCodeResult.rootLayout && !isGlobalNotFoundPath && !isAppErrorRoute) {
|
||||
if (!isDev) {
|
||||
// If we're building and missing a root layout, exit the build
|
||||
Log.error(`${bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ''))} doesn't have a root layout. To fix this error, make sure every page has a root layout.`);
|
||||
process.exit(1);
|
||||
} else {
|
||||
var _filesInDirMapMap_get;
|
||||
// In dev we'll try to create a root layout
|
||||
const [createdRootLayout, rootLayoutPath] = await verifyRootLayout({
|
||||
appDir: appDir,
|
||||
dir: rootDir,
|
||||
tsconfigPath: tsconfigPath,
|
||||
pagePath,
|
||||
pageExtensions
|
||||
});
|
||||
if (!createdRootLayout) {
|
||||
let message = `${bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ''))} doesn't have a root layout. `;
|
||||
if (rootLayoutPath) {
|
||||
var _this__compiler;
|
||||
message += `We tried to create ${bold(path.relative(((_this__compiler = this._compiler) == null ? void 0 : _this__compiler.context) ?? '', rootLayoutPath))} for you but something went wrong.`;
|
||||
} else {
|
||||
message += 'To fix this error, make sure every page has a root layout.';
|
||||
}
|
||||
throw Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
|
||||
value: "E1024",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
// Clear fs cache, get the new result with the created root layout.
|
||||
if (this._compilation) (_filesInDirMapMap_get = filesInDirMapMap.get(this._compilation)) == null ? void 0 : _filesInDirMapMap_get.clear();
|
||||
treeCodeResult = await createTreeCodeFromPath(pagePath, {
|
||||
page,
|
||||
resolveDir,
|
||||
resolver,
|
||||
metadataResolver,
|
||||
resolveParallelSegments,
|
||||
hasChildRoutesForSegment,
|
||||
getStaticSiblingSegments,
|
||||
loaderContext: this,
|
||||
pageExtensions,
|
||||
basePath,
|
||||
collectedDeclarations,
|
||||
isGlobalNotFoundEnabled,
|
||||
isDev: !!isDev
|
||||
});
|
||||
}
|
||||
}
|
||||
const pathname = new AppPathnameNormalizer().normalize(page);
|
||||
// Prefer to modify next/src/server/app-render/entry-base.ts since this is shared with Turbopack.
|
||||
// Any changes to this code should be reflected in Turbopack's app_source.rs and/or app-renderer.tsx as well.
|
||||
const code = await loadEntrypoint('app-page', {
|
||||
VAR_DEFINITION_PAGE: page,
|
||||
VAR_DEFINITION_PATHNAME: pathname
|
||||
}, {
|
||||
tree: treeCodeResult.treeCode,
|
||||
__next_app_require__: '__webpack_require__',
|
||||
// all modules are in the entry chunk, so we never actually need to load chunks in webpack
|
||||
__next_app_load_chunk__: '() => Promise.resolve()'
|
||||
});
|
||||
// Lazily evaluate the imported modules in the generated code
|
||||
const header = collectedDeclarations.map(([varName, modulePath])=>{
|
||||
return `const ${varName} = () => import(/* webpackMode: "eager" */ ${JSON.stringify(modulePath)});\n`;
|
||||
}).join('');
|
||||
return header + code;
|
||||
};
|
||||
export default nextAppLoader;
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+253
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* ## Barrel Optimizations
|
||||
*
|
||||
* This loader is used to optimize the imports of "barrel" files that have many
|
||||
* re-exports. Currently, both Node.js and Webpack have to enter all of these
|
||||
* submodules even if we only need a few of them.
|
||||
*
|
||||
* For example, say a file `foo.js` with the following contents:
|
||||
*
|
||||
* export { a } from './a'
|
||||
* export { b } from './b'
|
||||
* export { c } from './c'
|
||||
* ...
|
||||
*
|
||||
* If the user imports `a` only, this loader will accept the `names` option to
|
||||
* be `['a']`. Then, it request the "__barrel_transform__" SWC transform to load
|
||||
* `foo.js` and receive the following output:
|
||||
*
|
||||
* export const __next_private_export_map__ = '[["a","./a","a"],["b","./b","b"],["c","./c","c"],...]'
|
||||
*
|
||||
* format: '["<imported identifier>", "<import path>", "<exported name>"]'
|
||||
* e.g.: import { a as b } from './module-a' => '["b", "./module-a", "a"]'
|
||||
*
|
||||
* The export map, generated by SWC, is a JSON that represents the exports of
|
||||
* that module, their original file, and their original name (since you can do
|
||||
* `export { a as b }`).
|
||||
*
|
||||
* Then, this loader can safely remove all the exports that are not needed and
|
||||
* re-export the ones from `names`:
|
||||
*
|
||||
* export { a } from './a'
|
||||
*
|
||||
* That's the basic situation and also the happy path.
|
||||
*
|
||||
*
|
||||
*
|
||||
* ## Wildcard Exports
|
||||
*
|
||||
* For wildcard exports (e.g. `export * from './a'`), it becomes a bit more complicated.
|
||||
* Say `foo.js` with the following contents:
|
||||
*
|
||||
* export * from './a'
|
||||
* export * from './b'
|
||||
* export * from './c'
|
||||
* ...
|
||||
*
|
||||
* If the user imports `bar` from it, SWC can never know which files are going to be
|
||||
* exporting `bar`. So, we have to keep all the wildcard exports and do the same
|
||||
* process recursively. This loader will return the following output:
|
||||
*
|
||||
* export * from '__barrel_optimize__?names=bar&wildcard!=!./a'
|
||||
* export * from '__barrel_optimize__?names=bar&wildcard!=!./b'
|
||||
* export * from '__barrel_optimize__?names=bar&wildcard!=!./c'
|
||||
* ...
|
||||
*
|
||||
* The "!=!" tells Webpack to use the same loader to process './a', './b', and './c'.
|
||||
* After the recursive process, the "inner loaders" will either return an empty string
|
||||
* or:
|
||||
*
|
||||
* export * from './target'
|
||||
*
|
||||
* Where `target` is the file that exports `bar`.
|
||||
*
|
||||
*
|
||||
*
|
||||
* ## Non-Barrel Files
|
||||
*
|
||||
* If the file is not a barrel, we can't apply any optimizations. That's because
|
||||
* we can't easily remove things from the file. For example, say `foo.js` with:
|
||||
*
|
||||
* const v = 1
|
||||
* export function b () {
|
||||
* return v
|
||||
* }
|
||||
*
|
||||
* If the user imports `b` only, we can't remove the `const v = 1` even though
|
||||
* the file is side-effect free. In these caes, this loader will simply re-export
|
||||
* `foo.js`:
|
||||
*
|
||||
* export * from './foo'
|
||||
*
|
||||
* Besides these cases, this loader also carefully handles the module cache so
|
||||
* SWC won't analyze the same file twice, and no instance of the same file will
|
||||
* be accidentally created as different instances.
|
||||
*/ import path from 'path';
|
||||
import { transform } from '../../swc';
|
||||
import { installBindings } from '../../swc/install-bindings';
|
||||
// This is a in-memory cache for the mapping of barrel exports. This only applies
|
||||
// to the packages that we optimize. It will never change (e.g. upgrading packages)
|
||||
// during the lifetime of the server so we can safely cache it.
|
||||
// There is also no need to collect the cache for the same reason.
|
||||
const barrelTransformMappingCache = new Map();
|
||||
async function getBarrelMapping(resourcePath, swcCacheDir, resolve, fs) {
|
||||
if (barrelTransformMappingCache.has(resourcePath)) {
|
||||
return barrelTransformMappingCache.get(resourcePath);
|
||||
}
|
||||
// This is a SWC transform specifically for `optimizeBarrelExports`. We don't
|
||||
// care about other things but the export map only.
|
||||
async function transpileSource(filename, source, isWildcard) {
|
||||
const isTypeScript = filename.endsWith('.ts') || filename.endsWith('.tsx');
|
||||
return new Promise((res)=>transform(source, {
|
||||
filename,
|
||||
inputSourceMap: undefined,
|
||||
sourceFileName: filename,
|
||||
optimizeBarrelExports: {
|
||||
wildcard: isWildcard
|
||||
},
|
||||
jsc: {
|
||||
parser: {
|
||||
syntax: isTypeScript ? 'typescript' : 'ecmascript',
|
||||
[isTypeScript ? 'tsx' : 'jsx']: true
|
||||
},
|
||||
experimental: {
|
||||
cacheRoot: swcCacheDir
|
||||
}
|
||||
}
|
||||
}).then((output)=>{
|
||||
res(output.code);
|
||||
}));
|
||||
}
|
||||
// Avoid circular `export *` dependencies
|
||||
const visited = new Set();
|
||||
async function getMatches(file, isWildcard, isClientEntry) {
|
||||
if (visited.has(file)) {
|
||||
return null;
|
||||
}
|
||||
visited.add(file);
|
||||
const source = await new Promise((res, rej)=>{
|
||||
fs.readFile(file, (err, data)=>{
|
||||
if (err || data === undefined) {
|
||||
rej(err);
|
||||
} else {
|
||||
res(data.toString());
|
||||
}
|
||||
});
|
||||
});
|
||||
const output = await transpileSource(file, source, isWildcard);
|
||||
const matches = output.match(/^([^]*)export (const|var) __next_private_export_map__ = ('[^']+'|"[^"]+")/);
|
||||
if (!matches) {
|
||||
return null;
|
||||
}
|
||||
const matchedDirectives = output.match(/^([^]*)export (const|var) __next_private_directive_list__ = '([^']+)'/);
|
||||
const directiveList = matchedDirectives ? JSON.parse(matchedDirectives[3]) : [];
|
||||
// "use client" in barrel files has to be transferred to the target file.
|
||||
isClientEntry = directiveList.includes('use client');
|
||||
let exportList = JSON.parse(matches[3].slice(1, -1));
|
||||
const wildcardExports = [
|
||||
...output.matchAll(/export \* from "([^"]+)"/g)
|
||||
].map((match)=>match[1]);
|
||||
// In the wildcard case, if the value is exported from another file, we
|
||||
// redirect to that file (decl[0]). Otherwise, export from the current
|
||||
// file itself.
|
||||
if (isWildcard) {
|
||||
for (const decl of exportList){
|
||||
decl[1] = file;
|
||||
decl[2] = decl[0];
|
||||
}
|
||||
}
|
||||
// This recursively handles the wildcard exports (e.g. `export * from './a'`)
|
||||
if (wildcardExports.length) {
|
||||
await Promise.all(wildcardExports.map(async (req)=>{
|
||||
const targetPath = await resolve(path.dirname(file), req.replace('__barrel_optimize__?names=__PLACEHOLDER__!=!', ''));
|
||||
const targetMatches = await getMatches(targetPath, true, isClientEntry);
|
||||
if (targetMatches) {
|
||||
// Merge the export list
|
||||
exportList = exportList.concat(targetMatches.exportList);
|
||||
}
|
||||
}));
|
||||
}
|
||||
return {
|
||||
exportList,
|
||||
wildcardExports,
|
||||
isClientEntry
|
||||
};
|
||||
}
|
||||
const res = await getMatches(resourcePath, false, false);
|
||||
barrelTransformMappingCache.set(resourcePath, res);
|
||||
return res;
|
||||
}
|
||||
const NextBarrelLoader = async function() {
|
||||
this.async();
|
||||
this.cacheable(true);
|
||||
// Install bindings early so they are definitely available.
|
||||
// When run by webpack in next this is already done with correct configuration so this is a no-op.
|
||||
// In turbopack loaders are run in a subprocess so it may or may not be done.
|
||||
await installBindings();
|
||||
const { names, swcCacheDir } = this.getOptions();
|
||||
// For barrel optimizations, we always prefer the "module" field over the
|
||||
// "main" field because ESM handling is more robust with better tree-shaking.
|
||||
const resolve = this.getResolve({
|
||||
mainFields: [
|
||||
'module',
|
||||
'main'
|
||||
]
|
||||
});
|
||||
const mapping = await getBarrelMapping(this.resourcePath, swcCacheDir, resolve, this.fs);
|
||||
// `resolve` adds all sub-paths to the dependency graph. However, we already
|
||||
// cached the mapping and we assume them to not change. So, we can safely
|
||||
// clear the dependencies here to avoid unnecessary watchers which turned out
|
||||
// to be very expensive.
|
||||
this.clearDependencies();
|
||||
if (!mapping) {
|
||||
// This file isn't a barrel and we can't apply any optimizations. Let's re-export everything.
|
||||
// Since this loader accepts `names` and the request is keyed with `names`, we can't simply
|
||||
// return the original source here. That will create these imports with different names as
|
||||
// different modules instances.
|
||||
this.callback(null, `export * from ${JSON.stringify(this.resourcePath)}`);
|
||||
return;
|
||||
}
|
||||
const exportList = mapping.exportList;
|
||||
const isClientEntry = mapping.isClientEntry;
|
||||
const exportMap = new Map();
|
||||
for (const [name, filePath, orig] of exportList){
|
||||
exportMap.set(name, [
|
||||
filePath,
|
||||
orig
|
||||
]);
|
||||
}
|
||||
let output = '';
|
||||
let missedNames = [];
|
||||
for (const name of names){
|
||||
// If the name matches
|
||||
if (exportMap.has(name)) {
|
||||
const decl = exportMap.get(name);
|
||||
if (decl[1] === '*') {
|
||||
output += `\nexport * as ${name} from ${JSON.stringify(decl[0])}`;
|
||||
} else if (decl[1] === 'default') {
|
||||
output += `\nexport { default as ${name} } from ${JSON.stringify(decl[0])}`;
|
||||
} else if (decl[1] === name) {
|
||||
output += `\nexport { ${name} } from ${JSON.stringify(decl[0])}`;
|
||||
} else {
|
||||
output += `\nexport { ${decl[1]} as ${name} } from ${JSON.stringify(decl[0])}`;
|
||||
}
|
||||
} else {
|
||||
missedNames.push(name);
|
||||
}
|
||||
}
|
||||
// These are from wildcard exports.
|
||||
if (missedNames.length > 0) {
|
||||
for (const req of mapping.wildcardExports){
|
||||
output += `\nexport * from ${JSON.stringify(req.replace('__PLACEHOLDER__', missedNames.join(',') + '&wildcard'))}`;
|
||||
}
|
||||
}
|
||||
// When it has `"use client"` inherited from its barrel files, we need to
|
||||
// prefix it to this target file as well.
|
||||
if (isClientEntry) {
|
||||
output = `"use client";\n${output}`;
|
||||
}
|
||||
this.callback(null, output);
|
||||
};
|
||||
export default NextBarrelLoader;
|
||||
|
||||
//# sourceMappingURL=next-barrel-loader.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+27
@@ -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
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-client-pages-loader.ts"],"sourcesContent":["import { stringifyRequest } from '../stringify-request'\n\nexport type ClientPagesLoaderOptions = {\n absolutePagePath: string\n page: string\n}\n\n// this parameter: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\nfunction nextClientPagesLoader(this: any) {\n const pagesLoaderSpan = this.currentTraceSpan.traceChild(\n 'next-client-pages-loader'\n )\n\n return pagesLoaderSpan.traceFn(() => {\n const { absolutePagePath, page } =\n this.getOptions() as ClientPagesLoaderOptions\n\n pagesLoaderSpan.setAttribute('absolutePagePath', absolutePagePath)\n\n const stringifiedPageRequest = stringifyRequest(this, absolutePagePath)\n const stringifiedPage = JSON.stringify(page)\n\n return `\n (window.__NEXT_P = window.__NEXT_P || []).push([\n ${stringifiedPage},\n function () {\n return require(${stringifiedPageRequest});\n }\n ]);\n if(module.hot) {\n module.hot.dispose(function () {\n window.__NEXT_P.push([${stringifiedPage}])\n });\n }\n `\n })\n}\n\nexport default nextClientPagesLoader\n"],"names":["stringifyRequest","nextClientPagesLoader","pagesLoaderSpan","currentTraceSpan","traceChild","traceFn","absolutePagePath","page","getOptions","setAttribute","stringifiedPageRequest","stringifiedPage","JSON","stringify"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,uBAAsB;AAOvD,8FAA8F;AAC9F,SAASC;IACP,MAAMC,kBAAkB,IAAI,CAACC,gBAAgB,CAACC,UAAU,CACtD;IAGF,OAAOF,gBAAgBG,OAAO,CAAC;QAC7B,MAAM,EAAEC,gBAAgB,EAAEC,IAAI,EAAE,GAC9B,IAAI,CAACC,UAAU;QAEjBN,gBAAgBO,YAAY,CAAC,oBAAoBH;QAEjD,MAAMI,yBAAyBV,iBAAiB,IAAI,EAAEM;QACtD,MAAMK,kBAAkBC,KAAKC,SAAS,CAACN;QAEvC,OAAO,CAAC;;MAEN,EAAEI,gBAAgB;;uBAED,EAAED,uBAAuB;;;;;8BAKlB,EAAEC,gBAAgB;;;EAG9C,CAAC;IACD;AACF;AAEA,eAAeV,sBAAqB","ignoreList":[0]}
|
||||
Generated
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
import { getModuleBuildInfo } from '../get-module-build-info';
|
||||
import { stringifyRequest } from '../../stringify-request';
|
||||
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants';
|
||||
import { loadEntrypoint } from '../../../load-entrypoint';
|
||||
import { isMetadataRoute } from '../../../../lib/metadata/is-metadata-route';
|
||||
function getCacheHandlersSetup(cacheHandlersStringified, contextifyImportPath) {
|
||||
const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}');
|
||||
const definedCacheHandlers = Object.entries(cacheHandlers).filter((entry)=>Boolean(entry[1]));
|
||||
const cacheHandlerImports = [];
|
||||
const edgeCacheHandlersRegistration = [];
|
||||
for (const [index, [kind, handlerPath]] of definedCacheHandlers.entries()){
|
||||
const cacheHandlerVarName = `edgeCacheHandler_${index}`;
|
||||
const cacheHandlerImportPath = contextifyImportPath(handlerPath);
|
||||
cacheHandlerImports.push(`import ${cacheHandlerVarName} from ${JSON.stringify(cacheHandlerImportPath)}`);
|
||||
edgeCacheHandlersRegistration.push(`edgeCacheHandlers[${JSON.stringify(kind)}] = ${cacheHandlerVarName}`);
|
||||
}
|
||||
return {
|
||||
cacheHandlerImports: cacheHandlerImports.join('\n') || '\n',
|
||||
edgeCacheHandlersRegistration: edgeCacheHandlersRegistration.join('\n') || '\n'
|
||||
};
|
||||
}
|
||||
const EdgeAppRouteLoader = async function() {
|
||||
const { page, absolutePagePath, preferredRegion, appDirLoader: appDirLoaderBase64 = '', middlewareConfig: middlewareConfigBase64 = '', cacheHandler, cacheHandlers: cacheHandlersStringified } = this.getOptions();
|
||||
const appDirLoader = Buffer.from(appDirLoaderBase64, 'base64').toString();
|
||||
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, 'base64').toString());
|
||||
const cacheHandlersSetup = getCacheHandlersSetup(cacheHandlersStringified, (handlerPath)=>this.utils.contextify(this.context || this.rootContext, handlerPath));
|
||||
const incrementalCacheHandler = cacheHandler ? this.utils.contextify(this.context || this.rootContext, cacheHandler) : null;
|
||||
// Ensure we only run this loader for as a module.
|
||||
if (!this._module) throw Object.defineProperty(new Error('This loader is only usable as a module'), "__NEXT_ERROR_CODE", {
|
||||
value: "E433",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
const buildInfo = getModuleBuildInfo(this._module);
|
||||
buildInfo.nextEdgeSSR = {
|
||||
isServerComponent: !isMetadataRoute(page),
|
||||
page: page,
|
||||
isAppDir: true
|
||||
};
|
||||
buildInfo.route = {
|
||||
page,
|
||||
absolutePagePath,
|
||||
preferredRegion,
|
||||
middlewareConfig
|
||||
};
|
||||
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
|
||||
const modulePath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}`;
|
||||
return await loadEntrypoint('edge-app-route', {
|
||||
VAR_USERLAND: modulePath,
|
||||
VAR_PAGE: page
|
||||
}, cacheHandlersSetup, {
|
||||
incrementalCacheHandler
|
||||
});
|
||||
};
|
||||
export default EdgeAppRouteLoader;
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+45
@@ -0,0 +1,45 @@
|
||||
import { getModuleBuildInfo } from './get-module-build-info';
|
||||
import { stringifyRequest } from '../stringify-request';
|
||||
const nextEdgeFunctionLoader = function nextEdgeFunctionLoader() {
|
||||
const { absolutePagePath, page, rootDir, preferredRegion, middlewareConfig: middlewareConfigBase64, cacheHandler } = this.getOptions();
|
||||
const stringifiedPagePath = stringifyRequest(this, absolutePagePath);
|
||||
const stringifiedCacheHandlerPath = cacheHandler ? stringifyRequest(this, cacheHandler) : null;
|
||||
const buildInfo = getModuleBuildInfo(this._module);
|
||||
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, 'base64').toString());
|
||||
buildInfo.route = {
|
||||
page: page || '/',
|
||||
absolutePagePath,
|
||||
preferredRegion,
|
||||
middlewareConfig
|
||||
};
|
||||
buildInfo.nextEdgeApiFunction = {
|
||||
page: page || '/'
|
||||
};
|
||||
buildInfo.rootDir = rootDir;
|
||||
return `
|
||||
import 'next/dist/esm/server/web/globals'
|
||||
import { adapter } from 'next/dist/esm/server/web/adapter'
|
||||
import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'
|
||||
import { wrapApiHandler } from 'next/dist/esm/server/api-utils'
|
||||
${stringifiedCacheHandlerPath ? `import incrementalCacheHandler from ${stringifiedCacheHandlerPath}` : 'const incrementalCacheHandler = null'}
|
||||
|
||||
import handler from ${stringifiedPagePath}
|
||||
|
||||
if (typeof handler !== 'function') {
|
||||
throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
|
||||
}
|
||||
|
||||
export default function nHandler (opts) {
|
||||
return adapter({
|
||||
...opts,
|
||||
IncrementalCache,
|
||||
incrementalCacheHandler,
|
||||
page: ${JSON.stringify(page)},
|
||||
handler: wrapApiHandler(${JSON.stringify(page)}, handler),
|
||||
})
|
||||
}
|
||||
`;
|
||||
};
|
||||
export default nextEdgeFunctionLoader;
|
||||
|
||||
//# sourceMappingURL=next-edge-function-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-edge-function-loader.ts"],"sourcesContent":["import type webpack from 'webpack'\nimport { getModuleBuildInfo } from './get-module-build-info'\nimport { stringifyRequest } from '../stringify-request'\nimport type { ProxyConfig } from '../../analysis/get-page-static-info'\n\nexport type EdgeFunctionLoaderOptions = {\n absolutePagePath: string\n page: string\n rootDir: string\n preferredRegion: string | string[] | undefined\n middlewareConfig: string\n cacheHandler?: string\n}\n\nconst nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoaderOptions> =\n function nextEdgeFunctionLoader(this) {\n const {\n absolutePagePath,\n page,\n rootDir,\n preferredRegion,\n middlewareConfig: middlewareConfigBase64,\n cacheHandler,\n }: EdgeFunctionLoaderOptions = this.getOptions()\n const stringifiedPagePath = stringifyRequest(this, absolutePagePath)\n const stringifiedCacheHandlerPath = cacheHandler\n ? stringifyRequest(this, cacheHandler)\n : null\n const buildInfo = getModuleBuildInfo(this._module as any)\n const middlewareConfig: ProxyConfig = JSON.parse(\n Buffer.from(middlewareConfigBase64, 'base64').toString()\n )\n buildInfo.route = {\n page: page || '/',\n absolutePagePath,\n preferredRegion,\n middlewareConfig,\n }\n buildInfo.nextEdgeApiFunction = {\n page: page || '/',\n }\n buildInfo.rootDir = rootDir\n\n return `\n import 'next/dist/esm/server/web/globals'\n import { adapter } from 'next/dist/esm/server/web/adapter'\n import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'\n import { wrapApiHandler } from 'next/dist/esm/server/api-utils'\n ${\n stringifiedCacheHandlerPath\n ? `import incrementalCacheHandler from ${stringifiedCacheHandlerPath}`\n : 'const incrementalCacheHandler = null'\n }\n\n import handler from ${stringifiedPagePath}\n\n if (typeof handler !== 'function') {\n throw new Error('The Edge Function \"pages${page}\" must export a \\`default\\` function');\n }\n\n export default function nHandler (opts) {\n return adapter({\n ...opts,\n IncrementalCache,\n incrementalCacheHandler,\n page: ${JSON.stringify(page)},\n handler: wrapApiHandler(${JSON.stringify(page)}, handler),\n })\n }\n `\n }\n\nexport default nextEdgeFunctionLoader\n"],"names":["getModuleBuildInfo","stringifyRequest","nextEdgeFunctionLoader","absolutePagePath","page","rootDir","preferredRegion","middlewareConfig","middlewareConfigBase64","cacheHandler","getOptions","stringifiedPagePath","stringifiedCacheHandlerPath","buildInfo","_module","JSON","parse","Buffer","from","toString","route","nextEdgeApiFunction","stringify"],"mappings":"AACA,SAASA,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,gBAAgB,QAAQ,uBAAsB;AAYvD,MAAMC,yBACJ,SAASA;IACP,MAAM,EACJC,gBAAgB,EAChBC,IAAI,EACJC,OAAO,EACPC,eAAe,EACfC,kBAAkBC,sBAAsB,EACxCC,YAAY,EACb,GAA8B,IAAI,CAACC,UAAU;IAC9C,MAAMC,sBAAsBV,iBAAiB,IAAI,EAAEE;IACnD,MAAMS,8BAA8BH,eAChCR,iBAAiB,IAAI,EAAEQ,gBACvB;IACJ,MAAMI,YAAYb,mBAAmB,IAAI,CAACc,OAAO;IACjD,MAAMP,mBAAgCQ,KAAKC,KAAK,CAC9CC,OAAOC,IAAI,CAACV,wBAAwB,UAAUW,QAAQ;IAExDN,UAAUO,KAAK,GAAG;QAChBhB,MAAMA,QAAQ;QACdD;QACAG;QACAC;IACF;IACAM,UAAUQ,mBAAmB,GAAG;QAC9BjB,MAAMA,QAAQ;IAChB;IACAS,UAAUR,OAAO,GAAGA;IAEpB,OAAO,CAAC;;;;;QAKJ,EACEO,8BACI,CAAC,oCAAoC,EAAEA,6BAA6B,GACpE,uCACL;;4BAEmB,EAAED,oBAAoB;;;mDAGC,EAAEP,KAAK;;;;;;;;oBAQtC,EAAEW,KAAKO,SAAS,CAAClB,MAAM;sCACL,EAAEW,KAAKO,SAAS,CAAClB,MAAM;;;IAGzD,CAAC;AACH;AAEF,eAAeF,uBAAsB","ignoreList":[0]}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { getModuleBuildInfo } from '../get-module-build-info';
|
||||
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants';
|
||||
import { RouteKind } from '../../../../server/route-kind';
|
||||
import { normalizePagePath } from '../../../../shared/lib/page-path/normalize-page-path';
|
||||
import { loadEntrypoint } from '../../../load-entrypoint';
|
||||
/*
|
||||
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');
|
||||
}
|
||||
function getRouteModuleOptions(page) {
|
||||
const options = {
|
||||
definition: {
|
||||
kind: RouteKind.PAGES,
|
||||
page: normalizePagePath(page),
|
||||
pathname: page,
|
||||
// The following aren't used in production.
|
||||
bundlePath: '',
|
||||
filename: ''
|
||||
}
|
||||
};
|
||||
return options;
|
||||
}
|
||||
function getCacheHandlersSetup(cacheHandlersStringified, contextifyImportPath) {
|
||||
const cacheHandlers = JSON.parse(cacheHandlersStringified || '{}');
|
||||
const definedCacheHandlers = Object.entries(cacheHandlers).filter((entry)=>Boolean(entry[1]));
|
||||
const cacheHandlerImports = [];
|
||||
const cacheHandlerRegistration = [];
|
||||
for (const [index, [kind, handlerPath]] of definedCacheHandlers.entries()){
|
||||
const cacheHandlerVarName = `edgeCacheHandler_${index}`;
|
||||
const cacheHandlerImportPath = contextifyImportPath(handlerPath);
|
||||
cacheHandlerImports.push(`import ${cacheHandlerVarName} from ${JSON.stringify(cacheHandlerImportPath)}`);
|
||||
cacheHandlerRegistration.push(` cacheHandlers.setCacheHandler(${JSON.stringify(kind)}, ${cacheHandlerVarName})`);
|
||||
}
|
||||
return {
|
||||
cacheHandlerImports: cacheHandlerImports.join('\n') || '\n',
|
||||
cacheHandlerRegistration: cacheHandlerRegistration.join('\n') || '\n'
|
||||
};
|
||||
}
|
||||
const edgeSSRLoader = async function edgeSSRLoader() {
|
||||
const { page, absolutePagePath, absoluteAppPath, absoluteDocumentPath, absolute500Path, absoluteErrorPath, isServerComponent, appDirLoader: appDirLoaderBase64, pagesType, cacheHandler, cacheHandlers: cacheHandlersStringified, preferredRegion, middlewareConfig: middlewareConfigBase64 } = this.getOptions();
|
||||
const cacheHandlersSetup = getCacheHandlersSetup(cacheHandlersStringified, (handlerPath)=>this.utils.contextify(this.context || this.rootContext, handlerPath));
|
||||
const incrementalCacheHandler = cacheHandler ? this.utils.contextify(this.context || this.rootContext, cacheHandler) : null;
|
||||
const middlewareConfig = JSON.parse(Buffer.from(middlewareConfigBase64, 'base64').toString());
|
||||
const appDirLoader = Buffer.from(appDirLoaderBase64 || '', 'base64').toString();
|
||||
const isAppDir = pagesType === 'app';
|
||||
const buildInfo = getModuleBuildInfo(this._module);
|
||||
buildInfo.nextEdgeSSR = {
|
||||
isServerComponent,
|
||||
page: page,
|
||||
isAppDir
|
||||
};
|
||||
buildInfo.route = {
|
||||
page,
|
||||
absolutePagePath,
|
||||
preferredRegion,
|
||||
middlewareConfig
|
||||
};
|
||||
const pagePath = this.utils.contextify(this.context || this.rootContext, absolutePagePath);
|
||||
const appPath = absoluteAppPath ? this.utils.contextify(this.context || this.rootContext, swapDistFolderWithEsmDistFolder(absoluteAppPath)) : '';
|
||||
const errorPath = absoluteErrorPath ? this.utils.contextify(this.context || this.rootContext, swapDistFolderWithEsmDistFolder(absoluteErrorPath)) : '';
|
||||
const documentPath = absoluteDocumentPath ? this.utils.contextify(this.context || this.rootContext, swapDistFolderWithEsmDistFolder(absoluteDocumentPath)) : '';
|
||||
const userland500Path = absolute500Path ? this.utils.contextify(this.context || this.rootContext, swapDistFolderWithEsmDistFolder(absolute500Path)) : null;
|
||||
const stringifiedPagePath = JSON.stringify(pagePath);
|
||||
const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}${isAppDir ? `?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}` : ''}`;
|
||||
if (isAppDir) {
|
||||
return await loadEntrypoint('edge-ssr-app', {
|
||||
VAR_USERLAND: pageModPath,
|
||||
VAR_PAGE: page
|
||||
}, cacheHandlersSetup, {
|
||||
incrementalCacheHandler
|
||||
});
|
||||
} else {
|
||||
return await loadEntrypoint('edge-ssr', {
|
||||
VAR_USERLAND: pageModPath,
|
||||
VAR_DEFINITION_PATHNAME: page,
|
||||
VAR_MODULE_DOCUMENT: documentPath,
|
||||
VAR_MODULE_APP: appPath,
|
||||
VAR_MODULE_GLOBAL_ERROR: errorPath
|
||||
}, {
|
||||
pageRouteModuleOptions: JSON.stringify(getRouteModuleOptions(page)),
|
||||
errorRouteModuleOptions: JSON.stringify(getRouteModuleOptions('/_error')),
|
||||
user500RouteModuleOptions: JSON.stringify(getRouteModuleOptions('/500')),
|
||||
...cacheHandlersSetup ?? {}
|
||||
}, {
|
||||
userland500Page: userland500Path,
|
||||
incrementalCacheHandler
|
||||
});
|
||||
}
|
||||
};
|
||||
export default edgeSSRLoader;
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
export default function nextErrorBrowserBinaryLoader() {
|
||||
const { resourcePath, rootContext } = this;
|
||||
const relativePath = resourcePath.slice(rootContext.length + 1);
|
||||
throw Object.defineProperty(new Error(`Node.js binary module ./${relativePath} is not supported in the browser. Please only use the module on server side`), "__NEXT_ERROR_CODE", {
|
||||
value: "E79",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=next-error-browser-binary-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-error-browser-binary-loader.ts"],"sourcesContent":["import type { webpack } from 'next/dist/compiled/webpack/webpack'\n\nexport default function nextErrorBrowserBinaryLoader(\n this: webpack.LoaderContext<any>\n) {\n const { resourcePath, rootContext } = this\n const relativePath = resourcePath.slice(rootContext.length + 1)\n throw new Error(\n `Node.js binary module ./${relativePath} is not supported in the browser. Please only use the module on server side`\n )\n}\n"],"names":["nextErrorBrowserBinaryLoader","resourcePath","rootContext","relativePath","slice","length","Error"],"mappings":"AAEA,eAAe,SAASA;IAGtB,MAAM,EAAEC,YAAY,EAAEC,WAAW,EAAE,GAAG,IAAI;IAC1C,MAAMC,eAAeF,aAAaG,KAAK,CAACF,YAAYG,MAAM,GAAG;IAC7D,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,wBAAwB,EAAEH,aAAa,2EAA2E,CAAC,GADhH,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF","ignoreList":[0]}
|
||||
Generated
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
function nextFlightActionEntryLoader() {
|
||||
const { actions } = this.getOptions();
|
||||
const actionList = JSON.parse(actions);
|
||||
const individualActions = actionList.map(([path, actionsFromModule])=>{
|
||||
return actionsFromModule.map(({ id, exportedName })=>{
|
||||
return [
|
||||
id,
|
||||
path,
|
||||
exportedName
|
||||
];
|
||||
});
|
||||
}).flat();
|
||||
return `
|
||||
${individualActions.map(([id, path, exportedName])=>{
|
||||
// Re-export the same functions from the original module path as action IDs.
|
||||
return `export { ${exportedName} as "${id}" } from ${JSON.stringify(path)}`;
|
||||
}).join('\n')}
|
||||
`;
|
||||
}
|
||||
export default nextFlightActionEntryLoader;
|
||||
|
||||
//# sourceMappingURL=next-flight-action-entry-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-action-entry-loader.ts"],"sourcesContent":["import type { webpack } from 'next/dist/compiled/webpack/webpack'\n\nexport type NextFlightActionEntryLoaderOptions = {\n actions: string\n}\n\nexport type FlightActionEntryLoaderActions = [\n path: string,\n actions: { id: string; exportedName?: string; filename?: string }[],\n][]\n\nfunction nextFlightActionEntryLoader(\n this: webpack.LoaderContext<NextFlightActionEntryLoaderOptions>\n) {\n const { actions }: NextFlightActionEntryLoaderOptions = this.getOptions()\n\n const actionList = JSON.parse(actions) as FlightActionEntryLoaderActions\n const individualActions = actionList\n .map(([path, actionsFromModule]) => {\n return actionsFromModule.map(({ id, exportedName }) => {\n return [id, path, exportedName] as const\n })\n })\n .flat()\n\n return `\n${individualActions\n .map(([id, path, exportedName]) => {\n // Re-export the same functions from the original module path as action IDs.\n return `export { ${exportedName} as \"${id}\" } from ${JSON.stringify(path)}`\n })\n .join('\\n')}\n`\n}\n\nexport default nextFlightActionEntryLoader\n"],"names":["nextFlightActionEntryLoader","actions","getOptions","actionList","JSON","parse","individualActions","map","path","actionsFromModule","id","exportedName","flat","stringify","join"],"mappings":"AAWA,SAASA;IAGP,MAAM,EAAEC,OAAO,EAAE,GAAuC,IAAI,CAACC,UAAU;IAEvE,MAAMC,aAAaC,KAAKC,KAAK,CAACJ;IAC9B,MAAMK,oBAAoBH,WACvBI,GAAG,CAAC,CAAC,CAACC,MAAMC,kBAAkB;QAC7B,OAAOA,kBAAkBF,GAAG,CAAC,CAAC,EAAEG,EAAE,EAAEC,YAAY,EAAE;YAChD,OAAO;gBAACD;gBAAIF;gBAAMG;aAAa;QACjC;IACF,GACCC,IAAI;IAEP,OAAO,CAAC;AACV,EAAEN,kBACCC,GAAG,CAAC,CAAC,CAACG,IAAIF,MAAMG,aAAa;QAC5B,4EAA4E;QAC5E,OAAO,CAAC,SAAS,EAAEA,aAAa,KAAK,EAAED,GAAG,SAAS,EAAEN,KAAKS,SAAS,CAACL,OAAO;IAC7E,GACCM,IAAI,CAAC,MAAM;AACd,CAAC;AACD;AAEA,eAAed,4BAA2B","ignoreList":[0]}
|
||||
Generated
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
import { BARREL_OPTIMIZATION_PREFIX, RSC_MODULE_TYPES } from '../../../shared/lib/constants';
|
||||
import { getModuleBuildInfo } from './get-module-build-info';
|
||||
import { regexCSS } from './utils';
|
||||
export default function transformSource() {
|
||||
let { modules, server } = this.getOptions();
|
||||
const isServer = server === 'true';
|
||||
if (!Array.isArray(modules)) {
|
||||
modules = modules ? [
|
||||
modules
|
||||
] : [];
|
||||
}
|
||||
const code = modules.map((x)=>JSON.parse(x))// Filter out CSS files in the SSR compilation
|
||||
.filter(({ request })=>isServer ? !regexCSS.test(request) : true).map(({ request, ids })=>{
|
||||
const importPath = JSON.stringify(request.startsWith(BARREL_OPTIMIZATION_PREFIX) ? request.replace(':', '!=!') : request);
|
||||
// When we cannot determine the export names, we use eager mode to include the whole module.
|
||||
// Otherwise, we use eager mode with webpackExports to only include the necessary exports.
|
||||
// If we have '*' in the ids, we include all the imports
|
||||
if (ids.length === 0 || ids.includes('*')) {
|
||||
return `import(/* webpackMode: "eager" */ ${importPath});\n`;
|
||||
} else {
|
||||
return `import(/* webpackMode: "eager", webpackExports: ${JSON.stringify(ids)} */ ${importPath});\n`;
|
||||
}
|
||||
}).join(';\n');
|
||||
const buildInfo = getModuleBuildInfo(this._module);
|
||||
buildInfo.rsc = {
|
||||
type: RSC_MODULE_TYPES.client
|
||||
};
|
||||
if (process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN) {
|
||||
const rscModuleInformationJson = JSON.stringify(buildInfo.rsc);
|
||||
return `/* __rspack_internal_rsc_module_information_do_not_use__ ${rscModuleInformationJson} */\n` + code;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=next-flight-client-entry-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-client-entry-loader.ts"],"sourcesContent":["import type { webpack } from 'next/dist/compiled/webpack/webpack'\nimport {\n BARREL_OPTIMIZATION_PREFIX,\n RSC_MODULE_TYPES,\n} from '../../../shared/lib/constants'\nimport { getModuleBuildInfo } from './get-module-build-info'\nimport { regexCSS } from './utils'\n\n/**\n * { [client import path]: [exported names] }\n */\nexport type ClientComponentImports = Record<string, Set<string>>\nexport type CssImports = Record<string, string[]>\n\nexport type NextFlightClientEntryLoaderOptions = {\n modules: string[] | string\n /** This is transmitted as a string to `getOptions` */\n server: boolean | 'true' | 'false'\n}\n\nexport type FlightClientEntryModuleItem = {\n // module path\n request: string\n // imported identifiers\n ids: string[]\n}\n\nexport default function transformSource(\n this: webpack.LoaderContext<NextFlightClientEntryLoaderOptions>\n) {\n let { modules, server } = this.getOptions()\n const isServer = server === 'true'\n\n if (!Array.isArray(modules)) {\n modules = modules ? [modules] : []\n }\n\n const code = modules\n .map((x) => JSON.parse(x) as FlightClientEntryModuleItem)\n // Filter out CSS files in the SSR compilation\n .filter(({ request }) => (isServer ? !regexCSS.test(request) : true))\n .map(({ request, ids }: FlightClientEntryModuleItem) => {\n const importPath = JSON.stringify(\n request.startsWith(BARREL_OPTIMIZATION_PREFIX)\n ? request.replace(':', '!=!')\n : request\n )\n\n // When we cannot determine the export names, we use eager mode to include the whole module.\n // Otherwise, we use eager mode with webpackExports to only include the necessary exports.\n // If we have '*' in the ids, we include all the imports\n if (ids.length === 0 || ids.includes('*')) {\n return `import(/* webpackMode: \"eager\" */ ${importPath});\\n`\n } else {\n return `import(/* webpackMode: \"eager\", webpackExports: ${JSON.stringify(\n ids\n )} */ ${importPath});\\n`\n }\n })\n .join(';\\n')\n\n const buildInfo = getModuleBuildInfo(this._module!)\n\n buildInfo.rsc = {\n type: RSC_MODULE_TYPES.client,\n }\n if (process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN) {\n const rscModuleInformationJson = JSON.stringify(buildInfo.rsc)\n return (\n `/* __rspack_internal_rsc_module_information_do_not_use__ ${rscModuleInformationJson} */\\n` +\n code\n )\n }\n\n return code\n}\n"],"names":["BARREL_OPTIMIZATION_PREFIX","RSC_MODULE_TYPES","getModuleBuildInfo","regexCSS","transformSource","modules","server","getOptions","isServer","Array","isArray","code","map","x","JSON","parse","filter","request","test","ids","importPath","stringify","startsWith","replace","length","includes","join","buildInfo","_module","rsc","type","client","process","env","BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN","rscModuleInformationJson"],"mappings":"AACA,SACEA,0BAA0B,EAC1BC,gBAAgB,QACX,gCAA+B;AACtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,QAAQ,QAAQ,UAAS;AAqBlC,eAAe,SAASC;IAGtB,IAAI,EAAEC,OAAO,EAAEC,MAAM,EAAE,GAAG,IAAI,CAACC,UAAU;IACzC,MAAMC,WAAWF,WAAW;IAE5B,IAAI,CAACG,MAAMC,OAAO,CAACL,UAAU;QAC3BA,UAAUA,UAAU;YAACA;SAAQ,GAAG,EAAE;IACpC;IAEA,MAAMM,OAAON,QACVO,GAAG,CAAC,CAACC,IAAMC,KAAKC,KAAK,CAACF,GACvB,8CAA8C;KAC7CG,MAAM,CAAC,CAAC,EAAEC,OAAO,EAAE,GAAMT,WAAW,CAACL,SAASe,IAAI,CAACD,WAAW,MAC9DL,GAAG,CAAC,CAAC,EAAEK,OAAO,EAAEE,GAAG,EAA+B;QACjD,MAAMC,aAAaN,KAAKO,SAAS,CAC/BJ,QAAQK,UAAU,CAACtB,8BACfiB,QAAQM,OAAO,CAAC,KAAK,SACrBN;QAGN,4FAA4F;QAC5F,0FAA0F;QAC1F,wDAAwD;QACxD,IAAIE,IAAIK,MAAM,KAAK,KAAKL,IAAIM,QAAQ,CAAC,MAAM;YACzC,OAAO,CAAC,kCAAkC,EAAEL,WAAW,IAAI,CAAC;QAC9D,OAAO;YACL,OAAO,CAAC,gDAAgD,EAAEN,KAAKO,SAAS,CACtEF,KACA,IAAI,EAAEC,WAAW,IAAI,CAAC;QAC1B;IACF,GACCM,IAAI,CAAC;IAER,MAAMC,YAAYzB,mBAAmB,IAAI,CAAC0B,OAAO;IAEjDD,UAAUE,GAAG,GAAG;QACdC,MAAM7B,iBAAiB8B,MAAM;IAC/B;IACA,IAAIC,QAAQC,GAAG,CAACC,kCAAkC,EAAE;QAClD,MAAMC,2BAA2BrB,KAAKO,SAAS,CAACM,UAAUE,GAAG;QAC7D,OACE,CAAC,yDAAyD,EAAEM,yBAAyB,KAAK,CAAC,GAC3FxB;IAEJ;IAEA,OAAOA;AACT","ignoreList":[0]}
|
||||
Generated
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
import { getRSCModuleInformation } from '../../analysis/get-page-static-info';
|
||||
import { getModuleBuildInfo } from './get-module-build-info';
|
||||
const flightClientModuleLoader = function transformSource(source, sourceMap) {
|
||||
// Avoid buffer to be consumed
|
||||
if (typeof source !== 'string') {
|
||||
throw Object.defineProperty(new Error('Expected source to have been transformed to a string.'), "__NEXT_ERROR_CODE", {
|
||||
value: "E429",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
if (!this._module) {
|
||||
return source;
|
||||
}
|
||||
// Assign the RSC meta information to buildInfo.
|
||||
const buildInfo = getModuleBuildInfo(this._module);
|
||||
buildInfo.rsc = getRSCModuleInformation(source, false);
|
||||
let prefix = '';
|
||||
if (process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN) {
|
||||
const rscModuleInformationJson = JSON.stringify(buildInfo.rsc);
|
||||
prefix = `/* __rspack_internal_rsc_module_information_do_not_use__ ${rscModuleInformationJson} */\n`;
|
||||
source = prefix + source;
|
||||
}
|
||||
// This is a server action entry module in the client layer. We need to
|
||||
// create re-exports of "virtual modules" to expose the reference IDs to the
|
||||
// client separately so they won't be always in the same one module which is
|
||||
// not splittable. This server action module tree shaking is only applied in
|
||||
// production mode. In development mode, we want to preserve the original
|
||||
// modules (as transformed by SWC) to ensure that source mapping works.
|
||||
if (buildInfo.rsc.actionIds && process.env.NODE_ENV === 'production') {
|
||||
return prefix + Object.entries(buildInfo.rsc.actionIds).map(([id, exportInfo])=>{
|
||||
// exportInfo can be a string (legacy) or object with name
|
||||
const name = typeof exportInfo === 'string' ? exportInfo : exportInfo.name;
|
||||
return `export { ${name} } from 'next-flight-server-reference-proxy-loader?id=${id}&name=${name}!'`;
|
||||
}).join('\n');
|
||||
}
|
||||
return this.callback(null, source, sourceMap);
|
||||
};
|
||||
export default flightClientModuleLoader;
|
||||
|
||||
//# sourceMappingURL=next-flight-client-module-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-client-module-loader.ts"],"sourcesContent":["import type { webpack } from 'next/dist/compiled/webpack/webpack'\nimport { getRSCModuleInformation } from '../../analysis/get-page-static-info'\nimport { getModuleBuildInfo } from './get-module-build-info'\n\nconst flightClientModuleLoader: webpack.LoaderDefinitionFunction =\n function transformSource(this, source: string, sourceMap: any) {\n // Avoid buffer to be consumed\n if (typeof source !== 'string') {\n throw new Error('Expected source to have been transformed to a string.')\n }\n\n if (!this._module) {\n return source\n }\n // Assign the RSC meta information to buildInfo.\n const buildInfo = getModuleBuildInfo(this._module)\n buildInfo.rsc = getRSCModuleInformation(source, false)\n let prefix = ''\n if (process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN) {\n const rscModuleInformationJson = JSON.stringify(buildInfo.rsc)\n prefix = `/* __rspack_internal_rsc_module_information_do_not_use__ ${rscModuleInformationJson} */\\n`\n source = prefix + source\n }\n\n // This is a server action entry module in the client layer. We need to\n // create re-exports of \"virtual modules\" to expose the reference IDs to the\n // client separately so they won't be always in the same one module which is\n // not splittable. This server action module tree shaking is only applied in\n // production mode. In development mode, we want to preserve the original\n // modules (as transformed by SWC) to ensure that source mapping works.\n if (buildInfo.rsc.actionIds && process.env.NODE_ENV === 'production') {\n return (\n prefix +\n Object.entries(buildInfo.rsc.actionIds)\n .map(([id, exportInfo]) => {\n // exportInfo can be a string (legacy) or object with name\n const name =\n typeof exportInfo === 'string' ? exportInfo : exportInfo.name\n return `export { ${name} } from 'next-flight-server-reference-proxy-loader?id=${id}&name=${name}!'`\n })\n .join('\\n')\n )\n }\n\n return this.callback(null, source, sourceMap)\n }\n\nexport default flightClientModuleLoader\n"],"names":["getRSCModuleInformation","getModuleBuildInfo","flightClientModuleLoader","transformSource","source","sourceMap","Error","_module","buildInfo","rsc","prefix","process","env","BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN","rscModuleInformationJson","JSON","stringify","actionIds","NODE_ENV","Object","entries","map","id","exportInfo","name","join","callback"],"mappings":"AACA,SAASA,uBAAuB,QAAQ,sCAAqC;AAC7E,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,MAAMC,2BACJ,SAASC,gBAAsBC,MAAc,EAAEC,SAAc;IAC3D,8BAA8B;IAC9B,IAAI,OAAOD,WAAW,UAAU;QAC9B,MAAM,qBAAkE,CAAlE,IAAIE,MAAM,0DAAV,qBAAA;mBAAA;wBAAA;0BAAA;QAAiE;IACzE;IAEA,IAAI,CAAC,IAAI,CAACC,OAAO,EAAE;QACjB,OAAOH;IACT;IACA,gDAAgD;IAChD,MAAMI,YAAYP,mBAAmB,IAAI,CAACM,OAAO;IACjDC,UAAUC,GAAG,GAAGT,wBAAwBI,QAAQ;IAChD,IAAIM,SAAS;IACb,IAAIC,QAAQC,GAAG,CAACC,kCAAkC,EAAE;QAClD,MAAMC,2BAA2BC,KAAKC,SAAS,CAACR,UAAUC,GAAG;QAC7DC,SAAS,CAAC,yDAAyD,EAAEI,yBAAyB,KAAK,CAAC;QACpGV,SAASM,SAASN;IACpB;IAEA,uEAAuE;IACvE,4EAA4E;IAC5E,4EAA4E;IAC5E,4EAA4E;IAC5E,yEAAyE;IACzE,uEAAuE;IACvE,IAAII,UAAUC,GAAG,CAACQ,SAAS,IAAIN,QAAQC,GAAG,CAACM,QAAQ,KAAK,cAAc;QACpE,OACER,SACAS,OAAOC,OAAO,CAACZ,UAAUC,GAAG,CAACQ,SAAS,EACnCI,GAAG,CAAC,CAAC,CAACC,IAAIC,WAAW;YACpB,0DAA0D;YAC1D,MAAMC,OACJ,OAAOD,eAAe,WAAWA,aAAaA,WAAWC,IAAI;YAC/D,OAAO,CAAC,SAAS,EAAEA,KAAK,sDAAsD,EAAEF,GAAG,MAAM,EAAEE,KAAK,EAAE,CAAC;QACrG,GACCC,IAAI,CAAC;IAEZ;IAEA,OAAO,IAAI,CAACC,QAAQ,CAAC,MAAMtB,QAAQC;AACrC;AAEF,eAAeH,yBAAwB","ignoreList":[0]}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 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';
|
||||
const NextServerCSSLoader = function(content) {
|
||||
this.cacheable && this.cacheable();
|
||||
const options = this.getOptions();
|
||||
let isCSSModule = options.cssModules;
|
||||
// Only add the checksum during development.
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// This check is only for backwards compatibility.
|
||||
// TODO: Remove this in the next major version (next 14)
|
||||
if (isCSSModule === undefined) {
|
||||
this.emitWarning(Object.defineProperty(new Error("No 'cssModules' option was found for the next-flight-css-loader plugin."), "__NEXT_ERROR_CODE", {
|
||||
value: "E8",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
}));
|
||||
isCSSModule = this.resourcePath.match(/\.module\.(css|sass|scss)$/) !== null;
|
||||
}
|
||||
const checksum = crypto.createHash('sha1').update(typeof content === 'string' ? Buffer.from(content) : content).digest().toString('hex').substring(0, 12);
|
||||
if (isCSSModule) {
|
||||
return `\
|
||||
${content}
|
||||
module.exports.__checksum = ${JSON.stringify(checksum)}
|
||||
`;
|
||||
}
|
||||
// Server CSS imports are always available for HMR, so we attach
|
||||
// `module.hot.accept()` to the generated module.
|
||||
const hmrCode = 'if (module.hot) { module.hot.accept() }';
|
||||
return `\
|
||||
export default ${JSON.stringify(checksum)}
|
||||
${hmrCode}
|
||||
`;
|
||||
}
|
||||
return content;
|
||||
};
|
||||
export default NextServerCSSLoader;
|
||||
|
||||
//# sourceMappingURL=next-flight-css-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-css-loader.ts"],"sourcesContent":["/**\n * For server-side CSS imports, we need to ignore the actual module content but\n * still trigger the hot-reloading diff mechanism. So here we put the content\n * inside a comment.\n */\n\nimport crypto from 'crypto'\nimport type webpack from 'webpack'\n\ntype NextServerCSSLoaderOptions = {\n cssModules: boolean\n}\n\nconst NextServerCSSLoader: webpack.LoaderDefinitionFunction<NextServerCSSLoaderOptions> =\n function (content) {\n this.cacheable && this.cacheable()\n const options = this.getOptions()\n let isCSSModule = options.cssModules\n\n // Only add the checksum during development.\n if (process.env.NODE_ENV !== 'production') {\n // This check is only for backwards compatibility.\n // TODO: Remove this in the next major version (next 14)\n if (isCSSModule === undefined) {\n this.emitWarning(\n new Error(\n \"No 'cssModules' option was found for the next-flight-css-loader plugin.\"\n )\n )\n isCSSModule =\n this.resourcePath.match(/\\.module\\.(css|sass|scss)$/) !== null\n }\n const checksum = crypto\n .createHash('sha1')\n .update(typeof content === 'string' ? Buffer.from(content) : content)\n .digest()\n .toString('hex')\n .substring(0, 12)\n\n if (isCSSModule) {\n return `\\\n${content}\nmodule.exports.__checksum = ${JSON.stringify(checksum)}\n`\n }\n\n // Server CSS imports are always available for HMR, so we attach\n // `module.hot.accept()` to the generated module.\n const hmrCode = 'if (module.hot) { module.hot.accept() }'\n\n return `\\\nexport default ${JSON.stringify(checksum)}\n${hmrCode}\n`\n }\n\n return content\n }\n\nexport default NextServerCSSLoader\n"],"names":["crypto","NextServerCSSLoader","content","cacheable","options","getOptions","isCSSModule","cssModules","process","env","NODE_ENV","undefined","emitWarning","Error","resourcePath","match","checksum","createHash","update","Buffer","from","digest","toString","substring","JSON","stringify","hmrCode"],"mappings":"AAAA;;;;CAIC,GAED,OAAOA,YAAY,SAAQ;AAO3B,MAAMC,sBACJ,SAAUC,OAAO;IACf,IAAI,CAACC,SAAS,IAAI,IAAI,CAACA,SAAS;IAChC,MAAMC,UAAU,IAAI,CAACC,UAAU;IAC/B,IAAIC,cAAcF,QAAQG,UAAU;IAEpC,4CAA4C;IAC5C,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;QACzC,kDAAkD;QAClD,wDAAwD;QACxD,IAAIJ,gBAAgBK,WAAW;YAC7B,IAAI,CAACC,WAAW,CACd,qBAEC,CAFD,IAAIC,MACF,4EADF,qBAAA;uBAAA;4BAAA;8BAAA;YAEA;YAEFP,cACE,IAAI,CAACQ,YAAY,CAACC,KAAK,CAAC,kCAAkC;QAC9D;QACA,MAAMC,WAAWhB,OACdiB,UAAU,CAAC,QACXC,MAAM,CAAC,OAAOhB,YAAY,WAAWiB,OAAOC,IAAI,CAAClB,WAAWA,SAC5DmB,MAAM,GACNC,QAAQ,CAAC,OACTC,SAAS,CAAC,GAAG;QAEhB,IAAIjB,aAAa;YACf,OAAO,CAAC;AAChB,EAAEJ,QAAQ;4BACkB,EAAEsB,KAAKC,SAAS,CAACT,UAAU;AACvD,CAAC;QACK;QAEA,gEAAgE;QAChE,iDAAiD;QACjD,MAAMU,UAAU;QAEhB,OAAO,CAAC;eACC,EAAEF,KAAKC,SAAS,CAACT,UAAU;AAC1C,EAAEU,QAAQ;AACV,CAAC;IACG;IAEA,OAAOxB;AACT;AAEF,eAAeD,oBAAmB","ignoreList":[0]}
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
// This file must be bundled in the app's client layer, it shouldn't be directly
|
||||
// imported by the server.
|
||||
export { callServer } from 'next/dist/client/app-call-server';
|
||||
export { findSourceMapURL } from 'next/dist/client/app-find-source-map-url';
|
||||
// A noop wrapper to let the Flight client create the server reference.
|
||||
// See also: https://github.com/facebook/react/pull/26632
|
||||
// eslint-disable-next-line import/no-extraneous-dependencies
|
||||
export { createServerReference } from 'react-server-dom-webpack/client';
|
||||
|
||||
//# sourceMappingURL=action-client-wrapper.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-flight-loader/action-client-wrapper.ts"],"sourcesContent":["// This file must be bundled in the app's client layer, it shouldn't be directly\n// imported by the server.\n\nexport { callServer } from 'next/dist/client/app-call-server'\nexport { findSourceMapURL } from 'next/dist/client/app-find-source-map-url'\n\n// A noop wrapper to let the Flight client create the server reference.\n// See also: https://github.com/facebook/react/pull/26632\n// eslint-disable-next-line import/no-extraneous-dependencies\nexport { createServerReference } from 'react-server-dom-webpack/client'\n"],"names":["callServer","findSourceMapURL","createServerReference"],"mappings":"AAAA,gFAAgF;AAChF,0BAA0B;AAE1B,SAASA,UAAU,QAAQ,mCAAkC;AAC7D,SAASC,gBAAgB,QAAQ,2CAA0C;AAE3E,uEAAuE;AACvE,yDAAyD;AACzD,6DAA6D;AAC7D,SAASC,qBAAqB,QAAQ,kCAAiC","ignoreList":[0]}
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
// This function ensures that all the exported values are valid server actions,
|
||||
// during the runtime. By definition all actions are required to be async
|
||||
// functions, but here we can only check that they are functions.
|
||||
export function ensureServerEntryExports(actions) {
|
||||
for(let i = 0; i < actions.length; i++){
|
||||
const action = actions[i];
|
||||
if (typeof action !== 'function') {
|
||||
throw Object.defineProperty(new Error(`A "use server" file can only export async functions, found ${typeof action}.\nRead more: https://nextjs.org/docs/messages/invalid-use-server-value`), "__NEXT_ERROR_CODE", {
|
||||
value: "E352",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=action-validate.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-flight-loader/action-validate.ts"],"sourcesContent":["// This function ensures that all the exported values are valid server actions,\n// during the runtime. By definition all actions are required to be async\n// functions, but here we can only check that they are functions.\nexport function ensureServerEntryExports(actions: any[]) {\n for (let i = 0; i < actions.length; i++) {\n const action = actions[i]\n if (typeof action !== 'function') {\n throw new Error(\n `A \"use server\" file can only export async functions, found ${typeof action}.\\nRead more: https://nextjs.org/docs/messages/invalid-use-server-value`\n )\n }\n }\n}\n"],"names":["ensureServerEntryExports","actions","i","length","action","Error"],"mappings":"AAAA,+EAA+E;AAC/E,yEAAyE;AACzE,iEAAiE;AACjE,OAAO,SAASA,yBAAyBC,OAAc;IACrD,IAAK,IAAIC,IAAI,GAAGA,IAAID,QAAQE,MAAM,EAAED,IAAK;QACvC,MAAME,SAASH,OAAO,CAACC,EAAE;QACzB,IAAI,OAAOE,WAAW,YAAY;YAChC,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,2DAA2D,EAAE,OAAOD,OAAO,uEAAuE,CAAC,GADhJ,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;IACF;AACF","ignoreList":[0]}
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export { cache } from '../../../../server/use-cache/use-cache-wrapper';
|
||||
|
||||
//# sourceMappingURL=cache-wrapper.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-flight-loader/cache-wrapper.ts"],"sourcesContent":["export { cache } from '../../../../server/use-cache/use-cache-wrapper'\n"],"names":["cache"],"mappings":"AAAA,SAASA,KAAK,QAAQ,iDAAgD","ignoreList":[0]}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
import { ModuleFilenameHelpers } from 'next/dist/compiled/webpack/webpack';
|
||||
import { RSC_MOD_REF_PROXY_ALIAS } from '../../../../lib/constants';
|
||||
import { BARREL_OPTIMIZATION_PREFIX, RSC_MODULE_TYPES } from '../../../../shared/lib/constants';
|
||||
import { warnOnce } from '../../../../shared/lib/utils/warn-once';
|
||||
import { getRSCModuleInformation } from '../../../analysis/get-page-static-info';
|
||||
import { formatBarrelOptimizedResource } from '../../utils';
|
||||
import { getModuleBuildInfo } from '../get-module-build-info';
|
||||
const noopHeadPath = require.resolve('next/dist/client/components/noop-head');
|
||||
// For edge runtime it will be aliased to esm version by webpack
|
||||
const MODULE_PROXY_PATH = 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy';
|
||||
export function getAssumedSourceType(mod, sourceType) {
|
||||
var _buildInfo_rsc, _buildInfo_rsc1;
|
||||
const buildInfo = getModuleBuildInfo(mod);
|
||||
const detectedClientEntryType = buildInfo == null ? void 0 : (_buildInfo_rsc = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc.clientEntryType;
|
||||
const clientRefs = (buildInfo == null ? void 0 : (_buildInfo_rsc1 = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc1.clientRefs) || [];
|
||||
// It's tricky to detect the type of a client boundary, but we should always
|
||||
// use the `module` type when we can, to support `export *` and `export from`
|
||||
// syntax in other modules that import this client boundary.
|
||||
if (sourceType === 'auto') {
|
||||
if (detectedClientEntryType === 'auto') {
|
||||
if (clientRefs.length === 0) {
|
||||
// If there's zero export detected in the client boundary, and it's the
|
||||
// `auto` type, we can safely assume it's a CJS module because it doesn't
|
||||
// have ESM exports.
|
||||
return 'commonjs';
|
||||
} else if (!clientRefs.includes('*')) {
|
||||
// Otherwise, we assume it's an ESM module.
|
||||
return 'module';
|
||||
}
|
||||
} else if (detectedClientEntryType === 'cjs') {
|
||||
return 'commonjs';
|
||||
}
|
||||
}
|
||||
return sourceType;
|
||||
}
|
||||
export default function transformSource(source, sourceMap) {
|
||||
var _module_matchResource, _buildInfo_rsc, _buildInfo_rsc1;
|
||||
// Avoid buffer to be consumed
|
||||
if (typeof source !== 'string') {
|
||||
throw Object.defineProperty(new Error('Expected source to have been transformed to a string.'), "__NEXT_ERROR_CODE", {
|
||||
value: "E429",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
const module = this._module;
|
||||
// Assign the RSC meta information to buildInfo.
|
||||
// Exclude next internal files which are not marked as client files
|
||||
const buildInfo = getModuleBuildInfo(module);
|
||||
buildInfo.rsc = getRSCModuleInformation(source, true);
|
||||
let prefix = '';
|
||||
if (process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN) {
|
||||
const rscModuleInformationJson = JSON.stringify(buildInfo.rsc);
|
||||
prefix = `/* __rspack_internal_rsc_module_information_do_not_use__ ${rscModuleInformationJson} */\n`;
|
||||
source = prefix + source;
|
||||
}
|
||||
prefix += `// This file is generated by the Webpack next-flight-loader.\n`;
|
||||
// Resource key is the unique identifier for the resource. When RSC renders
|
||||
// a client module, that key is used to identify that module across all compiler
|
||||
// layers.
|
||||
//
|
||||
// Usually it's the module's file path + the export name (e.g. `foo.js#bar`).
|
||||
// But with Barrel Optimizations, one file can be splitted into multiple modules,
|
||||
// so when you import `foo.js#bar` and `foo.js#baz`, they are actually different
|
||||
// "foo.js" being created by the Barrel Loader (one only exports `bar`, the other
|
||||
// only exports `baz`).
|
||||
//
|
||||
// Because of that, we must add another query param to the resource key to
|
||||
// differentiate them.
|
||||
let resourceKey = this.resourcePath;
|
||||
if ((_module_matchResource = module.matchResource) == null ? void 0 : _module_matchResource.startsWith(BARREL_OPTIMIZATION_PREFIX)) {
|
||||
resourceKey = formatBarrelOptimizedResource(resourceKey, module.matchResource);
|
||||
}
|
||||
// A client boundary.
|
||||
if (((_buildInfo_rsc = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc.type) === RSC_MODULE_TYPES.client) {
|
||||
const assumedSourceType = getAssumedSourceType(module, sourceTypeFromModule(module));
|
||||
const clientRefs = buildInfo.rsc.clientRefs;
|
||||
const stringifiedResourceKey = JSON.stringify(resourceKey);
|
||||
if (assumedSourceType === 'module') {
|
||||
if (clientRefs.length === 0) {
|
||||
return this.callback(null, 'export {}');
|
||||
}
|
||||
if (clientRefs.includes('*')) {
|
||||
this.callback(Object.defineProperty(new Error(`It's currently unsupported to use "export *" in a client boundary. Please use named exports instead.`), "__NEXT_ERROR_CODE", {
|
||||
value: "E46",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
}));
|
||||
return;
|
||||
}
|
||||
let esmSource = prefix + `\
|
||||
import { registerClientReference } from "react-server-dom-webpack/server";
|
||||
`;
|
||||
for (const ref of clientRefs){
|
||||
if (ref === 'default') {
|
||||
esmSource += `export default registerClientReference(
|
||||
function() { throw new Error(${JSON.stringify(`Attempted to call the default \
|
||||
export of ${stringifiedResourceKey} from the server, but it's on the client. \
|
||||
It's not possible to invoke a client function from the server, it can only be \
|
||||
rendered as a Component or passed to props of a Client Component.`)}); },
|
||||
${stringifiedResourceKey},
|
||||
"default",
|
||||
);\n`;
|
||||
} else {
|
||||
esmSource += `export const ${ref} = registerClientReference(
|
||||
function() { throw new Error(${JSON.stringify(`Attempted to call ${ref}() from \
|
||||
the server but ${ref} is on the client. It's not possible to invoke a client \
|
||||
function from the server, it can only be rendered as a Component or passed to \
|
||||
props of a Client Component.`)}); },
|
||||
${stringifiedResourceKey},
|
||||
${JSON.stringify(ref)},
|
||||
);`;
|
||||
}
|
||||
}
|
||||
const compilation = this._compilation;
|
||||
const originalSourceURL = process.env.NEXT_RSPACK ? `webpack://_N_E/${this.utils.contextify(this.context || this.rootContext, this.resourcePath)}/__nextjs-internal-proxy.mjs` : ModuleFilenameHelpers.createFilename(module, {
|
||||
moduleFilenameTemplate: 'webpack://[namespace]/[resource-path]/__nextjs-internal-proxy.mjs',
|
||||
namespace: '_N_E'
|
||||
}, {
|
||||
requestShortener: compilation.requestShortener,
|
||||
chunkGraph: compilation.chunkGraph,
|
||||
hashFunction: compilation.outputOptions.hashFunction
|
||||
});
|
||||
return this.callback(null, esmSource, {
|
||||
version: 3,
|
||||
sources: [
|
||||
originalSourceURL
|
||||
],
|
||||
// minimal, parseable mappings
|
||||
mappings: 'AAAA',
|
||||
sourcesContent: [
|
||||
esmSource
|
||||
]
|
||||
});
|
||||
} else if (assumedSourceType === 'commonjs') {
|
||||
let cjsSource = prefix + `\
|
||||
const { createProxy } = require("${MODULE_PROXY_PATH}")
|
||||
|
||||
module.exports = createProxy(${stringifiedResourceKey})
|
||||
`;
|
||||
const compilation = this._compilation;
|
||||
const originalSourceURL = process.env.NEXT_RSPACK ? `webpack://_N_E/${this.utils.contextify(this.context || this.rootContext, this.resourcePath)}/__nextjs-internal-proxy.cjs` : ModuleFilenameHelpers.createFilename(module, {
|
||||
moduleFilenameTemplate: 'webpack://[namespace]/[resource-path]/__nextjs-internal-proxy.cjs',
|
||||
namespace: '_N_E'
|
||||
}, {
|
||||
requestShortener: compilation.requestShortener,
|
||||
chunkGraph: compilation.chunkGraph,
|
||||
hashFunction: compilation.outputOptions.hashFunction
|
||||
});
|
||||
return this.callback(null, cjsSource, {
|
||||
version: 3,
|
||||
sources: [
|
||||
originalSourceURL
|
||||
],
|
||||
// minimal, parseable mappings
|
||||
mappings: 'AAAA',
|
||||
sourcesContent: [
|
||||
cjsSource
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
if (((_buildInfo_rsc1 = buildInfo.rsc) == null ? void 0 : _buildInfo_rsc1.type) !== RSC_MODULE_TYPES.client) {
|
||||
if (noopHeadPath === this.resourcePath) {
|
||||
warnOnce(`Warning: You're using \`next/head\` inside the \`app\` directory, please migrate to the Metadata API. See https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#step-3-migrating-nexthead for more details.`);
|
||||
}
|
||||
}
|
||||
const replacedSource = source.replace(RSC_MOD_REF_PROXY_ALIAS, MODULE_PROXY_PATH);
|
||||
this.callback(null, replacedSource, sourceMap);
|
||||
}
|
||||
function sourceTypeFromModule(module) {
|
||||
const moduleType = module.type;
|
||||
switch(moduleType){
|
||||
case 'javascript/auto':
|
||||
return 'auto';
|
||||
case 'javascript/dynamic':
|
||||
return 'script';
|
||||
case 'javascript/esm':
|
||||
return 'module';
|
||||
default:
|
||||
throw Object.defineProperty(new Error('Unexpected module type ' + moduleType), "__NEXT_ERROR_CODE", {
|
||||
value: "E651",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */ import { createClientModuleProxy } from 'react-server-dom-webpack/server';
|
||||
// Re-assign to make it typed.
|
||||
export const createProxy = createClientModuleProxy;
|
||||
|
||||
//# sourceMappingURL=module-proxy.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-flight-loader/module-proxy.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport { createClientModuleProxy } from 'react-server-dom-webpack/server'\n\n// Re-assign to make it typed.\nexport const createProxy: (moduleId: string) => any = createClientModuleProxy\n"],"names":["createClientModuleProxy","createProxy"],"mappings":"AAAA,oDAAoD,GACpD,SAASA,uBAAuB,QAAQ,kCAAiC;AAEzE,8BAA8B;AAC9B,OAAO,MAAMC,cAAyCD,wBAAuB","ignoreList":[0]}
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */ export { registerServerReference } from 'react-server-dom-webpack/server';
|
||||
|
||||
//# sourceMappingURL=server-reference.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-flight-loader/server-reference.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nexport { registerServerReference } from 'react-server-dom-webpack/server'\n"],"names":["registerServerReference"],"mappings":"AAAA,oDAAoD,GACpD,SAASA,uBAAuB,QAAQ,kCAAiC","ignoreList":[0]}
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export { trackDynamicImport } from '../../../../server/app-render/module-loading/track-dynamic-import';
|
||||
|
||||
//# sourceMappingURL=track-dynamic-import.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-flight-loader/track-dynamic-import.ts"],"sourcesContent":["export { trackDynamicImport } from '../../../../server/app-render/module-loading/track-dynamic-import'\n"],"names":["trackDynamicImport"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,oEAAmE","ignoreList":[0]}
|
||||
Generated
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
// This is a virtual proxy loader that takes a Server Reference ID and a name,
|
||||
// creates a module that just re-exports the reference as that name.
|
||||
const flightServerReferenceProxyLoader = function transformSource() {
|
||||
const { id, name } = this.getOptions();
|
||||
// Both the import and the `createServerReference` call are marked as side
|
||||
// effect free:
|
||||
// - private-next-rsc-action-client-wrapper is matched as `sideEffects: false` in
|
||||
// the Webpack loader
|
||||
// - createServerReference is marked as /*#__PURE__*/
|
||||
//
|
||||
// Because of that, Webpack is able to concatenate the modules and inline the
|
||||
// reference IDs recursively directly into the module that uses them.
|
||||
return `\
|
||||
import { createServerReference, callServer, findSourceMapURL } from 'private-next-rsc-action-client-wrapper'
|
||||
export ${name === 'default' ? 'default' : `const ${name} =`} /*#__PURE__*/createServerReference(${JSON.stringify(id)}, callServer, undefined, findSourceMapURL, ${JSON.stringify(name)})`;
|
||||
};
|
||||
export default flightServerReferenceProxyLoader;
|
||||
|
||||
//# sourceMappingURL=next-flight-server-reference-proxy-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-flight-server-reference-proxy-loader.ts"],"sourcesContent":["import type { webpack } from 'next/dist/compiled/webpack/webpack'\n\n// This is a virtual proxy loader that takes a Server Reference ID and a name,\n// creates a module that just re-exports the reference as that name.\n\nconst flightServerReferenceProxyLoader: webpack.LoaderDefinitionFunction<{\n id: string\n name: string\n}> = function transformSource(this) {\n const { id, name } = this.getOptions()\n\n // Both the import and the `createServerReference` call are marked as side\n // effect free:\n // - private-next-rsc-action-client-wrapper is matched as `sideEffects: false` in\n // the Webpack loader\n // - createServerReference is marked as /*#__PURE__*/\n //\n // Because of that, Webpack is able to concatenate the modules and inline the\n // reference IDs recursively directly into the module that uses them.\n return `\\\nimport { createServerReference, callServer, findSourceMapURL } from 'private-next-rsc-action-client-wrapper'\nexport ${\n name === 'default' ? 'default' : `const ${name} =`\n } /*#__PURE__*/createServerReference(${JSON.stringify(id)}, callServer, undefined, findSourceMapURL, ${JSON.stringify(name)})`\n}\n\nexport default flightServerReferenceProxyLoader\n"],"names":["flightServerReferenceProxyLoader","transformSource","id","name","getOptions","JSON","stringify"],"mappings":"AAEA,8EAA8E;AAC9E,oEAAoE;AAEpE,MAAMA,mCAGD,SAASC;IACZ,MAAM,EAAEC,EAAE,EAAEC,IAAI,EAAE,GAAG,IAAI,CAACC,UAAU;IAEpC,0EAA0E;IAC1E,eAAe;IACf,iFAAiF;IACjF,uBAAuB;IACvB,qDAAqD;IACrD,EAAE;IACF,6EAA6E;IAC7E,qEAAqE;IACrE,OAAO,CAAC;;OAEH,EACHD,SAAS,YAAY,YAAY,CAAC,MAAM,EAAEA,KAAK,EAAE,CAAC,CACnD,oCAAoC,EAAEE,KAAKC,SAAS,CAACJ,IAAI,2CAA2C,EAAEG,KAAKC,SAAS,CAACH,MAAM,CAAC,CAAC;AAChI;AAEA,eAAeH,iCAAgC","ignoreList":[0]}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
import path from 'path';
|
||||
import { bold, cyan } from '../../../../lib/picocolors';
|
||||
import loaderUtils from 'next/dist/compiled/loader-utils3';
|
||||
import postcssNextFontPlugin from './postcss-next-font';
|
||||
import { promisify } from 'util';
|
||||
export default async function nextFontLoader() {
|
||||
const nextFontLoaderSpan = this.currentTraceSpan.traceChild('next-font-loader');
|
||||
return nextFontLoaderSpan.traceAsyncFn(async ()=>{
|
||||
const callback = this.async();
|
||||
/**
|
||||
* The next-swc plugin next-transform-font turns font function calls into CSS imports.
|
||||
* At the end of the import, it adds the call arguments and some additional data as a resourceQuery.
|
||||
* e.g:
|
||||
* const inter = Inter({ subset: ['latin'] })
|
||||
* ->
|
||||
* import inter from 'next/font/google/target.css?{"import":"Inter","subsets":["latin"]}'
|
||||
*
|
||||
* Here we parse the resourceQuery to get the font function name, call arguments, and the path to the file that called the font function.
|
||||
*/ 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 = Object.defineProperty(new Error(`${bold('Cannot')} be used within ${cyan('pages/_document.js')}.`), "__NEXT_ERROR_CODE", {
|
||||
value: "E135",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
err.name = 'NextFontError';
|
||||
if (process.env.NEXT_RSPACK) {
|
||||
// Rspack uses miette for error formatting, which automatically includes stack
|
||||
// traces in the error message. To avoid showing redundant stack information
|
||||
// in the final error output, we clear the stack property.
|
||||
err.stack = undefined;
|
||||
}
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
const { isDev, isServer, assetPrefix, deploymentId, fontLoaderPath, postcss: getPostcss } = this.getOptions();
|
||||
if (assetPrefix && !/^\/|https?:\/\//.test(assetPrefix)) {
|
||||
const err = Object.defineProperty(new Error('assetPrefix must start with a leading slash or be an absolute URL(http:// or https://)'), "__NEXT_ERROR_CODE", {
|
||||
value: "E72",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
err.name = 'NextFontError';
|
||||
callback(err);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Emit font files to .next/static/media as [hash].[ext].
|
||||
*
|
||||
* If the font should be preloaded, add .p to the filename: [hash].p.[ext]
|
||||
* NextFontManifestPlugin adds these files to the next/font manifest.
|
||||
*
|
||||
* If the font is using a size-adjust fallback font, add -s to the filename: [hash]-s.[ext]
|
||||
* NextFontManifestPlugin uses this to see if fallback fonts are being used.
|
||||
* This is used to collect stats on fallback fonts usage by the Google Aurora team.
|
||||
*/ const emitFontFile = (content, ext, preload, isUsingSizeAdjust)=>{
|
||||
const opts = {
|
||||
context: this.rootContext,
|
||||
content
|
||||
};
|
||||
const interpolatedName = loaderUtils.interpolateName(this, `static/media/[hash]${isUsingSizeAdjust ? '-s' : ''}${preload ? '.p' : ''}.${ext}`, opts);
|
||||
const outputPath = `${assetPrefix}/_next/${interpolatedName}${deploymentId ? `?dpl=${deploymentId}` : ''}`;
|
||||
// Only the client emits the font file
|
||||
if (!isServer) {
|
||||
this.emitFile(interpolatedName, content, null);
|
||||
}
|
||||
// But both the server and client must get the resulting path
|
||||
return outputPath;
|
||||
};
|
||||
try {
|
||||
// Import the font loader function from either next/font/local or next/font/google
|
||||
// The font loader function emits font files and returns @font-faces and fallback font metrics
|
||||
const fontLoader = require(fontLoaderPath).default;
|
||||
let { css, fallbackFonts, adjustFontFallback, weight, style, variable } = await nextFontLoaderSpan.traceChild('font-loader').traceAsyncFn(()=>fontLoader({
|
||||
functionName,
|
||||
variableName,
|
||||
data,
|
||||
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 = [];
|
||||
// Generate a hash from the CSS content. Used to generate classnames
|
||||
const fontFamilyHash = loaderUtils.getHashDigest(Buffer.from(css), 'sha1', 'hex', 6);
|
||||
// Add CSS classes, exports and make the font-family locally scoped by turning it unguessable
|
||||
const result = await nextFontLoaderSpan.traceChild('postcss').traceAsyncFn(()=>postcss(postcssNextFontPlugin({
|
||||
exports,
|
||||
fallbackFonts,
|
||||
weight,
|
||||
style,
|
||||
adjustFontFallback,
|
||||
variable
|
||||
})).process(css, {
|
||||
from: undefined
|
||||
}));
|
||||
const ast = {
|
||||
type: 'postcss',
|
||||
version: result.processor.version,
|
||||
root: result.root
|
||||
};
|
||||
// Return the resulting CSS and send the postcss ast, font exports and the hash to the css-loader in the meta argument.
|
||||
callback(null, result.css, null, {
|
||||
exports,
|
||||
ast,
|
||||
fontFamilyHash
|
||||
});
|
||||
} catch (err) {
|
||||
callback(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+154
@@ -0,0 +1,154 @@
|
||||
import postcss from 'postcss';
|
||||
/**
|
||||
* The next/font postcss plugin receives the @font-face declarations returned from the next/font loaders.
|
||||
*
|
||||
* It hashes the font-family name to make it unguessable, it shouldn't be globally accessible.
|
||||
* If it were global, we wouldn't be able to tell which pages are using which fonts when generating preload tags.
|
||||
*
|
||||
* If the font loader returned fallback metrics, generate a fallback @font-face.
|
||||
*
|
||||
* If the font loader returned a variable name, add a CSS class that declares a variable containing the font and fallback fonts.
|
||||
*
|
||||
* Lastly, it adds the font-family to the exports object.
|
||||
* This enables you to access the actual font-family name, not just through the CSS class.
|
||||
* e.g:
|
||||
* const inter = Inter({ subsets: ['latin'] })
|
||||
* inter.style.fontFamily // => '__Inter_123456'
|
||||
*/ const postcssNextFontPlugin = ({ exports, fallbackFonts = [], adjustFontFallback, variable, weight, style })=>{
|
||||
return {
|
||||
postcssPlugin: 'postcss-next-font',
|
||||
Once (root) {
|
||||
let fontFamily;
|
||||
const normalizeFamily = (family)=>{
|
||||
return family.replace(/['"]/g, '');
|
||||
};
|
||||
const formatFamily = (family)=>{
|
||||
return `'${family}'`;
|
||||
};
|
||||
// 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 Object.defineProperty(new Error("Font loaders must return one or more @font-face's"), "__NEXT_ERROR_CODE", {
|
||||
value: "E428",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
// Add fallback @font-face with the provided 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(' ');
|
||||
// Format the font families to be used in the CSS
|
||||
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
|
||||
}),
|
||||
// If the font only has one weight or style, we can set it on the class
|
||||
...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 CSS class that defines a variable with the font families
|
||||
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
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
+58
@@ -0,0 +1,58 @@
|
||||
import isAnimated from 'next/dist/compiled/is-animated';
|
||||
import { optimizeImage } from '../../../../server/image-optimizer';
|
||||
const BLUR_IMG_SIZE = 8;
|
||||
const BLUR_QUALITY = 70;
|
||||
const VALID_BLUR_EXT = [
|
||||
'jpeg',
|
||||
'png',
|
||||
'webp',
|
||||
'avif'
|
||||
] // should match other usages
|
||||
;
|
||||
export async function getBlurImage(content, extension, imageSize, { basePath, outputPath, isDev, tracing = ()=>({
|
||||
traceFn: (fn)=>(...args)=>fn(...args),
|
||||
traceAsyncFn: (fn)=>(...args)=>fn(...args)
|
||||
}) }) {
|
||||
let blurDataURL;
|
||||
let blurWidth = 0;
|
||||
let blurHeight = 0;
|
||||
if (VALID_BLUR_EXT.includes(extension) && !isAnimated(content)) {
|
||||
// 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 = tracing('image-resize');
|
||||
const resizedImage = await resizeImageSpan.traceAsyncFn(()=>optimizeImage({
|
||||
buffer: content,
|
||||
width: blurWidth,
|
||||
height: blurHeight,
|
||||
contentType: `image/${extension}`,
|
||||
quality: BLUR_QUALITY
|
||||
}));
|
||||
const blurDataURLSpan = tracing('image-base64-tostring');
|
||||
blurDataURL = blurDataURLSpan.traceFn(()=>`data:image/${extension};base64,${resizedImage.toString('base64')}`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
dataURL: blurDataURL,
|
||||
width: blurWidth,
|
||||
height: blurHeight
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=blur.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-image-loader/blur.ts"],"sourcesContent":["import isAnimated from 'next/dist/compiled/is-animated'\nimport { optimizeImage } from '../../../../server/image-optimizer'\n\nconst BLUR_IMG_SIZE = 8\nconst BLUR_QUALITY = 70\nconst VALID_BLUR_EXT = ['jpeg', 'png', 'webp', 'avif'] // should match other usages\n\nexport async function getBlurImage(\n content: Buffer,\n extension: string,\n imageSize: { width: number; height: number },\n {\n basePath,\n outputPath,\n isDev,\n tracing = () => ({\n traceFn:\n (fn) =>\n (...args: any) =>\n fn(...args),\n traceAsyncFn:\n (fn) =>\n (...args: any) =>\n fn(...args),\n }),\n }: {\n basePath: string\n outputPath: string\n isDev: boolean\n tracing: (name?: string) => {\n traceFn(fn: Function): any\n traceAsyncFn(fn: Function): any\n }\n }\n) {\n let blurDataURL: string | undefined\n let blurWidth: number = 0\n let blurHeight: number = 0\n\n if (VALID_BLUR_EXT.includes(extension) && !isAnimated(content)) {\n // Shrink the image's largest dimension\n if (imageSize.width >= imageSize.height) {\n blurWidth = BLUR_IMG_SIZE\n blurHeight = Math.max(\n Math.round((imageSize.height / imageSize.width) * BLUR_IMG_SIZE),\n 1\n )\n } else {\n blurWidth = Math.max(\n Math.round((imageSize.width / imageSize.height) * BLUR_IMG_SIZE),\n 1\n )\n blurHeight = BLUR_IMG_SIZE\n }\n\n if (isDev) {\n // During `next dev`, we don't want to generate blur placeholders with webpack\n // because it can delay starting the dev server. Instead, we inline a\n // special url to lazily generate the blur placeholder at request time.\n const prefix = 'http://localhost'\n const url = new URL(`${basePath || ''}/_next/image`, prefix)\n url.searchParams.set('url', outputPath)\n url.searchParams.set('w', String(blurWidth))\n url.searchParams.set('q', String(BLUR_QUALITY))\n blurDataURL = url.href.slice(prefix.length)\n } else {\n const resizeImageSpan = tracing('image-resize')\n const resizedImage = await resizeImageSpan.traceAsyncFn(() =>\n optimizeImage({\n buffer: content,\n width: blurWidth,\n height: blurHeight,\n contentType: `image/${extension}`,\n quality: BLUR_QUALITY,\n })\n )\n const blurDataURLSpan = tracing('image-base64-tostring')\n blurDataURL = blurDataURLSpan.traceFn(\n () =>\n `data:image/${extension};base64,${resizedImage.toString('base64')}`\n )\n }\n }\n return {\n dataURL: blurDataURL,\n width: blurWidth,\n height: blurHeight,\n }\n}\n"],"names":["isAnimated","optimizeImage","BLUR_IMG_SIZE","BLUR_QUALITY","VALID_BLUR_EXT","getBlurImage","content","extension","imageSize","basePath","outputPath","isDev","tracing","traceFn","fn","args","traceAsyncFn","blurDataURL","blurWidth","blurHeight","includes","width","height","Math","max","round","prefix","url","URL","searchParams","set","String","href","slice","length","resizeImageSpan","resizedImage","buffer","contentType","quality","blurDataURLSpan","toString","dataURL"],"mappings":"AAAA,OAAOA,gBAAgB,iCAAgC;AACvD,SAASC,aAAa,QAAQ,qCAAoC;AAElE,MAAMC,gBAAgB;AACtB,MAAMC,eAAe;AACrB,MAAMC,iBAAiB;IAAC;IAAQ;IAAO;IAAQ;CAAO,CAAC,4BAA4B;;AAEnF,OAAO,eAAeC,aACpBC,OAAe,EACfC,SAAiB,EACjBC,SAA4C,EAC5C,EACEC,QAAQ,EACRC,UAAU,EACVC,KAAK,EACLC,UAAU,IAAO,CAAA;QACfC,SACE,CAACC,KACD,CAAC,GAAGC,OACFD,MAAMC;QACVC,cACE,CAACF,KACD,CAAC,GAAGC,OACFD,MAAMC;IACZ,CAAA,CAAE,EASH;IAED,IAAIE;IACJ,IAAIC,YAAoB;IACxB,IAAIC,aAAqB;IAEzB,IAAIf,eAAegB,QAAQ,CAACb,cAAc,CAACP,WAAWM,UAAU;QAC9D,uCAAuC;QACvC,IAAIE,UAAUa,KAAK,IAAIb,UAAUc,MAAM,EAAE;YACvCJ,YAAYhB;YACZiB,aAAaI,KAAKC,GAAG,CACnBD,KAAKE,KAAK,CAAC,AAACjB,UAAUc,MAAM,GAAGd,UAAUa,KAAK,GAAInB,gBAClD;QAEJ,OAAO;YACLgB,YAAYK,KAAKC,GAAG,CAClBD,KAAKE,KAAK,CAAC,AAACjB,UAAUa,KAAK,GAAGb,UAAUc,MAAM,GAAIpB,gBAClD;YAEFiB,aAAajB;QACf;QAEA,IAAIS,OAAO;YACT,8EAA8E;YAC9E,qEAAqE;YACrE,uEAAuE;YACvE,MAAMe,SAAS;YACf,MAAMC,MAAM,IAAIC,IAAI,GAAGnB,YAAY,GAAG,YAAY,CAAC,EAAEiB;YACrDC,IAAIE,YAAY,CAACC,GAAG,CAAC,OAAOpB;YAC5BiB,IAAIE,YAAY,CAACC,GAAG,CAAC,KAAKC,OAAOb;YACjCS,IAAIE,YAAY,CAACC,GAAG,CAAC,KAAKC,OAAO5B;YACjCc,cAAcU,IAAIK,IAAI,CAACC,KAAK,CAACP,OAAOQ,MAAM;QAC5C,OAAO;YACL,MAAMC,kBAAkBvB,QAAQ;YAChC,MAAMwB,eAAe,MAAMD,gBAAgBnB,YAAY,CAAC,IACtDf,cAAc;oBACZoC,QAAQ/B;oBACRe,OAAOH;oBACPI,QAAQH;oBACRmB,aAAa,CAAC,MAAM,EAAE/B,WAAW;oBACjCgC,SAASpC;gBACX;YAEF,MAAMqC,kBAAkB5B,QAAQ;YAChCK,cAAcuB,gBAAgB3B,OAAO,CACnC,IACE,CAAC,WAAW,EAAEN,UAAU,QAAQ,EAAE6B,aAAaK,QAAQ,CAAC,WAAW;QAEzE;IACF;IACA,OAAO;QACLC,SAASzB;QACTI,OAAOH;QACPI,QAAQH;IACV;AACF","ignoreList":[0]}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import path from 'path';
|
||||
import loaderUtils from 'next/dist/compiled/loader-utils3';
|
||||
import { getImageSize } from '../../../../server/image-optimizer';
|
||||
import { getBlurImage } from './blur';
|
||||
function nextImageLoader(content) {
|
||||
const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader');
|
||||
return imageLoaderSpan.traceAsyncFn(async ()=>{
|
||||
const options = this.getOptions();
|
||||
const { compilerType, 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).catch((err)=>err));
|
||||
if (imageSize instanceof Error) {
|
||||
const err = imageSize;
|
||||
err.name = 'InvalidImageFormatError';
|
||||
throw err;
|
||||
}
|
||||
const { dataURL: blurDataURL, width: blurWidth, height: blurHeight } = await getBlurImage(content, extension, imageSize, {
|
||||
basePath,
|
||||
outputPath,
|
||||
isDev,
|
||||
tracing: imageLoaderSpan.traceChild.bind(imageLoaderSpan)
|
||||
});
|
||||
const stringifiedData = imageLoaderSpan.traceChild('image-data-stringify').traceFn(()=>JSON.stringify({
|
||||
src: outputPath,
|
||||
height: imageSize.height,
|
||||
width: imageSize.width,
|
||||
blurDataURL,
|
||||
blurWidth,
|
||||
blurHeight
|
||||
}));
|
||||
if (compilerType === 'client') {
|
||||
this.emitFile(interpolatedName, content, null);
|
||||
} else {
|
||||
this.emitFile(path.join('..', isDev || compilerType === 'edge-server' ? '' : '..', interpolatedName), content, null);
|
||||
}
|
||||
return `export default ${stringifiedData};`;
|
||||
});
|
||||
}
|
||||
export const raw = true;
|
||||
export default nextImageLoader;
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../../src/build/webpack/loaders/next-image-loader/index.ts"],"sourcesContent":["import type { CompilerNameValues } from '../../../../shared/lib/constants'\n\nimport path from 'path'\nimport loaderUtils from 'next/dist/compiled/loader-utils3'\nimport { getImageSize } from '../../../../server/image-optimizer'\nimport { getBlurImage } from './blur'\n\ninterface Options {\n compilerType: CompilerNameValues\n isDev: boolean\n assetPrefix: string\n basePath: string\n}\n\nfunction nextImageLoader(this: any, content: Buffer) {\n const imageLoaderSpan = this.currentTraceSpan.traceChild('next-image-loader')\n return imageLoaderSpan.traceAsyncFn(async () => {\n const options: Options = this.getOptions()\n const { compilerType, isDev, assetPrefix, basePath } = options\n const context = this.rootContext\n\n const opts = { context, content }\n const interpolatedName = loaderUtils.interpolateName(\n this,\n '/static/media/[name].[hash:8].[ext]',\n opts\n )\n const outputPath = assetPrefix + '/_next' + interpolatedName\n let extension = loaderUtils.interpolateName(this, '[ext]', opts)\n if (extension === 'jpg') {\n extension = 'jpeg'\n }\n\n const imageSizeSpan = imageLoaderSpan.traceChild('image-size-calculation')\n const imageSize = await imageSizeSpan.traceAsyncFn(() =>\n getImageSize(content).catch((err) => err)\n )\n\n if (imageSize instanceof Error) {\n const err = imageSize\n err.name = 'InvalidImageFormatError'\n throw err\n }\n\n const {\n dataURL: blurDataURL,\n width: blurWidth,\n height: blurHeight,\n } = await getBlurImage(content, extension, imageSize, {\n basePath,\n outputPath,\n isDev,\n tracing: imageLoaderSpan.traceChild.bind(imageLoaderSpan),\n })\n\n const stringifiedData = imageLoaderSpan\n .traceChild('image-data-stringify')\n .traceFn(() =>\n JSON.stringify({\n src: outputPath,\n height: imageSize.height,\n width: imageSize.width,\n blurDataURL,\n blurWidth,\n blurHeight,\n })\n )\n\n if (compilerType === 'client') {\n this.emitFile(interpolatedName, content, null)\n } else {\n this.emitFile(\n path.join(\n '..',\n isDev || compilerType === 'edge-server' ? '' : '..',\n interpolatedName\n ),\n content,\n null\n )\n }\n\n return `export default ${stringifiedData};`\n })\n}\nexport const raw = true\nexport default nextImageLoader\n"],"names":["path","loaderUtils","getImageSize","getBlurImage","nextImageLoader","content","imageLoaderSpan","currentTraceSpan","traceChild","traceAsyncFn","options","getOptions","compilerType","isDev","assetPrefix","basePath","context","rootContext","opts","interpolatedName","interpolateName","outputPath","extension","imageSizeSpan","imageSize","catch","err","Error","name","dataURL","blurDataURL","width","blurWidth","height","blurHeight","tracing","bind","stringifiedData","traceFn","JSON","stringify","src","emitFile","join","raw"],"mappings":"AAEA,OAAOA,UAAU,OAAM;AACvB,OAAOC,iBAAiB,mCAAkC;AAC1D,SAASC,YAAY,QAAQ,qCAAoC;AACjE,SAASC,YAAY,QAAQ,SAAQ;AASrC,SAASC,gBAA2BC,OAAe;IACjD,MAAMC,kBAAkB,IAAI,CAACC,gBAAgB,CAACC,UAAU,CAAC;IACzD,OAAOF,gBAAgBG,YAAY,CAAC;QAClC,MAAMC,UAAmB,IAAI,CAACC,UAAU;QACxC,MAAM,EAAEC,YAAY,EAAEC,KAAK,EAAEC,WAAW,EAAEC,QAAQ,EAAE,GAAGL;QACvD,MAAMM,UAAU,IAAI,CAACC,WAAW;QAEhC,MAAMC,OAAO;YAAEF;YAASX;QAAQ;QAChC,MAAMc,mBAAmBlB,YAAYmB,eAAe,CAClD,IAAI,EACJ,uCACAF;QAEF,MAAMG,aAAaP,cAAc,WAAWK;QAC5C,IAAIG,YAAYrB,YAAYmB,eAAe,CAAC,IAAI,EAAE,SAASF;QAC3D,IAAII,cAAc,OAAO;YACvBA,YAAY;QACd;QAEA,MAAMC,gBAAgBjB,gBAAgBE,UAAU,CAAC;QACjD,MAAMgB,YAAY,MAAMD,cAAcd,YAAY,CAAC,IACjDP,aAAaG,SAASoB,KAAK,CAAC,CAACC,MAAQA;QAGvC,IAAIF,qBAAqBG,OAAO;YAC9B,MAAMD,MAAMF;YACZE,IAAIE,IAAI,GAAG;YACX,MAAMF;QACR;QAEA,MAAM,EACJG,SAASC,WAAW,EACpBC,OAAOC,SAAS,EAChBC,QAAQC,UAAU,EACnB,GAAG,MAAM/B,aAAaE,SAASiB,WAAWE,WAAW;YACpDT;YACAM;YACAR;YACAsB,SAAS7B,gBAAgBE,UAAU,CAAC4B,IAAI,CAAC9B;QAC3C;QAEA,MAAM+B,kBAAkB/B,gBACrBE,UAAU,CAAC,wBACX8B,OAAO,CAAC,IACPC,KAAKC,SAAS,CAAC;gBACbC,KAAKpB;gBACLY,QAAQT,UAAUS,MAAM;gBACxBF,OAAOP,UAAUO,KAAK;gBACtBD;gBACAE;gBACAE;YACF;QAGJ,IAAItB,iBAAiB,UAAU;YAC7B,IAAI,CAAC8B,QAAQ,CAACvB,kBAAkBd,SAAS;QAC3C,OAAO;YACL,IAAI,CAACqC,QAAQ,CACX1C,KAAK2C,IAAI,CACP,MACA9B,SAASD,iBAAiB,gBAAgB,KAAK,MAC/CO,mBAEFd,SACA;QAEJ;QAEA,OAAO,CAAC,eAAe,EAAEgC,gBAAgB,CAAC,CAAC;IAC7C;AACF;AACA,OAAO,MAAMO,MAAM,KAAI;AACvB,eAAexC,gBAAe","ignoreList":[0]}
|
||||
Generated
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
const nextInvalidImportErrorLoader = function() {
|
||||
const { message } = this.getOptions();
|
||||
const error = Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
|
||||
value: "E394",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
if (process.env.NEXT_RSPACK) {
|
||||
// Rspack uses miette for error formatting, which automatically includes stack
|
||||
// traces in the error message. To avoid showing redundant stack information
|
||||
// in the final error output, we clear the stack property.
|
||||
error.stack = undefined;
|
||||
}
|
||||
throw error;
|
||||
};
|
||||
export default nextInvalidImportErrorLoader;
|
||||
|
||||
//# sourceMappingURL=next-invalid-import-error-loader.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../../src/build/webpack/loaders/next-invalid-import-error-loader.ts"],"sourcesContent":["import type webpack from 'webpack'\n\nexport type InvalidImportLoaderOpts = { message: string }\n\nconst nextInvalidImportErrorLoader: webpack.LoaderDefinitionFunction<InvalidImportLoaderOpts> =\n function () {\n const { message } = this.getOptions()\n const error = new Error(message)\n if (process.env.NEXT_RSPACK) {\n // Rspack uses miette for error formatting, which automatically includes stack\n // traces in the error message. To avoid showing redundant stack information\n // in the final error output, we clear the stack property.\n error.stack = undefined\n }\n throw error\n }\n\nexport default nextInvalidImportErrorLoader\n"],"names":["nextInvalidImportErrorLoader","message","getOptions","error","Error","process","env","NEXT_RSPACK","stack","undefined"],"mappings":"AAIA,MAAMA,+BACJ;IACE,MAAM,EAAEC,OAAO,EAAE,GAAG,IAAI,CAACC,UAAU;IACnC,MAAMC,QAAQ,qBAAkB,CAAlB,IAAIC,MAAMH,UAAV,qBAAA;eAAA;oBAAA;sBAAA;IAAiB;IAC/B,IAAII,QAAQC,GAAG,CAACC,WAAW,EAAE;QAC3B,8EAA8E;QAC9E,4EAA4E;QAC5E,0DAA0D;QAC1DJ,MAAMK,KAAK,GAAGC;IAChB;IACA,MAAMN;AACR;AAEF,eAAeH,6BAA4B","ignoreList":[0]}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* This loader is responsible for extracting the metadata image info for rendering in html
|
||||
*/ import { existsSync, promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import loaderUtils from 'next/dist/compiled/loader-utils3';
|
||||
import { getImageSize } from '../../../server/image-optimizer';
|
||||
import { imageExtMimeTypeMap } from '../../../lib/mime-type';
|
||||
import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants';
|
||||
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep';
|
||||
import { getLoaderModuleNamedExports } from './utils';
|
||||
import { installBindings } from '../../swc/install-bindings';
|
||||
// [NOTE] For turbopack, refer to app_page_loader_tree's write_metadata_item for
|
||||
// corresponding features.
|
||||
async function nextMetadataImageLoader(content) {
|
||||
// Install bindings early so they are definitely available to the loader.
|
||||
// When run by webpack in next this is already done with correct configuration so this is a no-op.
|
||||
// In turbopack loaders are run in a subprocess so it may or may not be done.
|
||||
await installBindings();
|
||||
const options = this.getOptions();
|
||||
const { type, segment, pageExtensions, basePath } = options;
|
||||
const { resourcePath, rootContext: context } = this;
|
||||
const { name: fileNameBase, ext } = path.parse(resourcePath);
|
||||
const useNumericSizes = type === 'twitter' || type === 'openGraph';
|
||||
let extension = ext.slice(1);
|
||||
if (extension === 'jpg') {
|
||||
extension = 'jpeg';
|
||||
}
|
||||
const opts = {
|
||||
context,
|
||||
content
|
||||
};
|
||||
const contentHash = loaderUtils.interpolateName(this, '[contenthash]', opts);
|
||||
const interpolatedName = loaderUtils.interpolateName(this, '[name].[ext]', opts);
|
||||
const isDynamicResource = pageExtensions.includes(extension);
|
||||
const pageSegment = isDynamicResource ? fileNameBase : interpolatedName;
|
||||
const hashQuery = contentHash ? '?' + contentHash : '';
|
||||
const pathnamePrefix = normalizePathSep(path.join(basePath, segment));
|
||||
if (isDynamicResource) {
|
||||
const exportedFieldsExcludingDefault = (await getLoaderModuleNamedExports(resourcePath, this)).filter((name)=>name !== 'default');
|
||||
// re-export and spread as `exportedImageData` to avoid non-exported error
|
||||
return `\
|
||||
import {
|
||||
${exportedFieldsExcludingDefault.map((field)=>`${field} as _${field}`).join(',')}
|
||||
} from ${JSON.stringify(// This is an arbitrary resource query to ensure it's a new request, instead
|
||||
// of sharing the same module with next-metadata-route-loader.
|
||||
// Since here we only need export fields such as `size`, `alt` and
|
||||
// `generateImageMetadata`, avoid sharing the same module can make this entry
|
||||
// smaller.
|
||||
resourcePath + '?' + WEBPACK_RESOURCE_QUERIES.metadataImageMeta)}
|
||||
import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
|
||||
|
||||
const imageModule = {
|
||||
${exportedFieldsExcludingDefault.map((field)=>`${field}: _${field}`).join(',')}
|
||||
}
|
||||
|
||||
function getImageMetadata(imageMetadata, idParam, resolvedParams) {
|
||||
const imageUrl = fillMetadataSegment(${JSON.stringify(pathnamePrefix)}, resolvedParams, ${JSON.stringify(pageSegment)}, false)
|
||||
const data = {
|
||||
alt: imageMetadata.alt,
|
||||
type: imageMetadata.contentType || 'image/png',
|
||||
url: imageUrl + (idParam ? ('/' + idParam) : '') + ${JSON.stringify(hashQuery)},
|
||||
}
|
||||
const { size } = imageMetadata
|
||||
if (size) {
|
||||
${type === 'twitter' || type === 'openGraph' ? 'data.width = size.width; data.height = size.height;' : 'data.sizes = size.width + "x" + size.height;'}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export default async function (props) {
|
||||
const { generateImageMetadata } = imageModule
|
||||
const resolvedParams = await props.params
|
||||
|
||||
if (generateImageMetadata) {
|
||||
const imageMetadataArray = await generateImageMetadata({ params: resolvedParams })
|
||||
return imageMetadataArray.map((imageMetadata, index) => {
|
||||
const idParam = imageMetadata.id + ''
|
||||
return getImageMetadata(imageMetadata, idParam, resolvedParams)
|
||||
})
|
||||
} else {
|
||||
return [getImageMetadata(imageModule, '', resolvedParams)]
|
||||
}
|
||||
}`;
|
||||
}
|
||||
let imageError;
|
||||
const imageSize = await getImageSize(content).catch((error)=>{
|
||||
const message = `Process image "${path.posix.join(segment || '/', interpolatedName)}" failed: ${error}`;
|
||||
imageError = Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
|
||||
value: "E1040",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
return {};
|
||||
});
|
||||
if (imageError) {
|
||||
throw imageError;
|
||||
}
|
||||
const imageData = {
|
||||
...extension in imageExtMimeTypeMap && {
|
||||
type: imageExtMimeTypeMap[extension]
|
||||
},
|
||||
...useNumericSizes && imageSize.width != null && imageSize.height != null ? imageSize : {
|
||||
sizes: // For SVGs, skip sizes and use "any" to let it scale automatically based on viewport,
|
||||
// For the images doesn't provide the size properly, use "any" as well.
|
||||
// If the size is presented, use the actual size for the image.
|
||||
extension !== 'svg' && imageSize.width != null && imageSize.height != null ? `${imageSize.width}x${imageSize.height}` : 'any'
|
||||
}
|
||||
};
|
||||
if (type === 'openGraph' || type === 'twitter') {
|
||||
const altPath = path.join(path.dirname(resourcePath), fileNameBase + '.alt.txt');
|
||||
if (existsSync(altPath)) {
|
||||
imageData.alt = await fs.readFile(altPath, 'utf8');
|
||||
}
|
||||
}
|
||||
return `\
|
||||
import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route'
|
||||
|
||||
export default async (props) => {
|
||||
const imageData = ${JSON.stringify(imageData)}
|
||||
const imageUrl = fillMetadataSegment(${JSON.stringify(pathnamePrefix)}, await props.params, ${JSON.stringify(pageSegment)}, true)
|
||||
|
||||
return [{
|
||||
...imageData,
|
||||
url: imageUrl + ${JSON.stringify(hashQuery)},
|
||||
}]
|
||||
}`;
|
||||
}
|
||||
export const raw = true;
|
||||
export default nextMetadataImageLoader;
|
||||
|
||||
//# sourceMappingURL=next-metadata-image-loader.js.map
|
||||
Generated
Vendored
+1
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
Reference in New Issue
Block a user