This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

8
node_modules/@docusaurus/core/lib/babel/preset.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { ConfigAPI, TransformOptions } from '@babel/core';
export default function babelPresets(api: ConfigAPI): TransformOptions;

80
node_modules/@docusaurus/core/lib/babel/preset.js generated vendored Normal file
View File

@@ -0,0 +1,80 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
function getTransformOptions(isServer) {
const absoluteRuntimePath = path_1.default.dirname(require.resolve(`@babel/runtime/package.json`));
return {
// All optional newlines and whitespace will be omitted when generating code
// in compact mode
compact: true,
presets: [
isServer
? [
require.resolve('@babel/preset-env'),
{
targets: {
node: 'current',
},
},
]
: [
require.resolve('@babel/preset-env'),
{
useBuiltIns: 'entry',
loose: true,
corejs: '3',
// Do not transform modules to CJS
modules: false,
// Exclude transforms that make all code slower
exclude: ['transform-typeof-symbol'],
},
],
[
require.resolve('@babel/preset-react'),
{
runtime: 'automatic',
},
],
require.resolve('@babel/preset-typescript'),
],
plugins: [
// Polyfills the runtime needed for async/await, generators, and friends
// https://babeljs.io/docs/en/babel-plugin-transform-runtime
[
require.resolve('@babel/plugin-transform-runtime'),
{
corejs: false,
helpers: true,
// By default, it assumes @babel/runtime@7.0.0. Since we use >7.0.0,
// better to explicitly specify the version so that it can reuse the
// helper better. See https://github.com/babel/babel/issues/10261
// eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
version: require('@babel/runtime/package.json')
.version,
regenerator: true,
useESModules: true,
// Undocumented option that lets us encapsulate our runtime, ensuring
// the correct version is used
// https://github.com/babel/babel/blob/090c364a90fe73d36a30707fc612ce037bdbbb24/packages/babel-plugin-transform-runtime/src/index.js#L35-L42
absoluteRuntime: absoluteRuntimePath,
},
],
// Adds syntax support for import()
isServer
? require.resolve('babel-plugin-dynamic-import-node')
: require.resolve('@babel/plugin-syntax-dynamic-import'),
],
};
}
function babelPresets(api) {
const callerName = api.caller((caller) => caller?.name);
return getTransformOptions(callerName === 'server');
}
exports.default = babelPresets;

9
node_modules/@docusaurus/core/lib/client/App.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
import '@generated/client-modules';
export default function App(): JSX.Element;

42
node_modules/@docusaurus/core/lib/client/App.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import '@generated/client-modules';
import routes from '@generated/routes';
import { useLocation } from '@docusaurus/router';
import renderRoutes from '@docusaurus/renderRoutes';
import Root from '@theme/Root';
import SiteMetadata from '@theme/SiteMetadata';
import normalizeLocation from './normalizeLocation';
import { BrowserContextProvider } from './browserContext';
import { DocusaurusContextProvider } from './docusaurusContext';
import PendingNavigation from './PendingNavigation';
import BaseUrlIssueBanner from './BaseUrlIssueBanner';
import SiteMetadataDefaults from './SiteMetadataDefaults';
// TODO, quick fix for CSS insertion order
// eslint-disable-next-line import/order
import ErrorBoundary from '@docusaurus/ErrorBoundary';
import HasHydratedDataAttribute from './hasHydratedDataAttribute';
export default function App() {
const routeElement = renderRoutes(routes);
const location = useLocation();
return (<ErrorBoundary>
<DocusaurusContextProvider>
<BrowserContextProvider>
<Root>
<SiteMetadataDefaults />
<SiteMetadata />
<BaseUrlIssueBanner />
<PendingNavigation location={normalizeLocation(location)}>
{routeElement}
</PendingNavigation>
</Root>
<HasHydratedDataAttribute />
</BrowserContextProvider>
</DocusaurusContextProvider>
</ErrorBoundary>);
}

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
import './styles.module.css';
/**
* We want to help the users with a bad baseUrl configuration (very common
* error). Help message is inlined, and hidden if JS or CSS is able to load.
*
* This component only inserts the base URL banner for the homepage, to avoid
* polluting every statically rendered page.
*
* Note: it might create false positives (ie network failures): not a big deal
*
* @see https://github.com/facebook/docusaurus/pull/3621
*/
export default function MaybeBaseUrlIssueBanner(): JSX.Element | null;

View File

@@ -0,0 +1,88 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { useLocation } from '@docusaurus/router';
import Head from '@docusaurus/Head';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
// Double-security: critical CSS will hide the banner if CSS can load!
import './styles.module.css';
// __ prefix allows search crawlers (Algolia/DocSearch) to ignore anchors
// https://github.com/facebook/docusaurus/issues/8883#issuecomment-1516328368
const BannerContainerId = '__docusaurus-base-url-issue-banner-container';
const BannerId = '__docusaurus-base-url-issue-banner';
const SuggestionContainerId = '__docusaurus-base-url-issue-banner-suggestion-container';
// It is important to not use React to render this banner
// otherwise Google would index it, even if it's hidden with some critical CSS!
// See https://github.com/facebook/docusaurus/issues/4028
// - We can't SSR (or it would be indexed)
// - We can't CSR (as it means the baseurl is correct)
function createInlineHtmlBanner(baseUrl) {
return `
<div id="${BannerId}" style="border: thick solid red; background-color: rgb(255, 230, 179); margin: 20px; padding: 20px; font-size: 20px;">
<p style="font-weight: bold; font-size: 30px;">Your Docusaurus site did not load properly.</p>
<p>A very common reason is a wrong site <a href="https://docusaurus.io/docs/docusaurus.config.js/#baseUrl" style="font-weight: bold;">baseUrl configuration</a>.</p>
<p>Current configured baseUrl = <span style="font-weight: bold; color: red;">${baseUrl}</span> ${baseUrl === '/' ? ' (default value)' : ''}</p>
<p>We suggest trying baseUrl = <span id="${SuggestionContainerId}" style="font-weight: bold; color: green;"></span></p>
</div>
`;
}
// Needs to work for older browsers!
function createInlineScript(baseUrl) {
/* language=js */
return `
document.addEventListener('DOMContentLoaded', function maybeInsertBanner() {
var shouldInsert = typeof window['docusaurus'] === 'undefined';
shouldInsert && insertBanner();
});
function insertBanner() {
var bannerContainer = document.createElement('div');
bannerContainer.id = '${BannerContainerId}';
var bannerHtml = ${JSON.stringify(createInlineHtmlBanner(baseUrl))
// See https://redux.js.org/recipes/server-rendering/#security-considerations
.replace(/</g, '\\\u003c')};
bannerContainer.innerHTML = bannerHtml;
document.body.prepend(bannerContainer);
var suggestionContainer = document.getElementById('${SuggestionContainerId}');
var actualHomePagePath = window.location.pathname;
var suggestedBaseUrl = actualHomePagePath.substr(-1) === '/'
? actualHomePagePath
: actualHomePagePath + '/';
suggestionContainer.innerHTML = suggestedBaseUrl;
}
`;
}
function BaseUrlIssueBanner() {
const { siteConfig: { baseUrl }, } = useDocusaurusContext();
return (<>
{!ExecutionEnvironment.canUseDOM && (
// Safe to use `ExecutionEnvironment`, because `Head` is purely
// side-effect and doesn't affect hydration
<Head>
<script>{createInlineScript(baseUrl)}</script>
</Head>)}
</>);
}
/**
* We want to help the users with a bad baseUrl configuration (very common
* error). Help message is inlined, and hidden if JS or CSS is able to load.
*
* This component only inserts the base URL banner for the homepage, to avoid
* polluting every statically rendered page.
*
* Note: it might create false positives (ie network failures): not a big deal
*
* @see https://github.com/facebook/docusaurus/pull/3621
*/
export default function MaybeBaseUrlIssueBanner() {
const { siteConfig: { baseUrl, baseUrlIssueBanner }, } = useDocusaurusContext();
const { pathname } = useLocation();
const isHomePage = pathname === baseUrl;
const enabled = baseUrlIssueBanner && isHomePage;
return enabled ? <BaseUrlIssueBanner /> : null;
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
:global(#__docusaurus-base-url-issue-banner-container) {
display: none;
}

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
import { type ReactNode } from 'react';
import type { BrokenLinks } from '@docusaurus/useBrokenLinks';
export type StatefulBrokenLinks = BrokenLinks & {
getCollectedLinks: () => string[];
getCollectedAnchors: () => string[];
};
export declare const createStatefulBrokenLinks: () => StatefulBrokenLinks;
export declare const useBrokenLinksContext: () => BrokenLinks;
export declare function BrokenLinksProvider({ children, brokenLinks, }: {
children: ReactNode;
brokenLinks: BrokenLinks;
}): JSX.Element;

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useContext } from 'react';
export const createStatefulBrokenLinks = () => {
// Set to dedup, as it's not useful to collect multiple times the same value
const allAnchors = new Set();
const allLinks = new Set();
return {
collectAnchor: (anchor) => {
typeof anchor !== 'undefined' && allAnchors.add(anchor);
},
collectLink: (link) => {
typeof link !== 'undefined' && allLinks.add(link);
},
getCollectedAnchors: () => [...allAnchors],
getCollectedLinks: () => [...allLinks],
};
};
const Context = React.createContext({
collectAnchor: () => {
// No-op for client
},
collectLink: () => {
// No-op for client
},
});
export const useBrokenLinksContext = () => useContext(Context);
export function BrokenLinksProvider({ children, brokenLinks, }) {
return <Context.Provider value={brokenLinks}>{children}</Context.Provider>;
}

View File

