@analogjs/vite-plugin-nitro 3.0.0-alpha.3 → 3.0.0-alpha.30

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 (53) hide show
  1. package/package.json +25 -10
  2. package/src/index.d.ts +11 -9
  3. package/src/index.js +7 -2
  4. package/src/index.js.map +1 -1
  5. package/src/lib/build-server.d.ts +2 -2
  6. package/src/lib/build-server.js +101 -119
  7. package/src/lib/build-server.js.map +1 -1
  8. package/src/lib/build-sitemap.d.ts +9 -9
  9. package/src/lib/build-sitemap.js +130 -63
  10. package/src/lib/build-sitemap.js.map +1 -1
  11. package/src/lib/build-ssr.d.ts +3 -2
  12. package/src/lib/build-ssr.js +26 -18
  13. package/src/lib/build-ssr.js.map +1 -1
  14. package/src/lib/hooks/post-rendering-hook.d.ts +1 -1
  15. package/src/lib/hooks/post-rendering-hook.js +10 -6
  16. package/src/lib/hooks/post-rendering-hook.js.map +1 -1
  17. package/src/lib/options.d.ts +132 -106
  18. package/src/lib/plugins/dev-server-plugin.d.ts +3 -3
  19. package/src/lib/plugins/dev-server-plugin.js +91 -101
  20. package/src/lib/plugins/dev-server-plugin.js.map +1 -1
  21. package/src/lib/plugins/page-endpoints.d.ts +5 -5
  22. package/src/lib/plugins/page-endpoints.js +26 -57
  23. package/src/lib/plugins/page-endpoints.js.map +1 -1
  24. package/src/lib/utils/debug.d.ts +5 -0
  25. package/src/lib/utils/debug.js +15 -0
  26. package/src/lib/utils/debug.js.map +1 -0
  27. package/src/lib/utils/get-content-files.d.ts +54 -54
  28. package/src/lib/utils/get-content-files.js +88 -97
  29. package/src/lib/utils/get-content-files.js.map +1 -1
  30. package/src/lib/utils/get-page-handlers.d.ts +58 -58
  31. package/src/lib/utils/get-page-handlers.js +70 -84
  32. package/src/lib/utils/get-page-handlers.js.map +1 -1
  33. package/src/lib/utils/load-esm.d.ts +18 -18
  34. package/src/lib/utils/node-web-bridge.d.ts +1 -1
  35. package/src/lib/utils/node-web-bridge.js +50 -45
  36. package/src/lib/utils/node-web-bridge.js.map +1 -1
  37. package/src/lib/utils/register-dev-middleware.d.ts +12 -12
  38. package/src/lib/utils/register-dev-middleware.js +41 -47
  39. package/src/lib/utils/register-dev-middleware.js.map +1 -1
  40. package/src/lib/utils/renderers.d.ts +47 -47
  41. package/src/lib/utils/renderers.js +57 -56
  42. package/src/lib/utils/renderers.js.map +1 -1
  43. package/src/lib/utils/rolldown.d.ts +2 -0
  44. package/src/lib/utils/rolldown.js +12 -0
  45. package/src/lib/utils/rolldown.js.map +1 -0
  46. package/src/lib/vite-plugin-nitro.d.ts +3 -3
  47. package/src/lib/vite-plugin-nitro.js +728 -677
  48. package/src/lib/vite-plugin-nitro.js.map +1 -1
  49. package/README.md +0 -125
  50. package/src/lib/options.js +0 -2
  51. package/src/lib/options.js.map +0 -1
  52. package/src/lib/utils/load-esm.js +0 -23
  53. package/src/lib/utils/load-esm.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"build-sitemap.js","sourceRoot":"","sources":["../../../../../packages/vite-plugin-nitro/src/lib/build-sitemap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAExC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAcpC,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,MAAkB,EAClB,aAA4B,EAC5B,MAAwE,EACxE,SAAiB,EACjB,aAGC;IAED,MAAM,SAAS,GAAa,MAAM,eAAe,CAAC,MAAM,CAAC,CAAC;IAE1D,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,UAAU,CAAC,aAAa,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;QACnD,MAAM,WAAW,GAAgB,SAAS,CAAC,GAAG,CAAC,CAAC,IAAY,EAAE,EAAE;YAC9D,MAAM,GAAG,GAAG,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CAAa,CAAC;AAC/C,CAAC"}
