@docusaurus/core 4.0.0-canary-7041 → 4.0.0-canary-7078

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.
@@ -12,6 +12,7 @@ import siteConfig from '@generated/docusaurus.config';
12
12
  import ExecutionEnvironment from './exports/ExecutionEnvironment';
13
13
  import App from './App';
14
14
  import preload from './preload';
15
+ import { normalizeBrowserPathname } from './normalizeLocation';
15
16
  import docusaurus from './docusaurus';
16
17
  function Router({ children }) {
17
18
  return siteConfig.future.experimental_router === 'hash' ? (<HashRouter>{children}</HashRouter>) : (<BrowserRouter>{children}</BrowserRouter>);
@@ -46,7 +47,10 @@ if (ExecutionEnvironment.canUseDOM) {
46
47
  window.docusaurusRoot = root;
47
48
  }
48
49
  };
49
- preload(window.location.pathname).then(() => {
50
+ // Normalize /page.html to /page, the route App renders: preloading
51
+ // /page.html would hydrate an empty route and render the page twice
52
+ // See https://github.com/meta/docusaurus/pull/12810
53
+ preload(normalizeBrowserPathname(window.location.pathname)).then(() => {
50
54
  startTransition(renderApp);
51
55
  });
52
56
  // Webpack Hot Module Replacement API
@@ -6,3 +6,4 @@
6
6
  */
7
7
  import type { Location } from 'history';
8
8
  export default function normalizeLocation<T extends Location>(location: T): T;
9
+ export declare function normalizeBrowserPathname(browserPathname: string): string;
@@ -8,24 +8,32 @@ import { matchRoutes } from 'react-router-config';
8
8
  import routes from '@generated/routes';
9
9
  // Memoize previously normalized pathnames.
10
10
  const pathnames = new Map();
11
- export default function normalizeLocation(location) {
12
- if (pathnames.has(location.pathname)) {
13
- return {
14
- ...location,
15
- pathname: pathnames.get(location.pathname),
16
- };
17
- }
11
+ function computeNormalizedPathname(pathname) {
18
12
  // If the location was registered with an `.html` extension, we don't strip it
19
13
  // away, or it will render to a 404 page.
20
- const matchedRoutes = matchRoutes(routes, location.pathname);
14
+ const matchedRoutes = matchRoutes(routes, pathname);
21
15
  if (matchedRoutes.some(({ route }) => route.exact === true)) {
22
- pathnames.set(location.pathname, location.pathname);
23
- return location;
16
+ return pathname;
17
+ }
18
+ return pathname.trim().replace(/(?:\/index)?\.html$/, '') || '/';
19
+ }
20
+ function normalizePathname(pathname) {
21
+ let normalizedPathname = pathnames.get(pathname);
22
+ if (normalizedPathname === undefined) {
23
+ normalizedPathname = computeNormalizedPathname(pathname);
24
+ pathnames.set(pathname, normalizedPathname);
24
25
  }
25
- const pathname = location.pathname.trim().replace(/(?:\/index)?\.html$/, '') || '/';
26
- pathnames.set(location.pathname, pathname);
26
+ return normalizedPathname;
27
+ }
28
+ export default function normalizeLocation(location) {
27
29
  return {
28
30
  ...location,
29
- pathname,
31
+ pathname: normalizePathname(location.pathname),
30
32
  };
31
33
  }
34
+ // The router decodes the browser pathname before App normalizes it. Encode it
35
+ // back for preload(), which decodes again and throws on /100%25 if not encoded
36
+ export function normalizeBrowserPathname(browserPathname) {
37
+ const routerPathname = decodeURI(browserPathname);
38
+ return encodeURI(normalizePathname(routerPathname));
39
+ }
@@ -7,7 +7,7 @@
7
7
  import type http from 'node:http';
8
8
  import type { DocusaurusConfig } from '@docusaurus/types';
9
9
  type ServeRequestHandler = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;
10
- export declare function createServeRequestHandler({ outDir, baseUrl, trailingSlash, }: {
10
+ export declare function createServeRequestHandler({ outDir, baseUrl: configBaseUrl, trailingSlash, }: {
11
11
  outDir: string;
12
12
  } & Pick<DocusaurusConfig, 'baseUrl' | 'trailingSlash'>): ServeRequestHandler;
13
13
  export {};
@@ -8,16 +8,43 @@
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.createServeRequestHandler = createServeRequestHandler;
10
10
  const tslib_1 = require("tslib");
11
+ const node_path_1 = tslib_1.__importDefault(require("node:path"));
11
12
  const serve_handler_1 = tslib_1.__importDefault(require("serve-handler"));
13
+ const fs_1 = require("@docusaurus/fs");
12
14
  const utils_common_1 = require("@docusaurus/utils-common");
13
- function createServeRequestHandler({ outDir, baseUrl, trailingSlash, }) {
15
+ const utils_1 = require("@docusaurus/utils");
16
+ function createServeRequestHandler({ outDir, baseUrl: configBaseUrl, trailingSlash, }) {
17
+ // Browsers send the baseUrl percent-encoded, like "/caf%C3%A9/"
18
+ // A baseUrl already percent-encoded in the config stays the same
19
+ const baseUrl = (0, utils_1.parseURLPath)(configBaseUrl).pathname;
14
20
  return async (req, res) => {
15
- const redirectLocation = getRedirectLocation(req.url, {
21
+ // Browsers must revalidate every response, so that a rebuild or a config
22
+ // change never leaves a stale page or redirect in their cache
23
+ // Set here because serve-handler doesn't apply `headers` to its redirects
24
+ // See https://github.com/meta/docusaurus/pull/12903
25
+ res.setHeader('Cache-Control', 'no-cache');
26
+ // Automatically redirect requests to /baseUrl/
27
+ // Temporary: this redirect only exists in docusaurus serve, not on hosts
28
+ if (!req.url?.startsWith(baseUrl)) {
29
+ redirect(res, 302, baseUrl);
30
+ return;
31
+ }
32
+ // serve-handler answers 500 to null bytes, its file system calls throw
33
+ // Answer 400 instead, like serve-handler does to malformed encodings
34
+ if (hasNullByte(req.url)) {
35
+ res.writeHead(400);
36
+ res.end('Bad Request');
37
+ return;
38
+ }
39
+ const redirectLocation = await getRedirectLocation(req.url, {
40
+ outDir,
16
41
  baseUrl,
17
42
  trailingSlash,
18
43
  });
19
44
  if (redirectLocation !== undefined) {
20
- redirect(res, redirectLocation);
45
+ // Permanent, like the serve-handler redirects and most static hosts
46
+ // See https://github.com/meta/docusaurus/pull/12907
47
+ redirect(res, 301, redirectLocation);
21
48
  return;
22
49
  }
23
50
  // Remove baseUrl before calling serveHandler, because /baseUrl/ should
@@ -28,40 +55,183 @@ function createServeRequestHandler({ outDir, baseUrl, trailingSlash, }) {
28
55
  // See also https://github.com/meta/docusaurus/pull/10090
29
56
  // Requests without url were redirected to the baseUrl
30
57
  req.url = req.url.replace(baseUrl, '/');
58
+ // serve-handler can't serve these pages: cleanUrls would redirect them
59
+ req.url = (await getHtmlPathPageFileUrl(outDir, req.url)) ?? req.url;
31
60
  await (0, serve_handler_1.default)(req, res, {
32
- cleanUrls: true,
61
+ // cleanUrls serves /file with file.html, but also redirects /file.html
62
+ // to /file, even when the file exists, and drops the baseUrl
63
+ // We already did our clean URL redirects: only existing .html files and
64
+ // paths with an encoded ".html" or "/index" get there
65
+ // See https://github.com/meta/docusaurus/pull/12916
66
+ cleanUrls: !hasCleanUrlSuffix(req.url),
33
67
  public: outDir,
34
- trailingSlash,
68
+ // We do the trailing slash redirects: serve-handler would decode
69
+ // encoded slashes, merge them and drop the baseUrl
70
+ trailingSlash: undefined,
35
71
  directoryListing: false,
72
+ // serve-handler only answers 304 to an ETag revalidation, and the ETag
73
+ // stays the same when a rebuild doesn't change the file content
74
+ etag: true,
75
+ headers: [
76
+ // The default value has the file name, which crashes Node.js when it
77
+ // has Latin-1 characters like "café.html"
78
+ // See https://github.com/vercel/serve-handler/issues/205
79
+ {
80
+ source: '**',
81
+ headers: [{ key: 'Content-Disposition', value: 'inline' }],
82
+ },
83
+ // The bundler adds a content hash to the names of these files
84
+ // Overrides the Cache-Control set above, only for existing files
85
+ {
86
+ source: 'assets/**',
87
+ headers: [
88
+ {
89
+ key: 'Cache-Control',
90
+ value: 'public, max-age=31536000, immutable',
91
+ },
92
+ ],
93
+ },
94
+ ],
36
95
  });
37
96
  };
38
97
  }
39
- function getRedirectLocation(url, { baseUrl, trailingSlash }) {
40
- // Automatically redirect requests to /baseUrl/
41
- if (!url?.startsWith(baseUrl)) {
42
- return baseUrl;
43
- }
44
- // We do the redirect ourselves for a good reason
45
- // server-handler is annoying and won't include /baseUrl/ in redirects
98
+ async function getRedirectLocation(url, { outDir, baseUrl, trailingSlash, }) {
99
+ // We do all the redirects ourselves for a good reason
100
+ // serve-handler redirects drop the /baseUrl/ and the query string
46
101
  // See https://github.com/meta/docusaurus/issues/10078#issuecomment-2084932934
47
- if (baseUrl !== '/') {
48
- // Not super robust, but should be good enough for our use case
49
- // See https://github.com/meta/docusaurus/pull/10090
50
- const looksLikeAsset = !!url.match(/\.[a-z\d]{1,4}$/i);
51
- if (!looksLikeAsset) {
52
- const normalizedUrl = (0, utils_common_1.applyTrailingSlash)(url, {
53
- trailingSlash,
54
- baseUrl,
55
- });
56
- if (url !== normalizedUrl) {
57
- return normalizedUrl;
58
- }
102
+ const urlPath = parseRootURLPath(url);
103
+ // ".." can resolve outside of the baseUrl
104
+ // Like serve-handler, answer 400 to these paths
105
+ if (!urlPath?.pathname.startsWith(baseUrl)) {
106
+ return undefined;
107
+ }
108
+ const { pathname, search } = urlPath;
109
+ // Merge repeated slashes, like the serve-handler redirects
110
+ const mergedPathname = pathname.replace(/\/{2,}/g, '/');
111
+ if (pathname !== mergedPathname) {
112
+ return (0, utils_1.serializeURLPath)({ pathname: mergedPathname, search });
113
+ }
114
+ // Static hosts serve the existing .html files, without clean URL redirects
115
+ const outDirUrl = url.slice(baseUrl.length - 1);
116
+ if (await isHtmlFileRequest(outDir, outDirUrl)) {
117
+ return undefined;
118
+ }
119
+ const isHtmlPathPage = (await getHtmlPathPageFileUrl(outDir, outDirUrl)) !== undefined;
120
+ const cleanPathname = getCleanPathname(pathname, baseUrl);
121
+ if (!isHtmlPathPage && pathname !== cleanPathname) {
122
+ return (0, utils_1.serializeURLPath)({ pathname: cleanPathname, search });
123
+ }
124
+ // Not super robust, but should be good enough for our use case
125
+ // See https://github.com/meta/docusaurus/pull/10090
126
+ const looksLikeAsset = !!pathname.match(/\.[a-z\d]+$/i);
127
+ const isAsset = looksLikeAsset &&
128
+ !(await isPage(outDir, pathname.slice(baseUrl.length - 1)));
129
+ if (!isAsset) {
130
+ const normalizedPathname = (0, utils_common_1.applyTrailingSlash)(pathname, {
131
+ trailingSlash,
132
+ baseUrl,
133
+ });
134
+ if (pathname !== normalizedPathname) {
135
+ return (0, utils_1.serializeURLPath)({ pathname: normalizedPathname, search });
59
136
  }
60
137
  }
61
138
  return undefined;
62
139
  }
63
- function redirect(res, location) {
64
- res.writeHead(302, {
140
+ // Like parseURLPath(), but undefined when ".." segments go above the root
141
+ // It also keeps "//host/path" as a path instead of parsing another host
142
+ function parseRootURLPath(url) {
143
+ // ".." segments going above the root can reach the name of a fake root,
144
+ // like "/../__docusaurus_root__/file", but not the names of 2 fake roots
145
+ const urlPath = parseFakeRootURLPath(url, '/__docusaurus_root__');
146
+ const otherUrlPath = parseFakeRootURLPath(url, '/__docusaurus_other_root__');
147
+ if (urlPath === undefined || otherUrlPath === undefined) {
148
+ return undefined;
149
+ }
150
+ return urlPath;
151
+ }
152
+ function parseFakeRootURLPath(url, fakeRoot) {
153
+ const { pathname, search } = (0, utils_1.parseURLPath)(`.${url}`, `${fakeRoot}/`);
154
+ if (!pathname.startsWith(`${fakeRoot}/`)) {
155
+ return undefined;
156
+ }
157
+ return { pathname: pathname.slice(fakeRoot.length), search };
158
+ }
159
+ // Like serve-handler, only the pathname is decoded, not the query string
160
+ function hasNullByte(url) {
161
+ const pathname = url.split(/[?#]/)[0];
162
+ return pathname.includes('%00');
163
+ }
164
+ // The page of a .html path that isn't a file, like the client redirect files
165
+ // "old-page.html/index.html", or "old-page.html.html" with trailingSlash false
166
+ // See https://github.com/meta/docusaurus/pull/12920
167
+ async function getHtmlPathPageFileUrl(outDir, url) {
168
+ const pathname = url.split(/[?#]/)[0];
169
+ if (!pathname.endsWith('.html')) {
170
+ return undefined;
171
+ }
172
+ const queryAndHash = url.slice(pathname.length);
173
+ const pageFileUrls = [`${pathname}/index.html`, `${pathname}.html`];
174
+ for (const pageFileUrl of pageFileUrls) {
175
+ if (await isHtmlFileRequest(outDir, pageFileUrl)) {
176
+ return pageFileUrl + queryAndHash;
177
+ }
178
+ }
179
+ return undefined;
180
+ }
181
+ // The decoded paths that serve-handler's cleanUrls redirects
182
+ function hasCleanUrlSuffix(url) {
183
+ const pathname = url.split(/[?#]/)[0];
184
+ try {
185
+ return /(?:\.html|\/index)$/.test(decodeURIComponent(pathname));
186
+ }
187
+ catch {
188
+ return false; // Malformed percent-encoding, serve-handler answers 400
189
+ }
190
+ }
191
+ // Pages with a dot in their name look like assets, like "docs/2.x"
192
+ async function isPage(outDir, urlPath) {
193
+ const filePath = getFilePath(outDir, urlPath);
194
+ if (filePath === undefined) {
195
+ return false;
196
+ }
197
+ return ((await (0, fs_1.pathExists)(node_path_1.default.join(filePath, 'index.html'))) ||
198
+ (0, fs_1.pathExists)(`${filePath}.html`));
199
+ }
200
+ // The url without the baseUrl, like serve-handler receives it
201
+ async function isHtmlFileRequest(outDir, url) {
202
+ // Like serve-handler, decode the path before resolving its ".." segments:
203
+ // parseURLPath() resolves "/folder%2Fx/../file.html" to "/file.html"
204
+ const pathname = url.split(/[?#]/)[0];
205
+ const filePath = getFilePath(outDir, pathname);
206
+ if (!filePath?.endsWith('.html')) {
207
+ return false;
208
+ }
209
+ // Not a folder, like the client redirect file "old-page.html/index.html"
210
+ const stats = await fs_1.fs.stat(filePath).catch(() => undefined);
211
+ return stats?.isFile() ?? false;
212
+ }
213
+ function getFilePath(outDir, urlPath) {
214
+ let filePath;
215
+ try {
216
+ filePath = node_path_1.default.join(outDir, decodeURIComponent(urlPath));
217
+ }
218
+ catch {
219
+ return undefined; // Malformed percent-encoding
220
+ }
221
+ // Encoded slashes can decode to ".." segments: never look outside outDir
222
+ if (node_path_1.default.relative(outDir, filePath).startsWith('..')) {
223
+ return undefined;
224
+ }
225
+ return filePath;
226
+ }
227
+ // The serve-handler cleanUrls redirect, keeping the baseUrl
228
+ function getCleanPathname(pathname, baseUrl) {
229
+ const cleanPathname = pathname.replace(/(?:\.html|\/index)$/, '');
230
+ // Like serve-handler, /index redirects to /
231
+ return cleanPathname === baseUrl.slice(0, -1) ? baseUrl : cleanPathname;
232
+ }
233
+ function redirect(res, statusCode, location) {
234
+ res.writeHead(statusCode, {
65
235
  Location: location,
66
236
  });
67
237
  res.end();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@docusaurus/core",
3
3
  "description": "Easy to Maintain Open Source Documentation Websites",
4
- "version": "4.0.0-canary-7041",
4
+ "version": "4.0.0-canary-7078",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -27,15 +27,15 @@
27
27
  "url": "https://github.com/meta/docusaurus/issues"
28
28
  },
29
29
  "dependencies": {
30
- "@docusaurus/babel": "4.0.0-canary-7041",
31
- "@docusaurus/bundler": "4.0.0-canary-7041",
32
- "@docusaurus/fs": "4.0.0-canary-7041",
33
- "@docusaurus/glob": "4.0.0-canary-7041",
34
- "@docusaurus/logger": "4.0.0-canary-7041",
35
- "@docusaurus/mdx-loader": "4.0.0-canary-7041",
36
- "@docusaurus/utils": "4.0.0-canary-7041",
37
- "@docusaurus/utils-common": "4.0.0-canary-7041",
38
- "@docusaurus/utils-validation": "4.0.0-canary-7041",
30
+ "@docusaurus/babel": "4.0.0-canary-7078",
31
+ "@docusaurus/bundler": "4.0.0-canary-7078",
32
+ "@docusaurus/fs": "4.0.0-canary-7078",
33
+ "@docusaurus/glob": "4.0.0-canary-7078",
34
+ "@docusaurus/logger": "4.0.0-canary-7078",
35
+ "@docusaurus/mdx-loader": "4.0.0-canary-7078",
36
+ "@docusaurus/utils": "4.0.0-canary-7078",
37
+ "@docusaurus/utils-common": "4.0.0-canary-7078",
38
+ "@docusaurus/utils-validation": "4.0.0-canary-7078",
39
39
  "@rspack/core": "^2.3.0",
40
40
  "@rspack/dev-server": "^2.2.2",
41
41
  "boxen": "^9.0.0",
@@ -59,7 +59,7 @@
59
59
  "react-router-config": "^5.1.1",
60
60
  "react-router-dom": "^5.3.4",
61
61
  "semver": "^7.8.5",
62
- "serve-handler": "^6.1.7",
62
+ "serve-handler": "^6.1.8",
63
63
  "tinypool": "^2.1.2",
64
64
  "tslib": "^2.8.1",
65
65
  "update-notifier": "^7.3.1",
@@ -68,8 +68,8 @@
68
68
  "webpack-merge": "^6.0.1"
69
69
  },
70
70
  "devDependencies": {
71
- "@docusaurus/module-type-aliases": "4.0.0-canary-7041",
72
- "@docusaurus/types": "4.0.0-canary-7041",
71
+ "@docusaurus/module-type-aliases": "4.0.0-canary-7078",
72
+ "@docusaurus/types": "4.0.0-canary-7078",
73
73
  "@total-typescript/shoehorn": "^0.1.2",
74
74
  "@types/escape-html": "^1.0.4",
75
75
  "@types/history": "^4.7.11",