@qwik.dev/router 2.0.0-beta.8 → 2.0.0-rc.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.
Files changed (80) hide show
  1. package/lib/adapters/azure-swa/vite/index.d.ts +2 -2
  2. package/lib/adapters/azure-swa/vite/index.mjs +44 -57
  3. package/lib/adapters/bun-server/vite/index.d.ts +2 -2
  4. package/lib/adapters/bun-server/vite/index.mjs +16 -22
  5. package/lib/adapters/cloud-run/vite/index.d.ts +2 -2
  6. package/lib/adapters/cloud-run/vite/index.mjs +15 -19
  7. package/lib/adapters/cloudflare-pages/vite/index.d.ts +2 -2
  8. package/lib/adapters/cloudflare-pages/vite/index.mjs +45 -76
  9. package/lib/adapters/deno-server/vite/index.d.ts +2 -2
  10. package/lib/adapters/deno-server/vite/index.mjs +25 -34
  11. package/lib/adapters/netlify-edge/vite/index.d.ts +2 -2
  12. package/lib/adapters/netlify-edge/vite/index.mjs +49 -89
  13. package/lib/adapters/node-server/vite/index.d.ts +2 -2
  14. package/lib/adapters/node-server/vite/index.mjs +16 -22
  15. package/lib/adapters/shared/vite/index.d.ts +9 -16
  16. package/lib/adapters/shared/vite/index.mjs +280 -293
  17. package/lib/adapters/ssg/vite/index.d.ts +1 -1
  18. package/lib/adapters/ssg/vite/index.mjs +13 -299
  19. package/lib/adapters/vercel-edge/vite/index.d.ts +3 -3
  20. package/lib/adapters/vercel-edge/vite/index.mjs +75 -79
  21. package/lib/chunks/dev-preloaded-route-loader.mjs +2 -0
  22. package/lib/chunks/format.mjs +24 -0
  23. package/lib/chunks/fs.mjs +143 -0
  24. package/lib/chunks/head.qwik.mjs +1570 -0
  25. package/lib/chunks/http-error.qwik.mjs +28 -0
  26. package/lib/chunks/pathname.mjs +58 -0
  27. package/lib/chunks/request-body-limit.mjs +27 -0
  28. package/lib/chunks/request-path.mjs +53 -0
  29. package/lib/chunks/route-trie-key.mjs +10 -0
  30. package/lib/chunks/routes.mjs +26 -0
  31. package/lib/chunks/server-error.mjs +38 -0
  32. package/lib/chunks/static-file.mjs +70 -0
  33. package/lib/chunks/system.mjs +271 -0
  34. package/lib/chunks/user-response.mjs +1883 -0
  35. package/lib/chunks/worker-thread.mjs +274 -0
  36. package/lib/index.d.ts +550 -182
  37. package/lib/index.qwik.mjs +1742 -2030
  38. package/lib/middleware/aws-lambda/index.d.ts +15 -17
  39. package/lib/middleware/aws-lambda/index.mjs +46 -50
  40. package/lib/middleware/azure-swa/index.mjs +85 -294
  41. package/lib/middleware/bun/index.d.ts +20 -5
  42. package/lib/middleware/bun/index.mjs +117 -201
  43. package/lib/middleware/cloudflare-pages/index.mjs +101 -101
  44. package/lib/middleware/deno/index.d.ts +22 -5
  45. package/lib/middleware/deno/index.mjs +103 -191
  46. package/lib/middleware/firebase/index.mjs +22 -31
  47. package/lib/middleware/netlify-edge/index.mjs +63 -80
  48. package/lib/middleware/node/index.d.ts +17 -5
  49. package/lib/middleware/node/index.mjs +298 -269
  50. package/lib/middleware/request-handler/index.d.ts +259 -58
  51. package/lib/middleware/request-handler/index.mjs +108 -1730
  52. package/lib/middleware/vercel-edge/index.mjs +76 -100
  53. package/lib/modules.d.ts +7 -4
  54. package/lib/service-worker/index.mjs +14 -0
  55. package/lib/ssg/index.d.ts +50 -26
  56. package/lib/ssg/index.mjs +257 -43
  57. package/lib/vite/index.d.ts +59 -11
  58. package/lib/vite/index.mjs +2533 -27535
  59. package/modules.d.ts +7 -4
  60. package/package.json +53 -70
  61. package/lib/adapters/azure-swa/vite/index.cjs +0 -96
  62. package/lib/adapters/bun-server/vite/index.cjs +0 -50
  63. package/lib/adapters/cloud-run/vite/index.cjs +0 -47
  64. package/lib/adapters/cloudflare-pages/vite/index.cjs +0 -115
  65. package/lib/adapters/deno-server/vite/index.cjs +0 -62
  66. package/lib/adapters/netlify-edge/vite/index.cjs +0 -130
  67. package/lib/adapters/node-server/vite/index.cjs +0 -50
  68. package/lib/adapters/shared/vite/index.cjs +0 -338
  69. package/lib/adapters/ssg/vite/index.cjs +0 -339
  70. package/lib/adapters/vercel-edge/vite/index.cjs +0 -118
  71. package/lib/index.qwik.cjs +0 -2085
  72. package/lib/middleware/node/index.cjs +0 -310
  73. package/lib/middleware/request-handler/index.cjs +0 -1766
  74. package/lib/service-worker.cjs +0 -17
  75. package/lib/service-worker.mjs +0 -15
  76. package/lib/ssg/deno.mjs +0 -8
  77. package/lib/ssg/index.cjs +0 -67
  78. package/lib/ssg/node.cjs +0 -1126
  79. package/lib/ssg/node.mjs +0 -1088
  80. package/lib/vite/index.cjs +0 -27607