1
+ {"version":3,"file":"build-sitemap.js","names":[],"sources":["../../../src/lib/build-sitemap.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { create } from 'xmlbuilder2';\nimport { XMLBuilder } from 'xmlbuilder2/lib/interfaces';\nimport { UserConfig } from 'vite';\nimport {\n PrerenderSitemapConfig,\n SitemapConfig,\n SitemapEntry,\n SitemapExcludeRule,\n SitemapRouteDefinition,\n SitemapRouteInput,\n SitemapRouteSource,\n} from './options';\n\ntype RouteSitemapConfig =\n | PrerenderSitemapConfig\n | (() => PrerenderSitemapConfig)\n | undefined;\n\nexport type PagesJson = SitemapEntry;\n\nexport interface BuildSitemapOptions {\n apiPrefix?: string;\n}\n\nexport async function buildSitemap(\n _config: UserConfig,\n sitemapConfig: SitemapConfig,\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n outputDir: string,\n routeSitemaps: Record<string, RouteSitemapConfig>,\n buildOptions: BuildSitemapOptions = {},\n): Promise<void> {\n const host = normalizeSitemapHost(sitemapConfig.host);\n const routeList = await collectSitemapRoutes(routes, sitemapConfig.include);\n const sitemapData = await resolveSitemapEntries(\n routeList,\n host,\n routeSitemaps,\n sitemapConfig,\n buildOptions,\n );\n\n if (!sitemapData.length) {\n return;\n }\n\n const sitemap = createXml('urlset');\n\n for (const item of sitemapData) {\n const page = sitemap.ele('url');\n page.ele('loc').txt(item.loc);\n\n if (item.lastmod) {\n page.ele('lastmod').txt(item.lastmod);\n }\n\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq);\n }\n\n if (item.priority !== undefined) {\n page.ele('priority').txt(String(item.priority));\n }\n }\n\n const resolvedOutputDir = resolve(outputDir);\n const mapPath = resolve(resolvedOutputDir, 'sitemap.xml');\n try {\n if (!resolvedOutputDir || resolvedOutputDir === resolve()) {\n throw new Error(\n 'Refusing to write the sitemap to the current working directory. Expected the Nitro public output directory instead.',\n );\n }\n\n if (!existsSync(resolvedOutputDir)) {\n mkdirSync(resolvedOutputDir, { recursive: true });\n }\n console.log(`Writing sitemap at ${mapPath}`);\n writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));\n } catch (e) {\n console.error(`Unable to write file at ${mapPath}`, e);\n }\n}\n\nasync function resolveSitemapEntries(\n routes: SitemapRouteInput[],\n host: string,\n routeSitemaps: Record<string, RouteSitemapConfig>,\n sitemapConfig: SitemapConfig,\n buildOptions: BuildSitemapOptions,\n): Promise<SitemapEntry[]> {\n const defaults = sitemapConfig.defaults ?? {};\n const seen = new Set<string>();\n const entries: SitemapEntry[] = [];\n\n for (const route of routes) {\n const entry = await toSitemapEntry(\n route,\n host,\n routeSitemaps,\n defaults,\n sitemapConfig.transform,\n );\n\n if (!entry) {\n continue;\n }\n\n if (\n isInternalSitemapRoute(entry.route, buildOptions.apiPrefix) ||\n (await isExcludedSitemapRoute(entry, sitemapConfig.exclude))\n ) {\n continue;\n }\n\n if (seen.has(entry.loc)) {\n continue;\n }\n\n seen.add(entry.loc);\n entries.push(entry);\n }\n\n return entries;\n}\n\nasync function toSitemapEntry(\n route: SitemapRouteInput,\n host: string,\n routeSitemaps: Record<string, RouteSitemapConfig>,\n defaults: PrerenderSitemapConfig,\n transform: SitemapConfig['transform'],\n): Promise<SitemapEntry | undefined> {\n const normalizedRoute = normalizeSitemapRoute(\n typeof route === 'string' ? route : route?.route,\n );\n if (!normalizedRoute) {\n return undefined;\n }\n\n const baseEntry = createSitemapEntry(\n {\n ...defaults,\n ...resolveRouteSitemapConfig(routeSitemaps[normalizedRoute]),\n ...(typeof route === 'object' ? route : {}),\n route: normalizedRoute,\n },\n host,\n );\n\n if (!transform) {\n return baseEntry;\n }\n\n const transformed = await transform(baseEntry);\n if (!transformed) {\n return undefined;\n }\n\n return createSitemapEntry(\n {\n ...baseEntry,\n ...transformed,\n },\n host,\n );\n}\n\nfunction createSitemapEntry(\n routeDefinition: SitemapRouteDefinition,\n host: string,\n): SitemapEntry {\n const route = normalizeSitemapRoute(routeDefinition.route) ?? '/';\n\n return {\n route,\n loc: new URL(route, ensureTrailingSlash(host)).toString(),\n lastmod: routeDefinition.lastmod,\n changefreq: routeDefinition.changefreq,\n priority: routeDefinition.priority,\n };\n}\n\nfunction resolveRouteSitemapConfig(\n config: RouteSitemapConfig,\n): PrerenderSitemapConfig {\n if (!config) {\n return {};\n }\n\n return typeof config === 'function' ? config() : config;\n}\n\nfunction normalizeSitemapHost(host: string): string {\n const resolvedHost = new URL(host);\n resolvedHost.hash = '';\n return resolvedHost.toString();\n}\n\nfunction ensureTrailingSlash(host: string): string {\n return host.endsWith('/') ? host : `${host}/`;\n}\n\nfunction normalizeSitemapRoute(route: string | undefined): string | undefined {\n if (!route) {\n return undefined;\n }\n\n const trimmedRoute = route.trim();\n if (!trimmedRoute) {\n return undefined;\n }\n\n const pathWithQuery = trimmedRoute.split('#', 1)[0] ?? '';\n const [pathname, search] = pathWithQuery.split('?', 2);\n const normalizedPathname = pathname\n ? `/${pathname.replace(/^\\/+/, '').replace(/\\/{2,}/g, '/')}`\n : '/';\n\n return search ? `${normalizedPathname}?${search}` : normalizedPathname;\n}\n\nfunction isInternalSitemapRoute(route: string, apiPrefix = 'api'): boolean {\n const normalizedApiPrefix = normalizeSitemapRoute(`/${apiPrefix}`) ?? '/api';\n return (\n route === `${normalizedApiPrefix}/_analog/pages` ||\n route.startsWith(`${normalizedApiPrefix}/_analog/pages/`)\n );\n}\n\nasync function isExcludedSitemapRoute(\n entry: SitemapEntry,\n excludeRules: SitemapExcludeRule[] | undefined,\n): Promise<boolean> {\n if (!excludeRules?.length) {\n return false;\n }\n\n for (const rule of excludeRules) {\n if (typeof rule === 'function') {\n if (await rule(entry)) {\n return true;\n }\n continue;\n }\n\n if (rule instanceof RegExp) {\n if (rule.test(entry.route)) {\n return true;\n }\n continue;\n }\n\n if (toGlobRegExp(rule).test(entry.route)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction toGlobRegExp(pattern: string): RegExp {\n const doubleStarToken = '__ANALOG_DOUBLE_STAR__';\n const singleStarToken = '__ANALOG_SINGLE_STAR__';\n const escapedPattern = pattern\n .replace(/\\*\\*/g, doubleStarToken)\n .replace(/\\*/g, singleStarToken)\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n const regexPattern = escapedPattern\n .replace(new RegExp(doubleStarToken, 'g'), '.*')\n .replace(new RegExp(singleStarToken, 'g'), '[^/]*');\n return new RegExp(`^${regexPattern}$`);\n}\n\nasync function collectSitemapRoutes(\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n include?: SitemapRouteSource,\n): Promise<SitemapRouteInput[]> {\n const routeList = await resolveRouteInputs(routes);\n const includedRoutes = include ? await resolveRouteInputs(include) : [];\n return [...routeList, ...includedRoutes];\n}\n\nasync function resolveRouteInputs(\n routes:\n | SitemapRouteSource\n | (string | undefined)[]\n | (() => Promise<(string | undefined)[]>),\n): Promise<SitemapRouteInput[]> {\n let routeList: SitemapRouteInput[];\n\n if (typeof routes === 'function') {\n routeList = await routes();\n } else if (Array.isArray(routes)) {\n routeList = routes;\n } else {\n routeList = [];\n }\n\n return routeList.filter(Boolean);\n}\n\nfunction createXml(elementName: 'urlset' | 'sitemapindex'): XMLBuilder {\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, {\n xmlns: 'https://www.sitemaps.org/schemas/sitemap/0.9',\n })\n .com(`This file was automatically generated by Analog.`);\n}\n"],"mappings":";;;;AA0BA,eAAsB,aACpB,SACA,eACA,QACA,WACA,eACA,eAAoC,EAAE,EACvB;CACf,MAAM,OAAO,qBAAqB,cAAc,KAAK;CAErD,MAAM,cAAc,MAAM,sBADR,MAAM,qBAAqB,QAAQ,cAAc,QAAQ,EAGzE,MACA,eACA,eACA,aACD;AAED,KAAI,CAAC,YAAY,OACf;CAGF,MAAM,UAAU,UAAU,SAAS;AAEnC,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,OAAO,QAAQ,IAAI,M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D,IAAI,mDAAmD"}
@@ -1,3 +1,4 @@
1
- import { UserConfig } from 'vite';
2
- import { Options } from './options.js';
1
+ import { UserConfig } from "vite";
2
+ import { Options } from "./options.js";
3
+ export declare function buildClientApp(config: UserConfig, options?: Options): Promise<void>;
3
4
  export declare function buildSSRApp(config: UserConfig, options?: Options): Promise<void>;