@@ -0,0 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { type ReactElement } from 'react';
import type { ClientModule } from '@docusaurus/types';
import type { Location } from 'history';
export declare function dispatchLifecycleAction<K extends keyof ClientModule>(lifecycleAction: K, ...args: Parameters<NonNullable<ClientModule[K]>>): () => void;
declare function ClientLifecyclesDispatcher({ children, location, previousLocation, }: {
children: ReactElement;
location: Location;
previousLocation: Location | null;
}): JSX.Element;
export default ClientLifecyclesDispatcher;

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import clientModules from '@generated/client-modules';
import useIsomorphicLayoutEffect from './exports/useIsomorphicLayoutEffect';
export function dispatchLifecycleAction(lifecycleAction, ...args) {
const callbacks = clientModules.map((clientModule) => {
const lifecycleFunction = (clientModule.default?.[lifecycleAction] ??
clientModule[lifecycleAction]);
return lifecycleFunction?.(...args);
});
return () => callbacks.forEach((cb) => cb?.());
}
function scrollAfterNavigation({ location, previousLocation, }) {
if (!previousLocation) {
return; // no-op: use native browser feature
}
const samePathname = location.pathname === previousLocation.pathname;
const sameHash = location.hash === previousLocation.hash;
const sameSearch = location.search === previousLocation.search;
// Query-string changes: do not scroll to top/hash
if (samePathname && sameHash && !sameSearch) {
return;
}
const { hash } = location;
if (!hash) {
window.scrollTo(0, 0);
}
else {
const id = decodeURIComponent(hash.substring(1));
const element = document.getElementById(id);
element?.scrollIntoView();
}
}
function ClientLifecyclesDispatcher({ children, location, previousLocation, }) {
useIsomorphicLayoutEffect(() => {
if (previousLocation !== location) {
scrollAfterNavigation({ location, previousLocation });
dispatchLifecycleAction('onRouteDidUpdate', { previousLocation, location });
}
}, [previousLocation, location]);
return children;
}
export default ClientLifecyclesDispatcher;

View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import type { Location } from 'history';
type Props = {
readonly location: Location;
readonly children: JSX.Element;
};
type State = {
nextRouteHasLoaded: boolean;
};
declare class PendingNavigation extends React.Component<Props, State> {
private previousLocation;
private routeUpdateCleanupCb;
constructor(props: Props);
shouldComponentUpdate(nextProps: Props, nextState: State): boolean;
render(): JSX.Element;
}
export default PendingNavigation;

View File

@@ -0,0 +1,73 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { Route } from 'react-router-dom';
import ClientLifecyclesDispatcher, { dispatchLifecycleAction, } from './ClientLifecyclesDispatcher';
import ExecutionEnvironment from './exports/ExecutionEnvironment';
import preload from './preload';
class PendingNavigation extends React.Component {
previousLocation;
routeUpdateCleanupCb;
constructor(props) {
super(props);
// previousLocation doesn't affect rendering, hence not stored in state.
this.previousLocation = null;
this.routeUpdateCleanupCb = ExecutionEnvironment.canUseDOM
? dispatchLifecycleAction('onRouteUpdate', {
previousLocation: null,
location: this.props.location,
})
: () => { };
this.state = {
nextRouteHasLoaded: true,
};
}
// Intercept location update and still show current route until next route
// is done loading.
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.location === this.props.location) {
// `nextRouteHasLoaded` is false means there's a pending route transition.
// Don't update until it's done.
return nextState.nextRouteHasLoaded;
}
// props.location being different means the router is trying to navigate to
// a new route. We will preload the new route.
const nextLocation = nextProps.location;
// Save the location first.
this.previousLocation = this.props.location;
this.setState({ nextRouteHasLoaded: false });
this.routeUpdateCleanupCb = dispatchLifecycleAction('onRouteUpdate', {
previousLocation: this.previousLocation,
location: nextLocation,
});
// Load data while the old screen remains. Force preload instead of using
// `window.docusaurus`, because we want to avoid loading screen even when
// user is on saveData
preload(nextLocation.pathname)
.then(() => {
this.routeUpdateCleanupCb();
this.setState({ nextRouteHasLoaded: true });
})
.catch((e) => {
console.warn(e);
// If chunk loading failed, it could be because the path to a chunk
// no longer exists due to a new deployment. Force refresh the page
// instead of just not navigating.
window.location.reload();
});
return false;
}
render() {
const { children, location } = this.props;
// Use a controlled <Route> to trick all descendants into rendering the old
// location.
return (<ClientLifecyclesDispatcher previousLocation={this.previousLocation} location={location}>
<Route location={location} render={() => children}/>
</ClientLifecyclesDispatcher>);
}
}
export default PendingNavigation;

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
export default function SiteMetadataDefaults(): JSX.Element;

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Head from '@docusaurus/Head';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
export default function SiteMetadataDefaults() {
const { siteConfig: { favicon, title, noIndex }, i18n: { currentLocale, localeConfigs }, } = useDocusaurusContext();
const faviconUrl = useBaseUrl(favicon);
const { htmlLang, direction: htmlDir } = localeConfigs[currentLocale];
return (<Head>
{/*
charSet + generator are handled in the html templates
See https://github.com/facebook/docusaurus/pull/7952
<meta charSet="UTF-8" />
<meta name="generator" content={`Docusaurus v${docusaurusVersion}`} />
*/}
<html lang={htmlLang} dir={htmlDir}/>
<title>{title}</title>
<meta property="og:title" content={title}/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
{noIndex && <meta name="robots" content="noindex, nofollow"/>}
{favicon && <link rel="icon" href={faviconUrl}/>}
</Head>);
}

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { type ReactNode } from 'react';
export declare const Context: React.Context<boolean>;
export declare function BrowserContextProvider({ children, }: {
children: ReactNode;
}): JSX.Element;

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useEffect, useState } from 'react';
// Encapsulate the logic to avoid React hydration problems
// See https://www.joshwcomeau.com/react/the-perils-of-rehydration/
// On first client-side render, we need to render exactly as the server rendered
// isBrowser is set to true only after a successful hydration
// Note, isBrowser is not part of useDocusaurusContext() for perf reasons
// Using useDocusaurusContext() (much more common need) should not trigger
// re-rendering after a successful hydration
export const Context = React.createContext(false);
export function BrowserContextProvider({ children, }) {
const [isBrowser, setIsBrowser] = useState(false);
useEffect(() => {
setIsBrowser(true);
}, []);
return <Context.Provider value={isBrowser}>{children}</Context.Provider>;
}

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare global {
interface NodeModule {
hot?: {
accept: () => void;
};
}
}
export {};

View File

@@ -0,0 +1,51 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { HelmetProvider } from 'react-helmet-async';
import ExecutionEnvironment from './exports/ExecutionEnvironment';
import App from './App';
import preload from './preload';
import docusaurus from './docusaurus';
const hydrate = Boolean(process.env.HYDRATE_CLIENT_ENTRY);
// Client-side render (e.g: running in browser) to become single-page
// application (SPA).
if (ExecutionEnvironment.canUseDOM) {
window.docusaurus = docusaurus;
const container = document.getElementById('__docusaurus');
const app = (<HelmetProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</HelmetProvider>);
const onRecoverableError = (error, errorInfo) => {
console.error('Docusaurus React Root onRecoverableError:', error, errorInfo);
};
const renderApp = () => {
if (hydrate) {
React.startTransition(() => {
ReactDOM.hydrateRoot(container, app, {
onRecoverableError,
});
});
}
else {
const root = ReactDOM.createRoot(container, { onRecoverableError });
React.startTransition(() => {
root.render(app);
});
}
};
preload(window.location.pathname).then(renderApp);
// Webpack Hot Module Replacement API
if (module.hot) {
// Self-accepting method/ trick
// (https://github.com/webpack/webpack-dev-server/issues/100#issuecomment-290911036)
module.hot.accept();
}
}

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare global {
const __webpack_require__: {
gca: (name: string) => string;
};
interface Navigator {
connection?: {
effectiveType: string;
saveData: boolean;
};
}
}
declare const _default: Readonly<{
prefetch(routePath: string): false | Promise<void[]>;
preload(routePath: string): false | Promise<void[]>;
}>;
export default _default;

60
node_modules/@docusaurus/core/lib/client/docusaurus.js generated vendored Normal file
View File

