@qwik.dev/router 2.0.0-rc.3 → 2.0.0-rc.5

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.
@@ -269,8 +269,14 @@ function createQwikRouter(opts) {
269
269
  const handled = await requestHandler(serverRequestEv, opts);
270
270
  if (handled) {
271
271
  const err = await handled.completion;
272
+ if (err) {
273
+ if (res.headersSent && !res.writableEnded) {
274
+ res.destroy();
275
+ res.end();
276
+ }
277
+ throw err;
278
+ }
272
279
  if (handled.requestEv.headersSent) return;
273
- if (err) throw err;
274
280
  }
275
281
  next();
276
282
  } catch (e) {
@@ -103,10 +103,10 @@ declare type CacheControlTarget = 'Cache-Control' | 'CDN-Cache-Control' | 'Cloud
103
103
  *
104
104
  * - `true`: use the surface's default key.
105
105
  *
106
- * - SSR default: `${status}|${eTag}|${pathname}` when an eTag is set, otherwise
107
- * `${status}|${pathname}`.
108
- * - Loader default: `${pathname}|${filteredSearch}|${loaderId}|${eTag}` when an eTag is set,
109
- * otherwise `${pathname}|${filteredSearch}|${loaderId}`.
106
+ * - SSR default: `${status}|${eTag}|${origin}${pathname}` when an eTag is set, otherwise
107
+ * `${status}|${origin}${pathname}`.
108
+ * - Loader default: `${origin}${pathname}|${filteredSearch}|${loaderId}|${eTag}` when an eTag is set,
109
+ * otherwise `${origin}${pathname}|${filteredSearch}|${loaderId}`.
110
110
  * - Function: receives the request event and the normalized, unquoted eTag (or an empty string when
111
111
  * none was provided). Return the cache key string, or `null` or `''` to skip caching for this
112
112
  * request. Loader callbacks receive the loader-scoped request event, with `url`, `query`, and
@@ -849,8 +849,8 @@ export declare interface ServerRenderOptions extends RenderOptions {
849
849
  /**
850
850
  * Protection against cross-site request forgery (CSRF) attacks.
851
851
  *
852
- * When `true`, for every incoming POST, PUT, PATCH, or DELETE form submissions, the request
853
- * origin is checked to match the server's origin. `lax-proto` is for SSL-terminating proxies
852
+ * When `true`, for every incoming POST, PUT, PATCH, or DELETE request, the request origin is
853
+ * checked to match the server's origin. `lax-proto` is for SSL-terminating proxies
854
854
  *
855
855
  * Be careful when disabling this option as it may lead to CSRF attacks.
856
856
  *
@@ -1,8 +1,8 @@
1
- import { H as getRouterConfig, d as loadRoute, dt as _asyncRequestStore } from "../../chunks/head.qwik.mjs";
2
- import { c as resolveValidInternalFullPathname, l as trimInternalPathname, s as recognizeRequest, u as trimRecognizedInternalPathname } from "../../chunks/request-path.mjs";
1
+ import { G as getRouterConfig, i as loadRoute, yt as _asyncRequestStore } from "../../chunks/head.qwik.mjs";
2
+ import { c as recognizeRequest, d as trimRecognizedInternalPathname, u as trimInternalPathname } from "../../chunks/request-path.mjs";
3
3
  import { i as RedirectMessage, r as AbortMessage, t as ServerError } from "../../chunks/server-error.mjs";
4
4
  import { t as devPreloadedRouteLoaders } from "../../chunks/dev-preloaded-route-loader.mjs";
5
- import { a as getStaticPathRedirect, c as clearSsrCache, d as mergeHeadersCookies, i as resolveRequestHandlers, n as getErrorHtml, o as isStaticPath, r as renderQwikMiddleware, s as clearLoaderCache, t as runQwikRouter, u as RewriteMessage } from "../../chunks/user-response.mjs";
5
+ import { a as getStaticPathRedirect, d as mergeHeadersCookies, f as resolveLoaderPagePathname, i as resolveRequestHandlers, m as clearSsrCache, n as getErrorHtml, o as isStaticPath, p as clearLoaderCache, r as renderQwikMiddleware, t as runQwikRouter, u as RewriteMessage } from "../../chunks/user-response.mjs";
6
6
  import { isDev } from "@qwik.dev/core";
7
7
  /**
8
8
  * The request handler for QwikRouter. Called by every adapter.
@@ -34,8 +34,7 @@ function getRequestHandlerPathname(serverRequestEv, isDevRequest = isDev) {
34
34
  if (!recognized) return serverRequestEv.url.pathname;
35
35
  const loaderPathname = trimRecognizedInternalPathname(serverRequestEv.url.pathname, recognized);
36
36
  if (recognized.type !== "@isQLoader") return loaderPathname;
37
- const routePath = serverRequestEv.request.headers.get("X-Qwik-fullpath") ?? (isDevRequest ? serverRequestEv.request.headers.get("X-Qwik-route-path") : null);
38
- return resolveValidInternalFullPathname(loaderPathname, routePath) ?? loaderPathname;
37
+ return resolveLoaderPagePathname(serverRequestEv.request, loaderPathname, isDevRequest) ?? loaderPathname;
39
38
  }
40
39
  async function loadRequestHandlers(qwikRouterConfig, pathname, method, opts, serverRequestEv) {
41
40
  const { routes, serverPlugins, cacheModules } = qwikRouterConfig;
@@ -67,6 +67,12 @@ export declare interface SsgRenderOptions extends RenderOptions {
67
67
  maxWorkers?: number;
68
68
  /** Maximum number of tasks to be running at one time per worker. Defaults to `20`. */
69
69
  maxTasksPerWorker?: number;
70
+ /**
71
+ * Number of times to retry a route whose render failed or timed out, or an `onStaticGenerate`
72
+ * call that threw, before recording the error. Each retry waits 500ms, doubling up to 2s, plus up
73
+ * to 30% at random. Defaults to `0` (the first failure is final).
74
+ */
75
+ retries?: number;
70
76
  /**
71
77
  * File system path to write the `sitemap.xml` to. Defaults to `sitemap.xml` and written to the
72
78
  * root of the `outDir`. Setting to `null` will prevent the sitemap from being created.
@@ -114,6 +120,7 @@ export declare interface StaticGenerateResult {
114
120
  duration: number;
115
121
  rendered: number;
116
122
  errors: number;
123
+ retried: number;
117
124
  staticPaths: string[];
118
125
  }
119
126
 
package/lib/ssg/index.mjs CHANGED
@@ -12,6 +12,18 @@ async function mainThread(sys) {
12
12
  log.info("\n" + bold(green("Starting Qwik Router SSG...")));
13
13
  const qwikRouterConfig = opts.qwikRouterConfig;
14
14
  const renderTimeout = 3e4;
15
+ const maxRetries = opts.retries ?? 0;
16
+ const failedAttempts = /* @__PURE__ */ new Map();
17
+ const callWithRetries = async (label, call) => {
18
+ for (let attempt = 1;; attempt++) try {
19
+ return await call();
20
+ } catch (e) {
21
+ if (attempt > maxRetries) throw e;
22
+ const reason = e instanceof Error ? e.message : String(e);
23
+ log.warn(`Retrying ${label} after it failed (${attempt} of ${maxRetries}): ${reason}`);
24
+ await new Promise((resolve) => setTimeout(resolve, getRetryDelay(attempt)));
25
+ }
26
+ };
15
27
  const queue = [];
16
28
  const active = /* @__PURE__ */ new Set();
17
29
  const routes = qwikRouterConfig.routes;
@@ -24,6 +36,7 @@ async function mainThread(sys) {
24
36
  duration: 0,
25
37
  rendered: 0,
26
38
  errors: 0,
39
+ retried: 0,
27
40
  staticPaths: []
28
41
  };
29
42
  let isCompleted = false;
@@ -34,6 +47,7 @@ async function mainThread(sys) {
34
47
  if (generatorResult.errors === 0) {
35
48
  log.info(`\n${green("SSG results")}`);
36
49
  if (generatorResult.rendered > 0) log.info(`- Generated: ${dim(`${generatorResult.rendered} page${generatorResult.rendered === 1 ? "" : "s"}`)}`);
50
+ if (generatorResult.retried > 0) log.info(`- Retried: ${dim(`${generatorResult.retried} route${generatorResult.retried === 1 ? "" : "s"}`)}`);
37
51
  log.info(`- Duration: ${dim(msToString(generatorResult.duration))}`);
38
52
  const total = generatorResult.rendered + generatorResult.errors;
39
53
  if (total > 0) log.info(`- Average: ${dim(msToString(generatorResult.duration / total) + " per page")}`);
@@ -67,6 +81,17 @@ async function mainThread(sys) {
67
81
  });
68
82
  }
69
83
  };
84
+ const hasRetriesLeft = (staticRoute) => (failedAttempts.get(staticRoute.pathname) ?? 0) < maxRetries;
85
+ const retryLater = (staticRoute, reason) => {
86
+ const attempt = (failedAttempts.get(staticRoute.pathname) ?? 0) + 1;
87
+ failedAttempts.set(staticRoute.pathname, attempt);
88
+ if (attempt === 1) generatorResult.retried++;
89
+ log.warn(`Retrying ${magenta(staticRoute.pathname)} after a failed render (${attempt} of ${maxRetries}): ${reason}`);
90
+ setTimeout(() => {
91
+ queue.push(staticRoute);
92
+ next();
93
+ }, getRetryDelay(attempt));
94
+ };
70
95
  const render = async (staticRoute) => {
71
96
  try {
72
97
  active.add(staticRoute.pathname);
@@ -74,9 +99,27 @@ async function mainThread(sys) {
74
99
  const result = await Promise.race([main.render({
75
100
  type: "render",
76
101
  ...staticRoute
77
- }), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error(`SSG render timed out after ${renderTimeout}ms`)), renderTimeout))]);
78
- active.delete(staticRoute.pathname);
102
+ }), new Promise((resolve) => setTimeout(() => resolve(void 0), renderTimeout))]);
79
103
  log.debug(`render done: ${staticRoute.pathname}`);