@@ -1,20 +1,28 @@
1
- import { build, mergeConfig } from 'vite';
2
- import * as vite from 'vite';
3
- import { relative, resolve } from 'node:path';
4
- export async function buildSSRApp(config, options) {
5
- const workspaceRoot = options?.workspaceRoot ?? process.cwd();
6
- const sourceRoot = options?.sourceRoot ?? 'src';
7
- const rootDir = relative(workspaceRoot, config.root || '.') || '.';
8
- const ssrBuildConfig = mergeConfig(config, {
9
- build: {
10
- ssr: true,
11
- [vite.rolldownVersion ? 'rolldownOptions' : 'rollupOptions']: {
12
- input: options?.entryServer ||
13
- resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),
14
- },
15
- outDir: options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr'),
16
- },
17
- });
18
- await build(ssrBuildConfig);
1
+ import { getBundleOptionsKey } from "./utils/rolldown.js";
2
+ import { build, mergeConfig } from "vite";
3
+ import { relative, resolve } from "node:path";
4
+ //#region packages/vite-plugin-nitro/src/lib/build-ssr.ts
5
+ async function buildClientApp(config, options) {
6
+ const workspaceRoot = options?.workspaceRoot ?? process.cwd();
7
+ const rootDir = relative(workspaceRoot, config.root || ".") || ".";
8
+ await build(mergeConfig(config, { build: {
9
+ ssr: false,
10
+ outDir: config.build?.outDir || resolve(workspaceRoot, "dist", rootDir, "client"),
11
+ emptyOutDir: true
12
+ } }));
19
13
  }