@@ -0,0 +1,60 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { matchRoutes } from 'react-router-config';
import routesChunkNames from '@generated/routesChunkNames';
import routes from '@generated/routes';
import prefetchHelper from './prefetch';
import preloadHelper from './preload';
import flat from './flat';
const fetched = new Set();
const loaded = new Set();
// If user is on slow or constrained connection.
const isSlowConnection = () => navigator.connection?.effectiveType.includes('2g') ||
navigator.connection?.saveData;
const canPrefetch = (routePath) => !isSlowConnection() && !loaded.has(routePath) && !fetched.has(routePath);
const canPreload = (routePath) => !isSlowConnection() && !loaded.has(routePath);
const getChunkNamesToLoad = (path) => Object.entries(routesChunkNames)
.filter(
// Remove the last part containing the route hash
// input: /blog/2018/12/14/Happy-First-Birthday-Slash-fe9
// output: /blog/2018/12/14/Happy-First-Birthday-Slash
([routeNameWithHash]) => routeNameWithHash.replace(/-[^-]+$/, '') === path)
.flatMap(([, routeChunks]) => Object.values(flat(routeChunks)));
const docusaurus = {
prefetch(routePath) {
if (!canPrefetch(routePath)) {
return false;
}
fetched.add(routePath);
// Find all webpack chunk names needed.
const matches = matchRoutes(routes, routePath);
const chunkNamesNeeded = matches.flatMap((match) => getChunkNamesToLoad(match.route.path));
// Prefetch all webpack chunk assets file needed.
return Promise.all(chunkNamesNeeded.map((chunkName) => {
// "__webpack_require__.gca" is injected by ChunkAssetPlugin. Pass it
// the name of the chunk you want to load and it will return its URL.
// eslint-disable-next-line camelcase
const chunkAsset = __webpack_require__.gca(chunkName);
// In some cases, webpack might decide to optimize further, leading to
// the chunk assets being merged to another chunk. In this case, we can
// safely filter it out and don't need to load it.
if (chunkAsset && !chunkAsset.includes('undefined')) {
return prefetchHelper(chunkAsset);
}
return Promise.resolve();
}));
},
preload(routePath) {
if (!canPreload(routePath)) {
return false;
}
loaded.add(routePath);
return preloadHelper(routePath);
},
};
// This object is directly mounted onto window, better freeze it
export default Object.freeze(docusaurus);

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { type ReactNode } from 'react';
import type { DocusaurusContext } from '@docusaurus/types';
export declare const Context: React.Context<DocusaurusContext>;
export declare function DocusaurusContextProvider({ children, }: {
children: ReactNode;
}): JSX.Element;

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import siteConfig from '@generated/docusaurus.config';
import globalData from '@generated/globalData';
import i18n from '@generated/i18n';
import codeTranslations from '@generated/codeTranslations';
import siteMetadata from '@generated/site-metadata';
// Static value on purpose: don't make it dynamic!
// Using context is still useful for testability reasons.
const contextValue = {
siteConfig,
siteMetadata,
globalData,
i18n,
codeTranslations,
};
export const Context = React.createContext(contextValue);
export function DocusaurusContextProvider({ children, }) {
return <Context.Provider value={contextValue}>{children}</Context.Provider>;
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
/// <reference types="react" />
import type { Props } from '@docusaurus/BrowserOnly';
export default function BrowserOnly({ children, fallback, }: Props): JSX.Element | null;

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { isValidElement } from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
// Similar comp to the one described here:
// https://www.joshwcomeau.com/react/the-perils-of-rehydration/#abstractions
export default function BrowserOnly({ children, fallback, }) {
const isBrowser = useIsBrowser();
if (isBrowser) {
if (typeof children !== 'function' &&
process.env.NODE_ENV === 'development') {
throw new Error(`Docusaurus error: The children of <BrowserOnly> must be a "render function", e.g. <BrowserOnly>{() => <span>{window.location.href}</span>}</BrowserOnly>.
Current type: ${isValidElement(children) ? 'React element' : typeof children}`);
}
return <>{children?.()}</>;
}
return fallback ?? null;
}

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import Loadable from 'react-loadable';
declare global {
interface NodeRequire {
resolveWeak: (name: string) => number;
}
}
export default function ComponentCreator(path: string, hash: string): ReturnType<typeof Loadable>;

View File

@@ -0,0 +1,110 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Loadable from 'react-loadable';
import routesChunkNames from '@generated/routesChunkNames';
import registry from '@generated/registry';
import Loading from '@theme/Loading';
import flat from '../flat';
import { RouteContextProvider } from '../routeContext';
export default function ComponentCreator(path, hash) {
// 404 page
if (path === '*') {
return Loadable({
loading: Loading,
loader: () => import('@theme/NotFound'),
modules: ['@theme/NotFound'],
webpack: () => [require.resolveWeak('@theme/NotFound')],
render(loaded, props) {
const NotFound = loaded.default;
return (<RouteContextProvider
// Do we want a better name than native-default?
value={{ plugin: { name: 'native', id: 'default' } }}>
<NotFound {...props}/>
</RouteContextProvider>);
},
});
}
const chunkNames = routesChunkNames[`${path}-${hash}`];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const loader = {};
const modules = [];
const optsWebpack = [];
// A map from prop names to chunk names.
// e.g. Suppose the plugin added this as route:
// { __comp: "...", prop: { foo: "..." }, items: ["...", "..."] }
// It will become:
// { __comp: "...", "prop.foo": "...", "items.0": "...", "items.1": ... }
// Loadable.Map will _map_ over `loader` and load each key.
const flatChunkNames = flat(chunkNames);
Object.entries(flatChunkNames).forEach(([keyPath, chunkName]) => {
const chunkRegistry = registry[chunkName];
if (chunkRegistry) {
// eslint-disable-next-line prefer-destructuring
loader[keyPath] = chunkRegistry[0];
modules.push(chunkRegistry[1]);
optsWebpack.push(chunkRegistry[2]);
}
});
return Loadable.Map({
loading: Loading,
loader,
modules,
webpack: () => optsWebpack,
render(loaded, props) {
// `loaded` will be a map from key path (as returned from the flattened
// chunk names) to the modules loaded from the loaders. We now have to
// restore the chunk names' previous shape from this flat record.
// We do so by taking advantage of the existing `chunkNames` and replacing
// each chunk name with its loaded module, so we don't create another
// object from scratch.
const loadedModules = JSON.parse(JSON.stringify(chunkNames));
Object.entries(loaded).forEach(([keyPath, loadedModule]) => {
// JSON modules are also loaded as `{ default: ... }` (`import()`
// semantics) but we just want to pass the actual value to props.
const chunk = loadedModule.default;
// One loaded chunk can only be one of two things: a module (props) or a
// component. Modules are always JSON, so `default` always exists. This
// could only happen with a user-defined component.
if (!chunk) {
throw new Error(`The page component at ${path} doesn't have a default export. This makes it impossible to render anything. Consider default-exporting a React component.`);
}
// A module can be a primitive, for example, if the user stored a string
// as a prop. However, there seems to be a bug with swc-loader's CJS
// logic, in that it would load a JSON module with content "foo" as
// `{ default: "foo", 0: "f", 1: "o", 2: "o" }`. Just to be safe, we
// first make sure that the chunk is non-primitive.
if (typeof chunk === 'object' || typeof chunk === 'function') {
Object.keys(loadedModule)
.filter((k) => k !== 'default')
.forEach((nonDefaultKey) => {
chunk[nonDefaultKey] =
loadedModule[nonDefaultKey];
});
}
// We now have this chunk prepared. Go down the key path and replace the
// chunk name with the actual chunk.
let val = loadedModules;
const keyPaths = keyPath.split('.');
keyPaths.slice(0, -1).forEach((k) => {
val = val[k];
});
val[keyPaths[keyPaths.length - 1]] = chunk;
});
/* eslint-disable no-underscore-dangle */
const Component = loadedModules.__comp;
delete loadedModules.__comp;
const routeContext = loadedModules.__context;
delete loadedModules.__context;
/* eslint-enable no-underscore-dangle */
// Is there any way to put this RouteContextProvider upper in the tree?
return (<RouteContextProvider value={routeContext}>
<Component {...loadedModules} {...props}/>
</RouteContextProvider>);
},
});
}

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
import React, { type ReactNode } from 'react';
import type { Props } from '@docusaurus/ErrorBoundary';
type State = {
error: Error | null;
};
export default class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props);
componentDidCatch(error: Error): void;
render(): ReactNode;
}
export {};

View File

@@ -0,0 +1,37 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import ThemeError from '@theme/Error';
// eslint-disable-next-line react/function-component-definition
const DefaultFallback = (params) => (<ThemeError {...params}/>);
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
}
componentDidCatch(error) {
// Catch errors in any components below and re-render with error message
if (ExecutionEnvironment.canUseDOM) {
this.setState({ error });
}
}
render() {
const { children } = this.props;
const { error } = this.state;
if (error) {
const fallbackParams = {
error,
tryAgain: () => this.setState({ error: null }),
};
const fallback = this.props.fallback ?? DefaultFallback;
return fallback(fallbackParams);
}
// See https://github.com/facebook/docusaurus/issues/6337#issuecomment-1012913647
return children ?? null;
}
}

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare const ExecutionEnvironment: {
canUseDOM: boolean;
canUseEventListeners: boolean;
canUseIntersectionObserver: boolean;
canUseViewport: boolean;
};
export default ExecutionEnvironment;

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const canUseDOM = typeof window !== 'undefined' &&
'document' in window &&
'createElement' in window.document;
const ExecutionEnvironment = {
canUseDOM,
// window.attachEvent is IE-specific; it's very likely Docusaurus won't work
// on IE anyway.
canUseEventListeners: canUseDOM && ('addEventListener' in window || 'attachEvent' in window),
canUseIntersectionObserver: canUseDOM && 'IntersectionObserver' in window,
canUseViewport: canUseDOM && 'screen' in window,
};
export default ExecutionEnvironment;

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
/// <reference types="react" />
import type { Props } from '@docusaurus/Head';
export default function Head(props: Props): JSX.Element;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { Helmet } from 'react-helmet-async';
export default function Head(props) {
return <Helmet {...props}/>;
}

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
import { type ReactNode } from 'react';
import type { InterpolateProps, InterpolateValues } from '@docusaurus/Interpolate';
export declare function interpolate<Str extends string>(text: Str, values?: InterpolateValues<Str, string | number>): string;
export declare function interpolate<Str extends string, Value extends ReactNode>(text: Str, values?: InterpolateValues<Str, Value>): ReactNode;
export default function Interpolate<Str extends string>({ children, values, }: InterpolateProps<Str>): JSX.Element;

View File

@@ -0,0 +1,33 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { isValidElement } from 'react';
export function interpolate(text, values) {
// eslint-disable-next-line prefer-named-capture-group
const segments = text.split(/(\{\w+\})/).map((seg, index) => {
// Odd indices (1, 3, 5...) of the segments are (potentially) interpolatable
if (index % 2 === 1) {
const value = values?.[seg.slice(1, -1)];
if (value !== undefined) {
return value;
}
// No match: add warning? There's no way to "escape" interpolation though
}
return seg;
});
if (segments.some((seg) => isValidElement(seg))) {
return segments
.map((seg, index) => isValidElement(seg) ? React.cloneElement(seg, { key: index }) : seg)
.filter((seg) => seg !== '');
}
return segments.join('');
}
export default function Interpolate({ children, values, }) {
if (typeof children !== 'string') {
throw new Error(`The Docusaurus <Interpolate> component only accept simple string values. Received: ${isValidElement(children) ? 'React element' : typeof children}`);
}
return <>{interpolate(children, values)}</>;
}

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
import React from 'react';
import type { Props } from '@docusaurus/Link';
declare const _default: React.ForwardRefExoticComponent<Omit<Props, "ref"> & React.RefAttributes<HTMLAnchorElement>>;
export default _default;

View File

