rsbuild-plugin-react-router
Version:
React Router plugin for Rsbuild
937 lines (934 loc) • 866 kB
JavaScript
"use strict";
let globalStore;
const __rslib_import_meta_url__ = "u" < typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
var __webpack_require__ = {};
__webpack_require__.n = (module)=>{
var getter = module && module.__esModule ? ()=>module.default : ()=>module;
return __webpack_require__.d(getter, {
a: getter
}), getter;
}, __webpack_require__.d = (exports1, getters, values)=>{
var define = (defs, kind)=>{
for(var key in defs)__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key) && Object.defineProperty(exports1, key, {
enumerable: !0,
[kind]: defs[key]
});
};
define(getters, "get"), define(values, "value");
}, __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop), __webpack_require__.r = (exports1)=>{
"u" > typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports1, Symbol.toStringTag, {
value: 'Module'
}), Object.defineProperty(exports1, '__esModule', {
value: !0
});
};
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__), __webpack_require__.d(__webpack_exports__, {
loadReactRouterServerBuild: ()=>loadReactRouterServerBuild,
pluginReactRouter: ()=>pluginReactRouter,
resolveReactRouterServerBuild: ()=>resolveReactRouterServerBuild,
shouldParallelizeEnvironmentBuilds: ()=>shouldParallelizeEnvironmentBuilds
});
const external_node_fs_namespaceObject = require("node:fs"), external_fs_extra_namespaceObject = require("fs-extra");
var external_fs_extra_default = __webpack_require__.n(external_fs_extra_namespaceObject);
const core_namespaceObject = require("@rsbuild/core"), external_jiti_namespaceObject = require("jiti"), external_pathe_namespaceObject = require("pathe"), external_node_os_namespaceObject = require("node:os"), DEFAULT_RESERVED_CORES = 2, getAvailableCpuCount = ()=>'function' == typeof external_node_os_namespaceObject.availableParallelism ? (0, external_node_os_namespaceObject.availableParallelism)() : (0, external_node_os_namespaceObject.cpus)().length, getDefaultConcurrency = (cpuCount = getAvailableCpuCount())=>Math.max(0, Math.floor(cpuCount) - 2), getCappedPluginConcurrency = (cap = 16)=>Math.max(1, Math.min(cap, getDefaultConcurrency() || 1)), PLUGIN_NAME = 'rsbuild:react-router', JS_EXTENSIONS = [
'.tsx',
'.ts',
'.jsx',
'.js',
'.mjs',
'.mts'
], JS_LOADERS = null, BUILD_CLIENT_ROUTE_QUERY_STRING = '?__react-router-build-client-route', SERVER_ONLY_ROUTE_EXPORTS = [
'loader',
'action',
'middleware',
'headers'
], SERVER_ONLY_ROUTE_EXPORTS_SET = new Set(SERVER_ONLY_ROUTE_EXPORTS), CLIENT_NON_COMPONENT_EXPORTS = [
'clientAction',
'clientLoader',
'clientMiddleware',
'handle',
'meta',
'links',
'shouldRevalidate'
], CLIENT_COMPONENT_EXPORTS = [
'default',
'ErrorBoundary',
'HydrateFallback',
'Layout'
], CLIENT_ROUTE_EXPORTS = [
...CLIENT_NON_COMPONENT_EXPORTS,
...CLIENT_COMPONENT_EXPORTS
], CLIENT_ROUTE_EXPORTS_SET = new Set(CLIENT_ROUTE_EXPORTS), NAMED_COMPONENT_EXPORTS = [
'HydrateFallback',
'ErrorBoundary'
], NAMED_COMPONENT_EXPORTS_SET = new Set(NAMED_COMPONENT_EXPORTS), SERVER_EXPORTS = {
loader: 'loader',
action: 'action',
middleware: 'middleware',
headers: 'headers'
}, CLIENT_EXPORTS = {
clientAction: 'clientAction',
clientLoader: 'clientLoader',
clientMiddleware: 'clientMiddleware',
default: 'default',
ErrorBoundary: 'ErrorBoundary',
handle: 'handle',
HydrateFallback: 'HydrateFallback',
Layout: 'Layout',
links: 'links',
meta: 'meta',
shouldRevalidate: 'shouldRevalidate'
}, normalizeSlashes = (value)=>value.replace(/\\/g, '/'), getLazyCompilationModuleValues = (module)=>[
module.request,
module.userRequest,
module.rawRequest,
module.resource,
module.identifier?.(),
module.nameForCondition?.()
].filter((value)=>!!value), matchesLazyCompilationTest = (test, module)=>{
if (!test) return !0;
if ('function' == typeof test) return test(module);
let conditionName = module.nameForCondition?.();
return !!conditionName && (test.lastIndex = 0, test.test(conditionName));
}, createReactRouterHydrationModuleTest = (entryClientPath)=>{
let eagerPatterns = [
'virtual/react-router/browser-manifest',
...entryClientPath ? [
entryClientPath.replace(/\\/g, '/'),
BUILD_CLIENT_ROUTE_QUERY_STRING,
'?react-router-route'
] : []
];
return (module)=>getLazyCompilationModuleValues(module).some((value)=>{
let normalizedValue = value.replace(/\\/g, '/');
return eagerPatterns.some((pattern)=>normalizedValue.includes(pattern));
});
}, guardReactRouterLazyCompilation = ({ lazyCompilation, entryClientPath, prewarmReactRouterModules = !1 })=>{
if (void 0 === lazyCompilation || !1 === lazyCompilation) return lazyCompilation;
let options = !0 === lazyCompilation ? {
entries: !0,
imports: !0
} : lazyCompilation, userTest = options.test, isReactRouterHydrationModule = prewarmReactRouterModules ? createReactRouterHydrationModuleTest('') : createReactRouterHydrationModuleTest(entryClientPath);
return {
...options,
test: (module)=>!isReactRouterHydrationModule(module) && matchesLazyCompilationTest(userTest, module)
};
}, createDevServerMiddleware = (dependencies)=>{
let listenerPromise, getListener = ()=>listenerPromise ??= (async ()=>{
let createRequestHandler = dependencies.createRequestHandler ?? (await import("react-router")).createRequestHandler, createRequestListener = dependencies.createRequestListener ?? (await import("@remix-run/node-fetch-server")).createRequestListener, requestHandler = createRequestHandler(dependencies.loadBuild, 'development');
return createRequestListener((request)=>requestHandler(request));
})();
return getListener().catch(()=>{
listenerPromise = void 0;
}), async (req, res, next)=>{
try {
let listener = await getListener();
await listener(req, res);
} catch (error) {
next(error);
}
};
}, createReactRouterDevServerSetup = ({ loadBuild })=>function(context) {
if ('dev' === context.action) return ()=>{
context.server.middlewares.use(createDevServerMiddleware({
loadBuild
}));
};
}, external_yuku_parser_namespaceObject = require("yuku-parser"), getProgram = (ast)=>ast.program ?? ast, getPatternIdentifierNames = (pattern, names = new Set())=>{
if (!pattern) return names;
if ('Identifier' === pattern.type) return names.add(pattern.name), names;
if ('RestElement' === pattern.type) return getPatternIdentifierNames(pattern.argument, names);
if ('AssignmentPattern' === pattern.type) return getPatternIdentifierNames(pattern.left, names);
if ('ArrayPattern' === pattern.type) {
for (let element of pattern.elements ?? [])getPatternIdentifierNames(element, names);
return names;
}
if ('ObjectPattern' === pattern.type) for (let property of pattern.properties ?? [])'RestElement' === property.type ? getPatternIdentifierNames(property.argument, names) : getPatternIdentifierNames(property.value, names);
return names;
}, getIdentifierNamesFromPattern = (pattern)=>Array.from(getPatternIdentifierNames(pattern)), patternIncludesName = (pattern, name)=>getPatternIdentifierNames(pattern).has(name), getExportedName = (node)=>{
let exported = node?.exported ?? node;
return exported ? 'Identifier' === exported.type ? exported.name : 'Literal' === exported.type || 'StringLiteral' === exported.type ? String(exported.value) : null : null;
}, identifier = (name)=>({
type: 'Identifier',
start: 0,
end: 0,
name,
decorators: [],
optional: !1,
typeAnnotation: null
}), route_ast_literal = (value)=>({
type: 'Literal',
start: 0,
end: 0,
value,
raw: JSON.stringify(value)
}), callExpression = (callee, args)=>({
type: 'CallExpression',
start: 0,
end: 0,
callee,
arguments: args,
optional: !1
}), importDeclaration = (specifiers, source)=>({
type: 'ImportDeclaration',
start: 0,
end: 0,
specifiers: specifiers.map((specifier)=>({
type: 'ImportSpecifier',
start: 0,
end: 0,
imported: identifier(specifier.imported),
local: identifier(specifier.local),
importKind: 'value'
})),
source: route_ast_literal(source),
attributes: [],
phase: null,
importKind: 'value'
}), exportSpecifier = (local, exported)=>({
type: 'ExportSpecifier',
start: 0,
end: 0,
local: identifier(local),
exported: identifier(exported),
exportKind: 'value'
}), exportNamedDeclaration = (specifiers)=>({
type: 'ExportNamedDeclaration',
start: 0,
end: 0,
declaration: null,
specifiers,
source: null,
attributes: [],
exportKind: 'value'
}), variableDeclaration = (name, init)=>({
type: 'VariableDeclaration',
start: 0,
end: 0,
kind: 'const',
declare: !1,
declarations: [
{
type: 'VariableDeclarator',
start: 0,
end: 0,
id: identifier(name),
init,
definite: !1
}
]
}), removeFromArray = (array, value)=>{
let index = array.indexOf(value);
index >= 0 && array.splice(index, 1);
};
function validateDestructuredExports(id, exportsToRemove) {
validateBindingTarget(id, new Set(exportsToRemove));
}
function invalidDestructureError(name) {
return Error(`Cannot remove destructured export "${name}"`);
}
const assertAllowedBindingName = (name, exportsToRemove)=>{
if (exportsToRemove.has(name)) throw invalidDestructureError(name);
}, validateRestElement = (element, exportsToRemove)=>{
element.argument?.type === 'Identifier' && element.argument.name && assertAllowedBindingName(element.argument.name, exportsToRemove);
}, validateObjectProperty = (property, exportsToRemove)=>{
'RestElement' === property.type ? validateRestElement(property, exportsToRemove) : 'Property' === property.type && validateBindingTarget(property.value, exportsToRemove);
}, validateBindingTarget = (node, exportsToRemove)=>{
if (node) switch(node.type){
case 'Identifier':
node.name && assertAllowedBindingName(node.name, exportsToRemove);
return;
case 'AssignmentPattern':
validateBindingTarget(node.left, exportsToRemove);
return;
case 'ArrayPattern':
for (let element of node.elements ?? [])element?.type === 'RestElement' ? validateRestElement(element, exportsToRemove) : validateBindingTarget(element, exportsToRemove);
return;
case 'ObjectPattern':
for (let property of node.properties ?? [])validateObjectProperty(property, exportsToRemove);
}
}, getDeclaredNames = (node)=>{
let names = new Set();
if ('VariableDeclaration' === node.type) for (let declarator of node.declarations ?? [])getPatternIdentifierNames(declarator.id, names);
else if (('FunctionDeclaration' === node.type || 'ClassDeclaration' === node.type) && node.id?.name) names.add(node.id.name);
else if ('ImportDeclaration' === node.type) for (let specifier of node.specifiers ?? [])specifier.local?.name && names.add(specifier.local.name);
return names;
}, isIdentifierDeclaration = (node, parent)=>{
if (!parent || 'Identifier' !== node.type) return !1;
if (('FunctionDeclaration' === parent.type || 'FunctionExpression' === parent.type || 'ClassDeclaration' === parent.type || 'ClassExpression' === parent.type) && parent.id === node) return !0;
if ('VariableDeclarator' === parent.type) return !!(node.name && getPatternIdentifierNames(parent.id).has(node.name));
if (('ImportSpecifier' === parent.type || 'ImportDefaultSpecifier' === parent.type || 'ImportNamespaceSpecifier' === parent.type) && parent.local === node) return !0;
if (('FunctionDeclaration' === parent.type || 'FunctionExpression' === parent.type || 'ArrowFunctionExpression' === parent.type) && node.name) {
let name = node.name;
return (parent.params ?? []).some((param)=>getPatternIdentifierNames(param).has(name));
}
return !1;
}, isNonReferenceIdentifier = (node, parent)=>!!parent && 'Identifier' === node.type && (!!isIdentifierDeclaration(node, parent) || 'MemberExpression' === parent.type && parent.property === node && !parent.computed || 'Property' === parent.type && parent.key === node && !parent.computed && !parent.shorthand || 'MethodDefinition' === parent.type && parent.key === node && !parent.computed || 'ExportSpecifier' === parent.type || 'ExportDefaultSpecifier' === parent.type || 'ExportNamespaceSpecifier' === parent.type || 'ImportSpecifier' === parent.type && parent.imported === node || 'LabeledStatement' === parent.type || 'BreakStatement' === parent.type || 'ContinueStatement' === parent.type || !1), isUppercaseName = (name)=>/^[A-Z]/.test(name), collectReferencedNames = (node)=>{
let referenced = new Set();
return (0, external_yuku_parser_namespaceObject.walk)(node, {
Identifier (node, ctx) {
!isNonReferenceIdentifier(node, ctx.parent) && node.name && referenced.add(node.name);
},
JSXIdentifier (node, ctx) {
let name, parent = ctx.parent;
if (parent) {
if ('JSXMemberExpression' === parent.type && parent.object === node) {
node.name && referenced.add(node.name);
return;
}
if (node.name && (name = node.name, /^[A-Z]/.test(name)) && ('JSXOpeningElement' === parent.type || 'JSXClosingElement' === parent.type) && parent.name === node) return void referenced.add(node.name);
}
},
ExportSpecifier (node, ctx) {
let declaration = ctx.parent;
!declaration?.source && declaration?.exportKind !== 'type' && node.local?.name && 'type' !== node.exportKind && referenced.add(node.local.name);
}
}), referenced;
}, createTopLevelDeclarationGraph = (program)=>{
let declarationsByNode = new Map(), declarationsByName = new Map(), registerDeclaration = (node, declarationNode, declaredNames)=>{
let declaration = {
referencedNames: collectReferencedNames(declarationNode)
};
for (let name of (declarationsByNode.set(node, declaration), declaredNames)){
let namedDeclarations = declarationsByName.get(name) ?? new Set();
namedDeclarations.add(declaration), declarationsByName.set(name, namedDeclarations);
}
};
for (let statement of [
...program.body ?? []
]){
if ('VariableDeclaration' === statement.type) {
for (let declarator of statement.declarations ?? [])registerDeclaration(declarator, declarator, getPatternIdentifierNames(declarator.id));
continue;
}
('FunctionDeclaration' === statement.type || 'ClassDeclaration' === statement.type) && registerDeclaration(statement, statement, getDeclaredNames(statement));
}
return {
declarationsByNode,
declarationsByName
};
}, collectLiveTopLevelDeclarations = (program, graph)=>{
let pendingNames = [];
for (let statement of program.body ?? [])if ('VariableDeclaration' !== statement.type && !graph.declarationsByNode.has(statement)) for (let name of collectReferencedNames(statement))pendingNames.push(name);
let visitedNames = new Set(), liveDeclarations = new Set();
for(; pendingNames.length > 0;){
let name = pendingNames.pop();
if (!(!name || visitedNames.has(name))) {
for (let declaration of (visitedNames.add(name), graph.declarationsByName.get(name) ?? []))if (!liveDeclarations.has(declaration)) for (let referencedName of (liveDeclarations.add(declaration), declaration.referencedNames))pendingNames.push(referencedName);
}
}
return liveDeclarations;
}, declarationReferencesName = (declaration, names, graph, cache1, visitedNames = new Set())=>{
let cached = cache1.get(declaration);
if (void 0 !== cached) return cached;
for (let referencedName of declaration.referencedNames){
if (names.has(referencedName)) return cache1.set(declaration, !0), !0;
if (!visitedNames.has(referencedName)) {
for (let referencedDeclaration of (visitedNames.add(referencedName), graph.declarationsByName.get(referencedName) ?? []))if (declarationReferencesName(referencedDeclaration, names, graph, cache1, visitedNames)) return cache1.set(declaration, !0), !0;
}
}
return cache1.set(declaration, !1), !1;
}, removeNewlyDeadTopLevelDeclarations = (program, graph, previouslyLive, removedExportReferencedNames)=>{
let currentlyLive = collectLiveTopLevelDeclarations(program, graph), removedReferenceCache = new Map(), isRemovableDeadDeclaration = (node)=>{
let declaration = graph.declarationsByNode.get(node);
return !(!declaration || currentlyLive.has(declaration)) && (previouslyLive.has(declaration) || declarationReferencesName(declaration, removedExportReferencedNames, graph, removedReferenceCache));
};
program.body = program.body.filter((statement)=>'VariableDeclaration' === statement.type ? (statement.declarations = (statement.declarations ?? []).filter((declarator)=>!isRemovableDeadDeclaration(declarator)), statement.declarations.length > 0) : !isRemovableDeadDeclaration(statement));
}, hasRemovableExport = (program, exportsToRemove)=>{
let removesNamedExports = [
...exportsToRemove
].some((name)=>'default' !== name);
for (let statement of program.body ?? []){
if ('ExportAllDeclaration' === statement.type) {
let exportedName = statement.exported ? getExportedName({
exported: statement.exported
}) : null;
if (exportedName && exportsToRemove.has(exportedName) || !exportedName && removesNamedExports) return !0;
continue;
}
if ('ExportDefaultDeclaration' === statement.type) {
if (exportsToRemove.has('default')) return !0;
continue;
}
if ('ExportNamedDeclaration' !== statement.type) continue;
for (let specifier of statement.specifiers ?? []){
if ('ExportSpecifier' !== specifier.type) continue;
let exportedName = getExportedName(specifier);
if (exportedName && exportsToRemove.has(exportedName)) return !0;
}
let declaration = statement.declaration;
if (declaration?.type === 'VariableDeclaration') {
for (let declarator of declaration.declarations ?? [])for (let name of getPatternIdentifierNames(declarator.id))if (exportsToRemove.has(name)) return !0;
continue;
}
if ((declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') && declaration.id?.name && exportsToRemove.has(declaration.id.name)) return !0;
}
return !1;
}, removeExports = (ast, exportsToRemove, exportsToRemoveSet = new Set(exportsToRemove))=>{
let program = ast.program ?? ast;
if (!hasRemovableExport(program, exportsToRemoveSet)) return !1;
let declarationGraph = createTopLevelDeclarationGraph(program), previouslyLive = collectLiveTopLevelDeclarations(program, declarationGraph), exportsChanged = !1, removedExportLocalNames = new Set(), removedExportReferencedNames = new Set(), removesNamedExports = exportsToRemove.some((name)=>'default' !== name), trackRemovedExportReferences = (node)=>{
if (!node) return;
let declaration = declarationGraph.declarationsByNode.get(node);
for (let name of declaration?.referencedNames ?? collectReferencedNames(node))removedExportReferencedNames.add(name);
};
for (let statement of [
...program.body
]){
if ('ExportAllDeclaration' === statement.type) {
let exportedName = statement.exported ? getExportedName({
exported: statement.exported
}) : null;
if (exportedName && exportsToRemoveSet.has(exportedName) && (exportsChanged = !0, removeFromArray(program.body, statement)), !exportedName && removesNamedExports) throw Error('Cannot remove named exports from `export *`; use explicit named re-exports.');
continue;
}
if ('ExportNamedDeclaration' === statement.type) {
statement.specifiers?.length && (statement.specifiers = statement.specifiers.filter((specifier)=>{
if ('ExportSpecifier' !== specifier.type) return !0;
let exportedName = getExportedName(specifier);
return !(exportedName && exportsToRemoveSet.has(exportedName)) || (exportsChanged = !0, specifier.local?.name && (removedExportLocalNames.add(specifier.local.name), removedExportReferencedNames.add(specifier.local.name)), !1);
}), 0 !== statement.specifiers.length || statement.declaration || removeFromArray(program.body, statement));
let declaration = statement.declaration;
declaration?.type === 'VariableDeclaration' && (declaration.declarations = (declaration.declarations ?? []).filter((declarator)=>{
let id = declarator.id;
return id?.type === 'Identifier' ? !(id.name && exportsToRemoveSet.has(id.name)) || (exportsChanged = !0, removedExportLocalNames.add(id.name), removedExportReferencedNames.add(id.name), trackRemovedExportReferences(declarator), !1) : (id && validateDestructuredExports(id, exportsToRemove), !0);
}), 0 === declaration.declarations.length && removeFromArray(program.body, statement)), (declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') && declaration.id?.name && exportsToRemoveSet.has(declaration.id.name) && (exportsChanged = !0, removedExportLocalNames.add(declaration.id.name), removedExportReferencedNames.add(declaration.id.name), trackRemovedExportReferences(statement), removeFromArray(program.body, statement));
}
if ('ExportDefaultDeclaration' === statement.type && exportsToRemoveSet.has('default')) {
exportsChanged = !0;
let declaration = statement.declaration;
declaration?.type === 'Identifier' && declaration.name ? (removedExportLocalNames.add(declaration.name), removedExportReferencedNames.add(declaration.name)) : declaration?.id?.name && (removedExportLocalNames.add(declaration.id.name), removedExportReferencedNames.add(declaration.id.name)), trackRemovedExportReferences(statement), removeFromArray(program.body, statement);
}
}
for (let statement of [
...program.body
]){
let expression = 'ExpressionStatement' === statement.type ? statement.expression : null, left = expression?.type === 'AssignmentExpression' ? expression.left : null;
left?.type === 'MemberExpression' && left.object?.type === 'Identifier' && left.object.name && removedExportLocalNames.has(left.object.name) && removeFromArray(program.body, statement);
}
return exportsChanged && removeNewlyDeadTopLevelDeclarations(program, declarationGraph, previouslyLive, removedExportReferencedNames), exportsChanged;
}, removeUnusedImports = (ast)=>{
let program = ast.program ?? ast, referenced = collectReferencedNames(program);
for (let statement of [
...program.body
])'ImportDeclaration' === statement.type && 0 !== (statement.specifiers ?? []).length && (statement.specifiers = (statement.specifiers ?? []).filter((specifier)=>'type' !== specifier.importKind && (!specifier.local?.name || referenced.has(specifier.local.name))), 0 === statement.specifiers.length && removeFromArray(program.body, statement));
};
function toFunctionExpression(decl) {
return {
...decl,
type: 'FunctionExpression',
declare: void 0
};
}
function toClassExpression(decl) {
return {
...decl,
type: 'ClassExpression',
declare: void 0
};
}
const getComponentExportName = (exportedName)=>'default' === exportedName ? 'Component' : isNamedComponentExport(exportedName) ? exportedName : null, getImportInsertionIndex = (program)=>{
let index = 0;
for (let statement of program.body ?? []){
if ('ExpressionStatement' !== statement.type || void 0 === statement.directive && statement.expression?.type !== 'Literal') break;
index += 1;
}
return index;
}, declarationIncludesName = (declaration, name)=>'VariableDeclaration' === declaration.type ? (declaration.declarations ?? []).some((declarator)=>patternIncludesName(declarator.id, name)) : ('FunctionDeclaration' === declaration.type || 'ClassDeclaration' === declaration.type || 'TSEnumDeclaration' === declaration.type) && declaration.id?.name ? declaration.id.name === name : 'ImportDeclaration' === declaration.type && (declaration.specifiers ?? []).some((specifier)=>specifier.local?.name === name), hasTopLevelBindingName = (program, name)=>{
for (let statement of program.body ?? []){
if ('ImportDeclaration' === statement.type) {
if (declarationIncludesName(statement, name)) return !0;
continue;
}
if ('ExportDefaultDeclaration' === statement.type) {
if (statement.declaration?.id?.name === name) return !0;
continue;
}
let declaration = 'ExportNamedDeclaration' === statement.type ? statement.declaration : statement;
if (declaration && declarationIncludesName(declaration, name)) return !0;
}
return !1;
}, transformRoute = (ast)=>{
let program = ast.program ?? ast, usedNames = new Set(), hocs = [], componentWrapperDeclarations = [];
function getUid(name) {
let uid = `_${name}`, index = 2;
for(; usedNames.has(uid) || hasTopLevelBindingName(program, uid);)uid = `_${name}${index++}`;
return usedNames.add(uid), uid;
}
function getHocUid(hocName) {
let uid = getUid(hocName);
return hocs.push([
hocName,
uid
]), identifier(uid);
}
for (let statement of [
...program.body ?? []
]){
if ('ExportDefaultDeclaration' === statement.type) {
let declaration = statement.declaration;
if (!declaration || !0 === declaration.declare || 'TSInterfaceDeclaration' === declaration.type) continue;
let uid = getHocUid('withComponentProps');
if (('FunctionDeclaration' === declaration.type || 'ClassDeclaration' === declaration.type) && declaration.id?.name) {
let statementIndex = program.body.indexOf(statement);
program.body.splice(statementIndex, 0, declaration), statement.declaration = callExpression(uid, [
identifier(declaration.id.name)
]);
continue;
}
statement.declaration = callExpression(uid, [
'FunctionDeclaration' === declaration.type ? toFunctionExpression(declaration) : 'ClassDeclaration' === declaration.type ? toClassExpression(declaration) : declaration
]);
continue;
}
if ('ExportNamedDeclaration' !== statement.type || 'type' === statement.exportKind) continue;
let declaration = statement.declaration;
if (declaration?.type === 'VariableDeclaration') {
for (let declarator of declaration.declarations ?? []){
if (declarator.id?.type !== 'Identifier' || !declarator.init || !isNamedComponentExport(declarator.id.name)) continue;
let uid = getHocUid(`with${declarator.id.name}Props`);
declarator.init = callExpression(uid, [
declarator.init
]);
}
continue;
}
if ((declaration?.type === 'FunctionDeclaration' || declaration?.type === 'ClassDeclaration') && declaration.id?.name && isNamedComponentExport(declaration.id.name)) {
statement.declaration = function(name, declaration) {
let uid = getHocUid(`with${name}Props`);
return variableDeclaration(name, callExpression(uid, [
'FunctionDeclaration' === declaration.type ? toFunctionExpression(declaration) : 'ClassDeclaration' === declaration.type ? toClassExpression(declaration) : declaration
]));
}(declaration.id.name, declaration);
continue;
}
if (statement.source) {
let importSpecifiers = [], sourceWrapperDeclarations = [], wrappedExportSpecifiers = [];
if (statement.specifiers = (statement.specifiers ?? []).filter((specifier)=>{
if ('ExportSpecifier' !== specifier.type || 'type' === specifier.exportKind) return !0;
let exportedName = getExportedName(specifier), importedName = getExportedName(specifier.local), componentExportName = exportedName ? getComponentExportName(exportedName) : null;
if (!exportedName || !importedName || !componentExportName) return !0;
let sourceLocalName = getUid(`${exportedName}Source`), wrappedLocalName = getUid(exportedName), uid = getHocUid(`with${componentExportName}Props`);
return importSpecifiers.push({
imported: importedName,
local: sourceLocalName
}), sourceWrapperDeclarations.push(variableDeclaration(wrappedLocalName, callExpression(uid, [
identifier(sourceLocalName)
]))), wrappedExportSpecifiers.push(exportSpecifier(wrappedLocalName, exportedName)), !1;
}), importSpecifiers.length > 0) {
let statementIndex = program.body.indexOf(statement), replacementStatements = [
importDeclaration(importSpecifiers, String(statement.source.value))
];
statement.specifiers.length > 0 && replacementStatements.push(statement), replacementStatements.push(...sourceWrapperDeclarations), replacementStatements.push(exportNamedDeclaration(wrappedExportSpecifiers)), program.body.splice(statementIndex, 1, ...replacementStatements);
}
continue;
}
for (let specifier of statement.specifiers ?? []){
if ('ExportSpecifier' !== specifier.type || 'type' === specifier.exportKind) continue;
let exportedName = getExportedName(specifier), componentExportName = exportedName ? getComponentExportName(exportedName) : null;
if (!exportedName || !componentExportName) continue;
let localName = specifier.local?.name;
if (!localName) continue;
let wrappedLocalName = getUid(exportedName), uid = getHocUid(`with${componentExportName}Props`);
componentWrapperDeclarations.push(variableDeclaration(wrappedLocalName, callExpression(uid, [
identifier(localName)
]))), specifier.local = identifier(wrappedLocalName);
}
}
program.body.push(...componentWrapperDeclarations), hocs.length > 0 && program.body.splice(getImportInsertionIndex(program), 0, importDeclaration(hocs.map(([name, local])=>({
imported: name,
local
})), 'virtual/react-router/with-props'));
};
function isNamedComponentExport(name) {
return NAMED_COMPONENT_EXPORTS_SET.has(name);
}
function combineURLs(baseURL, relativeURL) {
return relativeURL ? `${baseURL.replace(/\/+$/, '')}/${relativeURL.replace(/^\/+/, '')}` : baseURL;
}
function normalizeAssetPrefix(assetPrefix) {
return assetPrefix && 'auto' !== assetPrefix ? assetPrefix.endsWith('/') ? assetPrefix : `${assetPrefix}/` : '/';
}
function stripFileExtension(file) {
return file.replace(/\.[^/.]+$/, '');
}
function createRouteId(file) {
return (0, external_pathe_namespaceObject.normalize)(stripFileExtension(file));
}
function findEntryFile(basePath) {
for (let ext of JS_EXTENSIONS){
let filePath = `${basePath}${ext}`;
if ((0, external_node_fs_namespaceObject.existsSync)(filePath)) return filePath;
}
return `${basePath}.tsx`;
}
function generateWithProps() {
return `
import { createElement as h } from "react";
import { useActionData, useLoaderData, useMatches, useParams, useRouteError } from "react-router";
export function withComponentProps(Component) {
return function Wrapped() {
const props = {
params: useParams(),
loaderData: useLoaderData(),
actionData: useActionData(),
matches: useMatches(),
};
return h(Component, props);
};
}
export function withHydrateFallbackProps(HydrateFallback) {
return function Wrapped() {
const props = {
params: useParams(),
};
return h(HydrateFallback, props);
};
}
export function withErrorBoundaryProps(ErrorBoundary) {
return function Wrapped() {
const props = {
params: useParams(),
loaderData: useLoaderData(),
actionData: useActionData(),
error: useRouteError(),
};
return h(ErrorBoundary, props);
};
}
`;
}
const Function_isFunction = (input)=>"function" == typeof input, Function_dual = function(arity, body) {
if ("function" == typeof arity) return function() {
return arity(arguments) ? body.apply(this, arguments) : (self)=>body(self, ...arguments);
};
switch(arity){
case 0:
case 1:
throw RangeError(`Invalid arity ${arity}`);
case 2:
return function(a, b) {
return arguments.length >= 2 ? body(a, b) : function(self) {
return body(self, a);
};
};
case 3:
return function(a, b, c) {
return arguments.length >= 3 ? body(a, b, c) : function(self) {
return body(self, a, b);
};
};
case 4:
return function(a, b, c, d) {
return arguments.length >= 4 ? body(a, b, c, d) : function(self) {
return body(self, a, b, c);
};
};
case 5:
return function(a, b, c, d, e) {
return arguments.length >= 5 ? body(a, b, c, d, e) : function(self) {
return body(self, a, b, c, d);
};
};
default:
return function() {
if (arguments.length >= arity) return body.apply(this, arguments);
let args = arguments;
return function(self) {
return body(self, ...args);
};
};
}
}, Function_apply = (...a)=>(self)=>self(...a), Function_identity = (a)=>a, satisfies = ()=>(b)=>b, Function_unsafeCoerce = null, constant = (value)=>()=>value, Function_constTrue = constant(!0), Function_constFalse = constant(!1), Function_constNull = null, Function_constUndefined = constant(void 0), Function_constVoid = Function_constUndefined, flip = (f)=>(...b)=>(...a)=>f(...a)(...b), compose = null, absurd = (_)=>{
throw Error("Called `absurd` function which should be uncallable");
}, tupled = (f)=>(a)=>f(...a), untupled = (f)=>(...a)=>f(a);
function Function_pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
switch(arguments.length){
case 1:
return a;
case 2:
return ab(a);
case 3:
return bc(ab(a));
case 4:
return cd(bc(ab(a)));
case 5:
return de(cd(bc(ab(a))));
case 6:
return ef(de(cd(bc(ab(a)))));
case 7:
return fg(ef(de(cd(bc(ab(a))))));
case 8:
return gh(fg(ef(de(cd(bc(ab(a)))))));
case 9:
return hi(gh(fg(ef(de(cd(bc(ab(a))))))));
default:
{
let ret = arguments[0];
for(let i = 1; i < arguments.length; i++)ret = arguments[i](ret);
return ret;
}
}
}
function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {
switch(arguments.length){
case 1:
return ab;
case 2:
return function() {
return bc(ab.apply(this, arguments));
};
case 3:
return function() {
return cd(bc(ab.apply(this, arguments)));
};
case 4:
return function() {
return de(cd(bc(ab.apply(this, arguments))));
};
case 5:
return function() {
return ef(de(cd(bc(ab.apply(this, arguments)))));
};
case 6:
return function() {
return fg(ef(de(cd(bc(ab.apply(this, arguments))))));
};
case 7:
return function() {
return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))));
};
case 8:
return function() {
return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))));
};
case 9:
return function() {
return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))));
};
}
}
const hole = null, SK = (_, b)=>b, globalStoreId = "effect/GlobalValue", GlobalValue_globalValue = (id, compute)=>(globalStore || (globalThis[globalStoreId] ??= new Map(), globalStore = globalThis[globalStoreId]), globalStore.has(id) || globalStore.set(id, compute()), globalStore.get(id)), mapInput = null, isTupleOf = null, isTupleOfAtLeast = null, isTruthy = (input)=>!!input, isSet = (input)=>input instanceof Set, isMap = (input)=>input instanceof Map, isString = (input)=>"string" == typeof input, isNumber = (input)=>"number" == typeof input, Predicate_isBoolean = (input)=>"boolean" == typeof input, isBigInt = (input)=>"bigint" == typeof input, isSymbol = (input)=>"symbol" == typeof input, isPropertyKey = (u)=>"string" == typeof u || isNumber(u) || "symbol" == typeof u, Predicate_isFunction = Function_isFunction, isUndefined = (input)=>void 0 === input, isNotUndefined = (input)=>void 0 !== input, isNull = (input)=>null === input, isNotNull = (input)=>null !== input, isNever = (_)=>!1, isUnknown = (_)=>!0, isRecordOrArray = (input)=>"object" == typeof input && null !== input, Predicate_isObject = (input)=>isRecordOrArray(input) || Function_isFunction(input), Predicate_hasProperty = Function_dual(2, (self, property)=>Predicate_isObject(self) && property in self), Predicate_isTagged = Function_dual(2, (self, tag)=>Predicate_hasProperty(self, "_tag") && self._tag === tag), isNullable = (input)=>null == input, isNotNullable = (input)=>null != input, isError = (input)=>input instanceof Error, isUint8Array = (input)=>input instanceof Uint8Array, isDate = (input)=>input instanceof Date, Predicate_isIterable = (input)=>"string" == typeof input || Predicate_hasProperty(input, Symbol.iterator), isRecord = (input)=>isRecordOrArray(input) && !Array.isArray(input), isReadonlyRecord = null, isPromise = (input)=>Predicate_hasProperty(input, "then") && "catch" in input && Function_isFunction(input.then) && Function_isFunction(input.catch), isPromiseLike = (input)=>Predicate_hasProperty(input, "then") && Function_isFunction(input.then), isRegExp = (input)=>input instanceof RegExp, Predicate_compose = null, product = (self, that)=>([a, b])=>self(a) && that(b), Predicate_all = (collection)=>(as)=>{
let collectionIndex = 0;
for (let p of collection){
if (collectionIndex >= as.length) break;
if (!1 === p(as[collectionIndex])) return !1;
collectionIndex++;
}
return !0;
}, productMany = (self, collection)=>{
let rest = Predicate_all(collection);
return ([head, ...tail])=>!1 !== self(head) && rest(tail);
}, Predicate_tuple = (...elements)=>Predicate_all(elements), struct = (fields)=>{
let keys = Object.keys(fields);
return (a)=>{
for (let key of keys)if (!fields[key](a[key])) return !1;
return !0;
};
}, not = (self)=>(a)=>!self(a), or = null, and = null, xor = null, eqv = null, implies = null, nor = null, nand = null, every = (collection)=>(a)=>{
for (let p of collection)if (!p(a)) return !1;
return !0;
}, some = (collection)=>(a)=>{
for (let p of collection)if (p(a)) return !0;
return !1;
}, getBugErrorMessage = (message)=>`BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`, GenKindTypeId = Symbol.for("effect/Gen/GenKind"), isGenKind = (u)=>isObject(u) && GenKindTypeId in u;
class GenKindImpl {
value;
constructor(value){
this.value = value;
}
get _F() {
return Function_identity;
}
get _R() {
return (_)=>_;
}
get _O() {
return (_)=>_;
}
get _E() {
return (_)=>_;
}
[GenKindTypeId] = GenKindTypeId;
[Symbol.iterator]() {
return new SingleShotGen(this);
}
}
class SingleShotGen {
self;
called = !1;
constructor(self){
this.self = self;
}
next(a) {
return this.called ? {
value: a,
done: !0
} : (this.called = !0, {
value: this.self,
done: !1
});
}
return(a) {
return {
value: a,
done: !0
};
}
throw(e) {
throw e;
}
[Symbol.iterator]() {
return new SingleShotGen(this.self);
}
}
const makeGenKind = (kind)=>new GenKindImpl(kind), adapter = ()=>function() {
let x = arguments[0];
for(let i = 1; i < arguments.length; i++)x = arguments[i](x);
return new GenKindImpl(x);
}, defaultIncHi = 0x14057b7e, defaultIncLo = 0xf767814f, MUL_HI = 1481765933, MUL_LO = 1284865837, BIT_53 = 9007199254740992.0, BIT_27 = 134217728.0;
class PCGRandom {
_state;
constructor(seedHi, seedLo, incHi, incLo){
return ((input)=>null == input)(seedLo) && ((input)=>null == input)(seedHi) ? (seedLo = 0xffffffff * Math.random() >>> 0, seedHi = 0) : ((input)=>null == input)(seedLo) && (seedLo = seedHi, seedHi = 0), ((input)=>null == input)(incLo) && ((input)=>null == input)(incHi) ? (incLo = this._state ? this._state[3] : 0xf767814f, incHi = this._state ? this._state[2] : 0x14057b7e) : ((input)=>null == input)(incLo) && (incLo = incHi, incHi = 0), this._state = new Int32Array([
0,
0,
incHi >>> 0,
(1 | (incLo || 0)) >>> 0
]), this._next(), add64(this._state, this._state[0], this._state[1], seedHi >>> 0, seedLo >>> 0), this._next(), this;
}
getState() {
return [
this._state[0],
this._state[1],
this._state[2],
this._state[3]
];
}
setState(state) {
this._state[0] = state[0], this._state[1] = state[1], this._state[2] = state[2], this._state[3] = 1 | state[3];
}
integer(max) {
return Math.round(this.number() * Number.MAX_SAFE_INTEGER) % max;
}
number() {
return (134217728.0 * ((0x03ffffff & this._next()) * 1.0) + (0x07ffffff & this._next()) * 1.0) / 9007199254740992.0;
}
_next() {
let oldHi = this._state[0] >>> 0, oldLo = this._state[1] >>> 0;
mul64(this._state, oldHi, oldLo, 1481765933, 1284865837), add64(this._state, this._state[0], this._state[1], this._state[2], this._state[3]);
let xsHi = oldHi >>> 18, xsLo = (oldLo >>> 18 | oldHi << 14) >>> 0;
xsHi = (xsHi ^ oldHi) >>> 0;
let xorshifted = ((xsLo = (xsLo ^ oldLo) >>> 0) >>> 27 | xsHi << 5) >>> 0, rot = oldHi >>> 27;
return (xorshifted >>> rot | xorshifted << ((-rot >>> 0 & 31) >>> 0)) >>> 0;
}
}
function mul64(out, aHi, aLo, bHi, bLo) {
let c1 = (aLo >>> 16) * (0xffff & bLo) >>> 0, c0 = (0xffff & aLo) * (bLo >>> 16) >>> 0, lo = (0xffff & aLo) * (0xffff & bLo) >>> 0, hi = (aLo >>> 16) * (bLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16)) >>> 0;
(lo = lo + (c0 = c0 << 16 >>> 0) >>> 0) >>> 0 < c0 >>> 0 && (hi = hi + 1 >>> 0), (lo = lo + (c1 = c1 << 16 >>> 0) >>> 0) >>> 0 < c1 >>> 0 && (hi = hi + 1 >>> 0), hi = (hi = hi + Math.imul(aLo, bHi) >>> 0) + Math.imul(aHi, bLo) >>> 0, out[0] = hi, out[1] = lo;
}
function add64(out, aHi, aLo, bHi, bLo) {
let hi = aHi + bHi >>> 0, lo = aLo + bLo >>> 0;
lo >>> 0 < aLo >>> 0 && (hi = hi + 1 | 0), out[0] = hi, out[1] = lo;
}
const YieldWrapTypeId = Symbol.for("effect/Utils/YieldWrap");
class YieldWrap {
#value;
constructor(value){
this.#value = value;
}
[YieldWrapTypeId]() {
return this.#value;
}
}
function Utils_yieldWrapGet(self) {
if ("object" == typeof self && null !== self && YieldWrapTypeId in self) return self[YieldWrapTypeId]();
throw Error(getBugErrorMessage("yieldWrapGet"));
}
const structuralRegionState = GlobalValue_globalValue("effect/Utils/isStructuralRegion", ()=>({
enabled: !1,
tester: void 0
})), structuralRegion = (body, tester)=>{
let current = structuralRegionState.enabled, currentTester = structuralRegionState.tester;
structuralRegionState.enabled = !0, tester && (structuralRegionState.tester = tester);
try {
return body();
} finally{
structuralRegionState.enabled = current, structuralRegionState.tester = currentTester;
}
}, standard = {
effect_internal_function: (body)=>body()
}, forced = {
effect_internal_function: (body)=>body()
}, isNotOptimizedAway = standard.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function") === !0, internalCall = isNotOptimizedAway ? standard.effect_internal_function : forced.effect_internal_function, genConstructor = null, Utils_isGeneratorFunction = (u)=>isObject(u) && null === u.constructor, randomHashCache = GlobalValue_globalValue(Symbol.for("effect/Hash/randomHashCache"), ()=>new WeakMap()), Hash_symbol = Symbol.for("effect/Hash"), Hash_hash = (self)=>{
if (!0 === structuralRegionState.enabled) return 0;
switch(typeof self){
case "number":
return number(self);
case "bigint":
return Hash_string(self.toString(10));
case "boolean":
case "symbol":
return Hash_string(String(self));
case "string":
return Hash_string(self);
case "undefined":
return Hash_string("undefined");
case "function":
case "object":
if (null === self) return Hash_string("null");
if (self instanceof Date) {
if (Number.isNaN(self.getTime())) return Hash_string("Invalid Date");
return Hash_hash(self.toISOString());
}
if (self instanceof URL) return Hash_hash(self.href);
else if (isHash(self)) return self[Hash_symbol]();
else return Hash_random(self);
default:
throw Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`);
}
}, Hash_random = (self)=>(randomHashCache.has(self) || randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))), randomHashCache.get(self)), Hash_combine = (b)=>(self)=>53 * self ^ b, optimize = (n)=>0xbfffffff & n | n >>> 1 & 0x40000000, isHash = (u)=>Predicate_hasProperty(u, Hash_symbol), number = (n)=>{
if (n != n || n === 1 / 0) return 0;
let h = 0 | n;
for(h !== n && (h ^= 0xffffffff * n); n > 0xffffffff;)h ^= n /= 0xffffffff;
return optimize(h);
}, Hash_string = (str)=>{
let h = 5381, i = str.length;
for(; i;)h = 33 * h ^ str.charCodeAt(--i);
return optimize(h);
}, structureKeys = (o, keys)=>{
let h = 12289;
for(let i = 0; i < keys.length; i++)h ^= Function_pipe(Hash_string(keys[i]), Hash_combine(Hash_hash(o[keys[i]])));
return optimize(h);
}, structure = (o)=>structureKeys(o, Object.keys(o)), Hash_array = (arr)=>{
let h = 6151;
for(let i = 0; i < arr.length; i++)h = Function_pipe(h, Hash_combine(Hash_hash(arr[i])));
return optimize(h);
}, Hash_cached = function() {
if (1 == arguments.length) {
let self = arguments[0];
return function(hash) {
return Object.defineProperty(self, Hash_symbol, {
value: ()=>hash,
enumerable: !1
}), hash;
};
}
let self = arguments[0], hash = arguments[1];
return Object.defineProperty(self, Hash_symbol, {
value: ()=>hash,
enumerable: !1
}), hash;
}, Equal_symbol = Symbol.for("effect/Equal");
function equals() {
return 1 == arguments.length ? (self)=>compareBoth(self, arguments[0]) : compareBoth(arguments[0], arguments[1]);
}
function compareBoth(self, that) {
if (self === that) return !0;
let selfType = typeof self;
if (selfType !== typeof that) return !1;
if ("object" === selfType || "function" === selfType) {
if (null !== self && null !== that) {
if (isEqual(self) && isEqual(that)) if (Hash_hash(self) === Hash_hash(that) && self[Equal_symbol](that)) return !0;
else return !!structuralRegionState.enabled && !!structuralRegionState.tester && structuralRegionState.test