create project

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

View File

@@ -0,0 +1,23 @@
import type { Module } from '@swc/core';
export declare class NoSuchDeclarationError extends Error {
}
export declare class UnsupportedValueError extends Error {
/** @example `config.runtime[0].value` */
path?: string;
constructor(message: string, paths?: string[]);
}
/**
* Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'edge' }") from swc's AST.
* The value must be one of (or throws UnsupportedValueError):
* - string
* - boolean
* - number
* - null
* - undefined
* - array containing values listed in this list
* - object containing values listed in this list
*
* Throws NoSuchDeclarationError if the declaration is not found.
*/
export declare function extractExportedConstValue(module: Module, exportedName: string): any;

View File

@@ -0,0 +1,181 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.extractExportedConstValue = extractExportedConstValue;
class NoSuchDeclarationError extends Error {
}
exports.NoSuchDeclarationError = NoSuchDeclarationError;
function isExportDeclaration(node) {
return node.type === "ExportDeclaration";
}
function isVariableDeclaration(node) {
return node.type === "VariableDeclaration";
}
function isIdentifier(node) {
return node.type === "Identifier";
}
function isBooleanLiteral(node) {
return node.type === "BooleanLiteral";
}
function isNullLiteral(node) {
return node.type === "NullLiteral";
}
function isStringLiteral(node) {
return node.type === "StringLiteral";
}
function isNumericLiteral(node) {
return node.type === "NumericLiteral";
}
function isArrayExpression(node) {
return node.type === "ArrayExpression";
}
function isObjectExpression(node) {
return node.type === "ObjectExpression";
}
function isKeyValueProperty(node) {
return node.type === "KeyValueProperty";
}
function isRegExpLiteral(node) {
return node.type === "RegExpLiteral";
}
function isTemplateLiteral(node) {
return node.type === "TemplateLiteral";
}
class UnsupportedValueError extends Error {
constructor(message, paths){
super(message);
// Generating "path" that looks like "config.runtime[0].value"
let codePath;
if (paths) {
codePath = "";
for (const path of paths){
if (path[0] === "[") {
// "array" + "[0]"
codePath += path;
} else {
if (codePath === "") {
codePath = path;
} else {
// "object" + ".key"
codePath += `.${path}`;
}
}
}
}
this.path = codePath;
}
}
exports.UnsupportedValueError = UnsupportedValueError;
function extractValue(node, path) {
if (isNullLiteral(node)) {
return null;
} else if (isBooleanLiteral(node)) {
// e.g. true / false
return node.value;
} else if (isStringLiteral(node)) {
// e.g. "abc"
return node.value;
} else if (isNumericLiteral(node)) {
// e.g. 123
return node.value;
} else if (isRegExpLiteral(node)) {
// e.g. /abc/i
return new RegExp(node.pattern, node.flags);
} else if (isIdentifier(node)) {
switch(node.value){
case "undefined":
return undefined;
default:
throw new UnsupportedValueError(`Unknown identifier "${node.value}"`, path);
}
} else if (isArrayExpression(node)) {
// e.g. [1, 2, 3]
const arr = [];
for(let i = 0, len = node.elements.length; i < len; i++){
const elem = node.elements[i];
if (elem) {
if (elem.spread) {
// e.g. [ ...a ]
throw new UnsupportedValueError("Unsupported spread operator in the Array Expression", path);
}
arr.push(extractValue(elem.expression, path && [
...path,
`[${i}]`
]));
} else {
// e.g. [1, , 2]
// ^^
arr.push(undefined);
}
}
return arr;
} else if (isObjectExpression(node)) {
// e.g. { a: 1, b: 2 }
const obj = {};
for (const prop of node.properties){
if (!isKeyValueProperty(prop)) {
// e.g. { ...a }
throw new UnsupportedValueError("Unsupported spread operator in the Object Expression", path);
}
let key;
if (isIdentifier(prop.key)) {
// e.g. { a: 1, b: 2 }
key = prop.key.value;
} else if (isStringLiteral(prop.key)) {
// e.g. { "a": 1, "b": 2 }
key = prop.key.value;
} else {
throw new UnsupportedValueError(`Unsupported key type "${prop.key.type}" in the Object Expression`, path);
}
obj[key] = extractValue(prop.value, path && [
...path,
key
]);
}
return obj;
} else if (isTemplateLiteral(node)) {
// e.g. `abc`
if (node.expressions.length !== 0) {
// TODO: should we add support for `${'e'}d${'g'}'e'`?
throw new UnsupportedValueError("Unsupported template literal with expressions", path);
}
// When TemplateLiteral has 0 expressions, the length of quasis is always 1.
// Because when parsing TemplateLiteral, the parser yields the first quasi,
// then the first expression, then the next quasi, then the next expression, etc.,
// until the last quasi.
// Thus if there is no expression, the parser ends at the frst and also last quasis
//
// A "cooked" interpretation where backslashes have special meaning, while a
// "raw" interpretation where backslashes do not have special meaning
// https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
const [{ cooked , raw }] = node.quasis;
return cooked ?? raw;
} else {
throw new UnsupportedValueError(`Unsupported node type "${node.type}"`, path);
}
}
function extractExportedConstValue(module, exportedName) {
for (const moduleItem of module.body){
if (!isExportDeclaration(moduleItem)) {
continue;
}
const declaration = moduleItem.declaration;
if (!isVariableDeclaration(declaration)) {
continue;
}
if (declaration.kind !== "const") {
continue;
}
for (const decl of declaration.declarations){
if (isIdentifier(decl.id) && decl.id.value === exportedName && decl.init) {
return extractValue(decl.init, [
exportedName
]);
}
}
}
throw new NoSuchDeclarationError();
}
//# sourceMappingURL=extract-const-value.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
import type { NextConfig } from '../../server/config-shared';
import type { RouteHas } from '../../lib/load-custom-routes';
import { ServerRuntime } from 'next/types';
export interface MiddlewareConfig {
matchers: MiddlewareMatcher[];
unstable_allowDynamicGlobs: string[];
regions: string[] | string;
}
export interface MiddlewareMatcher {
regexp: string;
locale?: false;
has?: RouteHas[];
missing?: RouteHas[];
}
export interface PageStaticInfo {
runtime?: ServerRuntime;
ssg?: boolean;
ssr?: boolean;
rsc?: RSCModuleType;
middleware?: Partial<MiddlewareConfig>;
}
export declare type RSCModuleType = 'server' | 'client';
export declare function getRSCModuleType(source: string): RSCModuleType;
/**
* For a given pageFilePath and nextConfig, if the config supports it, this
* function will read the file and return the runtime that should be used.
* It will look into the file content only if the page *requires* a runtime
* to be specified, that is, when gSSP or gSP is used.
* Related discussion: https://github.com/vercel/next.js/discussions/34179
*/
export declare function getPageStaticInfo(params: {
nextConfig: Partial<NextConfig>;
pageFilePath: string;
isDev?: boolean;
page?: string;
pageType?: 'pages' | 'app';
}): Promise<PageStaticInfo>;