104
+ if (!result) {
105
+ const timeoutMessage = `SSG render timed out after ${renderTimeout}ms`;
106
+ if (!hasRetriesLeft(staticRoute)) throw new Error(timeoutMessage);
107
+ await main.restartWorker(staticRoute.pathname);
108
+ retryLater(staticRoute, timeoutMessage);
109
+ flushQueue();
110
+ return;
111
+ }
112
+ if (result.isInterrupted) {
113
+ queue.push(staticRoute);
114
+ flushQueue();
115
+ return;
116
+ }
117
+ if (result.error && hasRetriesLeft(staticRoute)) {
118
+ retryLater(staticRoute, result.error.message);
119
+ flushQueue();
120
+ return;
121
+ }
122
+ active.delete(staticRoute.pathname);
80
123
  if (result.error) {
81
124
  const err = new Error(result.error.message);
82
125
  err.stack = result.error.stack;
@@ -138,11 +181,11 @@ async function mainThread(sys) {
138
181
  else {
139
182
  const pageLoader = pageLoaders[pageLoaders.length - 1];
140
183
  if (typeof pageLoader === "function") {
141
- const pageModule = await pageLoader();
142
- if (typeof pageModule.onStaticGenerate === "function") {
143
- const staticGenerate = await pageModule.onStaticGenerate({ env: { get(key) {
184
+ const onStaticGenerate = (await pageLoader()).onStaticGenerate;
185
+ if (typeof onStaticGenerate === "function") {
186
+ const staticGenerate = await callWithRetries(`onStaticGenerate for ${magenta(originalPathname)}`, () => onStaticGenerate({ env: { get(key) {
144
187
  return sys.getEnv(key);
145
- } } });
188
+ } } }));
146
189
  if (Array.isArray(staticGenerate.params)) for (const params of staticGenerate.params) {
147
190
  const pathname = getPathnameForDynamicRoute(originalPathname, paramNames, params);
148
191
  addToQueue(pathname, params);
@@ -193,6 +236,9 @@ async function mainThread(sys) {
193
236
  }
194
237
  });
195
238
  }
239
+ function getRetryDelay(attempt) {
240
+ return Math.min(500 * 2 ** (attempt - 1), 2e3) * (1 + Math.random() * .3);
241
+ }
196
242
  function validateOptions(opts) {
197
243
  if (!opts.qwikRouterConfig) throw new Error(`Missing "qwikRouterConfig" option`);
198
244
  let siteOrigin = opts.origin;
@@ -1,14 +1,14 @@
1
1
  import { r as isSameOriginUrl, t as ensureSlash } from "../chunks/pathname.mjs";
2
- import { c as resolveValidInternalFullPathname, s as recognizeRequest, u as trimRecognizedInternalPathname } from "../chunks/request-path.mjs";
2
+ import { c as recognizeRequest, d as trimRecognizedInternalPathname, l as resolveValidInternalFullPathname } from "../chunks/request-path.mjs";
3
3
  import { t as escapeStaticTrieKey } from "../chunks/route-trie-key.mjs";
4
4
  import { n as addWarning, t as addError } from "../chunks/format.mjs";
5
5
  import { _ as normalizePath$1, a as getPathnameFromDirPath, b as parseRouteIndexName, c as isIndexModule, d as isMenuFileName, f as isModuleExt, g as isServiceWorkerName, h as isPluginModule, i as getMenuPathname, l as isLayoutModule, m as isPageModuleExt, n as createFileId, o as isEntryName, p as isPageExt, r as getExtension, s as isErrorName, t as caughtErrorName, u as isMarkdownExt, v as normalizePathKey, x as removeExtension } from "../chunks/fs.mjs";
6
6
  import { t as devPreloadedRouteLoaders } from "../chunks/dev-preloaded-route-loader.mjs";
7
7
  import { t as createRouteTester } from "../chunks/routes.mjs";
8
8
  import fs, { existsSync } from "node:fs";
9
- import path, { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
9
+ import path, { basename, dirname, extname, isAbsolute, join, posix, resolve } from "node:path";
10
10
  import { readFile } from "node:fs/promises";
11
- import { loadEnv, mergeConfig, normalizePath } from "vite";
11
+ import { build, loadEnv, mergeConfig, normalizePath } from "vite";
12
12
  import { findExports, findStaticImports, parseStaticImport } from "mlly";
13
13
  import { marked } from "marked";
14
14
  import { createHash } from "node:crypto";
@@ -1310,13 +1310,65 @@ function isFileServerFree(filePath, cache) {
1310
1310
  }
1311
1311
  return pending;
1312
1312
  }
1313
+ var CHUNK_ID_PREFIX = "\0qwik-router-sw-chunk:";
1314
+ async function bundleServiceWorkerChunks(bundle, serviceWorkerChunks, minify = false) {
1315
+ for (const swChunk of serviceWorkerChunks) {
1316
+ if (!hasChunkImports(swChunk)) continue;
1317
+ swChunk.code = await bundleAsClassicScript(swChunk.fileName, bundle, minify);
1318
+ swChunk.imports = [];
1319
+ swChunk.dynamicImports = [];
1320
+ }
1321
+ }
1322
+ function hasChunkImports(chunk) {
1323
+ return chunk.imports.length > 0 || chunk.dynamicImports.length > 0;
1324
+ }
1325
+ async function bundleAsClassicScript(entryFileName, bundle, minify) {
1326
+ const result = await build({
1327
+ configFile: false,
1328
+ envDir: false,
1329
+ publicDir: false,
1330
+ logLevel: "silent",
1331
+ plugins: [builtChunksPlugin(bundle)],
1332
+ build: {
1333
+ write: false,
1334
+ minify,
1335
+ modulePreload: false,
1336
+ reportCompressedSize: false,
1337
+ rolldownOptions: {
1338
+ input: CHUNK_ID_PREFIX + entryFileName,
1339
+ output: {
1340
+ format: "iife",
1341
+ codeSplitting: false
1342
+ }
1343
+ }
1344
+ }
1345
+ });
1346
+ return (Array.isArray(result) ? result : [result])[0].output[0].code;
1347
+ }
1348
+ function builtChunksPlugin(bundle) {
1349
+ return {
1350
+ name: "vite-plugin-qwik-router-sw-chunks",
1351
+ resolveId(source, importer) {
1352
+ if (source.startsWith(CHUNK_ID_PREFIX)) return source;
1353
+ if (!importer?.startsWith(CHUNK_ID_PREFIX)) return null;
1354
+ const importerFileName = importer.slice(22);
1355
+ const fileName = posix.join(posix.dirname(importerFileName), source);
1356
+ return bundle[fileName]?.type === "chunk" ? CHUNK_ID_PREFIX + fileName : null;
1357
+ },
1358
+ load(id) {
1359
+ if (!id.startsWith(CHUNK_ID_PREFIX)) return null;
1360
+ const output = bundle[id.slice(22)];
1361
+ return output?.type === "chunk" ? output.code : null;
1362
+ }
1363
+ };
1364
+ }
1313
1365
  function getRouteImports(routes, manifest) {
1314
1366
  const result = {};
1315
1367
  routes.forEach((route) => {
1316
1368
  const routeAndLayoutPaths = [removeExtension(route.filePath), ...route.layouts ? route.layouts.map((layout) => removeExtension(layout.filePath)) : []];
1317
1369
  const bundles = [];
1318
1370
  for (const [bundleName, bundle] of Object.entries(manifest.bundles)) if (isBundlePartOfRoute(bundle, routeAndLayoutPaths)) bundles.push(bundleName);
1319
- if (bundles.length > 0) result[route.routeName] = { dynamicImports: bundles };
1371
+ if (bundles.length > 0) result[ensureSlash(route.routeName)] = { dynamicImports: bundles };
1320
1372
  });
1321
1373
  for (const bundleName of Object.keys(manifest.bundles)) {
1322
1374
  const bundle = manifest.bundles[bundleName];
@@ -1433,6 +1485,8 @@ function parseId(originalId) {
1433
1485
  params: new URLSearchParams(queryStr)
1434
1486
  };
1435
1487
  }
1488
+ new TextEncoder();
1489
+ new TextDecoder();
1436
1490
  var supportedExtensions = [
1437
1491
  ".jpg",
1438
1492
  ".jpeg",
@@ -2477,7 +2531,7 @@ function qwikRouterPlugin(userOpts, buildContextRef) {
2477
2531
  }
2478
2532
  return null;
2479
2533
  },
2480
- generateBundle(_, bundles) {
2534
+ async generateBundle(_, bundles) {
2481
2535
  const manifest = qwikPlugin.api.getManifest();
2482
2536
  if (manifest) {
2483
2537
  const srcDir = qwikPlugin.api.getOptions().srcDir;
@@ -2485,21 +2539,10 @@ function qwikRouterPlugin(userOpts, buildContextRef) {
2485
2539
  }
2486
2540
  for (const chunk of Object.values(bundles)) if (chunk.type === "chunk" && chunk.code.includes("__LOADERS:")) chunk.code = replaceLoaderPlaceholders(chunk.code, loadersByFile);
2487
2541
  if (this.environment.config.consumer === "client") {
2488
- const entries = [...ctx.entries, ...ctx.serviceWorkers].map((entry) => {
2489
- return {
2490
- chunkFileName: entry.chunkFileName,
2491
- extensionlessFilePath: removeExtension(entry.filePath)
2492
- };
2493
- });
2494
- for (const entry of entries) for (const fileName in bundles) {
2495
- const c = bundles[fileName];
2496
- if (c.type === "chunk" && c.isDynamicEntry && c.facadeModuleId) {
2497
- const extensionlessFilePath = removeExtension(normalizePath$1(c.facadeModuleId));
2498
- if (entry.extensionlessFilePath === extensionlessFilePath) {
2499
- c.fileName = entry.chunkFileName;
2500
- continue;
2501
- }
2502
- }
2542
+ await bundleServiceWorkerChunks(bundles, ctx.serviceWorkers.map((sw) => findEntryChunk(bundles, sw.filePath)).filter((c) => !!c), this.environment.config.build.minify);
2543
+ for (const entry of [...ctx.entries, ...ctx.serviceWorkers]) {
2544
+ const c = findEntryChunk(bundles, entry.filePath);
2545
+ if (c) c.fileName = entry.chunkFileName;
2503
2546
  }
2504
2547
  }
2505
2548
  },
@@ -2511,6 +2554,10 @@ function qwikRouterPlugin(userOpts, buildContextRef) {
2511
2554
  }
2512
2555
  };
2513
2556
  }
2557
+ function findEntryChunk(bundles, filePath) {
2558
+ const extensionlessFilePath = removeExtension(filePath);
2559
+ for (const output of Object.values(bundles)) if (output.type === "chunk" && output.isDynamicEntry && output.facadeModuleId && removeExtension(normalizePath$1(output.facadeModuleId)) === extensionlessFilePath) return output;
2560
+ }
2514
2561
  async function generateServerPackageJson(outDir) {
2515
2562
  await fs.promises.mkdir(outDir, { recursive: true });
2516
2563
  const serverPackageJsonPath = join(outDir, "package.json");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@qwik.dev/router",
3
3
  "description": "The router for Qwik.",
4
- "version": "2.0.0-rc.3",
4
+ "version": "2.0.0-rc.5",
5
5
  "bugs": "https://github.com/QwikDev/qwik/issues",
6
6
  "dependencies": {
7
7
  "@azure/functions": "3.5.1",
@@ -40,8 +40,8 @@
40
40
  "tsm": "2.3.0",
41
41
  "typescript": "5.9.3",
42
42
  "uvu": "0.5.6",
43
- "vite": "8.2.1",
44
- "@qwik.dev/core": "2.0.0-rc.3"
43
+ "vite": "8.2.4",
44
+ "@qwik.dev/core": "2.0.0-rc.5"
45
45
  },
46
46
  "engines": {
47
47
  "node": "^18.17.0 || ^20.3.0 || >=21.0.0"
@@ -166,7 +166,7 @@
166
166
  "main": "./lib/index.qwik.mjs",
167
167
  "peerDependencies": {
168
168
  "vite": ">=8 <9",
169
- "@qwik.dev/core": "2.0.0-rc.3"
169
+ "@qwik.dev/core": "2.0.0-rc.5"
170
170
  },
171
171
  "publishConfig": {
172
172
  "access": "public"