initial commit

This commit is contained in:
Zoe
2023-01-03 09:29:04 -06:00
commit 7851137d88
12889 changed files with 2557443 additions and 0 deletions

7
node_modules/@nuxt/devalue/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,7 @@
Copyright (c) 2018-19 [these people](https://github.com/nuxt-contrib/devalue/graphs/contributors)
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.

146
node_modules/@nuxt/devalue/README.md generated vendored Normal file
View File

@@ -0,0 +1,146 @@
# @nuxt/devalue
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![codecov][codecov-src]][codecov-href]
[![package phobia][package-phobia-src]][package-phobia-href]
[![bundle phobia][bundle-phobia-src]][bundle-phobia-href]
> Forked from [devalue](https://github.com/Rich-Harris/devalue) to log errors on non-serializable properties rather than throwing `Error`.
Like `JSON.stringify`, but handles
* cyclical references (`obj.self = obj`)
* repeated references (`[value, value]`)
* `undefined`, `Infinity`, `NaN`, `-0`
* regular expressions
* dates
* `Map` and `Set`
* `.toJSON()` method for non-POJOs
Try it out on [runkit.com](https://npm.runkit.com/@nuxt/devalue).
## Goals:
* Performance
* Security (see [XSS mitigation](#xss-mitigation))
* Compact output
## Non-goals:
* Human-readable output
* Stringifying functions or arbritary non-POJOs
## Usage
```js
import devalue from '@nuxt/devalue';
let obj = { a: 1, b: 2 };
obj.c = 3;
devalue(obj); // '{a:1,b:2,c:3}'
obj.self = obj;
devalue(obj); // '(function(a){a.a=1;a.b=2;a.c=3;a.self=a;return a}({}))'
```
If `devalue` encounters a function or a non-POJO, it will throw an error.
## XSS mitigation
Say you're server-rendering a page and want to serialize some state, which could include user input. `JSON.stringify` doesn't protect against XSS attacks:
```js
const state = {
userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};
const template = `
<script>
// NEVER DO THIS
var preloaded = ${JSON.stringify(state)};
</script>`;
```
Which would result in this:
```html
<script>
// NEVER DO THIS
var preloaded = {"userinput":"</script><script src='https://evil.com/mwahaha.js'>"};
</script>
```
Using `devalue`, we're protected against that attack:
```js
const template = `
<script>
var preloaded = ${devalue(state)};
</script>`;
```
```html
<script>
var preloaded = {userinput:"\\u003C\\u002Fscript\\u003E\\u003Cscript src=\'https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js\'\\u003E"};
</script>
```
This, along with the fact that `devalue` bails on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by `devalue` can be safely deserialized with `eval` or `new Function`:
```js
const value = (0,eval)('(' + str + ')');
```
## Other security considerations
While `devalue` prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, **you should not send user data from client to server** using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed `devalue` would have access to your system.
When using `eval`, ensure that you call it *indirectly* so that the evaluated code doesn't have access to the surrounding scope:
```js
{
const sensitiveData = 'Setec Astronomy';
eval('sendToEvilServer(sensitiveData)'); // pwned :(
(0,eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}
```
Using `new Function(code)` is akin to using indirect eval.
## See also
* [lave](https://github.com/jed/lave) by Jed Schmidt
* [arson](https://github.com/benjamn/arson) by Ben Newman
* [tosource](https://github.com/marcello3d/node-tosource) by Marcello Bastéa-Forte
* [serialize-javascript](https://github.com/yahoo/serialize-javascript) by Eric Ferraiuolo
## License
[MIT](LICENSE)
<!-- Refs -->
[npm-version-src]: https://flat.badgen.net/npm/v/@nuxt/devalue/latest
[npm-version-href]: https://www.npmjs.com/package/@nuxt/devalue
[npm-downloads-src]: https://flat.badgen.net/npm/dm/@nuxt/devalue
[npm-downloads-href]: https://www.npmjs.com/package/@nuxt/devalue
[circleci-src]: https://flat.badgen.net/circleci/github/nuxt-contrib/devalue
[circleci-href]: https://circleci.com/gh/nuxt-contrib/devalue
[package-phobia-src]: https://flat.badgen.net/packagephobia/install/@nuxt/devalue
[package-phobia-href]: https://packagephobia.now.sh/result?p=@nuxt/devalue
[bundle-phobia-src]: https://flat.badgen.net/bundlephobia/minzip/@nuxt/devalue
[bundle-phobia-href]: https://bundlephobia.com/result?p=@nuxt/devalue
[codecov-src]: https://flat.badgen.net/codecov/c/github/nuxt-contrib/devalue/master
[codecov-href]: https://codecov.io/gh/nuxt-contrib/devalue

236
node_modules/@nuxt/devalue/dist/devalue.js generated vendored Normal file
View File

@@ -0,0 +1,236 @@
'use strict';
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
module.exports = devalue;

234
node_modules/@nuxt/devalue/dist/devalue.mjs generated vendored Normal file
View File

@@ -0,0 +1,234 @@
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
export default devalue;

3
node_modules/@nuxt/devalue/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
declare function devalue(value: any): string;
export default devalue;

38
node_modules/@nuxt/devalue/package.json generated vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "@nuxt/devalue",
"version": "2.0.0",
"description": "Gets the job done when JSON.stringify can't",
"repository": "nuxt-contrib/devalue",
"license": "MIT",
"exports": {
".": {
"require": "./dist/devalue.js",
"import": "./dist/devalue.mjs"
}
},
"main": "./dist/devalue.js",
"module": "./dist/devalue.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "siroc build",
"prepack": "yarn build",
"lint": "eslint --ext .ts,.js .",
"test": "yarn lint && jest",
"release": "yarn test && standard-version && git push --follow-tags && npm publish"
},
"devDependencies": {
"@nuxtjs/eslint-config-typescript": "^6.0.0",
"@types/jest": "^26.0.23",
"@types/mocha": "^8.2.2",
"@types/node": "^15.3.0",
"eslint": "^7.26.0",
"jest": "^26.6.3",
"siroc": "^0.10.0",
"standard-version": "^9.3.0",
"ts-jest": "^26.5.6",
"typescript": "^4.2.4"
}
}

21
node_modules/@nuxt/kit/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 - Nuxt Project
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.

5
node_modules/@nuxt/kit/README.md generated vendored Normal file
View File

@@ -0,0 +1,5 @@
# Nuxt Kit
> Toolkit for authoring Nuxt Modules
Learn more about this package: <https://v3.nuxtjs.org>

333
node_modules/@nuxt/kit/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,333 @@
import { ModuleOptions, ModuleDefinition, NuxtModule, Nuxt, NuxtConfig, NuxtOptions, ImportPresetWithDeprecation, NuxtCompatibility, NuxtCompatibilityIssues, ComponentsDir, Component, NuxtTemplate, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, ResolvedNuxtTemplate } from '@nuxt/schema';
import { LoadConfigOptions } from 'c12';
import { Import } from 'unimport';
import { Configuration, WebpackPluginInstance } from 'webpack';
import { UserConfig, Plugin } from 'vite';
import * as unctx_index from 'unctx/index';
import { NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack';
import * as consola from 'consola';
import { genSafeVariableName } from 'knitwork';
/**
* Define a Nuxt module, automatically merging defaults with user provided options, installing
* any hooks that are provided, and calling an optional setup function for full control.
*/
declare function defineNuxtModule<OptionsT extends ModuleOptions>(definition: ModuleDefinition<OptionsT>): NuxtModule<OptionsT>;
/** Installs a module on a Nuxt instance. */
declare function installModule(moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt): Promise<void>;
interface LoadNuxtConfigOptions extends LoadConfigOptions<NuxtConfig> {
}
declare function loadNuxtConfig(opts: LoadNuxtConfigOptions): Promise<NuxtOptions>;
interface LoadNuxtOptions extends LoadNuxtConfigOptions {
/** Load nuxt with development mode */
dev?: boolean;
/** Use lazy initialization of nuxt if set to false */
ready?: boolean;
/** @deprecated Use cwd option */
rootDir?: LoadNuxtConfigOptions['cwd'];
/** @deprecated use overrides option */
config?: LoadNuxtConfigOptions['overrides'];
}
declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
declare function buildNuxt(nuxt: Nuxt): Promise<any>;
declare function addImports(imports: Import | Import[]): void;
declare function addImportsDir(dirs: string | string[]): void;
declare function addImportsSources(presets: ImportPresetWithDeprecation | ImportPresetWithDeprecation[]): void;
interface ExtendConfigOptions {
/**
* Install plugin on dev
*
* @default true
*/
dev?: boolean;
/**
* Install plugin on build
*
* @default true
*/
build?: boolean;
/**
* Install plugin on server side
*
* @default true
*/
server?: boolean;
/**
* Install plugin on client side
*
* @default true
*/
client?: boolean;
}
interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
}
interface ExtendViteConfigOptions extends ExtendConfigOptions {
}
/**
* Extend Webpack config
*
* The fallback function might be called multiple times
* when applying to both client and server builds.
*/
declare function extendWebpackConfig(fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions): void;
/**
* Extend Vite config
*/
declare function extendViteConfig(fn: ((config: UserConfig) => void), options?: ExtendViteConfigOptions): (() => void) | undefined;
/**
* Append Webpack plugin to the config.
*/
declare function addWebpackPlugin(plugin: WebpackPluginInstance | WebpackPluginInstance[], options?: ExtendWebpackConfigOptions): void;
/**
* Append Vite plugin to the config.
*/
declare function addVitePlugin(plugin: Plugin | Plugin[], options?: ExtendViteConfigOptions): void;
/**
* Check version constraints and return incompatibility issues as an array
*/
declare function checkNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<NuxtCompatibilityIssues>;
/**
* Check version constraints and throw a detailed error if has any, otherwise returns true
*/
declare function assertNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<true>;
/**
* Check version constraints and return true if passed, otherwise returns false
*/
declare function hasNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<boolean>;
/**
* Check if current nuxt instance is version 2 legacy
*/
declare function isNuxt2(nuxt?: Nuxt): any;
/**
* Check if current nuxt instance is version 3
*/
declare function isNuxt3(nuxt?: Nuxt): any;
/**
* Get nuxt version
*/
declare function getNuxtVersion(nuxt?: Nuxt | any): any;
/**
* Register a directory to be scanned for components and imported only when used.
*
* Requires Nuxt 2.13+
*/
declare function addComponentsDir(dir: ComponentsDir): Promise<void>;
type AddComponentOptions = {
name: string;
filePath: string;
} & Partial<Exclude<Component, 'shortPath' | 'async' | 'level' | 'import' | 'asyncImport'>>;
/**
* Register a directory to be scanned for components and imported only when used.
*
* Requires Nuxt 2.13+
*/
declare function addComponent(opts: AddComponentOptions): Promise<void>;
/** Direct access to the Nuxt context - see https://github.com/unjs/unctx. */
declare const nuxtCtx: unctx_index.UseContext<Nuxt>;
/**
* Get access to Nuxt instance.
*
* Throws an error if Nuxt instance is unavailable.
*
* @example
* ```js
* const nuxt = useNuxt()
* ```
*/
declare function useNuxt(): Nuxt;
/**
* Get access to Nuxt instance.
*
* Returns null if Nuxt instance is unavailable.
*
* @example
* ```js
* const nuxt = tryUseNuxt()
* if (nuxt) {
* // Do something
* }
* ```
*/
declare function tryUseNuxt(): Nuxt | null;
/**
* Return a filter function to filter an array of paths
*/
declare function isIgnored(pathname: string): boolean;
declare function addLayout(this: any, template: NuxtTemplate, name?: string): void;
declare function extendPages(cb: NuxtHooks['pages:extend']): void;
/**
* Normalize a nuxt plugin object
*/
declare function normalizePlugin(plugin: NuxtPlugin | string): NuxtPlugin;
/**
* Registers a nuxt plugin and to the plugins array.
*
* Note: You can use mode or .client and .server modifiers with fileName option
* to use plugin only in client or server side.
*
* Note: By default plugin is prepended to the plugins array. You can use second argument to append (push) instead.
*
* @example
* ```js
* addPlugin({
* src: path.resolve(__dirname, 'templates/foo.js'),
* filename: 'foo.server.js' // [optional] only include in server bundle
* })
* ```
*/
interface AddPluginOptions {
append?: boolean;
}
declare function addPlugin(_plugin: NuxtPlugin | string, opts?: AddPluginOptions): NuxtPlugin;
/**
* Adds a template and registers as a nuxt plugin.
*/
declare function addPluginTemplate(plugin: NuxtPluginTemplate | string, opts?: AddPluginOptions): NuxtPlugin;
interface ResolvePathOptions {
/** Base for resolving paths from. Default is Nuxt rootDir. */
cwd?: string;
/** An object of aliases. Default is Nuxt configured aliases. */
alias?: Record<string, string>;
/** The file extensions to try. Default is Nuxt configured extensions. */
extensions?: string[];
}
/**
* Resolve full path to a file or directory respecting Nuxt alias and extensions options
*
* If path could not be resolved, normalized input path will be returned
*/
declare function resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
/**
* Try to resolve first existing file in paths
*/
declare function findPath(paths: string | string[], opts?: ResolvePathOptions, pathType?: 'file' | 'dir'): Promise<string | null>;
/**
* Resolve path aliases respecting Nuxt alias options
*/
declare function resolveAlias(path: string, alias?: Record<string, string>): string;
interface Resolver {
resolve(...path: string[]): string;
resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
}
/**
* Create a relative resolver
*/
declare function createResolver(base: string | URL): Resolver;
declare function resolveFiles(path: string, pattern: string | string[], opts?: {
followSymbolicLinks?: boolean;
}): Promise<string[]>;
/**
* Adds a nitro server handler
*
*/
declare function addServerHandler(handler: NitroEventHandler): void;
/**
* Adds a nitro server handler for development-only
*
*/
declare function addDevServerHandler(handler: NitroDevEventHandler): void;
/**
* Adds a Nitro plugin
*/
declare function addServerPlugin(plugin: string): void;
/**
* Adds routes to be prerendered
*/
declare function addPrerenderRoutes(routes: string | string[]): void;
/**
* Access to the Nitro instance
*
* **Note:** You can call `useNitro()` only after `ready` hook.
*
* **Note:** Changes to the Nitro instance configuration are not applied.
*
* @example
*
* ```ts
* nuxt.hook('ready', () => {
* console.log(useNitro())
* })
* ```
*/
declare function useNitro(): Nitro;
/**
* Renders given template using lodash template during build into the project buildDir
*/
declare function addTemplate(_template: NuxtTemplate<any> | string): ResolvedNuxtTemplate<any>;
/**
* Normalize a nuxt template object
*/
declare function normalizeTemplate(template: NuxtTemplate<any> | string): ResolvedNuxtTemplate<any>;
/**
* Trigger rebuilding Nuxt templates
*
* You can pass a filter within the options to selectively regenerate a subset of templates.
*/
declare function updateTemplates(options?: {
filter?: (template: ResolvedNuxtTemplate<any>) => boolean;
}): Promise<any>;
declare const logger: consola.Consola;
declare function useLogger(scope?: string): consola.Consola;
/** @deprecated Do not use CJS utils */
interface ResolveModuleOptions {
paths?: string | string[];
}
/** @deprecated Do not use CJS utils */
interface RequireModuleOptions extends ResolveModuleOptions {
/** Clear the require cache (force fresh require) but only if not within `node_modules` */
clearCache?: boolean;
/** Automatically de-default the result of requiring the module. */
interopDefault?: boolean;
}
/** @deprecated Do not use CJS utils */
declare function isNodeModules(id: string): boolean;
/** @deprecated Do not use CJS utils */
declare function clearRequireCache(id: string): void;
/** @deprecated Do not use CJS utils */
declare function scanRequireTree(id: string, files?: Set<string>): Set<string>;
/** @deprecated Do not use CJS utils */
declare function getRequireCacheItem(id: string): NodeModule | undefined;
/** Resolve the `package.json` file for a given module. */
declare function requireModulePkg(id: string, opts?: RequireModuleOptions): any;
/** @deprecated Do not use CJS utils */
declare function resolveModule(id: string, opts?: ResolveModuleOptions): string;
/** @deprecated Do not use CJS utils */
declare function tryResolveModule(path: string, opts?: ResolveModuleOptions): string | null;
/** @deprecated Do not use CJS utils */
declare function requireModule(id: string, opts?: RequireModuleOptions): any;
/** @deprecated Do not use CJS utils */
declare function importModule(id: string, opts?: RequireModuleOptions): Promise<any>;
/** @deprecated Do not use CJS utils */
declare function tryImportModule(id: string, opts?: RequireModuleOptions): Promise<any> | undefined;
/** @deprecated Do not use CJS utils */
declare function tryRequireModule(id: string, opts?: RequireModuleOptions): any;
/** @deprecated */
declare function compileTemplate(template: NuxtTemplate, ctx: any): Promise<string>;
/** @deprecated */
declare const templateUtils: {
serialize: (data: any) => string;
importName: typeof genSafeVariableName;
importSources: (sources: string | string[], { lazy }?: {
lazy?: boolean | undefined;
}) => string;
};
export { AddComponentOptions, AddPluginOptions, ExtendConfigOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, LoadNuxtConfigOptions, LoadNuxtOptions, RequireModuleOptions, ResolveModuleOptions, ResolvePathOptions, Resolver, addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addServerHandler, addServerPlugin, addTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, clearRequireCache, compileTemplate, createResolver, defineNuxtModule, extendPages, extendViteConfig, extendWebpackConfig, findPath, getNuxtVersion, getRequireCacheItem, hasNuxtCompatibility, importModule, installModule, isIgnored, isNodeModules, isNuxt2, isNuxt3, loadNuxt, loadNuxtConfig, logger, normalizePlugin, normalizeTemplate, nuxtCtx, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateTemplates, useLogger, useNitro, useNuxt };

796
node_modules/@nuxt/kit/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,796 @@
import { promises, existsSync, readFileSync } from 'node:fs';
import defu from 'defu';
import { applyDefaults } from 'untyped';
import { dirname, join, normalize, relative, isAbsolute, resolve, basename, parse } from 'pathe';
import consola from 'consola';
import { getContext } from 'unctx';
import satisfies from 'semver/functions/satisfies.js';
import lodashTemplate from 'lodash.template';
import { genSafeVariableName, genDynamicImport, genImport } from 'knitwork';
import { pathToFileURL, fileURLToPath } from 'node:url';
import { interopDefault } from 'mlly';
import jiti from 'jiti';
import { globby } from 'globby';
import { resolveAlias as resolveAlias$1 } from 'pathe/utils';
import ignore from 'ignore';
import { loadConfig } from 'c12';
import { NuxtConfigSchema } from '@nuxt/schema';
import { resolvePackageJSON, readPackageJSON } from 'pkg-types';
import { kebabCase, pascalCase } from 'scule';
import hash from 'hash-sum';
const logger = consola;
function useLogger(scope) {
return scope ? logger.withScope(scope) : logger;
}
const nuxtCtx = getContext("nuxt");
function useNuxt() {
const instance = nuxtCtx.tryUse();
if (!instance) {
throw new Error("Nuxt instance is unavailable!");
}
return instance;
}
function tryUseNuxt() {
return nuxtCtx.tryUse();
}
async function checkNuxtCompatibility(constraints, nuxt = useNuxt()) {
const issues = [];
if (constraints.nuxt) {
const nuxtVersion = getNuxtVersion(nuxt);
const nuxtSemanticVersion = nuxtVersion.replace(/-[0-9]+\.[0-9a-f]{7,8}/, "");
if (!satisfies(nuxtSemanticVersion, constraints.nuxt, { includePrerelease: true })) {
issues.push({
name: "nuxt",
message: `Nuxt version \`${constraints.nuxt}\` is required but currently using \`${nuxtVersion}\``
});
}
}
if (isNuxt2(nuxt)) {
const bridgeRequirement = constraints.bridge;
const hasBridge = !!nuxt.options.bridge;
if (bridgeRequirement === true && !hasBridge) {
issues.push({
name: "bridge",
message: "Nuxt bridge is required"
});
} else if (bridgeRequirement === false && hasBridge) {
issues.push({
name: "bridge",
message: "Nuxt bridge is not supported"
});
}
}
await nuxt.callHook("kit:compatibility", constraints, issues);
issues.toString = () => issues.map((issue) => ` - [${issue.name}] ${issue.message}`).join("\n");
return issues;
}
async function assertNuxtCompatibility(constraints, nuxt = useNuxt()) {
const issues = await checkNuxtCompatibility(constraints, nuxt);
if (issues.length) {
throw new Error("Nuxt compatibility issues found:\n" + issues.toString());
}
return true;
}
async function hasNuxtCompatibility(constraints, nuxt = useNuxt()) {
const issues = await checkNuxtCompatibility(constraints, nuxt);
return !issues.length;
}
function isNuxt2(nuxt = useNuxt()) {
return getNuxtVersion(nuxt).startsWith("2.");
}
function isNuxt3(nuxt = useNuxt()) {
return getNuxtVersion(nuxt).startsWith("3.");
}
function getNuxtVersion(nuxt = useNuxt()) {
const version = (nuxt?._version || nuxt?.version || nuxt?.constructor?.version || "").replace(/^v/g, "");
if (!version) {
throw new Error("Cannot determine nuxt version! Is current instance passed?");
}
return version;
}
async function compileTemplate(template, ctx) {
const data = { ...ctx, options: template.options };
if (template.src) {
try {
const srcContents = await promises.readFile(template.src, "utf-8");
return lodashTemplate(srcContents, {})(data);
} catch (err) {
console.error("Error compiling template: ", template);
throw err;
}
}
if (template.getContents) {
return template.getContents(data);
}
throw new Error("Invalid template: " + JSON.stringify(template));
}
const serialize = (data) => JSON.stringify(data, null, 2).replace(/"{(.+)}"(?=,?$)/gm, (r) => JSON.parse(r).replace(/^{(.*)}$/, "$1"));
const importSources = (sources, { lazy = false } = {}) => {
if (!Array.isArray(sources)) {
sources = [sources];
}
return sources.map((src) => {
if (lazy) {
return `const ${genSafeVariableName(src)} = ${genDynamicImport(src, { comment: `webpackChunkName: ${JSON.stringify(src)}` })}`;
}
return genImport(src, genSafeVariableName(src));
}).join("\n");
};
const importName = genSafeVariableName;
const templateUtils = { serialize, importName, importSources };
function defineNuxtModule(definition) {
if (!definition.meta) {
definition.meta = {};
}
if (definition.meta.configKey === void 0) {
definition.meta.configKey = definition.meta.name;
}
async function getOptions(inlineOptions, nuxt = useNuxt()) {
const configKey = definition.meta.configKey || definition.meta.name;
const _defaults = definition.defaults instanceof Function ? definition.defaults(nuxt) : definition.defaults;
let _options = defu(inlineOptions, nuxt.options[configKey], _defaults);
if (definition.schema) {
_options = await applyDefaults(definition.schema, _options);
}
return Promise.resolve(_options);
}
async function normalizedModule(inlineOptions, nuxt) {
if (!nuxt) {
nuxt = tryUseNuxt() || this.nuxt;
}
const uniqueKey = definition.meta.name || definition.meta.configKey;
if (uniqueKey) {
nuxt.options._requiredModules = nuxt.options._requiredModules || {};
if (nuxt.options._requiredModules[uniqueKey]) {
return;
}
nuxt.options._requiredModules[uniqueKey] = true;
}
if (definition.meta.compatibility) {
const issues = await checkNuxtCompatibility(definition.meta.compatibility, nuxt);
if (issues.length) {
logger.warn(`Module \`${definition.meta.name}\` is disabled due to incompatibility issues:
${issues.toString()}`);
return;
}
}
nuxt2Shims(nuxt);
const _options = await getOptions(inlineOptions, nuxt);
if (definition.hooks) {
nuxt.hooks.addHooks(definition.hooks);
}
await definition.setup?.call(null, _options, nuxt);
}
normalizedModule.getMeta = () => Promise.resolve(definition.meta);
normalizedModule.getOptions = getOptions;
return normalizedModule;
}
const NUXT2_SHIMS_KEY = "__nuxt2_shims_key__";
function nuxt2Shims(nuxt) {
if (!isNuxt2(nuxt) || nuxt[NUXT2_SHIMS_KEY]) {
return;
}
nuxt[NUXT2_SHIMS_KEY] = true;
nuxt.hooks = nuxt;
if (!nuxtCtx.tryUse()) {
nuxtCtx.set(nuxt);
nuxt.hook("close", () => nuxtCtx.unset());
}
let virtualTemplates;
nuxt.hook("builder:prepared", (_builder, buildOptions) => {
virtualTemplates = buildOptions.templates.filter((t) => t.getContents);
for (const template of virtualTemplates) {
buildOptions.templates.splice(buildOptions.templates.indexOf(template), 1);
}
});
nuxt.hook("build:templates", async (templates) => {
const context = {
nuxt,
utils: templateUtils,
app: {
dir: nuxt.options.srcDir,
extensions: nuxt.options.extensions,
plugins: nuxt.options.plugins,
templates: [
...templates.templatesFiles,
...virtualTemplates
],
templateVars: templates.templateVars
}
};
for await (const template of virtualTemplates) {
const contents = await compileTemplate({ ...template, src: "" }, context);
await promises.mkdir(dirname(template.dst), { recursive: true });
await promises.writeFile(template.dst, contents);
}
});
}
const _require = jiti(process.cwd(), { interopDefault: true, esmResolve: true });
function isNodeModules(id) {
return /[/\\]node_modules[/\\]/.test(id);
}
function clearRequireCache(id) {
if (isNodeModules(id)) {
return;
}
const entry = getRequireCacheItem(id);
if (!entry) {
delete _require.cache[id];
return;
}
if (entry.parent) {
entry.parent.children = entry.parent.children.filter((e) => e.id !== id);
}
for (const child of entry.children) {
clearRequireCache(child.id);
}
delete _require.cache[id];
}
function scanRequireTree(id, files = /* @__PURE__ */ new Set()) {
if (isNodeModules(id) || files.has(id)) {
return files;
}
const entry = getRequireCacheItem(id);
if (!entry) {
files.add(id);
return files;
}
files.add(entry.id);
for (const child of entry.children) {
scanRequireTree(child.id, files);
}
return files;
}
function getRequireCacheItem(id) {
try {
return _require.cache[id];
} catch (e) {
}
}
function requireModulePkg(id, opts = {}) {
return requireModule(join(id, "package.json"), opts);
}
function resolveModule(id, opts = {}) {
return normalize(_require.resolve(id, {
paths: [].concat(
global.__NUXT_PREPATHS__,
opts.paths || [],
process.cwd(),
global.__NUXT_PATHS__
).filter(Boolean)
}));
}
function tryResolveModule(path, opts = {}) {
try {
return resolveModule(path, opts);
} catch (error) {
if (error?.code !== "MODULE_NOT_FOUND") {
throw error;
}
}
return null;
}
function requireModule(id, opts = {}) {
const resolvedPath = resolveModule(id, opts);
if (opts.clearCache && !isNodeModules(id)) {
clearRequireCache(resolvedPath);
}
const requiredModule = _require(resolvedPath);
return requiredModule;
}
function importModule(id, opts = {}) {
const resolvedPath = resolveModule(id, opts);
if (opts.interopDefault !== false) {
return import(pathToFileURL(resolvedPath).href).then(interopDefault);
}
return import(pathToFileURL(resolvedPath).href);
}
function tryImportModule(id, opts = {}) {
try {
return importModule(id, opts).catch(() => void 0);
} catch {
}
}
function tryRequireModule(id, opts = {}) {
try {
return requireModule(id, opts);
} catch (e) {
}
}
function isIgnored(pathname) {
const nuxt = tryUseNuxt();
if (!nuxt) {
return false;
}
if (!nuxt._ignore) {
nuxt._ignore = ignore(nuxt.options.ignoreOptions);
nuxt._ignore.add(nuxt.options.ignore);
const nuxtignoreFile = join(nuxt.options.rootDir, ".nuxtignore");
if (existsSync(nuxtignoreFile)) {
nuxt._ignore.add(readFileSync(nuxtignoreFile, "utf-8"));
}
}
const relativePath = relative(nuxt.options.rootDir, pathname);
if (relativePath.startsWith("..")) {
return false;
}
return !!(relativePath && nuxt._ignore.ignores(relativePath));
}
async function resolvePath(path, opts = {}) {
const _path = path;
path = normalize(path);
if (isAbsolute(path) && existsSync(path) && !await isDirectory(path)) {
return path;
}
const nuxt = tryUseNuxt();
const cwd = opts.cwd || (nuxt ? nuxt.options.rootDir : process.cwd());
const extensions = opts.extensions || (nuxt ? nuxt.options.extensions : [".ts", ".mjs", ".cjs", ".json"]);
const modulesDir = nuxt ? nuxt.options.modulesDir : [];
path = resolveAlias(path);
if (!isAbsolute(path)) {
path = resolve(cwd, path);
}
let _isDir = false;
if (existsSync(path)) {
_isDir = await isDirectory(path);
if (!_isDir) {
return path;
}
}
for (const ext of extensions) {
const pathWithExt = path + ext;
if (existsSync(pathWithExt)) {
return pathWithExt;
}
const pathWithIndex = join(path, "index" + ext);
if (_isDir && existsSync(pathWithIndex)) {
return pathWithIndex;
}
}
const resolveModulePath = tryResolveModule(_path, { paths: [cwd, ...modulesDir] });
if (resolveModulePath) {
return resolveModulePath;
}
return path;
}
async function findPath(paths, opts, pathType = "file") {
if (!Array.isArray(paths)) {
paths = [paths];
}
for (const path of paths) {
const rPath = await resolvePath(path, opts);
if (await existsSensitive(rPath)) {
const _isDir = await isDirectory(rPath);
if (!pathType || pathType === "file" && !_isDir || pathType === "dir" && _isDir) {
return rPath;
}
}
}
return null;
}
function resolveAlias(path, alias) {
if (!alias) {
alias = tryUseNuxt()?.options.alias || {};
}
return resolveAlias$1(path, alias);
}
function createResolver(base) {
if (!base) {
throw new Error("`base` argument is missing for createResolver(base)!");
}
base = base.toString();
if (base.startsWith("file://")) {
base = dirname(fileURLToPath(base));
}
return {
resolve: (...path) => resolve(base, ...path),
resolvePath: (path, opts) => resolvePath(path, { cwd: base, ...opts })
};
}
async function existsSensitive(path) {
if (!existsSync(path)) {
return false;
}
const dirFiles = await promises.readdir(dirname(path));
return dirFiles.includes(basename(path));
}
async function isDirectory(path) {
return (await promises.lstat(path)).isDirectory();
}
async function resolveFiles(path, pattern, opts = {}) {
const files = await globby(pattern, { cwd: path, followSymbolicLinks: opts.followSymbolicLinks ?? true });
return files.map((p) => resolve(path, p)).filter((p) => !isIgnored(p)).sort();
}
async function installModule(moduleToInstall, _inlineOptions, _nuxt) {
const nuxt = useNuxt();
const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions);
await nuxtModule(inlineOptions, nuxt);
if (typeof moduleToInstall === "string") {
nuxt.options.build.transpile.push(moduleToInstall);
}
nuxt.options._installedModules = nuxt.options._installedModules || [];
nuxt.options._installedModules.push({
meta: await nuxtModule.getMeta?.(),
entryPath: typeof moduleToInstall === "string" ? resolveAlias(moduleToInstall) : void 0
});
}
async function normalizeModule(nuxtModule, inlineOptions) {
const nuxt = useNuxt();
if (typeof nuxtModule === "string") {
const _src = resolveModule(resolveAlias(nuxtModule), { paths: nuxt.options.modulesDir });
const isESM = _src.endsWith(".mjs");
try {
nuxtModule = isESM ? await importModule(_src) : requireModule(_src);
} catch (error) {
console.error(`Error while requiring module \`${nuxtModule}\`: ${error}`);
throw error;
}
}
if (typeof nuxtModule !== "function") {
throw new TypeError("Nuxt module should be a function: " + nuxtModule);
}
return { nuxtModule, inlineOptions };
}
async function loadNuxtConfig(opts) {
globalThis.defineNuxtConfig = (c) => c;
const result = await loadConfig({
name: "nuxt",
configFile: "nuxt.config",
rcFile: ".nuxtrc",
extend: { extendKey: ["theme", "extends"] },
dotenv: true,
globalRc: true,
...opts
});
delete globalThis.defineNuxtConfig;
const { configFile, layers = [], cwd } = result;
const nuxtConfig = result.config;
nuxtConfig.rootDir = nuxtConfig.rootDir || cwd;
nuxtConfig._nuxtConfigFile = configFile;
nuxtConfig._nuxtConfigFiles = [configFile];
for (const layer of layers) {
layer.config = layer.config || {};
layer.config.rootDir = layer.config.rootDir ?? layer.cwd;
layer.config.srcDir = resolve(layer.config.rootDir, layer.config.srcDir);
}
const _layers = layers.filter((layer) => layer.configFile && !layer.configFile.endsWith(".nuxtrc"));
nuxtConfig._layers = _layers;
if (!_layers.length) {
_layers.push({
cwd,
config: {
rootDir: cwd,
srcDir: cwd
}
});
}
return await applyDefaults(NuxtConfigSchema, nuxtConfig);
}
async function loadNuxt(opts) {
opts.cwd = opts.cwd || opts.rootDir;
opts.overrides = opts.overrides || opts.config || {};
const resolveOpts = { paths: opts.cwd };
opts.overrides.dev = !!opts.dev;
const nearestNuxtPkg = await Promise.all(["nuxt3", "nuxt", "nuxt-edge"].map((pkg2) => resolvePackageJSON(pkg2, { url: opts.cwd }).catch(() => null))).then((r) => r.filter(Boolean).sort((a, b) => b.length - a.length)[0]);
if (!nearestNuxtPkg) {
throw new Error(`Cannot find any nuxt version from ${opts.cwd}`);
}
const pkg = await readPackageJSON(nearestNuxtPkg);
const majorVersion = parseInt((pkg.version || "").split(".")[0]);
if (majorVersion === 3) {
const { loadNuxt: loadNuxt3 } = await importModule(pkg._name || pkg.name, resolveOpts);
const nuxt2 = await loadNuxt3(opts);
return nuxt2;
}
const { loadNuxt: loadNuxt2 } = await tryImportModule("nuxt-edge", resolveOpts) || await importModule("nuxt", resolveOpts);
const nuxt = await loadNuxt2({
rootDir: opts.cwd,
for: opts.dev ? "dev" : "build",
configOverrides: opts.overrides,
ready: opts.ready,
envConfig: opts.dotenv
});
return nuxt;
}
async function buildNuxt(nuxt) {
const resolveOpts = { paths: nuxt.options.rootDir };
if (nuxt.options._majorVersion === 3) {
const { build: build2 } = await tryImportModule("nuxt3", resolveOpts) || await importModule("nuxt", resolveOpts);
return build2(nuxt);
}
const { build } = await tryImportModule("nuxt-edge", resolveOpts) || await importModule("nuxt", resolveOpts);
return build(nuxt);
}
function addImports(imports) {
assertNuxtCompatibility({ bridge: true });
useNuxt().hook("imports:extend", (_imports) => {
_imports.push(...Array.isArray(imports) ? imports : [imports]);
});
}
function addImportsDir(dirs) {
assertNuxtCompatibility({ bridge: true });
useNuxt().hook("imports:dirs", (_dirs) => {
for (const dir of Array.isArray(dirs) ? dirs : [dirs]) {
_dirs.push(dir);
}
});
}
function addImportsSources(presets) {
assertNuxtCompatibility({ bridge: true });
useNuxt().hook("imports:sources", (_presets) => {
for (const preset of Array.isArray(presets) ? presets : [presets]) {
_presets.push(preset);
}
});
}
function extendWebpackConfig(fn, options = {}) {
const nuxt = useNuxt();
if (options.dev === false && nuxt.options.dev) {
return;
}
if (options.build === false && nuxt.options.build) {
return;
}
nuxt.hook("webpack:config", (configs) => {
if (options.server !== false) {
const config = configs.find((i) => i.name === "server");
if (config) {
fn(config);
}
}
if (options.client !== false) {
const config = configs.find((i) => i.name === "client");
if (config) {
fn(config);
}
}
});
}
function extendViteConfig(fn, options = {}) {
const nuxt = useNuxt();
if (options.dev === false && nuxt.options.dev) {
return;
}
if (options.build === false && nuxt.options.build) {
return;
}
if (options.server !== false && options.client !== false) {
return nuxt.hook("vite:extend", ({ config }) => fn(config));
}
nuxt.hook("vite:extendConfig", (config, { isClient, isServer }) => {
if (options.server !== false && isServer) {
return fn(config);
}
if (options.client !== false && isClient) {
return fn(config);
}
});
}
function addWebpackPlugin(plugin, options) {
extendWebpackConfig((config) => {
config.plugins = config.plugins || [];
if (Array.isArray(plugin)) {
config.plugins.push(...plugin);
} else {
config.plugins.push(plugin);
}
}, options);
}
function addVitePlugin(plugin, options) {
extendViteConfig((config) => {
config.plugins = config.plugins || [];
if (Array.isArray(plugin)) {
config.plugins.push(...plugin);
} else {
config.plugins.push(plugin);
}
}, options);
}
async function addComponentsDir(dir) {
const nuxt = useNuxt();
await assertNuxtCompatibility({ nuxt: ">=2.13" }, nuxt);
nuxt.options.components = nuxt.options.components || [];
nuxt.hook("components:dirs", (dirs) => {
dirs.push(dir);
});
}
async function addComponent(opts) {
const nuxt = useNuxt();
await assertNuxtCompatibility({ nuxt: ">=2.13" }, nuxt);
nuxt.options.components = nuxt.options.components || [];
const component = {
export: opts.export || "default",
chunkName: "components/" + kebabCase(opts.name),
global: opts.global ?? false,
kebabName: kebabCase(opts.name || ""),
pascalName: pascalCase(opts.name || ""),
prefetch: false,
preload: false,
mode: "all",
shortPath: opts.filePath,
...opts
};
nuxt.hook("components:extend", (components) => {
const existingComponent = components.find((c) => (c.pascalName === component.pascalName || c.kebabName === component.kebabName) && c.mode === component.mode);
if (existingComponent) {
const name = existingComponent.pascalName || existingComponent.kebabName;
console.warn(`Overriding ${name} component.`);
Object.assign(existingComponent, component);
} else {
components.push(component);
}
});
}
function addTemplate(_template) {
const nuxt = useNuxt();
const template = normalizeTemplate(_template);
nuxt.options.build.templates = nuxt.options.build.templates.filter((p) => normalizeTemplate(p).filename !== template.filename);
nuxt.options.build.templates.push(template);
return template;
}
function normalizeTemplate(template) {
if (!template) {
throw new Error("Invalid template: " + JSON.stringify(template));
}
if (typeof template === "string") {
template = { src: template };
} else {
template = { ...template };
}
if (template.src) {
if (!existsSync(template.src)) {
throw new Error("Template not found: " + template.src);
}
if (!template.filename) {
const srcPath = parse(template.src);
template.filename = template.fileName || `${basename(srcPath.dir)}.${srcPath.name}.${hash(template.src)}${srcPath.ext}`;
}
}
if (!template.src && !template.getContents) {
throw new Error("Invalid template. Either getContents or src options should be provided: " + JSON.stringify(template));
}
if (!template.filename) {
throw new Error("Invalid template. Either filename should be provided: " + JSON.stringify(template));
}
if (template.filename.endsWith(".d.ts")) {
template.write = true;
}
if (!template.dst) {
const nuxt = useNuxt();
template.dst = resolve(nuxt.options.buildDir, template.filename);
}
return template;
}
function updateTemplates(options) {
return useNuxt().hooks.callHook("builder:generateApp", options);
}
function addLayout(template, name) {
const nuxt = useNuxt();
const { filename, src } = addTemplate(template);
const layoutName = kebabCase(name || parse(filename).name).replace(/["']/g, "");
if (isNuxt2(nuxt)) {
const layout = nuxt.options.layouts[layoutName];
if (layout) {
return logger.warn(
`Not overriding \`${layoutName}\` (provided by \`${layout}\`) with \`${src || filename}\`.`
);
}
nuxt.options.layouts[layoutName] = `./${filename}`;
if (name === "error") {
this.addErrorLayout(filename);
}
return;
}
nuxt.hook("app:templates", (app) => {
if (layoutName in app.layouts) {
const relativePath = relative(nuxt.options.srcDir, app.layouts[layoutName].file);
return logger.warn(
`Not overriding \`${layoutName}\` (provided by \`~/${relativePath}\`) with \`${src || filename}\`.`
);
}
app.layouts[layoutName] = {
file: join("#build", filename),
name: layoutName
};
});
}
function extendPages(cb) {
const nuxt = useNuxt();
if (isNuxt2(nuxt)) {
nuxt.hook("build:extendRoutes", cb);
} else {
nuxt.hook("pages:extend", cb);
}
}
function normalizePlugin(plugin) {
if (typeof plugin === "string") {
plugin = { src: plugin };
} else {
plugin = { ...plugin };
}
if (!plugin.src) {
throw new Error("Invalid plugin. src option is required: " + JSON.stringify(plugin));
}
plugin.src = normalize(resolveAlias(plugin.src));
if (plugin.ssr) {
plugin.mode = "server";
}
if (!plugin.mode) {
const [, mode = "all"] = plugin.src.match(/\.(server|client)(\.\w+)*$/) || [];
plugin.mode = mode;
}
return plugin;
}
function addPlugin(_plugin, opts = {}) {
const nuxt = useNuxt();
const plugin = normalizePlugin(_plugin);
nuxt.options.plugins = nuxt.options.plugins.filter((p) => normalizePlugin(p).src !== plugin.src);
nuxt.options.plugins[opts.append ? "push" : "unshift"](plugin);
return plugin;
}
function addPluginTemplate(plugin, opts = {}) {
const normalizedPlugin = typeof plugin === "string" ? { src: plugin } : { ...plugin, src: addTemplate(plugin).dst };
return addPlugin(normalizedPlugin, opts);
}
function normalizeHandlerMethod(handler) {
const [, method = void 0] = handler.handler.match(/\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/) || [];
return {
method,
...handler,
handler: normalize(handler.handler)
};
}
function addServerHandler(handler) {
useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler));
}
function addDevServerHandler(handler) {
useNuxt().options.devServerHandlers.push(handler);
}
function addServerPlugin(plugin) {
const nuxt = useNuxt();
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || [];
nuxt.options.nitro.plugins.push(normalize(plugin));
}
function addPrerenderRoutes(routes) {
const nuxt = useNuxt();
if (!Array.isArray(routes)) {
routes = [routes];
}
routes = routes.filter(Boolean);
if (!routes.length) {
return;
}
nuxt.hook("prerender:routes", (ctx) => {
for (const route of routes) {
ctx.routes.add(route);
}
});
}
function useNitro() {
const nuxt = useNuxt();
if (!nuxt._nitro) {
throw new Error("Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.");
}
return nuxt._nitro;
}
export { addComponent, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addServerHandler, addServerPlugin, addTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, clearRequireCache, compileTemplate, createResolver, defineNuxtModule, extendPages, extendViteConfig, extendWebpackConfig, findPath, getNuxtVersion, getRequireCacheItem, hasNuxtCompatibility, importModule, installModule, isIgnored, isNodeModules, isNuxt2, isNuxt3, loadNuxt, loadNuxtConfig, logger, normalizePlugin, normalizeTemplate, nuxtCtx, requireModule, requireModulePkg, resolveAlias, resolveFiles, resolveModule, resolvePath, scanRequireTree, templateUtils, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateTemplates, useLogger, useNitro, useNuxt };

41
node_modules/@nuxt/kit/package.json generated vendored Normal file
View File

@@ -0,0 +1,41 @@
{
"name": "@nuxt/kit",
"version": "3.0.0",
"repository": "nuxt/framework",
"license": "MIT",
"type": "module",
"main": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"dependencies": {
"@nuxt/schema": "3.0.0",
"c12": "^1.0.1",
"consola": "^2.15.3",
"defu": "^6.1.1",
"globby": "^13.1.2",
"hash-sum": "^2.0.0",
"ignore": "^5.2.0",
"jiti": "^1.16.0",
"knitwork": "^1.0.0",
"lodash.template": "^4.5.0",
"mlly": "^1.0.0",
"pathe": "^1.0.0",
"pkg-types": "^1.0.1",
"scule": "^1.0.0",
"semver": "^7.3.8",
"unctx": "^2.1.0",
"unimport": "^1.0.1",
"untyped": "^1.0.0"
},
"devDependencies": {
"@types/lodash.template": "^4",
"@types/semver": "^7",
"unbuild": "latest"
},
"engines": {
"node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"scripts": {}
}

21
node_modules/@nuxt/schema/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 - Nuxt Project
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.

3
node_modules/@nuxt/schema/README.md generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Nuxt Schema
> Cross-version Nuxt typedefs and defaults

1962
node_modules/@nuxt/schema/dist/index.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

567
node_modules/@nuxt/schema/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,567 @@
import { defineUntypedSchema } from 'untyped';
import defu from 'defu';
import { join, resolve } from 'pathe';
import { isDevelopment, isDebug } from 'std-env';
import { findWorkspaceDir } from 'pkg-types';
import createResolver from 'postcss-import-resolver';
import { withoutLeadingSlash } from 'ufo';
const adhoc = defineUntypedSchema({
components: {
$resolve: (val) => {
if (Array.isArray(val)) {
return { dirs: val };
}
if (val === void 0 || val === true) {
return { dirs: [{ path: "~/components/global", global: true }, "~/components"] };
}
return val;
}
},
imports: {
global: false,
dirs: []
},
pages: void 0,
telemetry: void 0
});
const app = defineUntypedSchema({
vue: {
compilerOptions: {}
},
app: {
baseURL: {
$resolve: async (val) => val || process.env.NUXT_APP_BASE_URL || "/"
},
buildAssetsDir: {
$resolve: async (val) => val || process.env.NUXT_APP_BUILD_ASSETS_DIR || "/_nuxt/"
},
cdnURL: {
$resolve: async (val, get) => await get("dev") ? "" : (process.env.NUXT_APP_CDN_URL ?? val) || ""
},
head: {
$resolve: async (val, get) => {
const resolved = defu(val, await get("meta"), {
meta: [],
link: [],
style: [],
script: [],
noscript: []
});
if (!resolved.meta.find((m) => m.charset)?.charset) {
resolved.meta.unshift({ charset: resolved.charset || "utf-8" });
}
if (!resolved.meta.find((m) => m.name === "viewport")?.content) {
resolved.meta.unshift({ name: "viewport", content: resolved.viewport || "width=device-width, initial-scale=1" });
}
resolved.meta = resolved.meta.filter(Boolean);
resolved.link = resolved.link.filter(Boolean);
resolved.style = resolved.style.filter(Boolean);
resolved.script = resolved.script.filter(Boolean);
resolved.noscript = resolved.noscript.filter(Boolean);
return resolved;
}
},
layoutTransition: false,
pageTransition: false,
keepalive: false,
rootId: "__nuxt",
rootTag: "div"
},
plugins: [],
css: {
$resolve: (val) => (val ?? []).map((c) => c.src || c)
}
});
const build = defineUntypedSchema({
builder: {
$resolve: async (val, get) => {
if (typeof val === "object") {
return val;
}
const map = {
vite: "@nuxt/vite-builder",
webpack: "@nuxt/webpack-builder"
};
return map[val] || val || (await get("vite") === false ? map.webpack : map.vite);
}
},
sourcemap: {
$resolve: async (val, get) => {
if (typeof val === "boolean") {
return { server: val, client: val };
}
return defu(val, {
server: true,
client: await get("dev")
});
}
},
build: {
transpile: {
$resolve: (val) => [].concat(val).filter(Boolean)
},
templates: [],
analyze: {
$resolve: async (val, get) => {
if (val !== true) {
return val ?? false;
}
const rootDir = await get("rootDir");
return {
template: "treemap",
projectRoot: rootDir,
filename: join(rootDir, ".nuxt/stats", "{name}.html")
};
}
}
}
});
const common = defineUntypedSchema({
extends: null,
theme: null,
rootDir: {
$resolve: (val) => typeof val === "string" ? resolve(val) : process.cwd()
},
workspaceDir: {
$resolve: async (val, get) => val ? resolve(await get("rootDir"), val) : await findWorkspaceDir(await get("rootDir")).catch(() => get("rootDir"))
},
srcDir: {
$resolve: async (val, get) => resolve(await get("rootDir"), val || ".")
},
serverDir: {
$resolve: async (val, get) => resolve(await get("rootDir"), val || resolve(await get("srcDir"), "server"))
},
buildDir: {
$resolve: async (val, get) => resolve(await get("rootDir"), val || ".nuxt")
},
modulesDir: {
$default: ["node_modules"],
$resolve: async (val, get) => [
...await Promise.all(val.map(async (dir) => resolve(await get("rootDir"), dir))),
resolve(process.cwd(), "node_modules")
]
},
dev: Boolean(isDevelopment),
test: Boolean(isDevelopment),
debug: {
$resolve: async (val, get) => val ?? isDebug
},
ssr: {
$resolve: (val) => val ?? true
},
modules: [],
dir: {
assets: "assets",
layouts: "layouts",
middleware: "middleware",
pages: "pages",
plugins: "plugins",
public: {
$resolve: async (val, get) => val || await get("dir.static") || "public"
},
static: {
$schema: { deprecated: "use `dir.public` option instead" },
$resolve: async (val, get) => val || await get("dir.public") || "public"
}
},
extensions: {
$resolve: (val) => [".js", ".jsx", ".mjs", ".ts", ".tsx", ".vue"].concat(val).filter(Boolean)
},
alias: {
$resolve: async (val, get) => ({
"~~": await get("rootDir"),
"@@": await get("rootDir"),
"~": await get("srcDir"),
"@": await get("srcDir"),
[await get("dir.assets")]: join(await get("srcDir"), await get("dir.assets")),
[await get("dir.public")]: join(await get("srcDir"), await get("dir.public")),
...val
})
},
ignoreOptions: void 0,
ignorePrefix: "-",
ignore: {
$resolve: async (val, get) => [
"**/*.stories.{js,ts,jsx,tsx}",
"**/*.{spec,test}.{js,ts,jsx,tsx}",
"**/*.d.ts",
".output",
await get("ignorePrefix") && `**/${await get("ignorePrefix")}*.*`
].concat(val).filter(Boolean)
},
watchers: {
rewatchOnRawEvents: void 0,
webpack: {
aggregateTimeout: 1e3
},
chokidar: {
ignoreInitial: true
}
},
hooks: null,
runtimeConfig: {
$resolve: async (val, get) => defu(val, {
public: {},
app: {
baseURL: (await get("app")).baseURL,
buildAssetsDir: (await get("app")).buildAssetsDir,
cdnURL: (await get("app")).cdnURL
}
})
},
appConfig: {}
});
const dev = defineUntypedSchema({
devServer: {
https: false,
port: process.env.NUXT_PORT || process.env.NITRO_PORT || process.env.PORT || 3e3,
host: process.env.NUXT_HOST || process.env.NITRO_HOST || process.env.HOST || "localhost",
url: "http://localhost:3000"
}
});
const experimental = defineUntypedSchema({
experimental: {
asyncEntry: {
$resolve: (val) => val ?? false
},
reactivityTransform: false,
externalVue: true,
treeshakeClientOnly: true,
viteNode: {
$resolve: (val) => {
val = process.env.EXPERIMENTAL_VITE_NODE ? true : val;
if (val === true) {
console.warn("`vite-node` is now enabled by default. You can safely remove `experimental.viteNode` from your config.");
} else if (val === false) {
console.warn("`vite-node` is now enabled by default. To disable it, set `vite.devBundler` to `legacy` instead.");
}
return val ?? true;
}
},
viteServerDynamicImports: true,
inlineSSRStyles: {
async $resolve(val, get) {
if (val === false || await get("dev") || await get("ssr") === false || await get("builder") === "@nuxt/webpack-builder") {
return false;
}
return val ?? true;
}
},
noScripts: false,
payloadExtraction: {
async $resolve(enabled, get) {
enabled = enabled ?? false;
if (enabled) {
console.warn("Using experimental payload extraction for full-static output. You can opt-out by setting `experimental.payloadExtraction` to `false`.");
}
return enabled;
}
},
crossOriginPrefetch: false,
writeEarlyHints: false
}
});
const generate = defineUntypedSchema({
generate: {
routes: [],
exclude: []
}
});
const internal = defineUntypedSchema({
_majorVersion: 3,
_legacyGenerate: false,
_start: false,
_build: false,
_generate: false,
_prepare: false,
_cli: false,
_requiredModules: {},
_nuxtConfigFile: void 0,
_nuxtConfigFiles: [],
appDir: "",
_installedModules: [],
_modules: []
});
const nitro = defineUntypedSchema({
nitro: {
routeRules: {
$resolve: async (val, get) => ({
...await get("routeRules") || {},
...val || {}
})
}
},
routeRules: {},
serverHandlers: [],
devServerHandlers: []
});
const postcss = defineUntypedSchema({
postcss: {
config: false,
plugins: {
"postcss-import": {
$resolve: async (val, get) => val !== false ? defu(val || {}, {
resolve: createResolver({
alias: { ...await get("alias") },
modules: [
await get("srcDir"),
await get("rootDir"),
...await get("modulesDir")
]
})
}) : val
},
"postcss-url": {},
autoprefixer: {},
cssnano: {
$resolve: async (val, get) => val ?? !(await get("dev") && {
preset: ["default", {
minifyFontValues: { removeQuotes: false }
}]
})
}
}
}
});
const router = defineUntypedSchema({
router: {
options: {}
}
});
const typescript = defineUntypedSchema({
typescript: {
strict: true,
includeWorkspace: false,
typeCheck: false,
tsConfig: {},
shim: true
}
});
const vite = defineUntypedSchema({
vite: {
root: {
$resolve: async (val, get) => val ?? await get("srcDir")
},
mode: {
$resolve: async (val, get) => val ?? (await get("dev") ? "development" : "production")
},
logLevel: "warn",
define: {
$resolve: async (val, get) => ({
"process.dev": await get("dev"),
...val || {}
})
},
resolve: {
extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"]
},
publicDir: {
$resolve: async (val, get) => val ?? resolve(await get("srcDir"), (await get("dir")).public)
},
vue: {
isProduction: {
$resolve: async (val, get) => val ?? !await get("dev")
},
template: {
compilerOptions: {
$resolve: async (val, get) => val ?? (await get("vue")).compilerOptions
}
}
},
optimizeDeps: {
exclude: {
$resolve: async (val, get) => [
...val || [],
...(await get("build.transpile")).filter((i) => typeof i === "string"),
"vue-demi"
]
}
},
esbuild: {
jsxFactory: "h",
jsxFragment: "Fragment",
tsconfigRaw: "{}"
},
clearScreen: false,
build: {
assetsDir: {
$resolve: async (val, get) => val ?? withoutLeadingSlash((await get("app")).buildAssetsDir)
},
emptyOutDir: false
},
server: {
fs: {
allow: {
$resolve: async (val, get) => [
await get("buildDir"),
await get("srcDir"),
await get("rootDir"),
await get("workspaceDir"),
...await get("modulesDir"),
...val ?? []
]
}
}
}
}
});
const webpack = defineUntypedSchema({
webpack: {
analyze: {
$resolve: async (val, get) => {
if (val !== true) {
return val ?? false;
}
const rootDir = await get("rootDir");
return {
template: "treemap",
projectRoot: rootDir,
filename: join(rootDir, ".nuxt/stats", "{name}.html")
};
}
},
profile: process.argv.includes("--profile"),
extractCSS: true,
cssSourceMap: {
$resolve: async (val, get) => val ?? await get("dev")
},
serverURLPolyfill: "url",
filenames: {
app: ({ isDev }) => isDev ? `[name].js` : `[contenthash:7].js`,
chunk: ({ isDev }) => isDev ? `[name].js` : `[contenthash:7].js`,
css: ({ isDev }) => isDev ? "[name].css" : "css/[contenthash:7].css",
img: ({ isDev }) => isDev ? "[path][name].[ext]" : "img/[name].[contenthash:7].[ext]",
font: ({ isDev }) => isDev ? "[path][name].[ext]" : "fonts/[name].[contenthash:7].[ext]",
video: ({ isDev }) => isDev ? "[path][name].[ext]" : "videos/[name].[contenthash:7].[ext]"
},
loaders: {
$resolve: async (val, get) => {
const styleLoaders = [
"css",
"cssModules",
"less",
"sass",
"scss",
"stylus",
"vueStyle"
];
for (const name of styleLoaders) {
const loader = val[name];
if (loader && loader.sourceMap === void 0) {
loader.sourceMap = Boolean(await get("build.cssSourceMap"));
}
}
return val;
},
file: { esModule: false },
fontUrl: { esModule: false, limit: 1e3 },
imgUrl: { esModule: false, limit: 1e3 },
pugPlain: {},
vue: {
productionMode: { $resolve: async (val, get) => val ?? !await get("dev") },
transformAssetUrls: {
video: "src",
source: "src",
object: "src",
embed: "src"
},
compilerOptions: { $resolve: async (val, get) => val ?? await get("vue.compilerOptions") }
},
css: {
importLoaders: 0,
url: {
filter: (url, resourcePath) => !url.startsWith("/")
},
esModule: false
},
cssModules: {
importLoaders: 0,
url: {
filter: (url, resourcePath) => !url.startsWith("/")
},
esModule: false,
modules: {
localIdentName: "[local]_[hash:base64:5]"
}
},
less: {},
sass: {
sassOptions: {
indentedSyntax: true
}
},
scss: {},
stylus: {},
vueStyle: {}
},
plugins: [],
terser: {},
aggressiveCodeRemoval: false,
optimizeCSS: {
$resolve: async (val, get) => val ?? (await get("build.extractCSS") ? {} : false)
},
optimization: {
runtimeChunk: "single",
minimize: { $resolve: async (val, get) => val ?? !await get("dev") },
minimizer: void 0,
splitChunks: {
chunks: "all",
automaticNameDelimiter: "/",
cacheGroups: {}
}
},
postcss: {
execute: void 0,
postcssOptions: {
config: {
$resolve: async (val, get) => val ?? await get("postcss.config")
},
plugins: {
$resolve: async (val, get) => val ?? await get("postcss.plugins")
}
},
sourceMap: void 0,
implementation: void 0,
order: ""
},
devMiddleware: {
stats: "none"
},
hotMiddleware: {},
friendlyErrors: true,
warningIgnoreFilters: []
}
});
const index = {
...adhoc,
...app,
...build,
...common,
...dev,
...experimental,
...generate,
...internal,
...nitro,
...postcss,
...router,
...typescript,
...vite,
...webpack
};
export { index as NuxtConfigSchema };

40
node_modules/@nuxt/schema/package.json generated vendored Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "@nuxt/schema",
"version": "3.0.0",
"repository": "nuxt/framework",
"license": "MIT",
"type": "module",
"main": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist",
"schema"
],
"devDependencies": {
"@types/lodash.template": "^4",
"@types/semver": "^7",
"@vitejs/plugin-vue": "^3.2.0",
"@unhead/schema": "^1.0.0",
"nitropack": "^1.0.0",
"unbuild": "latest",
"vite": "~3.2.4"
},
"dependencies": {
"c12": "^1.0.1",
"create-require": "^1.1.1",
"defu": "^6.1.1",
"jiti": "^1.16.0",
"pathe": "^1.0.0",
"pkg-types": "^1.0.1",
"postcss-import-resolver": "^2.0.0",
"scule": "^1.0.0",
"std-env": "^3.3.1",
"ufo": "^1.0.0",
"unimport": "^1.0.1",
"untyped": "^1.0.0"
},
"engines": {
"node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"scripts": {}
}

1267
node_modules/@nuxt/schema/schema/config.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

336
node_modules/@nuxt/schema/schema/config.defaults.json generated vendored Normal file
View File

@@ -0,0 +1,336 @@
{
"rootDir": "/<rootDir>",
"vite": {
"base": "/",
"root": "/<rootDir>",
"mode": "production",
"logLevel": "warn",
"define": {
"process.dev": false
},
"resolve": {
"extensions": [
".mjs",
".js",
".ts",
".jsx",
".tsx",
".json",
".vue"
]
},
"publicDir": "/<rootDir>/public",
"vue": {
"isProduction": true,
"template": {
"compilerOptions": {}
}
},
"optimizeDeps": {
"exclude": [
"vue-demi"
]
},
"esbuild": {
"jsxFactory": "h",
"jsxFragment": "Fragment",
"tsconfigRaw": "{}"
},
"clearScreen": false,
"build": {
"assetsDir": "_nuxt/",
"emptyOutDir": false
},
"server": {
"fs": {
"allow": [
"/<rootDir>/.nuxt",
"/<rootDir>",
"/<rootDir>",
"/<rootDir>",
"/<rootDir>/node_modules",
"/Users/pooya/Code/framework/packages/schema/node_modules"
]
}
}
},
"components": {
"dirs": [
{
"path": "~/components/global",
"global": true
},
"~/components"
]
},
"imports": {
"global": false,
"dirs": []
},
"vue": {
"compilerOptions": {}
},
"app": {
"baseURL": "/",
"buildAssetsDir": "/_nuxt/",
"cdnURL": "",
"head": {
"meta": [
{
"name": "viewport",
"content": "width=device-width, initial-scale=1"
},
{
"charset": "utf-8"
}
],
"link": [],
"style": [],
"script": [],
"noscript": []
},
"layoutTransition": false,
"pageTransition": false,
"keepalive": false,
"rootId": "__nuxt",
"rootTag": "div"
},
"dev": false,
"plugins": [],
"css": [],
"srcDir": "/<rootDir>",
"dir": {
"assets": "assets",
"layouts": "layouts",
"middleware": "middleware",
"pages": "pages",
"plugins": "plugins",
"static": "public",
"public": "public"
},
"build": {
"transpile": [],
"templates": [],
"analyze": false
},
"buildDir": "/<rootDir>/.nuxt",
"workspaceDir": "/<rootDir>",
"modulesDir": [
"/<rootDir>/node_modules",
"/Users/pooya/Code/framework/packages/schema/node_modules"
],
"builder": "@nuxt/vite-builder",
"sourcemap": {
"server": true,
"client": false
},
"extends": null,
"theme": null,
"serverDir": "/<rootDir>/server",
"test": false,
"debug": false,
"ssr": true,
"modules": [],
"extensions": [
".js",
".jsx",
".mjs",
".ts",
".tsx",
".vue"
],
"alias": {
"~~": "/<rootDir>",
"@@": "/<rootDir>",
"~": "/<rootDir>",
"@": "/<rootDir>",
"assets": "/<rootDir>/assets",
"public": "/<rootDir>/public"
},
"ignoreOptions": {},
"ignorePrefix": "-",
"ignore": [
"**/*.stories.{js,ts,jsx,tsx}",
"**/*.{spec,test}.{js,ts,jsx,tsx}",
"**/*.d.ts",
".output",
"**/-*.*"
],
"watchers": {
"rewatchOnRawEvents": {},
"webpack": {
"aggregateTimeout": 1000
},
"chokidar": {
"ignoreInitial": true
}
},
"hooks": null,
"runtimeConfig": {
"public": {},
"app": {
"baseURL": "/",
"buildAssetsDir": "/_nuxt/",
"cdnURL": ""
}
},
"appConfig": {},
"devServer": {
"https": false,
"port": 3000,
"host": "localhost",
"url": "http://localhost:3000"
},
"experimental": {
"asyncEntry": false,
"reactivityTransform": false,
"externalVue": true,
"treeshakeClientOnly": true,
"viteNode": true,
"viteServerDynamicImports": true,
"inlineSSRStyles": true,
"noScripts": false,
"payloadExtraction": false,
"crossOriginPrefetch": false,
"writeEarlyHints": false
},
"generate": {
"routes": [],
"exclude": []
},
"_majorVersion": 3,
"_legacyGenerate": false,
"_start": false,
"_build": false,
"_generate": false,
"_prepare": false,
"_cli": false,
"_requiredModules": {},
"_nuxtConfigFile": {},
"_nuxtConfigFiles": [],
"appDir": "",
"_installedModules": [],
"_modules": [],
"routeRules": {},
"nitro": {
"routeRules": {}
},
"serverHandlers": [],
"devServerHandlers": [],
"postcss": {
"config": false,
"plugins": {
"postcss-import": {},
"postcss-url": {},
"autoprefixer": {},
"cssnano": true
}
},
"router": {
"options": {}
},
"typescript": {
"strict": true,
"includeWorkspace": false,
"typeCheck": false,
"tsConfig": {},
"shim": true
},
"webpack": {
"analyze": false,
"profile": false,
"extractCSS": true,
"cssSourceMap": false,
"serverURLPolyfill": "url",
"filenames": {},
"loaders": {
"file": {
"esModule": false
},
"fontUrl": {
"esModule": false,
"limit": 1000
},
"imgUrl": {
"esModule": false,
"limit": 1000
},
"pugPlain": {},
"vue": {
"productionMode": true,
"transformAssetUrls": {
"video": "src",
"source": "src",
"object": "src",
"embed": "src"
},
"compilerOptions": {}
},
"css": {
"importLoaders": 0,
"url": {},
"esModule": false,
"sourceMap": false
},
"cssModules": {
"importLoaders": 0,
"url": {},
"esModule": false,
"modules": {
"localIdentName": "[local]_[hash:base64:5]"
},
"sourceMap": false
},
"less": {
"sourceMap": false
},
"sass": {
"sassOptions": {
"indentedSyntax": true
},
"sourceMap": false
},
"scss": {
"sourceMap": false
},
"stylus": {
"sourceMap": false
},
"vueStyle": {
"sourceMap": false
}
},
"plugins": [],
"terser": {},
"aggressiveCodeRemoval": false,
"optimizeCSS": false,
"optimization": {
"runtimeChunk": "single",
"minimize": true,
"minimizer": {},
"splitChunks": {
"chunks": "all",
"automaticNameDelimiter": "/",
"cacheGroups": {}
}
},
"postcss": {
"postcssOptions": {
"config": false,
"plugins": {
"postcss-import": {},
"postcss-url": {},
"autoprefixer": {},
"cssnano": true
}
},
"order": ""
},
"devMiddleware": {
"stats": "none"
},
"hotMiddleware": {},
"friendlyErrors": true,
"warningIgnoreFilters": []
}
}

1221
node_modules/@nuxt/schema/schema/config.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

2603
node_modules/@nuxt/schema/schema/config.schema.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

21
node_modules/@nuxt/telemetry/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Nuxt Project
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.

101
node_modules/@nuxt/telemetry/README.md generated vendored Normal file
View File

@@ -0,0 +1,101 @@
# Nuxt Telemetry Module
Nuxt collects anonymous telemetry data about general usage. This helps us to accurately gauge Nuxt feature usage and customization across all our users.
This program is optional. You will be asked on first time to get permission and you can always [opt-out](#opting-out) if you'd not like to share any information.
## Why collecting Telemetry?
Nuxt has grown a lot from its [initial release](https://github.com/nuxt/nuxt.js/releases/tag/v0.2.0) (7 Nov 2016) and we are keep listening to [community feedback](https://github.com/nuxt/nuxt.js/issues) to improve it.
However, this manual process only collects feedback from a subset of users that takes the time to fill the issue template and it may have different needs or use-case than you.
Nuxt Telemetry collects anonymous telemetry data about general usage. This helps us to accurately gauge feature usage and customization across all our users. This data will let us better understand how Nuxt is used globally, measuring improvements made (DX and performances) and their relevance.
## Events
We collect multiple events:
- Command invoked (`nuxt dev`, `nuxt build`, etc)
- Versions of Nuxt and Node.js
- General machine informations (MacOS/Linux/Windows and if command is run within CI, ci name)
- Duration of the Webpack build and average size of the application, as well as the generation stats (when using `nuxt generate` or `nuxt export`)
- What are the *public dependency* of your project (Nuxt modules)
You can see the list of events in [lib/events](./src/events).
Example of an event:
```json
{
"name": "NUXT_PROJECT",
"payload": {
"type": "GIT",
"isSSR": true,
"target": "server",
"isTypescriptBuild": false,
"isTypescriptRuntime": false,
"isProgrammatic": false,
"packageManager": "npm"
}
}
```
To display the exact data that will be sent, you can use `NUXT_TELEMETRY_DEBUG=1`.
## Sensitive data
We take your privacy and our security very seriously.
We do not collect any metrics which may contain sensitive data.
This includes, but is not limited to: environment variables, file paths, contents of files, logs, or serialized JavaScript errors.
The data we collect is completely anonymous, not traceable to the source (using hash+seed), and only meaningful in aggregate form. No data we collect is personally identifiable or trackable.
## Opting-out
You can disable Nuxt Telemetry for your project with several ways:
1. Setting `telemetry: false` in your `nuxt.config`:
```js
export default {
telemetry: false
}
```
2. Using an environment variable:
```bash
NUXT_TELEMETRY_DISABLED=1
```
3. Using `npx nuxt telemetry disable`
```bash
npx nuxt telemetry [status|enable|disable] [-g,--global] [dir]
```
## Skip Prompt
If you encounter problems with consent prompt, and want to participate without asking this question, you can set `telemetry: true` from `nuxt.config`:
```js
export default {
telemetry: true
}
```
## Thank you
We want to thank you for participating in this telemetry program to help us better understand how you use Nuxt to keep improving it 💚
## Development
- Run `yarn dev:prepare` to generate type stubs.
- Use `yarn dev` to start [playground](./playground) in development mode.
## License
[MIT License](./LICENSE)

3
node_modules/@nuxt/telemetry/bin/nuxt-telemetry.mjs generated vendored Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
process._startTime = Date.now()
import('../dist/cli.mjs').then(r => (r.default || r).main())

4
node_modules/@nuxt/telemetry/dist/cli.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
declare const usage = "npx nuxt-telemetry `status`|`enable`|`disable`|`consent` [`-g`,`--global`] [`dir`]";
declare function main(): void;
export { main, usage };

123
node_modules/@nuxt/telemetry/dist/cli.mjs generated vendored Normal file
View File

@@ -0,0 +1,123 @@
import { resolve } from 'path';
import { existsSync, readFileSync } from 'fs';
import { homedir } from 'os';
import destr from 'destr';
import mri from 'mri';
import * as rc from 'rc9';
import c from 'chalk';
import consola from 'consola';
import jiti from 'jiti';
import { isTest } from 'std-env';
import { parse } from 'dotenv';
import { e as ensureUserconsent, c as consentVersion } from './shared/telemetry.5a54e3dd.mjs';
import 'inquirer';
import 'is-docker';
const usage = "npx nuxt-telemetry `status`|`enable`|`disable`|`consent` [`-g`,`--global`] [`dir`]";
const RC_FILENAME = ".nuxtrc";
function _run() {
const _argv = process.argv.slice(2);
const args = mri(_argv, {
boolean: [
"--global"
],
alias: {
"-g": "--global"
}
});
const [command, _dir = "."] = args._;
const dir = resolve(process.cwd(), _dir);
const global = args["--global"];
if (!global && !existsSync(resolve(dir, "nuxt.config.js")) && !existsSync(resolve(dir, "nuxt.config.ts"))) {
consola.error("It seems you are not in a nuxt project!");
consola.info("You can try with providing dir or using `-g`");
showUsage();
}
switch (command) {
case "enable":
setRC("telemetry.enabled", true);
setRC("telemetry.consent", consentVersion);
showStatus();
consola.info("You can disable telemetry with `npx nuxt telemetry disable " + (global ? "-g" : _dir));
return;
case "disable":
setRC("telemetry.enabled", false);
setRC("telemetry.consent", 0);
showStatus();
consola.info("You can enable telemetry with `npx nuxt telemetry enable " + (global ? "-g" : _dir) + "`");
return;
case "status":
return showStatus();
case "consent":
return _prompt();
default:
showUsage();
}
async function _prompt() {
const accepted = await ensureUserconsent({});
if (accepted && !global) {
setRC("telemetry.enabled", true);
setRC("telemetry.consent", consentVersion);
}
showStatus();
}
function _checkDisabled() {
if (isTest) {
return "Because running in test environment";
}
if (destr(process.env.NUXT_TELEMETRY_DISABLED)) {
return "by `NUXT_TELEMETRY_DISABLED` environment variable";
}
const dotenvFile = resolve(dir, ".env");
if (existsSync(dotenvFile)) {
const _env = parse(readFileSync(dotenvFile));
if (destr(_env.NUXT_TELEMETRY_DISABLED)) {
return "by `NUXT_TELEMETRY_DISABLED` from " + dotenvFile;
}
}
const disabledByConf = (conf) => conf.telemetry === false || conf.telemetry && conf.telemetry.enabled === false;
try {
const _require = jiti(dir);
if (disabledByConf(_require("./nuxt.config"))) {
return "by " + _require.resolve("./nuxt.config");
}
} catch (_) {
}
if (disabledByConf(rc.read({ name: RC_FILENAME, dir }))) {
return "by " + resolve(dir, RC_FILENAME);
}
if (disabledByConf(rc.readUser({ name: RC_FILENAME }))) {
return "by " + resolve(homedir(), RC_FILENAME);
}
}
function showStatus() {
const disabled = _checkDisabled();
if (disabled) {
consola.info(`Nuxt telemetry is ${c.yellow("disabled")} ${disabled}`);
} else {
consola.info(`Nuxt telemetry is ${c.green("enabled")}`, global ? "on machine" : "on current project");
}
}
function showUsage() {
consola.info(`Usage: ${usage}`);
process.exit(0);
}
function setRC(key, val) {
const update = { [key]: val };
if (global) {
rc.updateUser(update, RC_FILENAME);
} else {
rc.update(update, { name: RC_FILENAME, dir });
}
}
}
function main() {
try {
_run();
} catch (err) {
consola.fatal(err);
process.exit(1);
}
}
export { main, usage };

5
node_modules/@nuxt/telemetry/dist/module.cjs generated vendored Normal file
View File

@@ -0,0 +1,5 @@
module.exports = function(...args) {
return import('./module.mjs').then(m => m.default.call(this, ...args))
}
const _meta = module.exports.meta = require('./module.json')
module.exports.getMeta = () => Promise.resolve(_meta)

14
node_modules/@nuxt/telemetry/dist/module.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import * as _nuxt_schema from '@nuxt/schema';
interface TelemetryOptions {
debug: boolean
endpoint: string
seed: string
consent?: number
enabled: boolean
}
type ModuleOptions = boolean | TelemetryOptions;
declare const _default: _nuxt_schema.NuxtModule<TelemetryOptions>;
export { ModuleOptions, _default as default };

5
node_modules/@nuxt/telemetry/dist/module.json generated vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"name": "@nuxt/telemetry",
"configKey": "telemetry",
"version": "2.1.8"
}

407
node_modules/@nuxt/telemetry/dist/module.mjs generated vendored Normal file
View File

@@ -0,0 +1,407 @@
import destr from 'destr';
import { nanoid } from 'nanoid';
import { getNuxtVersion, isNuxt3, useLogger, defineNuxtModule } from '@nuxt/kit';
import { e as ensureUserconsent, u as updateUserNuxtRc } from './shared/telemetry.5a54e3dd.mjs';
import { fetch } from 'ohmyfetch';
import path, { join } from 'path';
import { existsSync } from 'fs';
import createRequire from 'create-require';
import os from 'os';
import gitUrlParse from 'git-url-parse';
import parseGitConfig from 'parse-git-config';
import isDocker from 'is-docker';
import { provider } from 'std-env';
import fs from 'fs-extra';
import { createHash } from 'crypto';
import 'chalk';
import 'inquirer';
import 'consola';
import 'rc9';
const version = "2.1.8";
async function postEvent(endpoint, body) {
const res = await fetch(endpoint, {
method: "POST",
body: JSON.stringify(body),
headers: {
"content-type": "application/json",
"user-agent": "Nuxt Telemetry " + version
}
});
if (!res.ok) {
throw new Error(res.statusText);
}
}
const build = function({ nuxt }, payload) {
const duration = { build: payload.duration.build };
let isSuccess = true;
for (const [name, stat] of Object.entries(payload.stats)) {
duration[name] = stat.duration;
if (!stat.success) {
isSuccess = false;
}
}
return {
name: "build",
isSuccess,
isDev: nuxt.options.dev || false,
duration
};
};
const command = function({ nuxt }) {
let command2 = process.argv[2] || "unknown";
const flagMap = {
dev: "dev",
_generate: "generate",
_export: "export",
_build: "build",
_serve: "serve",
_start: "start"
};
for (const flag in flagMap) {
if (nuxt.options[flag]) {
command2 = flagMap[flag];
break;
}
}
return {
name: "command",
command: command2
};
};
const generate = function generate2({ nuxt }, payload) {
return {
name: "generate",
isExport: !!nuxt.options._export,
routesCount: payload.routesCount,
duration: {
generate: payload.duration.generate
}
};
};
const dependency = function({ nuxt: { options } }) {
const events = [];
const projectDeps = getDependencies(options.rootDir);
const modules = normalizeModules(options.modules);
const buildModules = normalizeModules(options.buildModules);
const relatedDeps = [...modules, ...buildModules];
for (const dep of projectDeps) {
if (!relatedDeps.includes(dep.name)) {
continue;
}
events.push({
name: "dependency",
packageName: dep.name,
version: dep.version,
isDevDependency: dep.dev,
isModule: modules.includes(dep.name),
isBuildModule: buildModules.includes(dep.name)
});
}
return events;
};
function normalizeModules(modules) {
return modules.map((m) => {
if (typeof m === "string") {
return m;
}
if (Array.isArray(m) && typeof m[0] === "string") {
return m[0];
}
return null;
}).filter(Boolean);
}
function getDependencies(rootDir) {
const pkgPath = join(rootDir, "package.json");
if (!existsSync(pkgPath)) {
return [];
}
const _require = createRequire(rootDir);
const pkg = _require(pkgPath);
const mapDeps = (depsObj, dev = false) => {
const _deps = [];
for (const name in depsObj) {
try {
const pkg2 = _require(join(name, "package.json"));
_deps.push({ name, version: pkg2.version, dev });
} catch (_e) {
_deps.push({ name, version: depsObj[name], dev });
}
}
return _deps;
};
const deps = [];
if (pkg.dependencies) {
deps.push(...mapDeps(pkg.dependencies));
}
if (pkg.devDependencies) {
deps.push(...mapDeps(pkg.devDependencies, true));
}
return deps;
}
const project = function(context) {
const { options } = context.nuxt;
return {
name: "project",
type: context.git && context.git.url ? "git" : "local",
isSSR: options.mode === "universal" || options.ssr === true,
target: options._generate ? "static" : "server",
packageManager: context.packageManager
};
};
const session = function({ seed }) {
return {
name: "session",
id: seed
};
};
const events = {
__proto__: null,
build: build,
command: command,
generate: generate,
dependency: dependency,
getDependencies: getDependencies,
project: project,
session: session
};
const FILE2PM = {
"yarn.lock": "yarn",
"package-lock.json": "npm",
"shrinkwrap.json": "npm",
"pnpm-lock.yaml": "pnpm"
};
async function detectPackageManager(rootDir) {
for (const file in FILE2PM) {
if (await fs.pathExists(path.resolve(rootDir, file))) {
return FILE2PM[file];
}
}
return "unknown";
}
function hash(str) {
return createHash("sha256").update(str).digest("hex").substr(0, 16);
}
async function createContext(nuxt, options) {
const rootDir = nuxt.options.rootDir || process.cwd();
const git = await getGit(rootDir);
const packageManager = await detectPackageManager(rootDir);
const { seed } = options;
const projectHash = await getProjectHash(rootDir, git, seed);
const projectSession = getProjectSession(projectHash, seed);
const nuxtVersion = getNuxtVersion(nuxt);
const nuxtMajorVersion = isNuxt3(nuxt) ? 3 : 2;
const nodeVersion = process.version.replace("v", "");
const isEdge = nuxtVersion.includes("edge");
return {
nuxt,
seed,
git,
projectHash,
projectSession,
nuxtVersion,
nuxtMajorVersion,
isEdge,
cli: getCLI(),
nodeVersion,
os: os.type().toLocaleLowerCase(),
environment: getEnv(),
packageManager,
concent: options.consent
};
}
function getEnv() {
if (provider) {
return provider;
}
if (isDocker()) {
return "Docker";
}
return "unknown";
}
function getCLI() {
const entry = process.argv[1];
const knownCLIs = {
"nuxt-ts.js": "nuxt-ts",
"nuxt-start.js": "nuxt-start",
"nuxt.js": "nuxt",
nuxi: "nuxi"
};
for (const key in knownCLIs) {
if (entry.includes(key)) {
const edge = entry.includes("-edge") ? "-edge" : "";
return knownCLIs[key] + edge;
}
}
return "programmatic";
}
function getProjectSession(projectHash, sessionId) {
return hash(`${projectHash}#${sessionId}`);
}
function getProjectHash(rootDir, git, seed) {
let id;
if (git && git.url) {
id = `${git.source}#${git.owner}#${git.name}`;
} else {
id = `${rootDir}#${seed}`;
}
return hash(id);
}
async function getGitRemote(rootDir) {
try {
const parsed = await parseGitConfig({ cwd: rootDir });
if (parsed) {
const gitRemote = parsed['remote "origin"'].url;
return gitRemote;
}
return null;
} catch (err) {
return null;
}
}
async function getGit(rootDir) {
const gitRemote = await getGitRemote(rootDir);
if (!gitRemote) {
return;
}
const meta = gitUrlParse(gitRemote);
const url = meta.toString("https");
return {
url,
gitRemote,
source: meta.source,
owner: meta.owner,
name: meta.name
};
}
const log = useLogger("@nuxt/telemetry");
class Telemetry {
constructor(nuxt, options) {
this.events = [];
this.nuxt = nuxt;
this.options = options;
}
getContext() {
if (!this._contextPromise) {
this._contextPromise = createContext(this.nuxt, this.options);
}
return this._contextPromise;
}
createEvent(name, payload) {
const eventFactory = events[name];
if (typeof eventFactory !== "function") {
log.warn("Unknown event:", name);
return;
}
const eventPromise = this._invokeEvent(name, eventFactory, payload);
this.events.push(eventPromise);
}
async _invokeEvent(name, eventFactory, payload) {
try {
const context = await this.getContext();
const event = await eventFactory(context, payload);
event.name = name;
return event;
} catch (err) {
log.error("Error while running event:", err);
}
}
async getPublicContext() {
const context = await this.getContext();
const eventContext = {};
for (const key of [
"nuxtVersion",
"nuxtMajorVersion",
"isEdge",
"nodeVersion",
"cli",
"os",
"environment",
"projectHash",
"projectSession"
]) {
eventContext[key] = context[key];
}
return eventContext;
}
async sendEvents(debug) {
const events2 = [].concat(...(await Promise.all(this.events)).filter(Boolean));
this.events = [];
const context = await this.getPublicContext();
const body = {
timestamp: Date.now(),
context,
events: events2
};
if (this.options.endpoint) {
const start = Date.now();
try {
if (debug) {
log.info("Sending events:", JSON.stringify(body, null, 2));
}
await postEvent(this.options.endpoint, body);
if (debug) {
log.success(`Events sent to \`${this.options.endpoint}\` (${Date.now() - start} ms)`);
}
} catch (err) {
if (debug) {
log.error(`Error sending sent to \`${this.options.endpoint}\` (${Date.now() - start} ms)
`, err);
}
}
}
}
}
const module = defineNuxtModule({
meta: {
name: "@nuxt/telemetry",
configKey: "telemetry"
},
defaults: {
endpoint: process.env.NUXT_TELEMETRY_ENDPOINT || "https://telemetry.nuxtjs.com",
debug: destr(process.env.NUXT_TELEMETRY_DEBUG),
enabled: void 0,
seed: void 0
},
async setup(toptions, nuxt) {
if (!toptions.debug) {
log.level = 0;
}
const _topLevelTelemetry = nuxt.options.telemetry;
if (_topLevelTelemetry !== true) {
if (toptions.enabled === false || _topLevelTelemetry === false || !await ensureUserconsent(toptions)) {
log.info("Telemetry disabled");
return;
}
}
log.info("Telemetry enabled");
if (!toptions.seed) {
toptions.seed = hash(nanoid());
updateUserNuxtRc("telemetry.seed", toptions.seed);
log.info("Seed generated:", toptions.seed);
}
const t = new Telemetry(nuxt, toptions);
nuxt.hook("modules:done", () => {
t.createEvent("project");
t.createEvent("session");
t.createEvent("command");
t.sendEvents(toptions.debug);
});
}
});
export { module as default };

View File

@@ -0,0 +1,41 @@
import c from 'chalk';
import inquirer from 'inquirer';
import consola from 'consola';
import { isMinimal } from 'std-env';
import isDocker from 'is-docker';
import { updateUser } from 'rc9';
const consentVersion = 1;
function updateUserNuxtRc(key, val) {
updateUser({ [key]: val }, ".nuxtrc");
}
async function ensureUserconsent(options) {
if (options.consent >= consentVersion) {
return true;
}
if (isMinimal || process.env.CODESANDBOX_SSE || process.env.NEXT_TELEMETRY_DISABLED || isDocker()) {
return false;
}
process.stdout.write("\n");
consola.info(`${c.green("Nuxt")} collects completely anonymous data about usage.
This will help us improve Nuxt developer experience over time.
Read more on ${c.cyan.underline("https://github.com/nuxt/telemetry")}
`);
const { accept } = await inquirer.prompt({
type: "confirm",
name: "accept",
message: "Are you interested in participating?"
});
process.stdout.write("\n");
if (accept) {
updateUserNuxtRc("telemetry.consent", consentVersion);
updateUserNuxtRc("telemetry.enabled", true);
return true;
}
updateUserNuxtRc("telemetry.enabled", false);
return false;
}
export { consentVersion as c, ensureUserconsent as e, updateUserNuxtRc as u };

10
node_modules/@nuxt/telemetry/dist/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { ModuleOptions } from './module'
declare module '@nuxt/schema' {
interface NuxtConfig { ['telemetry']?: Partial<ModuleOptions> }
interface NuxtOptions { ['telemetry']?: ModuleOptions }
}
export { ModuleOptions, default } from './module'

63
node_modules/@nuxt/telemetry/package.json generated vendored Normal file
View File

@@ -0,0 +1,63 @@
{
"name": "@nuxt/telemetry",
"version": "2.1.8",
"repository": "nuxt/telemetry",
"license": "MIT",
"type": "module",
"exports": {
".": {
"import": "./dist/module.mjs",
"require": "./dist/module.cjs"
}
},
"main": "./dist/module.cjs",
"types": "./dist/types.d.ts",
"bin": {
"nuxt-telemetry": "./bin/nuxt-telemetry.mjs"
},
"files": [
"dist",
"bin"
],
"scripts": {
"build": "nuxt-module-build",
"dev": "NUXT_TELEMETRY_DEBUG=1 nuxi dev playground",
"dev:build": "NUXT_TELEMETRY_DEBUG=1 nuxi build playground",
"dev:generate": "NUXT_TELEMETRY_DEBUG=1 nuxi build playground",
"dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
"lint": "eslint --ext .ts,.js,.vue .",
"nuxt-telemetry": "jiti ./src/cli.ts",
"prepack": "nuxt-module-build",
"release": "yarn test && yarn build && standard-version && git push --follow-tags && npm publish",
"test": "yarn lint"
},
"dependencies": {
"@nuxt/kit": "^3.0.0-rc.14",
"chalk": "^5.1.2",
"ci-info": "^3.6.1",
"consola": "^2.15.3",
"create-require": "^1.1.1",
"defu": "^6.1.1",
"destr": "^1.2.1",
"dotenv": "^16.0.3",
"fs-extra": "^10.1.0",
"git-url-parse": "^13.1.0",
"inquirer": "^9.1.4",
"is-docker": "^3.0.0",
"jiti": "^1.16.0",
"mri": "^1.2.0",
"nanoid": "^4.0.0",
"node-fetch": "^3.3.0",
"ohmyfetch": "^0.4.21",
"parse-git-config": "^3.0.0",
"rc9": "^2.0.0",
"std-env": "^3.3.1"
},
"devDependencies": {
"@nuxt/module-builder": "^0.2.1",
"@nuxtjs/eslint-config-typescript": "^11.0.0",
"eslint": "^8.27.0",
"nuxt": "^3.0.0-rc.14",
"standard-version": "^9.3.2"
}
}

11
node_modules/@nuxt/ui-templates/README.md generated vendored Normal file
View File

@@ -0,0 +1,11 @@
# `@nuxt/ui-templates`
<a href="https://www.npmjs.com/package/@nuxt/ui-templates-edge"><img src="https://flat.badgen.net/npm/v/@nuxt/ui-templates-edge"></a>
Pre-compiled html templates for internal pages.
🏀 [Online Playground](https://templates.ui.nuxtjs.org)
# License
<a rel="license" href="http://creativecommons.org/licenses/by-nd/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nd/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">Nuxt UI</span> by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Nuxt Project</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nd/4.0/">Creative Commons Attribution-NoDerivatives 4.0 International License</a>.<br />Based on a work at <a xmlns:dct="http://purl.org/dc/terms/" href="https://github.com/nuxt/ui" rel="dct:source">https://github.com/nuxt/ui</a>.

5
node_modules/@nuxt/ui-templates/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
export { template as error404 } from './templates/error-404'
export { template as error500 } from './templates/error-500'
export { template as errorDev } from './templates/error-dev'
export { template as loading } from './templates/loading'
export { template as welcome } from './templates/welcome'

19
node_modules/@nuxt/ui-templates/dist/index.html generated vendored Normal file
View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/petite-vue" defer init></script>
<script type="module" crossorigin src="/assets/windi.a182e502.js"></script>
<link rel="stylesheet" href="/assets/windi.a1789a23.css">
</head>
<body v-scope='{"templateNames":["error-404","error-500","error-dev","loading","messages.json","welcome"]}'>
<div class="container mx-auto pt-10">
<h1 class="text-4xl mb-8">Nuxt Templates</h1>
<ul>
<li v-for="name in templateNames.filter(name => !name.includes('.json'))">
<a :href="`/templates/${name}`" class="block border p-4 mb-2 hover:border-black">{{ name }}</a>
</li>
</ul>
</div>
</body>
</html>

5
node_modules/@nuxt/ui-templates/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,5 @@
export { template as error404 } from './templates/error-404.mjs'
export { template as error500 } from './templates/error-500.mjs'
export { template as errorDev } from './templates/error-dev.mjs'
export { template as loading } from './templates/loading.mjs'
export { template as welcome } from './templates/welcome.mjs'

View File

@@ -0,0 +1,3 @@
export type DefaultMessages = Record<"statusCode" | "statusMessage" | "description" | "backHome", string | boolean | number >
declare const template: (data: Partial<DefaultMessages>) => string
export { template }

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,48 @@
<script setup>
import { useHead } from '#imports'
const props = defineProps({
appName: {
type: String,
default: "Nuxt"
},
version: {
type: String,
default: ""
},
statusCode: {
type: Number,
default: 404
},
statusMessage: {
type: String,
default: "Not Found"
},
description: {
type: String,
default: "Sorry, the page you are looking for could not be found."
},
backHome: {
type: String,
default: "Go back home"
}
})
useHead({
title: `${ props.statusCode } - ${ props.statusMessage } | ${ props.appName }`,
script: [],
style: [
{
children: `*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}a{color:inherit;text-decoration:inherit}body{margin:0;font-family:inherit;line-height:inherit}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}h1,p{margin:0}h1{font-size:inherit;font-weight:inherit}`
}
]
})
</script>
<template>
<div class="font-sans antialiased bg-white dark:bg-black text-black dark:text-white grid min-h-screen place-content-center overflow-hidden"><div class="fixed left-0 right-0 spotlight z-10"></div><div class="max-w-520px text-center z-20"><h1 class="text-8xl sm:text-10xl font-medium mb-8" v-text="statusCode" /><p class="text-xl px-8 sm:px-0 sm:text-4xl font-light mb-16 leading-tight" v-text="description" /><div class="w-full flex items-center justify-center"><NuxtLink to="/" class="gradient-border text-md sm:text-xl py-2 px-4 sm:py-3 sm:px-6 cursor-pointer">
{{ backHome }}
</NuxtLink></div></div></div>
</template>
<style scoped>
.spotlight{background:linear-gradient(45deg, #00DC82 0%, #36E4DA 50%, #0047E1 100%);filter:blur(20vh);height:40vh;bottom:-30vh}.gradient-border{position:relative;border-radius:0.5rem;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}@media (prefers-color-scheme: light){.gradient-border{background-color:rgba(255, 255, 255, 0.3)}.gradient-border::before{background:linear-gradient(90deg, #e2e2e2 0%, #e2e2e2 25%, #00DC82 50%, #36E4DA 75%, #0047E1 100%)}}@media (prefers-color-scheme: dark){.gradient-border{background-color:rgba(20, 20, 20, 0.3)}.gradient-border::before{background:linear-gradient(90deg, #303030 0%, #303030 25%, #00DC82 50%, #36E4DA 75%, #0047E1 100%)}}.gradient-border::before{content:"";position:absolute;top:0;left:0;right:0;bottom:0;border-radius:0.5rem;padding:2px;width:100%;background-size:400% auto;opacity:0.5;transition:background-position 0.3s ease-in-out, opacity 0.2s ease-in-out;-webkit-mask:linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);mask:linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask-composite:exclude}.gradient-border:hover::before{background-position:-50% 0;opacity:1}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.cursor-pointer{cursor:pointer}.flex{display:-webkit-box;display:-ms-flexbox;display:-webkit-flex;display:flex}.grid{display:-ms-grid;display:grid}.place-content-center{place-content:center}.items-center{-webkit-box-align:center;-ms-flex-align:center;-webkit-align-items:center;align-items:center}.justify-center{-webkit-box-pack:center;-ms-flex-pack:center;-webkit-justify-content:center;justify-content:center}.font-sans{font-family: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-medium{font-weight:500}.font-light{font-weight:300}.text-8xl{font-size:6rem;line-height:1}.text-xl{font-size:1.25rem;line-height:1.75rem}.leading-tight{line-height:1.25}.mb-8{margin-bottom:2rem}.mb-16{margin-bottom:4rem}.max-w-520px{max-width:520px}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.px-8{padding-left:2rem;padding-right:2rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.px-4{padding-left:1rem;padding-right:1rem}.fixed{position:fixed}.left-0{left:0px}.right-0{right:0px}.text-center{text-align:center}.text-black{--tw-text-opacity:1;color:rgba(0,0,0,var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-full{width:100%}.z-10{z-index:10}.z-20{z-index:20}@media (min-width: 640px){.sm\:text-4xl{font-size:2.25rem;line-height:2.5rem}.sm\:text-xl{font-size:1.25rem;line-height:1.75rem}.sm\:text-10xl{font-size:10rem;line-height:1}.sm\:px-0{padding-left:0;padding-right:0}.sm\:py-3{padding-top:.75rem;padding-bottom:.75rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (prefers-color-scheme: dark){.dark\:bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.dark\:text-white{--tw-text-opacity:1;color:rgba(255,255,255,var(--tw-text-opacity))}}
</style>

View File

@@ -0,0 +1,3 @@
export type DefaultMessages = Record<"statusCode" | "statusMessage" | "description", string | boolean | number >
declare const template: (data: Partial<DefaultMessages>) => string
export { template }

View File

@@ -0,0 +1,18 @@
const _messages = {"appName":"Nuxt","version":"","statusCode":500,"statusMessage":"Server error","description":"This page is temporarily unavailable."}
const _render = function({ messages }) {
var __t, __p = '';
__p += '<!DOCTYPE html><html><head><title>' +
((__t = ( messages.statusCode )) == null ? '' : __t) +
' - ' +
((__t = ( messages.statusMessage )) == null ? '' : __t) +
' | ' +
((__t = ( messages.appName )) == null ? '' : __t) +
'</title><meta charset="utf-8"><meta content="width=device-width,initial-scale=1,minimum-scale=1" name="viewport"><style>.spotlight{background:linear-gradient(45deg, #00DC82 0%, #36E4DA 50%, #0047E1 100%);filter:blur(20vh)}*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{margin:0;font-family:inherit;line-height:inherit}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}h1,p{margin:0}h1{font-size:inherit;font-weight:inherit}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.grid{display:-ms-grid;display:grid}.place-content-center{place-content:center}.font-sans{font-family: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-medium{font-weight:500}.font-light{font-weight:300}.h-1\\/2{height:50%}.text-8xl{font-size:6rem;line-height:1}.text-xl{font-size:1.25rem;line-height:1.75rem}.leading-tight{line-height:1.25}.mb-8{margin-bottom:2rem}.mb-16{margin-bottom:4rem}.max-w-520px{max-width:520px}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.px-8{padding-left:2rem;padding-right:2rem}.fixed{position:fixed}.left-0{left:0px}.right-0{right:0px}.-bottom-1\\/2{bottom:-50%}.text-center{text-align:center}.text-black{--tw-text-opacity:1;color:rgba(0,0,0,var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}@media (min-width: 640px){.sm\\:text-4xl{font-size:2.25rem;line-height:2.5rem}.sm\\:text-10xl{font-size:10rem;line-height:1}.sm\\:px-0{padding-left:0;padding-right:0}}@media (prefers-color-scheme: dark){.dark\\:bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.dark\\:text-white{--tw-text-opacity:1;color:rgba(255,255,255,var(--tw-text-opacity))}}</style><script>(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll(\'link[rel="modulepreload"]\'))n(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function i(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerpolicy&&(r.referrerPolicy=e.referrerpolicy),e.crossorigin==="use-credentials"?r.credentials="include":e.crossorigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function n(e){if(e.ep)return;e.ep=!0;const r=i(e);fetch(e.href,r)}})();</script></head><body class="font-sans antialiased bg-white dark:bg-black text-black dark:text-white grid min-h-screen place-content-center overflow-hidden"><div class="fixed -bottom-1/2 left-0 right-0 h-1/2 spotlight"></div><div class="max-w-520px text-center"><h1 class="text-8xl sm:text-10xl font-medium mb-8">' +
((__t = ( messages.statusCode )) == null ? '' : __t) +
'</h1><p class="text-xl px-8 sm:px-0 sm:text-4xl font-light mb-16 leading-tight">' +
((__t = ( messages.description )) == null ? '' : __t) +
'</p></div></body></html>';
return __p
}
const _template = (messages) => _render({ messages: { ..._messages, ...messages } })
export const template = _template

View File

@@ -0,0 +1,40 @@
<script setup>
import { useHead } from '#imports'
const props = defineProps({
appName: {
type: String,
default: "Nuxt"
},
version: {
type: String,
default: ""
},
statusCode: {
type: Number,
default: 500
},
statusMessage: {
type: String,
default: "Server error"
},
description: {
type: String,
default: "This page is temporarily unavailable."
}
})
useHead({
title: `${ props.statusCode } - ${ props.statusMessage } | ${ props.appName }`,
script: [],
style: [
{
children: `*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{margin:0;font-family:inherit;line-height:inherit}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}h1,p{margin:0}h1{font-size:inherit;font-weight:inherit}`
}
]
})
</script>
<template>
<div class="font-sans antialiased bg-white dark:bg-black text-black dark:text-white grid min-h-screen place-content-center overflow-hidden"><div class="fixed -bottom-1/2 left-0 right-0 h-1/2 spotlight"></div><div class="max-w-520px text-center"><h1 class="text-8xl sm:text-10xl font-medium mb-8" v-text="statusCode" /><p class="text-xl px-8 sm:px-0 sm:text-4xl font-light mb-16 leading-tight" v-text="description" /></div></div>
</template>
<style scoped>
.spotlight{background:linear-gradient(45deg, #00DC82 0%, #36E4DA 50%, #0047E1 100%);filter:blur(20vh)}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.grid{display:-ms-grid;display:grid}.place-content-center{place-content:center}.font-sans{font-family: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-medium{font-weight:500}.font-light{font-weight:300}.h-1\/2{height:50%}.text-8xl{font-size:6rem;line-height:1}.text-xl{font-size:1.25rem;line-height:1.75rem}.leading-tight{line-height:1.25}.mb-8{margin-bottom:2rem}.mb-16{margin-bottom:4rem}.max-w-520px{max-width:520px}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.px-8{padding-left:2rem;padding-right:2rem}.fixed{position:fixed}.left-0{left:0px}.right-0{right:0px}.-bottom-1\/2{bottom:-50%}.text-center{text-align:center}.text-black{--tw-text-opacity:1;color:rgba(0,0,0,var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}@media (min-width: 640px){.sm\:text-4xl{font-size:2.25rem;line-height:2.5rem}.sm\:text-10xl{font-size:10rem;line-height:1}.sm\:px-0{padding-left:0;padding-right:0}}@media (prefers-color-scheme: dark){.dark\:bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.dark\:text-white{--tw-text-opacity:1;color:rgba(255,255,255,var(--tw-text-opacity))}}
</style>

View File

@@ -0,0 +1,3 @@
export type DefaultMessages = Record<"statusCode" | "statusMessage" | "description" | "stack", string | boolean | number >
declare const template: (data: Partial<DefaultMessages>) => string
export { template }

View File

@@ -0,0 +1,20 @@
const _messages = {"appName":"Nuxt","version":"","statusCode":500,"statusMessage":"Server error","description":"An error occurred in the application and the page could not be served. If you are the application owner, check your server logs for details.","stack":""}
const _render = function({ messages }) {
var __t, __p = '';
__p += '<!DOCTYPE html><html><head><title>' +
((__t = ( messages.statusCode )) == null ? '' : __t) +
' - ' +
((__t = ( messages.statusMessage )) == null ? '' : __t) +
' | ' +
((__t = ( messages.appName )) == null ? '' : __t) +
'</title><meta charset="utf-8"><meta content="width=device-width,initial-scale=1,minimum-scale=1" name="viewport"><style>.spotlight{background:linear-gradient(45deg, #00DC82 0%, #36E4DA 50%, #0047E1 100%);opacity:0.8;filter:blur(30vh);height:60vh;bottom:-40vh}*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{margin:0;font-family:inherit;line-height:inherit}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}h1,p,pre{margin:0}h1{font-size:inherit;font-weight:inherit}pre{font-size:1em;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.bg-black\\/5{--tw-bg-opacity:.05;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.rounded-t-md{border-top-left-radius:.375rem;border-top-right-radius:.375rem}.flex{display:-webkit-box;display:-ms-flexbox;display:-webkit-flex;display:flex}.flex-col{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;-webkit-flex-direction:column;flex-direction:column}.flex-1{-webkit-box-flex:1;-ms-flex:1 1 0%;-webkit-flex:1 1 0%;flex:1 1 0%}.font-sans{font-family: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-medium{font-weight:500}.font-light{font-weight:300}.h-auto{height:auto}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-6xl{font-size:3.75rem;line-height:1}.leading-tight{line-height:1.25}.mb-8{margin-bottom:2rem}.mb-6{margin-bottom:1.5rem}.min-h-screen{min-height:100vh}.overflow-y-auto{overflow-y:auto}.p-8{padding:2rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.pt-14{padding-top:3.5rem}.fixed{position:fixed}.left-0{left:0px}.right-0{right:0px}.text-black{--tw-text-opacity:1;color:rgba(0,0,0,var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.z-10{z-index:10}@media (min-width: 640px){.sm\\:text-8xl{font-size:6rem;line-height:1}.sm\\:text-2xl{font-size:1.5rem;line-height:2rem}}@media (prefers-color-scheme: dark){.dark\\:bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.dark\\:bg-white\\/10{--tw-bg-opacity:.1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.dark\\:text-white{--tw-text-opacity:1;color:rgba(255,255,255,var(--tw-text-opacity))}}</style><script>(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll(\'link[rel="modulepreload"]\'))n(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&n(o)}).observe(document,{childList:!0,subtree:!0});function i(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerpolicy&&(r.referrerPolicy=e.referrerpolicy),e.crossorigin==="use-credentials"?r.credentials="include":e.crossorigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function n(e){if(e.ep)return;e.ep=!0;const r=i(e);fetch(e.href,r)}})();</script></head><body class="font-sans antialiased bg-white px-10 pt-14 dark:bg-black text-black dark:text-white min-h-screen flex flex-col"><div class="fixed left-0 right-0 spotlight"></div><h1 class="text-6xl sm:text-8xl font-medium mb-6">' +
((__t = ( messages.statusCode )) == null ? '' : __t) +
'</h1><p class="text-xl sm:text-2xl font-light mb-8 leading-tight">' +
((__t = ( messages.description )) == null ? '' : __t) +
'</p><div class="bg-white rounded-t-md bg-black/5 dark:bg-white/10 flex-1 overflow-y-auto h-auto"><pre class="text-xl font-light leading-tight z-10 p-8">' +
((__t = ( messages.stack )) == null ? '' : __t) +
'</pre></div></body></html>';
return __p
}
const _template = (messages) => _render({ messages: { ..._messages, ...messages } })
export const template = _template

View File

@@ -0,0 +1,44 @@
<script setup>
import { useHead } from '#imports'
const props = defineProps({
appName: {
type: String,
default: "Nuxt"
},
version: {
type: String,
default: ""
},
statusCode: {
type: Number,
default: 500
},
statusMessage: {
type: String,
default: "Server error"
},
description: {
type: String,
default: "An error occurred in the application and the page could not be served. If you are the application owner, check your server logs for details."
},
stack: {
type: String,
default: ""
}
})
useHead({
title: `${ props.statusCode } - ${ props.statusMessage } | ${ props.appName }`,
script: [],
style: [
{
children: `*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{margin:0;font-family:inherit;line-height:inherit}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}h1,p,pre{margin:0}h1{font-size:inherit;font-weight:inherit}pre{font-size:1em;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}`
}
]
})
</script>
<template>
<div class="font-sans antialiased bg-white px-10 pt-14 dark:bg-black text-black dark:text-white min-h-screen flex flex-col"><div class="fixed left-0 right-0 spotlight"></div><h1 class="text-6xl sm:text-8xl font-medium mb-6" v-text="statusCode" /><p class="text-xl sm:text-2xl font-light mb-8 leading-tight" v-text="description" /><div class="bg-white rounded-t-md bg-black/5 dark:bg-white/10 flex-1 overflow-y-auto h-auto"><pre class="text-xl font-light leading-tight z-10 p-8" v-html="stack" /></div></div>
</template>
<style scoped>
.spotlight{background:linear-gradient(45deg, #00DC82 0%, #36E4DA 50%, #0047E1 100%);opacity:0.8;filter:blur(30vh);height:60vh;bottom:-40vh}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.bg-black\/5{--tw-bg-opacity:.05;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.rounded-t-md{border-top-left-radius:.375rem;border-top-right-radius:.375rem}.flex{display:-webkit-box;display:-ms-flexbox;display:-webkit-flex;display:flex}.flex-col{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;-webkit-flex-direction:column;flex-direction:column}.flex-1{-webkit-box-flex:1;-ms-flex:1 1 0%;-webkit-flex:1 1 0%;flex:1 1 0%}.font-sans{font-family: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-medium{font-weight:500}.font-light{font-weight:300}.h-auto{height:auto}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-6xl{font-size:3.75rem;line-height:1}.leading-tight{line-height:1.25}.mb-8{margin-bottom:2rem}.mb-6{margin-bottom:1.5rem}.min-h-screen{min-height:100vh}.overflow-y-auto{overflow-y:auto}.p-8{padding:2rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.pt-14{padding-top:3.5rem}.fixed{position:fixed}.left-0{left:0px}.right-0{right:0px}.text-black{--tw-text-opacity:1;color:rgba(0,0,0,var(--tw-text-opacity))}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.z-10{z-index:10}@media (min-width: 640px){.sm\:text-8xl{font-size:6rem;line-height:1}.sm\:text-2xl{font-size:1.5rem;line-height:2rem}}@media (prefers-color-scheme: dark){.dark\:bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}.dark\:bg-white\/10{--tw-bg-opacity:.1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.dark\:text-white{--tw-text-opacity:1;color:rgba(255,255,255,var(--tw-text-opacity))}}
</style>

View File

@@ -0,0 +1,3 @@
export type DefaultMessages = Record<"loading", string | boolean | number >
declare const template: (data: Partial<DefaultMessages>) => string
export { template }

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,128 @@
<script setup>
import { useHead } from '#imports'
const props = defineProps({
appName: {
type: String,
default: "Nuxt"
},
version: {
type: String,
default: ""
},
loading: {
type: String,
default: "Loading"
}
})
useHead({
title: `${ props.loading } | ${ props.appName }`,
script: [
{
children: `let ANIMATION_KEY = 'nuxt-loading-enable-animation'
let isLowPerformance = checkIsLowPerformance()
let enableAnimation = localStorage.getItem(ANIMATION_KEY) === 'false'
? false
: localStorage.getItem(ANIMATION_KEY) === 'true'
? true
: !isLowPerformance
const nuxtImg = window.document.getElementById('nuxtImg')
const animationToggle = window.document.getElementById('animation-toggle')
const body = window.document.body
let bodyRect
function checkIsLowPerformance() {
return window.matchMedia('(prefers-reduced-motion: reduce)').matches
|| navigator.hardwareConcurrency < 2
|| navigator.deviceMemory < 1
}
function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.x + (elem.width / 2)), 2) + Math.pow(mouseY - (elem.top + (elem.height / 2)), 2)));
}
function onFocusOut() {
if (!enableAnimation) {
return
}
mouseLight.style.opacity = 0
nuxtImg.style.opacity = 0.7
}
function onMouseMove(e) {
if (!enableAnimation) {
return
}
const pointerRect = nuxtImg.getBoundingClientRect()
if (!bodyRect) {
bodyRect = body.getBoundingClientRect()
}
const distance = calculateDistance(pointerRect, e.pageX, e.pageY)
const size = Math.max((1000 - distance) / 2 / 100, 1)
mouseLight.style.top = `${e.clientY - bodyRect.y - mouseLight.clientHeight / 2}px`
mouseLight.style.left = `${e.clientX - mouseLight.clientWidth / 2}px`
mouseLight.style.width = mouseLight.style.height = `${Math.max(Math.round(size * 100), 300)}px`
mouseLight.style.filter = `blur(${Math.min(Math.max(size * 50, 100), 160)}px)`
mouseLight.style.opacity = Math.min(Math.max(size / 4, 0.6), 1)
const dx = e.pageX - pointerRect.left
const dy = e.pageY - pointerRect.top
const logoGradient = `radial-gradient(circle at ${dx}px ${dy}px, black 75%, transparent 100%)`
nuxtImg.style['-webkit-mask-image'] = logoGradient
nuxtImg.style['mask-image'] = logoGradient
nuxtImg.style.opacity = Math.min(Math.max(size / 4, 0.7), 1)
}
function toggleAnimation(value = !enableAnimation) {
enableAnimation = value
if (value) {
onFocusOut()
animationToggle.innerText = 'Animation Enabled'
}
else {
mouseLight.style.opacity = 0
nuxtImg.style.opacity = 1
nuxtImg.style['mask-image'] = ''
nuxtImg.style['-webkit-mask-image'] = ''
animationToggle.innerText = 'Animation Disabled'
}
localStorage.setItem(ANIMATION_KEY, enableAnimation ? 'true' : 'false')
}
animationToggle.addEventListener('click', () => toggleAnimation(), { passive: true})
body.addEventListener('mousemove', onMouseMove, { passive: true })
body.addEventListener('mouseleave', onFocusOut, { passive: true })
toggleAnimation(enableAnimation)
if (typeof window.fetch === 'undefined') {
setTimeout(() => window.location.reload(), 1000)
} else {
const check = async () => {
try {
const body = await window
.fetch(window.location.href)
.then(r => r.text())
if (!body.includes('__NUXT_LOADING__')) {
return window
.location
.reload()
}
} catch {}
setTimeout(check, 1000)
}
check()
}`
}
],
style: [
{
children: `;#animation-toggle{position:fixed;padding:10px;top:0;right:0;transition:opacity 0.4s ease-in;opacity:0}#animation-toggle:hover{opacity:0.8}@keyframes gradient{0%{background-position:0 0}100%{background-position:-200% 0}}@media (prefers-color-scheme: dark){html,body{color:white;color-scheme:dark}}*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}a{color:inherit;text-decoration:inherit}body{margin:0;font-family:inherit;line-height:inherit}button{font-family:inherit;font-size:100%;line-height:1.15;margin:0;text-transform:none;background-color:transparent;background-image:none;padding:0;line-height:inherit;color:inherit}button{-webkit-appearance:button}button{cursor:pointer}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}svg{display:block;vertical-align:middle}`
}
]
})
</script>
<template>
<div class="relative overflow-hidden min-h-screen bg-white dark:bg-black flex flex-col justify-center items-center text-center"><div id="mouseLight" class="absolute top-0 rounded-full mouse-gradient transition-opacity h-[200px] w-[200px]"></div><a href="https://nuxt.com" target="_blank" rel="noopener" class="nuxt-logo z-20"><svg id="nuxtImg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 214 53" width="214" height="53" fill="none"><path fill="#00DC82" d="M42.692 50.378h27.773c.882 0 1.75-.225 2.513-.653a4.951 4.951 0 0 0 1.84-1.784 4.76 4.76 0 0 0 .672-2.437c0-.855-.233-1.696-.675-2.436l-18.652-31.33a4.95 4.95 0 0 0-1.838-1.783 5.144 5.144 0 0 0-2.513-.653c-.881 0-1.748.225-2.512.653a4.95 4.95 0 0 0-1.838 1.784l-4.77 8.016L33.368 4.08a4.953 4.953 0 0 0-1.84-1.784 5.148 5.148 0 0 0-2.512-.652c-.882 0-1.749.225-2.513.652a4.954 4.954 0 0 0-1.84 1.784L1.453 43.068a4.758 4.758 0 0 0-.674 2.436c0 .855.232 1.696.673 2.437a4.95 4.95 0 0 0 1.839 1.784c.764.428 1.63.653 2.512.653h17.434c6.907 0 12.001-2.943 15.506-8.683l8.51-14.292 4.558-7.648 13.68 22.974H47.253l-4.56 7.649Zm-19.74-7.657-12.166-.002 18.238-30.631 9.1 15.315L32.03 37.64c-2.328 3.724-4.972 5.081-9.078 5.081Z"></path><path fill="currentColor" d="M86.928 49.32V8.75h9.276l11.942 19.648c1.739 2.859 3.381 5.989 4.927 9.389-.386-3.748-.579-7.284-.579-10.607V8.75h8.753v40.57h-9.333L100.03 29.673c-1.778-2.86-3.44-5.97-4.986-9.331.387 3.709.58 7.225.58 10.548v18.43H86.93ZM155.782 20.11v29.21h-8.116v-4.057c-.811 1.391-2.01 2.492-3.594 3.304-1.546.811-3.304 1.217-5.275 1.217-2.165 0-4.058-.483-5.682-1.449-1.623-1.005-2.898-2.376-3.826-4.115-.889-1.739-1.333-3.71-1.333-5.912V20.11h8.058v16.402c0 1.777.522 3.245 1.565 4.404 1.044 1.121 2.396 1.681 4.058 1.681 1.739 0 3.169-.618 4.29-1.854 1.159-1.237 1.739-2.782 1.739-4.637V20.11h8.116ZM178.224 34.135l10.493 15.185h-8.58l-6.261-8.983-6.319 8.983h-8.637l10.55-15.242-9.797-13.968h8.812l5.333 7.708 5.334-7.708h8.869l-9.797 14.025ZM195.921 11.474h8.058v8.636h7.826v6.723h-7.826v11.533c0 2.782 1.372 4.173 4.116 4.173h3.71v6.781h-4.812c-3.401 0-6.106-.927-8.116-2.782-1.971-1.854-2.956-4.462-2.956-7.824V26.833h-5.623V20.11h5.623v-8.636Z"></path></svg> </a><button id="animation-toggle">Animation Enabled</button><div class="spotlight-wrapper"><div class="fixed left-0 right-0 spotlight spotlight-top z-10"></div></div><div class="spotlight-wrapper"><div class="fixed left-0 right-0 spotlight spotlight-bottom z-q0"></div></div><div class="nuxt-loader-bar"></div></div>
</template>
<style scoped>
.spotlight{filter:blur(20vh);height:50vh}.spotlight-wrapper{opacity:0.5;transition:opacity 0.4s ease-in}.nuxt-loader-bar{background:repeating-linear-gradient(to right, #36E4DA 0%, #1DE0B1 25%, #00DC82 50%, #1DE0B1 75%, #36E4DA 100%);height:100px;background-size:200% auto;background-position:0 0;animation:gradient 2s infinite;animation-fill-mode:forwards;animation-timing-function:linear;filter:blur(100px);position:fixed;bottom:-50px;left:-50px;right:-50px}.mouse-gradient{background:repeating-linear-gradient(to right, #00DC82 0%, #1DE0B1 50%, #36E4DA 100%);filter:blur(100px);opacity:0.5}#animation-toggle{position:fixed;padding:10px;top:0;right:0;transition:opacity 0.4s ease-in;opacity:0}#animation-toggle:hover{opacity:0.8}@keyframes gradient{0%{background-position:0 0}100%{background-position:-200% 0}}@media (prefers-color-scheme: dark){html,body{color:white;color-scheme:dark}.nuxt-loader-bar{opacity:0.5}}*,:before,:after{-webkit-box-sizing:border-box;box-sizing:border-box;border-width:0;border-style:solid;border-color:#e0e0e0}*{--tw-ring-inset:var(--tw-empty, );--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(14, 165, 233, .5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000}:root{-moz-tab-size:4;-o-tab-size:4;tab-size:4}a{color:inherit;text-decoration:inherit}body{margin:0;font-family:inherit;line-height:inherit}button{font-family:inherit;font-size:100%;line-height:1.15;margin:0;text-transform:none;background-color:transparent;background-image:none;padding:0;line-height:inherit;color:inherit}button{-webkit-appearance:button}button{cursor:pointer}html{-webkit-text-size-adjust:100%;font-family: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";line-height:1.5}svg{display:block;vertical-align:middle}.bg-white{--tw-bg-opacity:1;background-color:rgba(255,255,255,var(--tw-bg-opacity))}.rounded-full{border-radius:9999px}.flex{display:-webkit-box;display:-ms-flexbox;display:-webkit-flex;display:flex}.flex-col{-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;-webkit-flex-direction:column;flex-direction:column}.items-center{-webkit-box-align:center;-ms-flex-align:center;-webkit-align-items:center;align-items:center}.justify-center{-webkit-box-pack:center;-ms-flex-pack:center;-webkit-justify-content:center;justify-content:center}.h-\[200px\]{height:200px}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.left-0{left:0px}.right-0{right:0px}.top-0{top:0px}.text-center{text-align:center}.w-\[200px\]{width:200px}.z-10{z-index:10}.z-20{z-index:20}.transition-opacity{-webkit-transition-property:opacity;-o-transition-property:opacity;transition-property:opacity;-webkit-transition-timing-function:cubic-bezier(.4,0,.2,1);-o-transition-timing-function:cubic-bezier(.4,0,.2,1);transition-timing-function:cubic-bezier(.4,0,.2,1);-webkit-transition-duration:.15s;-o-transition-duration:.15s;transition-duration:.15s}@media (prefers-color-scheme: dark){.dark\:bg-black{--tw-bg-opacity:1;background-color:rgba(0,0,0,var(--tw-bg-opacity))}}
</style>

View File

@@ -0,0 +1,3 @@
export type DefaultMessages = Record<"title" | "readDocs" | "followTwitter" | "starGitHub", string | boolean | number >
declare const template: (data: Partial<DefaultMessages>) => string
export { template }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

46
node_modules/@nuxt/ui-templates/package.json generated vendored Normal file
View File

@@ -0,0 +1,46 @@
{
"name": "@nuxt/ui-templates",
"version": "1.0.0",
"repository": "nuxt/ui",
"license": "CC-BY-ND-4.0",
"exports": {
"./templates/*": "./dist/templates/*",
".": "./dist/index.mjs",
"./*": "./dist/*"
},
"main": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist/templates/*",
"dist/index.*"
],
"scripts": {
"build": "vite build",
"dev": "vite",
"lint": "eslint --ext .ts,.js .",
"optimize-assets": "npx svgo public/assets/**/*.svg",
"prepack": "pnpm build",
"prerender": "pnpm build && jiti ./lib/prerender",
"test": "pnpm lint && pnpm build"
},
"devDependencies": {
"@nuxt/ui-assets": "^0.1.0",
"@types/html-minifier": "^4.0.2",
"@types/lodash.template": "^4.5.1",
"critters": "^0.0.16",
"execa": "^6.1.0",
"globby": "^13.1.2",
"html-minifier": "^4.0.0",
"jiti": "^1.16.0",
"knitwork": "^1.0.0",
"lodash.template": "^4.5.0",
"scule": "^1.0.0",
"upath": "^2.0.1",
"vite": "^3.2.4",
"vite-plugin-windicss": "^1.8.8",
"windicss": "^3.5.6"
},
"publishConfig": {
"access": "public"
}
}

21
node_modules/@nuxt/vite-builder/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 - Nuxt Project
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.

5
node_modules/@nuxt/vite-builder/README.md generated vendored Normal file
View File

@@ -0,0 +1,5 @@
# Nuxt Vite Builder
> [Vite](https://vitejs.dev) bundler for Nuxt 3.
Learn more about this package: <https://v3.nuxtjs.org>

View File

@@ -0,0 +1,31 @@
import { transform } from 'esbuild';
import { visualizer } from 'rollup-plugin-visualizer';
function analyzePlugin(ctx) {
return [
{
name: "nuxt:analyze-minify",
async generateBundle(_opts, outputBundle) {
for (const [_bundleId, bundle] of Object.entries(outputBundle)) {
if (bundle.type !== "chunk") {
continue;
}
const originalEntries = Object.entries(bundle.modules);
const minifiedEntries = await Promise.all(originalEntries.map(async ([moduleId, module]) => {
const { code } = await transform(module.code || "", { minify: true });
return [moduleId, { ...module, code }];
}));
bundle.modules = Object.fromEntries(minifiedEntries);
}
}
},
visualizer({
...ctx.nuxt.options.build.analyze,
filename: ctx.nuxt.options.build.analyze.filename.replace("{name}", "client"),
title: "Client bundle stats",
gzipSize: true
})
];
}
export { analyzePlugin };

View File

@@ -0,0 +1,226 @@
import { pathToFileURL } from 'node:url';
import { existsSync } from 'node:fs';
import { builtinModules } from 'node:module';
import { normalize, resolve, isAbsolute } from 'pathe';
import { genObjectFromRawEntries, genDynamicImport } from 'knitwork';
import fse from 'fs-extra';
import { debounce } from 'perfect-debounce';
import { isIgnored, logger } from '@nuxt/kit';
import { h as hashId, c as createIsExternal, u as uniq, w as writeManifest, i as isCSS } from '../shared/vite-builder.1c88b3ee.mjs';
import 'vite';
import '@rollup/plugin-replace';
import 'mlly';
import 'ufo';
import 'pathe/utils';
import 'pkg-types';
import '@vitejs/plugin-vue';
import '@vitejs/plugin-vue-jsx';
import 'get-port-please';
import 'defu';
import 'h3';
import 'ohash';
import 'vite-node/server';
import 'vue-bundle-renderer';
import 'externality';
import 'escape-string-regexp';
import 'unplugin';
import 'estree-walker';
import 'magic-string';
async function transformRequest(opts, id) {
if (id && id.startsWith("/@id/__x00__")) {
id = "\0" + id.slice("/@id/__x00__".length);
}
if (id && id.startsWith("/@id/")) {
id = id.slice("/@id/".length);
}
if (id && !id.startsWith("/@fs/") && id.startsWith("/")) {
const resolvedPath = resolve(opts.viteServer.config.root, "." + id);
if (existsSync(resolvedPath)) {
id = resolvedPath;
}
}
id = id.replace(/^\/?(?=\w:)/, "/@fs/");
const externalId = id.replace(/\?v=\w+$|^\/@fs/, "");
if (await opts.isExternal(externalId)) {
const path = builtinModules.includes(externalId.split("node:").pop()) ? externalId : isAbsolute(externalId) ? pathToFileURL(externalId).href : externalId;
return {
code: `(global, module, _, exports, importMeta, ssrImport, ssrDynamicImport, ssrExportAll) =>
${genDynamicImport(path, { wrapper: false })}
.then(r => {
if (r.default && r.default.__esModule)
r = r.default
exports.default = r.default
ssrExportAll(r)
})
.catch(e => {
console.error(e)
throw new Error(${JSON.stringify(`[vite dev] Error loading external "${id}".`)})
})`,
deps: [],
dynamicDeps: []
};
}
const res = await opts.viteServer.transformRequest(id, { ssr: true }).catch((err) => {
console.warn(`[SSR] Error transforming ${id}:`, err);
}) || { code: "", map: {}, deps: [], dynamicDeps: [] };
const code = `async function (global, module, exports, __vite_ssr_exports__, __vite_ssr_import_meta__, __vite_ssr_import__, __vite_ssr_dynamic_import__, __vite_ssr_exportAll__) {
${res.code || "/* empty */"};
}`;
return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] };
}
async function transformRequestRecursive(opts, id, parent = "<entry>", chunks = {}) {
if (chunks[id]) {
chunks[id].parents.push(parent);
return;
}
const res = await transformRequest(opts, id);
const deps = uniq([...res.deps, ...res.dynamicDeps]);
chunks[id] = {
id,
code: res.code,
deps,
parents: [parent]
};
for (const dep of deps) {
await transformRequestRecursive(opts, dep, id, chunks);
}
return Object.values(chunks);
}
async function bundleRequest(opts, entryURL) {
const chunks = await transformRequestRecursive(opts, entryURL);
const listIds = (ids) => ids.map((id) => `// - ${id} (${hashId(id)})`).join("\n");
const chunksCode = chunks.map((chunk) => `
// --------------------
// Request: ${chunk.id}
// Parents:
${listIds(chunk.parents)}
// Dependencies:
${listIds(chunk.deps)}
// --------------------
const ${hashId(chunk.id + "-" + chunk.code)} = ${chunk.code}
`).join("\n");
const manifestCode = `const __modules__ = ${genObjectFromRawEntries(chunks.map((chunk) => [chunk.id, hashId(chunk.id + "-" + chunk.code)]))}`;
const ssrModuleLoader = `
const __pendingModules__ = new Map()
const __pendingImports__ = new Map()
const __ssrContext__ = { global: globalThis }
function __ssrLoadModule__(url, urlStack = []) {
const pendingModule = __pendingModules__.get(url)
if (pendingModule) { return pendingModule }
const modulePromise = __instantiateModule__(url, urlStack)
__pendingModules__.set(url, modulePromise)
modulePromise.catch(() => { __pendingModules__.delete(url) })
.finally(() => { __pendingModules__.delete(url) })
return modulePromise
}
async function __instantiateModule__(url, urlStack) {
const mod = __modules__[url]
if (mod.stubModule) { return mod.stubModule }
const stubModule = { [Symbol.toStringTag]: 'Module' }
Object.defineProperty(stubModule, '__esModule', { value: true })
mod.stubModule = stubModule
// https://vitejs.dev/guide/api-hmr.html
const importMeta = { url, hot: { accept() {}, prune() {}, dispose() {}, invalidate() {}, decline() {}, on() {} } }
urlStack = urlStack.concat(url)
const isCircular = url => urlStack.includes(url)
const pendingDeps = []
const ssrImport = async (dep) => {
// TODO: Handle externals if dep[0] !== '.' | '/'
if (!isCircular(dep) && !__pendingImports__.get(dep)?.some(isCircular)) {
pendingDeps.push(dep)
if (pendingDeps.length === 1) {
__pendingImports__.set(url, pendingDeps)
}
await __ssrLoadModule__(dep, urlStack)
if (pendingDeps.length === 1) {
__pendingImports__.delete(url)
} else {
pendingDeps.splice(pendingDeps.indexOf(dep), 1)
}
}
return __modules__[dep].stubModule
}
function ssrDynamicImport (dep) {
// TODO: Handle dynamic import starting with . relative to url
return ssrImport(dep)
}
function ssrExportAll(sourceModule) {
for (const key in sourceModule) {
if (key !== 'default') {
try {
Object.defineProperty(stubModule, key, {
enumerable: true,
configurable: true,
get() { return sourceModule[key] }
})
} catch (_err) { }
}
}
}
const cjsModule = {
get exports () {
return stubModule.default
},
set exports (v) {
stubModule.default = v
},
}
await mod(
__ssrContext__.global,
cjsModule,
stubModule.default,
stubModule,
importMeta,
ssrImport,
ssrDynamicImport,
ssrExportAll
)
return stubModule
}
`;
const code = [
chunksCode,
manifestCode,
ssrModuleLoader,
`export default await __ssrLoadModule__(${JSON.stringify(entryURL)})`
].join("\n\n");
return {
code,
ids: chunks.map((i) => i.id)
};
}
async function initViteDevBundler(ctx, onBuild) {
const viteServer = ctx.ssrServer;
const options = {
viteServer,
isExternal: createIsExternal(viteServer, ctx.nuxt.options.rootDir)
};
const _doBuild = async () => {
const start = Date.now();
const { code, ids } = await bundleRequest(options, ctx.entry);
await fse.writeFile(resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"), code, "utf-8");
await writeManifest(ctx, ids.filter(isCSS).map((i) => i.slice(1)));
const time = Date.now() - start;
logger.success(`Vite server built in ${time}ms`);
await onBuild();
};
const doBuild = debounce(_doBuild);
await _doBuild();
viteServer.watcher.on("all", (_event, file) => {
file = normalize(file);
if (file.indexOf(ctx.nuxt.options.buildDir) === 0 || isIgnored(file)) {
return;
}
doBuild();
});
ctx.nuxt.hook("app:templatesGenerated", () => doBuild());
}
export { bundleRequest, initViteDevBundler };

20
node_modules/@nuxt/vite-builder/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import * as vite from 'vite';
import { InlineConfig, SSROptions } from 'vite';
import { Nuxt } from '@nuxt/schema';
import { Options } from '@vitejs/plugin-vue';
interface ViteOptions extends InlineConfig {
vue?: Options;
ssr?: SSROptions;
devBundler?: 'vite-node' | 'legacy';
}
interface ViteBuildContext {
nuxt: Nuxt;
config: ViteOptions;
entry: string;
clientServer?: vite.ViteDevServer;
ssrServer?: vite.ViteDevServer;
}
declare function bundle(nuxt: Nuxt): Promise<void>;
export { ViteBuildContext, ViteOptions, bundle };

26
node_modules/@nuxt/vite-builder/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,26 @@
export { b as bundle } from './shared/vite-builder.1c88b3ee.mjs';
import 'vite';
import 'pathe';
import '@nuxt/kit';
import '@rollup/plugin-replace';
import 'mlly';
import 'ufo';
import 'pathe/utils';
import 'pkg-types';
import '@vitejs/plugin-vue';
import '@vitejs/plugin-vue-jsx';
import 'get-port-please';
import 'defu';
import 'h3';
import 'node:fs';
import 'ohash';
import 'node:url';
import 'vite-node/server';
import 'fs-extra';
import 'vue-bundle-renderer';
import 'externality';
import 'knitwork';
import 'escape-string-regexp';
import 'unplugin';
import 'estree-walker';
import 'magic-string';

View File

@@ -0,0 +1,2 @@
declare function _default(): Promise<any>;
export default _default;

View File

@@ -0,0 +1,3 @@
import { viteNodeFetch } from './vite-node-shared.mjs'
export default () => viteNodeFetch('/manifest')

View File

@@ -0,0 +1,2 @@
export const viteNodeOptions: any;
export const viteNodeFetch: import("ofetch/dist/error-8a55452d").$;

View File

@@ -0,0 +1,8 @@
export interface ViteNodeRuntimeOptions {
baseURL: string,
rootDir: string,
entryPath: string,
base: string
}
export function getViteNodeOptions (): ViteNodeRuntimeOptions

View File

@@ -0,0 +1,11 @@
import { Agent as HTTPSAgent } from 'node:https'
import { $fetch } from 'ofetch'
export const viteNodeOptions = JSON.parse(process.env.NUXT_VITE_NODE_OPTIONS || '{}')
export const viteNodeFetch = $fetch.create({
baseURL: viteNodeOptions.baseURL,
agent: viteNodeOptions.baseURL.startsWith('https://')
? new HTTPSAgent({ rejectUnauthorized: false })
: null
})

View File

@@ -0,0 +1,2 @@
declare function _default(ssrContext: any): Promise<any>;
export default _default;

View File

@@ -0,0 +1,99 @@
import { performance } from 'node:perf_hooks'
import { createError } from 'h3'
import { ViteNodeRunner } from 'vite-node/client'
import consola from 'consola'
import { viteNodeOptions, viteNodeFetch } from './vite-node-shared.mjs'
const runner = createRunner()
let render
export default async (ssrContext) => {
// Workaround for stub mode
// https://github.com/nuxt/framework/pull/3983
process.server = true
// Invalidate cache for files changed since last rendering
const invalidates = await viteNodeFetch('/invalidates')
const updates = runner.moduleCache.invalidateDepTree(invalidates)
// Execute SSR bundle on demand
const start = performance.now()
render = (updates.has(viteNodeOptions.entryPath) || !render) ? (await runner.executeFile(viteNodeOptions.entryPath)).default : render
if (updates.size) {
const time = Math.round((performance.now() - start) * 1000) / 1000
consola.success(`Vite server hmr ${updates.size} files`, time ? `in ${time}ms` : '')
}
const result = await render(ssrContext)
return result
}
function createRunner () {
const _importers = new Map()
return new ViteNodeRunner({
root: viteNodeOptions.root, // Equals to Nuxt `srcDir`
base: viteNodeOptions.base,
resolveId (id, importer) { _importers.set(id, importer) },
async fetchModule (id) {
const importer = _importers.get(id)
_importers.delete(id)
id = id.replace(/\/\//g, '/') // TODO: fix in vite-node
return await viteNodeFetch('/module/' + encodeURI(id)).catch((err) => {
const errorData = err?.data?.data
if (!errorData) {
throw err
}
let _err
try {
const { message, stack } = formatViteError(errorData, id, importer)
_err = createError({
statusMessage: 'Vite Error',
message,
stack
})
} catch (formatError) {
consola.warn('Internal nuxt error while formatting vite-node error. Please report this!', formatError)
const message = `[vite-node] [TransformError] ${errorData?.message || '-'}`
consola.error(message, errorData)
throw createError({
statusMessage: 'Vite Error',
message,
stack: `${message}\nat ${id}\n` + (errorData?.stack || '')
})
}
throw _err
})
}
})
}
function formatViteError (errorData, id, importer) {
const errorCode = errorData.name || errorData.reasonCode || errorData.code
const frame = errorData.frame || errorData.source || errorData.pluginCode
const getLocId = (locObj = {}) => locObj.file || locObj.id || locObj.url || id || ''
const getLocPos = (locObj = {}) => locObj.line ? `${locObj.line}:${locObj.column || 0}` : ''
const locId = getLocId(errorData.loc) || getLocId(errorData.location) || getLocId(errorData.input) || getLocId(errorData)
const locPos = getLocPos(errorData.loc) || getLocPos(errorData.location) || getLocPos(errorData.input) || getLocPos(errorData)
const loc = locId.replace(process.cwd(), '.') + (locPos ? `:${locPos}` : '')
const message = [
'[vite-node]',
errorData.plugin && `[plugin:${errorData.plugin}]`,
errorCode && `[${errorCode}]`,
loc,
errorData.reason && `: ${errorData.reason}`,
frame && `<br><pre>${frame.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre><br>`
].filter(Boolean).join(' ')
const stack = [
message,
`at ${loc} ${importer ? `(imported from ${importer})` : ''}`,
errorData.stack
].filter(Boolean).join('\n')
return {
message,
stack
}
}

View File

@@ -0,0 +1,842 @@
import * as vite from 'vite';
import { resolve, dirname, join, relative, isAbsolute } from 'pathe';
import { logger, resolveModule, requireModule, resolvePath, isIgnored, addVitePlugin } from '@nuxt/kit';
import replace from '@rollup/plugin-replace';
import { resolve as resolve$1, findStaticImports, sanitizeFilePath } from 'mlly';
import { joinURL, withoutLeadingSlash, parseURL, parseQuery, withTrailingSlash } from 'ufo';
import { filename } from 'pathe/utils';
import { resolveTSConfig } from 'pkg-types';
import vuePlugin from '@vitejs/plugin-vue';
import viteJsxPlugin from '@vitejs/plugin-vue-jsx';
import { getPort } from 'get-port-please';
import defu from 'defu';
import { toNodeListener, createApp, defineEventHandler, defineLazyEventHandler, eventHandler, createError } from 'h3';
import 'node:fs';
import { hash } from 'ohash';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { ViteNodeServer } from 'vite-node/server';
import fse from 'fs-extra';
import { normalizeViteManifest } from 'vue-bundle-renderer';
import { ExternalsDefaults, isExternal } from 'externality';
import { genObjectFromRawEntries } from 'knitwork';
import escapeRE from 'escape-string-regexp';
import { createUnplugin } from 'unplugin';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
function cacheDirPlugin(rootDir, name) {
const optimizeCacheDir = resolve(rootDir, "node_modules/.cache/vite", name);
return {
name: "nuxt:cache-dir",
configResolved(resolvedConfig) {
resolvedConfig.optimizeCacheDir = optimizeCacheDir;
}
};
}
function uniq(arr) {
return Array.from(new Set(arr));
}
const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/;
function isCSS(file) {
return IS_CSS_RE.test(file);
}
function hashId(id) {
return "$id_" + hash(id);
}
function devStyleSSRPlugin(options) {
return {
name: "nuxt:dev-style-ssr",
apply: "serve",
enforce: "post",
transform(code, id) {
if (!isCSS(id) || !code.includes("import.meta.hot")) {
return;
}
let moduleId = id;
if (moduleId.startsWith(options.srcDir)) {
moduleId = moduleId.slice(options.srcDir.length);
}
const selector = joinURL(options.buildAssetsURL, moduleId);
return code + `
document.querySelectorAll(\`link[href="${selector}"]\`).forEach(i=>i.remove())`;
}
};
}
let _distDir = dirname(fileURLToPath(import.meta.url));
if (_distDir.match(/(chunks|shared)$/)) {
_distDir = dirname(_distDir);
}
const distDir = _distDir;
resolve(distDir, "..");
function createIsExternal(viteServer, rootDir) {
const externalOpts = {
inline: [
/virtual:/,
/\.ts$/,
...ExternalsDefaults.inline || [],
...viteServer.config.ssr.noExternal
],
external: [
...viteServer.config.ssr.external || [],
/node_modules/
],
resolve: {
type: "module",
extensions: [".ts", ".js", ".json", ".vue", ".mjs", ".jsx", ".tsx", ".wasm"]
}
};
return (id) => isExternal(id, rootDir, externalOpts);
}
function viteNodePlugin(ctx) {
const invalidates = /* @__PURE__ */ new Set();
function markInvalidate(mod) {
if (!mod.id) {
return;
}
if (invalidates.has(mod.id)) {
return;
}
invalidates.add(mod.id);
for (const importer of mod.importers) {
markInvalidate(importer);
}
}
return {
name: "nuxt:vite-node-server",
enforce: "post",
configureServer(server) {
server.middlewares.use("/__nuxt_vite_node__", toNodeListener(createViteNodeApp(ctx, invalidates)));
ctx.nuxt.hook("app:templatesGenerated", () => {
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
if (id.startsWith("virtual:")) {
markInvalidate(mod);
}
}
});
},
handleHotUpdate({ file, server }) {
const mods = server.moduleGraph.getModulesByFile(file) || [];
for (const mod of mods) {
markInvalidate(mod);
}
}
};
}
function getManifest(ctx) {
const css = Array.from(ctx.ssrServer.moduleGraph.urlToModuleMap.keys()).filter((i) => isCSS(i));
const manifest = normalizeViteManifest({
"@vite/client": {
file: "@vite/client",
css,
module: true,
isEntry: true
},
[ctx.entry]: {
file: ctx.entry,
isEntry: true,
module: true,
resourceType: "script"
}
});
return manifest;
}
function createViteNodeApp(ctx, invalidates = /* @__PURE__ */ new Set()) {
const app = createApp();
app.use("/manifest", defineEventHandler(() => {
const manifest = getManifest(ctx);
return manifest;
}));
app.use("/invalidates", defineEventHandler(() => {
const ids = Array.from(invalidates);
invalidates.clear();
return ids;
}));
app.use("/module", defineLazyEventHandler(() => {
const viteServer = ctx.ssrServer;
const node = new ViteNodeServer(viteServer, {
deps: {
inline: [
/\/(nuxt|nuxt3)\//,
/^#/,
...ctx.nuxt.options.build.transpile
]
},
transformMode: {
ssr: [/.*/],
web: []
}
});
const isExternal = createIsExternal(viteServer, ctx.nuxt.options.rootDir);
node.shouldExternalize = async (id) => {
const result = await isExternal(id);
if (result?.external) {
return resolve$1(result.id, { url: ctx.nuxt.options.modulesDir });
}
return false;
};
return eventHandler(async (event) => {
const moduleId = decodeURI(event.node.req.url).substring(1);
if (moduleId === "/") {
throw createError({ statusCode: 400 });
}
const module = await node.fetchModule(moduleId).catch((err) => {
const errorData = {
code: "VITE_ERROR",
id: moduleId,
stack: "",
...err
};
throw createError({ data: errorData });
});
return module;
});
}));
return app;
}
async function initViteNodeServer(ctx) {
const viteNodeServerOptions = {
baseURL: `${ctx.nuxt.options.devServer.url}__nuxt_vite_node__`,
root: ctx.nuxt.options.srcDir,
entryPath: ctx.entry,
base: ctx.ssrServer.config.base || "/_nuxt/"
};
process.env.NUXT_VITE_NODE_OPTIONS = JSON.stringify(viteNodeServerOptions);
const serverResolvedPath = resolve(distDir, "runtime/vite-node.mjs");
const manifestResolvedPath = resolve(distDir, "runtime/client.manifest.mjs");
await fse.writeFile(
resolve(ctx.nuxt.options.buildDir, "dist/server/server.mjs"),
`export { default } from ${JSON.stringify(pathToFileURL(serverResolvedPath).href)}`
);
await fse.writeFile(
resolve(ctx.nuxt.options.buildDir, "dist/server/client.manifest.mjs"),
`export { default } from ${JSON.stringify(pathToFileURL(manifestResolvedPath).href)}`
);
}
async function buildClient(ctx) {
const clientConfig = vite.mergeConfig(ctx.config, {
entry: ctx.entry,
base: ctx.nuxt.options.dev ? joinURL(ctx.nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", ctx.nuxt.options.app.buildAssetsDir) : "./",
experimental: {
renderBuiltUrl: (filename, { type, hostType }) => {
if (hostType !== "js" || type === "asset") {
return { relative: true };
}
return { runtime: `globalThis.__publicAssetsURL(${JSON.stringify(filename)})` };
}
},
define: {
"process.server": false,
"process.client": true,
"module.hot": false
},
optimizeDeps: {
entries: [ctx.entry]
},
resolve: {
alias: {
"#build/plugins": resolve(ctx.nuxt.options.buildDir, "plugins/client"),
"#internal/nitro": resolve(ctx.nuxt.options.buildDir, "nitro.client.mjs")
},
dedupe: ["vue"]
},
build: {
sourcemap: ctx.nuxt.options.sourcemap.client ? ctx.config.build?.sourcemap ?? true : false,
manifest: true,
outDir: resolve(ctx.nuxt.options.buildDir, "dist/client"),
rollupOptions: {
input: ctx.entry
}
},
plugins: [
cacheDirPlugin(ctx.nuxt.options.rootDir, "client"),
vuePlugin(ctx.config.vue),
viteJsxPlugin(),
devStyleSSRPlugin({
srcDir: ctx.nuxt.options.srcDir,
buildAssetsURL: joinURL(ctx.nuxt.options.app.baseURL, ctx.nuxt.options.app.buildAssetsDir)
}),
viteNodePlugin(ctx)
],
appType: "custom",
server: {
middlewareMode: true
}
});
if (!ctx.nuxt.options.dev) {
clientConfig.server.hmr = false;
}
clientConfig.build.rollupOptions = defu(clientConfig.build.rollupOptions, {
output: {
chunkFileNames: ctx.nuxt.options.dev ? void 0 : withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, "[name].[hash].js")),
entryFileNames: ctx.nuxt.options.dev ? "entry.js" : withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, "[name].[hash].js"))
}
});
if (clientConfig.server && clientConfig.server.hmr !== false) {
const hmrPortDefault = 24678;
const hmrPort = await getPort({
port: hmrPortDefault,
ports: Array.from({ length: 20 }, (_, i) => hmrPortDefault + 1 + i)
});
clientConfig.server = defu(clientConfig.server, {
https: ctx.nuxt.options.devServer.https,
hmr: {
protocol: ctx.nuxt.options.devServer.https ? "wss" : "ws",
port: hmrPort
}
});
}
if (ctx.nuxt.options.build.analyze) {
clientConfig.plugins.push(...await import('../chunks/analyze.mjs').then((r) => r.analyzePlugin(ctx)));
}
await ctx.nuxt.callHook("vite:extendConfig", clientConfig, { isClient: true, isServer: false });
if (ctx.nuxt.options.dev) {
const viteServer = await vite.createServer(clientConfig);
ctx.clientServer = viteServer;
await ctx.nuxt.callHook("vite:serverCreated", viteServer, { isClient: true, isServer: false });
const viteRoutes = viteServer.middlewares.stack.map((m) => m.route).filter((r) => r.length > 1);
const viteMiddleware = defineEventHandler(async (event) => {
const originalURL = event.node.req.url;
if (!viteRoutes.some((route) => originalURL.startsWith(route)) && !originalURL.startsWith(clientConfig.base)) {
event.node.req.url = joinURL("/__url", originalURL);
}
await new Promise((resolve2, reject) => {
viteServer.middlewares.handle(event.node.req, event.node.res, (err) => {
event.node.req.url = originalURL;
return err ? reject(err) : resolve2(null);
});
});
});
await ctx.nuxt.callHook("server:devHandler", viteMiddleware);
ctx.nuxt.hook("close", async () => {
await viteServer.close();
});
} else {
const start = Date.now();
await vite.build(clientConfig);
await ctx.nuxt.callHook("vite:compiled");
logger.info(`Client built in ${Date.now() - start}ms`);
}
}
function ssrStylesPlugin(options) {
const cssMap = {};
const idRefMap = {};
const relativeToSrcDir = (path) => relative(options.srcDir, path);
const warnCache = /* @__PURE__ */ new Set();
return {
name: "ssr-styles",
generateBundle(outputOptions) {
const emitted = {};
for (const file in cssMap) {
const { files, inBundle } = cssMap[file];
if (!files.length || !inBundle) {
continue;
}
const base = typeof outputOptions.assetFileNames === "string" ? outputOptions.assetFileNames : outputOptions.assetFileNames({
type: "asset",
name: `${filename(file)}-styles.mjs`,
source: ""
});
emitted[file] = this.emitFile({
type: "asset",
name: `${filename(file)}-styles.mjs`,
source: [
...files.map((css, i) => `import style_${i} from './${relative(dirname(base), this.getFileName(css))}';`),
`export default [${files.map((_, i) => `style_${i}`).join(", ")}]`
].join("\n")
});
}
for (const key in emitted) {
options.chunksWithInlinedCSS.add(key);
}
this.emitFile({
type: "asset",
fileName: "styles.mjs",
source: [
"const interopDefault = r => r.default || r || []",
`export default ${genObjectFromRawEntries(
Object.entries(emitted).map(([key, value]) => [key, `() => import('./${this.getFileName(value)}').then(interopDefault)`])
)}`
].join("\n")
});
},
renderChunk(_code, chunk) {
if (!chunk.facadeModuleId) {
return null;
}
const id = relativeToSrcDir(chunk.facadeModuleId);
for (const file in chunk.modules) {
const relativePath = relativeToSrcDir(file);
if (relativePath in cssMap) {
cssMap[relativePath].inBundle = cssMap[relativePath].inBundle ?? !!id;
}
}
return null;
},
async transform(code, id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
const query = parseQuery(search);
if (!pathname.match(/\.(vue|((c|m)?j|t)sx?)$/g) || query.macro) {
return;
}
if (options.shouldInline && !options.shouldInline(id)) {
return;
}
const relativeId = relativeToSrcDir(id);
cssMap[relativeId] = cssMap[relativeId] || { files: [] };
let styleCtr = 0;
for (const i of findStaticImports(code)) {
const { type } = parseQuery(i.specifier);
if (type !== "style" && !i.specifier.endsWith(".css")) {
continue;
}
const resolved = await this.resolve(i.specifier, id);
if (!resolved) {
continue;
}
if (!await this.resolve(resolved.id + "?inline&used")) {
if (!warnCache.has(resolved.id)) {
warnCache.add(resolved.id);
this.warn(`[nuxt] Cannot extract styles for \`${i.specifier}\`. Its styles will not be inlined when server-rendering.`);
}
continue;
}
const ref = this.emitFile({
type: "chunk",
name: `${filename(id)}-styles-${++styleCtr}.mjs`,
id: resolved.id + "?inline&used"
});
idRefMap[relativeToSrcDir(resolved.id)] = ref;
cssMap[relativeId].files.push(ref);
}
}
};
}
async function writeManifest(ctx, css = []) {
const clientDist = resolve(ctx.nuxt.options.buildDir, "dist/client");
const serverDist = resolve(ctx.nuxt.options.buildDir, "dist/server");
const devClientManifest = {
"@vite/client": {
isEntry: true,
file: "@vite/client",
css,
module: true,
resourceType: "script"
},
[ctx.entry]: {
isEntry: true,
file: ctx.entry,
module: true,
resourceType: "script"
}
};
const clientManifest = ctx.nuxt.options.dev ? devClientManifest : await fse.readJSON(resolve(clientDist, "manifest.json"));
const buildAssetsDir = withTrailingSlash(withoutLeadingSlash(ctx.nuxt.options.app.buildAssetsDir));
const BASE_RE = new RegExp(`^${escapeRE(buildAssetsDir)}`);
for (const key in clientManifest) {
if (clientManifest[key].file) {
clientManifest[key].file = clientManifest[key].file.replace(BASE_RE, "");
}
for (const item of ["css", "assets"]) {
if (clientManifest[key][item]) {
clientManifest[key][item] = clientManifest[key][item].map((i) => i.replace(BASE_RE, ""));
}
}
}
await fse.mkdirp(serverDist);
const manifest = normalizeViteManifest(clientManifest);
await ctx.nuxt.callHook("build:manifest", manifest);
await fse.writeFile(resolve(serverDist, "client.manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
await fse.writeFile(resolve(serverDist, "client.manifest.mjs"), "export default " + JSON.stringify(manifest, null, 2), "utf8");
if (!ctx.nuxt.options.dev) {
await fse.rm(resolve(clientDist, "manifest.json"), { force: true });
}
}
async function buildServer(ctx) {
const _resolve = (id) => resolveModule(id, { paths: ctx.nuxt.options.modulesDir });
const serverConfig = vite.mergeConfig(ctx.config, {
entry: ctx.entry,
base: ctx.nuxt.options.dev ? joinURL(ctx.nuxt.options.app.baseURL.replace(/^\.\//, "/") || "/", ctx.nuxt.options.app.buildAssetsDir) : void 0,
experimental: {
renderBuiltUrl: (filename, { type, hostType }) => {
if (hostType !== "js") {
return { relative: true };
}
if (type === "public") {
return { runtime: `globalThis.__publicAssetsURL(${JSON.stringify(filename)})` };
}
if (type === "asset") {
const relativeFilename = filename.replace(withTrailingSlash(withoutLeadingSlash(ctx.nuxt.options.app.buildAssetsDir)), "");
return { runtime: `globalThis.__buildAssetsURL(${JSON.stringify(relativeFilename)})` };
}
}
},
define: {
"process.server": true,
"process.client": false,
"typeof window": '"undefined"',
"typeof document": '"undefined"',
"typeof navigator": '"undefined"',
"typeof location": '"undefined"',
"typeof XMLHttpRequest": '"undefined"'
},
optimizeDeps: {
entries: [ctx.entry]
},
resolve: {
alias: {
"#build/plugins": resolve(ctx.nuxt.options.buildDir, "plugins/server"),
...ctx.nuxt.options.experimental.externalVue || ctx.nuxt.options.dev ? {} : {
"@vue/reactivity": _resolve(`@vue/reactivity/dist/reactivity.cjs${ctx.nuxt.options.dev ? "" : ".prod"}.js`),
"@vue/shared": _resolve(`@vue/shared/dist/shared.cjs${ctx.nuxt.options.dev ? "" : ".prod"}.js`),
"vue-router": _resolve(`vue-router/dist/vue-router.cjs${ctx.nuxt.options.dev ? "" : ".prod"}.js`),
"vue/server-renderer": _resolve("vue/server-renderer"),
"vue/compiler-sfc": _resolve("vue/compiler-sfc"),
vue: _resolve(`vue/dist/vue.cjs${ctx.nuxt.options.dev ? "" : ".prod"}.js`)
}
}
},
ssr: {
external: ctx.nuxt.options.experimental.externalVue ? ["#internal/nitro", "#internal/nitro/utils", "vue", "vue-router"] : ["#internal/nitro", "#internal/nitro/utils"],
noExternal: [
...ctx.nuxt.options.build.transpile,
/\/esm\/.*\.js$/,
/\.(es|esm|esm-browser|esm-bundler).js$/,
"/__vue-jsx",
"#app",
/^nuxt(\/|$)/,
/(nuxt|nuxt3)\/(dist|src|app)/
]
},
build: {
sourcemap: ctx.nuxt.options.sourcemap.server ? ctx.config.build?.sourcemap ?? true : false,
outDir: resolve(ctx.nuxt.options.buildDir, "dist/server"),
ssr: ctx.nuxt.options.ssr ?? true,
rollupOptions: {
input: ctx.entry,
external: ["#internal/nitro", ...ctx.nuxt.options.experimental.externalVue ? ["vue", "vue-router"] : []],
output: {
entryFileNames: "server.mjs",
preferConst: true,
inlineDynamicImports: !ctx.nuxt.options.experimental.viteServerDynamicImports,
format: "module"
},
onwarn(warning, rollupWarn) {
if (warning.code && ["UNUSED_EXTERNAL_IMPORT"].includes(warning.code)) {
return;
}
rollupWarn(warning);
}
}
},
server: {
preTransformRequests: false,
hmr: false
},
plugins: [
cacheDirPlugin(ctx.nuxt.options.rootDir, "server"),
vuePlugin(ctx.config.vue),
viteJsxPlugin()
]
});
if (ctx.nuxt.options.experimental.inlineSSRStyles) {
const chunksWithInlinedCSS = /* @__PURE__ */ new Set();
serverConfig.plugins.push(ssrStylesPlugin({
srcDir: ctx.nuxt.options.srcDir,
chunksWithInlinedCSS,
shouldInline: typeof ctx.nuxt.options.experimental.inlineSSRStyles === "function" ? ctx.nuxt.options.experimental.inlineSSRStyles : void 0
}));
ctx.nuxt.hook("build:manifest", (manifest) => {
for (const key in manifest) {
const entry = manifest[key];
const shouldRemoveCSS = chunksWithInlinedCSS.has(key);
if (shouldRemoveCSS) {
entry.css = [];
}
}
});
}
await ctx.nuxt.callHook("vite:extendConfig", serverConfig, { isClient: false, isServer: true });
const onBuild = () => ctx.nuxt.callHook("vite:compiled");
if (!ctx.nuxt.options.dev) {
const start = Date.now();
logger.info("Building server...");
await vite.build(serverConfig);
await writeManifest(ctx);
await onBuild();
logger.success(`Server built in ${Date.now() - start}ms`);
return;
}
await writeManifest(ctx);
if (!ctx.nuxt.options.ssr) {
await onBuild();
return;
}
const viteServer = await vite.createServer(serverConfig);
ctx.ssrServer = viteServer;
await ctx.nuxt.callHook("vite:serverCreated", viteServer, { isClient: false, isServer: true });
ctx.nuxt.hook("close", () => viteServer.close());
await viteServer.pluginContainer.buildStart({});
if (ctx.config.devBundler !== "legacy") {
await initViteNodeServer(ctx);
} else {
logger.info("Vite server using legacy server bundler...");
await import('../chunks/dev-bundler.mjs').then((r) => r.initViteDevBundler(ctx, onBuild));
}
}
const PREFIX = "virtual:nuxt:";
function virtual(vfs) {
const extensions = ["", ".ts", ".vue", ".mjs", ".cjs", ".js", ".json"];
const resolveWithExt = (id) => {
for (const ext of extensions) {
const rId = id + ext;
if (rId in vfs) {
return rId;
}
}
return null;
};
return {
name: "virtual",
resolveId(id, importer) {
if (process.platform === "win32" && isAbsolute(id)) {
id = resolve(id);
}
const resolvedId = resolveWithExt(id);
if (resolvedId) {
return PREFIX + resolvedId;
}
if (importer && !isAbsolute(id)) {
const importerNoPrefix = importer.startsWith(PREFIX) ? importer.slice(PREFIX.length) : importer;
const importedDir = dirname(importerNoPrefix);
const resolved = resolveWithExt(join(importedDir, id));
if (resolved) {
return PREFIX + resolved;
}
}
return null;
},
load(id) {
if (!id.startsWith(PREFIX)) {
return null;
}
const idNoPrefix = id.slice(PREFIX.length);
if (idNoPrefix in vfs) {
return {
code: vfs[idNoPrefix],
map: null
};
}
}
};
}
async function warmupViteServer(server, entries, isServer) {
const warmedUrls = /* @__PURE__ */ new Set();
const warmup = async (url) => {
if (warmedUrls.has(url)) {
return;
}
warmedUrls.add(url);
try {
await server.transformRequest(url, { ssr: isServer });
} catch (e) {
logger.debug("Warmup for %s failed with: %s", url, e);
}
const mod = await server.moduleGraph.getModuleByUrl(url, isServer);
const deps = mod?.ssrTransformResult?.deps || Array.from(mod?.importedModules || []).map((m) => m.url);
await Promise.all(deps.map((m) => warmup(m.replace("/@id/__x00__", "\0"))));
};
await Promise.all(entries.map((entry) => warmup(entry)));
}
function resolveCSSOptions(nuxt) {
const css = {
postcss: {
plugins: []
}
};
const lastPlugins = ["autoprefixer", "cssnano"];
css.postcss.plugins = Object.entries(nuxt.options.postcss.plugins).sort((a, b) => lastPlugins.indexOf(a[0]) - lastPlugins.indexOf(b[0])).filter(([, opts]) => opts).map(([name, opts]) => {
const plugin = requireModule(name, {
paths: [
...nuxt.options.modulesDir,
distDir
]
});
return plugin(opts);
});
return css;
}
const keyedFunctions = [
"useState",
"useFetch",
"useAsyncData",
"useLazyAsyncData",
"useLazyFetch"
];
const KEYED_FUNCTIONS_RE = new RegExp(`(${keyedFunctions.join("|")})`);
const stringTypes = ["Literal", "TemplateLiteral"];
const composableKeysPlugin = createUnplugin((options) => {
return {
name: "nuxt:composable-keys",
enforce: "post",
transformInclude(id) {
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href));
return !pathname.match(/node_modules\/nuxt3?\//) && pathname.match(/\.(m?[jt]sx?|vue)/) && parseQuery(search).type !== "style" && !parseQuery(search).macro;
},
transform(code, id) {
if (!KEYED_FUNCTIONS_RE.test(code)) {
return;
}
const { 0: script = code, index: codeIndex = 0 } = code.match(/(?<=<script[^>]*>)[\S\s.]*?(?=<\/script>)/) || { index: 0, 0: code };
const s = new MagicString(code);
let count = 0;
const relativeID = isAbsolute(id) ? relative(options.rootDir, id) : id;
walk(this.parse(script, {
sourceType: "module",
ecmaVersion: "latest"
}), {
enter(_node) {
if (_node.type !== "CallExpression" || _node.callee.type !== "Identifier") {
return;
}
const node = _node;
const name = "name" in node.callee && node.callee.name;
if (!name || !keyedFunctions.includes(name) || node.arguments.length >= 4) {
return;
}
switch (name) {
case "useState":
if (node.arguments.length >= 2 || stringTypes.includes(node.arguments[0]?.type)) {
return;
}
break;
case "useFetch":
case "useLazyFetch":
if (node.arguments.length >= 3 || stringTypes.includes(node.arguments[1]?.type)) {
return;
}
break;
case "useAsyncData":
case "useLazyAsyncData":
if (node.arguments.length >= 3 || stringTypes.includes(node.arguments[0]?.type) || stringTypes.includes(node.arguments[node.arguments.length - 1]?.type)) {
return;
}
break;
}
const endsWithComma = code.slice(codeIndex + node.start, codeIndex + node.end - 1).trim().endsWith(",");
s.appendLeft(
codeIndex + node.end - 1,
(node.arguments.length && !endsWithComma ? ", " : "") + "'$" + hash(`${relativeID}-${++count}`) + "'"
);
}
});
if (s.hasChanged()) {
return {
code: s.toString(),
map: options.sourcemap ? s.generateMap({ source: id, includeContent: true }) : void 0
};
}
}
};
});
async function bundle(nuxt) {
const useAsyncEntry = nuxt.options.experimental.asyncEntry || nuxt.options.vite.devBundler === "vite-node" && nuxt.options.dev;
const entry = await resolvePath(resolve(nuxt.options.appDir, useAsyncEntry ? "entry.async" : "entry"));
const ctx = {
nuxt,
entry,
config: vite.mergeConfig(
{
resolve: {
alias: {
...nuxt.options.alias,
"#app": nuxt.options.appDir,
"#build/plugins": "",
"#build": nuxt.options.buildDir,
"web-streams-polyfill/ponyfill/es2018": "unenv/runtime/mock/empty",
"abort-controller": "unenv/runtime/mock/empty"
}
},
optimizeDeps: {
include: ["vue"]
},
css: resolveCSSOptions(nuxt),
build: {
rollupOptions: {
output: {
sanitizeFileName: sanitizeFilePath,
assetFileNames: nuxt.options.dev ? void 0 : (chunk) => withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, `${sanitizeFilePath(filename(chunk.name))}.[hash].[ext]`))
}
},
watch: {
exclude: nuxt.options.ignore
}
},
plugins: [
composableKeysPlugin.vite({ sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client, rootDir: nuxt.options.rootDir }),
replace({
...Object.fromEntries([";", "(", "{", "}", " ", " ", "\n"].map((d) => [`${d}global.`, `${d}globalThis.`])),
preventAssignment: true
}),
virtual(nuxt.vfs)
],
vue: {
reactivityTransform: nuxt.options.experimental.reactivityTransform
},
server: {
watch: { ignored: isIgnored },
fs: {
allow: [
nuxt.options.appDir,
...nuxt.options._layers.map((l) => l.config.rootDir)
]
}
}
},
nuxt.options.vite
)
};
if (!nuxt.options.dev) {
ctx.config.server.watch = void 0;
ctx.config.build.watch = void 0;
}
await nuxt.callHook("vite:extend", ctx);
if (ctx.nuxt.options.typescript.typeCheck === true || ctx.nuxt.options.typescript.typeCheck === "build" && !ctx.nuxt.options.dev) {
const checker = await import('vite-plugin-checker').then((r) => r.default);
addVitePlugin(checker({
vueTsc: {
tsconfigPath: await resolveTSConfig(ctx.nuxt.options.rootDir)
}
}), { client: !nuxt.options.ssr, server: nuxt.options.ssr });
}
nuxt.hook("vite:serverCreated", (server, env) => {
ctx.nuxt.hook("app:templatesGenerated", () => {
for (const [id, mod] of server.moduleGraph.idToModuleMap) {
if (id.startsWith("virtual:")) {
server.moduleGraph.invalidateModule(mod);
}
}
});
if (nuxt.options.vite.warmupEntry !== false && !(env.isServer && ctx.nuxt.options.vite.devBundler !== "legacy")) {
const start = Date.now();
warmupViteServer(server, [join("/@fs/", ctx.entry)], env.isServer).then(() => logger.info(`Vite ${env.isClient ? "client" : "server"} warmed up in ${Date.now() - start}ms`)).catch(logger.error);
}
});
await buildClient(ctx);
await buildServer(ctx);
}
export { bundle as b, createIsExternal as c, hashId as h, isCSS as i, uniq as u, writeManifest as w };

60
node_modules/@nuxt/vite-builder/package.json generated vendored Normal file
View File

@@ -0,0 +1,60 @@
{
"name": "@nuxt/vite-builder",
"version": "3.0.0",
"repository": "nuxt/framework",
"license": "MIT",
"type": "module",
"types": "./dist/index.d.ts",
"exports": "./dist/index.mjs",
"files": [
"dist"
],
"devDependencies": {
"@nuxt/schema": "3.0.0",
"@types/cssnano": "^5",
"unbuild": "latest",
"vue": "3.2.45"
},
"dependencies": {
"@nuxt/kit": "3.0.0",
"@rollup/plugin-replace": "^5.0.1",
"@vitejs/plugin-vue": "^3.2.0",
"@vitejs/plugin-vue-jsx": "^2.1.1",
"autoprefixer": "^10.4.13",
"chokidar": "^3.5.3",
"cssnano": "^5.1.14",
"defu": "^6.1.1",
"esbuild": "^0.15.14",
"escape-string-regexp": "^5.0.0",
"estree-walker": "^3.0.1",
"externality": "^1.0.0",
"fs-extra": "^10.1.0",
"get-port-please": "^2.6.1",
"h3": "^1.0.1",
"knitwork": "^1.0.0",
"magic-string": "^0.26.7",
"mlly": "^1.0.0",
"ohash": "^1.0.0",
"pathe": "^1.0.0",
"perfect-debounce": "^0.1.3",
"pkg-types": "^1.0.1",
"postcss": "^8.4.19",
"postcss-import": "^15.0.0",
"postcss-url": "^10.1.3",
"rollup": "^2.79.1",
"rollup-plugin-visualizer": "^5.8.3",
"ufo": "^1.0.0",
"unplugin": "^1.0.0",
"vite": "~3.2.4",
"vite-node": "^0.25.2",
"vite-plugin-checker": "^0.5.1",
"vue-bundle-renderer": "^1.0.0"
},
"peerDependencies": {
"vue": "^3.2.45"
},
"engines": {
"node": "^14.16.0 || ^16.10.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"scripts": {}
}