@@ -0,0 +1,121 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useEffect, useImperativeHandle, useRef, } from 'react';
import { NavLink, Link as RRLink } from 'react-router-dom';
import { applyTrailingSlash } from '@docusaurus/utils-common';
import useDocusaurusContext from './useDocusaurusContext';
import isInternalUrl from './isInternalUrl';
import ExecutionEnvironment from './ExecutionEnvironment';
import useBrokenLinks from './useBrokenLinks';
import { useBaseUrlUtils } from './useBaseUrl';
// TODO all this wouldn't be necessary if we used ReactRouter basename feature
// We don't automatically add base urls to all links,
// only the "safe" ones, starting with / (like /docs/introduction)
// this is because useBaseUrl() actually transforms relative links
// like "introduction" to "/baseUrl/introduction" => bad behavior to fix
const shouldAddBaseUrlAutomatically = (to) => to.startsWith('/');
function Link({ isNavLink, to, href, activeClassName, isActive, 'data-noBrokenLinkCheck': noBrokenLinkCheck, autoAddBaseUrl = true, ...props }, forwardedRef) {
const { siteConfig: { trailingSlash, baseUrl }, } = useDocusaurusContext();
const { withBaseUrl } = useBaseUrlUtils();
const brokenLinks = useBrokenLinks();
const innerRef = useRef(null);
useImperativeHandle(forwardedRef, () => innerRef.current);
// IMPORTANT: using to or href should not change anything
// For example, MDX links will ALWAYS give us the href props
// Using one prop or the other should not be used to distinguish
// internal links (/docs/myDoc) from external links (https://github.com)
const targetLinkUnprefixed = to || href;
function maybeAddBaseUrl(str) {
return autoAddBaseUrl && shouldAddBaseUrlAutomatically(str)
? withBaseUrl(str)
: str;
}
const isInternal = isInternalUrl(targetLinkUnprefixed);
// pathname:// is a special "protocol" we use to tell Docusaurus link
// that a link is not "internal" and that we shouldn't use history.push()
// this is not ideal but a good enough escape hatch for now
// see https://github.com/facebook/docusaurus/issues/3309
// note: we want baseUrl to be appended (see issue for details)
// TODO read routes and automatically detect internal/external links?
const targetLinkWithoutPathnameProtocol = targetLinkUnprefixed?.replace('pathname://', '');
// TODO we should use ReactRouter basename feature instead!
// Automatically apply base url in links that start with /
let targetLink = typeof targetLinkWithoutPathnameProtocol !== 'undefined'
? maybeAddBaseUrl(targetLinkWithoutPathnameProtocol)
: undefined;
if (targetLink && isInternal) {
targetLink = applyTrailingSlash(targetLink, { trailingSlash, baseUrl });
}
const preloaded = useRef(false);
const LinkComponent = (isNavLink ? NavLink : RRLink);
const IOSupported = ExecutionEnvironment.canUseIntersectionObserver;
const ioRef = useRef();
const handleRef = (el) => {
innerRef.current = el;
if (IOSupported && el && isInternal) {
// If IO supported and element reference found, set up Observer.
ioRef.current = new window.IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (el === entry.target) {
// If element is in viewport, stop observing and run callback.
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
if (entry.isIntersecting || entry.intersectionRatio > 0) {
ioRef.current.unobserve(el);
ioRef.current.disconnect();
if (targetLink != null) {
window.docusaurus.prefetch(targetLink);
}
}
}
});
});
// Add element to the observer.
ioRef.current.observe(el);
}
};
const onInteractionEnter = () => {
if (!preloaded.current && targetLink != null) {
window.docusaurus.preload(targetLink);
preloaded.current = true;
}
};
useEffect(() => {
// If IO is not supported. We prefetch by default (only once).
if (!IOSupported && isInternal) {
if (targetLink != null) {
window.docusaurus.prefetch(targetLink);
}
}
// When unmounting, stop intersection observer from watching.
return () => {
if (IOSupported && ioRef.current) {
ioRef.current.disconnect();
}
};
}, [ioRef, targetLink, IOSupported, isInternal]);
// It is simple local anchor link targeting current page?
const isAnchorLink = targetLink?.startsWith('#') ?? false;
// See also RR logic:
// https://github.com/remix-run/react-router/blob/v5/packages/react-router-dom/modules/Link.js#L47
const hasInternalTarget = !props.target || props.target === '_self';
// Should we use a regular <a> tag instead of React-Router Link component?
const isRegularHtmlLink = !targetLink || !isInternal || !hasInternalTarget || isAnchorLink;
if (!noBrokenLinkCheck && (isAnchorLink || !isRegularHtmlLink)) {
brokenLinks.collectLink(targetLink);
}
if (props.id) {
brokenLinks.collectAnchor(props.id);
}
return isRegularHtmlLink ? (
// eslint-disable-next-line jsx-a11y/anchor-has-content, @docusaurus/no-html-links
<a ref={innerRef} href={targetLink} {...(targetLinkUnprefixed &&
!isInternal && { target: '_blank', rel: 'noopener noreferrer' })} {...props}/>) : (<LinkComponent {...props} onMouseEnter={onInteractionEnter} onTouchStart={onInteractionEnter} innerRef={handleRef} to={targetLink}
// Avoid "React does not recognize the `activeClassName` prop on a DOM
// element"
{...(isNavLink && { isActive, activeClassName })}/>);
}
export default React.forwardRef(Link);

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare const _default: () => null;
export default _default;

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default () => null;

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
/// <reference types="react" />
import { type InterpolateValues } from '@docusaurus/Interpolate';
import type { TranslateParam, TranslateProps } from '@docusaurus/Translate';
export declare function translate<Str extends string>({ message, id }: TranslateParam<Str>, values?: InterpolateValues<Str, string | number>): string;
export default function Translate<Str extends string>({ children, id, values, }: TranslateProps<Str>): JSX.Element;

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { interpolate } from '@docusaurus/Interpolate';
// Can't read it from context, due to exposing imperative API
import codeTranslations from '@generated/codeTranslations';
function getLocalizedMessage({ id, message, }) {
if (typeof id === 'undefined' && typeof message === 'undefined') {
throw new Error('Docusaurus translation declarations must have at least a translation id or a default translation message');
}
return codeTranslations[(id ?? message)] ?? message ?? id;
}
// Imperative translation API is useful for some edge-cases:
// - translating page titles (meta)
// - translating string props (input placeholders, image alt, aria labels...)
export function translate({ message, id }, values) {
const localizedMessage = getLocalizedMessage({ message, id });
return interpolate(localizedMessage, values);
}
// Maybe we'll want to improve this component with additional features
// Like toggling a translation mode that adds a little translation button near
// the text?
export default function Translate({ children, id, values, }) {
if (children && typeof children !== 'string') {
console.warn('Illegal <Translate> children', children);
throw new Error('The Docusaurus <Translate> component only accept simple string values');
}
const localizedMessage = getLocalizedMessage({ message: children, id });
return <>{interpolate(localizedMessage, values)}</>;
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare const DEFAULT_PLUGIN_ID = "default";

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Constants used on the client-side: duplicated from server-side code
export const DEFAULT_PLUGIN_ID = 'default';

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare function hasProtocol(url: string): boolean;
export default function isInternalUrl(url?: string): boolean;

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export function hasProtocol(url) {
return /^(?:\w*:|\/\/)/.test(url);
}
export default function isInternalUrl(url) {
return typeof url !== 'undefined' && !hasProtocol(url);
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export { renderRoutes as default } from 'react-router-config';

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export { renderRoutes as default } from 'react-router-config';

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export { useHistory, useLocation, Redirect, matchPath } from 'react-router-dom';

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export { useHistory, useLocation, Redirect, matchPath } from 'react-router-dom';

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
import type { BaseUrlOptions, BaseUrlUtils } from '@docusaurus/useBaseUrl';
export declare function useBaseUrlUtils(): BaseUrlUtils;
export default function useBaseUrl(url: string, options?: BaseUrlOptions): string;

View File

@@ -0,0 +1,39 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useCallback } from 'react';
import useDocusaurusContext from './useDocusaurusContext';
import { hasProtocol } from './isInternalUrl';
function addBaseUrl(siteUrl, baseUrl, url, { forcePrependBaseUrl = false, absolute = false } = {}) {
// It never makes sense to add base url to a local anchor url, or one with a
// protocol
if (!url || url.startsWith('#') || hasProtocol(url)) {
return url;
}
if (forcePrependBaseUrl) {
return baseUrl + url.replace(/^\//, '');
}
// /baseUrl -> /baseUrl/
// https://github.com/facebook/docusaurus/issues/6315
if (url === baseUrl.replace(/\/$/, '')) {
return baseUrl;
}
// We should avoid adding the baseurl twice if it's already there
const shouldAddBaseUrl = !url.startsWith(baseUrl);
const basePath = shouldAddBaseUrl ? baseUrl + url.replace(/^\//, '') : url;
return absolute ? siteUrl + basePath : basePath;
}
export function useBaseUrlUtils() {
const { siteConfig: { baseUrl, url: siteUrl }, } = useDocusaurusContext();
const withBaseUrl = useCallback((url, options) => addBaseUrl(siteUrl, baseUrl, url, options), [siteUrl, baseUrl]);
return {
withBaseUrl,
};
}
export default function useBaseUrl(url, options = {}) {
const { withBaseUrl } = useBaseUrlUtils();
return withBaseUrl(url, options);
}

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
import type { BrokenLinks } from '@docusaurus/useBrokenLinks';
export default function useBrokenLinks(): BrokenLinks;

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useBrokenLinksContext } from '../BrokenLinksContext';
export default function useBrokenLinks() {
return useBrokenLinksContext();
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { DocusaurusContext } from '@docusaurus/types';
export default function useDocusaurusContext(): DocusaurusContext;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useContext } from 'react';
import { Context } from '../docusaurusContext';
export default function useDocusaurusContext() {
return useContext(Context);
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { GlobalData, UseDataOptions } from '@docusaurus/types';
export default function useGlobalData(): GlobalData;
export declare function useAllPluginInstancesData(pluginName: string, options?: UseDataOptions): GlobalData[string] | undefined;
export declare function usePluginData(pluginName: string, pluginId?: string, options?: UseDataOptions): GlobalData[string][string];

View File

@@ -0,0 +1,28 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import useDocusaurusContext from './useDocusaurusContext';
import { DEFAULT_PLUGIN_ID } from './constants';
export default function useGlobalData() {
const { globalData } = useDocusaurusContext();
return globalData;
}
export function useAllPluginInstancesData(pluginName, options = {}) {
const globalData = useGlobalData();
const pluginGlobalData = globalData[pluginName];
if (!pluginGlobalData && options.failfast) {
throw new Error(`Docusaurus plugin global data not found for "${pluginName}" plugin.`);
}
return pluginGlobalData;
}
export function usePluginData(pluginName, pluginId = DEFAULT_PLUGIN_ID, options = {}) {
const pluginGlobalData = useAllPluginInstancesData(pluginName);
const pluginInstanceGlobalData = pluginGlobalData?.[pluginId];
if (!pluginInstanceGlobalData && options.failfast) {
throw new Error(`Docusaurus plugin global data not found for "${pluginName}" plugin with id "${pluginId}".`);
}
return pluginInstanceGlobalData;
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default function useIsBrowser(): boolean;

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useContext } from 'react';
import { Context } from '../browserContext';
export default function useIsBrowser() {
return useContext(Context);
}

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useEffect } from 'react';
/**
* This hook is like `useLayoutEffect`, but without the SSR warning.
* It seems hacky but it's used in many React libs (Redux, Formik...).
* Also mentioned here: https://github.com/facebook/react/issues/16956
*
* It is useful when you need to update a ref as soon as possible after a React
* render (before `useEffect`).
*
* TODO should become unnecessary in React v19?
* https://github.com/facebook/react/pull/26395
* This was added in core with Docusaurus v3 but kept undocumented on purpose
*/
declare const useIsomorphicLayoutEffect: typeof useEffect;
export default useIsomorphicLayoutEffect;

View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { useEffect, useLayoutEffect } from 'react';
import ExecutionEnvironment from './ExecutionEnvironment';
/**
* This hook is like `useLayoutEffect`, but without the SSR warning.
* It seems hacky but it's used in many React libs (Redux, Formik...).
* Also mentioned here: https://github.com/facebook/react/issues/16956
*
* It is useful when you need to update a ref as soon as possible after a React
* render (before `useEffect`).
*
* TODO should become unnecessary in React v19?
* https://github.com/facebook/react/pull/26395
* This was added in core with Docusaurus v3 but kept undocumented on purpose
*/
const useIsomorphicLayoutEffect = ExecutionEnvironment.canUseDOM
? useLayoutEffect
: useEffect;
export default useIsomorphicLayoutEffect;

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { PluginRouteContext } from '@docusaurus/types';
export default function useRouteContext(): PluginRouteContext;

View File

@@ -0,0 +1,15 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { Context } from '../routeContext';
export default function useRouteContext() {
const context = React.useContext(Context);
if (!context) {
throw new Error('Unexpected: no Docusaurus route context found');
}
return context;
}

18
node_modules/@docusaurus/core/lib/client/flat.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { ChunkNames } from '@docusaurus/types';
/**
* Takes a tree, and flattens it into a map of keyPath -> value.
*
* ```js
* flat({ a: { b: 1 } }) === { "a.b": 1 };
* flat({ a: [1, 2] }) === { "a.0": 1, "a.1": 2 };
* ```
*/
export default function flat(target: ChunkNames): {
[keyPath: string]: string;
};

32
node_modules/@docusaurus/core/lib/client/flat.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const isTree = (x) => typeof x === 'object' && !!x && Object.keys(x).length > 0;
/**
* Takes a tree, and flattens it into a map of keyPath -> value.
*
* ```js
* flat({ a: { b: 1 } }) === { "a.b": 1 };
* flat({ a: [1, 2] }) === { "a.0": 1, "a.1": 2 };
* ```
*/
export default function flat(target) {
const delimiter = '.';
const output = {};
function dfs(object, prefix) {
Object.entries(object).forEach(([key, value]) => {
const newKey = prefix ? `${prefix}${delimiter}${key}` : key;
if (isTree(value)) {
dfs(value, newKey);
}
else {
output[newKey] = value;
}
});
}
dfs(target);
return output;
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
export default function HasHydratedDataAttribute(): JSX.Element;

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import Head from '@docusaurus/Head';
import useIsBrowser from '@docusaurus/useIsBrowser';
// See https://github.com/facebook/docusaurus/pull/9256
// Docusaurus adds a <html data-has-hydrated="true"> after hydration
export default function HasHydratedDataAttribute() {
const isBrowser = useIsBrowser();
return (<Head>
<html data-has-hydrated={isBrowser}/>
</Head>);
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Location } from 'history';
export default function normalizeLocation<T extends Location>(location: T): T;

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { matchRoutes } from 'react-router-config';
import routes from '@generated/routes';
// Memoize previously normalized pathnames.
const pathnames = new Map();
export default function normalizeLocation(location) {
if (pathnames.has(location.pathname)) {
return {
...location,
pathname: pathnames.get(location.pathname),
};
}
// If the location was registered with an `.html` extension, we don't strip it
// away, or it will render to a 404 page.
const matchedRoutes = matchRoutes(routes, location.pathname);
if (matchedRoutes.some(({ route }) => route.exact === true)) {
pathnames.set(location.pathname, location.pathname);
return location;
}
const pathname = location.pathname.trim().replace(/(?:\/index)?\.html$/, '') || '/';
pathnames.set(location.pathname, pathname);
return {
...location,
pathname,
};
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default function prefetch(url: string): Promise<void>;

53
node_modules/@docusaurus/core/lib/client/prefetch.js generated vendored Normal file
View File

@@ -0,0 +1,53 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function supports(feature) {
try {
const fakeLink = document.createElement('link');
return fakeLink.relList.supports(feature);
}
catch {
return false;
}
}
function linkPrefetchStrategy(url) {
return new Promise((resolve, reject) => {
if (typeof document === 'undefined') {
reject();
return;
}
const link = document.createElement('link');
link.setAttribute('rel', 'prefetch');
link.setAttribute('href', url);
link.onload = () => resolve();
link.onerror = () => reject();
const parentElement = document.getElementsByTagName('head')[0] ??
document.getElementsByName('script')[0]?.parentNode;
parentElement?.appendChild(link);
});
}
function xhrPrefetchStrategy(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url, true);
req.withCredentials = true;
req.onload = () => {
if (req.status === 200) {
resolve();
}
else {
reject();
}
};
req.send(null);
});
}
const supportedPrefetchStrategy = supports('prefetch')
? linkPrefetchStrategy
: xhrPrefetchStrategy;
export default function prefetch(url) {
return supportedPrefetchStrategy(url).catch(() => { }); // 404s are logged to the console anyway.
}

15
node_modules/@docusaurus/core/lib/client/preload.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Helper function to make sure all async components for that particular route
* is preloaded before rendering. This is especially useful to avoid loading
* screens.
*
* @param pathname the route pathname, example: /docs/installation
* @returns Promise object represents whether pathname has been preloaded
*/
export default function preload(pathname: string): Promise<void[]>;

22
node_modules/@docusaurus/core/lib/client/preload.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import routes from '@generated/routes';
import { matchRoutes } from 'react-router-config';
/**
* Helper function to make sure all async components for that particular route
* is preloaded before rendering. This is especially useful to avoid loading
* screens.
*
* @param pathname the route pathname, example: /docs/installation
* @returns Promise object represents whether pathname has been preloaded
*/
export default function preload(pathname) {
const matches = Array.from(new Set([pathname, decodeURI(pathname)]))
.map((p) => matchRoutes(routes, p))
.flat();
return Promise.all(matches.map((match) => match.route.component.preload?.()));
}

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { type ReactNode } from 'react';
import type { PluginRouteContext, RouteContext } from '@docusaurus/types';
export declare const Context: React.Context<PluginRouteContext | null>;
export declare function RouteContextProvider({ children, value, }: {
children: ReactNode;
value: PluginRouteContext | RouteContext | null;
}): JSX.Element;

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useMemo } from 'react';
export const Context = React.createContext(null);
function mergeContexts({ parent, value, }) {
if (!parent) {
if (!value) {
throw new Error('Unexpected: no Docusaurus route context found');
}
else if (!('plugin' in value)) {
throw new Error('Unexpected: Docusaurus topmost route context has no `plugin` attribute');
}
return value;
}
// TODO deep merge this
const data = { ...parent.data, ...value?.data };
return {
// Nested routes are not supposed to override plugin attribute
plugin: parent.plugin,
data,
};
}
export function RouteContextProvider({ children, value, }) {
const parent = React.useContext(Context);
const mergedValue = useMemo(() => mergeContexts({ parent, value }), [parent, value]);
return <Context.Provider value={mergedValue}>{children}</Context.Provider>;
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Locals } from '@slorber/static-site-generator-webpack-plugin';
export default function render(locals: Locals & {
path: string;
}): Promise<string>;

