@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.
Files changed (73) hide show
  1. package/README.md +25 -13
  2. package/SECURITY.md +1 -1
  3. package/adapters/express/entry.d.ts +1 -1
  4. package/adapters/express/entry.js.map +1 -1
  5. package/adapters/express/render.d.ts +4 -1
  6. package/adapters/express/render.js +1 -1
  7. package/adapters/express/render.js.map +1 -1
  8. package/browser/entry.d.ts +1 -0
  9. package/browser/entry.js +1 -1
  10. package/browser/entry.js.map +1 -1
  11. package/browser/stream.d.ts +5 -0
  12. package/browser/stream.js +2 -0
  13. package/browser/stream.js.map +1 -0
  14. package/cli/diagnostic-codes.d.ts +3 -0
  15. package/cli/diagnostic-codes.js +2 -0
  16. package/cli/diagnostic-codes.js.map +1 -0
  17. package/cli/doctor.d.ts +55 -0
  18. package/cli/doctor.js +2 -0
  19. package/cli/doctor.js.map +1 -0
  20. package/cli/init.d.ts +17 -0
  21. package/cli/init.js +2 -0
  22. package/cli/init.js.map +1 -0
  23. package/cli/project.d.ts +56 -0
  24. package/cli/project.js +2 -0
  25. package/cli/project.js.map +1 -0
  26. package/cli.js +1 -1
  27. package/cli.js.map +1 -1
  28. package/core/compose-html.d.ts +3 -4
  29. package/core/compose-html.js +1 -1
  30. package/core/compose-html.js.map +1 -1
  31. package/core/data-stream.d.ts +50 -0
  32. package/core/data-stream.js +2 -0
  33. package/core/data-stream.js.map +1 -0
  34. package/core/html-boundary.d.ts +7 -0
  35. package/core/html-boundary.js +2 -0
  36. package/core/html-boundary.js.map +1 -0
  37. package/core/render.d.ts +7 -1
  38. package/core/render.js +1 -1
  39. package/core/render.js.map +1 -1
  40. package/core/script.d.ts +6 -0
  41. package/core/script.js +2 -0
  42. package/core/script.js.map +1 -0
  43. package/edge/render-to-stream.js +1 -1
  44. package/edge/render-to-stream.js.map +1 -1
  45. package/helpers/build-custom-state.d.ts +1 -1
  46. package/helpers/build-custom-state.js +1 -1
  47. package/helpers/build-custom-state.js.map +1 -1
  48. package/helpers/build-router-state.d.ts +1 -1
  49. package/helpers/build-router-state.js +1 -1
  50. package/helpers/build-router-state.js.map +1 -1
  51. package/helpers/is-route-file.js +1 -1
  52. package/helpers/is-route-file.js.map +1 -1
  53. package/node/render-to-stream.js +1 -1
  54. package/node/render-to-stream.js.map +1 -1
  55. package/package.json +18 -6
  56. package/plugins/normalize-route.js +1 -1
  57. package/plugins/normalize-route.js.map +1 -1
  58. package/services/build.d.ts +1 -0
  59. package/services/build.js +1 -1
  60. package/services/build.js.map +1 -1
  61. package/services/diagnostics.d.ts +8 -3
  62. package/services/diagnostics.js +1 -1
  63. package/services/diagnostics.js.map +1 -1
  64. package/services/parse-routes.d.ts +17 -55
  65. package/services/parse-routes.js +1 -1
  66. package/services/parse-routes.js.map +1 -1
  67. package/services/path-normalize.js +1 -1
  68. package/services/path-normalize.js.map +1 -1
  69. package/services/source-files.d.ts +35 -0
  70. package/services/source-files.js +2 -0
  71. package/services/source-files.js.map +1 -0
  72. package/services/ssr-manifest.js +1 -1
  73. package/services/ssr-manifest.js.map +1 -1
package/README.md CHANGED
@@ -20,22 +20,14 @@
20
20
 
21
21
  ## Quick start
22
22
 
23
- **Start a new app** with the `minimal` template (default):
24
-
25
- ```bash
26
- npm create @lomray/ssr-app@latest my-app
27
- ```
28
-
29
- Choose the `full` template by passing the flag after `--`:
30
-
31
- ```bash
32
- npm create @lomray/ssr-app@latest my-app -- --template full
33
- ```
34
-
35
23
  **Add to an existing app:**
36
24
 
37
25
  ```bash
38
26
  npm i @lomray/vite-ssr-boost
27
+ npx ssr-boost init --dry-run
28
+ npx ssr-boost init --apply
29
+ npm install
30
+ npx ssr-boost doctor
39
31
  ```
40
32
 
41
33
  `@lomray/vite-ssr-boost` adds server rendering to your Vite project while keeping your route objects and components. Build SSR and SPA output from the same app, and choose a managed Express server or a Fetch handler for your own transport.
@@ -50,8 +42,22 @@ The [migration guide](./docs/guide/migrate-existing-spa.md) walks through the fi
50
42
  | `src/server.ts` | Add the server entry and request-scoped setup. |
51
43
  | `package.json` | Use the `ssr-boost` dev, build and start commands. |
52
44
 
45
+ **Start a new app** with the `minimal` template (default):
46
+
47
+ ```bash
48
+ npm create @lomray/ssr-app@latest my-app
49
+ ```
50
+
51
+ Choose the `full` template by passing the flag after `--`:
52
+
53
+ ```bash
54
+ npm create @lomray/ssr-app@latest my-app -- --template full
55
+ ```
56
+
53
57
  Starting a new app? Choose one of the [template branches](./docs/examples/index.md) with the [`npm create` command](./docs/guide/getting-started.md#create-a-new-app) or clone the branch directly.
54
58
 
59
+ To defer loader work, return `{ title, slow: fetchUsers() }` and render `slow` with Suspense and `<Await>`; see the [streaming guide](./docs/guide/data-streaming.md).
60
+
55
61
  ## Who this is for
56
62
 
57
63
  - Teams adding SSR to a Vite SPA with React Router route objects.
@@ -66,10 +72,14 @@ Starting a new app? Choose one of the [template branches](./docs/examples/index.
66
72
  - Your React version within the package's peer range: React and React DOM `>=18.2.0`.
67
73
  - Your hosting choice, provided it can run the selected SSR transport or serve SPA files.
68
74
 
75
+ Loader and action promises support `<Await>` and React 19 `use()` during hydration by default. [Stream loader data](./docs/guide/data-streaming.md) shows the loader pattern and `hydration: 'early'` for shell interaction before slow boundaries finish.
76
+
69
77
  ## What you add
70
78
 
71
79
  Add `SsrBoost()` to the Vite plugins, wire `client.ts` and `server.ts`, and replace the Vite scripts with `ssr-boost` commands. The [migration guide](./docs/guide/migrate-existing-spa.md) includes these entries and the HTML outlet, copied from the minimal example.
72
80
 
81
+ Deferred router data needs no additional state library. Keep footer hydration by default, or opt into early hydration with custom state available at `onShellReady`.
82
+
73
83
  ## Choose your server
74
84
 
75
85
  **Managed CLI (default).** Use `ssr-boost dev` for Express with Vite development and HMR, then `ssr-boost build` and `ssr-boost start` for production assets and SSR. The server entry is `@lomray/vite-ssr-boost/adapters/express/entry`, with hooks for requests, rendering and responses.
@@ -84,7 +94,7 @@ Add `SsrBoost()` to the Vite plugins, wire `client.ts` and `server.ts`, and repl
84
94
 
85
95
  ## Install and template quick start
86
96
 
87
- The package declares `engines.node: ">=22.12.0"`. The example uses Node 22.23.2; React Router and build tools can raise the required Node version.
97
+ See [Compatibility](#compatibility) for the package Node requirement. The example uses Node 22.23.2; React Router and build tools can raise the required Node version.
88
98
 
89
99
  Start with the [minimal template](https://github.com/Lomray-Software/vite-template/tree/example/minimal):
90
100
 
@@ -111,6 +121,8 @@ Already running this in production? Point our [free performance audit](https://a
111
121
 
112
122
  ## Compatibility
113
123
 
124
+ See the [support policy](./SUPPORT.md) for version lifetimes, response targets and breaking-change commitments, and [Upgrade from 7 to 8](./docs/guide/upgrade-v8.md) for migration instructions.
125
+
114
126
  The package is tested against the current and previous major of React, React Router and Vite, with an additional Vite 6 row. The [compatibility workflow](./.github/workflows/react-compatibility.yml) runs the full test suite and a built Worker check on Node 22.23.2 with these exact combinations:
115
127
 
116
128
  | React / React DOM | React Router | Vite |
package/SECURITY.md CHANGED
@@ -13,7 +13,7 @@ When reporting security issues, please provide the following information:
13
13
  - Steps to reproduce the vulnerability
14
14
  - Your contact information
15
15
 
16
- We take all security reports seriously and will do our best to rapidly address the issue. We are grateful for your contributions to our security efforts, and we will acknowledge your report upon resolution.
16
+ We will provide a human acknowledgment within **two business days** of receiving your security report. Business days are Monday through Friday, excluding public holidays observed by the responding maintainer. We will keep you informed while we investigate and coordinate a fix; acknowledgment does not mean resolution. See [Support policy](./SUPPORT.md) for the security maintenance windows.
17
17
 
18
18
  ## Responsible Disclosure
19
19
  We adhere to the principle of responsible disclosure. This means that if you discover a vulnerability, you agree to:
@@ -15,7 +15,7 @@ export interface IInitServerRequestOut<T = Record<string, any>> {
15
15
  shouldSkip?: boolean;
16
16
  shouldCancel?: boolean;
17
17
  }
18
- export interface IEntrypointOptions<TAppProps = Record<string, any>> extends Pick<IRenderOptions<TAppProps>, 'onRouterReady' | 'onShellReady' | 'onShellError' | 'onResponse' | 'onError' | 'getState' | 'getBody'> {
18
+ export interface IEntrypointOptions<TAppProps = Record<string, any>> extends Pick<IRenderOptions<TAppProps>, 'onRouterReady' | 'onShellReady' | 'onShellError' | 'onResponse' | 'onError' | 'getState' | 'getBody' | 'hydration' | 'nonce' | 'bootstrapScriptContent'> {
19
19
  onServerCreated?: (app: Express, serverApi: ServerApi) => Promise<void> | void;
20
20
  onServerStarted?: (app: Express, serverApi: ServerApi, server: Server) => Promise<void> | void;
21
21
  onRequest?: (req: Request, res: ExpressResponse) => Promise<IInitServerRequestOut<TAppProps>> | IInitServerRequestOut<TAppProps>;
@@ -1 +1 @@
1
- {"version":3,"file":"entry.js","sources":["../../../src/adapters/express/entry.tsx"],"sourcesContent":[null],"names":["entry","App","routes","init","routerOptions","rest","handler","createStaticHandler","render","bind"],"mappings":"8EA4EA,SAASA,EACPC,EACAC,GACAC,KAAEA,EAAIC,cAAEA,KAAkBC,GAAyC,IAEnE,MAAMC,EAAUC,EAAoBL,EAAyBE,GAE7D,MAAO,CACLI,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASL,QACrCE,OACAD,YACGG,EAEP"}
1
+ {"version":3,"file":"entry.js","sources":["../../../src/adapters/express/entry.tsx"],"sourcesContent":[null],"names":["entry","App","routes","init","routerOptions","rest","handler","createStaticHandler","render","bind"],"mappings":"8EA+EA,SAASA,EACPC,EACAC,GACAC,KAAEA,EAAIC,cAAEA,KAAkBC,GAAyC,IAEnE,MAAMC,EAAUC,EAAoBL,EAAyBE,GAE7D,MAAO,CACLI,OAAQA,EAAOC,KAAK,KAAM,CAAEH,UAASL,QACrCE,OACAD,YACGG,EAEP"}
@@ -26,6 +26,9 @@ export interface IRenderParams<TAppProps = Record<string, any>> {
26
26
  handler: StaticHandler;
27
27
  }
28
28
  export interface IRenderOptions<TAppProps = Record<string, any>> {
29
+ hydration?: 'early' | 'footer';
30
+ nonce?: string;
31
+ bootstrapScriptContent?: string;
29
32
  abortDelay?: number;
30
33
  getBody?: (request: ExpressRequest) => BodyInit | null | undefined;
31
34
  onRouterReady?: (params: {
@@ -61,5 +64,5 @@ export interface IShellReadyOut {
61
64
  /**
62
65
  * Render application
63
66
  */
64
- declare function render({ App, handler }: IRenderParams, config: ServerConfig, initialContext: Omit<IRequestContext, 'request'>, { onRouterReady, onShellReady, onResponse, onShellError, onError, getBody, getState, abortDelay, }: IRenderOptions): Promise<void>;
67
+ declare function render({ App, handler }: IRenderParams, config: ServerConfig, initialContext: Omit<IRequestContext, 'request'>, { onRouterReady, onShellReady, onResponse, onShellError, onError, getBody, getState, hydration, nonce, bootstrapScriptContent, abortDelay, }: IRenderOptions): Promise<void>;
65
68
  export default render;
@@ -1,2 +1,2 @@
1
- import e from"chalk";import r from"react";import t from"./create-request.js";import o from"../../constants/stream-error.js";import s from"../../core/early-hints.js";import{getHeaderEntries as n,getSetCookieHeaders as a}from"../../core/headers.js";import i from"../../core/render.js";import d from"../../node/render-to-stream.js";import c from"../../node/request-signal.js";import m from"../../node/write-early-hints.js";import p,{writeFetchHeaders as l}from"../../node/write-fetch-response.js";import u,{isDiagnosticsEnabled as h}from"../../services/diagnostics.js";import f from"../../services/ssr-manifest.js";const x=(e,r,o)=>{const s={signal:r};return o&&"GET"!==e.method&&"HEAD"!==e.method&&(s.body=o(e)??null),t(e,s)};async function y({App:t,handler:y},g,E,{onRouterReady:w,onShellReady:S,onResponse:j,onShellError:v,onError:C,getBody:R,getState:q,abortDelay:b=15e3}){const{appProps:A,html:H,req:k,res:D}=E,L=g.getLogger(),P=c(k,D);try{const c=Object.assign(E,{request:x(k,P.signal,R)}),T={appProps:A,diagnostics:h(!g.isProd)?new u(new URL(c.request.url).pathname,L):void 0,html:H,request:c.request,response:{headers:new Headers}},O=e=>(c.request=e.request,c.didError=e.didError,c.html=e.html,c.isStream=e.isStream,c.routerContext=e.routerContext,c.serverContext=e.serverContext,c),B=await i({createApp:(e,o)=>r.createElement(t,{server:{...o.appProps,req:k}},e),handler:y,renderToStream:d},T,{abortDelay:b,getState:q?({context:e})=>q({context:O(e)}):void 0,onError:({context:r,error:t})=>{const{code:s,message:n}=t;if(C?.({context:O(r),error:t}),L.info(e.red(`Stream error. Code: ${s}`)),[o.RenderAborted,o.RenderTimeout,o.RenderCancel].includes(s))return void L.info(e.dim(n));const{original:a}=t;L.error(a)},onResponse:j?({context:e,html:r,isEnd:t})=>j({context:O(e),html:r,isEnd:t}):void 0,onRouterReady:w?({context:e})=>w({context:O(e)}):void 0,onShellError:v?({context:e,error:r})=>v({context:O(e),error:r}):void 0,onShellReady:({context:e})=>{const r=O(e);((e,r)=>{if(r.headersSent||r.writableEnded)return;r.status(e.response.status??200),n(e.response.headers).forEach(([e,t])=>r.setHeader(e,t));const t=a(e.response.headers);t.length&&r.setHeader("Set-Cookie",t)})(e,D);const t=S?.({context:r});return((e,r)=>{const t=new Headers(e.response.headers);t.delete("Set-Cookie");for(const[e,o]of Object.entries(r.getHeaders()))if("set-cookie"!==e.toLowerCase()&&void 0!==o)if(Array.isArray(o))for(const r of o)t.append(e,r);else t.set(e,"number"==typeof o?String(o):o);e.response.headers=t,e.response.status=r.statusCode})(e,D),t??{}},prepare:async({context:e,executionContext:r})=>{const t=O(e),o=f.get(g);await o.prepareDevAssets(e.routerContext?.matches);const n=o.injectAssets(t);t.hasEarlyHints&&await s(r,n)},routerRequestContext:c},{onEarlyHints:e=>m(D,e)});O(T),await(async(e,r)=>{const t=r.headers.get("Location");if(t&&r.status>=300&&r.status<400&&!e.headersSent&&!e.writableEnded&&!e.destroyed)return l(e,r),await(r.body?.cancel()),void e.redirect(r.status,t);await p(e,r)})(D,B)}finally{P.dispose()}}export{y as default};
1
+ import e from"chalk";import t from"react";import r from"./create-request.js";import o from"../../constants/stream-error.js";import s from"../../core/early-hints.js";import{getHeaderEntries as n,getSetCookieHeaders as a}from"../../core/headers.js";import i from"../../core/render.js";import d from"../../node/render-to-stream.js";import c from"../../node/request-signal.js";import p from"../../node/write-early-hints.js";import m,{writeFetchHeaders as l}from"../../node/write-fetch-response.js";import u,{isDiagnosticsEnabled as h}from"../../services/diagnostics.js";import f from"../../services/ssr-manifest.js";const y=(e,t,o)=>{const s={signal:t};return o&&"GET"!==e.method&&"HEAD"!==e.method&&(s.body=o(e)??null),r(e,s)};async function x({App:r,handler:x},g,S,{onRouterReady:E,onShellReady:w,onResponse:C,onShellError:j,onError:v,getBody:R,getState:b,hydration:q,nonce:A,bootstrapScriptContent:H,abortDelay:k=15e3}){const{appProps:D,html:L,req:P,res:T}=S,O=g.getLogger(),B=c(P,T);try{const c=Object.assign(S,{request:y(P,B.signal,R)}),G={appProps:D,diagnostics:h(!g.isProd)?new u(new URL(c.request.url).pathname,O):void 0,html:L,request:c.request,response:{headers:new Headers}},U=e=>(c.request=e.request,c.didError=e.didError,c.html=e.html,c.isStream=e.isStream,c.routerContext=e.routerContext,c.serverContext=e.serverContext,c),$=await i({createApp:(e,o)=>t.createElement(r,{server:{...o.appProps,req:P}},e),handler:x,renderToStream:d},G,{abortDelay:k,hydration:q,nonce:A,bootstrapScriptContent:H,getState:b?({context:e})=>b({context:U(e)}):void 0,onError:({context:t,error:r})=>{const{code:s,message:n}=r;if(v?.({context:U(t),error:r}),O.info(e.red(`Stream error. Code: ${s}`)),[o.RenderAborted,o.RenderTimeout,o.RenderCancel].includes(s))return void O.info(e.dim(n));const{original:a}=r;O.error(a)},onResponse:C?({context:e,html:t,isEnd:r})=>C({context:U(e),html:t,isEnd:r}):void 0,onRouterReady:E?({context:e})=>E({context:U(e)}):void 0,onShellError:j?({context:e,error:t})=>j({context:U(e),error:t}):void 0,onShellReady:({context:e})=>{const t=U(e);((e,t)=>{if(t.headersSent||t.writableEnded)return;t.status(e.response.status??200),n(e.response.headers).forEach(([e,r])=>t.setHeader(e,r));const r=a(e.response.headers);r.length&&t.setHeader("Set-Cookie",r)})(e,T);const r=w?.({context:t});return((e,t)=>{const r=new Headers(e.response.headers);r.delete("Set-Cookie");for(const[e,o]of Object.entries(t.getHeaders()))if("set-cookie"!==e.toLowerCase()&&void 0!==o)if(Array.isArray(o))for(const t of o)r.append(e,t);else r.set(e,"number"==typeof o?String(o):o);e.response.headers=r,e.response.status=t.statusCode})(e,T),r??{}},prepare:async({context:e,executionContext:t})=>{const r=U(e),o=f.get(g);await o.prepareDevAssets(e.routerContext?.matches);const n=o.injectAssets(r);r.hasEarlyHints&&await s(t,n)},routerRequestContext:c},{onEarlyHints:e=>p(T,e)});U(G),await(async(e,t)=>{const r=t.headers.get("Location");if(r&&t.status>=300&&t.status<400&&!e.headersSent&&!e.writableEnded&&!e.destroyed)return l(e,t),await(t.body?.cancel()),void e.redirect(t.status,r);await m(e,t)})(T,$)}finally{B.dispose()}}export{x as default};
2
2
  //# sourceMappingURL=render.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","sources":["../../../src/adapters/express/render.tsx"],"sourcesContent":[null],"names":["createRenderRequest","req","signal","getBody","options","method","body","createFetchRequest","async","render","App","handler","config","initialContext","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","abortDelay","appProps","html","shellHtml","res","Logger","getLogger","requestSignal","createRequestSignal","context","Object","assign","request","coreContext","diagnostics","isDiagnosticsEnabled","isProd","Diagnostics","URL","url","pathname","undefined","response","headers","Headers","syncContext","updated","didError","isStream","routerContext","serverContext","coreRender","createApp","children","React","createElement","server","renderToStream","error","code","message","info","chalk","red","StreamError","RenderAborted","RenderTimeout","RenderCancel","includes","dim","original","isEnd","legacyContext","headersSent","writableEnded","status","getHeaderEntries","forEach","name","value","setHeader","cookies","getSetCookieHeaders","length","prepareResponse","shell","delete","entries","getHeaders","toLowerCase","Array","isArray","item","append","set","String","statusCode","syncResponse","prepare","executionContext","manifest","SsrManifest","get","prepareDevAssets","matches","hints","injectAssets","hasEarlyHints","emitEarlyHints","routerRequestContext","onEarlyHints","writeEarlyHints","location","destroyed","writeFetchHeaders","cancel","redirect","writeFetchResponse","writeResponse","dispose"],"mappings":"omBA+EA,MAAMA,EAAsB,CAC1BC,EACAC,EACAC,KAEA,MAAMC,EAA2D,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,IAAK,MAAMa,KAAQb,EACjBpC,EAAQkD,OAAOf,EAAMc,QAGvBjD,EAAQmD,IAAIhB,EAAuB,iBAAVC,EAAqBgB,OAAOhB,GAASA,GAIlElD,EAAQa,SAASC,QAAUA,EAC3Bd,EAAQa,SAASiC,OAASnD,EAAIwE,YA6JtBC,CAAanD,EAAStB,GAEf6D,GAAS,CAAA,GAMlBa,QAAS1F,OAASqB,QAASiB,EAASqD,uBAClC,MAAM3B,EAAgB3B,EAAYC,GAC5BsD,EAAWC,EAAYC,IAAI1F,SAE3BwF,EAASG,iBAAiBzD,EAAQG,eAAeuD,SAEvD,MAAMC,EAAQL,EAASM,aAAalC,GAEhCA,EAAcmC,qBACVC,EAAeT,EAAkBM,IAG3CI,qBAAsBhF,GAExB,CAIEiF,aAAenE,GAAYoE,EAAgBvF,EAAKmB,KAIpDE,EAAYZ,QArLMzB,OAAOgB,EAAsBkB,KACjD,MAAMsE,EAAWtE,EAASC,QAAQ2D,IAAI,YAEtC,GACEU,GACAtE,EAASiC,QAAU,KACnBjC,EAASiC,OAAS,MACjBnD,EAAIiD,cACJjD,EAAIkD,gBACJlD,EAAIyF,UAML,OAJAC,EAAkB1F,EAAKkB,SACjBA,EAASpC,MAAM6G,eACrB3F,EAAI4F,SAAS1E,EAASiC,OAAQqC,SAK1BK,EAAmB7F,EAAKkB,IAqKtB4E,CAAc9F,EAAKkB,EAC3B,SACEf,EAAc4F,SAChB,CACF"}
1
+ {"version":3,"file":"render.js","sources":["../../../src/adapters/express/render.tsx"],"sourcesContent":[null],"names":["createRenderRequest","req","signal","getBody","options","method","body","createFetchRequest","async","render","App","handler","config","initialContext","onRouterReady","onShellReady","onResponse","onShellError","onError","getState","hydration","nonce","bootstrapScriptContent","abortDelay","appProps","html","shellHtml","res","Logger","getLogger","requestSignal","createRequestSignal","context","Object","assign","request","coreContext","diagnostics","isDiagnosticsEnabled","isProd","Diagnostics","URL","url","pathname","undefined","response","headers","Headers","syncContext","updated","didError","isStream","routerContext","serverContext","coreRender","createApp","children","React","createElement","server","renderToStream","error","code","message","info","chalk","red","StreamError","RenderAborted","RenderTimeout","RenderCancel","includes","dim","original","isEnd","legacyContext","headersSent","writableEnded","status","getHeaderEntries","forEach","name","value","setHeader","cookies","getSetCookieHeaders","length","prepareResponse","shell","delete","entries","getHeaders","toLowerCase","Array","isArray","item","append","set","String","statusCode","syncResponse","prepare","executionContext","manifest","SsrManifest","get","prepareDevAssets","matches","hints","injectAssets","hasEarlyHints","emitEarlyHints","routerRequestContext","onEarlyHints","writeEarlyHints","location","destroyed","writeFetchHeaders","cancel","redirect","writeFetchResponse","writeResponse","dispose"],"mappings":"omBAkFA,MAAMA,EAAsB,CAC1BC,EACAC,EACAC,KAEA,MAAMC,EAA2D,CAAEF,UAMnE,OAJIC,GAA0B,QAAfF,EAAII,QAAmC,SAAfJ,EAAII,SACzCD,EAAQE,KAAOH,EAAQF,IAAQ,MAG1BM,EAAmBN,EAAKG,IA0EjCI,eAAeC,GACbC,IAAEA,EAAGC,QAAEA,GACPC,EACAC,GACAC,cACEA,EAAaC,aACbA,EAAYC,WACZA,EAAUC,aACVA,EAAYC,QACZA,EAAOf,QACPA,EAAOgB,SACPA,EAAQC,UACRA,EAASC,MACTA,EAAKC,uBACLA,EAAsBC,WACtBA,EAAa,OAGf,MAAMC,SAAEA,EAAUC,KAAMC,EAASzB,IAAEA,EAAG0B,IAAEA,GAAQd,EAC1Ce,EAAShB,EAAOiB,YAChBC,EAAgBC,EAAoB9B,EAAK0B,GAC/C,IACE,MAAMK,EAA2BC,OAAOC,OAAOrB,EAAgB,CAC7DsB,QAASnC,EAAoBC,EAAK6B,EAAc5B,OAAQC,KAEpDiC,EAAkC,CACtCZ,WACAa,YAAaC,GAAsB1B,EAAO2B,QACtC,IAAIC,EAAY,IAAIC,IAAIT,EAAQG,QAAQO,KAAKC,SAAUf,QACvDgB,EACJnB,KAAMC,EACNS,QAASH,EAAQG,QACjBU,SAAU,CACRC,QAAS,IAAIC,UAOXC,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AIkD,gBACJlD,EAAIyF,UAML,OAJAC,EAAkB1F,EAAKkB,SACjBA,EAASvC,MAAMgH,eACrB3F,EAAI4F,SAAS1E,EAASiC,OAAQqC,SAK1BK,EAAmB7F,EAAKkB,IA2KtB4E,CAAc9F,EAAKkB,EAC3B,SACEf,EAAc4F,SAChB,CACF"}
@@ -22,3 +22,4 @@ export interface IEntryClientOptions<T> {
22
22
  */
23
23
  declare function entry<TAppProps>(App: TApp<TAppProps>, routes: TRouteObject[], { init, routerOptions, createRouter, rootId, }?: IEntryClientOptions<TAppProps>): Promise<ReactDOM.Root | void>;
24
24
  export default entry;
25
+ export { entry };
package/browser/entry.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"react";import t from"react-dom/client";import{matchRoutes as o,createBrowserRouter as n,RouterProvider as r}from"react-router";import{IS_SSR_MODE as a}from"../constants/common.js";async function i(i,c,{init:d,routerOptions:l,createRouter:m=n,rootId:u="root"}={}){const s=(()=>{const e="__staticRouterHydrationData";if(!("loading"!==document.readyState||a&&void 0!==Reflect.get(window,e)))return new Promise(t=>{const o=()=>{a&&Reflect.deleteProperty(window,e),t()};document.addEventListener("DOMContentLoaded",o,{once:!0}),a&&Object.defineProperty(window,e,{configurable:!0,enumerable:!0,get:()=>{},set:n=>{Object.defineProperty(window,e,{configurable:!0,enumerable:!0,writable:!0,value:n}),document.removeEventListener("DOMContentLoaded",o),t()}})})})(),f=o(c,window.location,l?.basename)?.filter(e=>e.route.lazy);(s||f?.length)&&await Promise.all([s,...(f??[]).map(async e=>{const{lazy:t}=e.route;if("function"==typeof t){const o=await t();o&&Object.assign(e.route,{...o,lazy:void 0})}})]);const w=m(c,l),y=document.getElementById(u),p=await(d?.({isSSRMode:a,router:w})),b=()=>e.createElement(i,{client:p},e.createElement(r,{router:w}));return a&&"1"!==y.dataset.forceSpa?t.hydrateRoot(y,e.createElement(b,null)):t.createRoot(y).render(e.createElement(b,null))}export{i as default};
1
+ import e from"react";import t from"react-dom/client";import{matchRoutes as o,createBrowserRouter as r,RouterProvider as n}from"react-router";import a from"./stream.js";import{IS_SSR_MODE as i}from"../constants/common.js";async function c(c,d,{init:s,routerOptions:l,createRouter:m=r,rootId:u="root"}={}){const f=i?a():void 0,w=(()=>{const e="__staticRouterHydrationData";if(!("loading"!==document.readyState||i&&void 0!==Reflect.get(window,e)))return new Promise(t=>{const o=()=>{i&&Reflect.deleteProperty(window,e),t()};document.addEventListener("DOMContentLoaded",o,{once:!0}),i&&Object.defineProperty(window,e,{configurable:!0,enumerable:!0,get:()=>{},set:r=>{Object.defineProperty(window,e,{configurable:!0,enumerable:!0,writable:!0,value:r}),document.removeEventListener("DOMContentLoaded",o),t()}})})})(),y=o(d,window.location,l?.basename)?.filter(e=>e.route.lazy);(w||y?.length)&&await Promise.all([w,...(y??[]).map(async e=>{const{lazy:t}=e.route;if("function"==typeof t){const o=await t();o&&Object.assign(e.route,{...o,lazy:void 0})}})]);const p=Reflect.get(window,"__staticRouterHydrationData");f&&p?.__ssrBoostStream&&Reflect.set(window,"__staticRouterHydrationData",await f.ready);const R=m(d,l),b=document.getElementById(u),g=await(s?.({isSSRMode:i,router:R})),_=()=>e.createElement(c,{client:g},e.createElement(n,{router:R}));return i&&"1"!==b.dataset.forceSpa?t.hydrateRoot(b,e.createElement(_,null)):t.createRoot(b).render(e.createElement(_,null))}export{c as default,c as entry};
2
2
  //# sourceMappingURL=entry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"entry.js","sources":["../../src/browser/entry.tsx"],"sourcesContent":[null],"names":["async","entry","App","routes","init","routerOptions","createRouter","createBrowserRouter","rootId","documentReady","hydrationKey","document","readyState","IS_SSR_MODE","undefined","Reflect","get","window","Promise","resolve","onReady","deleteProperty","addEventListener","once","Object","defineProperty","configurable","enumerable","set","value","writable","removeEventListener","waitForDocument","lazyMatches","matchRoutes","location","basename","filter","m","route","lazy","length","all","map","lazyResult","assign","router","root","getElementById","appProps","isSSRMode","AppComponent","React","createElement","client","RouterProvider","dataset","ReactDOM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,YAAYX,EAAMK,EAAAC,cAACF,EAAY,OAHtCM,EAASE,WAAWZ,GAAMa,OAAOR,EAAAC,cAACF,EAAY,MAIzD"}
1
+ {"version":3,"file":"entry.js","sources":["../../src/browser/entry.tsx"],"sourcesContent":[null],"names":["async","entry","App","routes","init","routerOptions","createRouter","createBrowserRouter","rootId","stream","IS_SSR_MODE","receiveStream","undefined","documentReady","hydrationKey","document","readyState","Reflect","get","window","Promise","resolve","onReady","deleteProperty","addEventListener","once","Object","defineProperty","configurable","enumerable","set","value","writable","removeEventListener","waitForDocument","lazyMatches","matchRoutes","location","basename","filter","m","route","lazy","length","all","map","lazyResult","assign","hydration","__ssrBoostStream","ready","router","root","getElementById","appProps","isSSRMode","AppComponent","React","createElement","client","RouterProvider","dataset","ReactDOM","hydrateRoot","createRoot","render"],"mappings":"6NA0EAA,eAAeC,EACbC,EACAC,GACAC,KACEA,EAAIC,cACJA,EAAaC,aACbA,EAAeC,EAAmBC,OAClCA,EAAS,QACyB,CAAA,GAEpC,MAAMC,EAASC,EAAcC,SAAkBC,EACzCC,EAvDgB,MACtB,MAAMC,EAAe,8BAErB,KAC0B,YAAxBC,SAASC,YACRN,QAAqDE,IAAtCK,QAAQC,IAAIC,OAAQL,IAKtC,OAAO,IAAIM,QAAeC,IACxB,MAAMC,EAAU,KACVZ,GACFO,QAAQM,eAAeJ,OAAQL,GAGjCO,KAGFN,SAASS,iBAAiB,mBAAoBF,EAAS,CAAEG,MAAM,IAE3Df,GACFgB,OAAOC,eAAeR,OAAQL,EAAc,CAC1Cc,cAAc,EACdC,YAAY,EACZX,IAAK,OACLY,IAAMC,IACJL,OAAOC,eAAeR,OAAQL,EAAc,CAC1Cc,cAAc,EACdC,YAAY,EACZG,UAAU,EACVD,UAEFhB,SAASkB,oBAAoB,mBAAoBX,GACjDD,UAqBca,GAChBC,EAAcC,EAClBjC,EACAgB,OAAOkB,SACPhC,GAAeiC,WACdC,OAAQC,GAAMA,EAAEC,MAAMC,OAIrB7B,GAAiBsB,GAAaQ,eAC1BvB,QAAQwB,IAAI,CAChB/B,MACIsB,GAAe,IAAIU,IAAI7C,MAAOwC,IAChC,MAAME,KAAEA,GAASF,EAAEC,MAEnB,GAAoB,mBAATC,EAAqB,CAC9B,MAAMI,QAAmBJ,IAErBI,GACFpB,OAAOqB,OAAOP,EAAEC,MAAO,IAClBK,EACHJ,UAAM9B,GAGZ,MAKN,MAAMoC,EAAY/B,QAAQC,IAAIC,OAAQ,+BAGlCV,GAAUuC,GAAWC,kBACvBhC,QAAQa,IAAIX,OAAQ,oCAAqCV,EAAOyC,OAGlE,MAAMC,EAAS7C,EAAaH,EAAyBE,GAC/C+C,EAAOrC,SAASsC,eAAe7C,GAC/B8C,QAAkBlD,IAAO,CAAEmD,UAAW7C,EAAayC,YAEnDK,EAAmB,IACvBC,EAAAC,cAACxD,EAAG,CAACyD,OAAQL,GACXG,EAAAC,cAACE,GAAeT,OAAQA,KAI5B,OAAKzC,GAA4C,MAA7B0C,EAAKS,QAAkB,SAIpCC,EAASC,YAAYX,EAAMK,EAAAC,cAACF,EAAY,OAHtCM,EAASE,WAAWZ,GAAMa,OAAOR,EAAAC,cAACF,EAAY,MAIzD"}
@@ -0,0 +1,5 @@
1
+ /** Install before waiting for the document: inline frames may precede the async entry. */
2
+ declare const receiveStream: () => {
3
+ ready: Promise<unknown>;
4
+ };
5
+ export default receiveStream;
@@ -0,0 +1,2 @@
1
+ import{parse as e}from"devalue";const t=()=>{const t=window,r=t.__ssrBoostStream??=[],o=new Map;let s,c,n,i=!1,a=!1,l=!1;const m=new Promise((e,t)=>{c=e,n=t}),S=e=>{let t=o.get(e);if(!t){let r,s;const c=new Promise((e,t)=>{r=e,s=t});c.catch(()=>{}),t={promise:c,resolve:r,reject:s},o.set(e,t)}return t},d=t=>e(t,{SSRBPromise:([e])=>S(e).promise,SSRBObject:e=>Object.fromEntries(e),SSRBError:e=>{const t=Object.fromEntries(e),r=Object.assign(new Error("Streamed loader/action rejection"),t);return t.stack||delete r.stack,r},SSRBUndefined:()=>{}});return r.push=(...e)=>{for(const t of e)try{"shell"===t[0]?i=!0:"init"===t[0]?(s=d(t[1]),[,,a]=t,l=!0):S(t[1])[t[0]](d(t[2])),!l||a&&!i||c(s)}catch(e){n(e),o.forEach(t=>t.reject(e))}return 0},r.push(...r.splice(0)),m.catch(()=>{}),{ready:m}};export{t as default};
2
+ //# sourceMappingURL=stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.js","sources":["../../src/browser/stream.ts"],"sourcesContent":[null],"names":["receiveStream","target","window","queue","__ssrBoostStream","promises","Map","state","resolveReady","rejectReady","hasShell","isEarly","isInitialized","ready","Promise","resolve","reject","deferred","id","pending","get","promise","res","rej","catch","set","value","payload","parse","SSRBPromise","SSRBObject","entries","Object","fromEntries","SSRBError","data","error","assign","Error","stack","SSRBUndefined","push","frames","frame","forEach","splice"],"mappings":"gCAUA,MAAMA,EAAgB,KACpB,MAAMC,EAASC,OACTC,EAASF,EAAOG,mBAAqB,GACrCC,EAAW,IAAIC,IACrB,IAGIC,EACAC,EACAC,EALAC,GAAW,EACXC,GAAU,EACVC,GAAgB,EAIpB,MAAMC,EAAQ,IAAIC,QAAiB,CAACC,EAASC,KAC3CR,EAAeO,EACfN,EAAcO,IAIVC,EAAYC,IAChB,IAAIC,EAAUd,EAASe,IAAIF,GAE3B,IAAKC,EAAS,CACZ,IAAIJ,EACAC,EACJ,MAAMK,EAAU,IAAIP,QAAQ,CAACQ,EAAKC,KAChCR,EAAUO,EACVN,EAASO,IAGNF,EAAQG,MAAM,QACnBL,EAAU,CAAEE,UAASN,UAASC,UAC9BX,EAASoB,IAAIP,EAAIC,EACnB,CAEA,OAAOA,GAIHO,EAASC,GACbC,EAAMD,EAAS,CACbE,YAAa,EAAEX,KAAkBD,EAASC,GAAIG,QAC9CS,WAAaC,GAAiCC,OAAOC,YAAYF,GACjEG,UAAYH,IACV,MAAMI,EAAOH,OAAOC,YAAYF,GAC1BK,EAAQJ,OAAOK,OAAO,IAAIC,MAAM,oCAAqCH,GAM3E,OAJKA,EAAKI,cACDH,EAAMG,MAGRH,GAETI,cAAe,SA+BnB,OA3BArC,EAAMsC,KAAO,IAAIC,KACf,IAAK,MAAMC,KAASD,EAClB,IACmB,UAAbC,EAAM,GACRjC,GAAW,EACW,SAAbiC,EAAM,IACfpC,EAAQmB,EAAMiB,EAAM,KACpB,CAAA,CAAKhC,GAAWgC,EAChB/B,GAAgB,GAEhBK,EAAS0B,EAAM,IAAIA,EAAM,IAAIjB,EAAMiB,EAAM,MAGvC/B,GAAmBD,IAAWD,GAChCF,EAAaD,EAEjB,CAAE,MAAO6B,GACP3B,EAAY2B,GACZ/B,EAASuC,QAASzB,GAAYA,EAAQH,OAAOoB,GAC/C,CAGF,OAAO,GAETjC,EAAMsC,QAAQtC,EAAM0C,OAAO,IACtBhC,EAAMW,MAAM,QAEV,CAAEX"}
@@ -0,0 +1,3 @@
1
+ /** Codes safe to record in a build support bundle. Never record warning payloads. */
2
+ declare const DIAGNOSTIC_CODES: string[];
3
+ export default DIAGNOSTIC_CODES;
@@ -0,0 +1,2 @@
1
+ const S=["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"];export{S as default};
2
+ //# sourceMappingURL=diagnostic-codes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostic-codes.js","sources":["../../src/cli/diagnostic-codes.ts"],"sourcesContent":[null],"names":["DIAGNOSTIC_CODES"],"mappings":"AACA,MAAMA,EAAmB,CACvB,oCACA,mCACA,2BACA,oCACA,6BACA"}
@@ -0,0 +1,55 @@
1
+ export interface IDoctorOptions {
2
+ root?: string;
3
+ json?: boolean;
4
+ bundle?: string;
5
+ }
6
+ export interface ICheck {
7
+ name: string;
8
+ status: 'ok' | 'warn' | 'error';
9
+ message: string;
10
+ fix: string;
11
+ info?: boolean;
12
+ }
13
+ export interface IDoctorReport {
14
+ versions: Record<string, string | null>;
15
+ adapter: string | null;
16
+ routes: {
17
+ id: string;
18
+ path: string | null;
19
+ }[];
20
+ checks: ICheck[];
21
+ diagnosticCodes: string[];
22
+ }
23
+ export declare const TESTED_MATRIX: {
24
+ react: string;
25
+ router: string;
26
+ vite: string;
27
+ }[];
28
+ /** Prefer npm's own CLI, then the npm bundled beside the current Node runtime. */
29
+ export declare const resolveNpmCli: () => string | undefined;
30
+ /** Inspect npm's dependency tree, counting physical copies rather than dependants. */
31
+ export declare const reactCopies: (root: string) => {
32
+ react: number;
33
+ "react-dom": number;
34
+ };
35
+ /** Read-only project inspection. The JSON schema is also usable from automation. */
36
+ export declare const inspectProject: (options?: IDoctorOptions) => IDoctorReport;
37
+ /** Support bundles contain an allowlist, never raw messages, npm output, env, or source. */
38
+ export declare const supportBundle: (report: IDoctorReport) => {
39
+ schemaVersion: number;
40
+ versions: Record<string, string | null>;
41
+ adapter: string | null;
42
+ routes: {
43
+ id: string;
44
+ path: string | null;
45
+ }[];
46
+ checks: {
47
+ info?: true | undefined;
48
+ name: string;
49
+ status: "error" | "warn" | "ok";
50
+ fix: string;
51
+ }[];
52
+ diagnosticCodes: string[];
53
+ };
54
+ declare const runDoctor: (options?: IDoctorOptions) => void;
55
+ export default runDoctor;
package/cli/doctor.js ADDED
@@ -0,0 +1,2 @@
1
+ import e from"node:child_process";import t from"node:fs";import{createRequire as s}from"node:module";import r from"node:path";import o from"semver";import n from"./diagnostic-codes.js";import{libraryPackage as i,stringValue as a,readPackage as c,readConfig as l,readHtml as d,objectProperty as p}from"./project.js";import u from"../constants/plugin-name.js";import m from"../services/parse-routes.js";import f from"../services/server-config.js";import h from"../services/source-files.js";const g=[{react:"18.2.0",router:"7.18.3",vite:"6.4.3"},{react:"19.2.8",router:"7.18.3",vite:"7.3.6"},{react:"19.2.8",router:"8.3.1",vite:"8.2.2"}],v=()=>{const e=r.dirname(process.execPath);return[process.env.npm_execpath,r.join(e,"..","lib","node_modules","npm","bin","npm-cli.js"),r.join(e,"node_modules","npm","bin","npm-cli.js")].find(e=>e&&t.existsSync(e))},b=s=>{let o;try{const t=v(),r=["ls","react","react-dom","--json","--all","--long"];o=e.execFileSync(t?process.execPath:"npm",t?[t,...r]:r,{cwd:s,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:2e4,maxBuffer:8388608})}catch(e){const t=e;if(!t.stdout||t.signal)throw new Error("npm ls failed; install dependencies and rerun npm ls react react-dom --json.");o=String(t.stdout)}const n={react:new Set,"react-dom":new Set},i=(e,s)=>{for(const[o,a]of Object.entries(e.dependencies??{})){const e=a.path??r.join(s,"node_modules",o);"react"!==o&&"react-dom"!==o||!a.version||a.deduped||n[o].add(t.existsSync(e)?t.realpathSync(e):e),i(a,e)}};return i(JSON.parse(o),s),{react:n.react.size,"react-dom":n["react-dom"].size}},$=(e,t="")=>e.flatMap(e=>{const s=[t,String(e.index)].filter(Boolean).join("-");return[{id:e.id??s,path:e.path??null},...$(e.children,s)]}),y=(e={})=>{const v=r.resolve(e.root??process.cwd()),y=[],w={node:process.versions.node},x={versions:w,adapter:null,routes:[],checks:y,diagnosticCodes:[]},j=(e,t,s,r=!1)=>{try{y.push({name:e,status:"ok",message:s(),fix:t,...r?{info:r}:{}})}catch(s){y.push({name:e,status:"error",message:s.message,fix:t,...r?{info:r}:{}})}};let S={};j("package","Run doctor in the app directory or set --root.",()=>(S=c(r.join(v,"package.json")),"package.json is readable"));const R=s(r.join(v,"package.json")),k=[u,"react","react-dom","react-router","vite"],E=i(),O={[u]:E.engines.node},D={app:S.peerDependencies??{}};for(const e of k)j(`version:${e}`,`Install ${e} at a version satisfying the installed packages’ peer ranges.`,()=>{const t=c(R.resolve(`${e}/package.json`)),s=o.valid(t.version);if(D[e]=t.peerDependencies??(e===u?E.peerDependencies??{}:{}),w[e]=s,!s)throw new Error(`${e} has no valid installed version`);return t.engines?.node&&(O[e]=t.engines.node),`${e} ${s}`}),w[e]??=null;for(const e of y.filter(e=>e.name.startsWith("version:")&&"ok"===e.status)){const t=e.name.slice(8),s=Object.entries(D).flatMap(([e,s])=>s[t]&&!o.satisfies(w[t],s[t])?[`${e} requires ${t}: ${s[t]}`]:[]);s.length&&(e.status="error",e.message+=`; ${s.join("; ")}`)}const N=e=>Number(w.react===e.react&&w["react-dom"]===e.react)+Number(w["react-router"]===e.router)+Number(w.vite===e.vite),M=(e,t)=>{const s=o.parse(e),r=o.parse(t);return s?1e6*Math.abs(s.major-r.major)+1e3*Math.abs(s.minor-r.minor)+Math.abs(s.patch-r.patch):Number.MAX_SAFE_INTEGER},[F]=[...g].sort((e,t)=>N(t)-N(e)||M(w.react,e.react)-M(w.react,t.react)||M(w["react-dom"],e.react)-M(w["react-dom"],t.react)||M(w["react-router"],e.router)-M(w["react-router"],t.router)||M(w.vite,e.vite)-M(w.vite,t.vite)),z=`React ${w.react??"missing"}${w["react-dom"]!==w.react?` (React DOM ${w["react-dom"]??"missing"})`:""} + Router ${w["react-router"]??"missing"} + Vite ${w.vite??"missing"}`,C=3===N(F);let V;y.push({name:"compatibility",status:C?"ok":"warn",message:C?`${z} is a tested row`:`${z} is not a tested row; closest: React ${F.react} + Router ${F.router} + Vite ${F.vite}`,fix:`Use React and React DOM ${F.react}, React Router ${F.router}, and Vite ${F.vite} for a tested combination.`}),j("node","Use a Node version satisfying the package and app engines (CI uses 22.23.2).",()=>{S.engines?.node&&(O.app=S.engines.node);const e=Object.entries(O).filter(([,e])=>!o.satisfies(process.versions.node,e));if(e.length)throw new Error(`Node ${process.versions.node} does not satisfy ${e.map(([e,t])=>`${e}: ${t}`).join(", ")}`);return`Node ${process.versions.node} satisfies engines`}),j("react-copies","Run npm dedupe and align React/React DOM dependency versions.",()=>{const e=b(v);if(1!==e.react||1!==e["react-dom"])throw new Error(`React copies: ${e.react}; React DOM copies: ${e["react-dom"]}`);return"One physical copy each of React and React DOM"}),j("vite-plugin","Add SsrBoost() from @lomray/vite-ssr-boost/plugin to Vite plugins.",()=>{if(V=l(v),!V.plugin)throw new Error("Vite plugins do not contain the imported SsrBoost() plugin");return"SsrBoost() is in the Vite plugins"});const _=V?.viteRoot??(t.existsSync(r.join(v,"index.html"))?v:r.join(v,"src")),A=r.resolve(_,a(V?.option("indexFile"))??"index.html"),B=a(V?.option("clientFile"))??"client.ts",I=a(V?.option("serverFile"))??"server.ts";j("html-module",'Keep one local <script type="module" src="..."> pointing to the configured clientFile.',()=>{const e=d(A);if(1!==e.entries.length)throw new Error(`${r.relative(v,A)}: expected one module script, found ${e.entries.length}`);const t=e.attribute(e.entries[0],"src");if(!t||/^(?:\w+:|\/\/)/.test(t)||r.resolve(t.startsWith("/")?_:r.dirname(A),t.replace(/^\//,""))!==r.resolve(_,B))throw new Error(`${r.relative(v,A)}: module script does not match clientFile`);return"Module script matches the browser entry"}),j("html-outlet","Place exactly one \x3c!--ssr-outlet--\x3e inside the root element.",()=>{const e=d(A);if(1!==e.outlets)throw new Error(`${r.relative(v,A)}: expected one \x3c!--ssr-outlet--\x3e, found ${e.outlets}`);return"Exactly one SSR outlet"});const J=new h(V?.aliases);for(const[e,t,s]of[["browser",B,"browser/entry"],["server",I,"adapters/express/entry"]])j(`${e}-entry`,`Create the ${e} entry and import ${u}/${s}.`,()=>{if(!J.read(r.resolve(_,t)).ast.program.body.filter(e=>"ImportDeclaration"===e.type).some(e=>e.source.value.replace(/\.js$/,"")===`${u}/${s}`))throw new Error(`${t}: missing library ${s} import`);return"server"===e&&(x.adapter="express"),`${t} imports ${s}`});j("routes","Use statically analyzable route objects; follow the file and line in the parser error.",()=>(x.routes=$(new m(f.init({},{root:_,clientFile:B}),V?.aliases).parse(!0)),`${x.routes.length} route IDs resolved`)),j("scripts",'Set dev (or develop)="ssr-boost dev", build="ssr-boost build", start:ssr="ssr-boost start".',()=>{const e=S.scripts??{},t=[["dev",e.dev??e.develop],["build",e.build],["start",e["start:ssr"]??e.start]].filter(([e,t])=>!new RegExp(`(?:^|\\s)ssr-boost\\s+${e}(?:\\s|$)`).test(t??""));if(t.length)throw new Error(`Scripts missing ssr-boost commands: ${t.map(([e])=>e).join(", ")}`);return"Development, build, and SSR start scripts use ssr-boost"}),j("robots","Review public/robots.txt for your deployment; use build --unlock-robots only when intended.",()=>{const e=a(V?p(V.node,"publicDir"):void 0)??"public",s=r.resolve(_,e,"robots.txt");return t.existsSync(s)?/^Disallow:\s*\/\s*$/im.test(t.readFileSync(s,"utf8"))?"robots.txt blocks crawling at / (report only)":"robots.txt contains a custom/allow policy (report only)":"No robots.txt policy (report only)"},!0),j("size-budget","Add a size:check or test:size script with an application bundle budget.",()=>Object.keys(S.scripts??{}).some(e=>/(?:^|:)size(?::|$)/.test(e))?"Size budget script present":"No size budget script (informational)",!0);const P=V?p(V.node,"build"):void 0,U="ObjectExpression"===P?.type?a(p(P,"outDir")):void 0,W=r.resolve(_,U??"dist","ssr-boost-diagnostics.json");if(t.existsSync(W))try{const e=JSON.parse(t.readFileSync(W,"utf8")),s=e&&"object"==typeof e?Reflect.get(e,"codes"):void 0;x.diagnosticCodes=Array.isArray(s)?n.filter(e=>s.includes(e)):[]}catch{}return x},w=e=>({schemaVersion:1,versions:e.versions,adapter:e.adapter,routes:e.routes,checks:e.checks.map(({name:e,status:t,fix:s,info:r})=>({name:e,status:t,fix:s,...r?{info:r}:{}})),diagnosticCodes:e.diagnosticCodes}),x=(e={})=>{const s=y(e);if(e.bundle)try{t.writeFileSync(r.resolve(e.root??process.cwd(),e.bundle),`${JSON.stringify(w(s),null,2)}\n`)}catch{s.checks.push({name:"bundle",status:"error",message:"Cannot write the support bundle.",fix:"Choose a writable file in an existing directory for --bundle."})}e.json?console.info(JSON.stringify(s,null,2)):console.table(s.checks.map(({status:e,name:t,message:s,fix:r})=>({status:e,check:t,message:s,fix:r}))),process.exitCode=s.checks.some(e=>"error"===e.status)?1:0};export{g as TESTED_MATRIX,x as default,y as inspectProject,b as reactCopies,v as resolveNpmCli,w as supportBundle};
2
+ //# sourceMappingURL=doctor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor.js","sources":["../../src/cli/doctor.ts"],"sourcesContent":[null],"names":["TESTED_MATRIX","react","router","vite","resolveNpmCli","directory","path","dirname","process","execPath","env","npm_execpath","join","find","candidate","fs","existsSync","reactCopies","root","output","npmCli","args","childProcess","execFileSync","cwd","shell","encoding","stdio","timeout","maxBuffer","error","failed","stdout","signal","Error","String","copies","Set","visit","node","name","dependency","Object","entries","dependencies","location","version","deduped","add","realpathSync","JSON","parse","size","routeDetails","routes","parent","flatMap","route","position","index","filter","Boolean","id","children","inspectProject","options","resolve","checks","versions","report","adapter","diagnosticCodes","check","fix","inspect","info","push","status","message","pkg","readPackage","require","createRequire","packages","PLUGIN_NAME","ownPackage","libraryPackage","engines","peers","app","peerDependencies","metadata","semver","valid","item","row","startsWith","slice","failures","dependant","ranges","satisfies","length","matches","Number","distance","installed","tested","target","Math","abs","major","minor","patch","MAX_SAFE_INTEGER","closest","sort","left","right","trio","isTested","config","range","map","readConfig","plugin","viteRoot","indexFile","stringValue","option","clientFile","serverFile","html","readHtml","relative","src","attribute","test","replace","outlets","sources","SourceFiles","aliases","kind","file","expected","read","ast","program","body","type","some","source","value","ParseRoutes","ServerConfig","init","scripts","missing","dev","develop","build","start","command","RegExp","publicDir","objectProperty","undefined","readFileSync","keys","outDir","diagnosticsFile","recorded","codes","Reflect","get","Array","isArray","DIAGNOSTIC_CODES","code","includes","supportBundle","schemaVersion","runDoctor","bundle","writeFileSync","stringify","json","console","table","exitCode"],"mappings":"weA4CO,MAAMA,EAAgB,CAC3B,CAAEC,MAAO,SAAUC,OAAQ,SAAUC,KAAM,SAC3C,CAAEF,MAAO,SAAUC,OAAQ,SAAUC,KAAM,SAC3C,CAAEF,MAAO,SAAUC,OAAQ,QAASC,KAAM,UAW/BC,EAAgB,KAC3B,MAAMC,EAAYC,EAAKC,QAAQC,QAAQC,UAOvC,M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ACAL,UAKNjE,QAAQsL,SAAWzH,EAAOF,OAAOoF,KAAM/E,GAA2B,UAAjBA,EAAMK,QAAsB,EAAI"}
package/cli/init.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export interface IInitOptions {
2
+ root?: string;
3
+ entry?: string;
4
+ routes?: string;
5
+ dryRun?: boolean;
6
+ apply?: boolean;
7
+ }
8
+ export interface IFileChange {
9
+ file: string;
10
+ before: string;
11
+ after: string;
12
+ }
13
+ /** Build all edits first. A failed analysis leaves even --apply completely untouched. */
14
+ export declare const planInit: (options?: IInitOptions) => IFileChange[];
15
+ /** CLI default is a complete unified diff, with no temporary files or installs. */
16
+ declare const runInit: (options?: IInitOptions) => void;
17
+ export default runInit;
package/cli/init.js ADDED
@@ -0,0 +1,2 @@
1
+ import e from"node:fs";import t from"node:path";import{createTwoFilesPatch as r}from"diff";import{MANUAL_GUIDE as o,readConfig as n,format as i,objectProperty as s,stringValue as a,readHtml as l,editText as p,readPackage as c,libraryPackage as d}from"./project.js";import m from"../constants/plugin-name.js";import f from"../services/parse-routes.js";import u,{sourceError as y,walk as h,unwrap as $}from"../services/source-files.js";const g=(e,r)=>{const o=t.relative(t.dirname(e),r).split(t.sep).join("/");return o.startsWith(".")?o:`./${o}`},v=e=>{const t=new Set;return h(e,e=>{"Identifier"!==e.type&&"JSXIdentifier"!==e.type||t.add(e.name)}),t},w=(e,t,r,o,n)=>{const i=e.specifiers.filter(e=>t.has(e.local.name)),s=i.filter(e=>"ImportDefaultSpecifier"===e.type).map(e=>e.local.name),a=i.filter(e=>"ImportNamespaceSpecifier"===e.type).map(e=>`* as ${e.local.name}`),l=i.flatMap(e=>{if("ImportSpecifier"!==e.type)return[];const t="Identifier"===e.imported.type?e.imported.name:`${o}${e.imported.value}${o}`;return[`${"type"===e.importKind?"type ":""}${t}${t===e.local.name?"":` as ${e.local.name}`}`]}),p=[...s,...a,...l.length?[`{ ${l.join(", ")} }`]:[]];return p.length?`import ${"type"===e.importKind?"type ":""}${p.join(", ")} from ${o}${r}${o}${n}`:""},x=(e,t)=>{const r=[];for(const o of e.read(t).ast.program.body)"ExportDefaultDeclaration"===o.type&&r.push("default"),"ExportNamedDeclaration"===o.type&&("VariableDeclaration"===o.declaration?.type&&r.push(...o.declaration.declarations.flatMap(e=>"Identifier"===e.id.type?[e.id.name]:[])),r.push(...o.specifiers.map(e=>"Identifier"===e.exported.type?e.exported.name:e.exported.value)));return r.flatMap(r=>{const o=e.exported(t,r);return"ArrayExpression"===o.node.type?[{name:r,value:o}]:[]})},b=(r={})=>{const o=t.resolve(r.root??process.cwd()),b=n(o),{newline:S,quote:j,semicolon:E}=i(b.code),R=[],I=(r,n)=>{const i=e.existsSync(r)?e.readFileSync(r,"utf8"):"";i!==n&&R.push({file:t.relative(o,r).split(t.sep).join("/"),before:i,after:n})},C=s(b.node,"base");if(C&&"/"!==a(C))throw y(b.file,C,"Vite base; automatic migration currently maps only /");if(b.node.properties.some(e=>"SpreadElement"===e.type))throw y(b.file,b.node,"spread Vite configuration");const D=s(b.node,"build"),F="ObjectExpression"===D?.type?s(D,"rollupOptions"):void 0;if(b.option("entrypoint")||"ObjectExpression"===F?.type&&s(F,"input"))throw y(b.file,F,"multiple or custom build entries");const J=t.resolve(b.viteRoot,a(b.option("indexFile"))??"index.html"),X=l(J);if(1!==X.entries.length||!X.attribute(X.entries[0],"src"))throw y(J,void 0,`module entries (${X.entries.length}); expected one external module script`);const M=X.attribute(X.entries[0],"src");if(/(?:^(?:\w+:|\/\/))|[?#]/.test(M))throw y(J,void 0,"non-local browser entry URL");const A=t.resolve(M.startsWith("/")?b.viteRoot:t.dirname(J),M.replace(/^\//,"")),O=r.entry?t.resolve(o,r.entry):A;if(O!==A)throw y(J,void 0,"--entry does not match the module script");const B=new u(b.aliases),{code:P,ast:N}=B.read(O),V=i(P),T=V.quote,W=V.semicolon,z=V.newline,L=/\.[cm]?tsx?$/.test(O),k=t.resolve(t.dirname(O),"server."+(L?"ts":"js"));if(N.program.body.some(e=>"ImportDeclaration"===e.type&&e.source.value.replace(/\.js$/,"")===`${m}/browser/entry`)){if(!b.plugin||1!==X.outlets||!e.existsSync(k))throw y(O,void 0,"partially configured SSR app; finish the migration using doctor");return[]}if(e.existsSync(k))throw y(k,void 0,"existing server entry; refusing to overwrite");if(1!==X.roots.length||!X.roots[0].sourceCodeLocation?.endTag||X.outlets>1)throw y(J,void 0,'root element; expected exactly one empty element with id="root"');const q=X.roots[0].sourceCodeLocation;if(X.code.slice(q.startTag.endOffset,q.endTag.startOffset).replace("\x3c!--ssr-outlet--\x3e","").trim())throw y(J,void 0,"non-empty root element");const K=[],U=[];if(h(N,e=>{if("CallExpression"===e.type){if("Identifier"===e.callee.type){const t=B.import(O,e.callee.name);"createBrowserRouter"===t?.exported&&["react-router","react-router-dom"].includes(t.source)&&K.push(e)}"MemberExpression"===e.callee.type&&"Identifier"===e.callee.property.type&&"render"===e.callee.property.name&&U.push(e)}}),1!==K.length)throw y(O,K[1],`createBrowserRouter calls (${K.length}); JSX BrowserRouter/Routes and router factories need manual migration`);const[_]=K;if(1!==_.arguments.length||1!==U.length)throw y(O,_,"router options or multiple React roots; migrate their settings manually");const[G]=U,H="MemberExpression"===G.callee.type?B.resolve({node:G.callee.object,file:O}).node:void 0;if("CallExpression"!==H?.type||"Identifier"!==H.callee.type||"react-dom/client"!==B.import(O,H.callee.name)?.source||"createRoot"!==B.import(O,H.callee.name)?.exported||1!==H.arguments.length||1!==G.arguments.length)throw y(O,H,"React mount; use createRoot(element).render(...) without custom options");const Q=$(G.arguments[0]);let Y=Q;const Z=[],ee=new Map;for(;"JSXElement"===Y?.type||"JSXFragment"===Y?.type;){if("JSXElement"===Y.type){const{name:e}=Y.openingElement,t="JSXMemberExpression"===e.type&&"JSXIdentifier"===e.object.type?e:void 0,r="JSXIdentifier"===e.type?e.name:"JSXIdentifier"===t?.object.type?t.object.name:void 0,o=N.program.body.find(e=>"ImportDeclaration"===e.type&&e.specifiers.some(e=>"ImportNamespaceSpecifier"===e.type&&e.local.name===r)),n=r?B.import(O,r)??(o?{declaration:o,source:o.source.value,exported:"*"}:void 0):void 0,i="react"===n?.source&&["StrictMode","Fragment"].includes(t?.property.name??n.exported);if(!t&&"RouterProvider"===n?.exported&&["react-router","react-router-dom"].includes(n.source))break;if(!r||!n||t&&!i||Y.openingElement.attributes.length)throw y(O,Y,"App wrapper; use an imported component without additional props");const s=ee.get(n.declaration)??new Set;s.add(r),ee.set(n.declaration,s),Z.push({tag:t?`${r}.${t.property.name}`:r,builtin:i})}else Z.push({tag:"",builtin:!0});const e=Y.children.filter(e=>"JSXText"!==e.type||e.value.trim());if(1!==e.length)throw y(O,Y,"App wrapper; expected exactly one RouterProvider child");[Y]=e}if("JSXElement"!==Y?.type)throw y(O,Q,"React root; expected an imported RouterProvider with optional App, StrictMode or Fragment wrappers");const[te]=Y.openingElement.attributes;if(1!==Y.openingElement.attributes.length||"JSXAttribute"!==te?.type||"router"!==te.name.name||"JSXExpressionContainer"!==te.value?.type||B.resolve({node:te.value.expression,file:O}).node!==_)throw y(O,Y,"RouterProvider props; use the detected router without additional props");let re=[...ee].map(([e,t])=>w(e,t,e.source.value,T,W)).join(z),oe=re,ne="",ie="",se=Z[0]?.tag??"App";if(1!==Z.length||Z[0].builtin){const e=new Set([...ee.values()].flatMap(e=>[...e])),t=$(_.arguments[0]);"Identifier"===t?.type&&e.add(t.name);const r=t=>{let r=t;for(;e.has(r);)r+="_";return e.add(r),r};se=r("App");const o=r("FC"),n=r("PropsWithChildren"),i=r("ssrCreateElement"),s=r("ssrFragment"),a=L?`import type { ${"FC"===o?o:`FC as ${o}`}, ${"PropsWithChildren"===n?n:`PropsWithChildren as ${n}`} } from ${T}react${T}${W}`:"",l=Z.length?Z:[{tag:"",builtin:!0}],p=l.reduceRight((e,{tag:t})=>`<${t}>${e}</${t}>`,"{children}"),c=l.reduceRight((e,{tag:t})=>`${i}(${t||s}, null, ${e})`,"children"),d=`const ${se}${L?`: ${o}<${n}>`:""} = ({ children }) => `;re=[re,a].filter(Boolean).join(z),oe=[re,`import { createElement as ${i}${l.some(({tag:e})=>!e)?`, Fragment as ${s}`:""} } from ${T}react${T}${W}`].filter(Boolean).join(z),ie=`${d}${c}${W}${z}`,ne=/\.[jt]sx$/.test(O)?`${d}${p}${W}${z}`:ie,/\.[jt]sx$/.test(O)||(re=oe)}const ae=B.resolve({node:_.arguments[0],file:O});let le=ae,pe=le.file,ce=pe!==O?x(B,pe).find(e=>e.value.node===le.node)?.name:void 0;if(r.routes){pe=B.filename(g(O,t.resolve(o,r.routes)),O);const e=x(B,pe);if(1!==e.length)throw y(pe,void 0,`exported route arrays (${e.length}); --routes needs one exported array`);le=e[0].value,ce=e[0].name}new f({}).parseValue(B,le,!0);const de=new Set;if(!ce){const r=B.read(le.file),o=v(le.node);let n=-1;for(;n!==o.size;){n=o.size;for(const e of r.ast.program.body){const t="ExportNamedDeclaration"===e.type?e.declaration:e,r="VariableDeclaration"===t?.type?t.declarations.flatMap(e=>"Identifier"===e.id.type?[e.id.name]:[]):"FunctionDeclaration"===t?.type&&t.id?[t.id.name]:[];if(t&&r.some(e=>o.has(e))){if(t.start<=le.node.start&&t.end>=le.node.end)continue;de.add(e),v(t).forEach(e=>o.add(e))}}}const i=[];for(const e of r.ast.program.body)if("ImportDeclaration"===e.type){const t=w(e,o,e.source.value,T,W);t&&i.push(t)}else de.has(e)&&i.push(r.code.slice(e.start,e.end));const s=t.extname(le.file);if(pe=t.resolve(t.dirname(le.file),`routes.ssr${s}`),e.existsSync(pe))throw y(pe,void 0,"existing extracted routes file");i.push(`export default ${r.code.slice(le.node.start,le.node.end)}${L?" satisfies import('react-router').RouteObject[]":""}${W}`),I(pe,`${i.join(z+z)}${z}`),ce="default"}for(const e of N.program.body){if("VariableDeclaration"===e.type&&1!==e.declarations.length)throw y(O,e,"multiple bootstrap declarators; put each declaration on its own statement");if("ImportDeclaration"!==e.type&&!de.has(e)&&![_,H,G,...ae.file===O?[ae.node]:[]].some(t=>t.start>=e.start&&t.end<=e.end))throw y(O,e,"additional browser startup statement; move it to a shared wrapper or migrate manually")}const me=$(_.arguments[0]),fe="Identifier"===me?.type?B.import(O,me.name):void 0,ue=fe&&le.node===ae.node,ye=ue&&"Identifier"===me?.type?me.name:"default"===ce?"routes":ce,he=ue?w(fe.declaration,new Set([ye]),fe.source,T,W):`import ${"default"===ce?ye:`{ ${ce} }`} from ${T}${g(O,pe).replace(/\.[cm]?[jt]sx?$/,"")}${T}${W}`,$e=N.program.body.filter(e=>"ImportDeclaration"===e.type&&!e.specifiers.length).map(e=>P.slice(e.start,e.end));I(O,[`import entryClient from ${T}${m}/browser/entry${T}${W}`,re,he,...$e,"",...ne?[ne]:[],`void entryClient(${se}, ${ye})${W}`,""].join(z)),I(k,[`import entryServer from ${T}${m}/adapters/express/entry${T}${W}`,oe,he,"",...ie?[ie]:[],`export default entryServer(${se}, ${ye})${W}`,""].join(z));const ge=[],ve=[`clientFile: ${j}${t.relative(b.viteRoot,O).split(t.sep).join("/")}${j}`,`serverFile: ${j}${t.relative(b.viteRoot,k).split(t.sep).join("/")}${j}`];e.existsSync(t.join(o,"tsconfig.json"))||ve.push("tsconfigAliases: false");const we=`SsrBoost({ ${ve.join(", ")} })`;if(b.plugin)throw y(b.file,b.plugin,"existing SsrBoost plugin with a SPA browser entry; finish configuration manually");if("ArrayExpression"===b.plugins?.type)ge.push({start:b.plugins.start+1,end:b.plugins.start+1,text:`${we}${b.plugins.elements.length?", ":""}`});else{if(b.plugins)throw y(b.file,b.plugins,"Vite plugins; use an array literal");ge.push({start:b.node.start+1,end:b.node.start+1,text:`${S} plugins: [${we}],`})}if(v(b.ast).has("SsrBoost"))throw y(b.file,void 0,"existing SsrBoost binding; rename it before automatic migration");I(b.file,`import SsrBoost from ${j}${m}/plugin${j}${E}${S}${p(b.code,ge)}`),X.outlets||I(J,p(X.code,[{start:q.startTag.endOffset,end:q.startTag.endOffset,text:"\x3c!--ssr-outlet--\x3e"}]));const xe=t.join(o,"package.json"),be=e.readFileSync(xe,"utf8"),Se=c(xe),je={...Se.scripts,[Se.scripts&&Object.hasOwn(Se.scripts,"dev")?"dev":"develop"]:"ssr-boost dev",build:"ssr-boost build","start:ssr":"ssr-boost start"};"vite preview"===Se.scripts?.preview&&(je.preview="ssr-boost preview");const Ee=i(be),Re=d().version,Ie={...Se.dependencies,[m]:Se.dependencies?.[m]??Se.devDependencies?.[m]??`^${Re}`};return I(xe,`${JSON.stringify({...Se,scripts:je,dependencies:Ie},null,Ee.indent).replace(/\n/g,Ee.newline)}${be.endsWith("\n")?Ee.newline:""}`),R.sort((e,t)=>e.file.localeCompare(t.file))},S=(n={})=>{try{if(n.apply&&n.dryRun)throw new Error("Choose either --dry-run or --apply.");const o=b(n);if(!o.length)return void console.info("No changes: SSR is already initialized. Run ssr-boost doctor.");for(const e of o)console.info(r(e.before?`a/${e.file}`:"/dev/null",`b/${e.file}`,e.before,e.after));if(n.apply)for(const r of o)e.writeFileSync(t.resolve(n.root??process.cwd(),r.file),r.after);console.info(n.apply?`Applied ${o.length} file changes.`:"Dry run: no files written. Use --apply to write these changes."),console.info("Next: npm install; then npx ssr-boost doctor.")}catch(e){console.error(`${e.message}\nManual migration: ${o}`),process.exitCode=1}};export{S as default,b as planInit};
2
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sources":["../../src/cli/init.ts"],"sourcesContent":[null],"names":["relativeImport","from","to","relative","path","dirname","split","sep","join","startsWith","namesIn","node","names","Set","walk","child","type","add","name","importText","source","quote","semicolon","specifiers","filter","specifier","has","local","defaults","map","namespaces","named","flatMap","imported","value","importKind","bindings","length","arrayExports","sources","file","read","ast","program","body","push","declaration","declarations","id","exported","planInit","options","root","resolve","process","cwd","config","readConfig","newline","format","code","changes","after","before","fs","existsSync","readFileSync","base","objectProperty","stringValue","sourceError","properties","some","property","build","rollup","undefined","option","indexFile","viteRoot","html","readHtml","entries","attribute","src","test","detectedEntry","replace","entry","SourceFiles","aliases","entryFormat","q","end","nl","isTS","server","PLUGIN_NAME","plugin","outlets","roots","sourceCodeLocation","endTag","rootLocation","slice","startTag","endOffset","startOffset","trim","calls","renders","callee","import","includes","call","arguments","render","rootCall","object","rendered","unwrap","provider","wrappers","wrapperImports","Map","openingElement","member","namespace","find","binding","isBuiltin","attributes","get","set","tag","builtin","children","routerAttribute","expression","appImport","serverAppImport","appDeclaration","serverAppDeclaration","appName","reserved","values","argument","unique","result","fc","props","createElement","fragment","typeImport","tree","jsx","reduceRight","definition","Boolean","originalRoutes","routeValue","routeModule","routeExport","item","routes","filename","exports","ParseRoutes","parseValue","moved","previousSize","size","statement","declared","start","forEach","pieces","text","extension","extname","routeArgument","routeBinding","shouldKeepRouteImport","routeName","routeImport","sideEffects","edits","pluginOptions","pluginCall","plugins","elements","editText","packageFile","packageCode","pkg","readPackage","scripts","Object","hasOwn","preview","packageFormat","version","libraryPackage","dependencies","devDependencies","JSON","stringify","indent","endsWith","sort","left","right","localeCompare","runInit","apply","dryRun","Error","console","info","change","createTwoFilesPatch","writeFileSync","error","message","MANUAL_GUIDE","exitCode"],"mappings":"kbAoCA,MAAMA,EAAiB,CAACC,EAAcC,KACpC,MAAMC,EAAWC,EAAKD,SAASC,EAAKC,QAAQJ,GAAOC,GAAII,MAAMF,EAAKG,KAAKC,KAAK,KAE5E,OAAOL,EAASM,WAAW,KAAON,EAAW,KAAKA,KAI9CO,EAAWC,IACf,MAAMC,EAAQ,IAAIC,IAQlB,OANAC,EAAKH,EAAOI,IACS,eAAfA,EAAMC,MAAwC,kBAAfD,EAAMC,MACvCJ,EAAMK,IAAIF,EAAMG,QAIbN,GAIHO,EAAa,CACjBR,EACAC,EACAQ,EACAC,EACAC,KAEA,MAAMC,EAAaZ,EAAKY,WAAWC,OAAQC,GAAcb,EAAMc,IAAID,EAAUE,MAAMT,OAC7EU,EAAWL,EACdC,OAAQC,GAAiC,2BAAnBA,EAAUT,MAChCa,IAAKJ,GAAcA,EAAUE,MAAMT,MAChCY,EAAaP,EA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AAM,IAAIC,MAAM,uCAGlB,MAAM3J,EAAUX,EAASC,GAEzB,IAAKU,EAAQxB,OAGX,YAFAoL,QAAQC,KAAK,iEAKf,IAAK,MAAMC,KAAU9J,EACnB4J,QAAQC,KACNE,EACED,EAAO5J,OAAS,KAAK4J,EAAOnL,OAAS,YACrC,KAAKmL,EAAOnL,OACZmL,EAAO5J,OACP4J,EAAO7J,QAKb,GAAIX,EAAQmK,MACV,IAAK,MAAMK,KAAU9J,EACnBG,EAAG6J,cAAczN,EAAKiD,QAAQF,EAAQC,MAAQE,QAAQC,MAAOoK,EAAOnL,MAAOmL,EAAO7J,OAItF2J,QAAQC,KACNvK,EAAQmK,MACJ,WAAWzJ,EAAQxB,uBACnB,kEAENoL,QAAQC,KAAK,gDACf,CAAE,MAAOI,GACPL,QAAQK,MAAM,GAAIA,EAAgBC,8BAA8BC,KAChE1K,QAAQ2K,SAAW,CACrB"}
@@ -0,0 +1,56 @@
1
+ import type { Node, ObjectExpression } from '@babel/types';
2
+ import type { DefaultTreeAdapterTypes } from 'parse5';
3
+ import type { Alias } from 'vite';
4
+ import SourceFiles from '../services/source-files.js';
5
+ export declare const MANUAL_GUIDE = "https://lomray-software.github.io/vite-ssr-boost/guide/migrate-existing-spa";
6
+ export interface IPackage {
7
+ version?: string;
8
+ engines?: {
9
+ node?: string;
10
+ };
11
+ scripts?: Record<string, string>;
12
+ dependencies?: Record<string, string>;
13
+ devDependencies?: Record<string, string>;
14
+ peerDependencies?: Record<string, string>;
15
+ }
16
+ export interface IEdit {
17
+ start: number;
18
+ end: number;
19
+ text: string;
20
+ }
21
+ /** Apply non-overlapping source edits, preserving everything around them. */
22
+ export declare const editText: (code: string, edits: IEdit[]) => string;
23
+ /** Infer the small formatting choices needed for inserted code. */
24
+ export declare const format: (code: string) => {
25
+ newline: string;
26
+ quote: string;
27
+ semicolon: string;
28
+ indent: string;
29
+ };
30
+ export declare const readPackage: (file: string) => IPackage;
31
+ /** Works in the source checkout and in the published cli/ directory. */
32
+ export declare const libraryPackage: () => IPackage;
33
+ export declare const objectProperty: (object: ObjectExpression, name: string) => Node | undefined;
34
+ export declare const stringValue: (node?: Node) => string | undefined;
35
+ /** Read a conventional Vite config without evaluating plugins or env files. */
36
+ export declare const readConfig: (root: string) => {
37
+ file: string;
38
+ code: string;
39
+ ast: import("@babel/types").File;
40
+ node: ObjectExpression;
41
+ viteRoot: string;
42
+ plugins: Node | undefined;
43
+ plugin: import("@babel/types").SpreadElement | import("@babel/types").Expression | null | undefined;
44
+ option: (name: string) => Node | undefined;
45
+ aliases: Alias[];
46
+ sources: SourceFiles;
47
+ };
48
+ /** HTML locations come from an HTML parser, so comments and attribute order are harmless. */
49
+ export declare const readHtml: (file: string) => {
50
+ code: string;
51
+ entries: DefaultTreeAdapterTypes.Element[];
52
+ roots: DefaultTreeAdapterTypes.Element[];
53
+ outlets: number;
54
+ attribute: (node: DefaultTreeAdapterTypes.Element, name: string) => string | undefined;
55
+ };
56
+ export type TProjectConfig = ReturnType<typeof readConfig>;
package/cli/project.js ADDED
@@ -0,0 +1,2 @@
1
+ import e from"node:fs";import t from"node:path";import o from"json5";import{parse as s}from"parse5";import i from"../constants/plugin-name.js";import r,{sourceError as n,unwrap as a,propertyName as l}from"../services/source-files.js";const p="https://lomray-software.github.io/vite-ssr-boost/guide/migrate-existing-spa",c=(e,t)=>[...t].sort((e,t)=>t.start-e.start).reduce((e,t)=>e.slice(0,t.start)+t.text+e.slice(t.end),e),f=e=>({newline:e.includes("\r\n")?"\r\n":"\n",quote:/(?:from\s+|import\s*)"/.test(e)?'"':"'",semicolon:/(?:from\s+['"][^'"]+['"]|\))\s*;/.test(e)?";":"",indent:e.match(/\n([\t ]+)\S/)?.[1]??" "}),m=t=>JSON.parse(e.readFileSync(t,"utf8")),u=()=>{const t=new URL("../package.json",import.meta.url);return m(e.existsSync(t)?t.pathname:new URL("../../package.json",import.meta.url).pathname)},d=(e,t)=>{const o=e.properties.find(e=>l(e)===t);return"ObjectProperty"===o?.type?a(o.value):void 0},g=e=>"StringLiteral"===e?.type?e.value:void 0,y=s=>{const p=["ts","js","mts","mjs","cts","cjs"].map(e=>t.join(s,`vite.config.${e}`)).filter(t=>e.existsSync(t));if(1!==p.length)throw n(t.join(s,"vite.config.*"),void 0,`Vite configs (${p.length}); expected exactly one`);const[c]=p,f=new r,{code:m,ast:u}=f.read(c);let{node:y}=f.exported(c);if("CallExpression"===y.type&&"Identifier"===y.callee.type&&"defineConfig"===f.import(c,y.callee.name)?.exported&&(y=a(y.arguments[0])),"ArrowFunctionExpression"===y?.type&&(y=a(y.body)),"ObjectExpression"!==y?.type)throw n(c,y,"Vite configuration; use defineConfig({ ... })");const v=d(y,"root");if(v&&"StringLiteral"!==v.type)throw n(c,v,"Vite root; use a string literal");const x=t.resolve(s,g(v)??"."),j=d(y,"plugins"),h="ArrayExpression"===j?.type?j.elements.find(e=>"CallExpression"===e?.type&&"Identifier"===e.callee.type&&f.import(c,e.callee.name)?.source.replace(/\.js$/,"")===`${i}/plugin`):void 0,b="CallExpression"===h?.type?a(h.arguments[0]):void 0;if(b&&"ObjectExpression"!==b.type)throw n(c,b,"SsrBoost options; use an object literal");const E=e=>"ObjectExpression"===b?.type?d(b,e):void 0,S=[],w=d(y,"resolve"),O="ObjectExpression"===w?.type?d(w,"alias"):void 0;if("ObjectExpression"===O?.type)for(const e of O.properties){if("ObjectProperty"!==e.type)continue;const o=l(e);let i=g(a(e.value));const r=a(e.value),n="CallExpression"===r?.type?r.arguments[0]:void 0;"NewExpression"===n?.type&&"Identifier"===n.callee.type&&"URL"===n.callee.name&&"StringLiteral"===n.arguments[0]?.type&&(i=t.resolve(s,n.arguments[0].value)),o&&i&&S.push({find:o,replacement:i})}const L=t.join(s,"tsconfig.json");if(e.existsSync(L)&&("BooleanLiteral"!==E("tsconfigAliases")?.type||!1!==Reflect.get(E("tsconfigAliases"),"value"))){const i=o.parse(e.readFileSync(L,"utf8")),r=t.resolve(s,i.compilerOptions?.baseUrl??t.relative(s,x));for(const[e,o]of Object.entries(i.compilerOptions?.paths??{}))S.push({find:e.replace(/\/\*$/,""),replacement:t.resolve(r,o[0].replace(/\/\*$/,""))})}return{file:c,code:m,ast:u,node:y,viteRoot:x,plugins:j,plugin:h,option:E,aliases:S,sources:f}},v=t=>{const o=e.readFileSync(t,"utf8"),i=s(o,{sourceCodeLocationInfo:!0}),r=[],n=o.split("\x3c!--ssr-outlet--\x3e").length-1,a=e=>{"tagName"in e&&r.push(e),"childNodes"in e&&e.childNodes.forEach(a)};a(i);const l=(e,t)=>e.attrs.find(e=>e.name===t)?.value;return{code:o,entries:r.filter(e=>"script"===e.tagName&&"module"===l(e,"type")),roots:r.filter(e=>"root"===l(e,"id")),outlets:n,attribute:l}};export{p as MANUAL_GUIDE,c as editText,f as format,u as libraryPackage,d as objectProperty,y as readConfig,v as readHtml,m as readPackage,g as stringValue};
2
+ //# sourceMappingURL=project.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project.js","sources":["../../src/cli/project.ts"],"sourcesContent":[null],"names":["MANUAL_GUIDE","editText","code","edits","sort","left","right","start","reduce","result","edit","slice","text","end","format","newline","includes","quote","test","semicolon","indent","match","readPackage","file","JSON","parse","fs","readFileSync","libraryPackage","published","URL","url","existsSync","pathname","objectProperty","object","name","property","properties","find","item","propertyName","type","unwrap","value","undefined","stringValue","node","readConfig","root","candidates","map","extension","path","join","filter","length","sourceError","sources","SourceFiles","ast","read","exported","callee","import","arguments","body","rootNode","viteRoot","resolve","plugins","plugin","elements","element","source","replace","PLUGIN_NAME","options","option","aliases","alias","replacement","push","tsconfig","Reflect","get","ts","JSON5","base","compilerOptions","baseUrl","relative","replacements","Object","entries","paths","readHtml","document","parseHtml","sourceCodeLocationInfo","outlets","split","visit","childNodes","forEach","attribute","attrs","attr","tagName","roots"],"mappings":"0OAUO,MAAMA,EACX,8EAkBWC,EAAW,CAACC,EAAcC,IACrC,IAAIA,GACDC,KAAK,CAACC,EAAMC,IAAUA,EAAMC,MAAQF,EA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EAASjB,OACtBR,GAA0B,WAAjBA,EAAK6D,SAAoD,WAA5BH,EAAU1D,EAAM,SAIjC8D,MAFVrC,EAASjB,OAAQR,GAAmC,SAA1B0D,EAAU1D,EAAM,OAEzBqD,UAASK"}
package/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as e}from"fs";import o from"chalk";import{Command as i,Option as n}from"commander";import t from"./cli/build.js";import r from"./cli/helpers/keyboard-input.js";import s from"./cli/helpers/vite-reset-cache.js";import d from"./cli/run-amplify-build.js";import a from"./cli/run-dev.js";import c from"./cli/run-docker-build.js";import l from"./cli/run-prod.js";import p from"./cli/run-vercel-build.js";import m from"./constants/cli-actions.js";import f from"./constants/cli-context.js";import u from"./constants/cli-name.js";const{description:O,version:w}=JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")),v=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",r).setEncoding("utf8").resume())},y=new i;y.name(u).description(O).version(w).hook("preAction",(e,o)=>{global.viteBoostAction=o.name()});const g=new n("--host","Ability to access the local instance on other devices under the same network.").default(!1),b=new n("--focus-only [focusOnly]","Build or Start only specified part of app.").default("app").choices(["all","app","client","server","entrypoint"]),h=new n("--port [port]","Server port.").default(3e3),k=new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production"),P=new n("--build-dir [buildDir]","Build directory output.");y.command(m.dev).description("Run development server.").addOption(g).addOption(h).addOption(new n("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new n("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).addOption(new n("--entrypoint [entrypoint]","Run only entrypoint by name.")).action(async({host:e,port:i,resetCache:n,mode:t,entrypoint:r})=>{n&&await s();const d=async n=>{console.info(o.cyan("Starting the development server..."));const{server:s,config:d}=await a({version:w,isHost:e,isPrintInfo:n,port:i,mode:t,entrypointName:r});f.server=s,f.config=d};return f.reboot=d,v(),d()}),y.command(m.build).description("Create production build.").addOption(b).addOption(k).addOption(new n("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new n("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).addOption(new n("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new n("--eject","Produces entrypoint file to run app without cli").default(!1)).addOption(new n("--serverless","Produces entrypoint file to run app like serverless function").default(!1)).addOption(new n("--throw-warnings","The build will abort with an error if warnings occur in the process.").default(!1)).action(async({focusOnly:e,clientOptions:o,serverOptions:i,mode:n,unlockRobots:r,eject:s,serverless:d,throwWarnings:a})=>{await t({focusOnly:e,isUnlockRobots:r,isNoWarnings:a,isEject:s,isServerless:d,clientOptions:o,serverOptions:i,mode:n})}),y.command(m.start).description("Run production server.").addOption(g).addOption(h).addOption(b).addOption(P).addOption(new n("--module-preload","Add module preload scripts to server output.").default(!1)).action(({host:e,port:o,focusOnly:i,modulePreload:n,buildDir:t})=>{const r=async r=>{const{server:s,config:d}=await l({version:w,isHost:e,isPrintInfo:r,port:o,focusOnly:i,modulePreload:n,buildDir:t});f.server=s,f.config=d};return f.reboot=r,v(),r()}),y.command(m.preview).description("Build and preview production.").addOption(b).addOption(g).addOption(h).addOption(k).addOption(P).action(async({host:e,port:i,focusOnly:n,mode:r,buildDir:s})=>{global.viteBoostStartTime=performance.now();const d=async t=>{const{server:r,config:d}=await l({version:w,isHost:e,isPrintInfo:t,port:i,focusOnly:n,buildDir:s});r.on("listening",()=>{setTimeout(()=>{d.getLogger().info(o.yellow("\n Running preview mode... \n"))},0)}),f.server=r,f.config=d};f.reboot=d,v();await t({mode:r,isWatch:!0,focusOnly:n,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{d()}})}),y.command(m.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new n("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new n("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(b).addOption(k).action(async({imageName:e,dockerOptions:o,dockerFile:i,focusOnly:n,mode:t})=>{await c({imageName:e,dockerOptions:o,dockerFile:i,focusOnly:n,mode:t})}),y.command(m.buildAmplify).description("Create AWS Amplify production build.").addOption(new n("--manifest-file [manifest-file]","Path to the Amplify manifest file (Default is PLUGIN_PATH/workflow/amplify-manifest.json).")).addOption(new n("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(k).action(async({manifestFile:e,mode:o,isOptimize:i})=>{await d({manifestFile:e,mode:o,isOptimize:i})}),y.command(m.buildVercel).description("Create Vercel serverless production build.").addOption(new n("--config-file [config-file]","Path to the Vercel config.json file (Default is PLUGIN_PATH/workflow/vercel.config.json).")).addOption(new n("--config-vc-file [config-vc-file]","Path to the Vercel vc-config.json file (Default is PLUGIN_PATH/workflow/vercel.vc-config.json).")).addOption(new n("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(k).action(async({configFile:e,configVcFile:o,mode:i,isOptimize:n})=>{await p({configFile:e,configVcFile:o,mode:i,isOptimize:n})}),y.parse();
2
+ import{readFileSync as o}from"fs";import e from"chalk";import{Command as i,Option as t}from"commander";import n from"./cli/build.js";import r from"./cli/doctor.js";import d from"./cli/helpers/keyboard-input.js";import s from"./cli/helpers/vite-reset-cache.js";import a from"./cli/init.js";import c from"./cli/run-amplify-build.js";import l from"./cli/run-dev.js";import p from"./cli/run-docker-build.js";import m from"./cli/run-prod.js";import f from"./cli/run-vercel-build.js";import u from"./constants/cli-actions.js";import O from"./constants/cli-context.js";import w from"./constants/cli-name.js";const{description:v,version:y}=JSON.parse(o(new URL("./package.json",import.meta.url),"utf8")),g=()=>{process.stdin.isTTY&&(process.stdin.setRawMode(!0),process.stdin.on("data",d).setEncoding("utf8").resume())},h=new i;h.name(w).description(v).version(y).hook("preAction",(o,e)=>{global.viteBoostAction=e.name()});const b=new t("--host","Ability to access the local instance on other devices under the same network.").default(!1),k=new t("--focus-only [focusOnly]","Build or Start only specified part of app.").default("app").choices(["all","app","client","server","entrypoint"]),j=new t("--port [port]","Server port.").default(3e3),P=new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("production"),D=new t("--build-dir [buildDir]","Build directory output.");h.command(u.dev).description("Run development server.").addOption(b).addOption(j).addOption(new t("--reset-cache","Clear vite cache before run.").default(!1)).addOption(new t("--mode [mode]","Env mode.").env("VITE_ENV_MODE").default("development")).addOption(new t("--entrypoint [entrypoint]","Run only entrypoint by name.")).action(async({host:o,port:i,resetCache:t,mode:n,entrypoint:r})=>{t&&await s();const d=async t=>{console.info(e.cyan("Starting the development server..."));const{server:d,config:s}=await l({version:y,isHost:o,isPrintInfo:t,port:i,mode:n,entrypointName:r});O.server=d,O.config=s};return O.reboot=d,g(),d()}),h.command(u.build).description("Create production build.").addOption(k).addOption(P).addOption(new t("--client-options [client-options]",'Pass vite build options for client. Example: --client-options="--ssrManifest"').env("VITE_BUILD_CLIENT_OPTIONS").default("")).addOption(new t("--server-options [server-options]","Pass vite build options for server.").env("VITE_BUILD_SERVER_OPTIONS").default("")).addOption(new t("--unlock-robots","Change general directive Disallow to Allow in robots.txt").default(!1)).addOption(new t("--eject","Produces entrypoint file to run app without cli").default(!1)).addOption(new t("--serverless","Produces entrypoint file to run app like serverless function").default(!1)).addOption(new t("--throw-warnings","The build will abort with an error if warnings occur in the process.").default(!1)).action(async({focusOnly:o,clientOptions:e,serverOptions:i,mode:t,unlockRobots:r,eject:d,serverless:s,throwWarnings:a})=>{await n({focusOnly:o,isUnlockRobots:r,isNoWarnings:a,isEject:d,isServerless:s,clientOptions:e,serverOptions:i,mode:t})}),h.command(u.start).description("Run production server.").addOption(b).addOption(j).addOption(k).addOption(D).addOption(new t("--module-preload","Add module preload scripts to server output.").default(!1)).action(({host:o,port:e,focusOnly:i,modulePreload:t,buildDir:n})=>{const r=async r=>{const{server:d,config:s}=await m({version:y,isHost:o,isPrintInfo:r,port:e,focusOnly:i,modulePreload:t,buildDir:n});O.server=d,O.config=s};return O.reboot=r,g(),r()}),h.command(u.preview).description("Build and preview production.").addOption(k).addOption(b).addOption(j).addOption(P).addOption(D).action(async({host:o,port:i,focusOnly:t,mode:r,buildDir:d})=>{global.viteBoostStartTime=performance.now();const s=async n=>{const{server:r,config:s}=await m({version:y,isHost:o,isPrintInfo:n,port:i,focusOnly:t,buildDir:d});r.on("listening",()=>{setTimeout(()=>{s.getLogger().info(e.yellow("\n Running preview mode... \n"))},0)}),O.server=r,O.config=s};O.reboot=s,g();await n({mode:r,isWatch:!0,focusOnly:t,clientOptions:"-w",serverOptions:"-w",onFinish:()=>{s()}})}),h.command(u.buildDocker).description("Create docker image with production build.").requiredOption("--image-name <image-name>","Docker image name.").addOption(new t("--docker-options [docker-options]","Extra docker options which pass to docker build command.")).addOption(new t("--docker-file [docker-file]","Name of the Dockerfile (Default is PLUGIN_PATH/workflow/Dockerfile).")).addOption(k).addOption(P).action(async({imageName:o,dockerOptions:e,dockerFile:i,focusOnly:t,mode:n})=>{await p({imageName:o,dockerOptions:e,dockerFile:i,focusOnly:t,mode:n})}),h.command(u.buildAmplify).description("Create AWS Amplify production build.").addOption(new t("--manifest-file [manifest-file]","Path to the Amplify manifest file (Default is PLUGIN_PATH/workflow/amplify-manifest.json).")).addOption(new t("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(P).action(async({manifestFile:o,mode:e,isOptimize:i})=>{await c({manifestFile:o,mode:e,isOptimize:i})}),h.command(u.buildVercel).description("Create Vercel serverless production build.").addOption(new t("--config-file [config-file]","Path to the Vercel config.json file (Default is PLUGIN_PATH/workflow/vercel.config.json).")).addOption(new t("--config-vc-file [config-vc-file]","Path to the Vercel vc-config.json file (Default is PLUGIN_PATH/workflow/vercel.vc-config.json).")).addOption(new t("--is-optimize","Optimize node_modules folder.").default(!1)).addOption(P).action(async({configFile:o,configVcFile:e,mode:i,isOptimize:t})=>{await f({configFile:o,configVcFile:e,mode:i,isOptimize:t})}),h.command("doctor").description("Inspect SSR setup and report actionable checks.").option("--json","Print machine-readable JSON.").option("--root <dir>","Project directory.").option("--bundle <file>","Write an allowlisted support bundle JSON.").action(r),h.command("init").description("Add SSR to an existing Vite + React Router app (dry run by default).").option("--dry-run","Print every change without writing files.").option("--apply","Write the proposed changes.").option("--root <dir>","Project directory.").option("--entry <file>","Browser entry relative to the project directory.").option("--routes <file>","Module exporting the route array.").action(a),h.parse();
3
3
  //# sourceMappingURL=cli.js.map