@qwik.dev/router 2.0.0-beta.4 → 2.0.0-beta.40

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