@lomray/vite-ssr-boost 8.2.0 → 8.3.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -13
- package/SECURITY.md +1 -1
- package/adapters/express/entry.d.ts +1 -1
- package/adapters/express/entry.js.map +1 -1
- package/adapters/express/render.d.ts +4 -1
- package/adapters/express/render.js +1 -1
- package/adapters/express/render.js.map +1 -1
- package/browser/entry.d.ts +1 -0
- package/browser/entry.js +1 -1
- package/browser/entry.js.map +1 -1
- package/browser/stream.d.ts +5 -0
- package/browser/stream.js +2 -0
- package/browser/stream.js.map +1 -0
- package/cli/diagnostic-codes.d.ts +3 -0
- package/cli/diagnostic-codes.js +2 -0
- package/cli/diagnostic-codes.js.map +1 -0
- package/cli/doctor.d.ts +55 -0
- package/cli/doctor.js +2 -0
- package/cli/doctor.js.map +1 -0
- package/cli/init.d.ts +17 -0
- package/cli/init.js +2 -0
- package/cli/init.js.map +1 -0
- package/cli/project.d.ts +56 -0
- package/cli/project.js +2 -0
- package/cli/project.js.map +1 -0
- package/cli.js +1 -1
- package/cli.js.map +1 -1
- package/core/compose-html.d.ts +3 -4
- package/core/compose-html.js +1 -1
- package/core/compose-html.js.map +1 -1
- package/core/data-stream.d.ts +50 -0
- package/core/data-stream.js +2 -0
- package/core/data-stream.js.map +1 -0
- package/core/html-boundary.d.ts +7 -0
- package/core/html-boundary.js +2 -0
- package/core/html-boundary.js.map +1 -0
- package/core/render.d.ts +7 -1
- package/core/render.js +1 -1
- package/core/render.js.map +1 -1
- package/core/script.d.ts +6 -0
- package/core/script.js +2 -0
- package/core/script.js.map +1 -0
- package/edge/render-to-stream.js +1 -1
- package/edge/render-to-stream.js.map +1 -1
- package/helpers/build-custom-state.d.ts +1 -1
- package/helpers/build-custom-state.js +1 -1
- package/helpers/build-custom-state.js.map +1 -1
- package/helpers/build-router-state.d.ts +1 -1
- package/helpers/build-router-state.js +1 -1
- package/helpers/build-router-state.js.map +1 -1
- package/helpers/is-route-file.js +1 -1
- package/helpers/is-route-file.js.map +1 -1
- package/node/render-to-stream.js +1 -1
- package/node/render-to-stream.js.map +1 -1
- package/package.json +18 -6
- package/plugins/normalize-route.js +1 -1
- package/plugins/normalize-route.js.map +1 -1
- package/services/build.d.ts +1 -0
- package/services/build.js +1 -1
- package/services/build.js.map +1 -1
- package/services/diagnostics.d.ts +8 -3
- package/services/diagnostics.js +1 -1
- package/services/diagnostics.js.map +1 -1
- package/services/parse-routes.d.ts +17 -55
- package/services/parse-routes.js +1 -1
- package/services/parse-routes.js.map +1 -1
- package/services/path-normalize.js +1 -1
- package/services/path-normalize.js.map +1 -1
- package/services/source-files.d.ts +35 -0
- package/services/source-files.js +2 -0
- package/services/source-files.js.map +1 -0
- package/services/ssr-manifest.js +1 -1
- package/services/ssr-manifest.js.map +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { StaticHandlerContext } from 'react-router';
|
|
2
2
|
import Logger from './logger.js';
|
|
3
|
-
type TDiagnosticCode = 'SSR_BOOST_LOADER_NOT_SERIALIZABLE' | 'SSR_BOOST_STATE_NOT_SERIALIZABLE' | 'SSR_BOOST_OUTLET_MISSING' | 'SSR_BOOST_HYDRATION_STATE_MISSING' | 'SSR_BOOST_DUPLICATE_OUTPUT' | 'SSR_BOOST_ONRESPONSE_INVALID_RETURN';
|
|
3
|
+
type TDiagnosticCode = 'SSR_BOOST_LOADER_NOT_SERIALIZABLE' | 'SSR_BOOST_STREAM_PROMISE_ABORTED' | 'SSR_BOOST_STATE_NOT_SERIALIZABLE' | 'SSR_BOOST_OUTLET_MISSING' | 'SSR_BOOST_HYDRATION_STATE_MISSING' | 'SSR_BOOST_DUPLICATE_OUTPUT' | 'SSR_BOOST_ONRESPONSE_INVALID_RETURN';
|
|
4
4
|
interface ISerializationIssue {
|
|
5
5
|
path: string;
|
|
6
6
|
reason: string;
|
|
@@ -18,9 +18,10 @@ declare const formatDiagnostic: (code: TDiagnosticCode, sentence: string) => str
|
|
|
18
18
|
*/
|
|
19
19
|
declare const splitHtmlShell: (html: string, file: string, outlet?: string) => [string, string];
|
|
20
20
|
/**
|
|
21
|
-
*
|
|
21
|
+
* Custom state uses JSON. Router state also supports promises, Date, RegExp, bigint,
|
|
22
|
+
* Map and Set through the stream codec; functions, symbols, classes and cycles warn.
|
|
22
23
|
*/
|
|
23
|
-
declare const walkSerializable: (value: unknown, report: (issue: ISerializationIssue) => void, path?: string, ancestors?: Set<object
|
|
24
|
+
declare const walkSerializable: (value: unknown, report: (issue: ISerializationIssue) => void, path?: string, ancestors?: Set<object>, streamed?: boolean) => void;
|
|
24
25
|
/**
|
|
25
26
|
* Inspect one development response while allowing every chunk to stream immediately.
|
|
26
27
|
*/
|
|
@@ -44,6 +45,10 @@ declare class Diagnostics {
|
|
|
44
45
|
* Include React Router's route id and the full loader/action key path.
|
|
45
46
|
*/
|
|
46
47
|
inspectRouterState({ loaderData, actionData }: StaticHandlerContext): void;
|
|
48
|
+
/** Report the request's pending loader/action promises at the render deadline. */
|
|
49
|
+
streamAborted(count: number): void;
|
|
50
|
+
/** Inspect streamed resolutions with the same supported value matrix as initial data. */
|
|
51
|
+
inspectStreamValue(value: unknown, id: number): void;
|
|
47
52
|
/**
|
|
48
53
|
* Check custom state before the serializer can omit or coerce it.
|
|
49
54
|
*/
|
package/services/diagnostics.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"./logger.js";const e="\x3c!--ssr-outlet--\x3e",o="window.__staticRouterHydrationData",
|
|
1
|
+
import t from"./logger.js";const e="\x3c!--ssr-outlet--\x3e",o="window.__staticRouterHydrationData",r=Symbol.for("@lomray/vite-ssr-boost/diagnostics"),s=globalThis,n=t=>{const e="undefined"==typeof process?void 0:process.env;return"0"===e?.SSR_BOOST_DIAGNOSTICS||"1"===e?.SSR_BOOST_DIAGNOSTICS?"1"===e.SSR_BOOST_DIAGNOSTICS:t??"production"!==e?.NODE_ENV},i=(t,e)=>`[ssr-boost] ${t}: ${e} See https://lomray-software.github.io/vite-ssr-boost/reference/diagnostics#${t.toLowerCase()}`,a=(t,o,r=e)=>{const s=t.split(r);if(!r||2!==s.length)throw new Error(i("SSR_BOOST_OUTLET_MISSING",`Invalid HTML shell in ${JSON.stringify(o)}: expected exactly one non-empty outlet ${JSON.stringify(r)}.`));return s},S=t=>{if(null===t)return"null";if("object"!=typeof t){return{bigint:"BigInt",symbol:"Symbol"}[typeof t]??typeof t}const e=Object.getPrototypeOf(t),o=e?.constructor?.name;return"string"==typeof o&&o?o:"object"},c=(t,e,o="$",r=new Set,s=!1)=>{const n=typeof t;if(s&&(t instanceof Promise||t instanceof Date||t instanceof RegExp||"bigint"===n))return;if("function"===n||"bigint"===n||"symbol"===n)return void e({path:o,reason:`${S(t)} is not JSON-serializable`});if(null===t||"object"!==n)return;const i=t,a=Object.getPrototypeOf(i);if(!(s&&(i instanceof Map||i instanceof Set)||a===Object.prototype||null===a||Array.isArray(i)&&a===Array.prototype)){const t=S(i);return void e({path:o,reason:"Date"===t?"Date hydrates as a string":`${t} is not JSON-serializable`})}if(r.has(i))return void e({path:o,reason:"a circular reference is not JSON-serializable"});r.add(i);const f=s&&i instanceof Map?[...i].flatMap(([t,e],o)=>[[`${o}.key`,t],[`${o}.value`,e]]):s&&i instanceof Set?[...i].map((t,e)=>[String(e),t]):Object.entries(i);for(const[t,n]of f){const a=Array.isArray(i)&&/^(0|[1-9]\d*)$/.test(t)?`[${t}]`:/^[A-Za-z_$][\w$]*$/.test(t)?`.${t}`:`[${JSON.stringify(t)}]`;c(n,e,o+a,r,s)}r.delete(i)};class f{route;logger;chunks=[];constructor(e,o=new t){this.route=e,this.logger=o}warn(t,e){const o=i(t,e),n=s[r]??=new Set;n.has(o)||(n.add(o),this.logger.warn(o,{}))}inspectShell({header:t,footer:o}){("string"!=typeof t||"string"!=typeof o||t.includes(e)||o.includes(e))&&this.warn("SSR_BOOST_OUTLET_MISSING",`HTML shell for route ${JSON.stringify(this.route)} must supply both header and footer around exactly one ${e} outlet, with no outlet left in either half.`)}inspectRouterState({loaderData:t,actionData:e}){for(const[o,r]of Object.entries({loaderData:t,actionData:e}))for(const[t,e]of Object.entries(r??{}))c(e,({path:e,reason:o})=>this.warn("SSR_BOOST_LOADER_NOT_SERIALIZABLE",`Route ${JSON.stringify(t)} at ${e}: ${o}.`),`${o}[${JSON.stringify(t)}]`,new Set,!0)}streamAborted(t){this.warn("SSR_BOOST_STREAM_PROMISE_ABORTED",`Route ${JSON.stringify(this.route)} aborted with ${t} pending loader/action promise(s); the browser receives a rejection when connected.`)}inspectStreamValue(t,e){c(t,({path:t,reason:e})=>this.warn("SSR_BOOST_LOADER_NOT_SERIALIZABLE",`Route ${JSON.stringify(this.route)} at ${t}: ${e}.`),`promise[${e}]`,new Set,!0)}inspectState(t){c(t,({path:t,reason:e})=>this.warn("SSR_BOOST_STATE_NOT_SERIALIZABLE",`getState for route ${JSON.stringify(this.route)} at ${t}: ${e}.`))}inspectOnResponse(t){void 0!==t&&"string"!=typeof t&&this.warn("SSR_BOOST_ONRESPONSE_INVALID_RETURN",`onResponse for route ${JSON.stringify(this.route)} returned ${S(t)}; return a string or undefined.`)}append(t){this.chunks.push(t)}complete(){const t=this.chunks.join("");this.chunks=[];const e=new Map,r=t=>{e.set(t,(e.get(t)??0)+1)},s=t.replace(/<!--[\s\S]*?-->/g,"").replace(/(<(script|style|textarea|title)\b(?:[^"'<>]|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/\2\s*>/gi,(t,e,s,n)=>{if("script"===s.toLowerCase()){/\bwindow\.__staticRouterHydrationData\s*=/.test(n)&&r(o);for(const t of n.matchAll(/\$RC\s*\(\s*(["'])(B:[^"']+)\1/g))r(`$RC("${t[2]}")`)}return e});for(const t of s.matchAll(/<([a-z][\w:-]*)\b((?:[^"'<>]|"[^"]*"|'[^']*')*)>/gi)){const e=t[1].toLowerCase();"html"!==e&&"head"!==e||r(`<${e}>`);for(const e of t[2].matchAll(/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)){const t=e[2]??e[3]??e[4];"id"===e[1].toLowerCase()&&/^(S|B):/.test(t)&&r(`id="${t}"`)}}e.has(o)||this.warn("SSR_BOOST_HYDRATION_STATE_MISSING",`Completed response for route ${JSON.stringify(this.route)} has no ${o} script; preserve the hydration footer in onResponse.`);for(const[t,o]of e)o>1&&this.warn("SSR_BOOST_DUPLICATE_OUTPUT",`Completed response for route ${JSON.stringify(this.route)} repeats ${t}; onResponse must return undefined to keep a chunk and '' to withhold one.`)}}export{f as default,i as formatDiagnostic,n as isDiagnosticsEnabled,a as splitHtmlShell,c as walkSerializable};
|
|
2
2
|
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","sources":["../../src/services/diagnostics.ts"],"sourcesContent":[null],"names":["OUTLET","HYDRATION","warnedKey","Symbol","for","registry","globalThis","isDiagnosticsEnabled","enabled","env","process","undefined","SSR_BOOST_DIAGNOSTICS","NODE_ENV","formatDiagnostic","code","sentence","toLowerCase","splitHtmlShell","html","file","outlet","parts","split","length","Error","JSON","stringify","valueType","value","bigint","symbol","prototype","Object","getPrototypeOf","name","constructor","walkSerializable","report","path","ancestors","Set","type","reason","object","Array","isArray","has","add","key","child","
|
|
1
|
+
{"version":3,"file":"diagnostics.js","sources":["../../src/services/diagnostics.ts"],"sourcesContent":[null],"names":["OUTLET","HYDRATION","warnedKey","Symbol","for","registry","globalThis","isDiagnosticsEnabled","enabled","env","process","undefined","SSR_BOOST_DIAGNOSTICS","NODE_ENV","formatDiagnostic","code","sentence","toLowerCase","splitHtmlShell","html","file","outlet","parts","split","length","Error","JSON","stringify","valueType","value","bigint","symbol","prototype","Object","getPrototypeOf","name","constructor","walkSerializable","report","path","ancestors","Set","streamed","type","Promise","Date","RegExp","reason","object","Map","Array","isArray","has","add","entries","flatMap","key","child","index","map","String","suffix","test","delete","Diagnostics","route","logger","chunks","Logger","this","warn","detail","message","warned","inspectShell","header","footer","includes","inspectRouterState","loaderData","actionData","kind","data","streamAborted","count","inspectStreamValue","id","inspectState","state","inspectOnResponse","append","push","complete","join","markers","marker","set","get","markup","replace","_tag","opening","content","match","matchAll","attribute","total"],"mappings":"2BAiBA,MAAMA,EAAS,0BACTC,EAAY,qCACZC,EAAYC,OAAOC,IAAI,sCAEvBC,EAAWC,WAKXC,EAAwBC,IAC5B,MAAMC,EAAyB,oBAAZC,aAA0BC,EAAYD,QAAQD,IAEjE,MAAmC,MAA/BA,GAAKG,uBAAgE,MAA/BH,GAAKG,sBACR,MAA9BH,EAAIG,sBAGNJ,GAA6B,eAAlBC,GAAKI,UAMnBC,EAAmB,CAACC,EAAuBC,IAC/C,eAAeD,MAASC,gFAAuFD,EAAKE,gBAKhHC,EAAiB,CAACC,EAAcC,EAAcC,EAASrB,KAC3D,MAAMsB,EAAQH,EAAKI,MAAMF,GAEzB,IAAKA,GAA2B,IAAjBC,EAAME,OACnB,MAAM,IAAIC,MACRX,EACE,2BACA,yBAAyBY,KAAKC,UAAUP,6CAAgDM,KAAKC,UAAUN,QAK7G,OAAOC,GAMHM,EAAaC,IACjB,GAAc,OAAVA,EACF,MAAO,OAGT,GAAqB,iBAAVA,EAAoB,CAG7B,MAFsC,CAAEC,OAAQ,SAAUC,OAAQ,iBAE9CF,WAAiBA,CACvC,CAEA,MAAMG,EAAYC,OAAOC,eAAeL,GAClCM,EAAOH,GAAWI,aAAaD,KAErC,MAAuB,iBAATA,GAAqBA,EAAOA,EAAO,UAO7CE,EAAmB,CACvBR,EACAS,EACAC,EAAO,IACPC,EAAY,IAAIC,IAChBC,GAAW,KAEX,MAAMC,SAAcd,EAEpB,GACEa,IACCb,aAAiBe,SAChBf,aAAiBgB,MACjBhB,aAAiBiB,QACR,WAATH,GAEF,OAGF,GAAa,aAATA,GAAgC,WAATA,GAA8B,WAATA,EAG9C,YAFAL,EAAO,CAAEC,OAAMQ,OAAQ,GAAGnB,EAAUC,gCA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,QAAAyE,GACL,MAAMzE,EAAOkD,KAAKF,OAAO0B,KAAK,IAE9BxB,KAAKF,OAAS,GAEd,MAAM2B,EAAU,IAAI7C,IACdmC,EAASW,IACbD,EAAQE,IAAID,GAASD,EAAQG,IAAIF,IAAW,GAAK,IAG7CG,EAAS/E,EACZgF,QAAQ,mBAAoB,IAC5BA,QACC,uFACA,CAACC,EAAMC,EAAiBlE,EAAcmE,KACpC,GAA2B,WAAvBnE,EAAKlB,cAA4B,CAC/B,4CAA4C6C,KAAKwC,IACnDlB,EAAMnF,GAGR,IAAK,MAAMsG,KAASD,EAAQE,SAAS,mCACnCpB,EAAM,QAAQmB,EAAM,OAExB,CAEA,OAAOF,IAIb,IAAK,MAAME,KAASL,EAAOM,SAAS,sDAAuD,CACzF,MAAMrE,EAAOoE,EAAM,GAAGtF,cAET,SAATkB,GAA4B,SAATA,GACrBiD,EAAM,IAAIjD,MAGZ,IAAK,MAAMsE,KAAaF,EAAM,GAAGC,SAC/B,sDACC,CACD,MAAM3E,EAAQ4E,EAAU,IAAMA,EAAU,IAAMA,EAAU,GAErB,OAA/BA,EAAU,GAAGxF,eAA0B,UAAU6C,KAAKjC,IACxDuD,EAAM,OAAOvD,KAEjB,CACF,CAEKiE,EAAQ1C,IAAInD,IACfoE,KAAKC,KACH,oCACA,gCAAgC5C,KAAKC,UAAU0C,KAAKJ,iBAAiBhE,0DAIzE,IAAK,MAAO8F,EAAQW,KAAUZ,EACxBY,EAAQ,GACVrC,KAAKC,KACH,6BACA,gCAAgC5C,KAAKC,UAAU0C,KAAKJ,kBAAkB8B,8EAI9E"}
|
|
@@ -1,67 +1,29 @@
|
|
|
1
|
+
import type { Node as BabelNode } from '@babel/types';
|
|
1
2
|
import type { Alias } from 'vite';
|
|
2
|
-
import PathNormalize from './path-normalize.js';
|
|
3
3
|
import type ServerConfig from './server-config.js';
|
|
4
|
+
import SourceFiles from './source-files.js';
|
|
5
|
+
import type { ISourceValue } from './source-files.js';
|
|
4
6
|
export type TRoutesTree = {
|
|
5
7
|
index: number;
|
|
8
|
+
id?: string;
|
|
9
|
+
path?: string | null;
|
|
6
10
|
import: string;
|
|
7
11
|
children: TRoutesTree[];
|
|
8
12
|
};
|
|
9
|
-
/**
|
|
10
|
-
|
|
11
|
-
*/
|
|
13
|
+
/** Get the one statically named module loaded by a lazy route. */
|
|
14
|
+
export declare const lazyImport: ({ node, file }: ISourceValue) => string;
|
|
15
|
+
/** Static React Router route analysis; never imports application code. */
|
|
12
16
|
declare class ParseRoutes {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
*/
|
|
17
|
+
private readonly config;
|
|
18
|
+
private readonly viteAliases?;
|
|
16
19
|
private static unwrapExpression;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
*/
|
|
24
|
-
protected readonly config: ServerConfig;
|
|
25
|
-
/**
|
|
26
|
-
* @constructor
|
|
27
|
-
*/
|
|
28
|
-
constructor(config: ServerConfig, viteAliases?: Alias[]);
|
|
29
|
-
/**
|
|
30
|
-
* Parse routes
|
|
31
|
-
*/
|
|
32
|
-
parse(): TRoutesTree[];
|
|
33
|
-
/**
|
|
34
|
-
* Parse file and return ast
|
|
35
|
-
*/
|
|
36
|
-
private parseFile;
|
|
37
|
-
/**
|
|
38
|
-
* Find route import filepath
|
|
39
|
-
*/
|
|
40
|
-
private getImportPath;
|
|
41
|
-
/**
|
|
42
|
-
* Find routes array inside code
|
|
43
|
-
*/
|
|
44
|
-
private findRoutesDefinition;
|
|
45
|
-
/**
|
|
46
|
-
* Entrypoint routes file
|
|
47
|
-
*/
|
|
48
|
-
private findRoutesEntrypoint;
|
|
49
|
-
/**
|
|
50
|
-
* Resolve route filename import
|
|
51
|
-
*/
|
|
52
|
-
private resolveFilename;
|
|
53
|
-
/**
|
|
54
|
-
* Parse ast array routes objects
|
|
55
|
-
*/
|
|
56
|
-
private parseRoutesArray;
|
|
57
|
-
/**
|
|
58
|
-
* Parse imports map from ast
|
|
59
|
-
*/
|
|
20
|
+
constructor(config: ServerConfig, viteAliases?: Alias[] | undefined);
|
|
21
|
+
/** Locate the library entry by its import binding, not its local spelling. */
|
|
22
|
+
parse(includeEmpty?: boolean): TRoutesTree[];
|
|
23
|
+
/** Also used to validate a proposed migration before any files are written. */
|
|
24
|
+
parseValue(sources: SourceFiles, value: ISourceValue, includeEmpty?: boolean, ancestors?: Set<BabelNode>): TRoutesTree[];
|
|
25
|
+
private assetPath;
|
|
60
26
|
private static parseImportsMap;
|
|
61
|
-
/**
|
|
62
|
-
* Recursive build routes tree with dynamic imports
|
|
63
|
-
*/
|
|
64
|
-
private recursiveBuildRoutesTree;
|
|
65
27
|
/**
|
|
66
28
|
* Add pathId to static routes
|
|
67
29
|
*/
|
|
@@ -70,6 +32,6 @@ declare class ParseRoutes {
|
|
|
70
32
|
* Inject pathId to sync/async routes
|
|
71
33
|
* Add async wrapper (see import-routes)
|
|
72
34
|
*/
|
|
73
|
-
static handleRoutes(code: string, shouldAddPathId: boolean): string;
|
|
35
|
+
static handleRoutes(code: string, shouldAddPathId: boolean, filename?: string): string;
|
|
74
36
|
}
|
|
75
37
|
export default ParseRoutes;
|
package/services/parse-routes.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"
|
|
1
|
+
import e from"node:path";import t from"@babel/generator";import*as r from"@babel/parser";import o from"@babel/traverse";import{isObjectProperty as n,isFunction as i,isBooleanLiteral as s,isJSXElement as a,isIdentifier as l,isArrayExpression as p,objectProperty as u,identifier as c,stringLiteral as m,isJSXIdentifier as f,isObjectExpression as d}from"@babel/types";import y from"../constants/plugin-name.js";import h,{unwrap as g,walk as v,sourceError as w,propertyName as b}from"./source-files.js";const x=t.default??t,E=o.default??o,I=({node:e,file:t})=>{const r=g(e);if("ArrowFunctionExpression"!==r.type&&"FunctionExpression"!==r.type)throw w(t,r,"lazy route; use a function importing one literal module");let o=g(r.body);if("BlockStatement"===o?.type){if(1!==o.body.length||"ReturnStatement"!==o.body[0].type)throw w(t,r,"lazy function body; return one literal import (optionally with .then)");o=g(o.body[0].argument)}if("AwaitExpression"===o?.type&&(o=g(o.argument)),"CallExpression"===o?.type&&"MemberExpression"===o.callee.type&&"Identifier"===o.callee.property.type&&"then"===o.callee.property.name&&(o=g(o.callee.object)),"ImportExpression"!==o?.type)throw w(t,o,"lazy route result; return one literal import (optionally with .then)");const n=[];if(v(r,e=>{if("ImportExpression"===e.type){if("StringLiteral"!==e.source.type)throw w(t,e,"dynamic lazy import; use a string literal");n.push(e.source.value)}}),1!==n.length)throw w(t,r,`lazy route with ${n.length} imports; use exactly one literal module`);return n[0]};class S{config;viteAliases;static unwrapExpression=g;constructor(e,t){this.config=e,this.viteAliases=t}parse(t=!1){const{clientFile:r,root:o}=this.config.getParams(),n=e.resolve(o,r),i=new h(this.viteAliases??this.config.getVite()?.config.resolve.alias),s=[];if(v(i.read(n).ast,e=>{if("CallExpression"!==e.type||"Identifier"!==e.callee.type)return;const t=i.import(n,e.callee.name);if(t?.source.replace(/\.js$/,"")===`${y}/browser/entry`&&["default","entry"].includes(t.exported)){if(!e.arguments[1])throw w(n,e,"browser entry routes argument");s.push({node:e.arguments[1],file:n})}}),1!==s.length)throw w(n,s[1]?.node,`browser entry calls (${s.length}); expected one library browser/entry call`);return this.parseValue(i,s[0],t)}parseValue(e,t,r=!1,o=new Set){const{node:n,file:i}=e.resolve(t);if("ArrayExpression"!==n.type||o.has(n))throw w(i,n,"routes array; use a static, non-circular array");const s=new Set([...o,n]),a=[];return n.elements.forEach((t,o)=>{if(!t)throw w(i,n,"empty route array entry; use route objects");if("SpreadElement"===t.type)throw w(i,t,"route array spread; declare array entries explicitly");const l=e.properties({node:t,file:i}),p={index:o,import:"",children:[]},u=l.get("id"),c=l.get("path"),m=l.get("children"),f=l.get("lazy");if(u){const t=e.resolve(u);if("StringLiteral"!==t.node.type)throw w(t.file,t.node,"route id; use a static string");p.id=t.node.value}if(c){const e=g(c.node);p.path="StringLiteral"===e?.type?e.value:null}if(m&&(p.children=this.parseValue(e,m,r,s)),f){const t=e.resolve(f);p.import=this.assetPath(I(t),t.file)}else{const t=l.get("Component")??l.get("element"),r=g(t?.node),o="Identifier"===r?.type?r.name:"JSXElement"===r?.type&&"JSXIdentifier"===r.openingElement.name.type?r.openingElement.name.name:void 0,n=t&&o?e.import(t.file,o):void 0;n?p.import=this.assetPath(n.source,t.file):t&&(p.import=t.file)}(r||p.import||p.children.length)&&a.push(p)}),a}assetPath(t,r){return t.startsWith(".")?e.resolve(e.dirname(r),t):t}static parseImportsMap(e){const t={};for(const r of e.program.body)if("ImportDeclaration"===r.type)for(const e of r.specifiers)t[e.local.name]={path:r.source.value,isDefault:"ImportDefaultSpecifier"===e.type};return t}static processRouteFileCode(t,r,o,y,h,v){t.node.properties.forEach(w=>{if(n(w)){const x=b(w);if("lazy"===x&&i(g(w.value))){const r=g(w.value),f=I({node:r,file:h}),d=t.node.properties.find(e=>n(e)&&"onlyClient"===b(e));if(w.value={type:"CallExpression",callee:{type:"Identifier",name:v},arguments:n(d)&&(s(d.value)||a(d.value)||i(d.value)||l(d.value))?[w.value,d.value]:[w.value]},d&&(t.node.properties=t.node.properties.filter(e=>e!==d)),y(),f){const r=t.findParent?.(e=>p(S.unwrapExpression(e.node)));if(r&&f&&o){const r=u(c("pathId"),m(f.startsWith(".")&&e.isAbsolute(h)?e.resolve(e.dirname(h),f):f));t.node.properties.splice(t.node.properties.indexOf(w)+1,0,r)}}}if("element"===x||"Component"===x){let n="";a(w.value)&&f(w.value.openingElement.name)?n=w.value.openingElement.name.name:l(w.value)&&(n=w.value.name);const i=t.findParent?.(e=>p(S.unwrapExpression(e.node))),s=r[n]?.path;if(i&&s&&o){const r=u(c("pathId"),m(s.startsWith(".")&&e.isAbsolute(h)?e.resolve(e.dirname(h),s):s));t.node.properties.splice(t.node.properties.indexOf(w)+1,0,r)}}const E=S.unwrapExpression(w.value);"children"===x&&p(E)&&E.elements.forEach(e=>{d(e)&&S.processRouteFileCode({node:e},r,o,y,h,v)})}})}static handleRoutes(e,t,o="routes"){if(!e)return e;const n=r.parse(e,{sourceType:"module",createImportExpressions:!0,plugins:["typescript","jsx"]});if(!n)return e;const i=S.parseImportsMap(n);let s=!1,a="n";return E(n,{Program(e){e.scope.hasBinding(a)&&(a=e.scope.generateUidIdentifier("importRoute").name)}}),E(n,{ObjectExpression(e){S.processRouteFileCode(e,i,t,()=>{s=!0},o,a)}}),s&&n.program.body.unshift({type:"ImportDeclaration",specifiers:[{type:"ImportDefaultSpecifier",local:{type:"Identifier",name:a}}],source:{type:"StringLiteral",value:`${y}/helpers/import-route`}}),x(n,{retainLines:!0}).code}}export{S as default,I as lazyImport};
|
|
2
2
|
//# sourceMappingURL=parse-routes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse-routes.js","sources":["../../src/services/parse-routes.ts"],"sourcesContent":[null],"names":["generate","babelGenerate","default","traverse","babelTraverse","
|
|
1
|
+
{"version":3,"file":"parse-routes.js","sources":["../../src/services/parse-routes.ts"],"sourcesContent":[null],"names":["generate","babelGenerate","default","traverse","babelTraverse","lazyImport","node","file","value","unwrap","type","sourceError","result","body","length","argument","callee","property","name","object","imports","walk","child","source","push","ParseRoutes","config","viteAliases","static","constructor","this","parse","includeEmpty","clientFile","root","getParams","path","resolve","sources","SourceFiles","getVite","alias","calls","read","ast","imported","import","replace","PLUGIN_NAME","includes","exported","arguments","parseValue","ancestors","Set","has","next","results","elements","forEach","element","index","properties","route","children","id","get","routePath","lazy","resolved","literal","assetPath","component","componentNode","openingElement","undefined","specifier","startsWith","dirname","parseImportsMap","program","specifiers","local","isDefault","processRouteFileCode","nodePath","importsMap","shouldAddPathId","addImportRouteWrapper","filename","wrapperName","isObjectProperty","key","propertyName","isFunction","lazyValue","importPath","onlyClientProp","find","p","isBooleanLiteral","isJSXElement","isIdentifier","filter","parent","findParent","isArrayExpression","unwrapExpression","pathIdProperty","objectProperty","identifier","stringLiteral","isAbsolute","splice","indexOf","componentName","isJSXIdentifier","importName","isObjectExpression","handleRoutes","code","parser","sourceType","createImportExpressions","plugins","shouldAddRoutesImport","Program","scope","hasBinding","generateUidIdentifier","ObjectExpression","unshift","retainLines"],"mappings":"mfAiCA,MAAMA,EAAYC,EAAcC,SAAWD,EAErCE,EAAYC,EAAcF,SAAWE,EAe9BC,EAAa,EAAGC,OAAMC,WACjC,MAAMC,EAAQC,EAAOH,GAErB,GAAmB,4BAAfE,EAAME,MAAqD,uBAAfF,EAAME,KACpD,MAAMC,EAAYJ,EAAMC,EAAO,2DAGjC,IAAII,EAASH,EAAOD,EAAMK,MAE1B,GAAqB,mBAAjBD,GAAQF,KAA2B,CACrC,GAA2B,IAAvBE,EAAOC,KAAKC,QAAwC,oBAAxBF,EAAOC,KAAK,GAAGH,KAC7C,MAAMC,EACJJ,EACAC,EACA,yEAIJI,EAASH,EAAOG,EAAOC,KAAK,GAAGE,SACjC,CAeA,GAbqB,oBAAjBH,GAAQF,OACVE,EAASH,EAAOG,EAAOG,WAIN,mBAAjBH,GAAQF,MACe,qBAAvBE,EAAOI,OAAON,MACkB,eAAhCE,EAAOI,OAAOC,SAASP,MACS,SAAhCE,EAAOI,OAAOC,SAASC,OAEvBN,EAASH,EAAOG,EAAOI,OAAOG,SAGX,qBAAjBP,GAAQF,KACV,MAAMC,EACJJ,EACAK,EACA,wEAIJ,MAAMQ,EAAoB,GAa1B,GAXAC,EAAKb,EAAQc,IAEX,GAAmB,qBAAfA,EAAMZ,KAA6B,CACrC,GAA0B,kBAAtBY,EAAMC,OAAOb,KACf,MAAMC,EAAYJ,EAAMe,EAAO,6CAGjCF,EAAQI,KAAKF,EAAMC,OAAOf,MAC5B,IAGqB,IAAnBY,EAAQN,OACV,MAAMH,EACJJ,EACAC,EACA,mBAAmBY,EAAQN,kDAI/B,OAAOM,EAAQ,IAIjB,MAAMK,EAIeC,OACAC,YAJXC,wBAA0BnB,EAElC,WAAAoB,CACmBH,EACAC,GADAG,KAA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EACAC,EACAC,IAKV,GAEJ,CAMO,mBAAO6B,CAAaC,EAAcjC,EAA0BE,EAAW,UAC5E,IAAK+B,EACH,OAAOA,EAGT,MAAM5E,EAAM6E,EAAO1F,MAAMyF,EAAM,CAC7BE,WAAY,SACZC,yBAAyB,EACzBC,QAAS,CAAC,aAAc,SAG1B,IAAKhF,EACH,OAAO4E,EAGT,MAAMlC,EAAa7D,EAAYsD,gBAAgBnC,GAC/C,IAAIiF,GAAwB,EACxBnC,EAAc,IA4ClB,OA1CAvF,EAASyC,EAAK,CACZ,OAAAkF,CAAQzC,GACFA,EAAS0C,MAAMC,WAAWtC,KAC5BA,EAAcL,EAAS0C,MAAME,sBAAsB,eAAe/G,KAEtE,IAGFf,EAASyC,EAAK,CACZ,gBAAAsF,CAAiB7C,GACf5D,EAAY2D,qBACVC,EACAC,EACAC,EACA,KACEsC,GAAwB,GAE1BpC,EACAC,EAEJ,IAGEmC,GACFjF,EAAIoC,QAAQnE,KAAKsH,QAAQ,CACvBzH,KAAM,oBACNuE,WAAY,CACV,CACEvE,KAAM,yBACNwE,MAAO,CACLxE,KAAM,aACNQ,KAAMwE,KAIZnE,OAAQ,CACNb,KAAM,gBACNF,MAAO,GAAGwC,4BAKThD,EAAS4C,EAAK,CACnBwF,aAAa,IACZZ,IACL"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"node:fs";import s from"path";class e{viteAliases;config;constructor(t,s){this.config=t,this.viteAliases=s??t.getVite()?.config?.resolve.alias}getAliases(){const t={};return this.viteAliases?.forEach(({find:s,replacement:e})=>{"string"==typeof s&&(t[s]=e)}),t}getImportPostfix(){return["","/index"].map(t=>["",".js",".ts",".tsx"].map(s=>`${t}${s}`)).flat()}getAppPath(t,e=!1){if(!t)return;const{root:i}=this.config.getParams();let r=t;if(t.startsWith("./")||t.startsWith("../"))r=s.resolve(i,t);else{const s=this.getAliases(),[e]=t.split("/");s[e]&&(r=t.replace(e,s[e]))}return r=r.split(s.win32.sep).join(s.posix.sep),e?r:r.replace(i,"").replace(/^(\/)|(\/)$/g,"")}findAppFile(s){const e=this.getImportPostfix();for(const i of e){const e=`${s}${i}`;if(t.existsSync(e)&&t.statSync(e).isFile())return e}return null}}export{e as default};
|
|
1
|
+
import t from"node:fs";import s from"path";class e{viteAliases;config;constructor(t,s){this.config=t,this.viteAliases=s??t.getVite()?.config?.resolve.alias}getAliases(){const t={};return this.viteAliases?.forEach(({find:s,replacement:e})=>{"string"==typeof s&&(t[s]=e)}),t}getImportPostfix(){return["","/index"].map(t=>["",".js",".ts",".tsx",".jsx",".mjs",".mts"].map(s=>`${t}${s}`)).flat()}getAppPath(t,e=!1){if(!t)return;const{root:i}=this.config.getParams();let r=t;if(t.startsWith("./")||t.startsWith("../"))r=s.resolve(i,t);else{const s=this.getAliases(),[e]=t.split("/");s[e]&&(r=t.replace(e,s[e]))}return r=r.split(s.win32.sep).join(s.posix.sep),e?r:r.replace(i,"").replace(/^(\/)|(\/)$/g,"")}findAppFile(s){const e=this.getImportPostfix();for(const i of e){const e=`${s}${i}`;if(t.existsSync(e)&&t.statSync(e).isFile())return e}return null}}export{e as default};
|
|
2
2
|
//# sourceMappingURL=path-normalize.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path-normalize.js","sources":["../../src/services/path-normalize.ts"],"sourcesContent":[null],"names":["PathNormalize","viteAliases","config","constructor","this","getVite","resolve","alias","getAliases","aliases","forEach","find","replacement","getImportPostfix","map","prefix","ext","flat","getAppPath","appPath","withRoot","root","getParams","fullPath","startsWith","path","routeAlias","split","replace","win32","sep","join","posix","findAppFile","basePath","postfixes","postfix","filepath","fs","existsSync","statSync","isFile"],"mappings":"2CAQA,MAAMA,EAIeC,YAKAC,OAKnB,WAAAC,CAAYD,EAAsBD,GAChCG,KAAKF,OAASA,EACdE,KAAKH,YAAcA,GAAeC,EAAOG,WAAWH,QAAQI,QAAQC,KACtE,CAKO,UAAAC,GACL,MAAMC,EAAkC,CAAA,EAUxC,OARAL,KAAKH,aAAaS,QAAQ,EAAGC,OAAMC,kBACb,iBAATD,IAIXF,EAAQE,GAAQC,KAGXH,CACT,CAKO,gBAAAI,GACL,MAAO,CAAC,GAAI,UACTC,IAAKC,
|
|
1
|
+
{"version":3,"file":"path-normalize.js","sources":["../../src/services/path-normalize.ts"],"sourcesContent":[null],"names":["PathNormalize","viteAliases","config","constructor","this","getVite","resolve","alias","getAliases","aliases","forEach","find","replacement","getImportPostfix","map","prefix","ext","flat","getAppPath","appPath","withRoot","root","getParams","fullPath","startsWith","path","routeAlias","split","replace","win32","sep","join","posix","findAppFile","basePath","postfixes","postfix","filepath","fs","existsSync","statSync","isFile"],"mappings":"2CAQA,MAAMA,EAIeC,YAKAC,OAKnB,WAAAC,CAAYD,EAAsBD,GAChCG,KAAKF,OAASA,EACdE,KAAKH,YAAcA,GAAeC,EAAOG,WAAWH,QAAQI,QAAQC,KACtE,CAKO,UAAAC,GACL,MAAMC,EAAkC,CAAA,EAUxC,OARAL,KAAKH,aAAaS,QAAQ,EAAGC,OAAMC,kBACb,iBAATD,IAIXF,EAAQE,GAAQC,KAGXH,CACT,CAKO,gBAAAI,GACL,MAAO,CAAC,GAAI,UACTC,IAAKC,GACJ,CAAC,GAAI,MAAO,MAAO,OAAQ,OAAQ,OAAQ,QAAQD,IAAKE,GAAQ,GAAGD,IAASC,MAE7EC,MACL,CAKO,UAAAC,CAAWC,EAAkBC,GAAW,GAC7C,IAAKD,EACH,OAGF,MAAME,KAAEA,GAASjB,KAAKF,OAAOoB,YAC7B,IAAIC,EAAWJ,EAGf,GAAIA,EAAQK,WAAW,OAASL,EAAQK,WAAW,OACjDD,EAAWE,EAAKnB,QAAQe,EAAMF,OACzB,CAEL,MAAMV,EAAUL,KAAKI,cAEdkB,GAAcP,EAAQQ,MAAM,KAE/BlB,EAAQiB,KACVH,EAAWJ,EAAQS,QAAQF,EAAYjB,EAAQiB,IAEnD,CAKA,OAFAH,EAAWA,EAASI,MAAMF,EAAKI,MAAMC,KAAKC,KAAKN,EAAKO,MAAMF,KAEtDV,EACKG,EAGFA,EAASK,QAAQP,EAAM,IAAIO,QAAQ,eAAgB,GAC5D,CAKO,WAAAK,CAAYC,GACjB,MAAMC,EAAY/B,KAAKS,mBAEvB,IAAK,MAAMuB,KAAWD,EAAW,CAC/B,MAAME,EAAW,GAAGH,IAAWE,IAE/B,GAAIE,EAAGC,WAAWF,IAAaC,EAAGE,SAASH,GAAUI,SACnD,OAAOJ,CAEX,CAEA,OAAO,IACT"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { File, Node, ObjectExpression, ImportDeclaration } from '@babel/types';
|
|
2
|
+
import type { Alias } from 'vite';
|
|
3
|
+
export interface ISourceValue {
|
|
4
|
+
node: Node;
|
|
5
|
+
file: string;
|
|
6
|
+
}
|
|
7
|
+
export interface ISourceFile {
|
|
8
|
+
code: string;
|
|
9
|
+
ast: File;
|
|
10
|
+
}
|
|
11
|
+
/** Strip syntax that has no runtime effect. */
|
|
12
|
+
export declare const unwrap: (node: Node | null | undefined) => Node | undefined;
|
|
13
|
+
/** Walk syntax without evaluating application code or following type metadata. */
|
|
14
|
+
export declare const walk: (node: Node, visit: (child: Node) => void) => void;
|
|
15
|
+
/** A single actionable error, including the original source location. */
|
|
16
|
+
export declare const sourceError: (file: string, node: Node | undefined, construct: string) => Error;
|
|
17
|
+
/** Property names whose meaning is known without executing an expression. */
|
|
18
|
+
export declare const propertyName: (node: ObjectExpression["properties"][number]) => string | undefined;
|
|
19
|
+
/** Static module bindings shared by migration and route analysis. */
|
|
20
|
+
declare class SourceFiles {
|
|
21
|
+
private readonly aliases;
|
|
22
|
+
private readonly files;
|
|
23
|
+
constructor(aliases?: Alias[]);
|
|
24
|
+
read(file: string): ISourceFile;
|
|
25
|
+
import(file: string, name: string): {
|
|
26
|
+
source: string;
|
|
27
|
+
exported: string;
|
|
28
|
+
declaration: ImportDeclaration;
|
|
29
|
+
} | undefined;
|
|
30
|
+
filename(specifier: string, importer: string, node?: Node): string;
|
|
31
|
+
exported(file: string, name?: string, seen?: Set<string>): ISourceValue;
|
|
32
|
+
resolve(value: ISourceValue, seen?: Set<string>): ISourceValue;
|
|
33
|
+
properties(value: ISourceValue, ancestors?: Set<Node>): Map<string, ISourceValue>;
|
|
34
|
+
}
|
|
35
|
+
export default SourceFiles;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import e from"node:fs";import t from"node:path";import{parse as r}from"@babel/parser";import{VISITOR_KEYS as i}from"@babel/types";const o=e=>{switch(e?.type){case"TSSatisfiesExpression":case"TSAsExpression":case"TSTypeAssertion":case"TSNonNullExpression":case"ParenthesizedExpression":return o(e.expression);default:return e??void 0}},s=(e,t)=>{t(e);for(const r of i[e.type]??[]){const i=Reflect.get(e,r);for(const e of Array.isArray(i)?i:[i])e&&"object"==typeof e&&"type"in e&&s(e,t)}},n=(e,t,r)=>new Error(`${e}:${t?.loc?.start.line??1}:${(t?.loc?.start.column??0)+1}: Unsupported ${r} (${t?.type??"undefined"}).`),a=e=>{if("SpreadElement"!==e.type)return"StringLiteral"===e.key.type?e.key.value:e.computed||"Identifier"!==e.key.type?void 0:e.key.name};class p{aliases;files=new Map;constructor(e=[]){this.aliases=e}read(t){const i=this.files.get(t);if(i)return i;let o;try{o=e.readFileSync(t,"utf8")}catch{throw n(t,void 0,"missing source file")}try{const e={code:o,ast:r(o,{sourceType:"module",createImportExpressions:!0,plugins:["typescript","jsx"]})};return this.files.set(t,e),e}catch(e){throw new Error(`${t}: ${String(e.message)}`)}}import(e,t){for(const r of this.read(e).ast.program.body){if("ImportDeclaration"!==r.type||"type"===r.importKind)continue;const e=r.specifiers.find(e=>e.local.name===t);if("ImportDefaultSpecifier"===e?.type)return{source:r.source.value,exported:"default",declaration:r};if("ImportSpecifier"===e?.type&&"type"!==e.importKind)return{source:r.source.value,exported:"Identifier"===e.imported.type?e.imported.name:e.imported.value,declaration:r}}}filename(r,i,o){let s=r;for(const{find:e,replacement:t}of this.aliases)if("string"==typeof e?s===e||s.startsWith(`${e}/`):e.test(s)){s=s.replace(e,t);break}if(!t.isAbsolute(s)){if(!s.startsWith("."))throw n(i,o,`unresolvable import ${JSON.stringify(r)}`);s=t.resolve(t.dirname(i),s)}for(const t of["",".js",".ts",".tsx",".jsx",".mjs",".mts",".cjs",".cts","/index.js","/index.ts","/index.tsx","/index.jsx"]){const r=`${s}${t}`;if(e.existsSync(r)&&e.statSync(r).isFile())return r}throw n(i,o,`missing import ${JSON.stringify(r)}`)}exported(e,t="default",r=new Set){const i=`${e}#export:${t}`;if(r.has(i))throw n(e,void 0,`circular export ${t}`);r.add(i);for(const i of this.read(e).ast.program.body){if("ExportDefaultDeclaration"===i.type&&"default"===t)return this.resolve({node:i.declaration,file:e},r);if("ExportNamedDeclaration"===i.type){if("VariableDeclaration"===i.declaration?.type){const o=i.declaration.declarations.find(e=>"Identifier"===e.id.type&&e.id.name===t);if(o?.init)return this.resolve({node:o.init,file:e},r)}for(const o of i.specifiers){if(("Identifier"===o.exported.type?o.exported.name:o.exported.value)===t&&"ExportSpecifier"===o.type)return i.source?this.exported(this.filename(i.source.value,e,i),o.local.name,r):this.resolve({node:o.local,file:e},r)}}}throw n(e,void 0,`missing export ${JSON.stringify(t)}`)}resolve(e,t=new Set){const{file:r}=e,i=o(e.node);if("Identifier"!==i.type)return{node:i,file:r};const s=`${r}#${i.name}`;if(t.has(s))throw n(r,i,`circular binding ${i.name}`);t.add(s);const a=this.import(r,i.name);if(a)return this.exported(this.filename(a.source,r,i),a.exported,t);for(const e of this.read(r).ast.program.body){const o="ExportNamedDeclaration"===e.type?e.declaration:e;if("VariableDeclaration"===o?.type){const e=o.declarations.find(e=>"Identifier"===e.id.type&&e.id.name===i.name);if(e?.init)return this.resolve({node:e.init,file:r},t)}if("FunctionDeclaration"===o?.type&&o.id?.name===i.name)return{node:o,file:r}}throw n(r,i,`unresolved binding ${i.name}`)}properties(e,t=new Set){const{node:r,file:i}=this.resolve(e);if("ObjectExpression"!==r.type||t.has(r))throw n(i,r,"route object / object spread; use a static object");const o=new Set([...t,r]),s=new Map;for(const e of r.properties){if("SpreadElement"===e.type){for(const[t,r]of this.properties({node:e.argument,file:i},o))s.set(t,r);continue}const t=a(e);if(void 0===t)throw n(i,e,"computed route key; use a string literal");s.set(t,{node:"ObjectProperty"===e.type?e.value:e,file:i})}return s}}export{p as default,a as propertyName,n as sourceError,o as unwrap,s as walk};
|
|
2
|
+
//# sourceMappingURL=source-files.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source-files.js","sources":["../../src/services/source-files.ts"],"sourcesContent":[null],"names":["unwrap","node","type","expression","undefined","walk","visit","key","VISITOR_KEYS","value","Reflect","get","child","Array","isArray","sourceError","file","construct","Error","loc","start","line","column","propertyName","computed","name","SourceFiles","aliases","files","Map","constructor","this","read","cached","code","fs","readFileSync","result","ast","parse","sourceType","createImportExpressions","plugins","set","error","String","message","import","program","body","importKind","specifier","specifiers","find","item","local","source","exported","declaration","imported","filename","importer","replacement","startsWith","test","replace","path","isAbsolute","JSON","stringify","resolve","dirname","suffix","candidate","existsSync","statSync","isFile","seen","Set","has","add","declarations","id","init","statement","binding","properties","ancestors","next","property","entry","argument"],"mappings":"kIAkBO,MAAMA,EAAUC,IACrB,OAAQA,GAAMC,MACZ,IAAK,wBACL,IAAK,iBACL,IAAK,kBACL,IAAK,sBACL,IAAK,0BACH,OAAOF,EAAOC,EAAKE,YACrB,QACE,OAAOF,QAAQG,IAKRC,EAAO,CAACJ,EAAYK,KAC/BA,EAAML,GAEN,IAAK,MAAMM,KAAOC,EAAaP,EAAKC,OAAS,GAAI,CAC/C,MAAMO,EAAiBC,QAAQC,IAAIV,EAAMM,GAEzC,IAAK,MAAMK,KAASC,MAAMC,QAAQL,GAASA,EAAQ,CAACA,GAC9CG,GAA0B,iBAAVA,GAAsB,SAAUA,GAClDP,EAAKO,EAAeN,EAG1B,GAIWS,EAAc,CAACC,EAAcf,EAAwBgB,IAChE,IAAIC,MACF,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,KAA4BuF,EAAShF,MAAQgF,EAC5DzE,QAEJ,CAEA,OAAOsE,CACT"}
|
package/services/ssr-manifest.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:fs";import s from"node:path";import t from"chalk";import i from"./parse-routes.js";import r from"./path-normalize.js";import o,{AssetType as a}from"./route-assets.js";class n extends o{static instance=null;config;pathNormalize;root;buildDir;manifestName="manifest.json";viteAliases;basename;renderBuiltUrl;constructor(e,{buildDir:t,viteAliases:i,basename:o,renderBuiltUrl:a}={}){super(s.resolve(e.getParams().root,t||""),e.isModulePreload),this.config=e,this.root=e.getParams().root,this.buildDir=t,this.viteAliases=i??e.getVite()?.config?.resolve.alias,this.pathNormalize=new r(e,i),this.basename=o,this.renderBuiltUrl=a}static get(e,s={}){return null===n.instance&&(n.instance=new n(e,s)),n.instance}get isDev(){return Boolean(this.config.getVite())}getOutDir(){return s.resolve(this.root,this.buildDir||"")}getAssetsManifestFile(){return`${this.getOutDir()}/server/assets-manifest.json`}loadClientManifest(){const t=s.resolve(this.root,`${this.buildDir||""}/client/.vite`),i=`${t}/${this.manifestName}`;if(!e.existsSync(i))return{};const r=JSON.parse(e.readFileSync(i,{encoding:"utf-8"}));return e.rmSync(i),0===e.readdirSync(t).length&&e.rmSync(t,{recursive:!0}),r}getRoutesTreeIds(e,s){const t={};return e.forEach(
|
|
1
|
+
import e from"node:fs";import s from"node:path";import t from"chalk";import i from"./parse-routes.js";import r from"./path-normalize.js";import o,{AssetType as a}from"./route-assets.js";class n extends o{static instance=null;config;pathNormalize;root;buildDir;manifestName="manifest.json";viteAliases;basename;renderBuiltUrl;constructor(e,{buildDir:t,viteAliases:i,basename:o,renderBuiltUrl:a}={}){super(s.resolve(e.getParams().root,t||""),e.isModulePreload),this.config=e,this.root=e.getParams().root,this.buildDir=t,this.viteAliases=i??e.getVite()?.config?.resolve.alias,this.pathNormalize=new r(e,i),this.basename=o,this.renderBuiltUrl=a}static get(e,s={}){return null===n.instance&&(n.instance=new n(e,s)),n.instance}get isDev(){return Boolean(this.config.getVite())}getOutDir(){return s.resolve(this.root,this.buildDir||"")}getAssetsManifestFile(){return`${this.getOutDir()}/server/assets-manifest.json`}loadClientManifest(){const t=s.resolve(this.root,`${this.buildDir||""}/client/.vite`),i=`${t}/${this.manifestName}`;if(!e.existsSync(i))return{};const r=JSON.parse(e.readFileSync(i,{encoding:"utf-8"}));return e.rmSync(i),0===e.readdirSync(t).length&&e.rmSync(t,{recursive:!0}),r}getRoutesTreeIds(e,s){const t={};return e.forEach(e=>{const i=[s,String(e.index)].filter(Boolean).join("-"),r=e.id??i;e.import&&(t[r]=this.pathNormalize.getAppPath(e.import)),e.children.length>0&&Object.assign(t,this.getRoutesTreeIds(e.children,i))}),t}getRouteAssets(e,t,i=!1){const r=[...t?.assets??[],...t?.css??[],t?.file].reduce((e,r)=>{if(r){const o=this.getAssetType(r),a=t.isEntry&&t.file===r;if(o){const t=s.posix.normalize(`${this.basename}/${r}`),n=this.renderBuiltUrl?.(t,{type:"asset",ssr:!0,hostId:"",hostType:t.split(".").at(-1)?.toLowerCase()});e[r]={url:"string"==typeof n?n:t,weight:a?1.9:this.getAssetWeight(r),type:o,isNested:i,isPreload:!a}}}return e},{});return t?.imports?.length&&t.imports.forEach(s=>{const t=e[s];t&&Object.assign(r,this.getRouteAssets(e,t,!0))}),r}buildRoutesManifest(){const s=this.loadClientManifest(),t=new i(this.config,this.viteAliases),r=this.getRoutesTreeIds(t.parse()),o=this.pathNormalize.getImportPostfix(),a={};Object.entries(r).forEach(([e,t])=>{const i=o.find(e=>void 0!==s[`${t}${e}`]),r=s[`${t}${i||""}`];a[e]=this.sortAssets(Object.values(this.getRouteAssets(s,r)))}),e.writeFileSync(this.getAssetsManifestFile(),JSON.stringify(a,null,2),{encoding:"utf-8"})}getAssets(e){return this.isDev?this.getAssetsDev(e):super.getAssets(e)}getDevModules(e){const t=e?.map(({route:e})=>this.pathNormalize.getAppPath(e?.pathId,!0)).filter(Boolean)??[],i=this.pathNormalize.getImportPostfix(),r=this.config.getPluginConfig(),o=[r?.clientFile??"client.ts",r?.serverFile??"server.ts"].map(e=>s.resolve(this.root,e)),a=[];return[...o,...t].forEach(e=>{for(const s of i){const t=this.config.getVite()?.moduleGraph.getModuleById(`${e}${s}`);if(t){a.push(t);break}}}),a}async prepareDevAssets(e){const s=this.config.getVite();if(!s)return;const t=new Set,i=async e=>{t.has(e.url)||(t.add(e.url),e.file&&/\.(?:css|less|s[ac]ss|styl(?:us)?|pcss|postcss)$/.test(e.file)&&await s.transformRequest(e.url),await Promise.all([...e.importedModules].map(i)))};await Promise.all(this.getDevModules(e).map(i))}getAssetsDev(e){const s=Object.assign({},...this.getDevModules(e).map(e=>this.getModuleAssets(e)));return Object.values(s)}getModuleAssets(e,s=new Set){const i=e?.importedModules??e?.clientImportedModules;if(!i?.size||s.has(e.file))return{};let r={};return s.add(e.file),i.forEach(e=>{const{file:i,transformResult:o}=e,n=i?.split(".").at(-1);if(i&&n&&["css","scss","sass","less","styl","stylus","pcss","postcss"].includes(n)){const e=o?.code.match(/__vite__css\s+=\s+"(?<css>.+)"/)?.groups?.css;if(e)try{r[i]={type:a.style,url:i,weight:this.getAssetWeight(i),content:JSON.parse(`{"style": "${e}"}`).style,isNested:Boolean(s.size),isPreload:!1}}catch{console.warn(t.yellowBright("Failed to parse style: ",i))}}else r={...r,...this.getModuleAssets(e,s)}}),r}getAssetWeight(e){switch(this.getAssetType(e)){case a.style:return 1;case a.script:return 2;default:return 3}}getAssetType(e){const s=e.split(".").at(-1)?.toLowerCase();switch(s){case"css":case"scss":return a.style;case"js":return a.script;case"svg":case"jpg":case"jpeg":case"png":case"webp":case"gif":case"ico":return a.image;case"ttf":case"otf":case"woff":case"woff2":return a.font;default:return null}}}export{n as default};
|
|
2
2
|
//# sourceMappingURL=ssr-manifest.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":[null],"names":["SsrManifest","RouteAssets","static","config","pathNormalize","root","buildDir","manifestName","viteAliases","basename","renderBuiltUrl","constructor","super","path","resolve","getParams","isModulePreload","this","getVite","alias","PathNormalize","get","params","instance","isDev","Boolean","getOutDir","getAssetsManifestFile","loadClientManifest","clientManifestDir","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","readdirSync","length","recursive","getRoutesTreeIds","routes","index","forEach","route","
|
|
1
|
+
{"version":3,"file":"ssr-manifest.js","sources":["../../src/services/ssr-manifest.ts"],"sourcesContent":[null],"names":["SsrManifest","RouteAssets","static","config","pathNormalize","root","buildDir","manifestName","viteAliases","basename","renderBuiltUrl","constructor","super","path","resolve","getParams","isModulePreload","this","getVite","alias","PathNormalize","get","params","instance","isDev","Boolean","getOutDir","getAssetsManifestFile","loadClientManifest","clientManifestDir","clientSsrManifest","fs","existsSync","result","JSON","parse","readFileSync","encoding","rmSync","readdirSync","length","recursive","getRoutesTreeIds","routes","index","forEach","route","position","String","filter","join","routeId","id","import","getAppPath","children","Object","assign","getRouteAssets","manifest","module","isNested","assets","css","file","reduce","res","asset","type","getAssetType","isEntry","filename","posix","normalize","modifiedFilename","ssr","hostId","hostType","split","at","toLowerCase","url","weight","getAssetWeight","isPreload","imports","nestedAsset","nestedModule","buildRoutesManifest","routesService","ParseRoutes","routesPaths","postfixes","getImportPostfix","entries","routePath","routePostfix","find","postfix","undefined","routeMeta","sortAssets","values","writeFileSync","stringify","getAssets","getAssetsDev","getDevModules","routeIds","map","pathId","pluginConfig","getPluginConfig","rootIds","clientFile","serverFile","modules","moduleId","ext","moduleGraph","getModuleById","push","prepareDevAssets","vite","visited","Set","visit","async","has","add","test","transformRequest","Promise","all","importedModules","getModuleAssets","skipModules","clientImportedModules","size","subModule","transformResult","includes","code","match","groups","AssetType","style","content","console","warn","chalk","yellowBright","script","image","font"],"mappings":"0LAiCA,MAAMA,UAAoBC,EAIdC,gBAAsC,KAK7BC,OAKAC,cAKAC,KAKA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