Unverified Commit ad63effb authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Remove unneeded next-dev js in next-core (#56039)

x-ref:
https://github.com/vercel/next.js/pull/55983#issuecomment-1734766241


Closes WEB-1661
parent 778a3c55
/**
* Build npm package to be able to embed them in the binary
*/
import { mkdir, writeFile, rm, readFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { createRequire } from 'node:module'
import { join, dirname, basename, extname } from 'node:path'
import { fileURLToPath } from 'node:url'
import ncc from '@vercel/ncc'
import { findUp } from 'find-up'
const __dirname = dirname(fileURLToPath(import.meta.url))
const require = createRequire(import.meta.url)
/**
* @type {{
* name: string;
* type: "cjs" | "module" | "module-default";
* types?: string;
* }[]}
*/
const packages = [
{
name: 'anser',
type: 'cjs',
},
{
name: 'css.escape',
type: 'cjs',
types: 'export = CSS.escape',
},
{
name: 'platform',
type: 'cjs',
},
{
name: 'source-map',
type: 'module',
},
{
name: 'stacktrace-parser',
type: 'module',
},
{
name: 'strip-ansi',
type: 'module-default',
},
]
const externals = Object.fromEntries(
packages.map((pkg) => [
pkg.name,
`@vercel/turbopack-next/compiled/${pkg.name}`,
])
)
// adapted from https://github.com/vercel/next.js/blob/8fb5ef18e7958a19874e11b8037ac0f71c48baef/packages/next/taskfile-ncc.js
async function writePackageManifest(packageName, main) {
// some newer packages fail to include package.json in the exports
// so we can't reliably use require.resolve here
let packagePath
try {
packagePath = require.resolve(packageName + '/package.json')
} catch (_) {
packagePath = await findUp('package.json', {
cwd: dirname(require.resolve(packageName)),
})
}
const { name, author, license } = require(packagePath)
const compiledPackagePath = join(__dirname, `src/compiled/${packageName}`)
const potentialLicensePath = join(dirname(packagePath), './LICENSE')
if (existsSync(potentialLicensePath)) {
await writeFile(
join(compiledPackagePath, 'LICENSE'),
await readFile(potentialLicensePath, 'utf8')
)
} else {
// license might be lower case and not able to be found on case-sensitive
// file systems (ubuntu)
const otherPotentialLicensePath = join(dirname(packagePath), './license')
if (existsSync(otherPotentialLicensePath)) {
await writeFile(
join(compiledPackagePath, 'LICENSE'),
await readFile(otherPotentialLicensePath, 'utf8')
)
}
}
await writeFile(
join(compiledPackagePath, 'package.json'),
JSON.stringify(
Object.assign(
{},
{ name, main: `${basename(main, '.' + extname(main))}` },
author ? { author } : undefined,
license ? { license } : undefined
)
) + '\n'
)
}
async function main() {
const baseDir = join(__dirname, 'src/compiled')
await rm(baseDir, {
force: true,
recursive: true,
})
let types = '/* GENERATED FILE, DO NOT EDIT */\n'
for (const pkg of packages) {
const input = require.resolve(pkg.name)
const outputDir = join(baseDir, pkg.name)
await mkdir(outputDir, { recursive: true })
const { code, assets } = await ncc(input, {
minify: true,
assetBuilds: true,
quiet: true,
externals,
})
await writeFile(join(outputDir, 'index.js'), code)
for (const key in assets) {
await writeFile(join(outputDir, key), assets[key].source)
}
await writePackageManifest(pkg.name, 'index.js')
types += `\ndeclare module '@vercel/turbopack-next/compiled/${pkg.name}' {\n`
if (pkg.types) {
types += ` ${pkg.types}\n`
} else if (pkg.type === 'module-default') {
types += ` import m from '${pkg.name}'\n`
types += ` export default m\n`
} else if (pkg.type === 'module') {
types += ` export * from '${pkg.name}'\n`
} else if (pkg.type === 'cjs') {
types += ` import m from '${pkg.name}'\n`
types += ` export = m\n`
} else {
throw new Error(`unknown package type ${pkg.type} for ${pkg.name}`)
}
types += `}\n`
console.log(`built ${pkg.name}`)
}
await writeFile(join(__dirname, 'types', 'compiled.d.ts'), types)
}
main().catch((e) => {
console.dir(e)
process.exit(1)
})
...@@ -5,29 +5,6 @@ ...@@ -5,29 +5,6 @@
"license": "UNLICENSED", "license": "UNLICENSED",
"private": true, "private": true,
"scripts": { "scripts": {
"build": "pnpm build:compiled && pnpm check",
"build:compiled": "node build.mjs",
"check": "tsc --noEmit" "check": "tsc --noEmit"
},
"dependencies": {
"@vercel/turbopack-ecmascript-runtime": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-230922.2",
"@vercel/turbopack-node": "https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230922.2",
"anser": "^2.1.1",
"css.escape": "^1.5.1",
"next": "*",
"platform": "1.3.6",
"react-dom": "^18.2.0",
"react": "^18.2.0",
"source-map": "0.8.0-beta.0",
"stacktrace-parser": "^0.1.10",
"strip-ansi": "^7.0.1"
},
"devDependencies": {
"@types/node": "^18.11.11",
"@types/platform": "^1.3.4",
"@types/react": "18.2.5",
"@types/react-dom": "18.2.3",
"@vercel/ncc": "^0.36.0",
"find-up": "^6.3.0"
} }
} }
The MIT License (MIT)
Copyright (c) 2012-22 Ionică Bizău <bizauionica@gmail.com> (https://ionicabizau.net)
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.
(()=>{"use strict";var e={281:e=>{var r=function(){function defineProperties(e,r){for(var s=0;s<r.length;s++){var n=r[s];n.enumerable=n.enumerable||false;n.configurable=true;if("value"in n)n.writable=true;Object.defineProperty(e,n.key,n)}}return function(e,r,s){if(r)defineProperties(e.prototype,r);if(s)defineProperties(e,s);return e}}();function _classCallCheck(e,r){if(!(e instanceof r)){throw new TypeError("Cannot call a class as a function")}}var s=[[{color:"0, 0, 0",class:"ansi-black"},{color:"187, 0, 0",class:"ansi-red"},{color:"0, 187, 0",class:"ansi-green"},{color:"187, 187, 0",class:"ansi-yellow"},{color:"0, 0, 187",class:"ansi-blue"},{color:"187, 0, 187",class:"ansi-magenta"},{color:"0, 187, 187",class:"ansi-cyan"},{color:"255,255,255",class:"ansi-white"}],[{color:"85, 85, 85",class:"ansi-bright-black"},{color:"255, 85, 85",class:"ansi-bright-red"},{color:"0, 255, 0",class:"ansi-bright-green"},{color:"255, 255, 85",class:"ansi-bright-yellow"},{color:"85, 85, 255",class:"ansi-bright-blue"},{color:"255, 85, 255",class:"ansi-bright-magenta"},{color:"85, 255, 255",class:"ansi-bright-cyan"},{color:"255, 255, 255",class:"ansi-bright-white"}]];var n=function(){r(Anser,null,[{key:"escapeForHtml",value:function escapeForHtml(e){return(new Anser).escapeForHtml(e)}},{key:"linkify",value:function linkify(e){return(new Anser).linkify(e)}},{key:"ansiToHtml",value:function ansiToHtml(e,r){return(new Anser).ansiToHtml(e,r)}},{key:"ansiToJson",value:function ansiToJson(e,r){return(new Anser).ansiToJson(e,r)}},{key:"ansiToText",value:function ansiToText(e){return(new Anser).ansiToText(e)}}]);function Anser(){_classCallCheck(this,Anser);this.fg=this.bg=this.fg_truecolor=this.bg_truecolor=null;this.bright=0;this.decorations=[]}r(Anser,[{key:"setupPalette",value:function setupPalette(){this.PALETTE_COLORS=[];for(var e=0;e<2;++e){for(var r=0;r<8;++r){this.PALETTE_COLORS.push(s[e][r].color)}}var n=[0,95,135,175,215,255];var o=function format(e,r,s){return n[e]+", "+n[r]+", "+n[s]};var i=void 0,t=void 0,a=void 0;for(var l=0;l<6;++l){for(var c=0;c<6;++c){for(var u=0;u<6;++u){this.PALETTE_COLORS.push(o(l,c,u))}}}var f=8;for(var h=0;h<24;++h,f+=10){this.PALETTE_COLORS.push(o(f,f,f))}}},{key:"escapeForHtml",value:function escapeForHtml(e){return e.replace(/[&<>\"]/gm,(function(e){return e=="&"?"&amp;":e=='"'?"&quot;":e=="<"?"&lt;":e==">"?"&gt;":""}))}},{key:"linkify",value:function linkify(e){return e.replace(/(https?:\/\/[^\s]+)/gm,(function(e){return'<a href="'+e+'">'+e+"</a>"}))}},{key:"ansiToHtml",value:function ansiToHtml(e,r){return this.process(e,r,true)}},{key:"ansiToJson",value:function ansiToJson(e,r){r=r||{};r.json=true;r.clearLine=false;return this.process(e,r,true)}},{key:"ansiToText",value:function ansiToText(e){return this.process(e,{},false)}},{key:"process",value:function process(e,r,s){var n=this;var o=this;var i=e.split(/\033\[/);var t=i.shift();if(r===undefined||r===null){r={}}r.clearLine=/\r/.test(e);var a=i.map((function(e){return n.processChunk(e,r,s)}));if(r&&r.json){var l=o.processChunkJson("");l.content=t;l.clearLine=r.clearLine;a.unshift(l);if(r.remove_empty){a=a.filter((function(e){return!e.isEmpty()}))}return a}else{a.unshift(t)}return a.join("")}},{key:"processChunkJson",value:function processChunkJson(e,r,n){r=typeof r=="undefined"?{}:r;var o=r.use_classes=typeof r.use_classes!="undefined"&&r.use_classes;var i=r.key=o?"class":"color";var t={content:e,fg:null,bg:null,fg_truecolor:null,bg_truecolor:null,isInverted:false,clearLine:r.clearLine,decoration:null,decorations:[],was_processed:false,isEmpty:function isEmpty(){return!t.content}};var a=e.match(/^([!\x3c-\x3f]*)([\d;]*)([\x20-\x2c]*[\x40-\x7e])([\s\S]*)/m);if(!a)return t;var l=t.content=a[4];var c=a[2].split(";");if(a[1]!==""||a[3]!=="m"){return t}if(!n){return t}var u=this;while(c.length>0){var f=c.shift();var h=parseInt(f);if(isNaN(h)||h===0){u.fg=u.bg=null;u.decorations=[]}else if(h===1){u.decorations.push("bold")}else if(h===2){u.decorations.push("dim")}else if(h===3){u.decorations.push("italic")}else if(h===4){u.decorations.push("underline")}else if(h===5){u.decorations.push("blink")}else if(h===7){u.decorations.push("reverse")}else if(h===8){u.decorations.push("hidden")}else if(h===9){u.decorations.push("strikethrough")}else if(h===21){u.removeDecoration("bold")}else if(h===22){u.removeDecoration("bold");u.removeDecoration("dim")}else if(h===23){u.removeDecoration("italic")}else if(h===24){u.removeDecoration("underline")}else if(h===25){u.removeDecoration("blink")}else if(h===27){u.removeDecoration("reverse")}else if(h===28){u.removeDecoration("hidden")}else if(h===29){u.removeDecoration("strikethrough")}else if(h===39){u.fg=null}else if(h===49){u.bg=null}else if(h>=30&&h<38){u.fg=s[0][h%10][i]}else if(h>=90&&h<98){u.fg=s[1][h%10][i]}else if(h>=40&&h<48){u.bg=s[0][h%10][i]}else if(h>=100&&h<108){u.bg=s[1][h%10][i]}else if(h===38||h===48){var v=h===38;if(c.length>=1){var g=c.shift();if(g==="5"&&c.length>=1){var p=parseInt(c.shift());if(p>=0&&p<=255){if(!o){if(!this.PALETTE_COLORS){u.setupPalette()}if(v){u.fg=this.PALETTE_COLORS[p]}else{u.bg=this.PALETTE_COLORS[p]}}else{var d=p>=16?"ansi-palette-"+p:s[p>7?1:0][p%8]["class"];if(v){u.fg=d}else{u.bg=d}}}}else if(g==="2"&&c.length>=3){var b=parseInt(c.shift());var _=parseInt(c.shift());var m=parseInt(c.shift());if(b>=0&&b<=255&&_>=0&&_<=255&&m>=0&&m<=255){var k=b+", "+_+", "+m;if(!o){if(v){u.fg=k}else{u.bg=k}}else{if(v){u.fg="ansi-truecolor";u.fg_truecolor=k}else{u.bg="ansi-truecolor";u.bg_truecolor=k}}}}}}}if(u.fg===null&&u.bg===null&&u.decorations.length===0){return t}else{var y=[];var T=[];var w={};t.fg=u.fg;t.bg=u.bg;t.fg_truecolor=u.fg_truecolor;t.bg_truecolor=u.bg_truecolor;t.decorations=u.decorations;t.decoration=u.decorations.slice(-1).pop()||null;t.was_processed=true;return t}}},{key:"processChunk",value:function processChunk(e,r,n){var o=this;r=r||{};var i=this.processChunkJson(e,r,n);var t=r.use_classes;i.decorations=i.decorations.filter((function(e){if(e==="reverse"){if(!i.fg){i.fg=s[0][7][t?"class":"color"]}if(!i.bg){i.bg=s[0][0][t?"class":"color"]}var r=i.fg;i.fg=i.bg;i.bg=r;var n=i.fg_truecolor;i.fg_truecolor=i.bg_truecolor;i.bg_truecolor=n;i.isInverted=true;return false}return true}));if(r.json){return i}if(i.isEmpty()){return""}if(!i.was_processed){return i.content}var a=[];var l=[];var c=[];var u={};var f=function render_data(e){var r=[];var s=void 0;for(s in e){if(e.hasOwnProperty(s)){r.push("data-"+s+'="'+o.escapeForHtml(e[s])+'"')}}return r.length>0?" "+r.join(" "):""};if(i.isInverted){u["ansi-is-inverted"]="true"}if(i.fg){if(t){a.push(i.fg+"-fg");if(i.fg_truecolor!==null){u["ansi-truecolor-fg"]=i.fg_truecolor;i.fg_truecolor=null}}else{a.push("color:rgb("+i.fg+")")}}if(i.bg){if(t){a.push(i.bg+"-bg");if(i.bg_truecolor!==null){u["ansi-truecolor-bg"]=i.bg_truecolor;i.bg_truecolor=null}}else{a.push("background-color:rgb("+i.bg+")")}}i.decorations.forEach((function(e){if(t){l.push("ansi-"+e);return}if(e==="bold"){l.push("font-weight:bold")}else if(e==="dim"){l.push("opacity:0.5")}else if(e==="italic"){l.push("font-style:italic")}else if(e==="hidden"){l.push("visibility:hidden")}else if(e==="strikethrough"){c.push("line-through")}else{c.push(e)}}));if(c.length){l.push("text-decoration:"+c.join(" "))}if(t){return'<span class="'+a.concat(l).join(" ")+'"'+f(u)+">"+i.content+"</span>"}else{return'<span style="'+a.concat(l).join(";")+'"'+f(u)+">"+i.content+"</span>"}}},{key:"removeDecoration",value:function removeDecoration(e){var r=this.decorations.indexOf(e);if(r>=0){this.decorations.splice(r,1)}}}]);return Anser}();e.exports=n}};var r={};function __nccwpck_require__(s){var n=r[s];if(n!==undefined){return n.exports}var o=r[s]={exports:{}};var i=true;try{e[s](o,o.exports,__nccwpck_require__);i=false}finally{if(i)delete r[s]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(281);module.exports=s})();
\ No newline at end of file
{"name":"anser","main":"index.js","author":"Ionică Bizău <bizauionica@gmail.com> (https://ionicabizau.net)","license":"MIT"}
(()=>{var e={196:function(e){(function(r,t){if(true){e.exports=t(r)}else{}})(typeof global!="undefined"?global:this,(function(e){if(e.CSS&&e.CSS.escape){return e.CSS.escape}var cssEscape=function(e){if(arguments.length==0){throw new TypeError("`CSS.escape` requires an argument.")}var r=String(e);var t=r.length;var n=-1;var a;var i="";var u=r.charCodeAt(0);while(++n<t){a=r.charCodeAt(n);if(a==0){i+="�";continue}if(a>=1&&a<=31||a==127||n==0&&a>=48&&a<=57||n==1&&a>=48&&a<=57&&u==45){i+="\\"+a.toString(16)+" ";continue}if(n==0&&t==1&&a==45){i+="\\"+r.charAt(n);continue}if(a>=128||a==45||a==95||a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122){i+=r.charAt(n);continue}i+="\\"+r.charAt(n)}return i};if(!e.CSS){e.CSS={}}e.CSS.escape=cssEscape;return cssEscape}))}};var r={};function __nccwpck_require__(t){var n=r[t];if(n!==undefined){return n.exports}var a=r[t]={exports:{}};var i=true;try{e[t].call(a.exports,a,a.exports,__nccwpck_require__);i=false}finally{if(i)delete r[t]}return a.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var t=__nccwpck_require__(196);module.exports=t})();
\ No newline at end of file
{"name":"css.escape","main":"index.js","author":{"name":"Mathias Bynens","url":"https://mathiasbynens.be/"},"license":"MIT"}
Copyright 2014-2020 Benjamin Tan
Copyright 2011-2013 John-David Dalton
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.
(()=>{var e={346:function(e,i,t){e=t.nmd(e);
/*!
* Platform.js v1.3.6
* Copyright 2014-2020 Benjamin Tan
* Copyright 2011-2013 John-David Dalton
* Available under MIT license
*/(function(){"use strict";var t={function:true,object:true};var r=t[typeof window]&&window||this;var a=r;var n=t[typeof i]&&i;var o=t["object"]&&e&&!e.nodeType&&e;var l=n&&o&&typeof global=="object"&&global;if(l&&(l.global===l||l.window===l||l.self===l)){r=l}var s=Math.pow(2,53)-1;var f=/\bOpera/;var b=this;var c=Object.prototype;var p=c.hasOwnProperty;var u=c.toString;function capitalize(e){e=String(e);return e.charAt(0).toUpperCase()+e.slice(1)}function cleanupOS(e,i,t){var r={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};if(i&&t&&/^Win/i.test(e)&&!/^Windows Phone /i.test(e)&&(r=r[/[\d.]+$/.exec(e)])){e="Windows "+r}e=String(e);if(i&&t){e=e.replace(RegExp(i,"i"),t)}e=format(e.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0]);return e}function each(e,i){var t=-1,r=e?e.length:0;if(typeof r=="number"&&r>-1&&r<=s){while(++t<r){i(e[t],t,e)}}else{forOwn(e,i)}}function format(e){e=trim(e);return/^(?:webOS|i(?:OS|P))/.test(e)?e:capitalize(e)}function forOwn(e,i){for(var t in e){if(p.call(e,t)){i(e[t],t,e)}}}function getClassOf(e){return e==null?capitalize(e):u.call(e).slice(8,-1)}function isHostType(e,i){var t=e!=null?typeof e[i]:"number";return!/^(?:boolean|number|string|undefined)$/.test(t)&&(t=="object"?!!e[i]:true)}function qualify(e){return String(e).replace(/([ -])(?!$)/g,"$1?")}function reduce(e,i){var t=null;each(e,(function(r,a){t=i(t,r,a,e)}));return t}function trim(e){return String(e).replace(/^ +| +$/g,"")}function parse(e){var i=r;var t=e&&typeof e=="object"&&getClassOf(e)!="String";if(t){i=e;e=null}var n=i.navigator||{};var o=n.userAgent||"";e||(e=o);var l=t||b==a;var s=t?!!n.likeChrome:/\bChrome\b/.test(e)&&!/internal|\n/i.test(u.toString());var c="Object",p=t?c:"ScriptBridgingProxyObject",d=t?c:"Environment",S=t&&i.java?"JavaPackage":getClassOf(i.java),x=t?c:"RuntimeObject";var m=/\bJava/.test(S)&&i.java;var g=m&&getClassOf(i.environment)==d;var h=m?"a":"α";var v=m?"b":"β";var O=i.document||{};var y=i.operamini||i.opera;var w=f.test(w=t&&y?y["[[Class]]"]:getClassOf(y))?w:y=null;var M;var E=e;var P=[];var C=null;var k=e==o;var B=k&&y&&typeof y.version=="function"&&y.version();var W;var _=getLayout([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"]);var R=getName(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Electron","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel","K-Meleon","Konqueror","Lunascape","Maxthon",{label:"Microsoft Edge",pattern:"(?:Edge|Edg|EdgA|EdgiOS)"},"Midori","Nook Browser","PaleMoon","PhantomJS","Raven","Rekonq","RockMelt",{label:"Samsung Internet",pattern:"SamsungBrowser"},"SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser",{label:"SRWare Iron",pattern:"Iron"},"Sunrise","Swiftfox","Vivaldi","Waterfox","WebPositive",{label:"Yandex Browser",pattern:"YaBrowser"},{label:"UC Browser",pattern:"UCBrowser"},"Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chromium","Chrome",{label:"Chrome",pattern:"(?:HeadlessChrome)"},{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"Firefox for iOS",pattern:"FxiOS"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]);var A=getProduct([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},{label:"Galaxy S5",pattern:"SM-G900"},{label:"Galaxy S6",pattern:"SM-G920"},{label:"Galaxy S6 Edge",pattern:"SM-G925"},{label:"Galaxy S7",pattern:"SM-G930"},{label:"Galaxy S7 Edge",pattern:"SM-G935"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nexus","Nook","PlayBook","PlayStation Vita","PlayStation","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]);var I=getManufacturer({Apple:{iPad:1,iPhone:1,iPod:1},Alcatel:{},Archos:{},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1,Nexus:1},HP:{TouchPad:1},HTC:{},Huawei:{},Lenovo:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Oppo:{},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{PlayStation:1,"PlayStation Vita":1},Xiaomi:{Mi:1,Redmi:1}});var T=getOS(["Windows Phone","KaiOS","Android","CentOS",{label:"Chrome OS",pattern:"CrOS"},"Debian",{label:"DragonFly BSD",pattern:"DragonFly"},"Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","OpenBSD","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Tizen","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);function getLayout(i){return reduce(i,(function(i,t){return i||RegExp("\\b"+(t.pattern||qualify(t))+"\\b","i").exec(e)&&(t.label||t)}))}function getManufacturer(i){return reduce(i,(function(i,t,r){return i||(t[A]||t[/^[a-z]+(?: +[a-z]+\b)*/i.exec(A)]||RegExp("\\b"+qualify(r)+"(?:\\b|\\w*\\d)","i").exec(e))&&r}))}function getName(i){return reduce(i,(function(i,t){return i||RegExp("\\b"+(t.pattern||qualify(t))+"\\b","i").exec(e)&&(t.label||t)}))}function getOS(i){return reduce(i,(function(i,t){var r=t.pattern||qualify(t);if(!i&&(i=RegExp("\\b"+r+"(?:/[\\d.]+|[ \\w.]*)","i").exec(e))){i=cleanupOS(i,r,t.label||t)}return i}))}function getProduct(i){return reduce(i,(function(i,t){var r=t.pattern||qualify(t);if(!i&&(i=RegExp("\\b"+r+" *\\d+[.\\w_]*","i").exec(e)||RegExp("\\b"+r+" *\\w+-[\\w]*","i").exec(e)||RegExp("\\b"+r+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(e))){if((i=String(t.label&&!RegExp(r,"i").test(t.label)?t.label:i).split("/"))[1]&&!/[\d.]+/.test(i[0])){i[0]+=" "+i[1]}t=t.label||t;i=format(i[0].replace(RegExp(r,"i"),t).replace(RegExp("; *(?:"+t+"[_-])?","i")," ").replace(RegExp("("+t+")[-_.]?(\\w)","i"),"$1 $2"))}return i}))}function getVersion(i){return reduce(i,(function(i,t){return i||(RegExp(t+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(e)||0)[1]||null}))}function toStringPlatform(){return this.description||""}_&&(_=[_]);if(/\bAndroid\b/.test(T)&&!A&&(M=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(e))){A=trim(M[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null}if(I&&!A){A=getProduct([I])}else if(I&&A){A=A.replace(RegExp("^("+qualify(I)+")[-_.\\s]","i"),I+" ").replace(RegExp("^("+qualify(I)+")[-_.]?(\\w)","i"),I+" $2")}if(M=/\bGoogle TV\b/.exec(A)){A=M[0]}if(/\bSimulator\b/i.test(e)){A=(A?A+" ":"")+"Simulator"}if(R=="Opera Mini"&&/\bOPiOS\b/.test(e)){P.push("running in Turbo/Uncompressed mode")}if(R=="IE"&&/\blike iPhone OS\b/.test(e)){M=parse(e.replace(/like iPhone OS/,""));I=M.manufacturer;A=M.product}else if(/^iP/.test(A)){R||(R="Safari");T="iOS"+((M=/ OS ([\d_]+)/i.exec(e))?" "+M[1].replace(/_/g,"."):"")}else if(R=="Konqueror"&&/^Linux\b/i.test(T)){T="Kubuntu"}else if(I&&I!="Google"&&(/Chrome/.test(R)&&!/\bMobile Safari\b/i.test(e)||/\bVita\b/.test(A))||/\bAndroid\b/.test(T)&&/^Chrome/.test(R)&&/\bVersion\//i.test(e)){R="Android Browser";T=/\bAndroid\b/.test(T)?T:"Android"}else if(R=="Silk"){if(!/\bMobi/i.test(e)){T="Android";P.unshift("desktop mode")}if(/Accelerated *= *true/i.test(e)){P.unshift("accelerated")}}else if(R=="UC Browser"&&/\bUCWEB\b/.test(e)){P.push("speed mode")}else if(R=="PaleMoon"&&(M=/\bFirefox\/([\d.]+)\b/.exec(e))){P.push("identifying as Firefox "+M[1])}else if(R=="Firefox"&&(M=/\b(Mobile|Tablet|TV)\b/i.exec(e))){T||(T="Firefox OS");A||(A=M[1])}else if(!R||(M=!/\bMinefield\b/i.test(e)&&/\b(?:Firefox|Safari)\b/.exec(R))){if(R&&!A&&/[\/,]|^[^(]+?\)/.test(e.slice(e.indexOf(M+"/")+8))){R=null}if((M=A||I||T)&&(A||I||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(T))){R=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(T)?T:M)+" Browser"}}else if(R=="Electron"&&(M=(/\bChrome\/([\d.]+)\b/.exec(e)||0)[1])){P.push("Chromium "+M)}if(!B){B=getVersion(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",qualify(R),"(?:Firefox|Minefield|NetFront)"])}if(M=_=="iCab"&&parseFloat(B)>3&&"WebKit"||/\bOpera\b/.test(R)&&(/\bOPR\b/.test(e)?"Blink":"Presto")||/\b(?:Midori|Nook|Safari)\b/i.test(e)&&!/^(?:Trident|EdgeHTML)$/.test(_)&&"WebKit"||!_&&/\bMSIE\b/i.test(e)&&(T=="Mac OS"?"Tasman":"Trident")||_=="WebKit"&&/\bPlayStation\b(?! Vita\b)/i.test(R)&&"NetFront"){_=[M]}if(R=="IE"&&(M=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(e)||0)[1])){R+=" Mobile";T="Windows Phone "+(/\+$/.test(M)?M:M+".x");P.unshift("desktop mode")}else if(/\bWPDesktop\b/i.test(e)){R="IE Mobile";T="Windows Phone 8.x";P.unshift("desktop mode");B||(B=(/\brv:([\d.]+)/.exec(e)||0)[1])}else if(R!="IE"&&_=="Trident"&&(M=/\brv:([\d.]+)/.exec(e))){if(R){P.push("identifying as "+R+(B?" "+B:""))}R="IE";B=M[1]}if(k){if(isHostType(i,"global")){if(m){M=m.lang.System;E=M.getProperty("os.arch");T=T||M.getProperty("os.name")+" "+M.getProperty("os.version")}if(g){try{B=i.require("ringo/engine").version.join(".");R="RingoJS"}catch(e){if((M=i.system)&&M.global.system==i.system){R="Narwhal";T||(T=M[0].os||null)}}if(!R){R="Rhino"}}else if(typeof i.process=="object"&&!i.process.browser&&(M=i.process)){if(typeof M.versions=="object"){if(typeof M.versions.electron=="string"){P.push("Node "+M.versions.node);R="Electron";B=M.versions.electron}else if(typeof M.versions.nw=="string"){P.push("Chromium "+B,"Node "+M.versions.node);R="NW.js";B=M.versions.nw}}if(!R){R="Node.js";E=M.arch;T=M.platform;B=/[\d.]+/.exec(M.version);B=B?B[0]:null}}}else if(getClassOf(M=i.runtime)==p){R="Adobe AIR";T=M.flash.system.Capabilities.os}else if(getClassOf(M=i.phantom)==x){R="PhantomJS";B=(M=M.version||null)&&M.major+"."+M.minor+"."+M.patch}else if(typeof O.documentMode=="number"&&(M=/\bTrident\/(\d+)/i.exec(e))){B=[B,O.documentMode];if((M=+M[1]+4)!=B[1]){P.push("IE "+B[1]+" mode");_&&(_[1]="");B[1]=M}B=R=="IE"?String(B[1].toFixed(1)):B[0]}else if(typeof O.documentMode=="number"&&/^(?:Chrome|Firefox)\b/.test(R)){P.push("masking as "+R+" "+B);R="IE";B="11.0";_=["Trident"];T="Windows"}T=T&&format(T)}if(B&&(M=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(B)||/(?:alpha|beta)(?: ?\d)?/i.exec(e+";"+(k&&n.appMinorVersion))||/\bMinefield\b/i.test(e)&&"a")){C=/b/i.test(M)?"beta":"alpha";B=B.replace(RegExp(M+"\\+?$"),"")+(C=="beta"?v:h)+(/\d+\+?/.exec(M)||"")}if(R=="Fennec"||R=="Firefox"&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(T)){R="Firefox Mobile"}else if(R=="Maxthon"&&B){B=B.replace(/\.[\d.]+/,".x")}else if(/\bXbox\b/i.test(A)){if(A=="Xbox 360"){T=null}if(A=="Xbox 360"&&/\bIEMobile\b/.test(e)){P.unshift("mobile mode")}}else if((/^(?:Chrome|IE|Opera)$/.test(R)||R&&!A&&!/Browser|Mobi/.test(R))&&(T=="Windows CE"||/Mobi/i.test(e))){R+=" Mobile"}else if(R=="IE"&&k){try{if(i.external===null){P.unshift("platform preview")}}catch(e){P.unshift("embedded")}}else if((/\bBlackBerry\b/.test(A)||/\bBB10\b/.test(e))&&(M=(RegExp(A.replace(/ +/g," *")+"/([.\\d]+)","i").exec(e)||0)[1]||B)){M=[M,/BB10/.test(e)];T=(M[1]?(A=null,I="BlackBerry"):"Device Software")+" "+M[0];B=null}else if(this!=forOwn&&A!="Wii"&&(k&&y||/Opera/.test(R)&&/\b(?:MSIE|Firefox)\b/i.test(e)||R=="Firefox"&&/\bOS X (?:\d+\.){2,}/.test(T)||R=="IE"&&(T&&!/^Win/.test(T)&&B>5.5||/\bWindows XP\b/.test(T)&&B>8||B==8&&!/\bTrident\b/.test(e)))&&!f.test(M=parse.call(forOwn,e.replace(f,"")+";"))&&M.name){M="ing as "+M.name+((M=M.version)?" "+M:"");if(f.test(R)){if(/\bIE\b/.test(M)&&T=="Mac OS"){T=null}M="identify"+M}else{M="mask"+M;if(w){R=format(w.replace(/([a-z])([A-Z])/g,"$1 $2"))}else{R="Opera"}if(/\bIE\b/.test(M)){T=null}if(!k){B=null}}_=["Presto"];P.push(M)}if(M=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(e)||0)[1]){M=[parseFloat(M.replace(/\.(\d)$/,".0$1")),M];if(R=="Safari"&&M[1].slice(-1)=="+"){R="WebKit Nightly";C="alpha";B=M[1].slice(0,-1)}else if(B==M[1]||B==(M[2]=(/\bSafari\/([\d.]+\+?)/i.exec(e)||0)[1])){B=null}M[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(e)||0)[1];if(M[0]==537.36&&M[2]==537.36&&parseFloat(M[1])>=28&&_=="WebKit"){_=["Blink"]}if(!k||!s&&!M[1]){_&&(_[1]="like Safari");M=(M=M[0],M<400?1:M<500?2:M<526?3:M<533?4:M<534?"4+":M<535?5:M<537?6:M<538?7:M<601?8:M<602?9:M<604?10:M<606?11:M<608?12:"12")}else{_&&(_[1]="like Chrome");M=M[1]||(M=M[0],M<530?1:M<532?2:M<532.05?3:M<533?4:M<534.03?5:M<534.07?6:M<534.1?7:M<534.13?8:M<534.16?9:M<534.24?10:M<534.3?11:M<535.01?12:M<535.02?"13+":M<535.07?15:M<535.11?16:M<535.19?17:M<536.05?18:M<536.1?19:M<537.01?20:M<537.11?"21+":M<537.13?23:M<537.18?24:M<537.24?25:M<537.36?26:_!="Blink"?"27":"28")}_&&(_[1]+=" "+(M+=typeof M=="number"?".x":/[.+]/.test(M)?"":"+"));if(R=="Safari"&&(!B||parseInt(B)>45)){B=M}else if(R=="Chrome"&&/\bHeadlessChrome/i.test(e)){P.unshift("headless")}}if(R=="Opera"&&(M=/\bzbov|zvav$/.exec(T))){R+=" ";P.unshift("desktop mode");if(M=="zvav"){R+="Mini";B=null}else{R+="Mobile"}T=T.replace(RegExp(" *"+M+"$"),"")}else if(R=="Safari"&&/\bChrome\b/.exec(_&&_[1])){P.unshift("desktop mode");R="Chrome Mobile";B=null;if(/\bOS X\b/.test(T)){I="Apple";T="iOS 4.3+"}else{T=null}}else if(/\bSRWare Iron\b/.test(R)&&!B){B=getVersion("Chrome")}if(B&&B.indexOf(M=/[\d.]+$/.exec(T))==0&&e.indexOf("/"+M+"-")>-1){T=trim(T.replace(M,""))}if(T&&T.indexOf(R)!=-1&&!RegExp(R+" OS").test(T)){T=T.replace(RegExp(" *"+qualify(R)+" *"),"")}if(_&&!/\b(?:Avant|Nook)\b/.test(R)&&(/Browser|Lunascape|Maxthon/.test(R)||R!="Safari"&&/^iOS/.test(T)&&/\bSafari\b/.test(_[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(R)&&_[1])){(M=_[_.length-1])&&P.push(M)}if(P.length){P=["("+P.join("; ")+")"]}if(I&&A&&A.indexOf(I)<0){P.push("on "+I)}if(A){P.push((/^on /.test(P[P.length-1])?"":"on ")+A)}if(T){M=/ ([\d.+]+)$/.exec(T);W=M&&T.charAt(T.length-M[0].length-1)=="/";T={architecture:32,family:M&&!W?T.replace(M[0],""):T,version:M?M[1]:null,toString:function(){var e=this.version;return this.family+(e&&!W?" "+e:"")+(this.architecture==64?" 64-bit":"")}}}if((M=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(E))&&!/\bi686\b/i.test(E)){if(T){T.architecture=64;T.family=T.family.replace(RegExp(" *"+M),"")}if(R&&(/\bWOW64\b/i.test(e)||k&&/\w(?:86|32)$/.test(n.cpuClass||n.platform)&&!/\bWin64; x64\b/i.test(e))){P.unshift("32-bit")}}else if(T&&/^OS X/.test(T.family)&&R=="Chrome"&&parseFloat(B)>=39){T.architecture=64}e||(e=null);var F={};F.description=e;F.layout=_&&_[0];F.manufacturer=I;F.name=R;F.prerelease=C;F.product=A;F.ua=e;F.version=R&&B;F.os=T||{architecture:null,family:null,version:null,toString:function(){return"null"}};F.parse=parse;F.toString=toStringPlatform;if(F.version){P.unshift(B)}if(F.name){P.unshift(R)}if(T&&R&&!(T==String(T).split(" ")[0]&&(T==R.split(" ")[0]||A))){P.push(A?"("+T+")":"on "+T)}if(P.length){F.description=P.join(" ")}return F}var d=parse();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){r.platform=d;define((function(){return d}))}else if(n&&o){forOwn(d,(function(e,i){n[i]=e}))}else{r.platform=d}}).call(this)}};var i={};function __nccwpck_require__(t){var r=i[t];if(r!==undefined){return r.exports}var a=i[t]={id:t,loaded:false,exports:{}};var n=true;try{e[t].call(a.exports,a,a.exports,__nccwpck_require__);n=false}finally{if(n)delete i[t]}a.loaded=true;return a.exports}(()=>{__nccwpck_require__.nmd=e=>{e.paths=[];if(!e.children)e.children=[];return e}})();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var t=__nccwpck_require__(346);module.exports=t})();
\ No newline at end of file
{"name":"platform","main":"index.js","author":"Benjamin Tan <demoneaux@gmail.com>","license":"MIT"}
Copyright (c) 2009-2011, Mozilla Foundation and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of the Mozilla Foundation nor the names of project
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(()=>{var e={908:(e,n)=>{class ArraySet{constructor(){this._array=[];this._set=new Map}static fromArray(e,n){const t=new ArraySet;for(let r=0,o=e.length;r<o;r++){t.add(e[r],n)}return t}size(){return this._set.size}add(e,n){const t=this.has(e);const r=this._array.length;if(!t||n){this._array.push(e)}if(!t){this._set.set(e,r)}}has(e){return this._set.has(e)}indexOf(e){const n=this._set.get(e);if(n>=0){return n}throw new Error('"'+e+'" is not in the set.')}at(e){if(e>=0&&e<this._array.length){return this._array[e]}throw new Error("No element indexed by "+e)}toArray(){return this._array.slice()}}n.I=ArraySet},464:(e,n,t)=>{const r=t(779);const o=5;const s=1<<o;const i=s-1;const l=s;function toVLQSigned(e){return e<0?(-e<<1)+1:(e<<1)+0}function fromVLQSigned(e){const n=(e&1)===1;const t=e>>1;return n?-t:t}n.encode=function base64VLQ_encode(e){let n="";let t;let s=toVLQSigned(e);do{t=s&i;s>>>=o;if(s>0){t|=l}n+=r.encode(t)}while(s>0);return n}},779:(e,n)=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");n.encode=function(e){if(0<=e&&e<t.length){return t[e]}throw new TypeError("Must be between 0 and 63: "+e)}},389:(e,n)=>{n.GREATEST_LOWER_BOUND=1;n.LEAST_UPPER_BOUND=2;function recursiveSearch(e,t,r,o,s,i){const l=Math.floor((t-e)/2)+e;const a=s(r,o[l],true);if(a===0){return l}else if(a>0){if(t-l>1){return recursiveSearch(l,t,r,o,s,i)}if(i==n.LEAST_UPPER_BOUND){return t<o.length?t:-1}return l}if(l-e>1){return recursiveSearch(e,l,r,o,s,i)}if(i==n.LEAST_UPPER_BOUND){return l}return e<0?-1:e}n.search=function search(e,t,r,o){if(t.length===0){return-1}let s=recursiveSearch(-1,t.length,e,t,r,o||n.GREATEST_LOWER_BOUND);if(s<0){return-1}while(s-1>=0){if(r(t[s],t[s-1],true)!==0){break}--s}return s}},47:(e,n,t)=>{const r=t(211);function generatedPositionAfter(e,n){const t=e.generatedLine;const o=n.generatedLine;const s=e.generatedColumn;const i=n.generatedColumn;return o>t||o==t&&i>=s||r.compareByGeneratedPositionsInflated(e,n)<=0}class MappingList{constructor(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}unsortedForEach(e,n){this._array.forEach(e,n)}add(e){if(generatedPositionAfter(this._last,e)){this._last=e;this._array.push(e)}else{this._sorted=false;this._array.push(e)}}toArray(){if(!this._sorted){this._array.sort(r.compareByGeneratedPositionsInflated);this._sorted=true}return this._array}}n.H=MappingList},853:(e,n,t)=>{"use strict";const r=t(147);const o=t(17);e.exports=function readWasm(){return new Promise(((e,n)=>{const o=t.ab+"mappings.wasm";r.readFile(t.ab+"mappings.wasm",null,((t,r)=>{if(t){n(t);return}e(r.buffer)}))}))};e.exports.initialize=e=>{console.debug("SourceMapConsumer.initialize is a no-op when running in node.js")}},217:(e,n,t)=>{var r;const o=t(211);const s=t(389);const i=t(908).I;const l=t(464);const a=t(853);const u=t(898);const c=Symbol("smcInternal");class SourceMapConsumer{constructor(e,n){if(e==c){return Promise.resolve(this)}return _factory(e,n)}static initialize(e){a.initialize(e["lib/mappings.wasm"])}static fromSourceMap(e,n){return _factoryBSM(e,n)}static async with(e,n,t){const r=await new SourceMapConsumer(e,n);try{return await t(r)}finally{r.destroy()}}eachMapping(e,n,t){throw new Error("Subclasses must implement eachMapping")}allGeneratedPositionsFor(e){throw new Error("Subclasses must implement allGeneratedPositionsFor")}destroy(){throw new Error("Subclasses must implement destroy")}}SourceMapConsumer.prototype._version=3;SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.GREATEST_LOWER_BOUND=1;SourceMapConsumer.LEAST_UPPER_BOUND=2;n.SourceMapConsumer=SourceMapConsumer;class BasicSourceMapConsumer extends SourceMapConsumer{constructor(e,n){return super(c).then((t=>{let r=e;if(typeof e==="string"){r=o.parseSourceMapInput(e)}const s=o.getArg(r,"version");const l=o.getArg(r,"sources").map(String);const a=o.getArg(r,"names",[]);const c=o.getArg(r,"sourceRoot",null);const g=o.getArg(r,"sourcesContent",null);const f=o.getArg(r,"mappings");const h=o.getArg(r,"file",null);if(s!=t._version){throw new Error("Unsupported version: "+s)}t._sourceLookupCache=new Map;t._names=i.fromArray(a.map(String),true);t._sources=i.fromArray(l,true);t._absoluteSources=i.fromArray(t._sources.toArray().map((function(e){return o.computeSourceURL(c,e,n)})),true);t.sourceRoot=c;t.sourcesContent=g;t._mappings=f;t._sourceMapURL=n;t.file=h;t._computedColumnSpans=false;t._mappingsPtr=0;t._wasm=null;return u().then((e=>{t._wasm=e;return t}))}))}_findSourceIndex(e){const n=this._sourceLookupCache.get(e);if(typeof n==="number"){return n}const t=o.computeSourceURL(null,e,this._sourceMapURL);if(this._absoluteSources.has(t)){const n=this._absoluteSources.indexOf(t);this._sourceLookupCache.set(e,n);return n}const r=o.computeSourceURL(this.sourceRoot,e,this._sourceMapURL);if(this._absoluteSources.has(r)){const n=this._absoluteSources.indexOf(r);this._sourceLookupCache.set(e,n);return n}return-1}static fromSourceMap(e,n){return new BasicSourceMapConsumer(e.toString())}get sources(){return this._absoluteSources.toArray()}_getMappingsPtr(){if(this._mappingsPtr===0){this._parseMappings()}return this._mappingsPtr}_parseMappings(){const e=this._mappings;const n=e.length;const t=this._wasm.exports.allocate_mappings(n);const r=new Uint8Array(this._wasm.exports.memory.buffer,t,n);for(let t=0;t<n;t++){r[t]=e.charCodeAt(t)}const o=this._wasm.exports.parse_mappings(t);if(!o){const e=this._wasm.exports.get_last_error();let n=`Error parsing mappings (code ${e}): `;switch(e){case 1:n+="the mappings contained a negative line, column, source index, or name index";break;case 2:n+="the mappings contained a number larger than 2**32";break;case 3:n+="reached EOF while in the middle of parsing a VLQ";break;case 4:n+="invalid base 64 character while parsing a VLQ";break;default:n+="unknown error code";break}throw new Error(n)}this._mappingsPtr=o}eachMapping(e,n,t){const r=n||null;const o=t||SourceMapConsumer.GENERATED_ORDER;this._wasm.withMappingCallback((n=>{if(n.source!==null){n.source=this._absoluteSources.at(n.source);if(n.name!==null){n.name=this._names.at(n.name)}}if(this._computedColumnSpans&&n.lastGeneratedColumn===null){n.lastGeneratedColumn=Infinity}e.call(r,n)}),(()=>{switch(o){case SourceMapConsumer.GENERATED_ORDER:this._wasm.exports.by_generated_location(this._getMappingsPtr());break;case SourceMapConsumer.ORIGINAL_ORDER:this._wasm.exports.by_original_location(this._getMappingsPtr());break;default:throw new Error("Unknown order of iteration.")}}))}allGeneratedPositionsFor(e){let n=o.getArg(e,"source");const t=o.getArg(e,"line");const r=e.column||0;n=this._findSourceIndex(n);if(n<0){return[]}if(t<1){throw new Error("Line numbers must be >= 1")}if(r<0){throw new Error("Column numbers must be >= 0")}const s=[];this._wasm.withMappingCallback((e=>{let n=e.lastGeneratedColumn;if(this._computedColumnSpans&&n===null){n=Infinity}s.push({line:e.generatedLine,column:e.generatedColumn,lastColumn:n})}),(()=>{this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(),n,t-1,"column"in e,r)}));return s}destroy(){if(this._mappingsPtr!==0){this._wasm.exports.free_mappings(this._mappingsPtr);this._mappingsPtr=0}}computeColumnSpans(){if(this._computedColumnSpans){return}this._wasm.exports.compute_column_spans(this._getMappingsPtr());this._computedColumnSpans=true}originalPositionFor(e){const n={generatedLine:o.getArg(e,"line"),generatedColumn:o.getArg(e,"column")};if(n.generatedLine<1){throw new Error("Line numbers must be >= 1")}if(n.generatedColumn<0){throw new Error("Column numbers must be >= 0")}let t=o.getArg(e,"bias",SourceMapConsumer.GREATEST_LOWER_BOUND);if(t==null){t=SourceMapConsumer.GREATEST_LOWER_BOUND}let r;this._wasm.withMappingCallback((e=>r=e),(()=>{this._wasm.exports.original_location_for(this._getMappingsPtr(),n.generatedLine-1,n.generatedColumn,t)}));if(r){if(r.generatedLine===n.generatedLine){let e=o.getArg(r,"source",null);if(e!==null){e=this._absoluteSources.at(e)}let n=o.getArg(r,"name",null);if(n!==null){n=this._names.at(n)}return{source:e,line:o.getArg(r,"originalLine",null),column:o.getArg(r,"originalColumn",null),name:n}}}return{source:null,line:null,column:null,name:null}}hasContentsOfAllSources(){if(!this.sourcesContent){return false}return this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some((function(e){return e==null}))}sourceContentFor(e,n){if(!this.sourcesContent){return null}const t=this._findSourceIndex(e);if(t>=0){return this.sourcesContent[t]}if(n){return null}throw new Error('"'+e+'" is not in the SourceMap.')}generatedPositionFor(e){let n=o.getArg(e,"source");n=this._findSourceIndex(n);if(n<0){return{line:null,column:null,lastColumn:null}}const t={source:n,originalLine:o.getArg(e,"line"),originalColumn:o.getArg(e,"column")};if(t.originalLine<1){throw new Error("Line numbers must be >= 1")}if(t.originalColumn<0){throw new Error("Column numbers must be >= 0")}let r=o.getArg(e,"bias",SourceMapConsumer.GREATEST_LOWER_BOUND);if(r==null){r=SourceMapConsumer.GREATEST_LOWER_BOUND}let s;this._wasm.withMappingCallback((e=>s=e),(()=>{this._wasm.exports.generated_location_for(this._getMappingsPtr(),t.source,t.originalLine-1,t.originalColumn,r)}));if(s){if(s.source===t.source){let e=s.lastGeneratedColumn;if(this._computedColumnSpans&&e===null){e=Infinity}return{line:o.getArg(s,"generatedLine",null),column:o.getArg(s,"generatedColumn",null),lastColumn:e}}}return{line:null,column:null,lastColumn:null}}}BasicSourceMapConsumer.prototype.consumer=SourceMapConsumer;r=BasicSourceMapConsumer;class IndexedSourceMapConsumer extends SourceMapConsumer{constructor(e,n){return super(c).then((t=>{let r=e;if(typeof e==="string"){r=o.parseSourceMapInput(e)}const s=o.getArg(r,"version");const i=o.getArg(r,"sections");if(s!=t._version){throw new Error("Unsupported version: "+s)}let l={line:-1,column:0};return Promise.all(i.map((e=>{if(e.url){throw new Error("Support for url field in sections not implemented.")}const t=o.getArg(e,"offset");const r=o.getArg(t,"line");const s=o.getArg(t,"column");if(r<l.line||r===l.line&&s<l.column){throw new Error("Section offsets must be ordered and non-overlapping.")}l=t;const i=new SourceMapConsumer(o.getArg(e,"map"),n);return i.then((e=>({generatedOffset:{generatedLine:r+1,generatedColumn:s+1},consumer:e})))}))).then((e=>{t._sections=e;return t}))}))}get sources(){const e=[];for(let n=0;n<this._sections.length;n++){for(let t=0;t<this._sections[n].consumer.sources.length;t++){e.push(this._sections[n].consumer.sources[t])}}return e}originalPositionFor(e){const n={generatedLine:o.getArg(e,"line"),generatedColumn:o.getArg(e,"column")};const t=s.search(n,this._sections,(function(e,n){const t=e.generatedLine-n.generatedOffset.generatedLine;if(t){return t}return e.generatedColumn-n.generatedOffset.generatedColumn}));const r=this._sections[t];if(!r){return{source:null,line:null,column:null,name:null}}return r.consumer.originalPositionFor({line:n.generatedLine-(r.generatedOffset.generatedLine-1),column:n.generatedColumn-(r.generatedOffset.generatedLine===n.generatedLine?r.generatedOffset.generatedColumn-1:0),bias:e.bias})}hasContentsOfAllSources(){return this._sections.every((function(e){return e.consumer.hasContentsOfAllSources()}))}sourceContentFor(e,n){for(let n=0;n<this._sections.length;n++){const t=this._sections[n];const r=t.consumer.sourceContentFor(e,true);if(r){return r}}if(n){return null}throw new Error('"'+e+'" is not in the SourceMap.')}_findSectionIndex(e){for(let n=0;n<this._sections.length;n++){const{consumer:t}=this._sections[n];if(t._findSourceIndex(e)!==-1){return n}}return-1}generatedPositionFor(e){const n=this._findSectionIndex(o.getArg(e,"source"));const t=n>=0?this._sections[n]:null;const r=n>=0&&n+1<this._sections.length?this._sections[n+1]:null;const s=t&&t.consumer.generatedPositionFor(e);if(s&&s.line!==null){const e=t.generatedOffset.generatedLine-1;const n=t.generatedOffset.generatedColumn-1;if(s.line===1){s.column+=n;if(typeof s.lastColumn==="number"){s.lastColumn+=n}}if(s.lastColumn===Infinity&&r&&s.line===r.generatedOffset.generatedLine){s.lastColumn=r.generatedOffset.generatedColumn-2}s.line+=e;return s}return{line:null,column:null,lastColumn:null}}allGeneratedPositionsFor(e){const n=this._findSectionIndex(o.getArg(e,"source"));const t=n>=0?this._sections[n]:null;const r=n>=0&&n+1<this._sections.length?this._sections[n+1]:null;if(!t)return[];return t.consumer.allGeneratedPositionsFor(e).map((e=>{const n=t.generatedOffset.generatedLine-1;const o=t.generatedOffset.generatedColumn-1;if(e.line===1){e.column+=o;if(typeof e.lastColumn==="number"){e.lastColumn+=o}}if(e.lastColumn===Infinity&&r&&e.line===r.generatedOffset.generatedLine){e.lastColumn=r.generatedOffset.generatedColumn-2}e.line+=n;return e}))}eachMapping(e,n,t){this._sections.forEach(((r,o)=>{const s=o+1<this._sections.length?this._sections[o+1]:null;const{generatedOffset:i}=r;const l=i.generatedLine-1;const a=i.generatedColumn-1;r.consumer.eachMapping((function(n){if(n.generatedLine===1){n.generatedColumn+=a;if(typeof n.lastGeneratedColumn==="number"){n.lastGeneratedColumn+=a}}if(n.lastGeneratedColumn===Infinity&&s&&n.generatedLine===s.generatedOffset.generatedLine){n.lastGeneratedColumn=s.generatedOffset.generatedColumn-2}n.generatedLine+=l;e.call(this,n)}),n,t)}))}computeColumnSpans(){for(let e=0;e<this._sections.length;e++){this._sections[e].consumer.computeColumnSpans()}}destroy(){for(let e=0;e<this._sections.length;e++){this._sections[e].consumer.destroy()}}}r=IndexedSourceMapConsumer;function _factory(e,n){let t=e;if(typeof e==="string"){t=o.parseSourceMapInput(e)}const r=t.sections!=null?new IndexedSourceMapConsumer(t,n):new BasicSourceMapConsumer(t,n);return Promise.resolve(r)}function _factoryBSM(e,n){return BasicSourceMapConsumer.fromSourceMap(e,n)}},982:(e,n,t)=>{const r=t(464);const o=t(211);const s=t(908).I;const i=t(47).H;class SourceMapGenerator{constructor(e){if(!e){e={}}this._file=o.getArg(e,"file",null);this._sourceRoot=o.getArg(e,"sourceRoot",null);this._skipValidation=o.getArg(e,"skipValidation",false);this._sources=new s;this._names=new s;this._mappings=new i;this._sourcesContents=null}static fromSourceMap(e){const n=e.sourceRoot;const t=new SourceMapGenerator({file:e.file,sourceRoot:n});e.eachMapping((function(e){const r={generated:{line:e.generatedLine,column:e.generatedColumn}};if(e.source!=null){r.source=e.source;if(n!=null){r.source=o.relative(n,r.source)}r.original={line:e.originalLine,column:e.originalColumn};if(e.name!=null){r.name=e.name}}t.addMapping(r)}));e.sources.forEach((function(r){let s=r;if(n!==null){s=o.relative(n,r)}if(!t._sources.has(s)){t._sources.add(s)}const i=e.sourceContentFor(r);if(i!=null){t.setSourceContent(r,i)}}));return t}addMapping(e){const n=o.getArg(e,"generated");const t=o.getArg(e,"original",null);let r=o.getArg(e,"source",null);let s=o.getArg(e,"name",null);if(!this._skipValidation){this._validateMapping(n,t,r,s)}if(r!=null){r=String(r);if(!this._sources.has(r)){this._sources.add(r)}}if(s!=null){s=String(s);if(!this._names.has(s)){this._names.add(s)}}this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:t!=null&&t.line,originalColumn:t!=null&&t.column,source:r,name:s})}setSourceContent(e,n){let t=e;if(this._sourceRoot!=null){t=o.relative(this._sourceRoot,t)}if(n!=null){if(!this._sourcesContents){this._sourcesContents=Object.create(null)}this._sourcesContents[o.toSetString(t)]=n}else if(this._sourcesContents){delete this._sourcesContents[o.toSetString(t)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}}applySourceMap(e,n,t){let r=n;if(n==null){if(e.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}r=e.file}const i=this._sourceRoot;if(i!=null){r=o.relative(i,r)}const l=this._mappings.toArray().length>0?new s:this._sources;const a=new s;this._mappings.unsortedForEach((function(n){if(n.source===r&&n.originalLine!=null){const r=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});if(r.source!=null){n.source=r.source;if(t!=null){n.source=o.join(t,n.source)}if(i!=null){n.source=o.relative(i,n.source)}n.originalLine=r.line;n.originalColumn=r.column;if(r.name!=null){n.name=r.name}}}const s=n.source;if(s!=null&&!l.has(s)){l.add(s)}const u=n.name;if(u!=null&&!a.has(u)){a.add(u)}}),this);this._sources=l;this._names=a;e.sources.forEach((function(n){const r=e.sourceContentFor(n);if(r!=null){if(t!=null){n=o.join(t,n)}if(i!=null){n=o.relative(i,n)}this.setSourceContent(n,r)}}),this)}_validateMapping(e,n,t,r){if(n&&typeof n.line!=="number"&&typeof n.column!=="number"){throw new Error("original.line and original.column are not numbers -- you probably meant to omit "+"the original mapping entirely and only map the generated position. If so, pass "+"null for the original mapping instead of an object with empty or null values.")}if(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!n&&!t&&!r){}else if(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&t){}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:t,original:n,name:r}))}}_serializeMappings(){let e=0;let n=1;let t=0;let s=0;let i=0;let l=0;let a="";let u;let c;let g;let f;const h=this._mappings.toArray();for(let p=0,m=h.length;p<m;p++){c=h[p];u="";if(c.generatedLine!==n){e=0;while(c.generatedLine!==n){u+=";";n++}}else if(p>0){if(!o.compareByGeneratedPositionsInflated(c,h[p-1])){continue}u+=","}u+=r.encode(c.generatedColumn-e);e=c.generatedColumn;if(c.source!=null){f=this._sources.indexOf(c.source);u+=r.encode(f-l);l=f;u+=r.encode(c.originalLine-1-s);s=c.originalLine-1;u+=r.encode(c.originalColumn-t);t=c.originalColumn;if(c.name!=null){g=this._names.indexOf(c.name);u+=r.encode(g-i);i=g}}a+=u}return a}_generateSourcesContent(e,n){return e.map((function(e){if(!this._sourcesContents){return null}if(n!=null){e=o.relative(n,e)}const t=o.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,t)?this._sourcesContents[t]:null}),this)}toJSON(){const e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){e.file=this._file}if(this._sourceRoot!=null){e.sourceRoot=this._sourceRoot}if(this._sourcesContents){e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)}return e}toString(){return JSON.stringify(this.toJSON())}}SourceMapGenerator.prototype._version=3;n.SourceMapGenerator=SourceMapGenerator},207:(e,n,t)=>{const r=t(982).SourceMapGenerator;const o=t(211);const s=/(\r?\n)/;const i=10;const l="$$$isSourceNode$$$";class SourceNode{constructor(e,n,t,r,o){this.children=[];this.sourceContents={};this.line=e==null?null:e;this.column=n==null?null:n;this.source=t==null?null:t;this.name=o==null?null:o;this[l]=true;if(r!=null)this.add(r)}static fromStringWithSourceMap(e,n,t){const r=new SourceNode;const i=e.split(s);let l=0;const shiftNextLine=function(){const e=getNextLine();const n=getNextLine()||"";return e+n;function getNextLine(){return l<i.length?i[l++]:undefined}};let a=1,u=0;let c=null;let g;n.eachMapping((function(e){if(c!==null){if(a<e.generatedLine){addMappingWithCode(c,shiftNextLine());a++;u=0}else{g=i[l]||"";const n=g.substr(0,e.generatedColumn-u);i[l]=g.substr(e.generatedColumn-u);u=e.generatedColumn;addMappingWithCode(c,n);c=e;return}}while(a<e.generatedLine){r.add(shiftNextLine());a++}if(u<e.generatedColumn){g=i[l]||"";r.add(g.substr(0,e.generatedColumn));i[l]=g.substr(e.generatedColumn);u=e.generatedColumn}c=e}),this);if(l<i.length){if(c){addMappingWithCode(c,shiftNextLine())}r.add(i.splice(l).join(""))}n.sources.forEach((function(e){const s=n.sourceContentFor(e);if(s!=null){if(t!=null){e=o.join(t,e)}r.setSourceContent(e,s)}}));return r;function addMappingWithCode(e,n){if(e===null||e.source===undefined){r.add(n)}else{const s=t?o.join(t,e.source):e.source;r.add(new SourceNode(e.originalLine,e.originalColumn,s,n,e.name))}}}add(e){if(Array.isArray(e)){e.forEach((function(e){this.add(e)}),this)}else if(e[l]||typeof e==="string"){if(e){this.children.push(e)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e)}return this}prepend(e){if(Array.isArray(e)){for(let n=e.length-1;n>=0;n--){this.prepend(e[n])}}else if(e[l]||typeof e==="string"){this.children.unshift(e)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e)}return this}walk(e){let n;for(let t=0,r=this.children.length;t<r;t++){n=this.children[t];if(n[l]){n.walk(e)}else if(n!==""){e(n,{source:this.source,line:this.line,column:this.column,name:this.name})}}}join(e){let n;let t;const r=this.children.length;if(r>0){n=[];for(t=0;t<r-1;t++){n.push(this.children[t]);n.push(e)}n.push(this.children[t]);this.children=n}return this}replaceRight(e,n){const t=this.children[this.children.length-1];if(t[l]){t.replaceRight(e,n)}else if(typeof t==="string"){this.children[this.children.length-1]=t.replace(e,n)}else{this.children.push("".replace(e,n))}return this}setSourceContent(e,n){this.sourceContents[o.toSetString(e)]=n}walkSourceContents(e){for(let n=0,t=this.children.length;n<t;n++){if(this.children[n][l]){this.children[n].walkSourceContents(e)}}const n=Object.keys(this.sourceContents);for(let t=0,r=n.length;t<r;t++){e(o.fromSetString(n[t]),this.sourceContents[n[t]])}}toString(){let e="";this.walk((function(n){e+=n}));return e}toStringWithSourceMap(e){const n={code:"",line:1,column:0};const t=new r(e);let o=false;let s=null;let l=null;let a=null;let u=null;this.walk((function(e,r){n.code+=e;if(r.source!==null&&r.line!==null&&r.column!==null){if(s!==r.source||l!==r.line||a!==r.column||u!==r.name){t.addMapping({source:r.source,original:{line:r.line,column:r.column},generated:{line:n.line,column:n.column},name:r.name})}s=r.source;l=r.line;a=r.column;u=r.name;o=true}else if(o){t.addMapping({generated:{line:n.line,column:n.column}});s=null;o=false}for(let l=0,a=e.length;l<a;l++){if(e.charCodeAt(l)===i){n.line++;n.column=0;if(l+1===a){s=null;o=false}else if(o){t.addMapping({source:r.source,original:{line:r.line,column:r.column},generated:{line:n.line,column:n.column},name:r.name})}}else{n.column++}}}));this.walkSourceContents((function(e,n){t.setSourceContent(e,n)}));return{code:n.code,map:t}}}n.SourceNode=SourceNode},662:(e,n,t)=>{"use strict";e.exports=typeof URL==="function"?URL:t(310).URL},211:(e,n,t)=>{const r=t(662);function getArg(e,n,t){if(n in e){return e[n]}else if(arguments.length===3){return t}throw new Error('"'+n+'" is a required argument.')}n.getArg=getArg;const o=function(){const e=Object.create(null);return!("__proto__"in e)}();function identity(e){return e}function toSetString(e){if(isProtoString(e)){return"$"+e}return e}n.toSetString=o?identity:toSetString;function fromSetString(e){if(isProtoString(e)){return e.slice(1)}return e}n.fromSetString=o?identity:fromSetString;function isProtoString(e){if(!e){return false}const n=e.length;if(n<9){return false}if(e.charCodeAt(n-1)!==95||e.charCodeAt(n-2)!==95||e.charCodeAt(n-3)!==111||e.charCodeAt(n-4)!==116||e.charCodeAt(n-5)!==111||e.charCodeAt(n-6)!==114||e.charCodeAt(n-7)!==112||e.charCodeAt(n-8)!==95||e.charCodeAt(n-9)!==95){return false}for(let t=n-10;t>=0;t--){if(e.charCodeAt(t)!==36){return false}}return true}function strcmp(e,n){if(e===n){return 0}if(e===null){return 1}if(n===null){return-1}if(e>n){return 1}return-1}function compareByGeneratedPositionsInflated(e,n){let t=e.generatedLine-n.generatedLine;if(t!==0){return t}t=e.generatedColumn-n.generatedColumn;if(t!==0){return t}t=strcmp(e.source,n.source);if(t!==0){return t}t=e.originalLine-n.originalLine;if(t!==0){return t}t=e.originalColumn-n.originalColumn;if(t!==0){return t}return strcmp(e.name,n.name)}n.compareByGeneratedPositionsInflated=compareByGeneratedPositionsInflated;function parseSourceMapInput(e){return JSON.parse(e.replace(/^\)]}'[^\n]*\n/,""))}n.parseSourceMapInput=parseSourceMapInput;const s="http:";const i=`${s}//host`;function createSafeHandler(e){return n=>{const t=getURLType(n);const o=buildSafeBase(n);const l=new r(n,o);e(l);const a=l.toString();if(t==="absolute"){return a}else if(t==="scheme-relative"){return a.slice(s.length)}else if(t==="path-absolute"){return a.slice(i.length)}return computeRelativeURL(o,a)}}function withBase(e,n){return new r(e,n).toString()}function buildUniqueSegment(e,n){let t=0;do{const r=e+t++;if(n.indexOf(r)===-1)return r}while(true)}function buildSafeBase(e){const n=e.split("..").length-1;const t=buildUniqueSegment("p",e);let r=`${i}/`;for(let e=0;e<n;e++){r+=`${t}/`}return r}const l=/^[A-Za-z0-9\+\-\.]+:/;function getURLType(e){if(e[0]==="/"){if(e[1]==="/")return"scheme-relative";return"path-absolute"}return l.test(e)?"absolute":"path-relative"}function computeRelativeURL(e,n){if(typeof e==="string")e=new r(e);if(typeof n==="string")n=new r(n);const t=n.pathname.split("/");const o=e.pathname.split("/");if(o.length>0&&!o[o.length-1]){o.pop()}while(t.length>0&&o.length>0&&t[0]===o[0]){t.shift();o.shift()}const s=o.map((()=>"..")).concat(t).join("/");return s+n.search+n.hash}const a=createSafeHandler((e=>{e.pathname=e.pathname.replace(/\/?$/,"/")}));const u=createSafeHandler((e=>{e.href=new r(".",e.toString()).toString()}));const c=createSafeHandler((e=>{}));n.normalize=c;function join(e,n){const t=getURLType(n);const r=getURLType(e);e=a(e);if(t==="absolute"){return withBase(n,undefined)}if(r==="absolute"){return withBase(n,e)}if(t==="scheme-relative"){return c(n)}if(r==="scheme-relative"){return withBase(n,withBase(e,i)).slice(s.length)}if(t==="path-absolute"){return c(n)}if(r==="path-absolute"){return withBase(n,withBase(e,i)).slice(i.length)}const o=buildSafeBase(n+e);const l=withBase(n,withBase(e,o));return computeRelativeURL(o,l)}n.join=join;function relative(e,n){const t=relativeIfPossible(e,n);return typeof t==="string"?t:c(n)}n.relative=relative;function relativeIfPossible(e,n){const t=getURLType(e);if(t!==getURLType(n)){return null}const o=buildSafeBase(e+n);const s=new r(e,o);const i=new r(n,o);try{new r("",i.toString())}catch(e){return null}if(i.protocol!==s.protocol||i.user!==s.user||i.password!==s.password||i.hostname!==s.hostname||i.port!==s.port){return null}return computeRelativeURL(s,i)}function computeSourceURL(e,n,t){if(e&&getURLType(n)==="path-absolute"){n=n.replace(/^\//,"")}let r=c(n||"");if(e)r=join(e,r);if(t)r=join(u(t),r);return r}n.computeSourceURL=computeSourceURL},898:(e,n,t)=>{const r=t(853);function Mapping(){this.generatedLine=0;this.generatedColumn=0;this.lastGeneratedColumn=null;this.source=null;this.originalLine=null;this.originalColumn=null;this.name=null}let o=null;e.exports=function wasm(){if(o){return o}const e=[];o=r().then((n=>WebAssembly.instantiate(n,{env:{mapping_callback(n,t,r,o,s,i,l,a,u,c){const g=new Mapping;g.generatedLine=n+1;g.generatedColumn=t;if(r){g.lastGeneratedColumn=o-1}if(s){g.source=i;g.originalLine=l+1;g.originalColumn=a;if(u){g.name=c}}e[e.length-1](g)},start_all_generated_locations_for(){console.time("all_generated_locations_for")},end_all_generated_locations_for(){console.timeEnd("all_generated_locations_for")},start_compute_column_spans(){console.time("compute_column_spans")},end_compute_column_spans(){console.timeEnd("compute_column_spans")},start_generated_location_for(){console.time("generated_location_for")},end_generated_location_for(){console.timeEnd("generated_location_for")},start_original_location_for(){console.time("original_location_for")},end_original_location_for(){console.timeEnd("original_location_for")},start_parse_mappings(){console.time("parse_mappings")},end_parse_mappings(){console.timeEnd("parse_mappings")},start_sort_by_generated_location(){console.time("sort_by_generated_location")},end_sort_by_generated_location(){console.timeEnd("sort_by_generated_location")},start_sort_by_original_location(){console.time("sort_by_original_location")},end_sort_by_original_location(){console.timeEnd("sort_by_original_location")}}}))).then((n=>({exports:n.instance.exports,withMappingCallback:(n,t)=>{e.push(n);try{t()}finally{e.pop()}}}))).then(null,(e=>{o=null;throw e}));return o}},147:e=>{"use strict";e.exports=require("fs")},17:e=>{"use strict";e.exports=require("path")},310:e=>{"use strict";e.exports=require("url")}};var n={};function __nccwpck_require__(t){var r=n[t];if(r!==undefined){return r.exports}var o=n[t]={exports:{}};var s=true;try{e[t](o,o.exports,__nccwpck_require__);s=false}finally{if(s)delete n[t]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var t={};(()=>{var e=t;e.SourceMapGenerator=__nccwpck_require__(982).SourceMapGenerator;e.SourceMapConsumer=__nccwpck_require__(217).SourceMapConsumer;e.SourceNode=__nccwpck_require__(207).SourceNode})();module.exports=t})();
\ No newline at end of file
{"name":"source-map","main":"index.js","author":"Nick Fitzgerald <nfitzgerald@mozilla.com>","license":"BSD-3-Clause"}
MIT License
Copyright (c) 2014-2019 Georg Tavonius
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.
(()=>{"use strict";if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var e={};(()=>{var r=e;Object.defineProperty(r,"__esModule",{value:true});var n="<unknown>";function parse(e){var r=e.split("\n");return r.reduce((function(e,r){var n=parseChrome(r)||parseWinjs(r)||parseGecko(r)||parseNode(r)||parseJSC(r);if(n){e.push(n)}return e}),[])}var a=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;var l=/\((\S*)(?::(\d+))(?::(\d+))\)/;function parseChrome(e){var r=a.exec(e);if(!r){return null}var u=r[2]&&r[2].indexOf("native")===0;var t=r[2]&&r[2].indexOf("eval")===0;var i=l.exec(r[2]);if(t&&i!=null){r[2]=i[1];r[3]=i[2];r[4]=i[3]}return{file:!u?r[2]:null,methodName:r[1]||n,arguments:u?[r[2]]:[],lineNumber:r[3]?+r[3]:null,column:r[4]?+r[4]:null}}var u=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i;function parseWinjs(e){var r=u.exec(e);if(!r){return null}return{file:r[2],methodName:r[1]||n,arguments:[],lineNumber:+r[3],column:r[4]?+r[4]:null}}var t=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i;var i=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;function parseGecko(e){var r=t.exec(e);if(!r){return null}var a=r[3]&&r[3].indexOf(" > eval")>-1;var l=i.exec(r[3]);if(a&&l!=null){r[3]=l[1];r[4]=l[2];r[5]=null}return{file:r[3],methodName:r[1]||n,arguments:r[2]?r[2].split(","):[],lineNumber:r[4]?+r[4]:null,column:r[5]?+r[5]:null}}var s=/^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i;function parseJSC(e){var r=s.exec(e);if(!r){return null}return{file:r[3],methodName:r[1]||n,arguments:[],lineNumber:+r[4],column:r[5]?+r[5]:null}}var o=/^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;function parseNode(e){var r=o.exec(e);if(!r){return null}return{file:r[2],methodName:r[1]||n,arguments:[],lineNumber:+r[3],column:r[4]?+r[4]:null}}r.parse=parse})();module.exports=e})();
\ No newline at end of file
{"name":"stacktrace-parser","main":"index.js","author":"Georg Tavonius <g.tavonius@gmail.com> (http://jaz-lounge.com)","license":"MIT"}
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.
var e={};(()=>{e.d=(t,r)=>{for(var n in r){if(e.o(r,n)&&!e.o(t,n)){Object.defineProperty(t,n,{enumerable:true,get:r[n]})}}}})();(()=>{e.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();if(typeof e!=="undefined")e.ab=new URL(".",import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/)?1:0,-1)+"/";var t={};e.d(t,{Z:()=>stripAnsi});function ansiRegex({onlyFirst:e=false}={}){const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(t,e?undefined:"g")}function stripAnsi(e){if(typeof e!=="string"){throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``)}return e.replace(ansiRegex(),"")}var r=t.Z;export{r as default};
\ No newline at end of file
{"name":"strip-ansi","main":"index.js","author":{"name":"Sindre Sorhus","email":"sindresorhus@gmail.com","url":"https://sindresorhus.com"},"license":"MIT"}
import { initializeHMR } from './client'
initializeHMR({
assetPrefix: '',
})
import { connect } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import {
connectHMR,
addMessageListener,
sendMessage,
} from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
import { register, ReactDevOverlay } from '../overlay/client'
export function initializeHMR(options: { assetPrefix: string }) {
connect({
addMessageListener,
sendMessage,
})
connectHMR({
assetPrefix: options.assetPrefix,
log: true,
path: '/turbopack-hmr',
})
register()
}
export { ReactDevOverlay }
'use client'
import type React from 'react'
import { useRouter, usePathname } from 'next/dist/client/components/navigation'
import { useEffect } from 'react'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { ReactDevOverlay } from './client'
import { sendMessage } from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
type HotReloadProps = React.PropsWithChildren<{
assetPrefix?: string
}>
export default function HotReload({ children }: HotReloadProps) {
const router = useRouter()
const path = usePathname()!.slice(1)
useEffect(() => {
const unsubscribe = subscribeToUpdate(
{
path,
headers: {
rsc: '1',
},
},
sendMessage,
(update) => {
if (update.type !== 'issues') {
router.refresh()
}
}
)
return unsubscribe
}, [router, path])
return <ReactDevOverlay globalOverlay={true}>{children}</ReactDevOverlay>
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startOperationStreamHandler from '../internal/operation-stream'
import 'next/dist/server/node-polyfill-fetch'
import { join } from 'path'
import { parse as parseUrl } from 'node:url'
import { runEdgeFunction } from '../internal/edge'
import { headersFromEntries, initProxiedHeaders } from '../internal/headers'
import { NodeNextRequest } from 'next/dist/server/base-http/node'
import type { IncomingMessage } from 'node:http'
import type { RenderData } from 'types/turbopack'
import chunkGroup from 'INNER_EDGE_CHUNK_GROUP'
import { attachRequestMeta } from '../internal/next-request-helpers'
import { Readable } from 'stream'
startOperationStreamHandler(async (renderData: RenderData, respond) => {
const { response } = await runOperation(renderData)
if (response == null) {
throw new Error('no html returned')
}
const channel = respond({
status: response.status,
// @ts-expect-error Headers is iterable since node.js 18
headers: [...response.headers],
})
if (response.body) {
const reader = response.body.getReader()
for (;;) {
let { done, value } = await reader.read()
if (done) {
break
}
channel.chunk(Buffer.from(value!))
}
}
channel.end()
})
async function runOperation(renderData: RenderData) {
const edgeInfo = {
name: 'edge',
paths: chunkGroup
.filter((chunk) => chunk.endsWith('.js'))
.map((chunk: string) => join(process.cwd(), '.next/server/app', chunk)),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
const parsedUrl = parseUrl(renderData.originalUrl, true)
const incoming = new Readable() as IncomingMessage
incoming.push(null)
incoming.url = renderData.originalUrl
incoming.method = renderData.method
incoming.headers = initProxiedHeaders(
headersFromEntries(renderData.rawHeaders),
renderData.data?.serverInfo
)
const req = new NodeNextRequest(incoming)
attachRequestMeta(req, parsedUrl, req.headers.host!)
const res = await runEdgeFunction({
edgeInfo,
outputDir: 'edge-pages',
req,
query: renderData.rawQuery,
params: renderData.params,
path: renderData.path,
onWarning(warning) {
console.warn(warning)
},
})
return res as { response: Response }
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startOperationStreamHandler from '../internal/operation-stream'
import '../polyfill/app-polyfills.ts'
import 'next/dist/server/require-hook'
import type { IncomingMessage } from 'node:http'
import type { RenderData } from 'types/turbopack'
import type { RenderOpts } from 'next/dist/server/app-render/types'
import { RSC_VARY_HEADER } from 'next/dist/client/components/app-router-headers'
import { headersFromEntries, initProxiedHeaders } from '../internal/headers'
import { parse, ParsedUrlQuery } from 'node:querystring'
import { PassThrough } from 'node:stream'
;('TURBOPACK { chunking-type: isolatedParallel }')
import entry from 'APP_ENTRY'
import BOOTSTRAP from 'APP_BOOTSTRAP'
import { createServerResponse } from '../internal/http'
import { createManifests, installRequireAndChunkLoad } from './app/manifest'
import { join } from 'node:path'
import { nodeFs } from 'next/dist/server/lib/node-fs-methods'
import { IncrementalCache } from 'next/dist/server/lib/incremental-cache'
const {
renderToHTMLOrFlight,
} = require('next/dist/compiled/next-server/app-page.runtime.dev')
installRequireAndChunkLoad()
const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
startOperationStreamHandler(async (renderData: RenderData, respond) => {
const result = await runOperation(renderData)
if (result == null) {
throw new Error('no html returned')
}
const channel = respond({
status: result.statusCode,
headers: result.headers,
})
for await (const chunk of result.body) {
channel.chunk(chunk as Buffer)
}
channel.end()
})
async function runOperation(renderData: RenderData) {
const { clientReferenceManifest } = createManifests()
const req: IncomingMessage = {
url: renderData.originalUrl,
method: renderData.method,
headers: initProxiedHeaders(
headersFromEntries(renderData.rawHeaders),
renderData.data?.serverInfo
),
} as any
const url = new URL(renderData.originalUrl, 'next://')
const res = createServerResponse(req, renderData.path)
const query = parse(renderData.rawQuery)
const renderOpt: Omit<
RenderOpts,
'App' | 'Document' | 'Component' | 'page'
> & {
params: ParsedUrlQuery
} = {
// TODO: give an actual buildId when next build is supported
buildId: 'development',
basePath: '',
params: renderData.params,
supportsDynamicHTML: true,
dev: true,
buildManifest: {
polyfillFiles: [],
rootMainFiles: BOOTSTRAP.filter((path) => path.endsWith('.js')),
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
pages: {
'/_app': [],
},
ampFirstPages: [],
},
ComponentMod: {
...entry,
__next_app__: {
require: __next_require__,
loadChunk: __next_chunk_load__,
},
pages: ['page.js'],
},
incrementalCache: new IncrementalCache({
fs: nodeFs,
dev: true,
requestHeaders: { ...req.headers },
requestProtocol: url.protocol.replace(/:$/, '') as 'http' | 'https',
appDir: true,
allowedRevalidateHeaderKeys: renderData.data?.allowedRevalidateHeaderKeys,
minimalMode: false,
serverDistDir: join(process.cwd(), '.next/server'),
fetchCache: true,
fetchCacheKeyPrefix: renderData.data?.fetchCacheKeyPrefix,
maxMemoryCacheSize: renderData.data?.isrMemoryCacheSize,
flushToDisk: false,
getPrerenderManifest: () => ({
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: '',
},
notFoundRoutes: [],
}),
CurCacheHandler: undefined,
}),
clientReferenceManifest,
runtime: 'nodejs',
serverComponents: true,
assetPrefix: '',
pageConfig: {},
reactLoadableManifest: {},
nextConfigOutput: renderData.data?.nextConfigOutput,
}
const result = await renderToHTMLOrFlight(
req,
res,
renderData.path,
query,
renderOpt as any as RenderOpts
)
if (!result || result.isNull) throw new Error('rendering was not successful')
const body = new PassThrough()
if (result.isDynamic) {
result.pipe(body)
} else {
body.write(result.toUnchunkedString())
}
return {
statusCode: res.statusCode,
headers: [
['Content-Type', result.contentType ?? MIME_TEXT_HTML_UTF8],
['Vary', RSC_VARY_HEADER],
] as [string, string][],
body,
}
}
import { adapter } from 'next/dist/server/web/adapter'
import { RSC_VARY_HEADER } from 'next/dist/client/components/app-router-headers'
import { IncrementalCache } from 'next/dist/server/lib/incremental-cache'
import { renderToHTMLOrFlight } from 'next/dist/server/app-render/app-render'
;('TURBOPACK { chunking-type: isolatedParallel }')
import entry from 'APP_ENTRY'
import BOOTSTRAP from 'APP_BOOTSTRAP'
import { createManifests, installRequireAndChunkLoad } from './manifest'
import type { NextRequest, NextFetchEvent } from 'next/server'
import type { RenderOpts } from 'next/dist/server/app-render/types'
import type { ParsedUrlQuery } from 'querystring'
installRequireAndChunkLoad()
// avoid limiting stack traces to 10 lines
Error.stackTraceLimit = 100
const { clientReferenceManifest } = createManifests()
const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
async function render(request: NextRequest, event: NextFetchEvent) {
const renderOpt: Omit<
RenderOpts,
'App' | 'Document' | 'Component' | 'page'
> & { params: ParsedUrlQuery } = {
// TODO(WEB-1195) params
params: {},
supportsDynamicHTML: true,
dev: true,
buildId: 'development',
basePath: '',
buildManifest: {
polyfillFiles: [],
rootMainFiles: BOOTSTRAP.filter((path) => path.endsWith('.js')),
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
pages: {
'/_app': [],
},
ampFirstPages: [],
},
ComponentMod: {
...entry,
__next_app__: {
require: __next_require__,
loadChunk: __next_chunk_load__,
},
pages: ['page.js'],
},
clientReferenceManifest,
runtime: 'nodejs',
serverComponents: true,
assetPrefix: '',
pageConfig: {},
reactLoadableManifest: {},
// TODO nextConfigOutput
nextConfigOutput: undefined,
}
const tranform = new TransformStream()
const response = new Response(tranform.readable)
let { pathname, search: query } = new URL(request.url, 'next://')
const result = await renderToHTMLOrFlight(
// @ts-expect-error - TODO renderToHTMLOrFlight types should accept web platform types
request,
response,
pathname,
// TODO(WEB-1195) query
{},
renderOpt as any as RenderOpts
)
response.headers.append(
'Content-Type',
result.contentType || MIME_TEXT_HTML_UTF8
)
response.headers.append('Vary', RSC_VARY_HEADER)
const writer = tranform.writable.getWriter()
let innerClose: undefined | (() => void)
const target = {
write: (chunk: Uint8Array) => writer.write(chunk),
end: () => writer.close(),
on(_event: 'close', cb: () => void) {
innerClose = cb
},
off(_event: 'close', _cb: () => void) {
innerClose = undefined
},
}
const onClose = () => {
innerClose?.()
}
// No, this cannot be replaced with `finally`, because early cancelling
// the stream will create a rejected promise, and finally will create an
// unhandled rejection.
writer.closed.then(onClose, onClose)
result.pipe(target)
return response
}
// adapter uses this to detect edge rendering
self.__BUILD_MANIFEST = {}
// @ts-expect-error - exposed for edge support
globalThis._ENTRIES = {
middleware_edge: {
default: function (opts: any) {
return adapter({
...opts,
IncrementalCache,
handler: render,
})
},
},
}
import { EdgeRouteModuleWrapper } from 'next/dist/server/web/edge-route-module-wrapper'
import { AppRouteRouteModule } from 'next/dist/server/future/route-modules/app-route/module'
import { RouteKind } from 'next/dist/server/future/route-kind'
import * as userland from 'ENTRY'
import { PAGE, PATHNAME } from 'BOOTSTRAP_CONFIG'
// TODO: (wyattjoh) - perform the option construction in Rust to allow other modules to accept different options
const routeModule = new AppRouteRouteModule({
userland,
definition: {
kind: RouteKind.APP_ROUTE,
page: PAGE,
pathname: PATHNAME,
// The following aren't used in production.
filename: '',
bundlePath: '',
},
resolvedPagePath: `app/${PAGE}`,
nextConfigOutput: undefined,
})
// @ts-expect-error - exposed for edge support
globalThis._ENTRIES = {
middleware_edge: {
default: EdgeRouteModuleWrapper.wrap(routeModule, {
page: `/${PAGE}`,
}),
},
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { join } from 'path'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { runEdgeFunction, updateResponse } from '../../internal/edge'
import { attachRequestMeta } from '../../internal/next-request-helpers'
import chunkGroup from 'ROUTE_CHUNK_GROUP'
startHandler(async ({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const edgeInfo = {
name: 'edge',
paths: chunkGroup.map((chunk) =>
join(process.cwd(), '.next/server/app', chunk)
),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
const result = await runEdgeFunction({
edgeInfo,
outputDir: 'app',
req,
query,
params,
path,
onWarning(warning) {
console.warn(warning)
},
})
updateResponse(res, result)
})
import ReactDOMClient from 'react-dom/client'
import React, { use } from 'react'
import type { ReactElement } from 'react'
import { version } from 'next/package.json'
import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-webpack/client'
import { callServer } from 'next/dist/client/app-call-server'
import { linkGc } from 'next/dist/client/app-link-gc'
import { HeadManagerContext } from 'next/dist/shared/lib/head-manager-context.shared-runtime'
import { initializeHMR } from '@vercel/turbopack-next/dev/client'
initializeHMR({
assetPrefix: '',
})
window.next = {
version,
appDir: true,
}
globalThis.__next_require__ = (data) => {
const [client_id] = JSON.parse(data)
return __turbopack_require__(client_id)
}
globalThis.__next_chunk_load__ = __turbopack_load__
const appElement = document
const getCacheKey = () => {
const { pathname, search } = location
return pathname + search
}
const encoder = new TextEncoder()
let initialServerDataBuffer: string[] | undefined = undefined
let initialServerDataWriter: ReadableStreamDefaultController | undefined =
undefined
let initialServerDataLoaded = false
let initialServerDataFlushed = false
let initialFormStateData: null | any = null
function nextServerDataCallback(
seg:
| [isBootStrap: 0]
| [isNotBootstrap: 1, responsePartial: string]
| [isFormState: 2, formState: any]
): number {
if (seg[0] === 0) {
initialServerDataBuffer = []
} else if (seg[0] === 1) {
if (!initialServerDataBuffer)
throw new Error('Unexpected server data: missing bootstrap script.')
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[1]))
} else {
initialServerDataBuffer.push(seg[1])
}
} else if (seg[0] === 2) {
initialFormStateData = seg[1]
}
return 0
}
function nextServerDataRegisterWriter(ctr: ReadableStreamDefaultController) {
if (initialServerDataBuffer) {
initialServerDataBuffer.forEach((val) => {
ctr.enqueue(encoder.encode(val))
})
if (initialServerDataLoaded && !initialServerDataFlushed) {
ctr.close()
initialServerDataFlushed = true
initialServerDataBuffer = undefined
}
}
initialServerDataWriter = ctr
}
// When `DOMContentLoaded`, we can close all pending writers to finish hydration.
const DOMContentLoaded = function () {
if (initialServerDataWriter && !initialServerDataFlushed) {
initialServerDataWriter.close()
initialServerDataFlushed = true
initialServerDataBuffer = undefined
}
initialServerDataLoaded = true
}
// It's possible that the DOM is already loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false)
} else {
DOMContentLoaded()
}
const nextServerDataLoadingGlobal = (self.__next_f = self.__next_f || [])
nextServerDataLoadingGlobal.forEach(nextServerDataCallback)
nextServerDataLoadingGlobal.push = nextServerDataCallback
function createResponseCache() {
return new Map()
}
const rscCache = createResponseCache()
function useInitialServerResponse(cacheKey: string) {
const response = rscCache.get(cacheKey)
if (response) return response
const readable = new ReadableStream({
start(controller) {
nextServerDataRegisterWriter(controller)
},
})
const newResponse = createFromReadableStream(readable, { callServer })
rscCache.set(cacheKey, newResponse)
return newResponse
}
function ServerRoot({ cacheKey }: { cacheKey: string }) {
React.useEffect(() => {
rscCache.delete(cacheKey)
})
const response = useInitialServerResponse(cacheKey)
const root = use(response) as ReactElement
return root
}
function RSCComponent() {
const cacheKey = getCacheKey()
return <ServerRoot cacheKey={cacheKey} />
}
function hydrate() {
const reactEl = (
<React.StrictMode>
<HeadManagerContext.Provider
value={{
appDir: true,
}}
>
<RSCComponent />
</HeadManagerContext.Provider>
</React.StrictMode>
)
const isError = document.documentElement.id === '__next_error__'
if (isError) {
// cast necessary because of a typing bug
const reactRoot = ReactDOMClient.createRoot(
appElement as unknown as DocumentFragment
)
reactRoot.render(reactEl)
} else {
React.startTransition(() => {
;(ReactDOMClient as any).hydrateRoot(appElement, reactEl, {
experimental_formState: initialFormStateData,
})
})
}
linkGc()
}
window.next = {
version: 'turbo',
appDir: true,
}
hydrate()
// this file is just here to make typescript happy about the wrapped/virtual assets (import ".")
declare var Anything: any
export = Anything
export const __turbopack_module_id__: string | number
export const chunks: string[]
import type { ClientReferenceManifest } from 'next/dist/build/webpack/plugins/flight-manifest-plugin'
export function createManifests() {
const proxyMethodsForModule = (
id: string
): ProxyHandler<ClientReferenceManifest['ssrModuleMapping']> => {
return {
get(_target, prop: string) {
return {
id,
chunks: JSON.parse(id)[1],
name: prop,
}
},
}
}
const availableModules = new Set()
const toPath = (chunk: ChunkData) =>
typeof chunk === 'string' ? chunk : chunk.path
/// determines if a chunk is needed based on the current available modules
const filterAvailable = (chunk: ChunkData) => {
if (typeof chunk === 'string') {
return true
} else {
let includedList = chunk.included || []
if (includedList.length === 0) {
return true
}
let needed = false
for (const item of includedList) {
if (!availableModules.has(item)) {
availableModules.add(item)
needed = true
}
}
return needed
}
}
const proxyMethodsNested = (
type: 'ssrModuleMapping' | 'clientModules' | 'entryCSSFiles'
): ProxyHandler<
| ClientReferenceManifest['ssrModuleMapping']
| ClientReferenceManifest['clientModules']
| ClientReferenceManifest['entryCSSFiles']
> => {
return {
get(_target, key: string) {
if (type === 'ssrModuleMapping') {
return new Proxy({}, proxyMethodsForModule(key as string))
}
if (type === 'clientModules') {
// The key is a `${file}#${name}`, but `file` can contain `#` itself.
// There are 2 possibilities:
// "file#" => id = "file", name = ""
// "file#foo" => id = "file", name = "foo"
const pos = key.lastIndexOf('#')
let id = key
let name = ''
if (pos !== -1) {
id = key.slice(0, pos)
name = key.slice(pos + 1)
} else {
throw new Error('keys need to be formatted as {file}#{name}')
}
return {
id,
name,
chunks: JSON.parse(id)[1],
}
}
if (type === 'entryCSSFiles') {
const cssChunks = JSON.parse(key)
// TODO(WEB-856) subscribe to changes
return cssChunks.filter(filterAvailable).map(toPath)
}
},
}
}
const proxyMethods = (): ProxyHandler<ClientReferenceManifest> => {
const clientModulesProxy = new Proxy(
{},
proxyMethodsNested('clientModules')
)
const ssrModuleMappingProxy = new Proxy(
{},
proxyMethodsNested('ssrModuleMapping')
)
const entryCSSFilesProxy = new Proxy(
{},
proxyMethodsNested('entryCSSFiles')
)
return {
get(_target: any, prop: string) {
if (prop === 'ssrModuleMapping') {
return ssrModuleMappingProxy
}
if (prop === 'clientModules') {
return clientModulesProxy
}
if (prop === 'entryCSSFiles') {
return entryCSSFilesProxy
}
},
}
}
const clientReferenceManifest: ClientReferenceManifest = new Proxy(
{} as any,
proxyMethods()
)
return { clientReferenceManifest }
}
export function installRequireAndChunkLoad() {
globalThis.__next_require__ = (data) => {
const [, , ssr_id] = JSON.parse(data)
return __turbopack_require__(ssr_id)
}
globalThis.__next_chunk_load__ = () => Promise.resolve()
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../../internal/nodejs-proxy-handler'
import AppRouteRouteModule from 'next/dist/server/future/route-modules/app-route/module'
import { RouteKind } from 'next/dist/server/future/route-kind'
import * as userland from 'ENTRY'
import { PAGE, PATHNAME } from 'BOOTSTRAP_CONFIG'
const routeModule = new AppRouteRouteModule({
userland,
definition: {
kind: RouteKind.APP_ROUTE,
page: PAGE,
pathname: PATHNAME,
// The following aren't used in production.
filename: '',
bundlePath: '',
},
resolvedPagePath: `app/${PAGE}`,
nextConfigOutput: undefined,
})
startHandler(routeModule)
declare module 'CLIENT_MODULE' {
export const __turbopack_module_id__: string
}
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
/// <reference path="./server-to-client-ssr.d.ts" />
import { createProxy } from 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
;('TURBOPACK { chunking-type: isolatedParallel }')
import { __turbopack_module_id__ as id } from 'CLIENT_MODULE'
import client_id, { chunks } from 'CLIENT_CHUNKS'
export default createProxy(JSON.stringify([client_id, chunks, id]))
declare module 'CLIENT_CHUNKS' {
const moduleId: string
export default moduleId
export const chunks: any[]
}
/// <reference path="./server-to-client.d.ts" />
import { createProxy } from 'next/dist/build/webpack/loaders/next-flight-loader/module-proxy'
import client_id, { chunks } from 'CLIENT_CHUNKS'
export default createProxy(JSON.stringify([client_id, chunks]))
import 'next/dist/server/web/globals'
import { adapter } from 'next/dist/server/web/adapter'
import { NAME, PAGE } from 'BOOTSTRAP_CONFIG'
var mod = require('ENTRY')
var handler = mod.middleware || mod.default
if (typeof handler !== 'function') {
throw new Error(
`The Edge Function "pages/${PAGE}" must export a \`default\` function`
)
}
// @ts-ignore
globalThis._ENTRIES = {
[`middleware_${NAME}`]: {
default: function (opts: any) {
return adapter({
...opts,
page: `/${PAGE}`,
handler,
})
},
},
}
// TODO(alexkirsz) export * would be preferrable here once supported.
export {
default,
// @ts-expect-error
getStaticProps,
// @ts-expect-error
__N_SSG,
// @ts-expect-error
__N_SSP,
} from '@vercel/turbopack-next/pages/_error'
import '../internal/shims-client'
import { createRoot } from 'react-dom/client'
import { initializeHMR, ReactDevOverlay } from '../dev/client'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { sendMessage } from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
const pageChunkPath = location.pathname.slice(1)
subscribeToUpdate(
{
path: pageChunkPath,
headers: {
accept: 'text/html',
},
},
sendMessage,
(update) => {
if (update.type === 'restart' || update.type === 'notFound') {
location.reload()
}
}
)
initializeHMR({
assetPrefix: '',
})
const el = document.getElementById('__next')!
const innerHtml = {
__html: el.innerHTML,
}
createRoot(el).render(
<ReactDevOverlay>
<div dangerouslySetInnerHTML={innerHtml}></div>
</ReactDevOverlay>
)
// this file is just here to make typescript happy about the wrapped/virtual assets (import ".")
declare var Anything: any
export = Anything
;((manifest) => {
// adapted from https://github.com/vercel/next.js/blob/canary/packages/next/src/build/webpack/plugins/build-manifest-plugin.ts#L54-L54
function processRoute(rewrite) {
// omit external rewrite destinations since these aren't
// handled client-side
if (!rewrite.destination.startsWith('/')) {
delete rewrite.destination
}
return rewrite
}
manifest.__rewrites.beforeFiles.map(processRoute)
manifest.__rewrites.afterFiles.map(processRoute)
manifest.__rewrites.fallback.map(processRoute)
self.__BUILD_MANIFEST = manifest
self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB()
})($$MANIFEST$$)
import '../internal/shims-client'
import { initialize, hydrate, router, emitter, version } from 'next/dist/client'
import type { Router } from 'next/dist/client/router'
import {
assign,
urlQueryToSearchParams,
} from 'next/dist/shared/lib/router/utils/querystring'
import { formatWithValidation } from 'next/dist/shared/lib/router/utils/format-url'
import { initializeHMR } from '../dev/client'
import { subscribeToUpdate } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
import { sendMessage } from '@vercel/turbopack-ecmascript-runtime/dev/client/websocket'
;(self as any).__next_set_public_path__ = () => {}
async function loadPageChunk(assetPrefix: string, chunkData: ChunkData) {
if (typeof chunkData === 'string') {
const fullPath = assetPrefix + chunkData
await __turbopack_load__(fullPath)
} else {
let fullChunkData = {
...chunkData,
path: assetPrefix + chunkData.path,
}
await __turbopack_load__(fullChunkData)
}
}
;(async () => {
console.debug('Initializing Next.js')
window.next = {
version: version || '',
get router() {
return router
},
emitter,
}
const { assetPrefix } = await initialize({
devClient: {
// Expected when `process.env.NODE_ENV === 'development'`
onUnrecoverableError() {},
},
})
initializeHMR({
assetPrefix,
})
// for the page loader
window.__turbopack_load_page_chunks__ = (page, chunksData) => {
const chunkPromises = chunksData.map(loadPageChunk.bind(null, assetPrefix))
Promise.all(chunkPromises).catch((err) =>
console.error('failed to load chunks for page ' + page, err)
)
}
const pagePath = window.__NEXT_DATA__.page
window.__NEXT_P.push([
'/_app',
() => require('@vercel/turbopack-next/pages/_app'),
])
window.__NEXT_P.push([pagePath, () => require('PAGE')])
console.debug('Hydrating the page')
await hydrate({})
// This needs to happen after hydration because the router is initialized
// during hydration. To make this dependency clearer, we pass `router` as an
// explicit argument instead of relying on the `router` import binding.
subscribeToCurrentPageData({ assetPrefix, router })
subscribeToPageManifest({ assetPrefix })
console.debug('The page has been hydrated')
})().catch((err) => console.error(err))
function subscribeToPageManifest({ assetPrefix }: { assetPrefix: string }) {
// adapted from https://github.com/vercel/next.js/blob/836ac9cc7f290e95b564a61341fa95a5f4f0327e/packages/next/src/client/next-dev.ts#L57
subscribeToUpdate(
{
path: '_next/static/development/_devPagesManifest.json',
},
sendMessage,
(update) => {
if (['restart', 'notFound', 'partial'].includes(update.type)) {
return
}
fetch(`${assetPrefix}/_next/static/development/_devPagesManifest.json`)
.then((res) => res.json())
.then((manifest) => {
window.__DEV_PAGES_MANIFEST = manifest
})
.catch((err) => {
console.log(`Failed to fetch devPagesManifest`, err)
})
}
)
}
/**
* Subscribes to the current page's data updates from the HMR server.
*
* Updates on route change.
*/
function subscribeToCurrentPageData({
router,
assetPrefix,
}: {
router: Router
assetPrefix: string
}) {
let dataPath = getCurrentPageDataHref()
let unsubscribe = subscribeToPageData({
router,
dataPath,
assetPrefix,
})
router.events.on('routeChangeComplete', () => {
const nextDataPath = getCurrentPageDataHref()
if (dataPath === nextDataPath) {
return
}
dataPath = nextDataPath
unsubscribe()
unsubscribe = subscribeToPageData({
router,
dataPath,
assetPrefix,
})
})
}
function getCurrentPageDataHref(): string {
return router.pageLoader.getDataHref({
asPath: router.asPath,
href: formatWithValidation({
// No need to pass `router.query` when `skipInterpolation` is true.
pathname: router.pathname,
}),
skipInterpolation: true,
})
}
/**
* TODO(alexkirsz): Handle assetPrefix/basePath.
*/
function subscribeToPageData({
router,
dataPath,
assetPrefix,
}: {
router: Router
dataPath: string
assetPrefix: string
}): () => void {
return subscribeToUpdate(
{
// We need to remove the leading / from the data path as Turbopack
// resources are not prefixed with a /.
path: dataPath.slice(1),
headers: {
// This header is used by the Next.js server to determine whether this
// is a data request.
'x-nextjs-data': '1',
},
},
sendMessage,
(update) => {
if (update.type !== 'restart') {
return
}
// This triggers a reload of the page data.
// Adapted from next.js/packages/next/client/next-dev.js.
router
.replace(
router.pathname +
'?' +
String(
assign(
urlQueryToSearchParams(router.query),
new URLSearchParams(location.search)
)
),
router.asPath,
{ scroll: false }
)
.catch(() => {
// trigger hard reload when failing to refresh data
// to show error overlay properly
location.reload()
})
}
)
}
import type { Ipc, StructuredError } from '@vercel/turbopack-node/ipc/index'
import type { IncomingMessage } from 'node:http'
import { Buffer } from 'node:buffer'
import { createServer, makeRequest, type ServerInfo } from '../internal/server'
import { toPairs } from '../internal/headers'
import { makeResolver } from 'next/dist/server/lib/route-resolver'
import loadConfig from 'next/dist/server/config'
import { PHASE_DEVELOPMENT_SERVER } from 'next/dist/shared/lib/constants'
import 'next/dist/server/node-polyfill-fetch.js'
import middlewareChunkGroup from 'MIDDLEWARE_CHUNK_GROUP'
import middlewareConfig from 'MIDDLEWARE_CONFIG'
type Resolver = Awaited<
ReturnType<typeof import('next/dist/server/lib/route-resolver').makeResolver>
>
type RouterRequest = {
method: string
pathname: string
rawHeaders: [string, string][]
rawQuery: string
body: number[][]
}
type IpcOutgoingMessage = {
type: 'value'
data: string | Buffer
}
type MessageData =
| { type: 'middleware-headers'; data: MiddlewareHeadersResponse }
| { type: 'middleware-body'; data: Uint8Array }
| {
type: 'rewrite'
data: RewriteResponse
}
| {
type: 'error'
error: StructuredError
}
| { type: 'none' }
type RewriteResponse = {
url: string
headers: [string, string][]
}
type MiddlewareHeadersResponse = {
statusCode: number
headers: [string, string][]
}
let resolveRouteMemo: Promise<Resolver>
async function getResolveRoute(
dir: string,
serverInfo: ServerInfo
): Promise<Resolver> {
const nextConfig = await loadConfig(PHASE_DEVELOPMENT_SERVER, process.cwd())
const middlewareCfg = {
files: middlewareChunkGroup.filter((f) => /\.[mc]?js$/.test(f)),
matcher: middlewareConfig.matcher,
}
return await makeResolver(dir, nextConfig, middlewareCfg, serverInfo)
}
export default async function route(
ipc: Ipc<RouterRequest, IpcOutgoingMessage>,
routerRequest: RouterRequest,
dir: string,
serverInfo: ServerInfo
) {
const [resolveRoute, server] = await Promise.all([
(resolveRouteMemo ??= getResolveRoute(dir, serverInfo)),
createServer(),
])
try {
const {
clientRequest,
clientResponsePromise,
serverRequest,
serverResponse,
} = await makeRequest(
server,
routerRequest.method,
routerRequest.pathname,
routerRequest.rawQuery,
routerRequest.rawHeaders,
serverInfo
)
const body = Buffer.concat(
routerRequest.body.map((arr) => Buffer.from(arr))
)
// Send the clientRequest, so the server parses everything. We can then pass
// the serverRequest to Next.js to handle.
clientRequest.end(body)
// The route promise must not block us from starting the middleware
// response handling, so we cannot await it yet. By making the call, we
// allow Next.js to start writing to the response whenever it's ready.
const routePromise = resolveRoute(serverRequest, serverResponse)
// Now that the Next.js has started processing the route, the middleware
// response promise will resolve once they write data and then we can begin
// streaming.
// We again cannot await directly on the promise, because an error may
// occur in the routePromise while we're waiting.
const middlewarePromise = clientResponsePromise.then((c) =>
handleMiddlewareResponse(ipc, c)
)
// Now that both promises are in progress, we await both so that a
// rejection in either will end the routing.
const [routeResult] = await Promise.all([routePromise, middlewarePromise])
server.close()
if (routeResult) {
switch (routeResult.type) {
case 'none':
case 'error':
return routeResult
case 'rewrite':
return {
type: 'rewrite',
data: {
url: routeResult.url,
headers: Object.entries(routeResult.headers)
.filter(([, val]) => val != null)
.map(([name, value]) => [name, value!.toString()]),
},
}
default:
// @ts-expect-error data.type is never
throw new Error(`unknown route result type: ${data.type}`)
}
}
} catch (e) {
// Server doesn't need to be closed, because the sendError will terminate
// the process.
ipc.sendError(e as Error)
}
}
async function handleMiddlewareResponse(
ipc: Ipc<RouterRequest, IpcOutgoingMessage>,
clientResponse: IncomingMessage
): Promise<void> {
// If this header is specified, we know that the response was not handled by
// middleware. The headers and body of the response are useless.
if (clientResponse.headers['x-nextjs-route-result']) {
return
}
const responseHeaders: MiddlewareHeadersResponse = {
statusCode: clientResponse.statusCode!,
headers: toPairs(clientResponse.rawHeaders),
}
await ipc.send({
type: 'value',
data: JSON.stringify({
type: 'middleware-headers',
data: responseHeaders,
}),
})
for await (const chunk of clientResponse) {
await ipc.send({
type: 'value',
data: JSON.stringify({
type: 'middleware-body',
data: (chunk as Buffer).toJSON().data,
}),
})
}
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { parse as parseQuery } from 'node:querystring'
import { parse as parseUrl } from 'node:url'
import { apiResolver } from 'next/dist/server/api-utils/node'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { attachRequestMeta } from '../internal/next-request-helpers'
import * as allExports from 'INNER'
startHandler(({ request, response, query, params, path }) => {
const parsedQuery = parseQuery(query)
const mergedQuery = { ...parsedQuery, ...params }
// This enables `req.cookies` in API routes.
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
return apiResolver(
req.originalRequest,
res.originalResponse,
mergedQuery,
allExports,
{
previewModeId: '',
previewModeEncryptionKey: '',
previewModeSigningKey: '',
},
false,
true,
path
)
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/page-server-handler'
// eslint-disable-next-line
import Document from 'next/document'
import App from 'next/app'
startHandler({
isDataReq: true,
App,
Document,
mod: () => {
return import('INNER').then((namespace) => ({
Component: () => null,
namespace,
}))
},
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/api-server-handler'
import 'next/dist/server/node-polyfill-fetch.js'
import { join } from 'node:path'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { attachRequestMeta } from '../internal/next-request-helpers'
import { runEdgeFunction, updateResponse } from '../internal/edge'
import chunkGroup from 'INNER_EDGE_CHUNK_GROUP'
startHandler(async ({ request, response, query, params, path }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const edgeInfo = {
name: 'edge',
paths: chunkGroup.map((chunk: string) =>
join(process.cwd(), '.next/server/pages', chunk)
),
wasm: [],
env: Object.keys(process.env),
assets: [],
}
const result = await runEdgeFunction({
edgeInfo,
outputDir: 'pages',
req,
query,
params,
path,
onWarning(warning) {
console.warn(warning)
},
})
await updateResponse(res, result)
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from '../internal/page-server-handler'
import Document from '@vercel/turbopack-next/pages/_document'
import App from '@vercel/turbopack-next/pages/_app'
import chunkGroup from 'INNER_CLIENT_CHUNK_GROUP'
startHandler({
isDataReq: false,
App,
Document,
mod: () => {
return import('INNER').then((namespace) => ({
Component: namespace.default as any,
namespace,
}))
},
chunkGroup,
})
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startOperationStreamHandler from './operation-stream'
import type { ClientRequest, IncomingMessage, Server } from 'node:http'
import type { ServerResponse } from 'node:http'
import { Buffer } from 'node:buffer'
import type { RenderData } from 'types/turbopack'
import { createServer, makeRequest } from '../internal/server'
import { toPairs } from '../internal/headers'
type Handler = (data: {
request: IncomingMessage
response: ServerResponse<IncomingMessage>
query: string
params: Record<string, string | string[]>
path: string
}) => Promise<void>
type Operation = {
clientRequest: ClientRequest
clientResponsePromise: Promise<IncomingMessage>
apiOperation: Promise<void>
server: Server
}
type ResponseHeaders = {
status: number
headers: [string, string][]
}
export default function startHandler(handler: Handler): void {
startOperationStreamHandler(
async (renderData: RenderData, respond, reportError) => {
const operationPromise = (async function createOperation() {
const server = await createServer()
const {
clientRequest,
clientResponsePromise,
serverRequest,
serverResponse,
} = await makeRequest(
server,
renderData.method,
renderData.path,
renderData.rawQuery,
renderData.rawHeaders,
renderData.data?.serverInfo
)
return {
clientRequest,
server,
clientResponsePromise,
apiOperation: handler({
request: serverRequest,
response: serverResponse,
query: renderData.rawQuery,
params: renderData.params,
path: renderData.path,
}),
}
})()
function handleClientResponse(
server: Server,
clientResponse: IncomingMessage
) {
const responseHeaders: ResponseHeaders = {
status: clientResponse.statusCode!,
headers: toPairs(clientResponse.rawHeaders),
}
const channel = respond(responseHeaders)
clientResponse.on('data', (chunk) => {
channel.chunk(chunk)
})
clientResponse.once('end', () => {
channel.end()
server.close()
})
clientResponse.once('error', (err) => {
reportError(err)
})
}
/**
* Ends an operation by writing the response body to the client and waiting for the Next.js API resolver to finish.
*/
async function endOperation(operation: Operation, body: Buffer) {
operation.clientRequest.end(body)
try {
await operation.apiOperation
} catch (error) {
await reportError(error)
return
}
}
return {
streamRequest: false,
onBody: async (body) => {
const operation = await operationPromise
await Promise.all([
endOperation(operation, body),
operation.clientResponsePromise.then((clientResponse) =>
handleClientResponse(operation.server, clientResponse)
),
])
},
}
}
)
}
import { join } from 'path'
import type {
BaseNextRequest,
BaseNextResponse,
} from 'next/dist/server/base-http'
import type {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { parse, ParsedUrlQuery } from 'querystring'
import type { Params } from 'next/dist/shared/lib/router/utils/route-matcher'
import type { FetchEventResult } from 'next/dist/server/web/types'
import { getCloneableBody } from 'next/dist/server/body-streams'
// This is an adapted version of a similar function in next-dev-server.
// TODO exposes this method from next.js instead
export async function runEdgeFunction({
edgeInfo,
outputDir,
req,
query,
params,
path,
onWarning,
}: {
edgeInfo: {
name: string
paths: string[]
wasm: unknown[]
env: unknown[]
assets: unknown[]
}
outputDir: string
req: BaseNextRequest | NodeNextRequest
query: string
path: string
params: Params | undefined
onWarning?: (warning: Error) => void
}): Promise<FetchEventResult> {
// For edge to "fetch" we must always provide an absolute URL
const initialUrl = new URL(path, 'http://n')
const parsedQuery = parse(query)
const queryString = urlQueryToSearchParams({
...Object.fromEntries(initialUrl.searchParams),
...parsedQuery,
}).toString()
initialUrl.search = queryString
const url = initialUrl.toString()
if (!url.startsWith('http')) {
throw new Error(
'To use middleware you must provide a `hostname` and `port` to the Next.js Server'
)
}
const { run } = require('next/dist/server/web/sandbox')
const result = (await run({
distDir: join(process.cwd(), '.next/server', outputDir),
name: edgeInfo.name,
paths: edgeInfo.paths,
env: edgeInfo.env,
edgeFunctionEntry: edgeInfo,
request: {
headers: req.headers,
method: req.method,
nextConfig: {
basePath: '/',
i18n: undefined,
trailingSlash: true,
},
url,
page: {
name: path,
...(params && { params: params }),
},
body: getCloneableBody(req.body),
},
useCache: false,
onWarning,
})) as FetchEventResult
return result
}
export async function updateResponse(
response: BaseNextResponse<any> | NodeNextResponse,
result: FetchEventResult
) {
response.statusCode = result.response.status
response.statusMessage = result.response.statusText
result.response.headers.forEach((value: string, key) => {
// the append handling is special cased for `set-cookie`
if (key.toLowerCase() === 'set-cookie') {
response.setHeader(key, value)
} else {
response.appendHeader(key, value)
}
})
if (result.response.body) {
// TODO(gal): not sure that we always need to stream
const nodeResStream = (response as NodeNextResponse).originalResponse
const {
consumeUint8ArrayReadableStream,
} = require('next/dist/compiled/edge-runtime')
try {
for await (const chunk of consumeUint8ArrayReadableStream(
result.response.body
)) {
nodeResStream.write(chunk)
}
} finally {
nodeResStream.end()
}
} else {
;(response as NodeNextResponse).originalResponse.end()
}
}
function stringifyUrlQueryParam(param: unknown): string {
if (
typeof param === 'string' ||
(typeof param === 'number' && !isNaN(param)) ||
typeof param === 'boolean'
) {
return String(param)
} else {
return ''
}
}
function urlQueryToSearchParams(urlQuery: ParsedUrlQuery): URLSearchParams {
const result = new URLSearchParams()
Object.entries(urlQuery).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item) => result.append(key, stringifyUrlQueryParam(item)))
} else {
result.set(key, stringifyUrlQueryParam(value))
}
})
return result
}
import { ServerInfo } from './server'
export type Headers = Record<string, string | string[]>
/**
* Converts an array of raw header entries to a map of header names to values.
*/
export function headersFromEntries(entries: Array<[string, string]>): Headers {
const headers: Record<string, string | string[]> = Object.create(null)
for (const [key, value] of entries) {
if (key in headers) {
const prevValue = headers[key]
if (typeof prevValue === 'string') {
headers[key] = [prevValue, value]
} else {
prevValue.push(value)
}
} else {
headers[key] = value
}
}
return headers
}
/**
* Transforms an array of elements into an array of pairs of elements.
*
* ## Example
*
* ```ts
* toPairs(["a", "b", "c", "d"]) // => [["a", "b"], ["c", "d"]]
* ```
*/
export function toPairs<T>(arr: T[]): Array<[T, T]> {
if (arr.length % 2 !== 0) {
throw new Error('toPairs: expected an even number of elements')
}
const pairs: Array<[T, T]> = []
for (let i = 0; i < arr.length; i += 2) {
pairs.push([arr[i], arr[i + 1]])
}
return pairs
}
/**
* These headers are provided by default to match the http-proxy behavior
* https://github.com/http-party/node-http-proxy/blob/9b96cd72/lib/http-proxy/passes/web-incoming.js#L58-L86
*/
export function initProxiedHeaders(
headers: Headers,
proxiedFor: ServerInfo | null | undefined
): Headers {
const hostname = proxiedFor?.hostname || 'localhost'
const port = String(proxiedFor?.port || 3000)
headers['x-forwarded-for'] = proxiedFor?.ip || '::1'
headers['x-forwarded-host'] = `${hostname}:${port}`
headers['x-forwarded-port'] = port
headers['x-forwarded-proto'] = proxiedFor?.protocol || 'http'
return headers
}
import type { IncomingMessage, ServerResponse } from 'node:http'
/**
* Shim for Node.js's http.ServerResponse
*
* @type {ServerResponse}
*/
class ServerResponseShim {
headersSent = false
#headers: Map<string, number | string | ReadonlyArray<string>> = new Map()
#statusCode: number = 200
req: IncomingMessage
constructor(req: IncomingMessage) {
this.req = req
}
setHeader(name: string, value: number | string | ReadonlyArray<string>) {
this.#headers.set(name.toLowerCase(), value)
return this
}
getHeader(name: string) {
return this.#headers.get(name.toLowerCase())
}
getHeaderNames() {
return Array.from(this.#headers.keys())
}
getHeaders() {
return Object.fromEntries(this.#headers)
}
hasHeader(name: string) {
return this.#headers.has(name.toLowerCase())
}
removeHeader(name: string) {
this.#headers.delete(name.toLowerCase())
}
get statusCode() {
return this.#statusCode
}
set statusCode(code) {
this.#statusCode = code
}
get statusMessage() {
throw new Error('statusMessage is not implemented')
}
set statusMessage(message) {
throw new Error('set statusMessage is not implemented')
}
get socket() {
throw new Error('socket is not implemented')
}
get sendDate() {
throw new Error('sendDate is not implemented')
}
flushHeaders() {
throw new Error('flushHeaders is not implemented')
}
end() {
throw new Error('end is not implemented')
}
cork() {
throw new Error('cork is not implemented')
}
uncork() {
throw new Error('uncork is not implemented')
}
addTrailers() {
throw new Error('addTrailers is not implemented')
}
setTimeout(_msecs: any, _callback: any) {
throw new Error('setTimeout is not implemented')
}
get writableEnded() {
throw new Error('writableEnded is not implemented')
}
get writableFinished() {
throw new Error('writableFinished is not implemented')
}
write(_chunk: any, _encoding: any, _callback: any) {
throw new Error('write is not implemented')
}
writeContinue() {
throw new Error('writeContinue is not implemented')
}
writeHead(_statusCode: any, _statusMessage: any, _headers: any) {
throw new Error('writeHead is not implemented')
}
writeProcessing() {
throw new Error('writeProcessing is not implemented')
}
}
function getStatusCodeForPath(pathname: string): number {
if (pathname === '/404' || pathname === '/_error') {
return 404
}
return 200
}
/**
* Creates a `ServerResponse` object for a given request and pathname.
*/
export function createServerResponse(
req: IncomingMessage,
pathname: string
): ServerResponse {
const statusCode = getStatusCodeForPath(pathname)
const res = new ServerResponseShim(req) as any
// For pages, setting the status code on the response object is necessary for
// `Error.getInitialProps` to detect the status code.
res.statusCode = statusCode
return res as ServerResponse
}
import { TLSSocket } from 'tls'
import {
addRequestMeta,
NextUrlWithParsedQuery,
} from 'next/dist/server/request-meta'
import { NodeNextRequest } from 'next/dist/server/base-http/node'
import { BaseNextRequest } from 'next/dist/server/base-http'
import { getCloneableBody } from 'next/dist/server/body-streams'
import { formatHostname } from 'next/dist/server/lib/format-hostname'
export function attachRequestMeta(
req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery,
hostname: string
) {
const protocol = (
(req as NodeNextRequest).originalRequest?.socket as TLSSocket
)?.encrypted
? 'https'
: 'http'
const initUrl = `${protocol}://${formatHostname(hostname)}${req.url}`
addRequestMeta(req, '__NEXT_INIT_URL', initUrl)
addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query })
addRequestMeta(req, '_protocol', protocol)
addRequestMeta(req, '__NEXT_CLONABLE_BODY', getCloneableBody(req.body))
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import startHandler from './api-server-handler'
import '../polyfill/app-polyfills'
import { parse as parseUrl } from 'node:url'
import {
NodeNextRequest,
NodeNextResponse,
} from 'next/dist/server/base-http/node'
import { sendResponse } from 'next/dist/server/send-response'
import {
NextRequestAdapter,
signalFromNodeResponse,
} from 'next/dist/server/web/spec-extension/adapters/next-request'
import { attachRequestMeta } from './next-request-helpers'
import type {
AppRouteRouteHandlerContext,
AppRouteRouteModule,
} from 'next/dist/server/future/route-modules/app-route/module'
export default (routeModule: AppRouteRouteModule) => {
startHandler(async ({ request, response, params }) => {
const req = new NodeNextRequest(request)
const res = new NodeNextResponse(response)
const parsedUrl = parseUrl(req.url!, true)
attachRequestMeta(req, parsedUrl, request.headers.host!)
const context: AppRouteRouteHandlerContext = {
params,
prerenderManifest: {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: 'development-id',
} as any,
},
staticGenerationContext: {
supportsDynamicHTML: true,
},
}
const routeResponse = await routeModule.handle(
NextRequestAdapter.fromNodeNextRequest(
req,
signalFromNodeResponse(response)
),
context
)
await sendResponse(req, res, routeResponse)
})
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import { IPC } from '@vercel/turbopack-node/ipc/index'
import { Buffer } from 'node:buffer'
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
type Operation =
| {
streamRequest: true
onChunk?: (chunk: Buffer) => Promise<void>
onEnd?: () => Promise<void>
}
| {
streamRequest?: false
onBody?: (body: Buffer) => Promise<void>
}
type IpcIncomingMessage<T> =
| {
type: 'headers'
data: T
}
| {
type: 'bodyChunk'
data: number[]
}
| {
type: 'bodyText'
data: number[]
}
| { type: 'bodyEnd' }
type IpcOutgoingMessage<R> =
| {
type: 'headers'
data: R
}
| {
type: 'bodyChunk'
data: number[]
}
| {
type: 'bodyEnd'
}
interface Response {
chunk: (data: Buffer) => Promise<void>
end: () => Promise<void>
}
export default function startHandler<T, R>(
createOperation: (
data: T,
respond: (data: R) => Response,
reportError: (error: unknown) => Promise<never>
) => Promise<Operation | void>
) {
const ipc = IPC as Ipc<IpcIncomingMessage<T>, IpcOutgoingMessage<R>>
;(async () => {
while (true) {
let operation: Operation | void
{
const msg = await ipc.recv()
switch (msg.type) {
case 'headers': {
operation = await createOperation(
msg.data,
(data) => {
ipc.send({
type: 'headers',
data,
})
return {
chunk: (buf: Buffer) => {
return ipc.send({
type: 'bodyChunk',
data: buf.toJSON().data,
})
},
end: () => {
return ipc.send({ type: 'bodyEnd' })
},
}
},
(error) => {
return ipc.sendError(
error instanceof Error
? error
: new Error(`an unknown error occurred: ${error}`)
)
}
)
break
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
}
if (operation) {
if (operation.streamRequest) {
loop: while (true) {
const msg = await ipc.recv()
switch (msg.type) {
case 'bodyChunk':
case 'bodyText': {
await operation.onChunk?.(Buffer.from(msg.data))
break
}
case 'bodyEnd': {
await operation.onEnd?.()
break loop
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
}
} else {
let body = Buffer.alloc(0)
loop: while (true) {
const msg = await ipc.recv()
switch (msg.type) {
case 'bodyChunk':
case 'bodyText': {
body = Buffer.concat([body, Buffer.from(msg.data)])
break
}
case 'bodyEnd': {
await operation.onBody?.(body)
break loop
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
}
}
}
}
})().catch((err) => {
ipc.sendError(err)
})
}
// IPC need to be the first import to allow it to catch errors happening during
// the other imports
import { IPC } from '@vercel/turbopack-node/ipc/index'
import 'next/dist/server/node-polyfill-fetch.js'
import 'next/dist/server/require-hook'
import './shims'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { RenderOpts } from 'next/dist/server/render'
import { getRedirectStatus } from 'next/dist/lib/redirect-status'
import { PERMANENT_REDIRECT_STATUS } from 'next/dist/shared/lib/constants'
import { buildStaticPaths } from 'next/dist/build/utils'
import type { BuildManifest } from 'next/dist/server/get-page-files'
import type { ReactLoadableManifest } from 'next/dist/server/load-components'
import { headersFromEntries, initProxiedHeaders } from './headers'
import { createServerResponse } from './http'
import type { Ipc } from '@vercel/turbopack-node/ipc/index'
import type { RenderData } from 'types/turbopack'
import type { ChunkGroup } from 'types/next'
import type { NextComponentType } from 'next/types'
import { parse } from 'node:querystring'
const {
renderToHTML,
} = require('next/dist/compiled/next-server/pages.runtime.dev')
const ipc = IPC as Ipc<IpcIncomingMessage, IpcOutgoingMessage>
type IpcIncomingMessage = {
type: 'headers'
data: RenderData
}
type IpcOutgoingMessage =
| {
type: 'response'
statusCode: number
headers: Array<[string, string]>
body: string
}
| { type: 'rewrite'; path: string }
const MIME_APPLICATION_JAVASCRIPT = 'application/javascript'
const MIME_TEXT_HTML_UTF8 = 'text/html; charset=utf-8'
type ModuleImport = Promise<{
Component: NextComponentType
namespace: Record<string, any>
}>
export default function startHandler({
isDataReq,
App,
Document,
mod,
chunkGroup,
}: {
isDataReq: boolean
App?: any
Document?: any
mod: () => ModuleImport
chunkGroup?: ChunkGroup
}) {
;(async () => {
while (true) {
const msg = await ipc.recv()
let renderData: RenderData
switch (msg.type) {
case 'headers': {
renderData = msg.data
break
}
default: {
console.error('unexpected message type', msg.type)
process.exit(1)
}
}
const { Component, namespace } = await mod()
const res = await runOperation(renderData, Component, namespace)
ipc.send(res)
}
})().catch((err) => {
ipc.sendError(err)
})
async function runOperation(
renderData: RenderData,
Component: NextComponentType,
namespace: Record<string, any>
): Promise<IpcOutgoingMessage> {
if ('getStaticPaths' in namespace) {
const {
paths: prerenderRoutes,
fallback: prerenderFallback,
encodedPaths: _encodedPrerenderRoutes,
} = await buildStaticPaths({
page: renderData.path,
getStaticPaths: namespace.getStaticPaths,
// TODO(alexkirsz) Provide the correct next.config.js path.
configFileName: 'next.config.js',
})
// We provide a dummy base URL to the URL constructor so that it doesn't
// throw when we pass a relative URL.
let resolvedPath = new URL(renderData.url, 'next://').pathname
if (isDataReq) {
// we still want to match data requests so we remove the prefix and extension
// to get back the path the page would have
resolvedPath = resolvedPath.replace(
/^\/_next\/data\/development(.+).json$/,
'$1'
)
}
if (
prerenderFallback === false &&
// TODO(alexkirsz) Strip basePath.
!prerenderRoutes.includes(resolvedPath)
) {
return createNotFoundResponse(isDataReq)
}
}
// TODO(alexkirsz) This is missing *a lot* of data, but it's enough to get a
// basic render working.
const buildManifest: BuildManifest = {
pages: {
// TODO(alexkirsz) We should separate _app and page chunks. Right now, we
// computing the chunk items of `next-hydrate.js`, so they contain both
// _app and page chunks.
'/_app': [],
[renderData.path]: chunkGroup || [],
},
devFiles: [],
ampDevFiles: [],
polyfillFiles: [],
lowPriorityFiles: ['static/development/_buildManifest.js'],
rootMainFiles: [],
ampFirstPages: [],
}
// When rendering a data request, the default component export is eliminated
// by the Next.js strip export transform. The following checks for this case
// and replaces the default export with a dummy component instead.
const comp =
typeof Component === 'undefined' ||
(typeof Component === 'object' && Object.keys(Component).length === 0)
? () => null
: Component
const renderOpts: RenderOpts = {
strictNextHead: false,
/* LoadComponentsReturnType */
Component: comp,
App,
Document,
pageConfig: {},
buildManifest,
reactLoadableManifest: createReactLoadableManifestProxy(),
ComponentMod: {
default: comp,
...namespace,
},
page: renderData.path,
buildId: 'development',
/* RenderOptsPartial */
isDataReq,
runtimeConfig: {},
assetPrefix: '',
canonicalBase: '',
previewProps: {
previewModeId: '',
previewModeEncryptionKey: '',
previewModeSigningKey: '',
},
params: renderData.params,
basePath: '',
// TODO(WEB-583) this isn't correct, instead it should set `dev: true`
nextExport: true,
nextConfigOutput: renderData.data?.nextConfigOutput,
resolvedUrl: renderData.url,
optimizeFonts: false,
optimizeCss: false,
nextScriptWorkers: false,
supportsDynamicHTML: true,
images: {
deviceSizes: [],
imageSizes: [],
loader: 'default',
path: '',
loaderFile: '',
domains: [],
disableStaticImages: false,
minimumCacheTTL: 0,
formats: [],
dangerouslyAllowSVG: false,
contentSecurityPolicy: '',
contentDispositionType: 'inline',
remotePatterns: [],
unoptimized: true,
},
}
if ('getStaticPaths' in namespace) {
renderOpts.getStaticPaths = namespace.getStaticPaths
}
if ('getStaticProps' in namespace) {
renderOpts.getStaticProps = namespace.getStaticProps
}
if ('getServerSideProps' in namespace) {
renderOpts.getServerSideProps = namespace.getServerSideProps
}
const req: IncomingMessage = {
url: renderData.url,
method: 'GET',
headers: initProxiedHeaders(
headersFromEntries(renderData.rawHeaders),
renderData.data?.serverInfo
),
} as any
const res: ServerResponse = createServerResponse(req, renderData.path)
const parsedQuery = parse(renderData.rawQuery)
const query = { ...parsedQuery, ...renderData.params }
const renderResult = await renderToHTML(
/* req: IncomingMessage */
req,
/* res: ServerResponse */
res,
/* pathname: string */
renderData.path,
/* query: ParsedUrlQuery */
query,
/* renderOpts: RenderOpts */
renderOpts
)
const {
metadata: {
// Set when `getStaticProps` returns `notFound: true`.
isNotFound,
// Set when `getStaticProps` returns `redirect: { destination, permanent, statusCode }`.
isRedirect,
},
} = renderResult
if (isNotFound) {
return createNotFoundResponse(isDataReq)
}
if (isRedirect && !isDataReq) {
const {
metadata: {
pageData: { pageProps },
},
} = renderResult
const redirect = {
destination: pageProps.__N_REDIRECT,
statusCode: pageProps.__N_REDIRECT_STATUS,
basePath: pageProps.__N_REDIRECT_BASE_PATH,
}
const statusCode = getRedirectStatus(redirect)
// TODO(alexkirsz) Handle basePath.
// if (
// basePath &&
// redirect.basePath !== false &&
// redirect.destination.startsWith("/")
// ) {
// redirect.destination = `${basePath}${redirect.destination}`;
// }
const headers: Array<[string, string]> = [
['Location', redirect.destination],
]
if (statusCode === PERMANENT_REDIRECT_STATUS) {
headers.push(['Refresh', `0;url=${redirect.destination}`])
}
return {
type: 'response',
statusCode,
headers,
body: redirect.destination,
}
}
if (isDataReq) {
// TODO(from next.js): change this to a different passing mechanism
const {
metadata: { pageData },
} = renderResult
return {
type: 'response',
statusCode: res.statusCode,
headers: [['Content-Type', MIME_APPLICATION_JAVASCRIPT]],
// Page data is only returned if the page had getXxyProps.
body: JSON.stringify(pageData === undefined ? {} : pageData),
}
}
if (!renderResult || renderResult.isNull) {
throw new Error('no render result returned')
}
const body = renderResult.toUnchunkedString()
// TODO: handle revalidate
// const sprRevalidate = renderResult.metadata.revalidate;
return {
type: 'response',
statusCode: res.statusCode,
headers: [
['Content-Type', renderResult.contentType ?? MIME_TEXT_HTML_UTF8],
],
body,
}
}
}
function createNotFoundResponse(isDataReq: boolean): IpcOutgoingMessage {
if (isDataReq) {
return {
type: 'response',
// Returning a 404 status code is required for the client-side router
// to redirect to the error page.
statusCode: 404,
body: '{"notFound":true}',
headers: [['Content-Type', MIME_APPLICATION_JAVASCRIPT]],
}
}
return {
type: 'rewrite',
// /_next/404 is a Turbopack-internal route that will always redirect to
// the 404 page.
path: '/_next/404',
}
}
type ManifestItem = {
id: string
chunks: ChunkData[]
}
/**
* During compilation, Next.js builds a manifest of dynamic imports with the
* `ReactLoadablePlugin` for webpack.
*
* At the same time, the next/dynamic transform converts each `dynamic()` call
* so it contains a key to the corresponding entry within that manifest.
*
* During server-side rendering, each `dynamic()` call will be recorded and its
* corresponding entry in the manifest will be looked up.
* * The entry's chunks will be asynchronously loaded on the client using a
* <script defer> tag.
* * The entry's module id will be appended to a list of dynamic module ids.
*
* On the client-side, during hydration, the dynamic module ids are used to
* initialize the corresponding <Loadable> components.
*
* In development, Turbopack works differently: instead of building a static
* manifest, each `dynamic()` call will embed its own manifest entry within a
* serialized string key. Hence the need for a proxy that can dynamically
* deserialize the manifest entries from that string key.
*/
function createReactLoadableManifestProxy(): ReactLoadableManifest {
return new Proxy(
{},
{
get: (_target, prop: string, _receiver) => {
const { id, chunks } = JSON.parse(prop) as ManifestItem
return {
id,
files: chunks.map((chunk) => {
let path = typeof chunk === 'string' ? chunk : chunk.path
// Turbopack prefixes chunks with "_next/", but Next.js expects
// them to be relative to the build directory.
if (path.startsWith('_next/')) {
path = path.slice('_next/'.length)
}
return path
}),
}
},
}
)
}
import type { ClientRequest, IncomingMessage, Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import http, { ServerResponse } from 'node:http'
import { headersFromEntries, initProxiedHeaders } from './headers'
export type ServerInfo = Partial<{
hostname: string
port: number
ip: string
protocol: string
}>
/**
* Creates a server that listens a random port.
*/
export function createServer(): Promise<Server> {
return new Promise((resolve) => {
const server = http.createServer()
server.listen(0, () => {
resolve(server)
})
})
}
/**
* Creates a request to a server, and returns the (req, res) pairs from both
* the client's and server's perspective.
*/
export function makeRequest(
server: Server,
method: string,
path: string,
rawQuery?: string,
rawHeaders?: [string, string][],
proxiedFor?: ServerInfo
): Promise<{
clientRequest: ClientRequest
clientResponsePromise: Promise<IncomingMessage>
serverRequest: IncomingMessage
serverResponse: ServerResponse<IncomingMessage>
}> {
return new Promise((resolve, reject) => {
let clientResponseResolve: (value: IncomingMessage) => void
let clientResponseReject: (error: Error) => void
const clientResponsePromise = new Promise<IncomingMessage>(
(resolve, reject) => {
clientResponseResolve = resolve
clientResponseReject = reject
}
)
const errorListener = (err: Error) => {
server.removeListener('request', requestListener)
reject(err)
}
const requestListener = (
req: IncomingMessage,
res: ServerResponse<IncomingMessage>
) => {
server.removeListener('error', errorListener)
resolve({
clientRequest,
clientResponsePromise,
serverRequest: req,
serverResponse: res,
})
}
server.once('request', requestListener)
server.once('error', errorListener)
const address = server.address() as AddressInfo
const headers = headersFromEntries(rawHeaders ?? [])
initProxiedHeaders(headers, proxiedFor)
const clientRequest = http.request({
host: 'localhost',
port: address.port,
method,
path: rawQuery?.length ? `${path}?${rawQuery}` : path,
headers,
})
// Otherwise Node.js waits for the first chunk of data to be written before sending the request.
clientRequest.flushHeaders()
const clientResponseErrorListener = (err: Error) => {
clientRequest.removeListener('response', responseListener)
clientResponseReject(err)
}
const responseListener = (res: IncomingMessage) => {
clientRequest.removeListener('error', clientResponseErrorListener)
clientResponseResolve(res)
}
clientRequest.once('response', responseListener)
clientRequest.once('error', clientResponseErrorListener)
})
}
import './shims'
// Necessary for Next.js to accept and handle the `webpackHMR` option properly
// in next-hydrate.js.
// @ts-expect-error next.js sets this as readonly in their `global.d.ts`
process.env.NODE_ENV = 'development'
// This is a fix for web-vitals.js not being linked properly.
globalThis.__dirname = ''
// This ensures Next.js uses React 18's APIs (hydrateRoot) instead of React 17's
// (hydrate).
process.env.__NEXT_REACT_ROOT = 'true'
# Turbopack Next Dev Overlay
Adapted from [next.js](https://github.com/vercel/next.js/tree/canary/packages/react-dev-overlay)
import * as Bus from './internal/bus'
import { parseStack } from './internal/helpers/parseStack'
import { setHooks } from '@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client'
let isRegistered = false
let stackTraceLimit: number | undefined = undefined
function onUnhandledError(ev: ErrorEvent) {
const error = ev?.error
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
}
if (
error.message.match(/(hydration|content does not match|did not match)/i)
) {
error.message += `\n\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`
}
const e = error
Bus.emit({
type: Bus.TYPE_UNHANDLED_ERROR,
reason: error,
frames: parseStack(e.stack!),
})
}
function onUnhandledRejection(ev: PromiseRejectionEvent) {
const reason = ev?.reason
if (
!reason ||
!(reason instanceof Error) ||
typeof reason.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}
const e = reason
Bus.emit({
type: Bus.TYPE_UNHANDLED_REJECTION,
reason: reason,
frames: parseStack(e.stack!),
})
}
function register() {
if (isRegistered) {
return
}
isRegistered = true
try {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 50
stackTraceLimit = limit
// eslint-disable-next-line no-empty
} catch {}
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
setHooks({
beforeRefresh: onBeforeRefresh,
refresh: onRefresh,
buildOk: onBuildOk,
issues: onTurbopackIssues,
})
}
function unregister() {
if (!isRegistered) {
return
}
isRegistered = false
if (stackTraceLimit !== undefined) {
try {
Error.stackTraceLimit = stackTraceLimit
// eslint-disable-next-line no-empty
} catch {}
stackTraceLimit = undefined
}
window.removeEventListener('error', onUnhandledError)
window.removeEventListener('unhandledrejection', onUnhandledRejection)
}
function onBuildOk() {
Bus.emit({ type: Bus.TYPE_BUILD_OK })
}
function onTurbopackIssues(issues: Issue[]) {
Bus.emit({ type: Bus.TYPE_TURBOPACK_ISSUES, issues })
}
function onBeforeRefresh() {
Bus.emit({ type: Bus.TYPE_BEFORE_REFRESH })
}
function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFRESH })
}
export { getErrorByType } from './internal/helpers/getErrorByType'
export { getServerError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { register, unregister }
import React from 'react'
type ErrorBoundaryProps = {
error: Error | null
onError: (error: Error, componentStack: string | null) => void
fallback: React.ReactNode | null
children?: React.ReactNode
}
type ErrorBoundaryState = {
error: Error | null
lastPropsError: Error | null
}
class ErrorBoundary extends React.PureComponent<
ErrorBoundaryProps,
ErrorBoundaryState
> {
static getDerivedStateFromError(error: Error) {
return { error }
}
state = {
error: null,
lastPropsError: null,
}
componentDidCatch(
error: Error,
// Loosely typed because it depends on the React version and was
// accidentally excluded in some versions.
errorInfo?: { componentStack?: string | null }
) {
this.props.onError(error, errorInfo?.componentStack ?? null)
}
// I don't like this, but it works to clear the error boundary
//
// props.error is only set 1 render after state.error, so we can't treat it as the source of truth all the time.
// to get around this we store the error from props in state and only accept updates if the stored error from props
// matches the error in state.
//
// this is definitely not a controlled component and it only works if the error matches exactly
static getDerivedStateFromProps(
props: ErrorBoundaryProps,
state: ErrorBoundaryState
): ErrorBoundaryState | null {
if (state.lastPropsError === props.error) {
return null
}
let error = state.error
if (state.error === state.lastPropsError) {
error = props.error
}
return {
error,
lastPropsError: props.error,
}
}
render() {
const { error } = this.state
const { fallback } = this.props
// The component has to be unmounted or else it would continue to error
if (error != null) {
return fallback
}
return this.props.children
}
}
export { ErrorBoundary }
import * as React from 'react'
import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal'
import { Errors, SupportedErrorEvent } from './container/Errors'
import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset'
type RefreshState =
| {
// No refresh in progress.
type: 'idle'
}
| {
// The refresh process has been triggered, but the new code has not been
// executed yet.
type: 'pending'
errors: SupportedErrorEvent[]
reactError: Error | null
}
type OverlayState = {
nextId: number
// issues are from turbopack
issues: Issue[]
// errors are client side
errors: SupportedErrorEvent[]
refreshState: RefreshState
reactError: Error | null
notFound?: boolean
}
function pushErrorFilterDuplicates(
errors: SupportedErrorEvent[],
err: SupportedErrorEvent
): SupportedErrorEvent[] {
return [
...errors.filter((e) => {
// Filter out duplicate errors
return e.event.reason !== err.event.reason
}),
err,
]
}
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) {
case Bus.TYPE_BUILD_OK: {
return { ...state, notFound: false }
}
case Bus.TYPE_TURBOPACK_ISSUES: {
return { ...state, issues: ev.issues }
}
case Bus.TYPE_BEFORE_REFRESH: {
return {
...state,
refreshState: { type: 'pending', errors: [], reactError: null },
}
}
case Bus.TYPE_REFRESH: {
return {
...state,
notFound: false,
errors:
// Errors can come in during updates. In this case, UNHANDLED_ERROR
// and UNHANDLED_REJECTION events might be dispatched between the
// BEFORE_REFRESH and the REFRESH event. We want to keep those errors
// around until the next refresh. Otherwise we run into a race
// condition where those errors would be cleared on refresh completion
// before they can be displayed.
state.refreshState.type === 'pending'
? state.refreshState.errors
: [],
reactError:
state.refreshState.type === 'pending'
? state.refreshState.reactError
: null,
refreshState: { type: 'idle' },
}
}
case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: {
switch (state.refreshState.type) {
case 'idle': {
return {
...state,
nextId: state.nextId + 1,
errors: pushErrorFilterDuplicates(state.errors, {
id: state.nextId,
event: ev,
}),
}
}
case 'pending': {
return {
...state,
nextId: state.nextId + 1,
refreshState: {
...state.refreshState,
errors: pushErrorFilterDuplicates(state.refreshState.errors, {
id: state.nextId,
event: ev,
}),
},
}
}
default:
return state
}
}
case Bus.TYPE_NOT_FOUND: {
return { ...state, notFound: true }
}
case Bus.TYPE_REACT_ERROR: {
switch (state.refreshState.type) {
case 'idle': {
return {
...state,
reactError: ev.error,
}
}
case 'pending': {
return {
...state,
refreshState: {
...state.refreshState,
reactError: ev.error,
},
}
}
default:
return state
}
}
default: {
return state
}
}
}
type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false
}
return preventType.includes(errorType)
}
type ReactDevOverlayProps = {
globalOverlay?: boolean
preventDisplay?: ErrorType[]
children?: React.ReactNode
}
export default function ReactDevOverlay({
children,
preventDisplay,
globalOverlay,
}: ReactDevOverlayProps) {
const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, {
nextId: 1,
issues: [],
errors: [],
refreshState: {
type: 'idle',
},
reactError: null,
})
React.useEffect(() => {
Bus.on(dispatch)
return function () {
Bus.off(dispatch)
}
}, [dispatch])
const onComponentError = React.useCallback(
(error: Error, componentStack: string | null) => {
Bus.emit({
type: Bus.TYPE_REACT_ERROR,
error,
componentStack,
})
},
[]
)
const hasBuildError = state.issues.length > 0
const hasRuntimeErrors = state.errors.length > 0
const errorType = hasBuildError
? 'build'
: hasRuntimeErrors
? 'runtime'
: null
const isMounted = hasBuildError || hasRuntimeErrors
return (
<React.Fragment>
<ErrorBoundary
error={state.reactError}
onError={onComponentError}
fallback={
// When the overlay is global for the application and it wraps a component rendering `<html>`
// we have to render the html shell otherwise the shadow root will not be able to attach
globalOverlay ? (
<html>
<body></body>
</html>
) : null
}
>
{children ?? null}
</ErrorBoundary>
{isMounted ? (
<ShadowPortal
// setting key ensures that ShadowPortal is re-mounted when the error changes
// this is necessary as nextjs-portal need to be reinjected when we re-render <body>
key={'' + !state.reactError}
globalOverlay={globalOverlay}
>
<CssReset />
<Base />
<ComponentStyles />
{shouldPreventDisplay(errorType, preventDisplay) ? null : (
<Errors issues={state.issues} errors={state.errors} />
)}
</ShadowPortal>
) : null}
</React.Fragment>
)
}
import { StackFrame } from 'stacktrace-parser'
export const TYPE_BUILD_OK = 'build-ok'
export const TYPE_TURBOPACK_ISSUES = 'turbopack-error'
export const TYPE_BEFORE_REFRESH = 'before-fast-refresh'
export const TYPE_REFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection'
export const TYPE_REACT_ERROR = 'react-error'
export const TYPE_NOT_FOUND = 'not-found'
export type BuildOk = { type: typeof TYPE_BUILD_OK }
export type TurbopackIssues = {
type: typeof TYPE_TURBOPACK_ISSUES
issues: Issue[]
}
export type BeforeFastRefresh = { type: typeof TYPE_BEFORE_REFRESH }
export type FastRefresh = { type: typeof TYPE_REFRESH }
export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR
reason: Error
frames: StackFrame[]
}
export type UnhandledRejection = {
type: typeof TYPE_UNHANDLED_REJECTION
reason: Error
frames: StackFrame[]
}
export type ReactError = {
type: typeof TYPE_REACT_ERROR
error: Error
componentStack: string | null
}
export type NotFoundAction = {
type: typeof TYPE_NOT_FOUND
}
export type BusEvent =
| BuildOk
| TurbopackIssues
| BeforeFastRefresh
| FastRefresh
| UnhandledError
| UnhandledRejection
| ReactError
| NotFoundAction
export type BusEventHandler = (ev: BusEvent) => void
const handlers: Set<BusEventHandler> = new Set()
const queue: BusEvent[] = []
function drain() {
// Draining should never happen synchronously in case multiple handlers are
// registered.
setTimeout(function () {
while (
// Until we are out of events:
Boolean(queue.length) &&
// Or, if all handlers removed themselves as a result of handling the
// event(s)
Boolean(handlers.size)
) {
const ev = queue.shift()!
handlers.forEach((handler) => handler(ev))
}
}, 1)
}
export function emit(ev: BusEvent): void {
queue.push(Object.freeze({ ...ev }))
drain()
}
export function on(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
return false
}
handlers.add(fn)
drain()
return true
}
export function off(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
handlers.delete(fn)
return true
}
return false
}
import Anser from '@vercel/turbopack-next/compiled/anser'
import * as React from 'react'
import { StackFrame } from '@vercel/turbopack-next/compiled/stacktrace-parser'
import stripAnsi from '@vercel/turbopack-next/compiled/strip-ansi'
import { getFrameSource } from '../../helpers/stack-frame'
export type CodeFrameProps = { stackFrame: StackFrame; codeFrame: string }
export function CodeFrame({ stackFrame, codeFrame }: CodeFrameProps) {
// Strip leading spaces out of the code frame:
const formattedFrame = React.useMemo<string>(() => {
const lines = codeFrame.split(/\r?\n/g)
const prefixLength = lines
.map((line) =>
/^>? +\d+ +\| [ ]+/.exec(stripAnsi(line)) === null
? null
: /^>? +\d+ +\| ( *)/.exec(stripAnsi(line))
)
.filter(Boolean)
.map((v) => v!.pop()!)
.reduce((c, n) => (isNaN(c) ? n.length : Math.min(c, n.length)), NaN)
if (prefixLength > 1) {
const p = ' '.repeat(prefixLength)
return lines
.map((line, a) =>
~(a = line.indexOf('|'))
? line.substring(0, a) + line.substring(a).replace(p, '')
: line
)
.join('\n')
}
return lines.join('\n')
}, [codeFrame])
const decoded = React.useMemo(() => {
return Anser.ansiToJson(formattedFrame, {
json: true,
use_classes: true,
remove_empty: true,
})
}, [formattedFrame])
const open = React.useCallback(() => {
const params = new URLSearchParams()
for (const key in stackFrame) {
params.append(key, ((stackFrame as any)[key] ?? '').toString())
}
self
.fetch(
`${
process.env.__NEXT_ROUTER_BASEPATH || ''
}/__nextjs_launch-editor?${params.toString()}`
)
.then(
() => {},
() => {
console.error('There was an issue opening this code in your editor.')
}
)
}, [stackFrame])
// TODO: make the caret absolute
return (
<div data-nextjs-codeframe className="codeframe">
<div>
<p
role="link"
onClick={open}
tabIndex={1}
title="Click to open in your editor"
>
<span>
{getFrameSource(stackFrame)} @ {stackFrame.methodName}
</span>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15 3 21 3 21 9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</svg>
</p>
</div>
<pre>
{decoded.map((entry, index) => (
<span
key={`frame-${index}`}
style={{
color: entry.fg ? `var(--color-${entry.fg})` : undefined,
...(entry.decoration === 'bold'
? { fontWeight: 800 }
: entry.decoration === 'italic'
? { fontStyle: 'italic' }
: undefined),
}}
>
{entry.content}
</span>
))}
</pre>
</div>
)
}
export { CodeFrame } from './CodeFrame'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.codeframe {
overflow: auto;
border-radius: var(--size-gap-half);
background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg);
}
.codeframe::selection,
.codeframe *::selection {
background-color: var(--color-ansi-selection);
}
.codeframe * {
color: inherit;
background-color: transparent;
font-family: var(--font-mono);
}
.codeframe > * {
margin: 0;
padding: calc(var(--size-gap) + var(--size-gap-half))
calc(var(--size-gap-double) + var(--size-gap-half));
}
.codeframe > div {
display: inline-block;
width: auto;
min-width: 100%;
border-bottom: 1px solid var(--color-ansi-bright-black);
}
.codeframe > div > p {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
margin: 0;
}
.codeframe > div > p:hover {
text-decoration: underline dotted;
}
.codeframe div > p > svg {
width: auto;
height: 1em;
margin-left: 8px;
}
.codeframe div > pre {
overflow: hidden;
display: inline-block;
}
`
export { styles }
import * as React from 'react'
import { useOnClickOutside } from '../../hooks/use-on-click-outside'
import { clsx } from '../../helpers/clsx'
import { noop as css } from '../../helpers/noop-template'
export type DialogProps = {
'aria-labelledby': string
'aria-describedby': string
onClose?: (e: MouseEvent | TouchEvent) => void
className?: string
children?: React.ReactNode | undefined
}
export function Dialog({
children,
onClose,
className,
...props
}: DialogProps) {
const [dialog, setDialog] = React.useState<HTMLDivElement | null>(null)
const [role, setRole] = React.useState<string | undefined>(
typeof document !== 'undefined' && document.hasFocus()
? 'dialog'
: undefined
)
const onDialog = React.useCallback(
(node: React.SetStateAction<HTMLDivElement | null>) => {
setDialog(node)
},
[]
)
useOnClickOutside(dialog, onClose)
// Make HTMLElements with `role=link` accessible to be triggered by the
// keyboard, i.e. [Enter].
React.useEffect(() => {
if (dialog == null) {
return
}
const root = dialog.getRootNode()
// Always true, but we do this for TypeScript:
if (!(root instanceof ShadowRoot)) {
return
}
const shadowRoot = root
function handler(e: KeyboardEvent) {
const el = shadowRoot.activeElement
if (
e.key === 'Enter' &&
el instanceof HTMLElement &&
el.getAttribute('role') === 'link'
) {
e.preventDefault()
e.stopPropagation()
el.click()
}
}
function handleFocus() {
// safari will force itself as the active application when a background page triggers any sort of autofocus
// this is a workaround to only set the dialog role if the document has focus
setRole(document.hasFocus() ? 'dialog' : undefined)
}
shadowRoot.addEventListener('keydown', handler as EventListener)
window.addEventListener('focus', handleFocus)
window.addEventListener('blur', handleFocus)
return () => {
shadowRoot.removeEventListener('keydown', handler as EventListener)
window.removeEventListener('focus', handleFocus)
window.removeEventListener('blur', handleFocus)
}
}, [dialog])
return (
<div
ref={onDialog}
tabIndex={-1}
role={role}
aria-labelledby={props['aria-labelledby']}
aria-describedby={props['aria-describedby']}
aria-modal="true"
className={clsx('dialog', className)}
>
{children}
</div>
)
}
export const styles = css`
.dialog {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: var(--size-gap);
box-shadow: 0 var(--size-gap-half) var(--size-gap-double)
rgba(0, 0, 0, 0.25);
max-height: calc(100% - 56px);
overflow-y: hidden;
}
@media (max-height: 812px) {
.dialog-overlay {
max-height: calc(100% - 15px);
}
}
@media (min-width: 576px) {
.dialog {
max-width: 540px;
box-shadow: 0 var(--size-gap) var(--size-gap-quad) rgba(0, 0, 0, 0.25);
}
}
@media (min-width: 768px) {
.dialog {
max-width: 720px;
}
}
@media (min-width: 992px) {
.dialog {
max-width: 960px;
}
}
`
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
import { noop as css } from '../../helpers/noop-template'
export type DialogBodyProps = {
className?: string
children?: React.ReactNode
} & React.HTMLProps<HTMLDivElement>
export function DialogBody({ children, className, ...rest }: DialogBodyProps) {
return (
<div className={clsx('dialog-body', className)} {...rest}>
{children}
</div>
)
}
export const styles = css`
.dialog-content > .dialog-body {
position: relative;
flex: 1 1 auto;
padding: var(--size-gap-double);
}
`
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
import { noop as css } from '../../helpers/noop-template'
export type DialogContentProps = {
className?: string
children?: React.ReactNode
} & React.HTMLProps<HTMLDivElement>
export function DialogContent({
className,
children,
...rest
}: DialogContentProps) {
return (
<div className={clsx('dialog-content', className)} {...rest}>
{children}
</div>
)
}
export const styles = css`
.dialog-content {
display: flex;
flex-direction: column;
overflow-y: hidden;
border: none;
margin: 0;
padding: 0;
height: 100%;
}
`
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
import { CloseIcon } from '../../icons'
import { noop as css } from '../../helpers/noop-template'
export type DialogHeaderProps = {
close?: () => void
className?: string
children: React.ReactNode
}
export function DialogHeader({
children,
className,
close,
}: DialogHeaderProps) {
const buttonClose = React.useRef<HTMLButtonElement | null>(null)
React.useEffect(() => {
if (buttonClose.current == null) {
return
}
const root = buttonClose.current.getRootNode()
const d = self.document
function handler(e: KeyboardEvent) {
if (e.key === 'Escape') {
e.stopPropagation()
if (root instanceof ShadowRoot) {
const a = root.activeElement
if (a && a !== buttonClose.current && a instanceof HTMLElement) {
a.blur()
return
}
}
if (close) {
close()
}
}
}
root.addEventListener('keydown', handler as EventListener)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
}
}, [close, buttonClose])
return (
<div data-nextjs-dialog-header className={clsx('dialog-header', className)}>
{children}
<div className="filler">&nbsp;</div>
{close ? (
<button
ref={buttonClose}
type="button"
onClick={close}
aria-label="Close"
className="close-button"
>
<span aria-hidden="true">
<CloseIcon />
</span>
</button>
) : null}
</div>
)
}
export const styles = css`
.dialog-content > .dialog-header {
flex-shrink: 0;
}
.dialog-header {
--local-padding: var(--size-gap-big);
display: flex;
flex-direction: row;
align-content: center;
align-items: center;
justify-content: space-between;
height: calc(
var(--size-icon) + var(--local-padding) * 2 + var(--border) * 2
);
background-color: var(--color-bg-secondary);
}
.dialog-header > * {
height: 100%;
padding: var(--local-padding);
border-bottom: var(--border);
}
.dialog-header > *:not(:first-child):not(.close-button) {
border-left: var(--border-half);
}
.dialog-header
> *:not(:last-child):not(:nth-last-child(2):before(.close-button)) {
border-right: var(--border-half);
}
.dialog-header > .filler {
display: flex;
flex: 1 0 auto;
flex-grow: 1;
align-self: stretch;
padding-left: 0;
padding-right: 0;
}
.dialog-header > .filler > div {
display: flex;
flex: 1 0 auto;
flex-grow: 1;
align-self: stretch;
padding: var(--local-padding);
padding-left: 0;
padding-right: 0;
border-bottom: var(--border);
}
.dialog-header > button:last-of-type {
border: none;
border-bottom: var(--border);
background-color: transparent;
appearance: none;
}
.dialog-header > button:last-of-type > span {
display: flex;
opacity: 0.4;
transition: opacity 0.25s ease;
}
.dialog-header > button:last-of-type:hover > span {
opacity: 0.7;
}
`
import * as React from 'react'
import { noop as css } from '../../helpers/noop-template'
import { clsx } from '../../helpers/clsx'
import { TabList } from '../Tabs'
export type DialogHeaderTabListProps = {
className?: string
children: React.ReactNode
}
export function DialogHeaderTabList({
className,
children,
}: DialogHeaderTabListProps) {
return (
<TabList className={clsx('dialog-header-tab-list', className)}>
{children}
</TabList>
)
}
export const styles = css`
.dialog-header > .dialog-header-tab-list {
padding: 0;
border: none !important;
}
.dialog-header-tab-list {
height: 100%;
display: flex;
justify-content: start;
align-content: center;
border-bottom: 0;
}
.dialog-header-tab-list > .tab {
display: flex;
align-items: center;
padding-left: calc(var(--local-padding) + var(--size-gap));
padding-right: calc(var(--local-padding) + var(--size-gap));
/* slight offset for the severity top border on the tabs */
padding-top: calc(var(--local-padding) + var(--size-border));
padding-bottom: calc(var(--local-padding) - var(--size-border));
height: 100%;
border-top: none;
border-bottom: var(--border);
border-left: var(--border-half);
border-right: var(--border-half);
color: var(--color-text-dim);
background-color: transparent;
}
.dialog-header-tab-list > .tab:first-child {
border-left: none;
}
.tab::after {
position: absolute;
left: 0;
top: 0;
right: 0;
border-top: var(--size-border-double) solid transparent;
content: ' ';
}
.dialog-header-tab-list > .tab:hover {
background-color: var(--color-bg-secondary-hover);
}
.dialog-header-tab-list > .tab[aria-selected='true'] {
color: var(--color-text);
background-color: var(--color-bg);
border-bottom-color: transparent;
}
`
export { Dialog, DialogProps } from './Dialog'
export { DialogBody, DialogBodyProps } from './DialogBody'
export { DialogContent, DialogContentProps } from './DialogContent'
export { DialogHeader, DialogHeaderProps } from './DialogHeader'
export {
DialogHeaderTabList,
DialogHeaderTabListProps,
} from './DialogHeaderTabList'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
import { styles as dialogStyles } from './Dialog'
import { styles as bodyStyles } from './DialogBody'
import { styles as contentStyles } from './DialogContent'
import { styles as headerStyles } from './DialogHeader'
import { styles as tabListStyles } from './DialogHeaderTabList'
const styles = css`
${dialogStyles}
${bodyStyles}
${contentStyles}
${headerStyles}
${tabListStyles}
`
export { styles }
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
export type LeftRightDialogHeaderProps = {
hidden?: boolean
previous?: (() => void) | null
next?: (() => void) | null
severity: 'warning' | 'error'
className?: string
children: React.ReactNode
}
export function LeftRightDialogHeader({
hidden = false,
previous,
next,
severity,
className,
children,
}: LeftRightDialogHeaderProps) {
const buttonLeft = React.useRef<HTMLButtonElement | null>(null)
const buttonRight = React.useRef<HTMLButtonElement | null>(null)
const [nav, setNav] = React.useState<HTMLElement | null>(null)
const onNav = React.useCallback((el: HTMLElement) => {
setNav(el)
}, [])
React.useEffect(() => {
if (nav == null || hidden) {
return
}
const root = nav.getRootNode()
const d = self.document
function handler(e: KeyboardEvent) {
if (e.key === 'ArrowLeft') {
e.stopPropagation()
if (buttonLeft.current) {
buttonLeft.current.focus()
}
previous && previous()
} else if (e.key === 'ArrowRight') {
e.stopPropagation()
if (buttonRight.current) {
buttonRight.current.focus()
}
next && next()
}
}
root.addEventListener('keydown', handler as EventListener)
if (root !== d) {
d.addEventListener('keydown', handler)
}
return function () {
root.removeEventListener('keydown', handler as EventListener)
if (root !== d) {
d.removeEventListener('keydown', handler)
}
}
}, [hidden, nav, next, previous])
// Unlock focus for browsers like Firefox, that break all user focus if the
// currently focused item becomes disabled.
React.useEffect(() => {
if (nav == null) {
return
}
const root = nav.getRootNode()
// Always true, but we do this for TypeScript:
if (root instanceof ShadowRoot) {
const a = root.activeElement
if (previous == null) {
if (buttonLeft.current && a === buttonLeft.current) {
buttonLeft.current.blur()
}
} else if (next == null) {
if (buttonRight.current && a === buttonRight.current) {
buttonRight.current.blur()
}
}
}
}, [nav, next, previous])
return (
<nav
ref={onNav}
data-severity={severity}
className={clsx('dialog-left-right', className)}
>
{children}
&nbsp;
<button
ref={buttonLeft}
type="button"
disabled={previous == null ? true : undefined}
aria-disabled={previous == null ? true : undefined}
onClick={previous ?? undefined}
>
<ArrowLeft />
</button>
<button
ref={buttonRight}
type="button"
disabled={next == null ? true : undefined}
aria-disabled={next == null ? true : undefined}
onClick={next ?? undefined}
>
<ArrowRight />
</button>
</nav>
)
}
function ArrowLeft() {
return (
<svg
viewBox="0 0 14 14"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M6.99996 1.16666L1.16663 6.99999L6.99996 12.8333M12.8333 6.99999H1.99996H12.8333Z" />
</svg>
)
}
function ArrowRight() {
return (
<svg
viewBox="0 0 14 14"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M6.99996 1.16666L12.8333 6.99999L6.99996 12.8333M1.16663 6.99999H12H1.16663Z" />
</svg>
)
}
export { LeftRightDialogHeader } from './LeftRightDialogHeader'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.dialog-left-right {
white-space: nowrap;
}
.dialog-left-right > button {
--bg-alpha: 0.1;
--fg-alpha: 1;
display: inline-flex;
align-items: center;
justify-content: center;
width: calc(var(--size-gap-double) + var(--size-gap));
height: calc(var(--size-gap-double) + var(--size-gap));
font-size: 0;
border: none;
background-color: hsla(var(--color-base), var(--bg-alpha));
color: hsla(var(--color-base), var(--fg-alpha));
cursor: pointer;
transition: background-color 0.25s ease;
}
.dialog-left-right[data-severity='error'] > button {
--color-base: var(--color-error-bright-hsl);
}
.dialog-left-right[data-severity='warning'] > button {
--color-base: var(--color-warning-bright-hsl);
}
.dialog-left-right > button:hover {
--bg-alpha: 0.2;
}
.dialog-left-right > button:disabled {
--bg-alpha: 0.1;
--fg-alpha: 0.4;
cursor: not-allowed;
}
.dialog-left-right > button:first-of-type {
border-radius: var(--size-gap-half) 0 0 var(--size-gap-half);
margin-right: 1px;
}
.dialog-left-right > button:last-of-type {
border-radius: 0 var(--size-gap-half) var(--size-gap-half) 0;
}
.dialog-left-right > button > svg {
width: auto;
height: var(--size-icon-small);
}
`
export { styles }
import * as React from 'react'
import { lock, unlock } from './body-locker'
import allyTrap from './maintain--tab-focus'
import { clsx } from '../../helpers/clsx'
export type OverlayProps = React.PropsWithChildren & {
className?: string
fixed?: boolean
}
export function Overlay({ className, children, fixed }: OverlayProps) {
React.useEffect(() => {
lock()
return () => {
unlock()
}
}, [])
const [overlay, setOverlay] = React.useState<HTMLDivElement | null>(null)
const onOverlay = React.useCallback((el: HTMLDivElement) => {
setOverlay(el)
}, [])
React.useEffect(() => {
if (overlay == null) {
return
}
const handle2 = allyTrap({ context: overlay })
return () => {
handle2.disengage()
}
}, [overlay])
return (
<div className={clsx('dialog-overlay', className)} ref={onOverlay}>
<div
className={'dialog-backdrop'}
data-dialog-backdrop-fixed={fixed ? true : undefined}
/>
{children}
</div>
)
}
let previousBodyPaddingRight: string | undefined
let previousBodyOverflowSetting: string | undefined
let activeLocks = 0
export function lock() {
setTimeout(() => {
if (activeLocks++ > 0) {
return
}
const scrollBarGap =
window.innerWidth - document.documentElement.clientWidth
if (scrollBarGap > 0) {
previousBodyPaddingRight = document.body.style.paddingRight
document.body.style.paddingRight = `${scrollBarGap}px`
}
previousBodyOverflowSetting = document.body.style.overflow
document.body.style.overflow = 'hidden'
})
}
export function unlock() {
setTimeout(() => {
if (activeLocks === 0 || --activeLocks !== 0) {
return
}
if (previousBodyPaddingRight !== undefined) {
document.body.style.paddingRight = previousBodyPaddingRight
previousBodyPaddingRight = undefined
}
if (previousBodyOverflowSetting !== undefined) {
document.body.style.overflow = previousBodyOverflowSetting
previousBodyOverflowSetting = undefined
}
})
}
export { Overlay } from './Overlay'
export { styles } from './styles'
This source diff could not be displayed because it is too large. You can view the blob instead.
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.dialog-overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
z-index: 9000;
display: flex;
align-content: center;
align-items: center;
flex-direction: column;
padding: 10vh 15px 0;
}
@media (max-height: 812px) {
.dialog-overlay {
padding: 15px 15px 0;
}
}
.dialog-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(17, 17, 17, 0.2);
pointer-events: all;
z-index: -1;
}
.dialog-backdrop[data-dialog-backdrop-fixed] {
cursor: not-allowed;
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
}
`
export { styles }
import * as React from 'react'
import { createPortal } from 'react-dom'
export type ShadowPortalProps = {
children: React.ReactNode
globalOverlay?: boolean
}
export function ShadowPortal({ children, globalOverlay }: ShadowPortalProps) {
const mountNode = React.useRef<HTMLDivElement | null>(null)
const portalNode = React.useRef<HTMLElement | null>(null)
const shadowNode = React.useRef<ShadowRoot | null>(null)
const [, forceUpdate] = React.useState<{} | undefined>()
React.useLayoutEffect(() => {
const ownerDocument = globalOverlay
? document
: mountNode.current!.ownerDocument!
portalNode.current = ownerDocument.createElement('nextjs-portal')
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current)
forceUpdate({})
return () => {
if (
portalNode.current &&
portalNode.current.ownerDocument &&
portalNode.current.parentNode
) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current)
}
}
}, [globalOverlay])
return shadowNode.current ? (
createPortal(children, shadowNode.current as any)
) : globalOverlay ? null : (
<span ref={mountNode} />
)
}
// TODO: replace with `@react/tabs`
import * as React from 'react'
import { noop as css } from '../../helpers/noop-template'
import { createContext } from '../../hooks/context'
import { clsx } from '../../helpers/clsx'
type Merge<P1 = {}, P2 = {}> = Omit<P1, keyof P2> & P2
type PropsWithAs<As, OwnProps = {}> = As extends ''
? { as: keyof JSX.IntrinsicElements }
: As extends React.JSXElementConstructor<infer P>
? Merge<P, OwnProps & { as: As }>
: As extends keyof JSX.IntrinsicElements
? Merge<JSX.IntrinsicElements[As], OwnProps & { as: As }>
: never
type TabRefs = Record<string, HTMLElement | undefined>
type TabsContextType = {
selectedId: string
registerTabRef: (id: string, el: HTMLElement | null) => void
onSelectTab: (id: string) => void
}
const [TabsProvider, useTabsContext] = createContext<TabsContextType>('Tabs')
export type TabsProps = {
defaultId: string
selectedId?: string
onChange?: (id: string) => void
children: React.ReactNode
}
export function Tabs({
defaultId,
selectedId: controlledId,
onChange,
children,
}: TabsProps) {
const [selectedId, setSelectedId] = React.useState(controlledId ?? defaultId)
const [shouldCheckId, setShouldShouldCheckId] = React.useState(false)
const tabRefs = React.useRef<TabRefs>({})
const onSelectTabUnchecked = React.useCallback(
(id: string) => {
onChange && onChange(id)
setSelectedId(id)
},
[onChange]
)
const onSelectTab = React.useCallback(
(id: string) => {
if (id == selectedId) return
const tab = tabRefs.current[id]
if (!tab) {
console.error(
`Tried selecting invalid tab id "${id}", only ${JSON.stringify(
Object.keys(tabRefs.current)
)} are available.`
)
return
}
setTimeout(() => {
tab.focus()
}, 0)
onSelectTabUnchecked(id)
},
[selectedId, onSelectTabUnchecked]
)
const registerTabRef = React.useCallback(
(id: string, el: HTMLElement | null) => {
if (el == null) {
delete tabRefs.current[id]
setShouldShouldCheckId(true)
} else {
tabRefs.current[id] = el
}
},
[]
)
React.useEffect(() => {
if (!shouldCheckId) return
const currentTabRef = tabRefs.current[selectedId]
if (currentTabRef == null) {
const availableIds = Object.keys(tabRefs.current)
if (availableIds.length > 0) {
onSelectTabUnchecked(availableIds[0])
}
}
setShouldShouldCheckId(false)
}, [shouldCheckId, selectedId, onSelectTabUnchecked])
React.useEffect(() => {
if (controlledId && controlledId != selectedId) {
onSelectTabUnchecked(controlledId)
}
}, [controlledId, selectedId, onSelectTabUnchecked])
return (
<TabsProvider
selectedId={selectedId}
registerTabRef={registerTabRef}
onSelectTab={onSelectTab}
>
{children}
</TabsProvider>
)
}
export type TabListProps = {
className?: string
children: React.ReactNode
}
export function TabList({ className, children }: TabListProps) {
return (
<div role="tablist" className={clsx('tab-list', className)}>
{children}
</div>
)
}
export type TabProps = {
id: string
next?: string
prev?: string
className?: string
children: React.ReactNode
}
export function Tab({
id,
next,
prev,
className,
children,
...rest
}: TabProps & React.HTMLProps<HTMLButtonElement>) {
const { selectedId, registerTabRef, onSelectTab } = useTabsContext('Tab')
const selected = id == selectedId
const click = React.useCallback(
(ev: React.MouseEvent<any>) => {
ev.preventDefault()
onSelectTab(id)
},
[id, onSelectTab]
)
const keyDown = React.useCallback(
(ev: React.KeyboardEvent<any>) => {
if (prev && ev.key === 'ArrowLeft') {
ev.stopPropagation()
onSelectTab(prev)
} else if (next && ev.key === 'ArrowRight') {
ev.stopPropagation()
onSelectTab(next)
}
},
[next, prev, onSelectTab]
)
const ref = React.useCallback(
(el: HTMLElement | null) => registerTabRef(id, el),
[id, registerTabRef]
)
return (
<button
{...rest}
type="button"
ref={ref}
aria-controls={id}
id={`tab-${id}`}
role="tab"
aria-selected={selected}
tabIndex={selected ? 0 : -1}
className={clsx('tab', className)}
onClick={click}
onKeyDown={keyDown}
>
{children}
</button>
)
}
export type TabPanelPropsBase = {
id: string
className?: string
}
export function TabPanel<
As extends
| keyof JSX.IntrinsicElements
| React.JSXElementConstructor<any> = 'div'
>({
as: Comp = 'div',
id,
className,
children,
...rest
}: PropsWithAs<As, TabPanelPropsBase>) {
const { selectedId } = useTabsContext('Tab')
const selected = id == selectedId
return (
<Comp
{...rest}
id={id}
aria-labelledby={`tab-${id}`}
role="tabpanel"
className={clsx('tab-panel', className)}
data-hidden={!selected}
>
{children}
</Comp>
)
}
export const styles = css`
.tab-panel[data-hidden='true'] {
display: none;
}
`
import Anser from '@vercel/turbopack-next/compiled/anser'
import * as React from 'react'
export type TerminalProps = { content: string }
export function Terminal({ content }: TerminalProps) {
const decoded = React.useMemo(() => {
return Anser.ansiToJson(content, {
json: true,
use_classes: true,
remove_empty: true,
})
}, [content])
return (
<div data-nextjs-terminal className="terminal">
<pre>
{decoded.map((entry, index) => (
<span
key={`terminal-entry-${index}`}
style={{
color: entry.fg ? `var(--color-${entry.fg})` : undefined,
...(entry.decoration === 'bold'
? { fontWeight: 800 }
: entry.decoration === 'italic'
? { fontStyle: 'italic' }
: undefined),
}}
>
{entry.content}
</span>
))}
</pre>
</div>
)
}
export { Terminal } from './Terminal'
export { styles } from './styles'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.terminal {
display: flex;
overflow-y: hidden;
border-radius: var(--size-gap-half);
background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg);
}
.terminal::selection,
.terminal *::selection {
background-color: var(--color-ansi-selection);
}
.terminal * {
color: inherit;
background-color: transparent;
font-family: var(--font-mono);
}
.terminal > * {
margin: 0;
padding: calc(var(--size-gap) + var(--size-gap-half))
calc(var(--size-gap-double) + var(--size-gap-half));
}
.terminal pre {
width: 100%;
white-space: pre-wrap;
word-break: break-word;
overflow-y: scroll;
}
`
export { styles }
import * as React from 'react'
import { clsx } from '../../helpers/clsx'
export type ToastProps = React.PropsWithChildren & {
onClick?: (ev: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
className?: string
}
export function Toast({
onClick,
children,
className,
...rest
}: ToastProps & React.HTMLProps<HTMLDivElement>) {
return (
<div
{...rest}
data-nextjs-toast
onClick={onClick}
className={clsx('toast', className)}
>
<div data-nextjs-toast-wrapper className="toast-wrapper">
{children}
</div>
</div>
)
}
export { styles } from './styles'
export { Toast } from './Toast'
import { noop as css } from '../../helpers/noop-template'
const styles = css`
.toast {
position: fixed;
bottom: var(--size-gap-double);
left: var(--size-gap-double);
max-width: 420px;
z-index: 9000;
}
@media (max-width: 440px) {
.toast {
max-width: 90vw;
left: 5vw;
}
}
.toast-wrapper {
padding: 16px;
border-radius: var(--size-gap-half);
font-weight: 600;
box-shadow: 0px var(--size-gap-double) var(--size-gap-quad)
rgba(0, 0, 0, 0.25);
}
.toast[data-severity='error'] > .toast-wrapper {
color: var(--color-text-white);
background-color: var(--color-error);
}
.toast[data-severity='warning'] > .toast-wrapper {
color: var(--color-text-white);
background-color: var(--color-warning);
}
`
export { styles }
import * as React from 'react'
import {
TYPE_UNHANDLED_ERROR,
TYPE_UNHANDLED_REJECTION,
UnhandledError,
UnhandledRejection,
} from '../bus'
import {
Dialog,
DialogContent,
DialogHeader,
DialogHeaderTabList,
DialogProps,
} from '../components/Dialog'
import { Overlay } from '../components/Overlay'
import { Tab, TabPanel, Tabs } from '../components/Tabs'
import {
getErrorByType,
getUnresolvedErrorByType,
ReadyRuntimeError,
} from '../helpers/getErrorByType'
import { noop as css } from '../helpers/noop-template'
import { AlertOctagon, PackageX } from '../icons'
import { RuntimeErrorsDialogBody } from './RuntimeError'
import { TurbopackIssuesDialogBody } from '../container/TurbopackIssue'
import { ErrorsToast } from '../container/ErrorsToast'
export type SupportedErrorEvent = {
id: number
event: UnhandledError | UnhandledRejection
}
export type ErrorsProps = {
issues: Issue[]
errors: SupportedErrorEvent[]
}
type ReadyErrorEvent = ReadyRuntimeError
function getErrorSignature(ev: SupportedErrorEvent): string {
const { event } = ev
switch (event.type) {
case TYPE_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: {
return `${event.reason.name}::${event.reason.message}::${event.reason.stack}`
}
default: {
return ''
}
}
}
function useResolvedErrors(
errors: SupportedErrorEvent[]
): [ReadyRuntimeError[], boolean] {
const [lookups, setLookups] = React.useState(
{} as { [eventId: string]: ReadyErrorEvent }
)
const [readyErrors, nextError] = React.useMemo<
[ReadyErrorEvent[], SupportedErrorEvent | null]
>(() => {
const ready: ReadyErrorEvent[] = []
let next: SupportedErrorEvent | null = null
// Ensure errors are displayed in the order they occurred in:
for (let idx = 0; idx < errors.length; ++idx) {
const e = errors[idx]
const { id } = e
if (id in lookups) {
ready.push(lookups[id])
continue
}
// Check for duplicate errors
if (idx > 0) {
const prev = errors[idx - 1]
if (getErrorSignature(prev) === getErrorSignature(e)) {
continue
}
}
// Show unresolved errors as fallback
ready.push(getUnresolvedErrorByType(e))
next = e
break
}
return [ready, next]
}, [errors, lookups])
const isLoading = readyErrors.length === 0 && errors.length > 1
React.useEffect(() => {
if (nextError == null) {
return
}
let mounted = true
getErrorByType(nextError).then(
(resolved) => {
// We don't care if the desired error changed while we were resolving,
// thus we're not tracking it using a ref. Once the work has been done,
// we'll store it.
if (mounted) {
setLookups((m) => ({ ...m, [resolved.id]: resolved }))
}
},
() => {
// TODO: handle this, though an edge case
}
)
return () => {
mounted = false
}
}, [nextError])
// Reset component state when there are no errors to be displayed.
// This should never happen, but let's handle it.
React.useEffect(() => {
if (errors.length === 0) {
setLookups({})
}
}, [errors.length])
return [readyErrors, isLoading]
}
const enum TabId {
TurbopackErrors = 'turbopack-issues',
TurbopackWarnings = 'turbopack-warnings',
TurbopackExternal = 'turbopack-external',
RuntimeErrors = 'runtime-errors',
RuntimeWarnings = 'runtime-warnings',
}
const TAB_PRIORITY = [
TabId.TurbopackErrors,
TabId.RuntimeErrors,
TabId.TurbopackWarnings,
]
function isWarning(issue: Issue) {
return !['bug', 'fatal', 'error'].includes(issue.severity)
}
function isUserCode(issue: Issue) {
return !issue.file_path || !issue.file_path.includes('node_modules')
}
function isRuntimeWarning(error: ReadyRuntimeError) {
return [
'This Suspense boundary received an update before it finished hydrating.',
'Hydration failed because the initial UI does not match what was rendered on the server.',
'There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.',
'There was an error while hydrating this Suspense boundary. Switched to client rendering.',
].some((message) => error.error.message.includes(message))
}
interface TabBase {
id: TabId
icon: any
title: {
one: string
many: string
short: string
}
message: any
autoOpen: boolean
severity: 'error' | 'warning' | 'none'
as: any
}
interface TabConfig extends TabBase {
items: (input: {
readyErrors: ReadyRuntimeError[]
issues: Issue[]
}) => ReadyRuntimeError[] | Issue[]
}
const TABS: TabConfig[] = [
{
id: TabId.RuntimeErrors,
icon: <AlertOctagon />,
title: {
one: 'Runtime Error',
many: 'Runtime Errors',
short: 'Err',
},
message: <>Unhandled errors reported when running the application.</>,
items: ({ readyErrors }) => {
return readyErrors.filter((e) => !isRuntimeWarning(e))
},
severity: 'error',
autoOpen: true,
as: RuntimeErrorsDialogBody,
},
{
id: TabId.TurbopackErrors,
icon: <PackageX />,
title: {
one: 'Turbopack Error',
many: 'Turbopack Errors',
short: 'Err',
},
message: (
<>
Errors reported when compiling the application.
<br />
The application might work partially, but that's unlikely.
</>
),
items: ({ issues }) => {
return issues.filter((i) => isUserCode(i) && !isWarning(i))
},
severity: 'error',
autoOpen: true,
as: TurbopackIssuesDialogBody,
},
{
id: TabId.RuntimeWarnings,
icon: <AlertOctagon />,
title: {
one: 'Runtime Warnings',
many: 'Runtime Warnings',
short: 'Warn',
},
message: (
<>
Unhandled errors reported when running the application.
<br />
The application might work partially, but that's unlikely.
</>
),
items: ({ readyErrors }) => {
return readyErrors.filter((e) => isRuntimeWarning(e))
},
severity: 'warning',
autoOpen: false,
as: RuntimeErrorsDialogBody,
},
{
id: TabId.TurbopackWarnings,
icon: <PackageX />,
title: {
one: 'Turbopack Warning',
many: 'Turbopack Warnings',
short: 'Warn',
},
message: (
<>
Warnings reported when compiling the application.
<br />
The application will probably work regardless, but these issues should
be addressed eventually.
</>
),
items: ({ issues }) => {
return issues.filter((i) => isUserCode(i) && isWarning(i))
},
severity: 'warning',
autoOpen: false,
as: TurbopackIssuesDialogBody,
},
{
id: TabId.TurbopackExternal,
icon: <PackageX />,
title: {
one: 'Turbopack External Problem',
many: 'Turbopack External Problems',
short: 'Ext',
},
message: (
<>
Errors or warnings reported while compiling external code.
<br />
The application might be affected by them.
</>
),
items: ({ issues }) => {
return issues.filter((i) => !isUserCode(i) && !isWarning(i))
},
severity: 'none',
autoOpen: false,
as: TurbopackIssuesDialogBody,
},
]
interface Tab extends TabBase {
items: ReadyRuntimeError[] | Issue[]
}
// "instantiates" all tabs, filters out the ones that don't have any items
function createTabs({
issues,
readyErrors,
}: {
issues: Issue[]
readyErrors: ReadyRuntimeError[]
}): Tab[] {
const tabs = TABS.map((tab) => ({
...tab,
items: tab.items({ issues, readyErrors }),
}))
return tabs.filter((tab) => tab.items.length > 0)
}
function itemHash(item: object) {
return JSON.stringify(item)
}
type DisplayState =
| {
type: 'fullscreen'
tab: TabId
}
| {
type: 'minimized'
}
| {
type: 'hidden'
}
type ErrorsState = {
tabs: Tab[]
display: DisplayState
errorCount: number
warningCount: number
seenIds: Set<string>
issues: Issue[]
readyErrors: ReadyRuntimeError[]
lastSelectedTab: TabId | null
}
enum ErrorsActionType {
UpdateIssues = 'update-issues',
UpdateErrors = 'update-errors',
SelectTab = 'select-tab',
Fullscreen = 'fullscreen',
Minimize = 'minimize',
Hide = 'hide',
}
type UpdateIssuesAction = {
type: typeof ErrorsActionType.UpdateIssues
issues: Issue[]
}
type UpdateErrorsAction = {
type: typeof ErrorsActionType.UpdateErrors
readyErrors: ReadyRuntimeError[]
}
type SelectTabAction = {
type: typeof ErrorsActionType.SelectTab
tabId: TabId
}
type FullscreenAction = {
type: typeof ErrorsActionType.Fullscreen
}
type MinimizeAction = {
type: typeof ErrorsActionType.Minimize
}
type HideAction = {
type: typeof ErrorsActionType.Hide
}
type ErrorsAction =
| UpdateIssuesAction
| UpdateErrorsAction
| SelectTabAction
| FullscreenAction
| MinimizeAction
| HideAction
// puts item
function prependNewItems<T extends object>(
items: T[],
seenIds: Set<string>
): T[] {
const newItems = []
let newIdx = 0
for (const item of items) {
if (seenIds.has(itemHash(item))) {
newItems.push(item)
} else {
newItems.splice(newIdx, 0, item)
}
}
return newItems
}
function reducer(oldState: ErrorsState, action: ErrorsAction): ErrorsState {
let state = oldState
switch (action.type) {
case ErrorsActionType.UpdateIssues: {
if (action.issues == oldState.issues) {
return oldState
}
const issues = prependNewItems(action.issues, oldState.seenIds)
state = {
...oldState,
issues,
tabs: createTabs({
issues,
readyErrors: oldState.readyErrors,
}),
}
break
}
case ErrorsActionType.UpdateErrors: {
if (action.readyErrors == oldState.readyErrors) {
return oldState
}
const readyErrors = prependNewItems(action.readyErrors, oldState.seenIds)
state = {
...oldState,
readyErrors,
tabs: createTabs({
issues: oldState.issues,
readyErrors,
}),
}
break
}
case ErrorsActionType.SelectTab: {
state = {
...oldState,
display: {
type: 'fullscreen',
tab: action.tabId,
},
}
break
}
case ErrorsActionType.Fullscreen: {
state = {
...oldState,
display: {
type: 'fullscreen',
tab: oldState.lastSelectedTab || TabId.TurbopackErrors,
},
}
break
}
case ErrorsActionType.Minimize: {
return {
...oldState,
display: {
type: 'minimized',
},
}
}
case ErrorsActionType.Hide: {
return {
...oldState,
display: {
type: 'hidden',
},
}
}
}
let autoOpen = false
// When the selected tab disappears we will go to another important tab or close the overlay
if (
state.display.type == 'fullscreen' &&
!state.tabs.map((tab) => tab.id).includes(state.display.tab)
) {
const otherImportantTab = state.tabs.find((tab) => tab.autoOpen)
if (otherImportantTab) {
state.display.tab = otherImportantTab.id
} else {
state.display = {
type: 'hidden',
}
}
} else {
autoOpen = true
}
state.seenIds = new Set()
// When there is a new item we open the overlay when autoOpen is set
for (const tab of state.tabs) {
for (const item of tab.items) {
state.seenIds.add(itemHash(item))
if (!oldState.seenIds.has(itemHash(item))) {
if (state.display.type == 'hidden') {
state.display = {
type: 'minimized',
}
}
if (autoOpen && tab.autoOpen) {
state.display = {
type: 'fullscreen',
tab: tab.id,
}
}
}
}
}
if (state.tabs !== oldState.tabs) {
state.errorCount = state.tabs.reduce(
(sum, tab) => sum + (tab.severity === 'error' ? tab.items.length : 0),
0
)
state.warningCount = state.tabs.reduce(
(sum, tab) => sum + (tab.severity === 'warning' ? tab.items.length : 0),
0
)
}
if (
state.tabs.length === 0 ||
(state.errorCount === 0 && state.warningCount === 0)
) {
state.display = {
type: 'hidden',
}
}
if (state.display.type === 'fullscreen') {
state.lastSelectedTab = state.display.tab
}
return state
}
export function Errors({ issues, errors }: ErrorsProps) {
const [readyErrors, _isLoading] = useResolvedErrors(errors)
const [{ tabs, display, errorCount, warningCount }, dispatch] =
React.useReducer<React.Reducer<ErrorsState, ErrorsAction>, null>(
reducer,
null,
() =>
reducer(
{
seenIds: new Set(),
tabs: [],
lastSelectedTab: null,
display: {
type: 'hidden',
},
issues: [],
readyErrors,
errorCount: 0,
warningCount: 0,
},
{ type: ErrorsActionType.UpdateIssues, issues }
)
)
React.useEffect(() => {
dispatch({ type: ErrorsActionType.UpdateIssues, issues })
}, [issues])
React.useEffect(() => {
dispatch({ type: ErrorsActionType.UpdateErrors, readyErrors })
}, [readyErrors])
function setSelectedTab(tabId: string) {
dispatch({
type: ErrorsActionType.SelectTab,
tabId: tabId as TabId,
})
}
if (display.type == 'hidden') {
return null
}
if (display.type == 'minimized') {
return (
<ErrorsToast
errorCount={errorCount}
warningCount={warningCount}
severity={errorCount > 0 ? 'error' : 'warning'}
onClick={() => setSelectedTab(tabs[0].id)}
onClose={() => dispatch({ type: ErrorsActionType.Hide })}
/>
)
}
return (
<ErrorsDialog
aria-labelledby="nextjs__container_errors_label"
aria-describedby="nextjs__container_errors_desc"
onClose={() => dispatch({ type: ErrorsActionType.Minimize })}
>
<Tabs
defaultId={TabId.RuntimeErrors}
selectedId={display.tab}
onChange={setSelectedTab}
>
<DialogHeader
className="errors-header"
close={() => dispatch({ type: ErrorsActionType.Minimize })}
>
<DialogHeaderTabList>
{tabs.map((tab, i) => (
<Tab
key={tab.id}
id={tab.id}
next={tabs[(i + 1) % tabs.length].id}
prev={tabs[(i + tabs.length - 1) % tabs.length].id}
data-severity={tab.severity}
>
{tab.icon} {tab.items.length}{' '}
{tabs.length > 3
? tab.title.short
: tab.items.length > 1
? tab.title.many
: tab.title.one}
</Tab>
))}
</DialogHeaderTabList>
</DialogHeader>
{tabs.map((tab) => (
<TabPanel
key={tab.id}
id={tab.id}
as={tab.as}
items={tab.items}
message={tab.message}
severity={tab.severity}
className="errors-body"
/>
))}
</Tabs>
</ErrorsDialog>
)
}
function ErrorsDialog({ children, ...props }: DialogProps) {
return (
<Overlay>
<Dialog {...props}>
<DialogContent>{children}</DialogContent>
</Dialog>
</Overlay>
)
}
export const styles = css`
/** == Header == */
.errors-header > .tab-list > .tab > svg {
margin-right: var(--size-gap);
}
.errors-header > .tab-list > .tab[data-severity='error'] > svg {
color: var(--color-error);
}
.errors-header > .tab-list > .tab[data-severity='warning'] > svg {
color: var(--color-warning);
}
.errors-header > .tab-list > .tab {
position: relative;
}
.errors-header > .tab-list > .tab[data-severity='error']::after {
border-top-color: var(--color-error);
}
.errors-header > .tab-list > .tab[data-severity='warning']::after {
border-top-color: var(--color-warning);
}
/** == Body == */
.errors-body {
display: flex;
flex-direction: column;
overflow-y: hidden;
}
.errors-body > .title-pagination {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: var(--size-gap);
}
.errors-body > .title-pagination > nav > small {
font-size: var(--size-font-small);
color: var(--color-text-dim);
margin-right: var(--size-gap);
opacity: 0.7;
}
.errors-body > .title-pagination > nav > small > span {
font-family: var(--font-mono);
}
.errors-body > .title-pagination > h1 {
font-size: var(--size-font-big);
color: var(--color-text-dim);
margin: 0;
opacity: 0.9;
}
.errors-body > h2 {
font-family: var(--font-mono);
font-size: var(--size-font-big);
line-height: var(--size-font-bigger);
font-weight: bold;
margin: 0;
margin-bottom: var(--size-gap);
color: var(--color-error);
white-space: pre-wrap;
overflow-wrap: break-word;
}
.errors-body > h2[data-severity='error'] {
color: var(--color-error);
}
.errors-body > h2[data-severity='warning'] {
color: var(--color-warning);
}
.errors-body > div > small {
margin: 0;
margin-top: var(--size-gap-half);
}
.errors-body > h2 > a {
color: var(--color-error);
}
.errors-body > h5:not(:first-child) {
margin-top: var(--size-gap-double);
}
.errors-body > h5 {
margin-bottom: var(--size-gap);
}
`
import { Toast } from '../components/Toast'
import { AlertOctagon, AlertTriangle, CloseIcon } from '../icons'
import { noop as css } from '../helpers/noop-template'
export type ErrorsToastProps = {
errorCount: number
warningCount: number
severity: 'error' | 'warning'
onClick: () => void
onClose: () => void
}
export function ErrorsToast({
errorCount,
warningCount,
severity,
onClick,
onClose,
}: ErrorsToastProps) {
let message = ''
if (errorCount > 0) {
message += errorCount + ' ' + (errorCount > 1 ? 'Errors' : 'Error')
}
if (warningCount > 0) {
if (errorCount > 0) {
message += ' and '
}
message += warningCount + ' ' + (warningCount > 1 ? 'Warnings' : 'Warning')
}
return (
<Toast
className="toast-errors"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onClick()
}}
data-severity={severity}
>
<div className="toast-errors-body">
{severity == 'error' && <AlertOctagon />}
{severity == 'warning' && <AlertTriangle />}
<span>{message}</span>
<button
data-toast-errors-hide-button
className="toast-errors-hide-button"
type="button"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
onClose()
}}
aria-label={
{ error: 'Hide Errors', warning: 'Hide Warnings' }[severity]
}
>
<CloseIcon />
</button>
</div>
</Toast>
)
}
export const styles = css`
.toast-errors {
cursor: pointer;
transition: transform 0.2s ease;
will-change: transform;
}
.toast-errors:hover {
transform: scale(1.025);
}
.toast-errors-body {
display: flex;
align-items: center;
align-content: center;
justify-content: flex-start;
}
.toast-errors-body > svg {
margin-right: var(--size-gap);
}
.toast-errors-hide-button {
display: flex;
margin-left: var(--size-gap-triple);
border: none;
background: none;
color: var(--color-text-white);
padding: 0;
transition: transform, opacity 0.25s ease;
opacity: 0.7;
}
.toast-errors-hide-button:hover {
opacity: 1;
}
`
import * as React from 'react'
import { StackFrame } from '@vercel/turbopack-next/compiled/stacktrace-parser'
import { CodeFrame } from '../components/CodeFrame'
import { DialogBody, DialogBodyProps } from '../components/Dialog'
import { LeftRightDialogHeader } from '../components/LeftRightDialogHeader'
import { clsx } from '../helpers/clsx'
import { getErrorSource } from '../helpers/nodeStackFrames'
import { noop as css } from '../helpers/noop-template'
import { ReadyRuntimeError } from '../helpers/getErrorByType'
import { decodeMagicIdentifiers } from '../helpers/magic-identifier'
import { getFrameSource, OriginalStackFrame } from '../helpers/stack-frame'
import { usePagination } from '../hooks/usePagination'
import { ExternalLink } from '../icons'
function CallStackFrame({ frame }: { frame: OriginalStackFrame }) {
// TODO: ability to expand resolved frames
// TODO: render error or external indicator
const f: StackFrame = frame.originalStackFrame ?? frame.sourceStackFrame
const hasSource = Boolean(frame.originalCodeFrame)
const open = React.useCallback(() => {
if (!hasSource) return
const params = new URLSearchParams()
for (const key in f) {
params.append(key, ((f as any)[key] ?? '').toString())
}
self
.fetch(
`${
process.env.__NEXT_ROUTER_BASEPATH ?? ''
}/__nextjs_launch-editor?${params.toString()}`
)
.then(
() => {},
() => {
console.error('There was an issue opening this code in your editor.')
}
)
}, [hasSource, f])
return (
<li className="call-stack-frame" data-expanded={Boolean(frame.expanded)}>
<h6>{f.methodName}</h6>
<div
data-has-source={hasSource ? 'true' : undefined}
tabIndex={hasSource ? 10 : undefined}
role={hasSource ? 'link' : undefined}
onClick={open}
title={hasSource ? 'Click to open in your editor' : undefined}
>
<span>{getFrameSource(f)}</span>
<ExternalLink />
</div>
</li>
)
}
export type RuntimeErrorProps = { error: ReadyRuntimeError }
export function RuntimeError({ error }: RuntimeErrorProps) {
const firstFirstPartyFrameIndex = React.useMemo<number>(() => {
return error.frames.findIndex(
(entry) =>
entry.expanded &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
}, [error.frames])
const firstFrame = React.useMemo<OriginalStackFrame | null>(() => {
return error.frames[firstFirstPartyFrameIndex] ?? null
}, [error.frames, firstFirstPartyFrameIndex])
const allLeadingFrames = React.useMemo<OriginalStackFrame[]>(
() =>
firstFirstPartyFrameIndex < 0
? []
: error.frames.slice(0, firstFirstPartyFrameIndex),
[error.frames, firstFirstPartyFrameIndex]
)
const [all, setAll] = React.useState(firstFrame == null)
const toggleAll = React.useCallback(() => {
setAll((v) => !v)
}, [])
const leadingFrames = React.useMemo(
() => allLeadingFrames.filter((f) => f.expanded || all),
[all, allLeadingFrames]
)
const allCallStackFrames = React.useMemo<OriginalStackFrame[]>(
() => error.frames.slice(firstFirstPartyFrameIndex + 1),
[error.frames, firstFirstPartyFrameIndex]
)
const visibleCallStackFrames = React.useMemo<OriginalStackFrame[]>(
() => allCallStackFrames.filter((f) => f.expanded || all),
[all, allCallStackFrames]
)
const canShowMore = React.useMemo<boolean>(() => {
return (
allCallStackFrames.length !== visibleCallStackFrames.length ||
(all && firstFrame != null)
)
}, [
all,
allCallStackFrames.length,
firstFrame,
visibleCallStackFrames.length,
])
return (
<>
{firstFrame ? (
<>
<h5>Source</h5>
<ul className="call-stack-frames">
{leadingFrames.map((frame, index) => (
<CallStackFrame
key={`leading-frame-${index}-${all}`}
frame={frame}
/>
))}
</ul>
<CodeFrame
stackFrame={firstFrame.originalStackFrame!}
codeFrame={firstFrame.originalCodeFrame!}
/>
</>
) : undefined}
{visibleCallStackFrames.length ? (
<>
<h5>Call Stack</h5>
<ul className="call-stack-frames">
{visibleCallStackFrames.map((frame, index) => (
<CallStackFrame
key={`call-stack-${index}-${all}`}
frame={frame}
/>
))}
</ul>
</>
) : undefined}
{canShowMore ? (
<>
<button
tabIndex={10}
type="button"
onClick={toggleAll}
className="runtime-error-collapsed-action"
>
{all ? 'Hide' : 'Show'} collapsed frames
</button>
</>
) : undefined}
</>
)
}
function HotlinkedText(props: { text: string }) {
const { text } = props
const linkRegex = /https?:\/\/[^\s/$.?#].[^\s)'"]*/i
return (
<>
{linkRegex.test(text)
? text.split(' ').map((word, index, array) => {
if (linkRegex.test(word)) {
const link = linkRegex.exec(word)
return (
<React.Fragment key={`link-${index}`}>
{link && (
<a href={link[0]} target="_blank" rel="noreferrer noopener">
{word}
</a>
)}
{index === array.length - 1 ? '' : ' '}
</React.Fragment>
)
}
return index === array.length - 1 ? (
<React.Fragment key={`text-${index}`}>{word}</React.Fragment>
) : (
<React.Fragment key={`text-${index}`}>{word} </React.Fragment>
)
})
: text}
</>
)
}
type RuntimeErrorsDialogBodyProps = {
items: ReadyRuntimeError[]
message: string
'data-hidden'?: boolean
}
export function RuntimeErrorsDialogBody({
items: readyErrors,
message,
'data-hidden': hidden = false,
className,
...rest
}: RuntimeErrorsDialogBodyProps & Omit<DialogBodyProps, 'children'>) {
const [activeError, { previous, next }, activeIdx] =
usePagination(readyErrors)
if (readyErrors.length < 1 || activeError == null) {
return (
<DialogBody
{...rest}
data-hidden={hidden}
className={clsx('runtime-errors', className)}
/>
)
}
const isServerError = ['server', 'edge-server'].includes(
getErrorSource(activeError.error) || ''
)
return (
<DialogBody
{...rest}
data-hidden={hidden}
className={clsx('runtime-errors', className)}
>
<div className="title-pagination">
<h1 id="nextjs__container_errors_label">{message}</h1>
<LeftRightDialogHeader
hidden={hidden}
previous={activeIdx > 0 ? previous : null}
next={activeIdx < readyErrors.length - 1 ? next : null}
severity="error"
>
<small>
<span>{activeIdx + 1}</span> of <span>{readyErrors.length}</span>
</small>
</LeftRightDialogHeader>
</div>
<h2
data-nextjs-turbo-dialog-body
id="nextjs__container_errors_desc"
data-severity="error"
>
{activeError.error.name}:{' '}
<HotlinkedText
text={decodeMagicIdentifiers(activeError.error.message)}
/>
</h2>
{isServerError ? (
<div>
<small>
This error happened while generating the page. Any console logs will
be displayed in the terminal window.
</small>
</div>
) : undefined}
<RuntimeError key={activeError.id.toString()} error={activeError} />
</DialogBody>
)
}
export const styles = css`
button.runtime-error-collapsed-action {
background: none;
border: none;
padding: 0;
font-size: var(--size-font-small);
line-height: var(--size-font-bigger);
color: var(--color-text-dim);
}
.call-stack-frames {
list-style: none;
padding-left: calc(var(--size-gap) + var(--size-gap-half));
overflow-y: scroll;
}
.call-stack-frame:not(:last-child) {
margin-bottom: var(--size-gap-double);
}
.call-stack-frame > h6 {
margin-top: 0;
margin-bottom: 0;
font-family: var(--font-mono);
color: #666;
}
.call-stack-frame[data-expanded='true'] > h6 {
color: #222;
}
.call-stack-frame > div {
display: flex;
align-items: center;
padding-left: calc(var(--size-gap) + var(--size-gap-half));
font-size: var(--size-font-small);
color: #999;
}
.call-stack-frame > div > svg {
width: auto;
height: var(--size-font-small);
margin-left: var(--size-gap);
display: none;
}
.call-stack-frame > div[data-has-source] {
cursor: pointer;
}
.call-stack-frame > div[data-has-source]:hover {
text-decoration: underline dotted;
}
.call-stack-frame > div[data-has-source] > svg {
display: unset;
}
`
import { LeftRightDialogHeader } from '../components/LeftRightDialogHeader'
import { DialogBody, DialogBodyProps } from '../components/Dialog'
import { Terminal } from '../components/Terminal'
import { noop as css } from '../helpers/noop-template'
import { clsx } from '../helpers/clsx'
import { usePagination } from '../hooks/usePagination'
type TurbopackIssuesDialogBodyProps = {
items: Issue[]
message: string
severity: 'error' | 'warning'
'data-hidden'?: boolean
}
export function TurbopackIssuesDialogBody({
items: issues,
message,
severity,
'data-hidden': hidden = false,
className,
...rest
}: TurbopackIssuesDialogBodyProps & Omit<DialogBodyProps, 'children'>) {
const [activeIssue, { previous, next }, activeIdx] = usePagination(issues)
const hasIssues = issues.length > 0
if (!hasIssues || !activeIssue) {
return null
}
const activeIssueIsError = ['bug', 'fatal', 'error'].includes(
activeIssue.severity
)
return (
<DialogBody
{...rest}
data-hidden={hidden}
className={clsx('issues-body', className)}
>
<div className="title-pagination">
<h1 id="nextjs__container_errors_label">{message}</h1>
<LeftRightDialogHeader
hidden={hidden}
previous={activeIdx > 0 ? previous : null}
next={activeIdx < issues.length - 1 ? next : null}
severity={severity}
>
<small>
<span>{activeIdx + 1}</span> of <span>{issues.length}</span>
</small>
</LeftRightDialogHeader>
</div>
<h2
id="nextjs__container_errors_desc"
data-severity={activeIssueIsError ? 'error' : 'warning'}
>
{activeIssue.title}
</h2>
<Terminal content={activeIssue.formatted} />
{activeIssueIsError && (
<footer>
<p>
<small>
This error occurred during the build process and can only be
dismissed by fixing the error.
</small>
</p>
</footer>
)}
</DialogBody>
)
}
export const styles = css`
.issues-body > .terminal {
margin-top: var(--size-gap-double);
}
.issues-body > footer {
margin-top: var(--size-gap);
}
.issues-body > footer > p {
margin: 0;
}
.issues-body > footer > small {
color: #757575;
}
`
/*
MIT License
Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.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.
*/
// This file is based on https://github.com/lukeed/clsx/blob/v1.2.1/src/index.js
// It's been edited for the needs of this project
// See the LICENSE at the top of the file
export type TruthyClassValue =
| ClassArray
| ClassDictionary
| string
| number
| boolean
export type ClassValue = TruthyClassValue | null | undefined
export type ClassDictionary = Record<string, any>
export type ClassArray = ClassValue[]
function toVal(mix: TruthyClassValue) {
let k,
y,
str = ''
if (typeof mix === 'string' || typeof mix === 'number') {
str += mix
} else if (typeof mix === 'object') {
if (Array.isArray(mix)) {
for (k = 0; k < mix.length; k++) {
if (mix[k]) {
if ((y = toVal(mix[k]))) {
str && (str += ' ')
str += y
}
}
}
} else {
for (k in mix) {
if (mix[k]) {
str && (str += ' ')
str += k
}
}
}
}
return str
}
export function clsx(...inputs: ClassValue[]) {
let i = 0,
tmp,
x,
str = ''
while (i < inputs.length) {
if ((tmp = inputs[i++])) {
if ((x = toVal(tmp))) {
str && (str += ' ')
str += x
}
}
}
return str
}
import { TYPE_UNHANDLED_ERROR, TYPE_UNHANDLED_REJECTION } from '../bus'
import { SupportedErrorEvent } from '../container/Errors'
import { getErrorSource } from './nodeStackFrames'
import { getOriginalStackFrames, OriginalStackFrame } from './stack-frame'
export type ReadyRuntimeError = {
id: number
runtime: true
error: Error
frames: OriginalStackFrame[]
}
export async function getErrorByType(
ev: SupportedErrorEvent
): Promise<ReadyRuntimeError> {
const { id, event } = ev
switch (event.type) {
case TYPE_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: {
return {
id,
runtime: true,
error: event.reason,
frames: await getOriginalStackFrames(
event.frames,
getErrorSource(event.reason),
event.reason.toString()
),
}
}
default: {
break
}
}
throw new Error('type system invariant violation')
}
export function getUnresolvedErrorByType(
ev: SupportedErrorEvent
): ReadyRuntimeError {
const { id, event } = ev
switch (event.type) {
case TYPE_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: {
return {
id,
runtime: true,
error: event.reason,
frames: event.frames.map((frame) => ({
error: true,
reason: 'unresolved',
external: false,
expanded: false,
sourceStackFrame: frame,
originalStackFrame: null,
originalCodeFrame: null,
})),
}
}
default: {
break
}
}
throw new Error('type system invariant violation')
}
// see vercel/turbo crates/turbopack-ecmascript/src/magic_identifier.rs for the rust version
function decodeHex(hexStr: string): string {
if (hexStr.trim() === '') {
throw new Error("can't decode empty hex")
}
const num = parseInt(hexStr, 16)
if (isNaN(num)) {
throw new Error(`invalid hex: \`${hexStr}\``)
}
return String.fromCodePoint(num)
}
const enum Mode {
Text,
Underscore,
Hex,
LongHex,
}
const DECODE_REGEX = /^__TURBOPACK__([a-zA-Z0-9_$]+)__$/
function decodeMagicIdentifier(identifier: string): string {
const matches = identifier.match(DECODE_REGEX)
if (!matches) {
return identifier
}
const inner = matches[1]
let output = ''
let mode: Mode = Mode.Text
let buffer = ''
for (let i = 0; i < inner.length; i++) {
const char = inner[i]
if (mode === Mode.Text) {
if (char === '_') {
mode = Mode.Underscore
} else if (char === '$') {
mode = Mode.Hex
} else {
output += char
}
} else if (mode === Mode.Underscore) {
if (char === '_') {
output += ' '
mode = Mode.Text
} else if (char === '$') {
output += '_'
mode = Mode.Hex
} else {
output += '_'
output += char
mode = Mode.Text
}
} else if (mode === Mode.Hex) {
if (buffer.length === 2) {
output += decodeHex(buffer)
buffer = ''
}
if (char === '_') {
if (buffer !== '') {
throw new Error(`invalid hex: \`${buffer}\``)
}
mode = Mode.LongHex
} else if (char === '$') {
if (buffer !== '') {
throw new Error(`invalid hex: \`${buffer}\``)
}
mode = Mode.Text
} else {
buffer += char
}
} else if (mode === Mode.LongHex) {
if (char === '_') {
throw new Error(`invalid hex: \`${buffer + char}\``)
} else if (char === '$') {
output += decodeHex(buffer)
buffer = ''
mode = Mode.Text
} else {
buffer += char
}
}
}
return output
}
const IDENTIFIER_REGEX = /__TURBOPACK__[a-zA-Z0-9_$]+__/g
export function decodeMagicIdentifiers(str: string): string {
try {
return str.replaceAll(
IDENTIFIER_REGEX,
(ident) => `{${decodeMagicIdentifier(ident)}}`
)
} catch (e) {
console.error('decoding magic identifiers failed', e)
}
return str
}
import {
parse,
StackFrame,
} from '@vercel/turbopack-next/compiled/stacktrace-parser'
export function getFilesystemFrame(frame: StackFrame): StackFrame {
const f: StackFrame = { ...frame }
if (typeof f.file === 'string') {
if (
// Posix:
f.file.startsWith('/') ||
// Win32:
/^[a-z]:\\/i.test(f.file) ||
// Win32 UNC:
f.file.startsWith('\\\\')
) {
f.file = `file://${f.file}`
}
}
return f
}
const symbolError = Symbol('NextjsError')
export function getErrorSource(error: Error): 'server' | 'edge-server' | null {
return (error as any)[symbolError] || null
}
type ErrorType = 'edge-server' | 'server'
export function decorateServerError(error: Error, type: ErrorType) {
Object.defineProperty(error, symbolError, {
writable: false,
enumerable: false,
configurable: false,
value: type,
})
}
export function getServerError(error: Error, type: ErrorType): Error {
let n: Error
try {
throw new Error(error.message)
} catch (e) {
n = e as Error
}
n.name = error.name
try {
n.stack = `${n.toString()}\n${parse(error.stack!)
.map(getFilesystemFrame)
.map((f) => {
let str = ` at ${f.methodName}`
if (f.file) {
let loc = f.file
if (f.lineNumber) {
loc += `:${f.lineNumber}`
if (f.column) {
loc += `:${f.column}`
}
}
str += ` (${loc})`
}
return str
})
.join('\n')}`
} catch {
n.stack = error.stack
}
decorateServerError(n, type)
return n
}
export function noop(
strings: TemplateStringsArray,
...keys: readonly string[]
) {
const lastIndex = strings.length - 1
return (
strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +
strings[lastIndex]
)
}
import {
parse,
StackFrame,
} from '@vercel/turbopack-next/compiled/stacktrace-parser'
const regexNextStatic = /\/_next(\/static\/.+)/g
export function parseStack(stack: string): StackFrame[] {
const frames = parse(stack)
return frames.map((frame) => {
try {
const url = new URL(frame.file!)
const res = regexNextStatic.exec(url.pathname)
if (res) {
const distDir = process.env.__NEXT_DIST_DIR
?.replace(/\\/g, '/')
?.replace(/\/$/, '')
if (distDir) {
frame.file = 'file://' + distDir.concat(res.pop()!)
}
}
} catch {}
return frame
})
}
import { StackFrame } from '@vercel/turbopack-next/compiled/stacktrace-parser'
import { OriginalStackFrameResponse } from '../../middleware'
export type OriginalStackFrame =
| {
error: true
reason: string
external: false
expanded: false
sourceStackFrame: StackFrame
originalStackFrame: null
originalCodeFrame: null
}
| {
error: false
reason: null
external: false
expanded: boolean
sourceStackFrame: StackFrame
originalStackFrame: StackFrame
originalCodeFrame: string | null
}
| {
error: false
reason: null
external: true
expanded: false
sourceStackFrame: StackFrame
originalStackFrame: null
originalCodeFrame: null
}
export function getOriginalStackFrame(
source: StackFrame,
type: 'server' | 'edge-server' | null,
errorMessage: string
): Promise<OriginalStackFrame> {
async function _getOriginalStackFrame(): Promise<OriginalStackFrame> {
const params = new URLSearchParams()
params.append('isServer', String(type === 'server'))
params.append('isEdgeServer', String(type === 'edge-server'))
params.append('errorMessage', errorMessage)
for (const key in source) {
params.append(key, ((source as any)[key] ?? '').toString())
}
const controller = new AbortController()
const tm = setTimeout(() => controller.abort(), 3000)
const res = await self
.fetch(
`${
process.env.__NEXT_ROUTER_BASEPATH ?? ''
}/__nextjs_original-stack-frame?${params.toString()}`,
{
signal: controller.signal,
}
)
.finally(() => {
clearTimeout(tm)
})
if (!res.ok || res.status === 204) {
return Promise.reject(new Error(await res.text()))
}
const body: OriginalStackFrameResponse = await res.json()
return {
error: false,
reason: null,
external: false,
expanded: !(
/* collapsed */
(
source.file?.includes('node_modules') ??
body.originalStackFrame?.file?.includes('node_modules') ??
true
)
),
sourceStackFrame: source,
originalStackFrame: body.originalStackFrame,
originalCodeFrame: body.originalCodeFrame ?? null,
}
}
if (!source.file?.startsWith(location.origin)) {
return Promise.resolve({
error: false,
reason: null,
external: true,
expanded: false,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
})
}
return _getOriginalStackFrame().catch((err: Error) => ({
error: true,
reason: err?.message ?? err?.toString() ?? 'Unknown Error',
external: false,
expanded: false,
sourceStackFrame: source,
originalStackFrame: null,
originalCodeFrame: null,
}))
}
export function getOriginalStackFrames(
frames: StackFrame[],
type: 'server' | 'edge-server' | null,
errorMessage: string
) {
return Promise.all(
frames.map((frame) => getOriginalStackFrame(frame, type, errorMessage))
)
}
export function getFrameSource(frame: StackFrame): string {
let str = ''
try {
const u = new URL(frame.file!)
// Strip the origin for same-origin scripts.
if (
typeof globalThis !== 'undefined' &&
globalThis.location?.origin !== u.origin
) {
// URLs can be valid without an `origin`, so long as they have a
// `protocol`. However, `origin` is preferred.
if (u.origin === 'null') {
str += u.protocol
} else {
str += u.origin
}
}
// Strip query string information as it's typically too verbose to be
// meaningful.
str += u.pathname
str += ' '
} catch {
str += (frame.file ?? '(unknown)') + ' '
}
if (frame.lineNumber != null) {
if (frame.column != null) {
str += `(${frame.lineNumber}:${frame.column}) `
} else {
str += `(${frame.lineNumber}) `
}
}
return str.slice(0, -1)
}
/*
MIT License
Copyright (c) 2018-2022, React Training LLC
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.
*/
// This file is based on https://github.com/reach/reach-ui/blob/v0.18.0/packages/utils/src/context.tsx
// It's been edited for the needs of this project
// See the LICENSE at the top of the file
import * as React from 'react'
type ContextProvider<T> = React.FC<React.PropsWithChildren<T>>
export function createContext<ContextValueType extends object | null>(
rootComponentName: string,
defaultContext?: ContextValueType
): [
ContextProvider<ContextValueType>,
(callerComponentName: string) => ContextValueType
] {
const Ctx = React.createContext<ContextValueType | undefined>(defaultContext)
function Provider(props: React.PropsWithChildren<ContextValueType>) {
const { children, ...context } = props
const value = React.useMemo(
() => context,
// eslint-disable-next-line react-hooks/exhaustive-deps
Object.values(context)
) as ContextValueType
return <Ctx.Provider value={value}>{children}</Ctx.Provider>
}
function useContext(callerComponentName: string) {
const context = React.useContext(Ctx)
if (context) {
return context
}
if (defaultContext) {
return defaultContext
}
throw Error(
`${callerComponentName} must be rendered inside of a ${rootComponentName} component.`
)
}
Ctx.displayName = `${rootComponentName}Context`
Provider.displayName = `${rootComponentName}Provider`
return [Provider, useContext]
}
import * as React from 'react'
export function useOnClickOutside(
el: Node | null,
handler: ((e: MouseEvent | TouchEvent) => void) | undefined
) {
React.useEffect(() => {
if (el == null || handler == null) {
return
}
const listener = (e: MouseEvent | TouchEvent) => {
// Do nothing if clicking ref's element or descendent elements
if (!el || el.contains(e.target as Element)) {
return
}
handler(e)
}
const root = el.getRootNode()
root.addEventListener('mousedown', listener as EventListener)
root.addEventListener('touchstart', listener as EventListener)
return function () {
root.removeEventListener('mousedown', listener as EventListener)
root.removeEventListener('touchstart', listener as EventListener)
}
}, [handler, el])
}
import * as React from 'react'
export type PaginationActions = {
previous: (e?: React.KeyboardEvent | React.MouseEvent) => void
next: (e?: React.KeyboardEvent | React.MouseEvent) => void
setIdx: React.Dispatch<React.SetStateAction<number>>
}
export function usePagination<T>(
items: T[],
defaultIdx: number = 0
): [T | null, PaginationActions, number] {
const [idx, setIdx] = React.useState(defaultIdx)
React.useEffect(() => {
if (idx >= items.length && idx > 0) {
setIdx(items.length - 1)
}
}, [idx, items.length])
const currentItem = React.useMemo(() => {
return items[idx] ?? null
}, [items, idx])
const actions = React.useMemo(
() => ({
previous: (e?: React.KeyboardEvent | React.MouseEvent) => {
e?.preventDefault()
setIdx((idx) => Math.max(0, idx - 1))
},
next: (e?: React.KeyboardEvent | React.MouseEvent) => {
e?.preventDefault()
setIdx((idx) => Math.max(0, Math.min(items.length - 1, idx + 1)))
},
setIdx,
}),
[items.length]
)
return [currentItem, actions, idx]
}
import { BaseIcon, IconProps } from './BaseIcon'
export const AlertOctagon = (props: IconProps) => {
return (
<BaseIcon {...props}>
<polygon points="7.86 2 16.14 2 22 7.86 22 16.14 16.14 22 7.86 22 2 16.14 2 7.86 7.86 2"></polygon>
<line x1="12" y1="8" x2="12" y2="12"></line>
<line x1="12" y1="16" x2="12.01" y2="16"></line>
</BaseIcon>
)
}
import { BaseIcon, IconProps } from './BaseIcon'
export const AlertTriangle = (props: IconProps) => {
return (
<BaseIcon {...props}>
<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
<line x1="12" y1="9" x2="12" y2="13"></line>
<line x1="12" y1="17" x2="12.01" y2="17"></line>
</BaseIcon>
)
}
import { SVGProps, ReactNode } from 'react'
const defaultAttributes: Partial<SVGProps<SVGSVGElement>> = {
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
strokeWidth: 2,
strokeLinecap: 'round',
strokeLinejoin: 'round',
}
export interface IconProps extends Partial<SVGProps<SVGSVGElement>> {
size?: string | number
}
export const BaseIcon = ({
color = 'currentColor',
size = 24,
strokeWidth = 2,
...rest
}: IconProps & { children: ReactNode }) => {
return (
<svg
{...defaultAttributes}
width={size}
height={size}
stroke={color}
strokeWidth={strokeWidth}
{...rest}
/>
)
}
import { BaseIcon, IconProps } from './BaseIcon'
export const CloseIcon = (props: IconProps) => {
return (
<BaseIcon {...props}>
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</BaseIcon>
)
}
import { BaseIcon, IconProps } from './BaseIcon'
export const ExternalLink = (props: IconProps) => {
return (
<BaseIcon {...props}>
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15 3 21 3 21 9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</BaseIcon>
)
}
ISC License
Copyright (c) for portions of Lucide are held by Cole Bemis 2013-2022 as part of Feather (MIT). All other copyright (c) for Lucide are held by Lucide Contributors 2022.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import { BaseIcon, IconProps } from './BaseIcon'
export const PackageX = (props: IconProps) => {
return (
<BaseIcon {...props}>
<path d="M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14"></path>
<path d="M16.5 9.4 7.55 4.24"></path>
<polyline points="3.29 7 12 12 20.71 7"></polyline>
<line x1="12" y1="22" x2="12" y2="12"></line>
<path d="m17 13 5 5m-5 0 5-5"></path>
</BaseIcon>
)
}
export { AlertOctagon } from './AlertOctagon'
export { AlertTriangle } from './AlertTriangle'
export { CloseIcon } from './CloseIcon'
export { ExternalLink } from './ExternalLink'
export { IconProps } from './BaseIcon'
export { PackageX } from './PackageX'
import { noop as css } from '../helpers/noop-template'
export function Base() {
return (
<style>
{css`
:host {
--size-gap-half: 4px;
--size-gap: 8px;
--size-gap-big: 12px;
--size-gap-double: 16px;
--size-gap-triple: 24px;
--size-gap-quad: 32px;
--size-font-small: 14px;
--size-font: 16px;
--size-font-big: 20px;
--size-font-bigger: 24px;
--size-icon: 24px;
--size-icon-small: 12px;
--size-border-half: 1px;
--size-border: 2px;
--size-border-double: 4px;
--color-text: hsl(0, 0%, 0%);
--color-text-dim: hsl(0, 0%, 20%);
--color-text-white: hsl(0, 0%, 100%);
--color-error: hsl(-10, 100%, 45%);
--color-error-bright-hsl: -10, 100%, 67%;
--color-error-bright: hsl(var(--color-error-bright-hsl));
--color-warning: hsl(33.3, 100%, 47.5%);
--color-warning-bright-hsl: 33.3, 100%, 50%;
--color-warning-bright: hsl(var(--color-warning-bright-hsl));
--color-bg: hsl(0 0% 100%);
--color-bg-secondary: hsl(0 0% 93.5%);
--color-bg-secondary-hover: hsl(0 0% 90%);
--color-accents-1: hsl(0, 0%, 50%);
--color-accents-2: hsl(0, 0%, 13%);
--color-accents-3: hsl(0, 0%, 25%);
--color-border: hsla(0, 0%, 80%, 0.7);
--border-half: var(--size-border-half) solid var(--color-border);
--border: var(--size-border) solid var(--color-border);
--font-sans: ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
--font-serif: ui-serif, Georgia, Cambria, 'Times New Roman', Times,
serif;
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
'Liberation Mono', 'Courier New', monospace;
--color-ansi-selection: rgba(95, 126, 151, 0.48);
--color-ansi-bg: #111111;
--color-ansi-fg: #cccccc;
--color-ansi-white: #777777;
--color-ansi-black: #141414;
--color-ansi-blue: #00aaff;
--color-ansi-cyan: #88ddff;
--color-ansi-green: #98ec65;
--color-ansi-magenta: #aa88ff;
--color-ansi-red: #ff5555;
--color-ansi-yellow: #ffcc33;
--color-ansi-bright-white: #ffffff;
--color-ansi-bright-black: #777777;
--color-ansi-bright-blue: #33bbff;
--color-ansi-bright-cyan: #bbecff;
--color-ansi-bright-green: #b6f292;
--color-ansi-bright-magenta: #cebbff;
--color-ansi-bright-red: #ff8888;
--color-ansi-bright-yellow: #ffd966;
}
.mono {
font-family: var(--font-mono);
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-bottom: var(--size-gap);
font-weight: 500;
line-height: 1.5;
}
`}
</style>
)
}
import * as React from 'react'
import { styles as codeFrame } from '../components/CodeFrame'
import { styles as dialog } from '../components/Dialog'
import { styles as leftRightDialogHeader } from '../components/LeftRightDialogHeader'
import { styles as overlay } from '../components/Overlay'
import { styles as tabs } from '../components/Tabs'
import { styles as terminal } from '../components/Terminal'
import { styles as toast } from '../components/Toast'
import { styles as containerErrorStyles } from '../container/Errors'
import { styles as containerErrorToastStyles } from '../container/ErrorsToast'
import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError'
import { styles as containerTurbopackIssueStyles } from '../container/TurbopackIssue'
import { noop as css } from '../helpers/noop-template'
export function ComponentStyles() {
return (
<style>
{css`
${overlay}
${toast}
${dialog}
${leftRightDialogHeader}
${codeFrame}
${terminal}
${tabs}
${containerErrorStyles}
${containerErrorToastStyles}
${containerRuntimeErrorStyles}
${containerTurbopackIssueStyles}
`}
</style>
)
}
import { noop as css } from '../helpers/noop-template'
export function CssReset() {
return (
<style>
{css`
:host {
all: initial;
/* the direction property is not reset by 'all' */
direction: ltr;
}
/*!
* Bootstrap Reboot v4.4.1 (https://getbootstrap.com/)
* Copyright 2011-2019 The Bootstrap Authors
* Copyright 2011-2019 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
:host {
font-family: sans-serif;
line-height: 1.15;
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
article,
aside,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section {
display: block;
}
:host {
margin: 0;
font-family: var(--font-sans);
font-size: 16px;
font-weight: 400;
line-height: 1.5;
color: #212529;
text-align: left;
background-color: #fff;
}
[tabindex='-1']:focus:not(:focus-visible) {
outline: 0 !important;
}
hr {
box-sizing: content-box;
height: 0;
overflow: visible;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 0;
margin-bottom: 8px;
}
p {
margin-top: 0;
margin-bottom: 16px;
}
abbr[title],
abbr[data-original-title] {
text-decoration: underline;
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
border-bottom: 0;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 16px;
font-style: normal;
line-height: inherit;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 16px;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 8px;
margin-left: 0;
}
blockquote {
margin: 0 0 16px;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 80%;
}
sub,
sup {
position: relative;
font-size: 75%;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #007bff;
text-decoration: none;
background-color: transparent;
}
a:hover {
color: #0056b3;
text-decoration: underline;
}
a:not([href]) {
color: inherit;
text-decoration: none;
}
a:not([href]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas,
'Liberation Mono', 'Courier New', monospace;
font-size: 1em;
}
pre {
margin-top: 0;
margin-bottom: 16px;
overflow: auto;
}
figure {
margin: 0 0 16px;
}
img {
vertical-align: middle;
border-style: none;
}
svg {
overflow: hidden;
vertical-align: middle;
}
table {
border-collapse: collapse;
}
caption {
padding-top: 12px;
padding-bottom: 12px;
color: #6c757d;
text-align: left;
caption-side: bottom;
}
th {
text-align: inherit;
}
label {
display: inline-block;
margin-bottom: 8px;
}
button {
border-radius: 0;
}
button:focus {
outline: 1px dotted;
outline: 5px auto -webkit-focus-ring-color;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
input {
overflow: visible;
}
button,
select {
text-transform: none;
}
select {
word-wrap: normal;
}
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
}
button:not(:disabled),
[type='button']:not(:disabled),
[type='reset']:not(:disabled),
[type='submit']:not(:disabled) {
cursor: pointer;
}
button::-moz-focus-inner,
[type='button']::-moz-focus-inner,
[type='reset']::-moz-focus-inner,
[type='submit']::-moz-focus-inner {
padding: 0;
border-style: none;
}
input[type='radio'],
input[type='checkbox'] {
box-sizing: border-box;
padding: 0;
}
input[type='date'],
input[type='time'],
input[type='datetime-local'],
input[type='month'] {
-webkit-appearance: listbox;
}
textarea {
overflow: auto;
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
display: block;
width: 100%;
max-width: 100%;
padding: 0;
margin-bottom: 8px;
font-size: 24px;
line-height: inherit;
color: inherit;
white-space: normal;
}
progress {
vertical-align: baseline;
}
[type='number']::-webkit-inner-spin-button,
[type='number']::-webkit-outer-spin-button {
height: auto;
}
[type='search'] {
outline-offset: -2px;
-webkit-appearance: none;
}
[type='search']::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
summary {
display: list-item;
cursor: pointer;
}
template {
display: none;
}
[hidden] {
display: none !important;
}
`}
</style>
)
}
import { StackFrame } from '@vercel/turbopack-next/compiled/stacktrace-parser'
export type OriginalStackFrameResponse = {
originalStackFrame: StackFrame
originalCodeFrame: string | null
}
import 'next/dist/server/node-polyfill-fetch'
import 'next/dist/server/node-polyfill-web-streams'
import 'next/dist/server/node-polyfill-headers'
import 'next/dist/server/node-polyfill-crypto'
import './async-local-storage'
// Next.js now creates an AsyncLocalStorage in the module scope, meaning we
// need to:
// 1. Install it (it's accessed as `globalthis.AsyncLocalStorage`)
// 2. Do it in an import (import ordering is guaranteed)
import { AsyncLocalStorage } from 'node:async_hooks'
globalThis.AsyncLocalStorage = AsyncLocalStorage
{
"$schema": "https://turborepo.org/schema.json",
"extends": ["//"],
"pipeline": {
"build": {
"outputs": ["src/compiled/**"]
}
}
}
declare module 'next/dist/compiled/react-server-dom-webpack/client'
/* GENERATED FILE, DO NOT EDIT */
declare module '@vercel/turbopack-next/compiled/anser' {
import m from 'anser'
export = m
}
declare module '@vercel/turbopack-next/compiled/css.escape' {
export = CSS.escape
}
declare module '@vercel/turbopack-next/compiled/platform' {
import m from 'platform'
export = m
}
declare module '@vercel/turbopack-next/compiled/source-map' {
export * from 'source-map'
}
declare module '@vercel/turbopack-next/compiled/stacktrace-parser' {
export * from 'stacktrace-parser'
}
declare module '@vercel/turbopack-next/compiled/strip-ansi' {
import m from 'strip-ansi'
export default m
}
import type { Router } from 'next/dist/client/router'
import type { MittEmitter } from 'next/dist/shared/lib/mitt'
declare global {
function __turbopack_require__(name: any): any
function __turbopack_load__(path: ChunkData): any
function __webpack_require__(name: any): any
var __webpack_public_path__: string | undefined
var __DEV_MIDDLEWARE_MATCHERS: any[]
var __next_require__: (id: string) => any
var __next_chunk_load__: (id: string) => Promise
var __next_f: (
| [isBootStrap: 0]
| [isNotBootstrap: 1, responsePartial: string]
)[]
var next: {
version: string
appDir?: boolean
router?: Router
emitter?: MittEmitter<string>
}
function __turbopack_load_page_chunks__(
page: string,
paths: string[]
): unknown
var AsyncLocalStorage = class AsyncLocalStorage<T> {
getStore(): T | undefined
run<R, TArgs extends any[]>(
store: T,
callback: (...args: TArgs) => R,
...args: TArgs
): R
}
// This is a hack to allow us to use Turbopack's `module.hot` API in
// TypeScript modules.
interface NodeModule {
hot: Hot
}
}
export {}
declare module 'next/dist/client/components/static-generation-async-storage.js'
declare module 'next/dist/client/components/request-async-storage.js'
declare module 'next/dist/client/components/hooks-server-context.js'
declare module 'next/dist/compiled/react-server-dom-webpack/server.edge'
// modules provided by rust
declare module 'PAGE' {
import {
NextPage,
GetStaticPaths,
GetServerSideProps,
GetStaticProps,
} from 'next'
const Component: NextPage
export default Component
export const getStaticProps: GetStaticProps | undefined
export const getStaticPaths: GetStaticPaths | undefined
export const getServerSideProps: GetServerSideProps | undefined
}
declare module 'INNER' {
export * from 'PAGE'
}
declare module 'CHUNK_GROUP' {
const chunkGroup: import('types/next').ChunkGroup
export default chunkGroup
}
declare module 'MIDDLEWARE_CHUNK_GROUP' {
export { default } from 'CHUNK_GROUP'
}
declare module 'INNER_CLIENT_CHUNK_GROUP' {
export { default } from 'CHUNK_GROUP'
}
declare module 'INNER_EDGE_CHUNK_GROUP' {
export { default } from 'CHUNK_GROUP'
}
declare module 'ROUTE_CHUNK_GROUP' {
export { default } from 'CHUNK_GROUP'
}
declare module 'MIDDLEWARE_CONFIG' {
const matcher: string[]
export default {
matcher,
}
}
declare module 'ENTRY' {
// TODO: (wyattjoh) support other types of userland modules
import type { AppRouteUserlandModule } from 'next/dist/server/future/route-modules/app-route/module'
const module: AppRouteUserlandModule
export = module
}
declare module 'BOOTSTRAP_CONFIG' {
export const NAME: string
export const PAGE: string
export const PATHNAME: string
}
declare module 'APP_BOOTSTRAP' {
const chunks: Array<string>
export default chunks
}
declare module 'APP_ENTRY' {
export const tree: any
export const pathname: string
// and more...
}
import type { ServerInfo } from '@vercel/turbopack-next/internal/server'
import type { RenderOptsPartial } from 'next/dist/server/render'
export type RenderData = {
params: Record<string, string | string[]>
method: string
url: string
originalUrl: string
path: string
rawQuery: string
rawHeaders: Array<[string, string]>
data?: {
nextConfigOutput?: RenderOptsPartial['nextConfigOutput']
serverInfo?: ServerInfo
allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string
isrMemoryCacheSize?: number
}
}
use std::collections::HashMap;
use anyhow::{bail, Result};
use turbo_tasks::{Value, Vc};
use turbopack_binding::{
turbo::{tasks_env::ProcessEnv, tasks_fs::FileSystemPath},
turbopack::{
core::{
compile_time_info::CompileTimeInfo,
context::AssetContext,
resolve::{options::ImportMap, origin::PlainResolveOrigin},
},
dev_server::html::DevHtmlAsset,
node::execution_context::ExecutionContext,
turbopack::{ecmascript::EcmascriptModuleAsset, ModuleAssetContext},
},
};
use crate::{
mode::NextMode,
next_client::context::{
get_client_chunking_context, get_client_module_options_context,
get_client_resolve_options_context, get_client_runtime_entries, ClientContextType,
},
next_config::NextConfig,
next_import_map::insert_next_shared_aliases,
runtime::resolve_runtime_request,
};
#[turbo_tasks::function]
pub async fn get_fallback_page(
project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>,
dev_server_root: Vc<FileSystemPath>,
env: Vc<Box<dyn ProcessEnv>>,
client_compile_time_info: Vc<CompileTimeInfo>,
next_config: Vc<NextConfig>,
) -> Result<Vc<DevHtmlAsset>> {
let ty = Value::new(ClientContextType::Fallback);
let mode = NextMode::DevServer;
let resolve_options_context =
get_client_resolve_options_context(project_path, ty, mode, next_config, execution_context);
let module_options_context = get_client_module_options_context(
project_path,
execution_context,
client_compile_time_info.environment(),
ty,
mode,
next_config,
);
let chunking_context = get_client_chunking_context(
project_path,
dev_server_root,
client_compile_time_info.environment(),
mode,
);
let entries =
get_client_runtime_entries(project_path, env, ty, mode, next_config, execution_context);
let mut import_map = ImportMap::empty();
insert_next_shared_aliases(
&mut import_map,
project_path,
execution_context,
next_config,
NextMode::DevServer,
)
.await?;
let context: Vc<Box<dyn AssetContext>> = Vc::upcast(ModuleAssetContext::new(
Vc::cell(HashMap::new()),
client_compile_time_info,
module_options_context,
resolve_options_context.with_extended_import_map(import_map.cell()),
));
let runtime_entries = entries.resolve_entries(context);
let fallback_chunk = resolve_runtime_request(
Vc::upcast(PlainResolveOrigin::new(context, project_path)),
"entry/fallback".to_string(),
);
let module = if let Some(module) =
Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(fallback_chunk).await?
{
module
} else {
bail!("fallback runtime entry is not an ecmascript module");
};
Ok(DevHtmlAsset::new(
dev_server_root.join("fallback.html".to_string()),
vec![(
Vc::upcast(module),
Vc::upcast(chunking_context),
Some(runtime_entries.with_entry(Vc::upcast(module))),
)],
))
}
...@@ -14,7 +14,6 @@ mod bootstrap; ...@@ -14,7 +14,6 @@ mod bootstrap;
mod embed_js; mod embed_js;
mod emit; mod emit;
mod env; mod env;
mod fallback;
mod loader_tree; mod loader_tree;
pub mod middleware; pub mod middleware;
pub mod mode; pub mod mode;
...@@ -38,7 +37,6 @@ mod next_shared; ...@@ -38,7 +37,6 @@ mod next_shared;
pub mod next_telemetry; pub mod next_telemetry;
mod page_loader; mod page_loader;
pub mod pages_structure; pub mod pages_structure;
mod runtime;
mod sass; mod sass;
pub mod tracing_presets; pub mod tracing_presets;
mod transform_options; mod transform_options;
......
use anyhow::{bail, Result};
use turbo_tasks::Vc;
use turbopack_binding::turbopack::{
core::{
issue::{IssueSeverity, OptionIssueSource},
resolve::{origin::ResolveOrigin, parse::Request},
},
turbopack::ecmascript::{chunk::EcmascriptChunkPlaceable, resolve::cjs_resolve},
};
/// Resolves the turbopack runtime module from the given [Vc<Box<dyn
/// AssetContext>>].
#[turbo_tasks::function]
pub async fn resolve_runtime_request(
origin: Vc<Box<dyn ResolveOrigin>>,
path: String,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
let runtime_request_path = format!("@vercel/turbopack-next/{}", path);
let request = Request::parse_string(runtime_request_path.clone());
if let Some(asset) = *cjs_resolve(
origin,
request,
OptionIssueSource::none(),
IssueSeverity::Error.cell(),
)
.first_module()
.await?
{
if let Some(placeable) =
Vc::try_resolve_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(asset).await?
{
Ok(placeable)
} else {
bail!("turbopack runtime asset is not placeable")
}
} else {
// The @vercel/turbopack-dev module is not installed.
bail!("could not resolve the `{}` module", runtime_request_path)
}
}
...@@ -1524,60 +1524,7 @@ importers: ...@@ -1524,60 +1524,7 @@ importers:
specifier: 6.0.3 specifier: 6.0.3
version: 6.0.3 version: 6.0.3
packages/next-swc/crates/next-core/js: packages/next-swc/crates/next-core/js: {}
dependencies:
'@vercel/turbopack-ecmascript-runtime':
specifier: https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-230922.2
version: '@gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-ecmascript-runtime/js?turbopack-230922.2(react-refresh@0.12.0)(webpack@5.86.0)'
'@vercel/turbopack-node':
specifier: https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230922.2
version: '@gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230922.2'
anser:
specifier: ^2.1.1
version: 2.1.1
css.escape:
specifier: ^1.5.1
version: 1.5.1
next:
specifier: '*'
version: link:../../../../next
platform:
specifier: 1.3.6
version: 1.3.6
react:
specifier: ^18.2.0
version: 18.2.0
react-dom:
specifier: ^18.2.0
version: 18.2.0(react@18.2.0)
source-map:
specifier: 0.8.0-beta.0
version: 0.8.0-beta.0
stacktrace-parser:
specifier: ^0.1.10
version: 0.1.10
strip-ansi:
specifier: ^7.0.1
version: 7.0.1
devDependencies:
'@types/node':
specifier: 20.2.5
version: 20.2.5
'@types/platform':
specifier: ^1.3.4
version: 1.3.4
'@types/react':
specifier: 18.2.7
version: 18.2.7
'@types/react-dom':
specifier: 18.2.4
version: 18.2.4
'@vercel/ncc':
specifier: ^0.36.0
version: 0.36.1
find-up:
specifier: ^6.3.0
version: 6.3.0
packages/react-dev-overlay: packages/react-dev-overlay:
dependencies: dependencies:
...@@ -6784,6 +6731,7 @@ packages: ...@@ -6784,6 +6731,7 @@ packages:
dependencies: dependencies:
react-refresh: 0.12.0 react-refresh: 0.12.0
webpack: 5.86.0(@swc/core@1.3.85) webpack: 5.86.0(@swc/core@1.3.85)
dev: true
/@nicolo-ribaudo/chokidar-2@2.1.8-no-fsevents.3: /@nicolo-ribaudo/chokidar-2@2.1.8-no-fsevents.3:
resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==} resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==}
...@@ -8789,11 +8737,6 @@ packages: ...@@ -8789,11 +8737,6 @@ packages:
hasBin: true hasBin: true
dev: true dev: true
/@vercel/ncc@0.36.1:
resolution: {integrity: sha512-S4cL7Taa9yb5qbv+6wLgiKVZ03Qfkc4jGRuiUQMQ8HGBD5pcNRnHeYM33zBvJE4/zJGjJJ8GScB+WmTsn9mORw==}
hasBin: true
dev: true
/@vercel/nft@0.22.6: /@vercel/nft@0.22.6:
resolution: {integrity: sha512-gTsFnnT4mGxodr4AUlW3/urY+8JKKB452LwF3m477RFUJTAaDmcz2JqFuInzvdybYIeyIv1sSONEJxsxnbQ5JQ==} resolution: {integrity: sha512-gTsFnnT4mGxodr4AUlW3/urY+8JKKB452LwF3m477RFUJTAaDmcz2JqFuInzvdybYIeyIv1sSONEJxsxnbQ5JQ==}
engines: {node: '>=14'} engines: {node: '>=14'}
...@@ -9199,10 +9142,6 @@ packages: ...@@ -9199,10 +9142,6 @@ packages:
/anser@1.4.9: /anser@1.4.9:
resolution: {integrity: sha512-AI+BjTeGt2+WFk4eWcqbQ7snZpDBt8SaLlj0RT2h5xfdWaiy51OjYvqwMrNzJLGy8iOAL6nKDITWO+rd4MkYEA==} resolution: {integrity: sha512-AI+BjTeGt2+WFk4eWcqbQ7snZpDBt8SaLlj0RT2h5xfdWaiy51OjYvqwMrNzJLGy8iOAL6nKDITWO+rd4MkYEA==}
/anser@2.1.1:
resolution: {integrity: sha512-nqLm4HxOTpeLOxcmB3QWmV5TcDFhW9y/fyQ+hivtDFcK4OQ+pQ5fzPnXHM1Mfcm0VkLtvVi1TCPr++Qy0Q/3EQ==}
dev: false
/ansi-align@3.0.0: /ansi-align@3.0.0:
resolution: {integrity: sha512-ZpClVKqXN3RGBmKibdfWzqCY4lnjEuoNzU5T0oEFpfd/z5qJHVarukridD4juLO2FXMiwUQxr9WqQtaYa8XRYw==} resolution: {integrity: sha512-ZpClVKqXN3RGBmKibdfWzqCY4lnjEuoNzU5T0oEFpfd/z5qJHVarukridD4juLO2FXMiwUQxr9WqQtaYa8XRYw==}
dependencies: dependencies:
...@@ -9253,6 +9192,7 @@ packages: ...@@ -9253,6 +9192,7 @@ packages:
/ansi-regex@6.0.1: /ansi-regex@6.0.1:
resolution: {integrity: sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==} resolution: {integrity: sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA==}
engines: {node: '>=12'} engines: {node: '>=12'}
dev: true
/ansi-styles@2.2.1: /ansi-styles@2.2.1:
resolution: {integrity: sha512-kmCevFghRiWM7HB5zTPULl4r9bVFSWjz62MhqizDGUrq2NWuNMQyuv4tHHoKJHs69M/MF64lEcHdYIocrdWQYA==} resolution: {integrity: sha512-kmCevFghRiWM7HB5zTPULl4r9bVFSWjz62MhqizDGUrq2NWuNMQyuv4tHHoKJHs69M/MF64lEcHdYIocrdWQYA==}
...@@ -14046,14 +13986,6 @@ packages: ...@@ -14046,14 +13986,6 @@ packages:
path-exists: 4.0.0 path-exists: 4.0.0
dev: false dev: false
/find-up@6.3.0:
resolution: {integrity: sha512-v2ZsoEuVHYy8ZIlYqwPe/39Cy+cFDzp4dXPaxNvkEuouymu+2Jbz0PxpKarJHYJTmv2HWT3O382qY8l4jMWthw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
locate-path: 7.2.0
path-exists: 5.0.0
dev: true
/findup-sync@5.0.0: /findup-sync@5.0.0:
resolution: {integrity: sha512-MzwXju70AuyflbgeOhzvQWAvvQdo1XL0A9bVvlXsYcFEBM87WR4OakL4OfZq+QRmr+duJubio+UtNQCPsVESzQ==} resolution: {integrity: sha512-MzwXju70AuyflbgeOhzvQWAvvQdo1XL0A9bVvlXsYcFEBM87WR4OakL4OfZq+QRmr+duJubio+UtNQCPsVESzQ==}
engines: {node: '>= 10.13.0'} engines: {node: '>= 10.13.0'}
...@@ -17974,13 +17906,6 @@ packages: ...@@ -17974,13 +17906,6 @@ packages:
p-locate: 5.0.0 p-locate: 5.0.0
dev: false dev: false
/locate-path@7.2.0:
resolution: {integrity: sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
p-locate: 6.0.0
dev: true
/lodash._reinterpolate@3.0.0: /lodash._reinterpolate@3.0.0:
resolution: {integrity: sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=} resolution: {integrity: sha1-DM8tiRZq8Ds2Y8eWU4t1rG4RTZ0=}
dev: true dev: true
...@@ -20220,13 +20145,6 @@ packages: ...@@ -20220,13 +20145,6 @@ packages:
dependencies: dependencies:
yocto-queue: 0.1.0 yocto-queue: 0.1.0
/p-limit@4.0.0:
resolution: {integrity: sha512-5b0R4txpzjPWVw/cXXUResoD4hb6U/x9BH08L7nw+GN1sezDzPdxeRvpc9c433fZhBan/wusjbCsqwqm4EIBIQ==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
yocto-queue: 1.0.0
dev: true
/p-locate@2.0.0: /p-locate@2.0.0:
resolution: {integrity: sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==} resolution: {integrity: sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==}
engines: {node: '>=4'} engines: {node: '>=4'}
...@@ -20253,13 +20171,6 @@ packages: ...@@ -20253,13 +20171,6 @@ packages:
p-limit: 3.1.0 p-limit: 3.1.0
dev: false dev: false
/p-locate@6.0.0:
resolution: {integrity: sha512-wPrq66Llhl7/4AGC6I+cqxT07LhXvWL08LNXz1fENOw0Ap4sRZZ/gZpTTJ5jpurzzzfS2W/Ge9BY3LgLjCShcw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dependencies:
p-limit: 4.0.0
dev: true
/p-map-series@2.1.0: /p-map-series@2.1.0:
resolution: {integrity: sha512-RpYIIK1zXSNEOdwxcfe7FdvGcs7+y5n8rifMhMNWvaxRNMPINJHF5GDeuVxWqnfrcHPSCnp7Oo5yNXHId9Av2Q==} resolution: {integrity: sha512-RpYIIK1zXSNEOdwxcfe7FdvGcs7+y5n8rifMhMNWvaxRNMPINJHF5GDeuVxWqnfrcHPSCnp7Oo5yNXHId9Av2Q==}
engines: {node: '>=8'} engines: {node: '>=8'}
...@@ -20593,11 +20504,6 @@ packages: ...@@ -20593,11 +20504,6 @@ packages:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'} engines: {node: '>=8'}
/path-exists@5.0.0:
resolution: {integrity: sha512-RjhtfwJOxzcFmNOi6ltcbcu4Iu+FL3zEj83dk4kAS+fVpTxXLO1b38RvJgT/0QwvV/L3aY9TAnyv0EOqW4GoMQ==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dev: true
/path-is-absolute@1.0.1: /path-is-absolute@1.0.1:
resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
...@@ -22596,6 +22502,7 @@ packages: ...@@ -22596,6 +22502,7 @@ packages:
/react-refresh@0.12.0: /react-refresh@0.12.0:
resolution: {integrity: sha512-suLIhrU2IHKL5JEKR/fAwJv7bbeq4kJ+pJopf77jHwuR+HmJS/HbrPIGsTBUVfw7tXPOmYv7UJ7PCaN49e8x4A==} resolution: {integrity: sha512-suLIhrU2IHKL5JEKR/fAwJv7bbeq4kJ+pJopf77jHwuR+HmJS/HbrPIGsTBUVfw7tXPOmYv7UJ7PCaN49e8x4A==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
dev: true
/react-server-dom-webpack@0.0.0-experimental-09285d5a7-20230925(react-dom@18.2.0)(react@18.2.0)(webpack@5.86.0): /react-server-dom-webpack@0.0.0-experimental-09285d5a7-20230925(react-dom@18.2.0)(react@18.2.0)(webpack@5.86.0):
resolution: {integrity: sha512-LWI4TnUIT3wjDrtnruqe0f1aBLPf8arrBXCd3G/sZjdtX+WSJbBA0dYBOYH9YZrgeJKuKn/6kUYeoTR/BvcHbw==} resolution: {integrity: sha512-LWI4TnUIT3wjDrtnruqe0f1aBLPf8arrBXCd3G/sZjdtX+WSJbBA0dYBOYH9YZrgeJKuKn/6kUYeoTR/BvcHbw==}
...@@ -24671,6 +24578,7 @@ packages: ...@@ -24671,6 +24578,7 @@ packages:
engines: {node: '>=12'} engines: {node: '>=12'}
dependencies: dependencies:
ansi-regex: 6.0.1 ansi-regex: 6.0.1
dev: true
/strip-bom@2.0.0: /strip-bom@2.0.0:
resolution: {integrity: sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==} resolution: {integrity: sha512-kwrX1y7czp1E69n2ajbG65mIo9dqvJ+8aBQXOGVxqwvNbsXdFM6Lq37dLAY3mknUwru8CfcCbfOLL/gMo+fi3g==}
...@@ -26947,11 +26855,6 @@ packages: ...@@ -26947,11 +26855,6 @@ packages:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'} engines: {node: '>=10'}
/yocto-queue@1.0.0:
resolution: {integrity: sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==}
engines: {node: '>=12.20'}
dev: true
/yoga-wasm-web@0.3.3: /yoga-wasm-web@0.3.3:
resolution: {integrity: sha512-N+d4UJSJbt/R3wqY7Coqs5pcV0aUj2j9IaQ3rNj9bVCLld8tTGKRa2USARjnvZJWVx1NDmQev8EknoczaOQDOA==} resolution: {integrity: sha512-N+d4UJSJbt/R3wqY7Coqs5pcV0aUj2j9IaQ3rNj9bVCLld8tTGKRa2USARjnvZJWVx1NDmQev8EknoczaOQDOA==}
dev: true dev: true
...@@ -26978,14 +26881,7 @@ packages: ...@@ -26978,14 +26881,7 @@ packages:
transitivePeerDependencies: transitivePeerDependencies:
- react-refresh - react-refresh
- webpack - webpack
dev: true
'@gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230922.2':
resolution: {tarball: https://gitpkg-fork.vercel.sh/vercel/turbo/crates/turbopack-node/js?turbopack-230922.2}
name: '@vercel/turbopack-node'
version: 0.0.0
dependencies:
loader-runner: 4.3.0
dev: false
github.com/watson/ci-info/f43f6a1cefff47fb361c88cf4b943fdbcaafe540: github.com/watson/ci-info/f43f6a1cefff47fb361c88cf4b943fdbcaafe540:
resolution: {tarball: https://codeload.github.com/watson/ci-info/tar.gz/f43f6a1cefff47fb361c88cf4b943fdbcaafe540} resolution: {tarball: https://codeload.github.com/watson/ci-info/tar.gz/f43f6a1cefff47fb361c88cf4b943fdbcaafe540}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment