vite-plugin-kiru 0.31.0 → 0.32.0-preview.0

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/build.dev.ts CHANGED
@@ -3,13 +3,13 @@ import fs from "node:fs"
3
3
 
4
4
  await esbuild
5
5
  .context({
6
- entryPoints: ["src/index.ts"],
6
+ entryPoints: ["src/index.ts", "src/server.ts"],
7
7
  bundle: true,
8
8
  platform: "node",
9
9
  target: "esnext",
10
10
  format: "esm",
11
- outfile: "./dist/index.js",
12
- external: ["kiru", "vite"],
11
+ outdir: "./dist",
12
+ external: ["kiru", "vite", "virtual:kiru:entry-server"],
13
13
  write: true,
14
14
  plugins: [
15
15
  {
@@ -18,6 +18,7 @@ await esbuild
18
18
  onEnd(() => {
19
19
  console.log("[vite-plugin-kiru]: Build complete!")
20
20
  fs.copyFileSync("./src/types.d.ts", "dist/index.d.ts")
21
+ fs.copyFileSync("./src/types.server.d.ts", "dist/server.d.ts")
21
22
  })
22
23
  },
23
24
  },
package/dist/index.d.ts CHANGED
@@ -116,6 +116,11 @@ export interface SSGOptions {
116
116
  * @default "layout.{tsx,jsx}"
117
117
  */
118
118
  layout?: string
119
+ /**
120
+ * The filename of guard files to search for
121
+ * @default "guard.{ts,js}"
122
+ */
123
+ guard?: string
119
124
  /**
120
125
  * Enable transitions for all routes and loading states
121
126
  * @default false
@@ -133,6 +138,49 @@ export interface SSGOptions {
133
138
  build?: SSGBuildOptions
134
139
  }
135
140
 
141
+ export interface SSROptions {
142
+ /**
143
+ * The path to the server entry file
144
+ * @example "src/server.ts"
145
+ */
146
+ runtimeEntry: string
147
+ /**
148
+ * The base URL of the app
149
+ * @default "/"
150
+ */
151
+ baseUrl?: string
152
+ /**
153
+ * The directory of the app
154
+ * @default "src/pages"
155
+ */
156
+ dir?: string
157
+ /**
158
+ * The name of the document component
159
+ * @default "document.{tsx,jsx}"
160
+ */
161
+ document?: string
162
+ /**
163
+ * The filename of page components to search for
164
+ * @default "index.{tsx,jsx}"
165
+ */
166
+ page?: string
167
+ /**
168
+ * The filename of layout components to search for
169
+ * @default "layout.{tsx,jsx}"
170
+ */
171
+ layout?: string
172
+ /**
173
+ * The filename of guard files to search for
174
+ * @default "guard.{ts,js}"
175
+ */
176
+ guard?: string
177
+ /**
178
+ * Enable transitions for all routes and loading states
179
+ * @default false
180
+ */
181
+ transition?: boolean
182
+ }
183
+
136
184
  export interface DevtoolsOptions {
137
185
  /**
138
186
  * Specifies the path to the devtools app displayed via popup
@@ -193,6 +241,21 @@ export interface KiruPluginOptions {
193
241
  * ```
194
242
  */
195
243
  ssg?: SSGOptions | true
244
+
245
+ /**
246
+ * Options for SSR
247
+ * @example
248
+ * ```ts
249
+ * ssr: {
250
+ * dir: "./src/app",
251
+ * document: "document.{tsx,jsx}",
252
+ * page: "index.{tsx,jsx}",
253
+ * layout: "layout.{tsx,jsx}",
254
+ * transition: true
255
+ * }
256
+ * ```
257
+ */
258
+ ssr?: SSROptions
196
259
  }
197
260
 
198
261
  export const defaultEsBuildOptions: ESBuildOptions
package/dist/index.js CHANGED
@@ -8808,8 +8808,8 @@ function createLogger(state) {
8808
8808
  console.log(ANSI.cyan("[vite-plugin-kiru]"), ...data);
8809
8809
  };
8810
8810
  }
8811
- function resolveUserDocument(projectRoot, ssgOptions) {
8812
- const { dir, document } = ssgOptions;
8811
+ function resolveUserDocument(projectRoot, options) {
8812
+ const { dir, document } = options;
8813
8813
  const fp = path2.resolve(projectRoot, dir, document).replace(/\\/g, "/");
8814
8814
  const matches = globSync(fp);
8815
8815
  if (!matches.length) {
@@ -8840,57 +8840,79 @@ function shouldTransformFile(id, state) {
8840
8840
  }
8841
8841
 
8842
8842
  // src/virtual-modules.ts
8843
- var VIRTUAL_ROUTES_ID = "virtual:kiru:routes";
8843
+ var VIRTUAL_CONFIG_ID = "virtual:kiru:config";
8844
8844
  var VIRTUAL_ENTRY_SERVER_ID = "virtual:kiru:entry-server";
8845
8845
  var VIRTUAL_ENTRY_CLIENT_ID = "virtual:kiru:entry-client";
8846
- async function createVirtualModules(projectRoot, ssgOptions) {
8847
- const userDoc = resolveUserDocument(projectRoot, ssgOptions);
8848
- function createRoutesModule() {
8849
- const { dir, baseUrl, page, layout, transition } = ssgOptions;
8846
+ async function createVirtualModules(projectRoot, options, mode) {
8847
+ const userDoc = resolveUserDocument(projectRoot, options);
8848
+ function createConfigModule() {
8849
+ const { dir, baseUrl, page, layout, guard, transition } = options;
8850
8850
  return `
8851
8851
  import { formatViteImportMap, normalizePrefixPath } from "kiru/router/utils"
8852
8852
 
8853
8853
  const dir = normalizePrefixPath("${dir}")
8854
8854
  const baseUrl = normalizePrefixPath("${baseUrl}")
8855
- const pagesMap = import.meta.glob(["/**/${page}"])
8856
- const layoutsMap = import.meta.glob(["/**/${layout}"])
8857
- const pages = formatViteImportMap(pagesMap, dir, baseUrl)
8858
- const layouts = formatViteImportMap(layoutsMap, dir, baseUrl)
8855
+ const pages = formatViteImportMap(import.meta.glob(["/**/${page}"]), dir, baseUrl)
8856
+ const layouts = formatViteImportMap(import.meta.glob(["/**/${layout}"]), dir, baseUrl)
8857
+ const guards = formatViteImportMap(import.meta.glob(["/**/${guard}"]), dir, baseUrl)
8859
8858
  const transition = ${transition}
8860
8859
 
8861
- export { dir, baseUrl, pages, layouts, transition }
8860
+ export { dir, baseUrl, pages, layouts, guards, transition }
8862
8861
  `;
8863
8862
  }
8864
8863
  function createEntryServerModule() {
8864
+ if (mode === "ssr") {
8865
+ return `
8866
+ import { render as kiruServerRender } from "kiru/router/ssr"
8867
+ import Document from "${userDoc}"
8868
+ import * as config from "${VIRTUAL_CONFIG_ID}"
8869
+
8870
+ export const documentModuleId = "${userDoc.substring(projectRoot.length)}"
8871
+
8872
+ export async function render(url, ctx) {
8873
+ return kiruServerRender(url, { ...ctx, ...config, Document })
8874
+ }
8875
+ `;
8876
+ }
8865
8877
  return `
8866
8878
  import {
8867
- render as kiruServerRender,
8868
- generateStaticPaths as kiruServerGenerateStaticPaths
8869
- } from "kiru/router/server"
8879
+ render as kiruStaticRender,
8880
+ generateStaticPaths as kiruGenerateStaticPaths
8881
+ } from "kiru/router/ssg"
8870
8882
  import Document from "${userDoc}"
8871
- import { pages, layouts } from "${VIRTUAL_ROUTES_ID}"
8883
+ import * as config from "${VIRTUAL_CONFIG_ID}"
8884
+
8885
+ export const documentModuleId = "${userDoc.substring(projectRoot.length)}"
8872
8886
 
8873
8887
  export async function render(url, ctx) {
8874
- const { registerModule, registerPreloadedPageProps } = ctx
8875
- return kiruServerRender(url, { registerModule, registerPreloadedPageProps, Document, pages, layouts })
8888
+ return kiruStaticRender(url, { ...ctx, ...config, Document })
8876
8889
  }
8877
8890
 
8878
8891
  export async function generateStaticPaths() {
8879
- return kiruServerGenerateStaticPaths(pages)
8892
+ return kiruGenerateStaticPaths(config.pages)
8880
8893
  }
8881
8894
  `;
8882
8895
  }
8883
8896
  function createEntryClientModule() {
8897
+ if (mode === "ssr") {
8898
+ return `
8899
+ import { initClient } from "kiru/router/client"
8900
+ import * as config from "${VIRTUAL_CONFIG_ID}"
8901
+ import "${userDoc}"
8902
+
8903
+ initClient({ ...config, hydrationMode: "dynamic" })
8904
+ `;
8905
+ }
8884
8906
  return `
8885
8907
  import { initClient } from "kiru/router/client"
8886
- import { dir, baseUrl, pages, layouts, transition } from "${VIRTUAL_ROUTES_ID}"
8908
+ import * as config from "${VIRTUAL_CONFIG_ID}"
8887
8909
  import "${userDoc}"
8888
8910
 
8889
- initClient({ dir, baseUrl, pages, layouts, transition })
8911
+ initClient({ ...config })
8890
8912
  `;
8891
8913
  }
8892
8914
  return {
8893
- [VIRTUAL_ROUTES_ID]: createRoutesModule,
8915
+ [VIRTUAL_CONFIG_ID]: createConfigModule,
8894
8916
  [VIRTUAL_ENTRY_SERVER_ID]: createEntryServerModule,
8895
8917
  [VIRTUAL_ENTRY_CLIENT_ID]: createEntryClientModule
8896
8918
  };
@@ -8911,11 +8933,21 @@ var defaultSSGOptions = {
8911
8933
  document: "document.{tsx,jsx}",
8912
8934
  page: "index.{tsx,jsx}",
8913
8935
  layout: "layout.{tsx,jsx}",
8936
+ guard: "guard.{ts,js}",
8914
8937
  transition: false,
8915
8938
  build: {
8916
8939
  maxConcurrentRenders: 100
8917
8940
  }
8918
8941
  };
8942
+ var defaultSSROptions = {
8943
+ baseUrl: "/",
8944
+ dir: "src/pages",
8945
+ document: "document.{tsx,jsx}",
8946
+ page: "index.{tsx,jsx}",
8947
+ layout: "layout.{tsx,jsx}",
8948
+ guard: "guard.{ts,js}",
8949
+ transition: false
8950
+ };
8919
8951
  function createPluginState(opts = {}) {
8920
8952
  let fileLinkFormatter = (path8, line) => `vscode://file/${path8}:${line}`;
8921
8953
  let dtClientPathname = "/__devtools__";
@@ -8936,47 +8968,78 @@ function createPluginState(opts = {}) {
8936
8968
  dtHostScriptPath: "/__devtools_host__.js",
8937
8969
  manifestPath: "vite-manifest.json",
8938
8970
  loggingEnabled: opts.loggingEnabled === true,
8939
- ssgOptions: null
8971
+ ssgOptions: null,
8972
+ ssrOptions: null
8940
8973
  };
8941
- const { ssg } = opts;
8942
- if (!ssg) return state;
8943
- if (ssg === true) {
8974
+ if (opts.ssg && opts.ssr) {
8975
+ throw new Error(
8976
+ "[vite-plugin-kiru]: Cannot enable both SSG and SSR modes simultaneously"
8977
+ );
8978
+ }
8979
+ const { ssg, ssr } = opts;
8980
+ if (ssg) {
8981
+ if (ssg === true) {
8982
+ return {
8983
+ ...state,
8984
+ ssgOptions: defaultSSGOptions
8985
+ };
8986
+ }
8987
+ if (ssg.baseUrl && !ssg.baseUrl.startsWith("/")) {
8988
+ throw new Error("[vite-plugin-kiru]: ssg.baseUrl must start with '/'");
8989
+ }
8990
+ const {
8991
+ baseUrl,
8992
+ dir,
8993
+ document,
8994
+ page,
8995
+ layout,
8996
+ guard,
8997
+ transition,
8998
+ build: { maxConcurrentRenders }
8999
+ } = defaultSSGOptions;
8944
9000
  return {
8945
9001
  ...state,
8946
- ssgOptions: defaultSSGOptions
9002
+ ssgOptions: {
9003
+ baseUrl,
9004
+ dir,
9005
+ document,
9006
+ page,
9007
+ layout,
9008
+ guard,
9009
+ transition,
9010
+ sitemap: ssg.sitemap,
9011
+ ...ssg,
9012
+ build: {
9013
+ maxConcurrentRenders: ssg.build?.maxConcurrentRenders ?? maxConcurrentRenders
9014
+ }
9015
+ }
8947
9016
  };
8948
9017
  }
8949
- if (ssg.baseUrl && !ssg.baseUrl.startsWith("/")) {
8950
- throw new Error("[vite-plugin-kiru]: ssg.baseUrl must start with '/'");
8951
- }
8952
- const {
8953
- baseUrl,
8954
- dir,
8955
- document,
8956
- page,
8957
- layout,
8958
- transition,
8959
- build: { maxConcurrentRenders }
8960
- } = defaultSSGOptions;
8961
- return {
8962
- ...state,
8963
- ssgOptions: {
8964
- ...ssg,
8965
- baseUrl: ssg.baseUrl ?? baseUrl,
8966
- dir: ssg.dir ?? dir,
8967
- document: ssg.document ?? document,
8968
- page: ssg.page ?? page,
8969
- layout: ssg.layout ?? layout,
8970
- transition: ssg.transition ?? transition,
8971
- sitemap: ssg.sitemap,
8972
- build: {
8973
- maxConcurrentRenders: ssg.build?.maxConcurrentRenders ?? maxConcurrentRenders
8974
- }
9018
+ if (ssr) {
9019
+ if (ssr.baseUrl && !ssr.baseUrl.startsWith("/")) {
9020
+ throw new Error("[vite-plugin-kiru]: ssr.baseUrl must start with '/'");
8975
9021
  }
8976
- };
9022
+ const { baseUrl, dir, document, page, layout, guard, transition } = defaultSSROptions;
9023
+ return {
9024
+ ...state,
9025
+ ssrOptions: {
9026
+ baseUrl,
9027
+ dir,
9028
+ document,
9029
+ page,
9030
+ layout,
9031
+ guard,
9032
+ transition,
9033
+ ...ssr
9034
+ }
9035
+ };
9036
+ }
9037
+ return state;
8977
9038
  }
8978
9039
  function createViteConfig(config, opts) {
8979
- if (!opts.ssg) {
9040
+ const hasSSG = !!opts.ssg;
9041
+ const hasSSR = !!opts.ssr;
9042
+ if (!hasSSG && !hasSSR) {
8980
9043
  return {
8981
9044
  ...config,
8982
9045
  esbuild: {
@@ -9046,6 +9109,7 @@ function updatePluginState(state, config, opts) {
9046
9109
  dtHostScriptPath: state.dtHostScriptPath,
9047
9110
  manifestPath: state.manifestPath,
9048
9111
  ssgOptions: state.ssgOptions,
9112
+ ssrOptions: state.ssrOptions,
9049
9113
  staticProps: {}
9050
9114
  };
9051
9115
  }
@@ -11274,7 +11338,7 @@ async function getClientAssets(clientOutDirAbs, manifestPath) {
11274
11338
  const clientManifestPath = path6.resolve(clientOutDirAbs, manifestPath);
11275
11339
  if (fs3.existsSync(clientManifestPath)) {
11276
11340
  const manifest = JSON.parse(fs3.readFileSync(clientManifestPath, "utf-8"));
11277
- const clientEntryKey = "virtual:kiru:entry-client";
11341
+ const clientEntryKey = VIRTUAL_ENTRY_CLIENT_ID;
11278
11342
  if (manifest[clientEntryKey]?.file) {
11279
11343
  clientEntry = manifest[clientEntryKey].file;
11280
11344
  }
@@ -11300,7 +11364,7 @@ function collectCssForModules(manifest, moduleIds, projectRoot) {
11300
11364
  (it.css || []).forEach((c) => cssFiles.add(c));
11301
11365
  (it.imports || []).forEach((imp) => collectCss(imp));
11302
11366
  };
11303
- const entryClientKey = "virtual:kiru:entry-client";
11367
+ const entryClientKey = VIRTUAL_ENTRY_CLIENT_ID;
11304
11368
  if (manifest[entryClientKey] && !seen.has(entryClientKey)) {
11305
11369
  collectCss(entryClientKey);
11306
11370
  }
@@ -11363,10 +11427,10 @@ async function renderRoute(state, mod, route, srcFilePath, clientEntry, manifest
11363
11427
  const documentModuleId = documentPath.replace(/\\/g, "/");
11364
11428
  moduleIds.push(documentModuleId);
11365
11429
  const ctx = {
11366
- registerModule: (moduleId) => {
11430
+ registerModule(moduleId) {
11367
11431
  moduleIds.push(moduleId);
11368
11432
  },
11369
- registerPreloadedPageProps: (props) => {
11433
+ registerStaticProps(props) {
11370
11434
  ;
11371
11435
  (state.staticProps[srcFilePath] ??= {})[route] = props;
11372
11436
  }
@@ -11519,7 +11583,7 @@ async function appendStaticPropsToClientModules(state, clientOutDirAbs, log) {
11519
11583
  Object.keys(manifest).length,
11520
11584
  "entries"
11521
11585
  );
11522
- const clientEntryChunk = manifest["virtual:kiru:entry-client"];
11586
+ const clientEntryChunk = manifest[VIRTUAL_ENTRY_CLIENT_ID];
11523
11587
  if (!clientEntryChunk) {
11524
11588
  throw new Error("Client entry chunk not found in manifest");
11525
11589
  }
@@ -11548,6 +11612,21 @@ ${code}`, "utf-8");
11548
11612
 
11549
11613
  // src/index.ts
11550
11614
  import { build } from "vite";
11615
+
11616
+ // src/globals.ts
11617
+ var VITE_DEV_SERVER_INSTANCE = {
11618
+ get current() {
11619
+ return (
11620
+ // @ts-ignore
11621
+ globalThis.KIRU_VITE_DEV_SERVER_INSTANCE ?? null
11622
+ );
11623
+ },
11624
+ set current(server) {
11625
+ globalThis.KIRU_VITE_DEV_SERVER_INSTANCE = server;
11626
+ }
11627
+ };
11628
+
11629
+ // src/index.ts
11551
11630
  function kiru(opts = {}) {
11552
11631
  let state;
11553
11632
  let log;
@@ -11563,10 +11642,17 @@ function kiru(opts = {}) {
11563
11642
  const initialState = createPluginState(opts);
11564
11643
  state = updatePluginState(initialState, config, opts);
11565
11644
  log = createLogger(state);
11566
- if (state.ssgOptions) {
11645
+ if (state.ssrOptions) {
11567
11646
  virtualModules = await createVirtualModules(
11568
11647
  state.projectRoot,
11569
- state.ssgOptions
11648
+ state.ssrOptions,
11649
+ "ssr"
11650
+ );
11651
+ } else if (state.ssgOptions) {
11652
+ virtualModules = await createVirtualModules(
11653
+ state.projectRoot,
11654
+ state.ssgOptions,
11655
+ "ssg"
11570
11656
  );
11571
11657
  }
11572
11658
  },
@@ -11584,6 +11670,7 @@ function kiru(opts = {}) {
11584
11670
  );
11585
11671
  },
11586
11672
  configureServer(server) {
11673
+ VITE_DEV_SERVER_INSTANCE.current = server;
11587
11674
  if (state.isProduction || state.isBuild) return;
11588
11675
  const {
11589
11676
  ssgOptions,
@@ -11607,26 +11694,34 @@ function kiru(opts = {}) {
11607
11694
  const url = req.originalUrl || req.url || "/";
11608
11695
  const filePath = path7.join(state.baseOutDir, "client", url);
11609
11696
  const extName = path7.extname(filePath);
11610
- if (extName && extName !== ".html") {
11611
- return next();
11612
- }
11613
11697
  const accept = req.headers["accept"] || "";
11614
- if (typeof accept === "string" && accept.includes("text/html") && !url.startsWith("/node_modules/") && !url.startsWith("/@") && !url.startsWith(dtHostScriptPath) && !url.startsWith(dtClientPathname)) {
11615
- const { status, html } = await handleSSR(
11616
- server,
11617
- url,
11618
- state.projectRoot,
11619
- () => resolveUserDocument(projectRoot, ssgOptions)
11620
- );
11621
- res.statusCode = status;
11622
- res.setHeader("Content-Type", "text/html");
11623
- res.end(html);
11624
- return;
11698
+ const shouldHandle = typeof accept === "string" && accept.includes("text/html") && !url.startsWith("/node_modules/") && !url.startsWith("/@") && !url.startsWith(dtHostScriptPath) && !url.startsWith(dtClientPathname) && (extName === ".html" || !extName);
11699
+ if (!shouldHandle) {
11700
+ return next();
11625
11701
  }
11702
+ const { status, html } = await handleSSR(
11703
+ server,
11704
+ url,
11705
+ state.projectRoot,
11706
+ () => resolveUserDocument(projectRoot, ssgOptions)
11707
+ );
11708
+ res.statusCode = status;
11709
+ res.setHeader("Content-Type", "text/html");
11710
+ res.end(html);
11626
11711
  } catch (e) {
11627
- console.error(e);
11712
+ const error = e;
11713
+ console.error(
11714
+ ANSI.red("[SSG] Middleware Error"),
11715
+ `
11716
+ ${ANSI.yellow("URL:")} ${req.url}`,
11717
+ `
11718
+ ${ANSI.yellow("Error:")} ${error.message}`
11719
+ );
11720
+ if (error.stack) {
11721
+ console.error(ANSI.black_bright(error.stack));
11722
+ }
11723
+ next(e);
11628
11724
  }
11629
- next();
11630
11725
  });
11631
11726
  }
11632
11727
  },
@@ -11696,15 +11791,14 @@ function kiru(opts = {}) {
11696
11791
  };
11697
11792
  }
11698
11793
  };
11699
- return [
11700
- mainPlugin,
11701
- {
11794
+ const plugins = [mainPlugin];
11795
+ if (opts.ssg) {
11796
+ plugins.push({
11702
11797
  name: "vite-plugin-kiru:ssg",
11703
11798
  apply: "build",
11704
11799
  enforce: "post",
11705
11800
  async closeBundle(error) {
11706
- if (error || this.environment.config.build.ssr || !state.ssgOptions)
11707
- return;
11801
+ if (error || this.environment.config.build.ssr) return;
11708
11802
  log(ANSI.cyan("[SSG]"), "Starting SSG build...");
11709
11803
  await build({
11710
11804
  ...inlineConfig,
@@ -11716,8 +11810,35 @@ function kiru(opts = {}) {
11716
11810
  });
11717
11811
  log(ANSI.cyan("[SSG]"), "SSG build complete!");
11718
11812
  }
11719
- }
11720
- ];
11813
+ });
11814
+ } else if (opts.ssr) {
11815
+ plugins.push({
11816
+ name: "vite-plugin-kiru:ssr",
11817
+ apply: "build",
11818
+ enforce: "post",
11819
+ async closeBundle(error) {
11820
+ if (error || this.environment.config.build.ssr || !state.ssrOptions)
11821
+ return;
11822
+ log(ANSI.cyan("[SSR]"), "Starting SSR build...");
11823
+ await build({
11824
+ ...inlineConfig,
11825
+ configFile: false,
11826
+ build: {
11827
+ ...inlineConfig?.build,
11828
+ ssr: true,
11829
+ rollupOptions: {
11830
+ input: path7.resolve(
11831
+ state.projectRoot,
11832
+ state.ssrOptions.runtimeEntry
11833
+ )
11834
+ }
11835
+ }
11836
+ });
11837
+ log(ANSI.cyan("[SSR]"), "SSR build complete!");
11838
+ }
11839
+ });
11840
+ }
11841
+ return plugins;
11721
11842
  }
11722
11843
  function onHMR(callback) {
11723
11844
  }
package/dist/server.d.ts CHANGED
@@ -1,10 +1,8 @@
1
- import type { Readable } from "node:stream"
2
-
3
1
  export interface SSRHttpResponse {
4
2
  html: string
5
3
  statusCode: number
6
4
  headers: Array<[string, string]>
7
- stream: Readable
5
+ stream: ReadableStream | null
8
6
  }
9
7
 
10
8
  export interface SSRRenderResult {
@@ -13,6 +11,7 @@ export interface SSRRenderResult {
13
11
 
14
12
  export interface ServerRenderOptions {
15
13
  url: string
14
+ context: Kiru.RequestContext
16
15
  }
17
16
 
18
17
  export declare function renderPage(
package/dist/server.js CHANGED
@@ -1,9 +1,6 @@
1
1
  // src/server.ts
2
- import path3 from "node:path";
3
- import fs from "node:fs";
4
-
5
- // src/utils.ts
6
2
  import path2 from "node:path";
3
+ import fs from "node:fs";
7
4
 
8
5
  // ../../node_modules/.pnpm/@isaacs+balanced-match@4.0.1/node_modules/@isaacs/balanced-match/dist/esm/index.js
9
6
  var balanced = (a, b, str) => {
@@ -1557,7 +1554,7 @@ minimatch.Minimatch = Minimatch;
1557
1554
  minimatch.escape = escape;
1558
1555
  minimatch.unescape = unescape;
1559
1556
 
1560
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/glob.js
1557
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/glob.js
1561
1558
  import { fileURLToPath as fileURLToPath2 } from "node:url";
1562
1559
 
1563
1560
  // ../../node_modules/.pnpm/lru-cache@11.2.2/node_modules/lru-cache/dist/esm/index.js
@@ -4111,12 +4108,12 @@ var PathBase = class {
4111
4108
  /**
4112
4109
  * Get the Path object referenced by the string path, resolved from this Path
4113
4110
  */
4114
- resolve(path4) {
4115
- if (!path4) {
4111
+ resolve(path3) {
4112
+ if (!path3) {
4116
4113
  return this;
4117
4114
  }
4118
- const rootPath = this.getRootString(path4);
4119
- const dir = path4.substring(rootPath.length);
4115
+ const rootPath = this.getRootString(path3);
4116
+ const dir = path3.substring(rootPath.length);
4120
4117
  const dirParts = dir.split(this.splitSep);
4121
4118
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
4122
4119
  return result;
@@ -4868,8 +4865,8 @@ var PathWin32 = class _PathWin32 extends PathBase {
4868
4865
  /**
4869
4866
  * @internal
4870
4867
  */
4871
- getRootString(path4) {
4872
- return win32.parse(path4).root;
4868
+ getRootString(path3) {
4869
+ return win32.parse(path3).root;
4873
4870
  }
4874
4871
  /**
4875
4872
  * @internal
@@ -4915,8 +4912,8 @@ var PathPosix = class _PathPosix extends PathBase {
4915
4912
  /**
4916
4913
  * @internal
4917
4914
  */
4918
- getRootString(path4) {
4919
- return path4.startsWith("/") ? "/" : "";
4915
+ getRootString(path3) {
4916
+ return path3.startsWith("/") ? "/" : "";
4920
4917
  }
4921
4918
  /**
4922
4919
  * @internal
@@ -5005,11 +5002,11 @@ var PathScurryBase = class {
5005
5002
  /**
5006
5003
  * Get the depth of a provided path, string, or the cwd
5007
5004
  */
5008
- depth(path4 = this.cwd) {
5009
- if (typeof path4 === "string") {
5010
- path4 = this.cwd.resolve(path4);
5005
+ depth(path3 = this.cwd) {
5006
+ if (typeof path3 === "string") {
5007
+ path3 = this.cwd.resolve(path3);
5011
5008
  }
5012
- return path4.depth();
5009
+ return path3.depth();
5013
5010
  }
5014
5011
  /**
5015
5012
  * Return the cache of child entries. Exposed so subclasses can create
@@ -5496,9 +5493,9 @@ var PathScurryBase = class {
5496
5493
  process2();
5497
5494
  return results;
5498
5495
  }
5499
- chdir(path4 = this.cwd) {
5496
+ chdir(path3 = this.cwd) {
5500
5497
  const oldCwd = this.cwd;
5501
- this.cwd = typeof path4 === "string" ? this.cwd.resolve(path4) : path4;
5498
+ this.cwd = typeof path3 === "string" ? this.cwd.resolve(path3) : path3;
5502
5499
  this.cwd[setAsCwd](oldCwd);
5503
5500
  }
5504
5501
  };
@@ -5572,7 +5569,7 @@ var PathScurryDarwin = class extends PathScurryPosix {
5572
5569
  var Path = process.platform === "win32" ? PathWin32 : PathPosix;
5573
5570
  var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
5574
5571
 
5575
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/pattern.js
5572
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/pattern.js
5576
5573
  var isPatternList = (pl) => pl.length >= 1;
5577
5574
  var isGlobList = (gl) => gl.length >= 1;
5578
5575
  var Pattern = class _Pattern {
@@ -5737,7 +5734,7 @@ var Pattern = class _Pattern {
5737
5734
  }
5738
5735
  };
5739
5736
 
5740
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/ignore.js
5737
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/ignore.js
5741
5738
  var defaultPlatform2 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
5742
5739
  var Ignore = class {
5743
5740
  relative;
@@ -5824,7 +5821,7 @@ var Ignore = class {
5824
5821
  }
5825
5822
  };
5826
5823
 
5827
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/processor.js
5824
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/processor.js
5828
5825
  var HasWalkedCache = class _HasWalkedCache {
5829
5826
  store;
5830
5827
  constructor(store = /* @__PURE__ */ new Map()) {
@@ -5854,8 +5851,8 @@ var MatchRecord = class {
5854
5851
  }
5855
5852
  // match, absolute, ifdir
5856
5853
  entries() {
5857
- return [...this.store.entries()].map(([path4, n]) => [
5858
- path4,
5854
+ return [...this.store.entries()].map(([path3, n]) => [
5855
+ path3,
5859
5856
  !!(n & 2),
5860
5857
  !!(n & 1)
5861
5858
  ]);
@@ -6045,7 +6042,7 @@ var Processor = class _Processor {
6045
6042
  }
6046
6043
  };
6047
6044
 
6048
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/walker.js
6045
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/walker.js
6049
6046
  var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
6050
6047
  var GlobUtil = class {
6051
6048
  path;
@@ -6060,9 +6057,9 @@ var GlobUtil = class {
6060
6057
  signal;
6061
6058
  maxDepth;
6062
6059
  includeChildMatches;
6063
- constructor(patterns, path4, opts) {
6060
+ constructor(patterns, path3, opts) {
6064
6061
  this.patterns = patterns;
6065
- this.path = path4;
6062
+ this.path = path3;
6066
6063
  this.opts = opts;
6067
6064
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
6068
6065
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -6081,11 +6078,11 @@ var GlobUtil = class {
6081
6078
  });
6082
6079
  }
6083
6080
  }
6084
- #ignored(path4) {
6085
- return this.seen.has(path4) || !!this.#ignore?.ignored?.(path4);
6081
+ #ignored(path3) {
6082
+ return this.seen.has(path3) || !!this.#ignore?.ignored?.(path3);
6086
6083
  }
6087
- #childrenIgnored(path4) {
6088
- return !!this.#ignore?.childrenIgnored?.(path4);
6084
+ #childrenIgnored(path3) {
6085
+ return !!this.#ignore?.childrenIgnored?.(path3);
6089
6086
  }
6090
6087
  // backpressure mechanism
6091
6088
  pause() {
@@ -6300,8 +6297,8 @@ var GlobUtil = class {
6300
6297
  };
6301
6298
  var GlobWalker = class extends GlobUtil {
6302
6299
  matches = /* @__PURE__ */ new Set();
6303
- constructor(patterns, path4, opts) {
6304
- super(patterns, path4, opts);
6300
+ constructor(patterns, path3, opts) {
6301
+ super(patterns, path3, opts);
6305
6302
  }
6306
6303
  matchEmit(e) {
6307
6304
  this.matches.add(e);
@@ -6338,8 +6335,8 @@ var GlobWalker = class extends GlobUtil {
6338
6335
  };
6339
6336
  var GlobStream = class extends GlobUtil {
6340
6337
  results;
6341
- constructor(patterns, path4, opts) {
6342
- super(patterns, path4, opts);
6338
+ constructor(patterns, path3, opts) {
6339
+ super(patterns, path3, opts);
6343
6340
  this.results = new Minipass({
6344
6341
  signal: this.signal,
6345
6342
  objectMode: true
@@ -6372,7 +6369,7 @@ var GlobStream = class extends GlobUtil {
6372
6369
  }
6373
6370
  };
6374
6371
 
6375
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/glob.js
6372
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/glob.js
6376
6373
  var defaultPlatform3 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
6377
6374
  var Glob = class {
6378
6375
  absolute;
@@ -6572,7 +6569,7 @@ var Glob = class {
6572
6569
  }
6573
6570
  };
6574
6571
 
6575
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/has-magic.js
6572
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/has-magic.js
6576
6573
  var hasMagic = (pattern, options = {}) => {
6577
6574
  if (!Array.isArray(pattern)) {
6578
6575
  pattern = [pattern];
@@ -6584,7 +6581,7 @@ var hasMagic = (pattern, options = {}) => {
6584
6581
  return false;
6585
6582
  };
6586
6583
 
6587
- // ../../node_modules/.pnpm/glob@11.0.3/node_modules/glob/dist/esm/index.js
6584
+ // ../../node_modules/.pnpm/glob@12.0.0/node_modules/glob/dist/esm/index.js
6588
6585
  function globStreamSync(pattern, options = {}) {
6589
6586
  return new Glob(pattern, options).streamSync();
6590
6587
  }
@@ -6660,17 +6657,6 @@ function tEntries(obj) {
6660
6657
  return Object.entries(obj);
6661
6658
  }
6662
6659
 
6663
- // src/utils.ts
6664
- function resolveUserDocument(projectRoot, options) {
6665
- const { dir, document } = options;
6666
- const fp = path2.resolve(projectRoot, dir, document).replace(/\\/g, "/");
6667
- const matches = globSync(fp);
6668
- if (!matches.length) {
6669
- throw new Error(`Document not found at ${fp}`);
6670
- }
6671
- return path2.resolve(projectRoot, matches[0]).replace(/\\/g, "/");
6672
- }
6673
-
6674
6660
  // src/virtual-modules.ts
6675
6661
  var VIRTUAL_ENTRY_CLIENT_ID = "virtual:kiru:entry-client";
6676
6662
 
@@ -6692,15 +6678,14 @@ async function getClientAssets(clientOutDirAbs, manifestPath) {
6692
6678
  let clientEntry = null;
6693
6679
  let manifest = null;
6694
6680
  try {
6695
- const clientManifestPath = path3.resolve(clientOutDirAbs, manifestPath);
6681
+ const clientManifestPath = path2.resolve(clientOutDirAbs, manifestPath);
6696
6682
  if (fs.existsSync(clientManifestPath)) {
6697
6683
  const parsedManifest = JSON.parse(
6698
6684
  fs.readFileSync(clientManifestPath, "utf-8")
6699
6685
  );
6700
6686
  manifest = parsedManifest;
6701
- const clientEntryKey = "virtual:kiru:entry-client";
6702
- if (parsedManifest[clientEntryKey]?.file) {
6703
- clientEntry = parsedManifest[clientEntryKey].file;
6687
+ if (parsedManifest[VIRTUAL_ENTRY_CLIENT_ID]?.file) {
6688
+ clientEntry = parsedManifest[VIRTUAL_ENTRY_CLIENT_ID].file;
6704
6689
  }
6705
6690
  }
6706
6691
  } catch {
@@ -6723,7 +6708,7 @@ function collectCssForModules(manifest, moduleIds, projectRoot) {
6723
6708
  (it.css || []).forEach((c) => cssFiles.add(c));
6724
6709
  (it.imports || []).forEach((imp) => collectCss(imp));
6725
6710
  };
6726
- const entryClientKey = "virtual:kiru:entry-client";
6711
+ const entryClientKey = VIRTUAL_ENTRY_CLIENT_ID;
6727
6712
  if (manifestRef[entryClientKey] && !seen.has(entryClientKey)) {
6728
6713
  collectCss(entryClientKey);
6729
6714
  }
@@ -6749,8 +6734,8 @@ function collectCssForModules(manifest, moduleIds, projectRoot) {
6749
6734
  }
6750
6735
  for (const key in manifestRef) {
6751
6736
  const keyNormalized = key.replace(/\\/g, "/");
6752
- const moduleBaseName = path3.basename(normalizedId);
6753
- const keyBaseName = path3.basename(keyNormalized);
6737
+ const moduleBaseName = path2.basename(normalizedId);
6738
+ const keyBaseName = path2.basename(keyNormalized);
6754
6739
  if ((keyNormalized.endsWith(normalizedId) || normalizedId.endsWith(keyNormalized)) && moduleBaseName === keyBaseName) {
6755
6740
  collectCss(key);
6756
6741
  break;
@@ -6764,16 +6749,12 @@ function collectCssForModules(manifest, moduleIds, projectRoot) {
6764
6749
  return "";
6765
6750
  }
6766
6751
  async function renderPage(options) {
6767
- const { render } = await import("virtual:kiru:entry-server");
6768
- const moduleIds = [];
6752
+ const { render, documentModuleId } = await import("virtual:kiru:entry-server");
6753
+ const moduleIds = [documentModuleId];
6769
6754
  const projectRoot = process.cwd().replace(/\\/g, "/");
6770
- const documentModule = resolveUserDocument(projectRoot, {
6771
- dir: "src/pages",
6772
- document: "document.tsx"
6773
- }).substring(projectRoot.length);
6774
- moduleIds.push(documentModule);
6775
6755
  const { httpResponse } = await render(options.url, {
6776
- registerModule: (moduleId) => {
6756
+ userContext: options.context,
6757
+ registerModule(moduleId) {
6777
6758
  moduleIds.push(moduleId);
6778
6759
  }
6779
6760
  });
@@ -6785,7 +6766,7 @@ async function renderPage(options) {
6785
6766
  const isDevelopment = process.env.NODE_ENV !== "production";
6786
6767
  let html = httpResponse.html;
6787
6768
  if (isDevelopment) {
6788
- const scriptTag = `<script type="module" src="/@id/${VIRTUAL_ENTRY_CLIENT_ID}"></script>`;
6769
+ const scriptTag = `<script type="module" src="/@id/${VIRTUAL_ENTRY_CLIENT_ID}" async></script>`;
6789
6770
  html = html.includes("</body>") ? html.replace("</body>", scriptTag + "</body>") : html + scriptTag;
6790
6771
  const importedModules = /* @__PURE__ */ new Set();
6791
6772
  const seen = /* @__PURE__ */ new Set();
@@ -6799,7 +6780,7 @@ async function renderPage(options) {
6799
6780
  }
6800
6781
  };
6801
6782
  for (const id of moduleIds) {
6802
- const p = path3.join(projectRoot, id).replace(/\\/g, "/");
6783
+ const p = path2.join(projectRoot, id).replace(/\\/g, "/");
6803
6784
  const mod = VITE_DEV_SERVER_INSTANCE.current.moduleGraph.getModuleById(p);
6804
6785
  if (!mod) {
6805
6786
  console.error(`Module not found: ${p}`);
@@ -6819,7 +6800,7 @@ async function renderPage(options) {
6819
6800
  html = html.replace("<head>", "<head>" + stylesheets.join("\n"));
6820
6801
  }
6821
6802
  } else {
6822
- const clientOutDirAbs = path3.resolve(projectRoot, "dist/client");
6803
+ const clientOutDirAbs = path2.resolve(projectRoot, "dist/client");
6823
6804
  const { clientEntry, manifest } = await getClientAssets(
6824
6805
  clientOutDirAbs,
6825
6806
  "vite-manifest.json"
@@ -6831,10 +6812,15 @@ async function renderPage(options) {
6831
6812
  }
6832
6813
  }
6833
6814
  if (clientEntry) {
6834
- const scriptTag = `<script type="module" src="/${clientEntry}"></script>`;
6815
+ const scriptTag = `<script type="module" src="/${clientEntry}" async></script>`;
6835
6816
  html = html.includes("</body>") ? html.replace("</body>", scriptTag + "</body>") : html + scriptTag;
6836
6817
  }
6837
6818
  }
6819
+ const contextString = JSON.stringify(options.context);
6820
+ html = html.replace(
6821
+ "</head>",
6822
+ `<script type="application/json" k-request-context>${contextString}</script></head>`
6823
+ );
6838
6824
  return {
6839
6825
  httpResponse: {
6840
6826
  ...httpResponse,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-plugin-kiru",
3
- "version": "0.31.0",
3
+ "version": "0.32.0-preview.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -8,8 +8,18 @@
8
8
  "keywords": [],
9
9
  "author": "",
10
10
  "license": "ISC",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./server": {
17
+ "types": "./dist/server.d.ts",
18
+ "default": "./dist/server.js"
19
+ }
20
+ },
11
21
  "peerDependencies": {
12
- "kiru": ">=0.53.0"
22
+ "kiru": ">=0.54.0-preview.0"
13
23
  },
14
24
  "devDependencies": {
15
25
  "@types/node": "^22.17.0",
@@ -17,8 +27,9 @@
17
27
  "rollup": "^4.46.2",
18
28
  "tsx": "^4.20.3",
19
29
  "typescript": "^5.9.2",
30
+ "kiru-devtools-client": "^0.0.0",
20
31
  "kiru-devtools-host": "^1.0.0",
21
- "kiru-devtools-client": "^0.0.0"
32
+ "kiru": "^0.54.0-preview.0"
22
33
  },
23
34
  "dependencies": {
24
35
  "glob": "^12.0.0",