@@ -1,6 +1,6 @@
1
- import type { Plugin as Plugin_2 } from 'vite';
2
- import type { SsgRenderOptions } from 'packages/qwik-router/src/ssg';
3
- import type { UserConfig } from 'vite';
1
+ import { Plugin as Plugin_2 } from 'vite';
2
+ import type { SsgRenderOptions } from '../../../ssg/index.js';
3
+ import { UserConfig } from 'vite';
4
4
 
5
5
  /** @public */
6
6
  export declare interface AdapterSSGOptions extends Omit<SsgRenderOptions, 'outDir' | 'origin'> {
@@ -26,7 +26,7 @@ export declare interface AdapterSSGOptions extends Omit<SsgRenderOptions, 'outDi
26
26
  origin?: string;
27
27
  }
28
28
 
29
- declare interface BuildLayout {
29
+ declare interface BuiltLayout {
30
30
  filePath: string;
31
31
  dirPath: string;
32
32
  id: string;
@@ -34,7 +34,7 @@ declare interface BuildLayout {
34
34
  layoutName: string;
35
35
  }
36
36
 
37
- declare interface BuildRoute extends ParsedPathname {
37
+ declare interface BuiltRoute extends ParsedPathname {
38
38
  /** Unique id built from its relative file system path */
39
39
  id: string;
40
40
  /** Local file system path */
@@ -42,7 +42,7 @@ declare interface BuildRoute extends ParsedPathname {
42
42
  ext: string;
43
43
  /** URL Pathname */
44
44
  pathname: string;
45
- layouts: BuildLayout[];
45
+ layouts: BuiltLayout[];
46
46
  }
47
47
 
48
48
  /** @public */
@@ -74,14 +74,8 @@ export declare interface ServerAdapterOptions {
74
74
  ssg?: AdapterSSGOptions | null;
75
75
  }
76
76
 
77
- /**
78
- * Implements the SSG after the build is complete. Also provides a `generate(...)` callback that is
79
- * called after the SSG is complete, which allows for custom post-processing of the complete build
80
- * results.
81
- *
82
- * @public
83
- */
84
- export declare function viteAdapter(opts: ViteAdapterPluginOptions): Plugin_2<never>;
77
+ /** @public */
78
+ export declare function viteAdapter(opts: ViteAdapterPluginOptions): Plugin_2<never>[];
85
79
 
86
80
  /** @public */
87
81
  declare interface ViteAdapterPluginOptions {
@@ -98,8 +92,7 @@ declare interface ViteAdapterPluginOptions {
98
92
  clientPublicOutDir: string;
99
93
  serverOutDir: string;
100
94
  basePathname: string;
101
- routes: BuildRoute[];
102
- assetsDir?: string;
95
+ routes: BuiltRoute[];
103
96
  warn: (message: string) => void;
104
97
  error: (message: string) => void;
105
98
  }) => Promise<void>;
@@ -1,302 +1,289 @@
1
- // packages/qwik-router/src/adapters/shared/vite/index.ts
2
- import { basename, dirname, join as join2, resolve } from "node:path";
3
-
4
- // packages/qwik-router/src/adapters/shared/vite/post-build.ts
5
- import { getErrorHtml } from "../../../middleware/request-handler/index.mjs";
1
+ import { t as ensureSlash } from "../../../chunks/pathname.mjs";
2
+ import { r as LOADER_REGEX } from "../../../chunks/request-path.mjs";
6
3
  import fs from "node:fs";
7
- import { join } from "node:path";
8
- async function postBuild(clientOutDir, serverOutDir, pathName, userStaticPaths, cleanStatic) {
9
- if (pathName && !pathName.endsWith("/")) {
10
- pathName += "/";
11
- }
12
- const ignorePathnames = /* @__PURE__ */ new Set([
13
- pathName + "/" + (globalThis.__QWIK_BUILD_DIR__ || "build") + "/",
14
- pathName + "/" + (globalThis.__QWIK_ASSETS_DIR__ || "assets") + "/"
15
- ]);
16
- const staticPaths = new Set(userStaticPaths.map(normalizeTrailingSlash));
17
- const notFounds = [];
18
- const loadItem = async (fsDir, fsName, pathname) => {
19
- pathname = normalizeTrailingSlash(pathname);
20
- if (ignorePathnames.has(pathname)) {
21
- return;
22
- }
23
- const fsPath = join(fsDir, fsName);
24
- if (fsName === "index.html" || fsName === "q-data.json") {
25
- if (!staticPaths.has(pathname) && cleanStatic) {
26
- await fs.promises.unlink(fsPath);
27
- }
28
- return;
29
- }
30
- if (fsName === "404.html") {
31
- const notFoundHtml = await fs.promises.readFile(fsPath, "utf-8");
32
- notFounds.push([pathname, notFoundHtml]);
33
- return;
34
- }
35
- const stat = await fs.promises.stat(fsPath);
36
- if (stat.isDirectory()) {
37
- await loadDir(fsPath, pathname + fsName + "/");
38
- } else if (stat.isFile()) {
39
- staticPaths.add(pathname + fsName);
40
- }
41
- };
42
- const loadDir = async (fsDir, pathname) => {
43
- const itemNames = await fs.promises.readdir(fsDir);
44
- await Promise.all(itemNames.map((i) => loadItem(fsDir, i, pathname)));
45
- };
46
- if (fs.existsSync(clientOutDir)) {
47
- await loadDir(clientOutDir, pathName);
48
- }
49
- const notFoundPathsCode = createNotFoundPathsCode(pathName, notFounds);
50
- const staticPathsCode = createStaticPathsCode(staticPaths);
51
- await injectStatics(staticPathsCode, notFoundPathsCode, serverOutDir);
52
- }
53
- function normalizeTrailingSlash(pathname) {
54
- if (!pathname.endsWith("/")) {
55
- return pathname + "/";
56
- }
57
- return pathname;
58
- }
59
- function createNotFoundPathsCode(basePathname, notFounds) {
60
- notFounds.sort((a, b) => {
61
- if (a[0].length > b[0].length) {
62
- return -1;
63
- }
64
- if (a[0].length < b[0].length) {
65
- return 1;
66
- }
67
- if (a[0] < b[0]) {
68
- return -1;
69
- }
70
- if (a[0] > b[0]) {
71
- return 1;
72
- }
73
- return 0;
74
- });
75
- if (!notFounds.some((r) => r[0] === basePathname)) {
76
- const html = getErrorHtml(404, "Resource Not Found");
77
- notFounds.push([basePathname, html]);
78
- }
79
- return JSON.stringify(notFounds, null, 2).slice(1, -1);
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { spawn } from "node:child_process";
6
+ import { readFile, rm, unlink } from "node:fs/promises";
7
+ /** Cleans the client output SSG results if needed and injects the SSG metadata into the build output */
8
+ async function postBuild(clientOutDir, serverOutDir, pathName, userStaticPaths, cleanStatic, noTrailingSlash) {
9
+ if (pathName && !pathName.endsWith("/")) pathName = ensureSlash(pathName);
10
+ const pathNameBase = pathName || "/";
11
+ const ignorePathnames = /* @__PURE__ */ new Set([pathNameBase + (globalThis.__QWIK_BUILD_DIR__ || "build") + "/", pathNameBase + (globalThis.__QWIK_ASSETS_DIR__ || "assets") + "/"]);
12
+ const getStaticPathname = (pathname) => {
13
+ pathname = ensureSlash(pathname);
14
+ if (noTrailingSlash && pathname !== pathNameBase) return pathname.slice(0, -1);
15
+ return pathname;
16
+ };
17
+ const staticPaths = new Set(userStaticPaths.map(getStaticPathname));
18
+ const loadItem = async (fsDir, fsName, pathname) => {
19
+ pathname = ensureSlash(pathname);
20
+ if (ignorePathnames.has(pathname)) return;
21
+ const fsPath = join(fsDir, fsName);
22
+ if (fsName === "index.html") {
23
+ if (!staticPaths.has(getStaticPathname(pathname)) && cleanStatic) await fs.promises.unlink(fsPath);
24
+ return;
25
+ }
26
+ if (LOADER_REGEX.test("/" + fsName)) {
27
+ const staticPathname = getStaticPathname(pathname);
28
+ if (staticPaths.has(staticPathname)) staticPaths.add(ensureSlash(staticPathname) + fsName);
29
+ else if (cleanStatic) await fs.promises.unlink(fsPath);
30
+ return;
31
+ }
32
+ const stat = await fs.promises.stat(fsPath);
33
+ if (stat.isDirectory()) await loadDir(fsPath, ensureSlash(pathname + fsName));
34
+ else if (stat.isFile()) staticPaths.add(pathname + fsName);
35
+ };
36
+ const loadDir = async (fsDir, pathname) => {
37
+ const itemNames = await fs.promises.readdir(fsDir);
38
+ await Promise.all(itemNames.map((i) => loadItem(fsDir, i, pathname)));
39
+ };
40
+ if (fs.existsSync(clientOutDir)) await loadDir(clientOutDir, pathName);
41
+ await injectStatics(createStaticPathsCode(staticPaths), serverOutDir);
80
42
  }
81
43
  function createStaticPathsCode(staticPaths) {
82
- return JSON.stringify(Array.from(new Set(staticPaths)).sort()).slice(1, -1);
44
+ return JSON.stringify(Array.from(new Set(staticPaths)).sort()).slice(1, -1);
83
45
  }
84
- var injectStatics = async (staticPathsCode, notFoundPathsCode, outDir) => {
85
- const promises = /* @__PURE__ */ new Set();
86
- const doReplace = async (path) => {
87
- const code = await fs.promises.readFile(path, "utf-8");
88
- let replaced = false;
89
- const newCode = code.replace(
90
- /(['"])__QWIK_ROUTER_(STATIC_PATHS|NOT_FOUND)_ARRAY__\1/g,
91
- (_, _quote, type) => {
92
- replaced = true;
93
- return type === "STATIC_PATHS" ? staticPathsCode : notFoundPathsCode;
94
- }
95
- );
96
- if (replaced) {
97
- await fs.promises.writeFile(path, newCode);
98
- }
99
- };
100
- const walk = async (dir) => {
101
- const entries = await fs.promises.readdir(dir, { withFileTypes: true });
102
- for (const entry of entries) {
103
- if (entry.isDirectory()) {
104
- await walk(join(dir, entry.name));
105
- } else if (entry.name.endsWith("js")) {
106
- const p = doReplace(join(dir, entry.name)).finally(() => {
107
- promises.delete(p);
108
- });
109
- promises.add(p);
110
- }
111
- }
112
- };
113
- await walk(outDir);
114
- await Promise.all(promises);
46
+ var injectStatics = async (staticPathsCode, outDir) => {
47
+ const promises = /* @__PURE__ */ new Set();
48
+ const doReplace = async (path) => {
49
+ const code = await fs.promises.readFile(path, "utf-8");
50
+ let replaced = false;
51
+ const newCode = code.replace(/(['"`])__QWIK_ROUTER_STATIC_PATHS_ARRAY__\1/g, () => {
52
+ replaced = true;
53
+ return staticPathsCode;
54
+ });
55
+ if (replaced) await fs.promises.writeFile(path, newCode);
56
+ };
57
+ const walk = async (dir) => {
58
+ const entries = await fs.promises.readdir(dir, { withFileTypes: true });
59
+ for (const entry of entries) if (entry.isDirectory()) await walk(join(dir, entry.name));
60
+ else if (entry.name.endsWith("js")) {
61
+ const p = doReplace(join(dir, entry.name)).finally(() => {
62
+ promises.delete(p);
63
+ });
64
+ promises.add(p);
65
+ }
66
+ };
67
+ await walk(outDir);
68
+ await Promise.all(promises);
115
69
  };
116
-
117
- // packages/qwik-router/src/adapters/shared/vite/index.ts
70
+ /**
71
+ * Implements the SSG after the build is complete. Also provides a `generate(...)` callback that is
72
+ * called after the SSG is complete, which allows for custom post-processing of the complete build
73
+ * results.
74
+ *
75
+ * @public
76
+ */
77
+ var QWIK_SSG_ENTRY_ID = "@qwik-ssg-entry";
78
+ var QWIK_SSG_ENTRY_RESOLVED = "\0@qwik-ssg-entry";
79
+ var QWIK_SSG_WORKER_ENTRY_ID = "@qwik-ssg-worker-entry";
80
+ var QWIK_SSG_WORKER_ENTRY_RESOLVED = "\0@qwik-ssg-worker-entry";
81
+ /** @public */
118
82
  function viteAdapter(opts) {
119
- let qwikRouterPlugin = null;
120
- let qwikVitePlugin = null;
121
- let serverOutDir = null;
122
- let renderModulePath = null;
123
- let qwikRouterConfigModulePath = null;
124
- let isSsrBuild = false;
125
- const outputEntries = [];
126
- const plugin = {
127
- name: `vite-plugin-qwik-router-ssg-${opts.name}`,
128
- enforce: "post",
129
- apply: "build",
130
- config(config) {
131
- if (typeof opts.config === "function") {
132
- config = opts.config(config);
133
- }
134
- config.define = {
135
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "production"),
136
- ...config.define
137
- };
138
- return config;
139
- },
140
- configResolved(config) {
141
- var _a, _b, _c;
142
- isSsrBuild = !!config.build.ssr;
143
- if (isSsrBuild) {
144
- qwikRouterPlugin = config.plugins.find(
145
- (p) => p.name === "vite-plugin-qwik-router"
146
- );
147
- if (!qwikRouterPlugin) {
148
- throw new Error("Missing vite-plugin-qwik-router");
149
- }
150
- qwikVitePlugin = config.plugins.find(
151
- (p) => p.name === "vite-plugin-qwik"
152
- );
153
- if (!qwikVitePlugin) {
154
- throw new Error("Missing vite-plugin-qwik");
155
- }
156
- serverOutDir = config.build.outDir;
157
- if (((_a = config.build) == null ? void 0 : _a.ssr) !== true) {
158
- throw new Error(
159
- `"build.ssr" must be set to "true" in order to use the "${opts.name}" adapter.`
160
- );
161
- }
162
- if (!((_c = (_b = config.build) == null ? void 0 : _b.rollupOptions) == null ? void 0 : _c.input)) {
163
- throw new Error(
164
- `"build.rollupOptions.input" must be set in order to use the "${opts.name}" adapter.`
165
- );
166
- }
167
- }
168
- },
169
- buildStart() {
170
- if (isSsrBuild && opts.ssg !== null) {
171
- const { srcDir } = qwikVitePlugin.api.getOptions();
172
- this.emitFile({
173
- id: "@qwik-router-config",
174
- type: "chunk",
175
- fileName: "@qwik-router-config.js"
176
- });
177
- this.emitFile({
178
- id: `${srcDir}/entry.ssr`,
179
- type: "chunk",
180
- fileName: "entry.ssr.js"
181
- });
182
- }
183
- },
184
- generateBundle(_, bundles) {
185
- if (isSsrBuild) {
186
- outputEntries.length = 0;
187
- for (const fileName in bundles) {
188
- const chunk = bundles[fileName];
189
- if (chunk.type === "chunk" && chunk.isEntry) {
190
- outputEntries.push(fileName);
191
- if (chunk.name === "entry.ssr") {
192
- renderModulePath = join2(serverOutDir, fileName);
193
- } else if (chunk.name === "@qwik-router-config") {
194
- qwikRouterConfigModulePath = join2(serverOutDir, fileName);
195
- }
196
- }
197
- }
198
- }
199
- },
200
- closeBundle: {
201
- sequential: true,
202
- async handler() {
203
- var _a;
204
- if (isSsrBuild && serverOutDir && (qwikRouterPlugin == null ? void 0 : qwikRouterPlugin.api) && (qwikVitePlugin == null ? void 0 : qwikVitePlugin.api)) {
205
- const staticPaths = opts.staticPaths || [];
206
- const routes = qwikRouterPlugin.api.getRoutes();
207
- const basePathname = qwikRouterPlugin.api.getBasePathname();
208
- const clientOutDir = qwikVitePlugin.api.getClientOutDir();
209
- const clientPublicOutDir = qwikVitePlugin.api.getClientPublicOutDir();
210
- const assetsDir = qwikVitePlugin.api.getAssetsDir();
211
- const rootDir = qwikVitePlugin.api.getRootDir() ?? void 0;
212
- if (opts.ssg !== null && renderModulePath && qwikRouterConfigModulePath && clientOutDir && clientPublicOutDir) {
213
- let ssgOrigin = ((_a = opts.ssg) == null ? void 0 : _a.origin) ?? opts.origin;
214
- if (!ssgOrigin) {
215
- ssgOrigin = `https://yoursite.qwik.dev`;
216
- }
217
- if (ssgOrigin.length > 0 && !/:\/\//.test(ssgOrigin)) {
218
- ssgOrigin = `https://${ssgOrigin}`;
219
- }
220
- if (ssgOrigin.startsWith("//")) {
221
- ssgOrigin = `https:${ssgOrigin}`;
222
- }
223
- try {
224
- ssgOrigin = new URL(ssgOrigin).origin;
225
- } catch {
226
- this.warn(
227
- `Invalid "origin" option: "${ssgOrigin}". Using default origin: "https://yoursite.qwik.dev"`
228
- );
229
- ssgOrigin = `https://yoursite.qwik.dev`;
230
- }
231
- const staticGenerate = await import("../../../ssg/index.mjs");
232
- const generateOpts = {
233
- maxWorkers: opts.maxWorkers,
234
- basePathname,
235
- outDir: clientPublicOutDir,
236
- rootDir,
237
- ...opts.ssg,
238
- origin: ssgOrigin,
239
- renderModulePath,
240
- qwikRouterConfigModulePath
241
- };
242
- const staticGenerateResult = await staticGenerate.generate(generateOpts);
243
- if (staticGenerateResult.errors > 0) {
244
- const err = new Error(
245
- `Error while running SSG from "${opts.name}" adapter. At least one path failed to render.`
246
- );
247
- err.stack = void 0;
248
- this.error(err);
249
- }
250
- staticPaths.push(...staticGenerateResult.staticPaths);
251
- }
252
- await postBuild(
253
- clientPublicOutDir,
254
- serverOutDir,
255
- assetsDir ? join2(basePathname, assetsDir) : basePathname,
256
- staticPaths,
257
- !!opts.cleanStaticGenerated
258
- );
259
- if (typeof opts.generate === "function") {
260
- await opts.generate({
261
- outputEntries,
262
- serverOutDir,
263
- clientOutDir,
264
- clientPublicOutDir,
265
- basePathname,
266
- routes,
267
- assetsDir,
268
- warn: (message) => this.warn(message),
269
- error: (message) => this.error(message)
270
- });
271
- }
272
- this.warn(
273
- `
274
- ==============================================
275
- Note: Make sure that you are serving the built files with proper cache headers.
276
- See https://qwik.dev/docs/deployments/#cache-headers for more information.
277
- ==============================================`
278
- );
279
- }
280
- }
281
- }
282
- };
283
- return plugin;
83
+ let qwikRouterPlugin = null;
84
+ let qwikVitePlugin = null;
85
+ let viteCommand;
86
+ let buildAppRan = false;
87
+ const outputEntries = [];
88
+ const ssgOutDirFor = (root) => join(resolve(root), "node_modules", ".cache", `qwik-router-ssg-${process.pid}`);
89
+ return [{
90
+ name: `vite-plugin-qwik-router-ssg-${opts.name}`,
91
+ enforce: "post",
92
+ apply: "build",
93
+ config(config) {
94
+ if (typeof opts.config === "function") config = opts.config(config);
95
+ config.define = {
96
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || "production"),
97
+ ...config.define
98
+ };
99
+ config.builder ??= {};
100
+ if (opts.ssg !== null) config.environments = {
101
+ ...config.environments,
102
+ ssg: {
103
+ consumer: "server",
104
+ build: {
105
+ ssr: true,
106
+ outDir: ssgOutDirFor(config.root ?? process.cwd()),
107
+ emptyOutDir: true,
108
+ minify: false,
109
+ sourcemap: false
110
+ }
111
+ }
112
+ };
113
+ return config;
114
+ },
115
+ configEnvironment(name, environmentOptions) {
116
+ if (name === "ssg") environmentOptions.build = {
117
+ ...environmentOptions.build,
118
+ rolldownOptions: {
119
+ ...environmentOptions.build?.rolldownOptions,
120
+ input: {}
121
+ }
122
+ };
123
+ },
124
+ configResolved(config) {
125
+ viteCommand = config.command;
126
+ qwikRouterPlugin = config.plugins.find((p) => p.name === "vite-plugin-qwik-router");
127
+ if (!qwikRouterPlugin) throw new Error("Missing vite-plugin-qwik-router");
128
+ qwikRouterPlugin.api?._setSsgRoutes?.(opts.ssg?.include, opts.ssg?.exclude);
129
+ qwikVitePlugin = config.plugins.find((p) => p.name === "vite-plugin-qwik");
130
+ if (!qwikVitePlugin) throw new Error("Missing vite-plugin-qwik");
131
+ },
132
+ resolveId(id) {
133
+ if (id === QWIK_SSG_ENTRY_ID) return QWIK_SSG_ENTRY_RESOLVED;
134
+ if (id === QWIK_SSG_WORKER_ENTRY_ID) return QWIK_SSG_WORKER_ENTRY_RESOLVED;
135
+ },
136
+ load(id) {
137
+ if (id === QWIK_SSG_WORKER_ENTRY_RESOLVED) {
138
+ const { srcDir } = qwikVitePlugin.api.getOptions();
139
+ return [
140
+ `import render from '${srcDir}/entry.ssr';`,
141
+ `import qwikRouterConfig from '@qwik-router-config';`,
142
+ `import { startWorker } from '@qwik.dev/router/ssg';`,
143
+ `startWorker({ render, qwikRouterConfig }).catch((err) => {`,
144
+ ` console.error(err);`,
145
+ ` process.exit(1);`,
146
+ `});`
147
+ ].join("\n");
148
+ }
149
+ if (id !== QWIK_SSG_ENTRY_RESOLVED) return;
150
+ const clientPublicOutDir = qwikVitePlugin.api.getClientPublicOutDir();
151
+ const basePathname = qwikRouterPlugin.api.getBasePathname();
152
+ const rootDir = qwikVitePlugin.api.getRootDir() ?? void 0;
153
+ let ssgOrigin = opts.ssg?.origin ?? opts.origin;
154
+ if (!ssgOrigin) ssgOrigin = `https://yoursite.qwik.dev`;
155
+ if (ssgOrigin.length > 0 && !/:\/\//.test(ssgOrigin)) ssgOrigin = `https://${ssgOrigin}`;
156
+ if (ssgOrigin.startsWith("//")) ssgOrigin = `https:${ssgOrigin}`;
157
+ try {
158
+ ssgOrigin = new URL(ssgOrigin).origin;
159
+ } catch {
160
+ this.warn(`Invalid "origin" option: "${ssgOrigin}". Using default origin: "https://yoursite.qwik.dev"`);
161
+ ssgOrigin = `https://yoursite.qwik.dev`;
162
+ }
163
+ const ssgOpts = {
164
+ origin: ssgOrigin,
165
+ outDir: clientPublicOutDir,
166
+ basePathname,
167
+ rootDir,
168
+ ...opts.ssg,
169
+ maxWorkers: opts.maxWorkers ?? opts.ssg?.maxWorkers
170
+ };
171
+ for (const key of Object.keys(ssgOpts)) if (ssgOpts[key] === void 0) delete ssgOpts[key];
172
+ return [
173
+ `import qwikRouterConfig from '@qwik-router-config';`,
174
+ `import { runSsg } from '@qwik.dev/router/ssg';`,
175
+ ``,
176
+ `const ssgOpts = ${JSON.stringify(ssgOpts)};`,
177
+ ``,
178
+ `// Parse --quiet / --debug CLI flags`,
179
+ `const args = process.argv.slice(2);`,
180
+ `if (args.includes('--quiet')) ssgOpts.log = 'quiet';`,
181
+ `if (args.includes('--debug')) ssgOpts.log = 'debug';`,
182
+ ``,
183
+ `runSsg({`,
184
+ ` qwikRouterConfig,`,
185
+ ` workerFilePath: new URL('./run-ssg-worker.js', import.meta.url).href,`,
186
+ ` ...ssgOpts,`,
187
+ `}).catch((err) => {`,
188
+ ` console.error(err);`,
189
+ ` process.exit(1);`,
190
+ `});`
191
+ ].join("\n");
192
+ },
193
+ buildStart() {
194
+ if (this.environment.name === "ssg" && viteCommand === "build") {
195
+ this.emitFile({
196
+ id: QWIK_SSG_ENTRY_ID,
197
+ type: "chunk",
198
+ fileName: "run-ssg.js"
199
+ });
200
+ this.emitFile({
201
+ id: QWIK_SSG_WORKER_ENTRY_ID,
202
+ type: "chunk",
203
+ fileName: "run-ssg-worker.js"
204
+ });
205
+ }
206
+ },
207
+ generateBundle(_, bundles) {
208
+ if (this.environment.name === "ssr") {
209
+ outputEntries.length = 0;
210
+ for (const fileName in bundles) {
211
+ const chunk = bundles[fileName];
212
+ if (chunk.type === "chunk" && chunk.isEntry) outputEntries.push(fileName);
213
+ }
214
+ if (opts.ssg !== null && viteCommand === "build" && !buildAppRan) this.warn("Qwik Router SSG was skipped: the `ssr` environment was built directly instead of through the Vite app builder, so no pages were prerendered. Build with the Qwik CLI or `createBuilder(config).buildApp()` (a plain `vite build` does this automatically).");
215
+ }
216
+ },
217
+ async buildApp(builder) {
218
+ buildAppRan = true;
219
+ const ssr = builder.environments.ssr;
220
+ if (ssr) await builder.build(ssr);
221
+ const serverOutDir = ssr?.config.build.outDir;
222
+ if (!serverOutDir || !qwikRouterPlugin?.api || !qwikVitePlugin?.api) return;
223
+ const log = builder.config.logger;
224
+ const staticPaths = opts.staticPaths || [];
225
+ const routes = qwikRouterPlugin.api.getRoutes();
226
+ const basePathname = qwikRouterPlugin.api.getBasePathname();
227
+ const clientOutDir = qwikVitePlugin.api.getClientOutDir();
228
+ const clientPublicOutDir = qwikVitePlugin.api.getClientPublicOutDir();
229
+ const noTrailingSlash = builder.config.define?.["globalThis.__NO_TRAILING_SLASH__"] === "true";
230
+ const ssgEnv = builder.environments.ssg;
231
+ const ssgOutDir = ssgOutDirFor(builder.config.root);
232
+ if (ssgEnv && clientOutDir && clientPublicOutDir) {
233
+ await builder.build(ssgEnv);
234
+ const runSsgPath = join(ssgOutDir, "run-ssg.js");
235
+ if (await new Promise((res, reject) => {
236
+ const child = spawn(process.execPath, [runSsgPath], {
237
+ stdio: [
238
+ "ignore",
239
+ "inherit",
240
+ "inherit"
241
+ ],
242
+ env: {
243
+ ...process.env,
244
+ NODE_ENV: process.env.NODE_ENV || "production"
245
+ }
246
+ });
247
+ child.on("close", res);
248
+ child.on("error", reject);
249
+ }) !== 0) throw new Error(`Error while running SSG from "${opts.name}" adapter. At least one path failed to render.`);
250
+ const staticPathsFile = join(clientPublicOutDir, "_static-paths.json");
251
+ try {
252
+ staticPaths.push(...JSON.parse(await readFile(staticPathsFile, "utf-8")));
253
+ await unlink(staticPathsFile);
254
+ } catch {}
255
+ if (process.env.QWIK_ROUTER_KEEP_SSG_BUILD) log.warn(`SSG build kept at ${ssgOutDir}`);
256
+ else await rm(ssgOutDir, {
257
+ recursive: true,
258
+ force: true
259
+ });
260
+ }
261
+ await postBuild(clientPublicOutDir, serverOutDir, basePathname, staticPaths, !!opts.cleanStaticGenerated, noTrailingSlash);
262
+ if (typeof opts.generate === "function") await opts.generate({
263
+ outputEntries,
264
+ serverOutDir,
265
+ clientOutDir,
266
+ clientPublicOutDir,
267
+ basePathname,
268
+ routes,
269
+ warn: (message) => log.warn(message),
270
+ error: (message) => {
271
+ throw new Error(message);
272
+ }
273
+ });
274
+ log.warn("\n==============================================\nNote: Make sure that you are serving the built files with proper cache headers.\nSee https://qwik.dev/docs/deployments/#cache-headers for more information.\n==============================================");
275
+ }
276
+ }];
284
277
  }
278
+ /** @public */
285
279
  function getParentDir(startDir, dirName) {
286
- const root = resolve("/");
287
- let dir = startDir;
288
- for (let i = 0; i < 20; i++) {
289
- dir = dirname(dir);
290
- if (basename(dir) === dirName) {
291
- return dir;
292
- }
293
- if (dir === root) {
294
- break;
295
- }
296
- }
297
- throw new Error(`Unable to find "${dirName}" directory from "${startDir}"`);
280
+ const root = resolve("/");
281
+ let dir = startDir;
282
+ for (let i = 0; i < 20; i++) {
283
+ dir = dirname(dir);
284
+ if (basename(dir) === dirName) return dir;
285
+ if (dir === root) break;
286
+ }
287
+ throw new Error(`Unable to find "${dirName}" directory from "${startDir}"`);
298
288
  }
299
- export {
300
- getParentDir,
301
- viteAdapter
302
- };
289
+ export { getParentDir, viteAdapter };