fully-react
Version:
React Server for Vite
1,405 lines (1,386 loc) • 107 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
// ../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
"../../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
"use strict";
module.exports = balanced;
function balanced(a, b, str) {
if (a instanceof RegExp)
a = maybeMatch(a, str);
if (b instanceof RegExp)
b = maybeMatch(b, str);
var r = range(a, b, str);
return r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + a.length, r[1]),
post: str.slice(r[1] + b.length)
};
}
function maybeMatch(reg, str) {
var m = str.match(reg);
return m ? m[0] : null;
}
balanced.range = range;
function range(a, b, str) {
var begs, beg, left, right, result;
var ai = str.indexOf(a);
var bi = str.indexOf(b, ai + 1);
var i = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i == ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length == 1) {
result = [begs.pop(), bi];
} else {
beg = begs.pop();
if (beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [left, right];
}
}
return result;
}
}
});
// ../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
"../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
var balanced = require_balanced_match();
module.exports = expandTop;
var escSlash = "\0SLASH" + Math.random() + "\0";
var escOpen = "\0OPEN" + Math.random() + "\0";
var escClose = "\0CLOSE" + Math.random() + "\0";
var escComma = "\0COMMA" + Math.random() + "\0";
var escPeriod = "\0PERIOD" + Math.random() + "\0";
function numeric(str) {
return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
}
function parseCommaParts(str) {
if (!str)
return [""];
var parts = [];
var m = balanced("{", "}", str);
if (!m)
return str.split(",");
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(",");
p[p.length - 1] += "{" + body + "}";
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length - 1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
if (str.substr(0, 2) === "{}") {
str = "\\{\\}" + str.substr(2);
}
return expand2(escapeBraces(str), true).map(unescapeBraces);
}
function embrace(str) {
return "{" + str + "}";
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand2(str, isTop) {
var expansions = [];
var m = balanced("{", "}", str);
if (!m)
return [str];
var pre = m.pre;
var post = m.post.length ? expand2(m.post, false) : [""];
if (/\$$/.test(m.pre)) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + "{" + m.body + "}" + post[k];
expansions.push(expansion);
}
} else {
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(",") >= 0;
if (!isSequence && !isOptions) {
if (m.post.match(/,.*\}/)) {
str = m.pre + "{" + m.body + escClose + m.post;
return expand2(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
n = expand2(n[0], false).map(embrace);
if (n.length === 1) {
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length);
var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === "\\")
c = "";
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join("0");
if (i < 0)
c = "-" + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = [];
for (var j = 0; j < n.length; j++) {
N.push.apply(N, expand2(n[j], false));
}
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
}
return expansions;
}
}
});
// src/rsc-plugin/index.ts
import { parse } from "acorn-loose";
import { moduleResolve } from "import-meta-resolve";
import { fileURLToPath } from "url";
// src/rsc-plugin/utils.ts
function hasRscQuery(id) {
const query = splitQuery(id)[1];
return query.match(/(^|&)rsc($|&|=)/);
}
function addRscQuery(id) {
if (id.includes("?")) {
return id + "&rsc";
} else {
return id + "?rsc";
}
}
function removeRscQuery(id) {
const [base, query] = splitQuery(id);
if (!query)
return id;
const newQuery = query.split("&").filter((part) => !part.match(/rsc($|=)/)).join("&");
if (!newQuery)
return base;
return base + "?" + newQuery;
}
function splitQuery(id) {
const index = id.indexOf("?");
if (index === -1)
return [id, ""];
return [id.slice(0, index), id.slice(index + 1)];
}
// src/rsc-plugin/index.ts
import { mkdirSync, writeFileSync } from "fs";
import { join } from "path";
function reactServerComponents() {
let root;
let isBuild = false;
const clientModules = /* @__PURE__ */ new Set();
const serverModules = /* @__PURE__ */ new Set();
return {
name: "react-server-components",
enforce: "pre",
configResolved(config) {
root = config.root;
isBuild = config.command === "build";
},
async resolveId(id, importer, options) {
if (process.env.RSC_WORKER) {
return;
}
if (!importer || !hasRscQuery(importer))
return;
const resolved = await this.resolve(id, importer, {
...options,
skipSelf: true
});
if (!resolved || resolved.id.endsWith(".png"))
return;
if (resolved.id.startsWith(root) && !resolved.external && !resolved.id.includes("/node_modules/")) {
return addRscQuery(resolved.id);
}
if (!resolved.external)
return addRscQuery(resolved.id);
if (resolved.id.startsWith("node:"))
return resolved;
const url2 = importer.includes(":") ? new URL(importer) : new URL(`file://${importer}`);
const resolvedUrl = await moduleResolve(
id,
url2,
/* @__PURE__ */ new Set(["node", "import", "react-server"]),
false
);
if (resolvedUrl.protocol === "file:") {
const resolvedId = fileURLToPath(resolvedUrl);
return {
id: addRscQuery(resolvedId),
external: true
};
} else {
return {
id: resolvedUrl.href,
external: true
};
}
},
transform(code, id, options) {
if (!(options == null ? void 0 : options.ssr) || !process.env.RSC_WORKER && !hasRscQuery(id))
return;
const self = this;
return transformModuleIfNeeded(code, removeRscQuery(id));
async function transformModuleIfNeeded(code2, id2) {
if (code2.indexOf("use client") === -1 && code2.indexOf("use server") === -1) {
return code2;
}
const body = parse(code2, {
ecmaVersion: "2024",
sourceType: "module"
}).body;
let useClient = false;
let useServer = false;
for (let i = 0; i < body.length; i++) {
const node = body[i];
if (node.type !== "ExpressionStatement" || !node.directive) {
break;
}
if (node.directive === "use client") {
useClient = true;
}
if (node.directive === "use server") {
useServer = true;
}
}
if (!useClient && !useServer) {
return code2;
}
if (useClient && useServer) {
throw new Error(
'Cannot have both "use client" and "use server" directives in the same file.'
);
}
if (useClient) {
return transformClientModule(body, id2);
}
return transformServerModule(code2, body, id2);
}
async function transformClientModule(ast, id2) {
const names = [];
clientModules.add(id2);
await parseExportNamesInto(ast, names, id2);
let newSrc = "const CLIENT_REFERENCE = Symbol.for('react.client.reference');\n";
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (name === "default") {
newSrc += "export default ";
newSrc += "Object.defineProperties(function() {";
newSrc += "throw new Error(" + JSON.stringify(
`Attempted to call the default export of ${id2} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of aClient Component.`
) + ");";
} else {
newSrc += "export const " + name + " = ";
newSrc += "Object.defineProperties(function() {";
newSrc += "throw new Error(" + JSON.stringify(
`Attempted to call ${name}() from the server but ${name} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`
) + ");";
}
newSrc += "},{";
newSrc += "$$typeof: {value: CLIENT_REFERENCE},";
newSrc += "$$id: {value: " + JSON.stringify(id2 + "#" + name) + "}";
newSrc += "});\n";
}
return newSrc;
}
function transformServerModule(source, ast, id2) {
serverModules.add(id2);
const localNames = /* @__PURE__ */ new Map();
const localTypes = /* @__PURE__ */ new Map();
for (let i = 0; i < ast.length; i++) {
const node = ast[i];
switch (node.type) {
case "ExportAllDeclaration":
break;
case "ExportDefaultDeclaration":
if (node.declaration.type === "Identifier") {
localNames.set(node.declaration.name, "default");
} else if (node.declaration.type === "FunctionDeclaration") {
if (node.declaration.id) {
localNames.set(node.declaration.id.name, "default");
localTypes.set(node.declaration.id.name, "function");
} else {
}
}
continue;
case "ExportNamedDeclaration":
if (node.declaration) {
if (node.declaration.type === "VariableDeclaration") {
const declarations = node.declaration.declarations;
for (let j = 0; j < declarations.length; j++) {
addLocalExportedNames(localNames, declarations[j].id);
}
} else {
const name = node.declaration.id.name;
localNames.set(name, name);
if (node.declaration.type === "FunctionDeclaration") {
localTypes.set(name, "function");
}
}
}
if (node.specifiers) {
const specifiers = node.specifiers;
for (let j = 0; j < specifiers.length; j++) {
const specifier = specifiers[j];
localNames.set(specifier.local.name, specifier.exported.name);
}
}
continue;
}
}
let newSrc = source + "\n\n;";
localNames.forEach(function(exported, local) {
if (localTypes.get(local) !== "function") {
newSrc += "if (typeof " + local + ' === "function") ';
}
newSrc += "Object.defineProperties(" + local + ",{";
newSrc += '$$typeof: {value: Symbol.for("react.server.reference")},';
newSrc += "$$id: {value: " + JSON.stringify(id2 + "#" + exported) + "},";
newSrc += "$$bound: { value: null }";
newSrc += "});\n";
});
return newSrc;
}
async function parseExportNamesInto(ast, names, parentURL) {
for (let i = 0; i < ast.length; i++) {
const node = ast[i];
switch (node.type) {
case "ExportAllDeclaration":
if (node.exported) {
addExportNames(names, node.exported);
continue;
} else {
const { url: url2 } = await resolveClientImport(
node.source.value,
parentURL
);
const { code: code2 } = await self.load({ id: url2 });
const childBody = parse(code2 ?? "", {
ecmaVersion: "2024",
sourceType: "module"
}).body;
await parseExportNamesInto(childBody, names, url2);
continue;
}
case "ExportDefaultDeclaration":
names.push("default");
continue;
case "ExportNamedDeclaration":
if (node.declaration) {
if (node.declaration.type === "VariableDeclaration") {
const declarations = node.declaration.declarations;
for (let j = 0; j < declarations.length; j++) {
addExportNames(names, declarations[j].id);
}
} else {
addExportNames(names, node.declaration.id);
}
}
if (node.specifiers) {
const specifiers = node.specifiers;
for (let j = 0; j < specifiers.length; j++) {
addExportNames(names, specifiers[j].exported);
}
}
continue;
}
}
}
function addLocalExportedNames(names, node) {
switch (node.type) {
case "Identifier":
names.set(node.name, node.name);
return;
case "ObjectPattern":
for (let i = 0; i < node.properties.length; i++)
addLocalExportedNames(names, node.properties[i]);
return;
case "ArrayPattern":
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i];
if (element)
addLocalExportedNames(names, element);
}
return;
case "Property":
addLocalExportedNames(names, node.value);
return;
case "AssignmentPattern":
addLocalExportedNames(names, node.left);
return;
case "RestElement":
addLocalExportedNames(names, node.argument);
return;
case "ParenthesizedExpression":
addLocalExportedNames(names, node.expression);
return;
}
}
function addExportNames(names, node) {
switch (node.type) {
case "Identifier":
names.push(node.name);
return;
case "ObjectPattern":
for (let i = 0; i < node.properties.length; i++)
addExportNames(names, node.properties[i]);
return;
case "ArrayPattern":
for (let i = 0; i < node.elements.length; i++) {
const element = node.elements[i];
if (element)
addExportNames(names, element);
}
return;
case "Property":
addExportNames(names, node.value);
return;
case "AssignmentPattern":
addExportNames(names, node.left);
return;
case "RestElement":
addExportNames(names, node.argument);
return;
case "ParenthesizedExpression":
addExportNames(names, node.expression);
return;
}
}
async function resolveClientImport(specifier, parentURL) {
const resolved = await self.resolve(specifier, parentURL, {
skipSelf: true
});
if (!resolved) {
throw new Error(
"Could not resolve " + specifier + " from " + parentURL
);
}
return { url: resolved.id };
}
},
generateBundle(options) {
mkdirSync(options.dir, { recursive: true });
writeFileSync(
join(options.dir, "client-manifest.json"),
JSON.stringify([...clientModules.values()], null, 2)
);
writeFileSync(
join(options.dir, "server-manifest.json"),
JSON.stringify([...serverModules.values()], null, 2)
);
}
};
}
// src/winterkit/vite-plugins/inject-config.ts
import path from "path";
import fs from "fs";
import { resolve } from "import-meta-resolve";
import { pathToFileURL } from "url";
function injectConfig(options) {
return {
name: "hattip:inject-config",
enforce: "pre",
async config(cfg) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
const mainOutDir = ((_a = cfg.build) == null ? void 0 : _a.outDir) ?? "dist";
const buildSteps = [];
if (options.clientConfig || options.clientEntries) {
buildSteps.push({
name: "client",
config: {
...options.clientConfig,
build: {
...(_b = options.clientConfig) == null ? void 0 : _b.build,
manifest: true,
outDir: mainOutDir + "/client",
rollupOptions: {
...(_d = (_c = options.clientConfig) == null ? void 0 : _c.build) == null ? void 0 : _d.rollupOptions,
input: {
...typeof options.clientEntries === "boolean" ? {} : wrapInputOption(options.clientEntries),
...wrapInputOption(
(_g = (_f = (_e = options.clientConfig) == null ? void 0 : _e.build) == null ? void 0 : _f.rollupOptions) == null ? void 0 : _g.input
)
}
}
}
}
});
}
const serverEntry = wrapInputOption(options.extraServerEntries);
const root = cfg.root ?? process.cwd();
serverEntry["entry-hattip"] = options.hattipEntry ?? await findServerEntry(root);
serverEntry["entry-node"] = options.nodeEntry ?? await findServerEntry(root, true) ?? "virtual:hattip:default-node-entry";
buildSteps.push({
name: "server",
config: {
...options.serverConfig,
build: {
outDir: mainOutDir + "/server",
ssr: true,
...(_h = options.serverConfig) == null ? void 0 : _h.build,
rollupOptions: {
...(_j = (_i = options.serverConfig) == null ? void 0 : _i.build) == null ? void 0 : _j.rollupOptions,
input: {
...wrapInputOption(serverEntry),
...wrapInputOption(
(_m = (_l = (_k = options.serverConfig) == null ? void 0 : _k.build) == null ? void 0 : _l.rollupOptions) == null ? void 0 : _m.input
)
}
}
}
}
});
let bundler = options.bundler;
if (typeof bundler === "string") {
const modulePath = await resolve(
bundler,
pathToFileURL(root + "/index.js").href
);
bundler = await import(modulePath);
}
return {
buildSteps,
api: {
hattip: {
bundler
}
}
};
}
};
}
function wrapInputOption(input) {
if (!input) {
return {};
}
if (typeof input === "string") {
input = [input];
}
if (Array.isArray(input)) {
const result = {};
for (const key of input) {
const alias = path.parse(key).name;
result[alias] = key;
}
return result;
}
return input;
}
async function findServerEntry(root, node) {
const dirs = ["", "src", "server", "src/server"];
const names = node ? ["entry-node", "entry.node", "index.node"] : [
"entry-hattip",
"server",
"entry-server",
"index",
"index.hattip",
"index.server"
];
const extensions = [".ts", ".tsx", ".mts", ".mjs", ".js", ".jsx"];
for (const dir of dirs) {
for (const name of names) {
for (const ext2 of extensions) {
const file = path.join(root, dir, name + ext2);
if (fs.existsSync(file)) {
return file;
}
}
}
}
if (!node) {
throw new Error("hattip: Could not find server entry");
}
}
// src/winterkit/vite-plugins/connect.ts
import path2 from "path";
import url from "url";
var dirname = typeof __dirname === "undefined" ? url.fileURLToPath(new URL(".", import.meta.url)) : __dirname;
function vaviteConnect(options = {}) {
const {
handlerEntry = "/handler",
customServerEntry,
serveClientAssetsInDev = false,
standalone = true,
clientAssetsDir = null,
bundleSirv = true
} = options;
return [
{
name: "@vavite/connect:resolve",
enforce: "pre",
async resolveId(id) {
if (id === "/virtual:vavite-connect-handler") {
return this.resolve(handlerEntry);
} else if (id === "/virtual:vavite-connect-server") {
return path2.resolve(
dirname,
customServerEntry || "entry-standalone-bundled-sirv.js"
).replace(/\\/g, "/");
}
}
},
{
name: "@vavite/connect:server",
enforce: "post",
config(config, env) {
var _a;
const common = {
optimizeDeps: {
// This silences the "could not auto-determine entry point" warning
include: []
}
};
if (env.command === "build" && ((_a = config.build) == null ? void 0 : _a.ssr)) {
if (process.env.RSC_WORKER) {
return {
...common
// build: {
// rollupOptions: {
// input: {
// index: rscEntry,
// },
// },
// },
};
}
return {
...common,
// build: {
// rollupOptions: {
// input: {
// index:
// customServerEntry ||
// (standalone
// ? "/virtual:vavite-connect-server"
// : "/virtual:vavite-connect-handler"),
// },
// },
// },
define: clientAssetsDir ? {
__VAVITE_CLIENT_BUILD_OUTPUT_DIR: JSON.stringify(clientAssetsDir)
} : {}
};
}
return common;
},
configureServer(server) {
function addMiddleware() {
server.middlewares.use(async (req, res) => {
function renderError(status, message) {
res.statusCode = status;
res.end(message);
}
req.url = req.originalUrl || req.url;
try {
const module = await server.ssrLoadModule(handlerEntry);
await module.default(req, res, () => {
if (!res.writableEnded)
renderError(404, "Not found");
});
} catch (err) {
if (err instanceof Error) {
server.ssrFixStacktrace(err);
renderError(500, err.stack || err.message);
} else {
renderError(500, "Unknown error");
}
}
});
}
if (serveClientAssetsInDev) {
return addMiddleware;
} else {
addMiddleware();
}
}
}
];
}
// src/winterkit/vite-plugins/default-node-entry.ts
function defaultNodeEntry(options) {
let root;
let hattipEntry = options.hattipEntry;
return {
name: "hattip:default-node-entry",
enforce: "pre",
config(config) {
root = config.root ?? process.cwd();
},
async resolveId(source, importer, options2) {
if (!options2.ssr || source !== "virtual:hattip:default-node-entry") {
return;
}
const entry = await findServerEntry(root, true);
if (entry) {
const resolved = await this.resolve(entry, importer, {
...options2,
skipSelf: true
});
if (resolved)
return resolved;
}
hattipEntry = hattipEntry ?? await findServerEntry(root, false);
return "virtual:hattip:default-node-entry";
},
async load(id) {
if (id === "virtual:hattip:default-node-entry") {
if (typeof options.devEntry === "string") {
return options.devEntry;
} else {
return (options.devEntry ?? makeDefaultNodeEntry)(hattipEntry);
}
}
}
};
}
function makeDefaultNodeEntry(hattipEntry) {
if (!hattipEntry) {
throw new Error("No hattip entry found");
}
return `
import handler from ${JSON.stringify(hattipEntry)};
import { createMiddleware } from "winterkit/node";
export default createMiddleware(handler);
`;
}
// src/winterkit/expose-dev-server.ts
function exposeDevServer() {
let dev = false;
return {
name: "virtual:expose-vite-dev-server",
enforce: "pre",
config(_, env) {
dev = env.command === "serve";
},
configureServer(server) {
globalThis.__vite_dev_server__ = server;
},
resolveId(source, _importer, options) {
if (source === "virtual:vite-dev-server" && options.ssr) {
return "\0virtual:vite-dev-server";
}
},
load(id) {
if (id === "virtual:vite-dev-server" || id === "\0virtual:vite-dev-server") {
return "export default " + (dev ? "globalThis.__vite_dev_server__" : "undefined");
}
}
};
}
// src/winterkit/vite-plugin.ts
function hattip(options = {}) {
const cliOptions = globalThis.__hattip_cli_options__;
options.hattipEntry = options.hattipEntry ?? (cliOptions == null ? void 0 : cliOptions.hattipEntry);
options.nodeEntry = options.nodeEntry ?? (cliOptions == null ? void 0 : cliOptions.nodeEntry);
options.clientEntries = options.clientEntries ?? (cliOptions == null ? void 0 : cliOptions.clientEntries);
options.bundler = options.bundler ?? (cliOptions == null ? void 0 : cliOptions.bundler);
const hasClient = !!(options.clientConfig || options.clientEntries);
return [
exposeDevServer(),
injectConfig(options),
defaultNodeEntry({
hattipEntry: options.hattipEntry,
devEntry: options.devEntry
}),
vaviteConnect({
handlerEntry: options.nodeEntry || "virtual:hattip:default-node-entry",
serveClientAssetsInDev: hasClient,
clientAssetsDir: hasClient ? "dist/static" : void 0
})
];
}
// src/index.ts
import path6, { dirname as dirname2, join as join3 } from "path";
import inspect from "vite-plugin-inspect";
// src/rsc-plugin/tsconfig-paths.ts
import originalTsconfigPaths from "vite-tsconfig-paths";
var tsconfigPaths = (options) => {
const original = originalTsconfigPaths(options);
return {
...original,
async resolveId(id, importer, options2) {
let resolved = await original.resolveId.call(
this,
id,
importer,
options2
);
if (!resolved)
return resolved;
if (typeof resolved === "string")
resolved = { id: resolved };
if (hasRscQuery(resolved.id) === hasRscQuery(id))
return resolved;
if (hasRscQuery(resolved.id) && importer && !hasRscQuery(importer)) {
return removeRscQuery(resolved.id);
} else if (!hasRscQuery(resolved.id) && importer && hasRscQuery(importer)) {
return addRscQuery(resolved.id);
}
return resolved;
}
};
};
// src/index.ts
import reactRefresh from "@vitejs/plugin-react";
import { cpSync, existsSync, readFileSync, writeFileSync as writeFileSync2 } from "fs";
import { fileURLToPath as fileURLToPath2 } from "url";
// src/fs-router/index.ts
import * as fs2 from "fs";
import * as path4 from "path";
// ../../node_modules/.pnpm/minimatch@8.0.3/node_modules/minimatch/dist/mjs/index.js
var import_brace_expansion = __toESM(require_brace_expansion(), 1);
// ../../node_modules/.pnpm/minimatch@8.0.3/node_modules/minimatch/dist/mjs/assert-valid-pattern.js
var MAX_PATTERN_LENGTH = 1024 * 64;
var assertValidPattern = (pattern) => {
if (typeof pattern !== "string") {
throw new TypeError("invalid pattern");
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError("pattern is too long");
}
};
// ../../node_modules/.pnpm/minimatch@8.0.3/node_modules/minimatch/dist/mjs/brace-expressions.js
var posixClasses = {
"[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
"[:alpha:]": ["\\p{L}\\p{Nl}", true],
"[:ascii:]": ["\\x00-\\x7f", false],
"[:blank:]": ["\\p{Zs}\\t", true],
"[:cntrl:]": ["\\p{Cc}", true],
"[:digit:]": ["\\p{Nd}", true],
"[:graph:]": ["\\p{Z}\\p{C}", true, true],
"[:lower:]": ["\\p{Ll}", true],
"[:print:]": ["\\p{C}", true],
"[:punct:]": ["\\p{P}", true],
"[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
"[:upper:]": ["\\p{Lu}", true],
"[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
"[:xdigit:]": ["A-Fa-f0-9", false]
};
var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var rangesToString = (ranges) => ranges.join("");
var parseClass = (glob, position) => {
const pos = position;
if (glob.charAt(pos) !== "[") {
throw new Error("not in a brace expression");
}
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = "";
WHILE:
while (i < glob.length) {
const c = glob.charAt(i);
if ((c === "!" || c === "^") && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === "]" && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === "\\") {
if (!escaping) {
escaping = true;
i++;
continue;
}
}
if (c === "[" && !escaping) {
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
if (rangeStart) {
return ["$.", false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
escaping = false;
if (rangeStart) {
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
} else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = "";
i++;
continue;
}
if (glob.startsWith("-]", i + 1)) {
ranges.push(braceEscape(c + "-"));
i += 2;
continue;
}
if (glob.startsWith("-", i + 1)) {
rangeStart = c;
i += 2;
continue;
}
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
return ["", false, 0, false];
}
if (!ranges.length && !negs.length) {
return ["$.", false, glob.length - pos, true];
}
if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
return [comb, uflag, endPos - pos, true];
};
// ../../node_modules/.pnpm/minimatch@8.0.3/node_modules/minimatch/dist/mjs/unescape.js
var unescape = (s, { windowsPathsNoEscape = false } = {}) => {
return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
};
// ../../node_modules/.pnpm/minimatch@8.0.3/node_modules/minimatch/dist/mjs/ast.js
var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);
var isExtglobType = (c) => types.has(c);
var startNoTraversal = "(?!\\.\\.?(?:$|/))";
var startNoDot = "(?!\\.)";
var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);
var justDots = /* @__PURE__ */ new Set(["..", "."]);
var reSpecials = new Set("().*{}+?[]^$\\!");
var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
var qmark = "[^/]";
var star = qmark + "*?";
var starNoEmpty = qmark + "+?";
var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _fillNegs, fillNegs_fn, _parseAST, parseAST_fn, _parseGlob, parseGlob_fn;
var _AST = class {
constructor(type, parent, options = {}) {
__privateAdd(this, _fillNegs);
__publicField(this, "type");
__privateAdd(this, _root, void 0);
__privateAdd(this, _hasMagic, void 0);
__privateAdd(this, _uflag, false);
__privateAdd(this, _parts, []);
__privateAdd(this, _parent, void 0);
__privateAdd(this, _parentIndex, void 0);
__privateAdd(this, _negs, void 0);
__privateAdd(this, _filledNegs, false);
__privateAdd(this, _options, void 0);
__privateAdd(this, _toString, void 0);
// set to true if it's an extglob with no children
// (which really means one child of '')
__privateAdd(this, _emptyExt, false);
this.type = type;
if (type)
__privateSet(this, _hasMagic, true);
__privateSet(this, _parent, parent);
__privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this);
__privateSet(this, _options, __privateGet(this, _root) === this ? options : __privateGet(__privateGet(this, _root), _options));
__privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs));
if (type === "!" && !__privateGet(__privateGet(this, _root), _filledNegs))
__privateGet(this, _negs).push(this);
__privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0);
}
get hasMagic() {
if (__privateGet(this, _hasMagic) !== void 0)
return __privateGet(this, _hasMagic);
for (const p of __privateGet(this, _parts)) {
if (typeof p === "string")
continue;
if (p.type || p.hasMagic)
return __privateSet(this, _hasMagic, true);
}
return __privateGet(this, _hasMagic);
}
// reconstructs the pattern
toString() {
if (__privateGet(this, _toString) !== void 0)
return __privateGet(this, _toString);
if (!this.type) {
return __privateSet(this, _toString, __privateGet(this, _parts).map((p) => String(p)).join(""));
} else {
return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((p) => String(p)).join("|") + ")");
}
}
push(...parts) {
for (const p of parts) {
if (p === "")
continue;
if (typeof p !== "string" && !(p instanceof _AST && __privateGet(p, _parent) === this)) {
throw new Error("invalid part: " + p);
}
__privateGet(this, _parts).push(p);
}
}
toJSON() {
var _a;
const ret = this.type === null ? __privateGet(this, _parts).slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...__privateGet(this, _parts).map((p) => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && ((_a = __privateGet(this, _parent)) == null ? void 0 : _a.type) === "!")) {
ret.push({});
}
return ret;
}
isStart() {
var _a;
if (__privateGet(this, _root) === this)
return true;
if (!((_a = __privateGet(this, _parent)) == null ? void 0 : _a.isStart()))
return false;
if (__privateGet(this, _parentIndex) === 0)
return true;
const p = __privateGet(this, _parent);
for (let i = 0; i < __privateGet(this, _parentIndex); i++) {
const pp = __privateGet(p, _parts)[i];
if (!(pp instanceof _AST && pp.type === "!")) {
return false;
}
}
return true;
}
isEnd() {
var _a, _b, _c;
if (__privateGet(this, _root) === this)
return true;
if (((_a = __privateGet(this, _parent)) == null ? void 0 : _a.type) === "!")
return true;
if (!((_b = __privateGet(this, _parent)) == null ? void 0 : _b.isEnd()))
return false;
if (!this.type)
return (_c = __privateGet(this, _parent)) == null ? void 0 : _c.isEnd();
const pl = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0;
return __privateGet(this, _parentIndex) === pl - 1;
}
copyIn(part) {
if (typeof part === "string")
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new _AST(this.type, parent);
for (const p of __privateGet(this, _parts)) {
c.copyIn(p);
}
return c;
}
static fromGlob(pattern, options = {}) {
var _a;
const ast = new _AST(null, void 0, options);
__privateMethod(_a = _AST, _parseAST, parseAST_fn).call(_a, pattern, ast, 0, options);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
if (this !== __privateGet(this, _root))
return __privateGet(this, _root).toMMPattern();
const glob = this.toString();
const [re, body, hasMagic, uflag] = this.toRegExpSource();
const anyMagic = hasMagic || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();
if (!anyMagic) {
return body;
}
const flags = (__privateGet(this, _options).nocase ? "i" : "") + (uflag ? "u" : "");
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob
});
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource() {
var _a;
if (__privateGet(this, _root) === this)
__privateMethod(this, _fillNegs, fillNegs_fn).call(this);
if (!this.type) {
const noEmpty = this.isStart() && this.isEnd();
const src = __privateGet(this, _parts).map((p) => {
var _a2;
const [re, _, hasMagic, uflag] = typeof p === "string" ? __privateMethod(_a2 = _AST, _parseGlob, parseGlob_fn).call(_a2, p, __privateGet(this, _hasMagic), noEmpty) : p.toRegExpSource();
__privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || hasMagic);
__privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
return re;
}).join("");
let start2 = "";
if (this.isStart()) {
if (typeof __privateGet(this, _parts)[0] === "string") {
const dotTravAllowed = __privateGet(this, _parts).length === 1 && justDots.has(__privateGet(this, _parts)[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
const needNoTrav = (
// dots are allowed, and the pattern starts with [ or .
__privateGet(this, _options).dot && aps.has(src.charAt(0)) || // the pattern starts with \., and then [ or .
src.startsWith("\\.") && aps.has(src.charAt(2)) || // the pattern starts with \.\., and then [ or .
src.startsWith("\\.\\.") && aps.has(src.charAt(4))
);
const needNoDot = !__privateGet(this, _options).dot && aps.has(src.charAt(0));
start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";
}
}
}
let end = "";
if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && ((_a = __privateGet(this, _parent)) == null ? void 0 : _a.type) === "!") {
end = "(?:$|\\/)";
}
const final2 = start2 + src + end;
return [
final2,
unescape(src),
__privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
__privateGet(this, _uflag)
];
}
const start = this.type === "!" ? "(?:(?!(?:" : "(?:";
const body = __privateGet(this, _parts).map((p) => {
if (typeof p === "string") {
throw new Error("string type in extglob ast??");
}
const [re, _, _hasMagic2, uflag] = p.toRegExpSource();
__privateSet(this, _uflag, __privateGet(this, _uflag) || uflag);
return re;
}).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");
if (this.isStart() && this.isEnd() && !body && this.type !== "!") {
const s = this.toString();
__privateSet(this, _parts, [s]);
this.type = null;
__privateSet(this, _hasMagic, void 0);
return [s, unescape(this.toString()), false, false];
}
let final = "";
if (this.type === "!" && __privateGet(this, _emptyExt)) {
final = (this.isStart() && !__privateGet(this, _options).dot ? startNoDot : "") + starNoEmpty;
} else {
const close = this.type === "!" ? (
// !() must match something,but !(x) can match ''
"))" + (this.isStart() && !__privateGet(this, _options).dot ? startNoDot : "") + star + ")"
) : this.type === "@" ? ")" : `)${this.type}`;
final = start + body + close;
}
return [
final,
unescape(body),
__privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)),
__privateGet(this, _uflag)
];
}
};
var AST = _AST;
_root = new WeakMap();
_hasMagic = new WeakMap();
_uflag = new WeakMap();
_parts = new WeakMap();
_parent = new WeakMap();
_parentIndex = new WeakMap();
_negs = new WeakMap();
_filledNegs = new WeakMap();
_options = new WeakMap();
_toString =