14
+ async function buildSSRApp(config, options) {
15
+ const workspaceRoot = options?.workspaceRoot ?? process.cwd();
16
+ const sourceRoot = options?.sourceRoot ?? "src";
17
+ const rootDir = relative(workspaceRoot, config.root || ".") || ".";
18
+ await build(mergeConfig(config, { build: {
19
+ ssr: true,
20
+ [getBundleOptionsKey()]: { input: options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
21
+ outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr"),
22
+ emptyOutDir: false
23
+ } }));
24
+ }
25
+ //#endregion
26
+ export { buildClientApp, buildSSRApp };
27
+
20
28
  //# sourceMappingURL=build-ssr.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"build-ssr.js","sourceRoot":"","sources":["../../../../../packages/vite-plugin-nitro/src/lib/build-ssr.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAc,MAAM,MAAM,CAAC;AACtD,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAI9C,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,MAAkB,EAClB,OAAiB;IAEjB,MAAM,aAAa,GAAG,OAAO,EAAE,aAAa,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IAC9D,MAAM,UAAU,GAAG,OAAO,EAAE,UAAU,IAAI,KAAK,CAAC;IAChD,MAAM,OAAO,GAAG,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,GAAG,CAAC;IACnE,MAAM,cAAc,GAAG,WAAW,CAAC,MAAM,EAAc;QACrD,KAAK,EAAE;YACL,GAAG,EAAE,IAAI;YACT,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,eAAe,CAAC,EAAE;gBAC5D,KAAK,EACH,OAAO,EAAE,WAAW;oBACpB,OAAO,CAAC,aAAa,EAAE,OAAO,EAAE,GAAG,UAAU,iBAAiB,CAAC;aAClE;YACD,MAAM,EACJ,OAAO,EAAE,WAAW,IAAI,OAAO,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;SACzE;KACF,CAAC,CAAC;IAEH,MAAM,KAAK,CAAC,cAAc,CAAC,CAAC;AAC9B,CAAC"}
1
+ {"version":3,"file":"build-ssr.js","names":[],"sources":["../../../src/lib/build-ssr.ts"],"sourcesContent":["import { build, mergeConfig, UserConfig } from 'vite';\nimport { relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport { getBundleOptionsKey } from './utils/rolldown.js';\n\nexport async function buildClientApp(\n config: UserConfig,\n options?: Options,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const clientBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: false,\n outDir:\n config.build?.outDir ||\n resolve(workspaceRoot, 'dist', rootDir, 'client'),\n emptyOutDir: true,\n },\n });\n\n await build(clientBuildConfig);\n}\n\nexport async function buildSSRApp(\n config: UserConfig,\n options?: Options,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const sourceRoot = options?.sourceRoot ?? 'src';\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const bundleOptionsKey = getBundleOptionsKey();\n const ssrBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: true,\n [bundleOptionsKey]: {\n input:\n options?.entryServer ||\n resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),\n },\n outDir:\n options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n // Preserve the client build output. The client pass already handled its\n // own cleanup, and on Windows this nested SSR build can otherwise remove\n // sibling artifacts that Nitro needs to read immediately afterward.\n emptyOutDir: false,\n },\n });\n\n await build(ssrBuildConfig);\n}\n"],"mappings":";;;;AAMA,eAAsB,eACpB,QACA,SACe;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,IAAI,IAAI;AAW/D,OAAM,MAVoB,YAAY,QAAoB,EACxD,OAAO;EACL,KAAK;EACL,QACE,OAAO,OAAO,UACd,QAAQ,eAAe,QAAQ,SAAS,SAAS;EACnD,aAAa;EACd,EACF,CAAC,CAE4B;;AAGhC,eAAsB,YACpB,QACA,SACe;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,IAAI,IAAI;AAmB/D,OAAM,MAjBiB,YAAY,QAAoB,EACrD,OAAO;EACL,KAAK;GAHgB,qBAAqB,GAItB,EAClB,OACE,SAAS,eACT,QAAQ,eAAe,SAAS,GAAG,WAAW,iBAAiB,EAClE;EACD,QACE,SAAS,eAAe,QAAQ,eAAe,QAAQ,SAAS,MAAM;EAIxE,aAAa;EACd,EACF,CAAC,CAEyB"}
@@ -1,2 +1,2 @@
1
- import type { Nitro, PrerenderRoute } from 'nitro/types';
1
+ import type { Nitro, PrerenderRoute } from "nitro/types";
2
2
  export declare function addPostRenderingHooks(nitro: Nitro, hooks: ((pr: PrerenderRoute) => Promise<void>)[]): void;
@@ -1,8 +1,12 @@
1
- export function addPostRenderingHooks(nitro, hooks) {
2
- hooks.forEach((hook) => {
3
- nitro.hooks.hook('prerender:generate', (route) => {
4
- hook(route);
5
- });
6
- });
1
+ //#region packages/vite-plugin-nitro/src/lib/hooks/post-rendering-hook.ts
2
+ function addPostRenderingHooks(nitro, hooks) {
3
+ hooks.forEach((hook) => {
4
+ nitro.hooks.hook("prerender:generate", (route) => {
5
+ hook(route);
6
+ });
7
+ });
7
8
  }
9
+ //#endregion
10
+ export { addPostRenderingHooks };
11
+
8
12
  //# sourceMappingURL=post-rendering-hook.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"post-rendering-hook.js","sourceRoot":"","sources":["../../../../../../packages/vite-plugin-nitro/src/lib/hooks/post-rendering-hook.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,qBAAqB,CACnC,KAAY,EACZ,KAAgD;IAEhD,KAAK,CAAC,OAAO,CAAC,CAAC,IAAwC,EAAE,EAAE;QACzD,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB,EAAE,CAAC,KAAqB,EAAE,EAAE;YAC/D,IAAI,CAAC,KAAK,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"post-rendering-hook.js","names":[],"sources":["../../../../src/lib/hooks/post-rendering-hook.ts"],"sourcesContent":["import type { Nitro, PrerenderRoute } from 'nitro/types';\n\nexport function addPostRenderingHooks(\n nitro: Nitro,\n hooks: ((pr: PrerenderRoute) => Promise<void>)[],\n): void {\n hooks.forEach((hook: (preRoute: PrerenderRoute) => void) => {\n nitro.hooks.hook('prerender:generate', (route: PrerenderRoute) => {\n hook(route);\n });\n });\n}\n"],"mappings":";AAEA,SAAgB,sBACd,OACA,OACM;AACN,OAAM,SAAS,SAA6C;AAC1D,QAAM,MAAM,KAAK,uBAAuB,UAA0B;AAChE,QAAK,MAAM;IACX;GACF"}
@@ -1,121 +1,147 @@
1
- import type { PrerenderRoute } from 'nitro/types';
1
+ import type { PrerenderRoute } from "nitro/types";
2
+ import type { UserConfig } from "vite";
2
3
  export interface Options {
3
- ssr?: boolean;
4
- ssrBuildDir?: string;
5
- /**
6
- * Prerender the static pages without producing the server output.
7
- */
8
- static?: boolean;
9
- prerender?: PrerenderOptions;
10
- entryServer?: string;
11
- index?: string;
12
- /**
13
- * Relative path to source files. Default is 'src'.
14
- */
15
- sourceRoot?: string;
16
- /**
17
- * Absolute path to workspace root. Default is 'process.cwd()'
18
- */
19
- workspaceRoot?: string;
20
- /**
21
- * Additional page paths to include
22
- */
23
- additionalPagesDirs?: string[];
24
- /**
25
- * Additional API paths to include
26
- */
27
- additionalAPIDirs?: string[];
28
- apiPrefix?: string;
29
- /**
30
- * Toggles internal API middleware.
31
- * If disabled, a proxy request is used to route /api
32
- * requests to / in the production server build.
33
- *
34
- * @deprecated
35
- * Use the src/server/routes/api folder
36
- * for API routes.
37
- */
38
- useAPIMiddleware?: boolean;
4
+ ssr?: boolean;
5
+ ssrBuildDir?: string;
6
+ /**
7
+ * Prerender the static pages without producing the server output.
8
+ */
9
+ static?: boolean;
10
+ prerender?: PrerenderOptions;
11
+ entryServer?: string;
12
+ index?: string;
13
+ /**
14
+ * Relative path to source files. Default is 'src'.
15
+ */
16
+ sourceRoot?: string;
17
+ /**
18
+ * Absolute path to workspace root. Default is 'process.cwd()'
19
+ */
20
+ workspaceRoot?: string;
21
+ /**
22
+ * Additional page paths to include
23
+ */
24
+ additionalPagesDirs?: string[];
25
+ /**
26
+ * Additional API paths to include
27
+ */
28
+ additionalAPIDirs?: string[];
29
+ apiPrefix?: string;
30
+ /**
31
+ * Toggles internal API middleware.
32
+ * If disabled, a proxy request is used to route /api
33
+ * requests to / in the production server build.
34
+ *
35
+ * @deprecated
36
+ * Use the src/server/routes/api folder
37
+ * for API routes.
38
+ */
39
+ useAPIMiddleware?: boolean;
40
+ /**
41
+ * Vite-native build passthrough. Rolldown-only options such as
42
+ * `build.rolldownOptions.output.codeSplitting` are forwarded when present.
43
+ */
44
+ vite?: {
45
+ build?: UserConfig["build"];
46
+ };
39
47
  }
40
48
  export interface PrerenderOptions {
41
- /**
42
- * Add additional routes to prerender through crawling page links.
43
- */
44
- discover?: boolean;
45
- /**
46
- * List of routes to prerender resolved statically or dynamically.
47
- */
48
- routes?: (string | PrerenderContentDir | PrerenderRouteConfig)[] | (() => Promise<(string | PrerenderContentDir | PrerenderRouteConfig | undefined)[]>);
49
- sitemap?: SitemapConfig;
50
- /** List of functions that run for each route after pre-rendering is complete. */
51
- postRenderingHooks?: ((routes: PrerenderRoute) => Promise<void>)[];
49
+ /**
50
+ * Add additional routes to prerender through crawling page links.
51
+ */
52
+ discover?: boolean;
53
+ /**
54
+ * List of routes to prerender resolved statically or dynamically.
55
+ */
56
+ routes?: (string | PrerenderContentDir | PrerenderRouteConfig)[] | (() => Promise<(string | PrerenderContentDir | PrerenderRouteConfig | undefined)[]>);
57
+ sitemap?: SitemapConfig;
58
+ /** List of functions that run for each route after pre-rendering is complete. */
59
+ postRenderingHooks?: ((routes: PrerenderRoute) => Promise<void>)[];
52
60
  }
61
+ export type SitemapPriority = number | `${number}`;
62
+ export interface SitemapRouteDefinition {
63
+ route: string;
64
+ lastmod?: string;
65
+ changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
66
+ priority?: SitemapPriority;
67
+ }
68
+ export interface SitemapEntry extends SitemapRouteDefinition {
69
+ loc: string;
70
+ }
71
+ export type SitemapRouteInput = string | SitemapRouteDefinition | undefined;
72
+ export type SitemapRouteSource = SitemapRouteInput[] | (() => Promise<SitemapRouteInput[]>);
73
+ export type SitemapExcludeRule = string | RegExp | ((entry: SitemapEntry) => boolean | Promise<boolean>);
74
+ export type SitemapTransform = (entry: SitemapEntry) => SitemapRouteDefinition | false | Promise<SitemapRouteDefinition | false>;
53
75
  export interface SitemapConfig {
54
- host: string;
76
+ host: string;
77
+ include?: SitemapRouteSource;
78
+ exclude?: SitemapExcludeRule[];
79
+ defaults?: PrerenderSitemapConfig;
80
+ transform?: SitemapTransform;
55
81
  }
56
82
  export interface PrerenderContentDir {
57
- /**
58
- * The directory where files should be grabbed from.
59
- * @example `/src/contents/blog`
60
- */
61
- contentDir: string;
62
- /**
63
- * Transform the matching content files path into a route.
64
- * The function is called for each matching content file within the specified contentDir.
65
- * @param file information of the matching file (`path`, `name`, `extension`, `attributes`, `content`)
66
- * @returns a string with the route should be returned (e. g. `/blog/<slug>`) or the value `false`, when the route should not be prerendered.
67
- */
68
- transform: (file: PrerenderContentFile) => string | false;
69
- /**
70
- * Customize the sitemap definition for the prerendered route
71
- *
72
- * https://www.sitemaps.org/protocol.html#xmlTagDefinitions
73
- */
74
- sitemap?: PrerenderSitemapConfig | ((file: PrerenderContentFile) => PrerenderSitemapConfig);
75
- /**
76
- * Output the source markdown content alongside the prerendered route.
77
- * The source file will be accessible at the route path with a .md extension.
78
- * @param file information of the matching file including its content
79
- * @returns the markdown content string to output, or `false` to skip outputting for this file
80
- */
81
- outputSourceFile?: (file: PrerenderContentFile) => string | false;
83
+ /**
84
+ * The directory where files should be grabbed from.
85
+ * @example `/src/contents/blog`
86
+ */
87
+ contentDir: string;
88
+ /**
89
+ * Transform the matching content files path into a route.
90
+ * The function is called for each matching content file within the specified contentDir.
91
+ * @param file information of the matching file (`path`, `name`, `extension`, `attributes`, `content`)
92
+ * @returns a string with the route should be returned (e. g. `/blog/<slug>`) or the value `false`, when the route should not be prerendered.
93
+ */
94
+ transform: (file: PrerenderContentFile) => string | false;
95
+ /**
96
+ * Customize the sitemap definition for the prerendered route
97
+ *
98
+ * https://www.sitemaps.org/protocol.html#xmlTagDefinitions
99
+ */
100
+ sitemap?: PrerenderSitemapConfig | ((file: PrerenderContentFile) => PrerenderSitemapConfig);
101
+ /**
102
+ * Output the source markdown content alongside the prerendered route.
103
+ * The source file will be accessible at the route path with a .md extension.
104
+ * @param file information of the matching file including its content
105
+ * @returns the markdown content string to output, or `false` to skip outputting for this file
106
+ */
107
+ outputSourceFile?: (file: PrerenderContentFile) => string | false;
82
108
  }
83
109
  /**
84
- * @param path the path to the content file
85
- * @param name the basename of the matching content file without the file extension
86
- * @param extension the file extension
87
- * @param attributes the frontmatter attributes extracted from the frontmatter section of the file
88
- * @param content the raw file content including frontmatter
89
- * @returns a string with the route should be returned (e. g. `/blog/<slug>`) or the value `false`, when the route should not be prerendered.
90
- */
110
+ * @param path the path to the content file
111
+ * @param name the basename of the matching content file without the file extension
112
+ * @param extension the file extension
113
+ * @param attributes the frontmatter attributes extracted from the frontmatter section of the file
114
+ * @param content the raw file content including frontmatter
115
+ * @returns a string with the route should be returned (e. g. `/blog/<slug>`) or the value `false`, when the route should not be prerendered.
116
+ */
91
117
  export interface PrerenderContentFile {
92
- path: string;
93
- attributes: Record<string, any>;
94
- name: string;
95
- extension: string;
96
- content: string;
118
+ path: string;
119
+ attributes: Record<string, any>;
120
+ name: string;
121
+ extension: string;
122
+ content: string;
97
123
  }
98
124
  export interface PrerenderSitemapConfig {
99
- lastmod?: string;
100
- changefreq?: 'always' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly' | 'never';
101
- priority?: string;
125
+ lastmod?: string;
126
+ changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
127
+ priority?: SitemapPriority;
102
128
  }
103
129
  export interface PrerenderRouteConfig {
104
- route: string;
105
- /**
106
- * Customize the sitemap definition for the prerendered route
107
- *
108
- * https://www.sitemaps.org/protocol.html#xmlTagDefinitions
109
- */
110
- sitemap?: PrerenderSitemapConfig | (() => PrerenderSitemapConfig);
111
- /**
112
- * Prerender static data for the prerendered route
113
- */
114
- staticData?: boolean;
115
- /**
116
- * Path to the source markdown file to output alongside the prerendered route.
117
- * The source file will be accessible at the route path with a .md extension.
118
- * @example 'src/content/overview.md'
119
- */
120
- outputSourceFile?: string;
130
+ route: string;
131
+ /**
132
+ * Customize the sitemap definition for the prerendered route
133
+ *
134
+ * https://www.sitemaps.org/protocol.html#xmlTagDefinitions
135
+ */
136
+ sitemap?: PrerenderSitemapConfig | (() => PrerenderSitemapConfig);
137
+ /**
138
+ * Prerender static data for the prerendered route
139
+ */
140
+ staticData?: boolean;
141
+ /**
142
+ * Path to the source markdown file to output alongside the prerendered route.
143
+ * The source file will be accessible at the route path with a .md extension.
144
+ * @example 'src/content/overview.md'
145
+ */
146
+ outputSourceFile?: string;
121
147
  }
@@ -1,7 +1,7 @@
1
- import { Plugin } from 'vite';
2
- import { Options } from '../options.js';
1
+ import { Plugin } from "vite";
2
+ import { Options } from "../options.js";
3
3
  type ServerOptions = Options & {
4
- routeRules?: Record<string, any> | undefined;
4
+ routeRules?: Record<string, any> | undefined;
5
5
  };
6
6
  export declare function devServerPlugin(options: ServerOptions): Plugin;
7
7
  export {};
@@ -1,70 +1,59 @@
1
- // SSR dev server, middleware and error page source modified from
2
- // https://github.com/solidjs/solid-start/blob/main/packages/start/dev/server.js
3
- import { normalizePath, } from 'vite';
4
- import { resolve } from 'node:path';
5
- import { readFileSync } from 'node:fs';
6
- import { createRouter as createRadixRouter, toRouteMatcher } from 'radix3';
7
- import { defu } from 'defu';
8
- import { registerDevServerMiddleware } from '../utils/register-dev-middleware.js';
9
- import { writeWebResponseToNode } from '../utils/node-web-bridge.js';
10
- export function devServerPlugin(options) {
11
- const workspaceRoot = options?.workspaceRoot || process.cwd();
12
- const sourceRoot = options?.sourceRoot ?? 'src';
13
- const index = options.index || 'index.html';
14
- let config;
15
- let root;
16
- let isTest = false;
17
- return {
18
- name: 'analogjs-dev-ssr-plugin',
19
- config(userConfig, { mode }) {
20
- config = userConfig;
21
- root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');
22
- isTest = isTest ? isTest : mode === 'test';
23
- return {
24
- appType: 'custom',
25
- resolve: {
26
- alias: {
27
- '~analog/entry-server': options.entryServer || `${root}/${sourceRoot}/main.server.ts`,
28
- },
29
- },
30
- };
31
- },
32
- configureServer(viteServer) {
33
- if (isTest) {
34
- return;
35
- }
36
- return async () => {
37
- remove_html_middlewares(viteServer.middlewares);
38
- registerDevServerMiddleware(root, sourceRoot, viteServer);
39
- viteServer.middlewares.use(async (req, res) => {
40
- let template = readFileSync(resolve(viteServer.config.root, index), 'utf-8');
41
- template = await viteServer.transformIndexHtml(req.originalUrl, template);
42
- const _routeRulesMatcher = toRouteMatcher(createRadixRouter({ routes: options.routeRules }));
43
- const _getRouteRules = (path) => defu({}, ..._routeRulesMatcher.matchAll(path).reverse());
44
- try {
45
- let result;
46
- // Check for route rules explicitly disabling SSR
47
- if (_getRouteRules(req.originalUrl).ssr === false) {
48
- result = template;
49
- }
50
- else {
51
- const entryServer = (await viteServer.ssrLoadModule('~analog/entry-server'))['default'];
52
- result = await entryServer(req.originalUrl, template, {
53
- req,
54
- res,
55
- });
56
- }
57
- if (result instanceof Response) {
58
- await writeWebResponseToNode(res, result);
59
- return;
60
- }
61
- res.setHeader('Content-Type', 'text/html');
62
- res.end(result);
63
- }
64
- catch (e) {
65
- viteServer.ssrFixStacktrace(e);
66
- res.statusCode = 500;
67
- res.end(`
1
+ import { writeWebResponseToNode } from "../utils/node-web-bridge.js";
2
+ import { registerDevServerMiddleware } from "../utils/register-dev-middleware.js";
3
+ import { normalizePath } from "vite";
4
+ import { resolve } from "node:path";
5
+ import { readFileSync } from "node:fs";
6
+ import { createRouter, toRouteMatcher } from "radix3";
7
+ import { defu } from "defu";
8
+ //#region packages/vite-plugin-nitro/src/lib/plugins/dev-server-plugin.ts
9
+ function devServerPlugin(options) {
10
+ const workspaceRoot = options?.workspaceRoot || process.cwd();
11
+ const sourceRoot = options?.sourceRoot ?? "src";
12
+ const index = options.index || "index.html";
13
+ let config;
14
+ let root;
15
+ let isTest = false;
16
+ return {
17
+ name: "analogjs-dev-ssr-plugin",
18
+ config(userConfig, { mode }) {
19
+ config = userConfig;
20
+ root = normalizePath(resolve(workspaceRoot, config.root || ".") || ".");
21
+ isTest = isTest ? isTest : mode === "test";
22
+ return {
23
+ appType: "custom",
24
+ resolve: { alias: { "~analog/entry-server": options.entryServer || `${root}/${sourceRoot}/main.server.ts` } }
25
+ };
26
+ },
27
+ configureServer(viteServer) {
28
+ if (isTest) return;
29
+ return async () => {
30
+ remove_html_middlewares(viteServer.middlewares);
31
+ registerDevServerMiddleware(root, sourceRoot, viteServer);
32
+ viteServer.middlewares.use(async (req, res) => {
33
+ let template = readFileSync(resolve(viteServer.config.root, index), "utf-8");
34
+ template = await viteServer.transformIndexHtml(req.originalUrl, template);
35
+ const _routeRulesMatcher = toRouteMatcher(createRouter({ routes: options.routeRules }));
36
+ const _getRouteRules = (path) => defu({}, ..._routeRulesMatcher.matchAll(path).reverse());
37
+ try {
38
+ let result;
39
+ if (_getRouteRules(req.originalUrl).ssr === false) result = template;
40
+ else {
41
+ const entryServer = (await viteServer.ssrLoadModule("~analog/entry-server"))["default"];
42
+ result = await entryServer(req.originalUrl, template, {
43
+ req,
44
+ res
45
+ });
46
+ }
47
+ if (result instanceof Response) {
48
+ await writeWebResponseToNode(res, result);
49
+ return;
50
+ }
51
+ res.setHeader("Content-Type", "text/html");
52
+ res.end(result);
53
+ } catch (e) {
54
+ viteServer.ssrFixStacktrace(e);
55
+ res.statusCode = 500;
56
+ res.end(`
68
57
  <!DOCTYPE html>
69
58
  <html lang="en">
70
59
  <head>
@@ -72,50 +61,51 @@ export function devServerPlugin(options) {
72
61
  <title>Error</title>
73
62
  <script type="module">
74
63
  import { ErrorOverlay } from '/@vite/client'
75
- document.body.appendChild(new ErrorOverlay(${JSON.stringify(prepareError(req, e)).replace(/</g, '\\u003c')}))
76
- </script>
64
+ document.body.appendChild(new ErrorOverlay(${JSON.stringify(prepareError(req, e)).replace(/</g, "\\u003c")}))
65
+ <\/script>
77
66
  </head>
78
67
  <body>
79
68
  </body>
80
69
  </html>
81
70
  `);
82
- }
83
- });
84
- };
85
- },
86
- };
71
+ }
72
+ });
73
+ };
74
+ }
75
+ };
87
76
  }
88
77
  /**
89
- * Removes Vite internal middleware
90
- *
91
- * @param server
92
- */
78
+ * Removes Vite internal middleware
79
+ *
80
+ * @param server
81
+ */
93
82
  function remove_html_middlewares(server) {
94
- const html_middlewares = [
95
- 'viteIndexHtmlMiddleware',
96
- 'vite404Middleware',
97
- 'viteSpaFallbackMiddleware',
98
- 'viteHtmlFallbackMiddleware',
99
- ];
100
- for (let i = server.stack.length - 1; i > 0; i--) {
101
- const handler = server.stack[i]?.handle;
102
- const handlerName = typeof handler === 'function' ? handler.name : undefined;
103
- if (handlerName && html_middlewares.includes(handlerName)) {
104
- server.stack.splice(i, 1);
105
- }
106
- }
83
+ const html_middlewares = [
84
+ "viteIndexHtmlMiddleware",
85
+ "vite404Middleware",
86
+ "viteSpaFallbackMiddleware",
87
+ "viteHtmlFallbackMiddleware"
88
+ ];
89
+ for (let i = server.stack.length - 1; i > 0; i--) {
90
+ const handler = server.stack[i]?.handle;
91
+ const handlerName = typeof handler === "function" ? handler.name : void 0;
92
+ if (handlerName && html_middlewares.includes(handlerName)) server.stack.splice(i, 1);
93
+ }
107
94
  }
108
95
  /**
109
- * Formats error for SSR message in error overlay
110
- * @param req
111
- * @param error
112
- * @returns
113
- */
96
+ * Formats error for SSR message in error overlay
97
+ * @param req
98
+ * @param error
99
+ * @returns
100
+ */
114
101
  function prepareError(req, error) {
115
- const e = error;
116
- return {
117
- message: `An error occured while server rendering ${req.url}:\n\n\t${typeof e === 'string' ? e : e.message} `,
118
- stack: typeof e === 'string' ? '' : e.stack,
119
- };
102
+ const e = error;
103
+ return {
104
+ message: `An error occured while server rendering ${req.url}:\n\n\t${typeof e === "string" ? e : e.message} `,
105
+ stack: typeof e === "string" ? "" : e.stack
106
+ };
120
107
  }
108
+ //#endregion
109
+ export { devServerPlugin };
110
+
121
111
  //# sourceMappingURL=dev-server-plugin.js.map