View File

@@ -0,0 +1,287 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getRSCModuleType = getRSCModuleType;
exports.getPageStaticInfo = getPageStaticInfo;
var _fs = require("fs");
var _micromatch = require("next/dist/compiled/micromatch");
var _extractConstValue = require("./extract-const-value");
var _parseModule = require("./parse-module");
var Log = _interopRequireWildcard(require("../output/log"));
var _constants = require("../../lib/constants");
var _loadCustomRoutes = require("../../lib/load-custom-routes");
var _tryToParsePath = require("../../lib/try-to-parse-path");
var _isApiRoute = require("../../lib/is-api-route");
var _isEdgeRuntime = require("../../lib/is-edge-runtime");
var _constants1 = require("../../shared/lib/constants");
function _getRequireWildcardCache() {
if (typeof WeakMap !== "function") return null;
var cache = new WeakMap();
_getRequireWildcardCache = function() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const CLIENT_MODULE_LABEL = `/* __next_internal_client_entry_do_not_use__ */`;
function getRSCModuleType(source) {
return source.includes(CLIENT_MODULE_LABEL) ? _constants1.RSC_MODULE_TYPES.client : _constants1.RSC_MODULE_TYPES.server;
}
/**
* Receives a parsed AST from SWC and checks if it belongs to a module that
* requires a runtime to be specified. Those are:
* - Modules with `export function getStaticProps | getServerSideProps`
* - Modules with `export { getStaticProps | getServerSideProps } <from ...>`
* - Modules with `export const runtime = ...`
*/ function checkExports(swcAST) {
if (Array.isArray(swcAST == null ? void 0 : swcAST.body)) {
try {
let runtime;
let ssr = false;
let ssg = false;
for (const node of swcAST.body){
var ref11, ref1, ref2, ref3;
if (node.type === "ExportDeclaration" && ((ref11 = node.declaration) == null ? void 0 : ref11.type) === "VariableDeclaration") {
var ref4, ref5;
const id = (ref5 = (ref4 = node.declaration) == null ? void 0 : ref4.declarations[0]) == null ? void 0 : ref5.id.value;
if (id === "runtime") {
var ref6, ref7;
runtime = (ref7 = (ref6 = node.declaration) == null ? void 0 : ref6.declarations[0]) == null ? void 0 : ref7.init.value;
}
}
if (node.type === "ExportDeclaration" && ((ref1 = node.declaration) == null ? void 0 : ref1.type) === "FunctionDeclaration" && [
"getStaticProps",
"getServerSideProps"
].includes((ref2 = node.declaration.identifier) == null ? void 0 : ref2.value)) {
ssg = node.declaration.identifier.value === "getStaticProps";
ssr = node.declaration.identifier.value === "getServerSideProps";
}
if (node.type === "ExportDeclaration" && ((ref3 = node.declaration) == null ? void 0 : ref3.type) === "VariableDeclaration") {
var ref8, ref9;
const id = (ref9 = (ref8 = node.declaration) == null ? void 0 : ref8.declarations[0]) == null ? void 0 : ref9.id.value;
if ([
"getStaticProps",
"getServerSideProps"
].includes(id)) {
ssg = id === "getStaticProps";
ssr = id === "getServerSideProps";
}
}
if (node.type === "ExportNamedDeclaration") {
const values = node.specifiers.map((specifier)=>{
var ref, ref10;
return specifier.type === "ExportSpecifier" && ((ref = specifier.orig) == null ? void 0 : ref.type) === "Identifier" && ((ref10 = specifier.orig) == null ? void 0 : ref10.value);
});
ssg = values.some((value)=>[
"getStaticProps"
].includes(value));
ssr = values.some((value)=>[
"getServerSideProps"
].includes(value));
}
}
return {
ssr,
ssg,
runtime
};
} catch (err) {}
}
return {
ssg: false,
ssr: false
};
}
async function tryToReadFile(filePath, shouldThrow) {
try {
return await _fs.promises.readFile(filePath, {
encoding: "utf8"
});
} catch (error) {
if (shouldThrow) {
throw error;
}
}
}
function getMiddlewareMatchers(matcherOrMatchers, nextConfig) {
let matchers = [];
if (Array.isArray(matcherOrMatchers)) {
matchers = matcherOrMatchers;
} else {
matchers.push(matcherOrMatchers);
}
const { i18n } = nextConfig;
let routes = matchers.map((m)=>typeof m === "string" ? {
source: m
} : m);
// check before we process the routes and after to ensure
// they are still valid
(0, _loadCustomRoutes).checkCustomRoutes(routes, "middleware");
routes = routes.map((r)=>{
let { source } = r;
const isRoot = source === "/";
if ((i18n == null ? void 0 : i18n.locales) && r.locale !== false) {
source = `/:nextInternalLocale([^/.]{1,})${isRoot ? "" : source}`;
}
source = `/:nextData(_next/data/[^/]{1,})?${source}${isRoot ? `(${nextConfig.i18n ? "|\\.json|" : ""}/?index|/?index\\.json)?` : "(.json)?"}`;
if (nextConfig.basePath) {
source = `${nextConfig.basePath}${source}`;
}
return {
...r,
source
};
});
(0, _loadCustomRoutes).checkCustomRoutes(routes, "middleware");
return routes.map((r)=>{
const { source , ...rest } = r;
const parsedPage = (0, _tryToParsePath).tryToParsePath(source);
if (parsedPage.error || !parsedPage.regexStr) {
throw new Error(`Invalid source: ${source}`);
}
return {
...rest,
regexp: parsedPage.regexStr
};
});
}
function getMiddlewareConfig(pageFilePath, config, nextConfig) {
const result = {};
if (config.matcher) {
result.matchers = getMiddlewareMatchers(config.matcher, nextConfig);
}
if (typeof config.regions === "string" || Array.isArray(config.regions)) {
result.regions = config.regions;
} else if (typeof config.regions !== "undefined") {
Log.warn(`The \`regions\` config was ignored: config must be empty, a string or an array of strings. (${pageFilePath})`);
}
if (config.unstable_allowDynamic) {
result.unstable_allowDynamicGlobs = Array.isArray(config.unstable_allowDynamic) ? config.unstable_allowDynamic : [
config.unstable_allowDynamic
];
for (const glob of result.unstable_allowDynamicGlobs ?? []){
try {
(0, _micromatch).matcher(glob);
} catch (err) {
throw new Error(`${pageFilePath} exported 'config.unstable_allowDynamic' contains invalid pattern '${glob}': ${err.message}`);
}
}
}
return result;
}
let warnedAboutExperimentalEdge = false;
function warnAboutExperimentalEdge() {
if (warnedAboutExperimentalEdge) {
return;
}
Log.warn(`You are using an experimental edge runtime, the API might change.`);
warnedAboutExperimentalEdge = true;
}
const warnedUnsupportedValueMap = new Map();
function warnAboutUnsupportedValue(pageFilePath, page, error) {
if (warnedUnsupportedValueMap.has(pageFilePath)) {
return;
}
Log.warn(`Next.js can't recognize the exported \`config\` field in ` + (page ? `route "${page}"` : `"${pageFilePath}"`) + ":\n" + error.message + (error.path ? ` at "${error.path}"` : "") + ".\n" + "The default config will be used instead.\n" + "Read More - https://nextjs.org/docs/messages/invalid-page-config");
warnedUnsupportedValueMap.set(pageFilePath, true);
}
async function getPageStaticInfo(params) {
var ref;
const { isDev , pageFilePath , nextConfig , page , pageType } = params;
const fileContent = await tryToReadFile(pageFilePath, !isDev) || "";
if (/runtime|getStaticProps|getServerSideProps|export const config/.test(fileContent)) {
var ref15;
const swcAST = await (0, _parseModule).parseModule(pageFilePath, fileContent);
const { ssg , ssr , runtime } = checkExports(swcAST);
const rsc = getRSCModuleType(fileContent);
// default / failsafe value for config
let config = {};
try {
config = (0, _extractConstValue).extractExportedConstValue(swcAST, "config");
} catch (e) {
if (e instanceof _extractConstValue.UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e);
}
// `export config` doesn't exist, or other unknown error throw by swc, silence them
}
// Currently, we use `export const config = { runtime: '...' }` to specify the page runtime.
// But in the new app directory, we prefer to use `export const runtime = '...'`
// and deprecate the old way. To prevent breaking changes for `pages`, we use the exported config
// as the fallback value.
let resolvedRuntime = runtime || config.runtime;
if (typeof resolvedRuntime !== "undefined" && resolvedRuntime !== _constants.SERVER_RUNTIME.nodejs && !(0, _isEdgeRuntime).isEdgeRuntime(resolvedRuntime)) {
const options = Object.values(_constants.SERVER_RUNTIME).join(", ");
if (typeof resolvedRuntime !== "string") {
Log.error(`The \`runtime\` config must be a string. Please leave it empty or choose one of: ${options}`);
} else {
Log.error(`Provided runtime "${resolvedRuntime}" is not supported. Please leave it empty or choose one of: ${options}`);
}
if (!isDev) {
process.exit(1);
}
}
const requiresServerRuntime = ssr || ssg || pageType === "app";
resolvedRuntime = (0, _isEdgeRuntime).isEdgeRuntime(resolvedRuntime) ? resolvedRuntime : requiresServerRuntime ? resolvedRuntime || ((ref15 = nextConfig.experimental) == null ? void 0 : ref15.runtime) : undefined;
if (resolvedRuntime === _constants.SERVER_RUNTIME.experimentalEdge) {
warnAboutExperimentalEdge();
}
if (resolvedRuntime === _constants.SERVER_RUNTIME.edge && pageType === "pages" && page && !(0, _isApiRoute).isAPIRoute(page.replace(/^\/pages\//, "/"))) {
const message = `Page ${page} provided runtime 'edge', the edge runtime for rendering is currently experimental. Use runtime 'experimental-edge' instead.`;
Log.error(message);
if (!isDev) {
process.exit(1);
}
}
const middlewareConfig = getMiddlewareConfig(page ?? "middleware/edge API route", config, nextConfig);
return {
ssr,
ssg,
rsc,
...middlewareConfig && {
middleware: middlewareConfig
},
...resolvedRuntime && {
runtime: resolvedRuntime
}
};
}
return {
ssr: false,
ssg: false,
rsc: _constants1.RSC_MODULE_TYPES.server,
runtime: (ref = nextConfig.experimental) == null ? void 0 : ref.runtime
};
}
//# sourceMappingURL=get-page-static-info.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
/**
* Parses a module with SWC using an LRU cache where the parsed module will
* be indexed by a sha of its content holding up to 500 entries.
*/
export declare const parseModule: (_: string, content: string) => Promise<any>;

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseModule = void 0;
var _lruCache = _interopRequireDefault(require("next/dist/compiled/lru-cache"));
var _withPromiseCache = require("../../lib/with-promise-cache");
var _crypto = require("crypto");
var _swc = require("../swc");
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const parseModule = (0, _withPromiseCache).withPromiseCache(new _lruCache.default({
max: 500
}), async (filename, content)=>(0, _swc).parse(content, {
isModule: "unknown",
filename
}).catch(()=>null), (_, content)=>(0, _crypto).createHash("sha1").update(content).digest("hex"));
exports.parseModule = parseModule;
//# sourceMappingURL=parse-module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../build/analysis/parse-module.ts"],"names":["parseModule","withPromiseCache","LRUCache","max","filename","content","parse","isModule","catch","_","createHash","update","digest"],"mappings":"AAAA;;;;;AAAqB,IAAA,SAA8B,kCAA9B,8BAA8B,EAAA;AAClB,IAAA,iBAA8B,WAA9B,8BAA8B,CAAA;AACpC,IAAA,OAAQ,WAAR,QAAQ,CAAA;AACb,IAAA,IAAQ,WAAR,QAAQ,CAAA;;;;;;AAMvB,MAAMA,WAAW,GAAGC,CAAAA,GAAAA,iBAAgB,AAK1C,CAAA,iBAL0C,CACzC,IAAIC,SAAQ,QAAA,CAAc;IAAEC,GAAG,EAAE,GAAG;CAAE,CAAC,EACvC,OAAOC,QAAgB,EAAEC,OAAe,GACtCC,CAAAA,GAAAA,IAAK,AAA4C,CAAA,MAA5C,CAACD,OAAO,EAAE;QAAEE,QAAQ,EAAE,SAAS;QAAEH,QAAQ;KAAE,CAAC,CAACI,KAAK,CAAC,IAAM,IAAI,CAAC,EACrE,CAACC,CAAC,EAAEJ,OAAO,GAAKK,CAAAA,GAAAA,OAAU,AAAQ,CAAA,WAAR,CAAC,MAAM,CAAC,CAACC,MAAM,CAACN,OAAO,CAAC,CAACO,MAAM,CAAC,KAAK,CAAC,CACjE;QALYZ,WAAW,GAAXA,WAAW"}