142
node_modules/@docusaurus/core/lib/client/serverEntry.js generated vendored Normal file
View File

@@ -0,0 +1,142 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import path from 'path';
import fs from 'fs-extra';
// eslint-disable-next-line no-restricted-imports
import _ from 'lodash';
import * as eta from 'eta';
import { StaticRouter } from 'react-router-dom';
import { HelmetProvider } from 'react-helmet-async';
import { getBundles } from 'react-loadable-ssr-addon-v5-slorber';
import Loadable from 'react-loadable';
import { minify } from 'html-minifier-terser';
import { renderStaticApp } from './serverRenderer';
import preload from './preload';
import App from './App';
import { createStatefulBrokenLinks, BrokenLinksProvider, } from './BrokenLinksContext';
const getCompiledSSRTemplate = _.memoize((template) => eta.compile(template.trim(), {
rmWhitespace: true,
}));
function renderSSRTemplate(ssrTemplate, data) {
const compiled = getCompiledSSRTemplate(ssrTemplate);
return compiled(data, eta.defaultConfig);
}
function buildSSRErrorMessage({ error, pathname, }) {
const parts = [
`Docusaurus server-side rendering could not render static page with path ${pathname} because of error: ${error.message}`,
];
const isNotDefinedErrorRegex = /(?:window|document|localStorage|navigator|alert|location|buffer|self) is not defined/i;
if (isNotDefinedErrorRegex.test(error.message)) {
// prettier-ignore
parts.push(`It looks like you are using code that should run on the client-side only.
To get around it, try using \`<BrowserOnly>\` (https://docusaurus.io/docs/docusaurus-core/#browseronly) or \`ExecutionEnvironment\` (https://docusaurus.io/docs/docusaurus-core/#executionenvironment).
It might also require to wrap your client code in \`useEffect\` hook and/or import a third-party library dynamically (if any).`);
}
return parts.join('\n');
}
export default async function render(locals) {
try {
return await doRender(locals);
}
catch (errorUnknown) {
const error = errorUnknown;
const message = buildSSRErrorMessage({ error, pathname: locals.path });
const ssrError = new Error(message, { cause: error });
// It is important to log the error here because the stacktrace causal chain
// is not available anymore upper in the tree (this SSR runs in eval)
console.error(ssrError);
throw ssrError;
}
}
// Renderer for static-site-generator-webpack-plugin (async rendering).
async function doRender(locals) {
const { routesLocation, headTags, preBodyTags, postBodyTags, onLinksCollected, onHeadTagsCollected, baseUrl, ssrTemplate, noIndex, DOCUSAURUS_VERSION, } = locals;
const location = routesLocation[locals.path];
await preload(location);
const modules = new Set();
const routerContext = {};
const helmetContext = {};
const statefulBrokenLinks = createStatefulBrokenLinks();
const app = (
// @ts-expect-error: we are migrating away from react-loadable anyways
<Loadable.Capture report={(moduleName) => modules.add(moduleName)}>
<HelmetProvider context={helmetContext}>
<StaticRouter location={location} context={routerContext}>
<BrokenLinksProvider brokenLinks={statefulBrokenLinks}>
<App />
</BrokenLinksProvider>
</StaticRouter>
</HelmetProvider>
</Loadable.Capture>);
const appHtml = await renderStaticApp(app);
onLinksCollected({
staticPagePath: location,
anchors: statefulBrokenLinks.getCollectedAnchors(),
links: statefulBrokenLinks.getCollectedLinks(),
});
const { helmet } = helmetContext;
const htmlAttributes = helmet.htmlAttributes.toString();
const bodyAttributes = helmet.bodyAttributes.toString();
const metaStrings = [
helmet.title.toString(),
helmet.meta.toString(),
helmet.link.toString(),
helmet.script.toString(),
];
onHeadTagsCollected(location, helmet);
const metaAttributes = metaStrings.filter(Boolean);
const { generatedFilesDir } = locals;
const manifestPath = path.join(generatedFilesDir, 'client-manifest.json');
// Using readJSON seems to fail for users of some plugins, possibly because of
// the eval sandbox having a different `Buffer` instance (native one instead
// of polyfilled one)
const manifest = (await fs
.readFile(manifestPath, 'utf-8')
.then(JSON.parse));
// Get all required assets for this particular page based on client
// manifest information.
const modulesToBeLoaded = [...manifest.entrypoints, ...Array.from(modules)];
const bundles = getBundles(manifest, modulesToBeLoaded);
const stylesheets = (bundles.css ?? []).map((b) => b.file);
const scripts = (bundles.js ?? []).map((b) => b.file);
const renderedHtml = renderSSRTemplate(ssrTemplate, {
appHtml,
baseUrl,
htmlAttributes,
bodyAttributes,
headTags,
preBodyTags,
postBodyTags,
metaAttributes,
scripts,
stylesheets,
noIndex,
version: DOCUSAURUS_VERSION,
});
try {
if (process.env.SKIP_HTML_MINIFICATION === 'true') {
return renderedHtml;
}
// Minify html with https://github.com/DanielRuf/html-minifier-terser
return await minify(renderedHtml, {
removeComments: false,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
useShortDoctype: true,
minifyJS: true,
});
}
catch (err) {
// prettier-ignore
console.error(`Minification of page ${locals.path} failed.`);
console.error(err);
throw err;
}
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { ReactNode } from 'react';
export declare function renderStaticApp(app: ReactNode): Promise<string>;

View File

@@ -0,0 +1,61 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { renderToPipeableStream } from 'react-dom/server';
import { Writable } from 'stream';
export async function renderStaticApp(app) {
// Inspired from
// https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation
// https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/cache-dir/static-entry.js
const writableStream = new WritableAsPromise();
const { pipe } = renderToPipeableStream(app, {
onError(error) {
writableStream.destroy(error);
},
onAllReady() {
pipe(writableStream);
},
});
return writableStream.getPromise();
}
// WritableAsPromise inspired by https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/cache-dir/server-utils/writable-as-promise.js
/* eslint-disable no-underscore-dangle */
class WritableAsPromise extends Writable {
_output;
_deferred;
constructor() {
super();
this._output = ``;
this._deferred = {
promise: null,
resolve: () => null,
reject: () => null,
};
this._deferred.promise = new Promise((resolve, reject) => {
this._deferred.resolve = resolve;
this._deferred.reject = reject;
});
}
_write(chunk, _enc, next) {
this._output += chunk.toString();
next();
}
_destroy(error, next) {
if (error instanceof Error) {
this._deferred.reject(error);
}
else {
next();
}
}
end() {
this._deferred.resolve(this._output);
return this.destroy();
}
getPromise() {
return this._deferred.promise;
}
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
/// <reference types="react" />
import type { Props } from '@theme/Error';
export default function Error({ error, tryAgain }: Props): JSX.Element;

View File

@@ -0,0 +1,60 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Should we translate theme-fallback?
/* eslint-disable @docusaurus/no-untranslated-text */
import React from 'react';
import Head from '@docusaurus/Head';
import ErrorBoundary from '@docusaurus/ErrorBoundary';
import { getErrorCausalChain } from '@docusaurus/utils-common';
import Layout from '@theme/Layout';
function ErrorDisplay({ error, tryAgain }) {
return (<div style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-start',
minHeight: '100vh',
width: '100%',
maxWidth: '80ch',
fontSize: '20px',
margin: '0 auto',
padding: '1rem',
}}>
<h1 style={{ fontSize: '3rem' }}>This page crashed</h1>
<button type="button" onClick={tryAgain} style={{
margin: '1rem 0',
fontSize: '2rem',
cursor: 'pointer',
borderRadius: 20,
padding: '1rem',
}}>
Try again
</button>
<ErrorBoundaryError error={error}/>
</div>);
}
function ErrorBoundaryError({ error }) {
const causalChain = getErrorCausalChain(error);
const fullMessage = causalChain.map((e) => e.message).join('\n\nCause:\n');
return <p style={{ whiteSpace: 'pre-wrap' }}>{fullMessage}</p>;
}
export default function Error({ error, tryAgain }) {
// We wrap the error in its own error boundary because the layout can actually
// throw too... Only the ErrorDisplay component is simple enough to be
// considered safe to never throw
return (<ErrorBoundary
// Note: we display the original error here, not the error that we
// captured in this extra error boundary
fallback={() => <ErrorDisplay error={error} tryAgain={tryAgain}/>}>
<Head>
<title>Page Error</title>
</Head>
<Layout>
<ErrorDisplay error={error} tryAgain={tryAgain}/>
</Layout>
</ErrorBoundary>);
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
/// <reference types="react" />
import type { Props } from '@theme/Layout';
export default function Layout({ children }: Props): JSX.Element;

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
export default function Layout({ children }) {
return <>{children}</>;
}

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
import type { LoadingComponentProps } from 'react-loadable';
export default function Loading({ error, retry, pastDelay, }: LoadingComponentProps): JSX.Element | null;

View File

@@ -0,0 +1,70 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Should we translate theme-fallback?
/* eslint-disable @docusaurus/no-untranslated-text */
import React from 'react';
export default function Loading({ error, retry, pastDelay, }) {
if (error) {
return (<div style={{
textAlign: 'center',
color: '#fff',
backgroundColor: '#fa383e',
borderColor: '#fa383e',
borderStyle: 'solid',
borderRadius: '0.25rem',
borderWidth: '1px',
boxSizing: 'border-box',
display: 'block',
padding: '1rem',
flex: '0 0 50%',
marginLeft: '25%',
marginRight: '25%',
marginTop: '5rem',
maxWidth: '50%',
width: '100%',
}}>
<p>{String(error)}</p>
<div>
<button type="button" onClick={retry}>
Retry
</button>
</div>
</div>);
}
if (pastDelay) {
return (<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
}}>
<svg id="loader" style={{
width: 128,
height: 110,
position: 'absolute',
top: 'calc(100vh - 64%)',
}} viewBox="0 0 45 45" xmlns="http://www.w3.org/2000/svg" stroke="#61dafb">
<g fill="none" fillRule="evenodd" transform="translate(1 1)" strokeWidth="2">
<circle cx="22" cy="22" r="6" strokeOpacity="0">
<animate attributeName="r" begin="1.5s" dur="3s" values="6;22" calcMode="linear" repeatCount="indefinite"/>
<animate attributeName="stroke-opacity" begin="1.5s" dur="3s" values="1;0" calcMode="linear" repeatCount="indefinite"/>
<animate attributeName="stroke-width" begin="1.5s" dur="3s" values="2;0" calcMode="linear" repeatCount="indefinite"/>
</circle>
<circle cx="22" cy="22" r="6" strokeOpacity="0">
<animate attributeName="r" begin="3s" dur="3s" values="6;22" calcMode="linear" repeatCount="indefinite"/>
<animate attributeName="stroke-opacity" begin="3s" dur="3s" values="1;0" calcMode="linear" repeatCount="indefinite"/>
<animate attributeName="stroke-width" begin="3s" dur="3s" values="2;0" calcMode="linear" repeatCount="indefinite"/>
</circle>
<circle cx="22" cy="22" r="8">
<animate attributeName="r" begin="0s" dur="1.5s" values="6;1;2;3;4;5;6" calcMode="linear" repeatCount="indefinite"/>
</circle>
</g>
</svg>
</div>);
}
return null;
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
export default function NotFound(): JSX.Element;

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Should we translate theme-fallback?
/* eslint-disable @docusaurus/no-untranslated-text */
import React from 'react';
import Head from '@docusaurus/Head';
import Layout from '@theme/Layout';
export default function NotFound() {
return (<>
<Head>
<title>Page Not Found</title>
</Head>
<Layout>
<div style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '50vh',
fontSize: '20px',
}}>
<h1>Oops, page not found </h1>
</div>
</Layout>
</>);
}

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="@docusaurus/module-type-aliases" />
/// <reference types="react" />
import type { Props } from '@theme/Root';
export default function Root({ children }: Props): JSX.Element;

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
// Wrapper at the very top of the app, that is applied constantly
// and does not depend on current route (unlike the layout)
//
// Gives the opportunity to add stateful providers on top of the app
// and these providers won't reset state when we navigate
//
// See https://github.com/facebook/docusaurus/issues/3919
export default function Root({ children }) {
return <>{children}</>;
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="react" />
export default function SiteMetadata(): JSX.Element | null;

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// To be implemented by the theme with <Head>
export default function SiteMetadata() {
return null;
}

13
node_modules/@docusaurus/core/lib/commands/build.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { type LoadContextOptions } from '../server';
export type BuildCLIOptions = Pick<LoadContextOptions, 'config' | 'locale' | 'outDir'> & {
bundleAnalyzer?: boolean;
minify?: boolean;
dev?: boolean;
};
export declare function build(siteDirParam?: string, cliOptions?: Partial<BuildCLIOptions>, forceTerminate?: boolean): Promise<string>;

206
node_modules/@docusaurus/core/lib/commands/build.js generated vendored Normal file
View File

@@ -0,0 +1,206 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const utils_1 = require("@docusaurus/utils");
const copy_webpack_plugin_1 = tslib_1.__importDefault(require("copy-webpack-plugin"));
const react_loadable_ssr_addon_v5_slorber_1 = tslib_1.__importDefault(require("react-loadable-ssr-addon-v5-slorber"));
const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
const server_1 = require("../server");
const brokenLinks_1 = require("../server/brokenLinks");
const client_1 = tslib_1.__importDefault(require("../webpack/client"));
const server_2 = tslib_1.__importDefault(require("../webpack/server"));
const utils_2 = require("../webpack/utils");
const CleanWebpackPlugin_1 = tslib_1.__importDefault(require("../webpack/plugins/CleanWebpackPlugin"));
const i18n_1 = require("../server/i18n");
async function build(siteDirParam = '.', cliOptions = {},
// When running build, we force terminate the process to prevent async
// operations from never returning. However, if run as part of docusaurus
// deploy, we have to let deploy finish.
// See https://github.com/facebook/docusaurus/pull/2496
forceTerminate = true) {
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
process.env.DOCUSAURUS_CURRENT_LOCALE = cliOptions.locale;
if (cliOptions.dev) {
logger_1.default.info `Building in dev mode`;
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
}
const siteDir = await fs_extra_1.default.realpath(siteDirParam);
['SIGINT', 'SIGTERM'].forEach((sig) => {
process.on(sig, () => process.exit());
});
async function tryToBuildLocale({ locale, isLastLocale, }) {
try {
return await buildLocale({
siteDir,
locale,
cliOptions,
forceTerminate,
isLastLocale,
});
}
catch (err) {
throw new Error(logger_1.default.interpolate `Unable to build website for locale name=${locale}.`, {
cause: err,
});
}
}
const context = await (0, server_1.loadContext)({
siteDir,
outDir: cliOptions.outDir,
config: cliOptions.config,
locale: cliOptions.locale,
localizePath: cliOptions.locale ? false : undefined,
});
const i18n = await (0, i18n_1.loadI18n)(context.siteConfig, {
locale: cliOptions.locale,
});
if (cliOptions.locale) {
return tryToBuildLocale({ locale: cliOptions.locale, isLastLocale: true });
}
if (i18n.locales.length > 1) {
logger_1.default.info `Website will be built for all these locales: ${i18n.locales}`;
}
// We need the default locale to always be the 1st in the list. If we build it
// last, it would "erase" the localized sites built in sub-folders
const orderedLocales = [
i18n.defaultLocale,
...i18n.locales.filter((locale) => locale !== i18n.defaultLocale),
];
const results = await (0, utils_1.mapAsyncSequential)(orderedLocales, (locale) => {
const isLastLocale = orderedLocales.indexOf(locale) === orderedLocales.length - 1;
return tryToBuildLocale({ locale, isLastLocale });
});
return results[0];
}
exports.build = build;
async function buildLocale({ siteDir, locale, cliOptions, forceTerminate, isLastLocale, }) {
// Temporary workaround to unlock the ability to translate the site config
// We'll remove it if a better official API can be designed
// See https://github.com/facebook/docusaurus/issues/4542
process.env.DOCUSAURUS_CURRENT_LOCALE = locale;
logger_1.default.info `name=${`[${locale}]`} Creating an optimized production build...`;
const props = await (0, server_1.load)({
siteDir,
outDir: cliOptions.outDir,
config: cliOptions.config,
locale,
localizePath: cliOptions.locale ? false : undefined,
});
// Apply user webpack config.
const { outDir, generatedFilesDir, plugins, siteConfig: { onBrokenLinks, onBrokenAnchors, staticDirectories: staticDirectoriesOption, }, routes, } = props;
const clientManifestPath = path_1.default.join(generatedFilesDir, 'client-manifest.json');
let clientConfig = (0, webpack_merge_1.default)(await (0, client_1.default)(props, cliOptions.minify, true), {
plugins: [
// Remove/clean build folders before building bundles.
new CleanWebpackPlugin_1.default({ verbose: false }),
// Visualize size of webpack output files with an interactive zoomable
// tree map.
cliOptions.bundleAnalyzer && new webpack_bundle_analyzer_1.BundleAnalyzerPlugin(),
// Generate client manifests file that will be used for server bundle.
new react_loadable_ssr_addon_v5_slorber_1.default({
filename: clientManifestPath,
}),
].filter((x) => Boolean(x)),
});
const collectedLinks = {};
const headTags = {};
let serverConfig = await (0, server_2.default)({
props,
onLinksCollected: ({ staticPagePath, links, anchors }) => {
collectedLinks[staticPagePath] = { links, anchors };
},
onHeadTagsCollected: (staticPagePath, tags) => {
headTags[staticPagePath] = tags;
},
});
// The staticDirectories option can contain empty directories, or non-existent
// directories (e.g. user deleted `static`). Instead of issuing an error, we
// just silently filter them out, because user could have never configured it
// in the first place (the default option should always "work").
const staticDirectories = (await Promise.all(staticDirectoriesOption.map(async (dir) => {
const staticDir = path_1.default.resolve(siteDir, dir);
if ((await fs_extra_1.default.pathExists(staticDir)) &&
(await fs_extra_1.default.readdir(staticDir)).length > 0) {
return staticDir;
}
return '';
}))).filter(Boolean);
if (staticDirectories.length > 0) {
serverConfig = (0, webpack_merge_1.default)(serverConfig, {
plugins: [
new copy_webpack_plugin_1.default({
patterns: staticDirectories.map((dir) => ({
from: dir,
to: outDir,
toType: 'dir',
})),
}),
],
});
}
// Plugin Lifecycle - configureWebpack and configurePostCss.
plugins.forEach((plugin) => {
const { configureWebpack, configurePostCss } = plugin;
if (configurePostCss) {
clientConfig = (0, utils_2.applyConfigurePostCss)(configurePostCss.bind(plugin), clientConfig);
}
if (configureWebpack) {
clientConfig = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
clientConfig, false, props.siteConfig.webpack?.jsLoader, plugin.content);
serverConfig = (0, utils_2.applyConfigureWebpack)(configureWebpack.bind(plugin), // The plugin lifecycle may reference `this`.
serverConfig, true, props.siteConfig.webpack?.jsLoader, plugin.content);
}
});
// Make sure generated client-manifest is cleaned first so we don't reuse
// the one from previous builds.
if (await fs_extra_1.default.pathExists(clientManifestPath)) {
await fs_extra_1.default.unlink(clientManifestPath);
}
// Run webpack to build JS bundle (client) and static html files (server).
await (0, utils_2.compile)([clientConfig, serverConfig]);
// Remove server.bundle.js because it is not needed.
if (typeof serverConfig.output?.filename === 'string') {
const serverBundle = path_1.default.join(outDir, serverConfig.output.filename);
if (await fs_extra_1.default.pathExists(serverBundle)) {
await fs_extra_1.default.unlink(serverBundle);
}
}
// Plugin Lifecycle - postBuild.
await Promise.all(plugins.map(async (plugin) => {
if (!plugin.postBuild) {
return;
}
await plugin.postBuild({
...props,
head: headTags,
content: plugin.content,
});
}));
await (0, brokenLinks_1.handleBrokenLinks)({
collectedLinks,
routes,
onBrokenLinks,
onBrokenAnchors,
});
logger_1.default.success `Generated static files in path=${path_1.default.relative(process.cwd(), outDir)}.`;
if (isLastLocale) {
logger_1.default.info `Use code=${'npm run serve'} command to test your build locally.`;
}
if (forceTerminate && isLastLocale && !cliOptions.bundleAnalyzer) {
process.exit(0);
}
return outDir;
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare function clear(siteDirParam?: string): Promise<void>;

45
node_modules/@docusaurus/core/lib/commands/clear.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.clear = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const utils_1 = require("@docusaurus/utils");
async function removePath(entry) {
if (!(await fs_extra_1.default.pathExists(entry.path))) {
return;
}
try {
await fs_extra_1.default.remove(entry.path);
logger_1.default.success `Removed the ${entry.description} at path=${entry.path}.`;
}
catch (err) {
logger_1.default.error `Could not remove the ${entry.description} at path=${entry.path}.`;
logger_1.default.error(err);
}
}
async function clear(siteDirParam = '.') {
const siteDir = await fs_extra_1.default.realpath(siteDirParam);
const generatedFolder = {
path: path_1.default.join(siteDir, utils_1.GENERATED_FILES_DIR_NAME),
description: 'generated folder',
};
const buildFolder = {
path: path_1.default.join(siteDir, utils_1.DEFAULT_BUILD_DIR_NAME),
description: 'build output folder',
};
// In Yarn PnP, cache is stored in `.yarn/.cache` because n_m doesn't exist
const cacheFolders = ['node_modules', '.yarn'].map((p) => ({
path: path_1.default.join(siteDir, p, '.cache'),
description: 'Webpack persistent cache folder',
}));
await Promise.all([generatedFolder, buildFolder, ...cacheFolders].map(removePath));
}
exports.clear = clear;

11
node_modules/@docusaurus/core/lib/commands/deploy.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { type LoadContextOptions } from '../server';
export type DeployCLIOptions = Pick<LoadContextOptions, 'config' | 'locale' | 'outDir'> & {
skipBuild?: boolean;
};
export declare function deploy(siteDirParam?: string, cliOptions?: Partial<DeployCLIOptions>): Promise<void>;

199
node_modules/@docusaurus/core/lib/commands/deploy.js generated vendored Normal file
View File

@@ -0,0 +1,199 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.deploy = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const os_1 = tslib_1.__importDefault(require("os"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
const utils_1 = require("@docusaurus/utils");
const server_1 = require("../server");
const build_1 = require("./build");
// GIT_PASS env variable should not appear in logs
function obfuscateGitPass(str) {
const gitPass = process.env.GIT_PASS;
return gitPass ? str.replace(gitPass, 'GIT_PASS') : str;
}
// Log executed commands so that user can figure out mistakes on his own
// for example: https://github.com/facebook/docusaurus/issues/3875
function shellExecLog(cmd) {
try {
const result = shelljs_1.default.exec(cmd);
logger_1.default.info `code=${obfuscateGitPass(cmd)} subdue=${`code: ${result.code}`}`;
return result;
}
catch (err) {
logger_1.default.error `code=${obfuscateGitPass(cmd)}`;
throw err;
}
}
async function deploy(siteDirParam = '.', cliOptions = {}) {
const siteDir = await fs_extra_1.default.realpath(siteDirParam);
const { outDir, siteConfig, siteConfigPath } = await (0, server_1.loadContext)({
siteDir,
config: cliOptions.config,
outDir: cliOptions.outDir,
});
if (typeof siteConfig.trailingSlash === 'undefined') {
logger_1.default.warn(`When deploying to GitHub Pages, it is better to use an explicit "trailingSlash" site config.
Otherwise, GitHub Pages will add an extra trailing slash to your site urls only on direct-access (not when navigation) with a server redirect.
This behavior can have SEO impacts and create relative link issues.
`);
}
logger_1.default.info('Deploy command invoked...');
if (!shelljs_1.default.which('git')) {
throw new Error('Git not installed or on the PATH!');
}
// Source repo is the repo from where the command is invoked
const sourceRepoUrl = shelljs_1.default
.exec('git remote get-url origin', { silent: true })
.stdout.trim();
// The source branch; defaults to the currently checked out branch
const sourceBranch = process.env.CURRENT_BRANCH ??
shelljs_1.default.exec('git rev-parse --abbrev-ref HEAD', { silent: true }).stdout.trim();
const gitUser = process.env.GIT_USER;
let useSSH = process.env.USE_SSH !== undefined &&
process.env.USE_SSH.toLowerCase() === 'true';
if (!gitUser && !useSSH) {
// If USE_SSH is unspecified: try inferring from repo URL
if (process.env.USE_SSH === undefined && (0, utils_1.hasSSHProtocol)(sourceRepoUrl)) {
useSSH = true;
}
else {
throw new Error('Please set the GIT_USER environment variable, or explicitly specify USE_SSH instead!');
}
}
const organizationName = process.env.ORGANIZATION_NAME ??
process.env.CIRCLE_PROJECT_USERNAME ??
siteConfig.organizationName;
if (!organizationName) {
throw new Error(`Missing project organization name. Did you forget to define "organizationName" in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`);
}
logger_1.default.info `organizationName: name=${organizationName}`;
const projectName = process.env.PROJECT_NAME ??
process.env.CIRCLE_PROJECT_REPONAME ??
siteConfig.projectName;
if (!projectName) {
throw new Error(`Missing project name. Did you forget to define "projectName" in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`);
}
logger_1.default.info `projectName: name=${projectName}`;
// We never deploy on pull request.
const isPullRequest = process.env.CI_PULL_REQUEST ?? process.env.CIRCLE_PULL_REQUEST;
if (isPullRequest) {
shelljs_1.default.echo('Skipping deploy on a pull request.');
shelljs_1.default.exit(0);
}
// github.io indicates organization repos that deploy via default branch. All
// others use gh-pages (either case can be configured actually, but we can
// make educated guesses). Organization deploys look like:
// - Git repo: https://github.com/<organization>/<organization>.github.io
// - Site url: https://<organization>.github.io
const isGitHubPagesOrganizationDeploy = projectName.includes('.github.io');
if (isGitHubPagesOrganizationDeploy &&
!process.env.DEPLOYMENT_BRANCH &&
!siteConfig.deploymentBranch) {
throw new Error(`For GitHub pages organization deployments, 'docusaurus deploy' does not assume anymore that 'master' is your default Git branch.
Please provide the branch name to deploy to as an environment variable, for example DEPLOYMENT_BRANCH=main or DEPLOYMENT_BRANCH=master .
You can also set the deploymentBranch property in docusaurus.config.js .`);
}
const deploymentBranch = process.env.DEPLOYMENT_BRANCH ?? siteConfig.deploymentBranch ?? 'gh-pages';
logger_1.default.info `deploymentBranch: name=${deploymentBranch}`;
const githubHost = process.env.GITHUB_HOST ?? siteConfig.githubHost ?? 'github.com';
const githubPort = process.env.GITHUB_PORT ?? siteConfig.githubPort;
let deploymentRepoURL;
if (useSSH) {
deploymentRepoURL = (0, utils_1.buildSshUrl)(githubHost, organizationName, projectName, githubPort);
}
else {
const gitPass = process.env.GIT_PASS;
const gitCredentials = gitPass ? `${gitUser}:${gitPass}` : gitUser;
deploymentRepoURL = (0, utils_1.buildHttpsUrl)(gitCredentials, githubHost, organizationName, projectName, githubPort);
}
logger_1.default.info `Remote repo URL: name=${obfuscateGitPass(deploymentRepoURL)}`;
// Check if this is a cross-repo publish.
const crossRepoPublish = !sourceRepoUrl.endsWith(`${organizationName}/${projectName}.git`);
// We don't allow deploying to the same branch unless it's a cross publish.
if (sourceBranch === deploymentBranch && !crossRepoPublish) {
throw new Error(`You cannot deploy from this branch (${sourceBranch}).` +
'\nYou will need to checkout to a different branch!');
}
// Save the commit hash that triggers publish-gh-pages before checking
// out to deployment branch.
const currentCommit = shellExecLog('git rev-parse HEAD').stdout.trim();
const runDeploy = async (outputDirectory) => {
const fromPath = outputDirectory;
const toPath = await fs_extra_1.default.mkdtemp(path_1.default.join(os_1.default.tmpdir(), `${projectName}-${deploymentBranch}`));
shelljs_1.default.cd(toPath);
// Check out deployment branch when cloning repository, and then remove all
// the files in the directory. If the 'clone' command fails, assume that
// the deployment branch doesn't exist, and initialize git in an empty
// directory, check out a clean deployment branch and add remote.
if (shellExecLog(`git clone --depth 1 --branch ${deploymentBranch} ${deploymentRepoURL} "${toPath}"`).code === 0) {
shellExecLog('git rm -rf .');
}
else {
shellExecLog('git init');
shellExecLog(`git checkout -b ${deploymentBranch}`);
shellExecLog(`git remote add origin ${deploymentRepoURL}`);
}
try {
await fs_extra_1.default.copy(fromPath, toPath);
}
catch (err) {
logger_1.default.error `Copying build assets from path=${fromPath} to path=${toPath} failed.`;
throw err;
}
shellExecLog('git add --all');
const gitUserName = process.env.GIT_USER_NAME;
if (gitUserName) {
shellExecLog(`git config user.name "${gitUserName}"`);
}
const gitUserEmail = process.env.GIT_USER_EMAIL;
if (gitUserEmail) {
shellExecLog(`git config user.email "${gitUserEmail}"`);
}
const commitMessage = process.env.CUSTOM_COMMIT_MESSAGE ??
`Deploy website - based on ${currentCommit}`;
const commitResults = shellExecLog(`git commit -m "${commitMessage}"`);
if (shellExecLog(`git push --force origin ${deploymentBranch}`).code !== 0) {
throw new Error('Running "git push" command failed. Does the GitHub user account you are using have push access to the repository?');
}
else if (commitResults.code === 0) {
// The commit might return a non-zero value when site is up to date.
let websiteURL = '';
if (githubHost === 'github.com') {
websiteURL = projectName.includes('.github.io')
? `https://${organizationName}.github.io/`
: `https://${organizationName}.github.io/${projectName}/`;
}
else {
// GitHub enterprise hosting.
websiteURL = `https://${githubHost}/pages/${organizationName}/${projectName}/`;
}
shelljs_1.default.echo(`Website is live at "${websiteURL}".`);
shelljs_1.default.exit(0);
}
};
if (!cliOptions.skipBuild) {
// Build site, then push to deploymentBranch branch of specified repo.
try {
await (0, build_1.build)(siteDir, cliOptions, false).then(runDeploy);
}
catch (err) {
logger_1.default.error('Deployment of the build output failed.');
throw err;
}
}
else {
// Push current build to deploymentBranch branch of specified repo.
await runDeploy(outDir);
}
}
exports.deploy = deploy;

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { CommanderStatic } from 'commander';
export declare function externalCommand(cli: CommanderStatic): Promise<void>;

23
node_modules/@docusaurus/core/lib/commands/external.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.externalCommand = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const server_1 = require("../server");
const init_1 = require("../server/plugins/init");
async function externalCommand(cli) {
const siteDir = await fs_extra_1.default.realpath('.');
const context = await (0, server_1.loadContext)({ siteDir });
const plugins = await (0, init_1.initPlugins)(context);
// Plugin Lifecycle - extendCli.
plugins.forEach((plugin) => {
plugin.extendCli?.(cli);
});
}
exports.externalCommand = externalCommand;

14
node_modules/@docusaurus/core/lib/commands/serve.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { type HostPortOptions } from '../server/getHostPort';
import type { LoadContextOptions } from '../server';
export type ServeCLIOptions = HostPortOptions & Pick<LoadContextOptions, 'config'> & {
dir?: string;
build?: boolean;
open?: boolean;
};
export declare function serve(siteDirParam?: string, cliOptions?: Partial<ServeCLIOptions>): Promise<void>;

Some files were not shown because too many files have changed in this diff Show More