@alauda/doom 0.5.5 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli/index.js CHANGED
@@ -28,6 +28,7 @@ program
28
28
  .option('-c, --config [config]', 'Specify the path to the config file')
29
29
  .option('-v <version>', 'Specify the version of the documentation')
30
30
  .option('-p, --prefix <prefix>', 'Specify the prefix of the documentation base')
31
+ .option('-f, --force [boolean]', 'Force to fetch latest reference remotes, otherwise use local cache', (value) => !!value && value !== 'false', false)
31
32
  .command('dev', { isDefault: true })
32
33
  .description('Start the development server')
33
34
  .argument('[root]', 'Root directory of the documentation')
@@ -37,9 +38,9 @@ program
37
38
  setNodeEnv('development');
38
39
  let devServer;
39
40
  let cliWatcher;
40
- const { config: configFile, v: version, prefix, ...server } = this.optsWithGlobals();
41
+ const { config: configFile, v: version, prefix, force, ...server } = this.optsWithGlobals();
41
42
  const startDevServer = async () => {
42
- const { config, filepath } = await loadConfig(root, configFile, prefix, version);
43
+ const { config, filepath } = await loadConfig(root, configFile, prefix, version, force);
43
44
  const docDirectory = config.root;
44
45
  try {
45
46
  devServer = await dev({
@@ -102,8 +103,8 @@ program
102
103
  .argument('[root]', 'Root directory of the documentation')
103
104
  .action(async function (root) {
104
105
  setNodeEnv('production');
105
- const { config: configFile, prefix, v: version, } = this.optsWithGlobals();
106
- const { config } = await loadConfig(root, configFile, prefix, version);
106
+ const { config: configFile, prefix, v: version, force, } = this.optsWithGlobals();
107
+ const { config } = await loadConfig(root, configFile, prefix, version, force);
107
108
  const docDirectory = config.root;
108
109
  await build({
109
110
  config,
@@ -120,8 +121,8 @@ program
120
121
  .option('--host [host]', 'Host name')
121
122
  .action(async function (root) {
122
123
  setNodeEnv('production');
123
- const { config: configFile, prefix, v: version, ...server } = this.optsWithGlobals();
124
- const { config } = await loadConfig(root, configFile, prefix, version);
124
+ const { config: configFile, prefix, v: version, force, ...server } = this.optsWithGlobals();
125
+ const { config } = await loadConfig(root, configFile, prefix, version, force);
125
126
  await serve({
126
127
  config,
127
128
  ...server,
@@ -1,5 +1,5 @@
1
1
  import { type DoomConfig } from '../utils/index.js';
2
- export declare function loadConfig(root?: string, configFile?: string, prefix?: string, version?: string): Promise<{
2
+ export declare function loadConfig(root?: string, configFile?: string, prefix?: string, version?: string, force?: boolean): Promise<{
3
3
  config: DoomConfig;
4
4
  filepath?: string;
5
5
  }>;
@@ -11,6 +11,7 @@ import { apiPlugin, autoSidebarPlugin, createTransformerCallouts, globalPlugin,
11
11
  import { normalizeVersion } from '../shared/index.js';
12
12
  import { pkgResolve, resolveStaticConfig, } from '../utils/index.js';
13
13
  import { CWD, DEFAULT_CONFIG_NAME, DEFAULT_EXTENSIONS, I18N_FILE, SITES_FILE, YAML_EXTENSIONS, } from './constants.js';
14
+ import { referencePlugin } from '../plugins/reference/index.js';
14
15
  const DEFAULT_LOGO = '/logo.svg';
15
16
  const zhLocaleConfig = {
16
17
  searchPlaceholderText: '搜索文档',
@@ -20,9 +21,20 @@ const zhLocaleConfig = {
20
21
  prevPageText: '上一页',
21
22
  nextPageText: '下一页',
22
23
  };
23
- const getCommonConfig = async (config, version) => {
24
+ const getCommonConfig = async (config, cliRoot, prefix, configFilePath, version, force) => {
24
25
  const fallbackToZh = 'lang' in config && config.lang == null;
26
+ const root = resolveDocRoot(CWD, cliRoot, config.root);
27
+ let base = addLeadingSlash(config.base || '/');
28
+ if (version && version !== 'unversioned') {
29
+ base = removeTrailingSlash(base) + `/${version}`;
30
+ }
31
+ base = addTrailingSlash(base);
32
+ if (prefix) {
33
+ base = normalizeSlash(prefix) + base;
34
+ }
25
35
  return {
36
+ base,
37
+ root,
26
38
  lang: fallbackToZh ? 'zh' : config.lang,
27
39
  route: {
28
40
  exclude: [
@@ -61,9 +73,19 @@ const getCommonConfig = async (config, version) => {
61
73
  },
62
74
  defaultRenderMode: 'pure',
63
75
  }),
64
- apiPlugin(),
65
- autoSidebarPlugin(),
66
- globalPlugin(version),
76
+ apiPlugin(config.api),
77
+ autoSidebarPlugin(config.sidebar),
78
+ globalPlugin({
79
+ sites: config.sites,
80
+ version,
81
+ }),
82
+ referencePlugin({
83
+ base,
84
+ root,
85
+ localBasePath: configFilePath ? path.dirname(configFilePath) : root,
86
+ items: config.reference,
87
+ force,
88
+ }),
67
89
  shikiPlugin({
68
90
  langs: ['dockerfile', 'html', 'go', 'jsonc'],
69
91
  transformers: [
@@ -100,7 +122,7 @@ const getCommonConfig = async (config, version) => {
100
122
  const findConfig = (basePath) => {
101
123
  return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(fs.existsSync);
102
124
  };
103
- export async function loadConfig(root, configFile, prefix, version) {
125
+ export async function loadConfig(root, configFile, prefix, version, force) {
104
126
  let configFilePath;
105
127
  if (configFile) {
106
128
  configFilePath = path.resolve(configFile);
@@ -150,16 +172,11 @@ export async function loadConfig(root, configFile, prefix, version) {
150
172
  }
151
173
  }
152
174
  const normalizedVersion = normalizeVersion(version);
153
- const mergedConfig = mergeRsbuildConfig(await getCommonConfig(config, normalizedVersion), config);
154
- let base = addLeadingSlash(mergedConfig.base || '/');
155
- if (normalizedVersion && normalizedVersion !== 'unversioned') {
156
- base = removeTrailingSlash(base) + `/${normalizedVersion}`;
157
- }
158
- mergedConfig.base = base = addTrailingSlash(base);
159
- if (prefix) {
160
- mergedConfig.base = normalizeSlash(prefix) + base;
161
- }
162
- mergedConfig.root = resolveDocRoot(CWD, root, mergedConfig.root);
175
+ const commonConfig = await getCommonConfig(config, root, prefix, configFilePath, normalizedVersion, force);
176
+ const mergedConfig = mergeRsbuildConfig(commonConfig, config, {
177
+ base: commonConfig.base,
178
+ root: commonConfig.root,
179
+ });
163
180
  let ensureDefaultLogo = false;
164
181
  if (!mergedConfig.logo) {
165
182
  mergedConfig.logo = DEFAULT_LOGO;
@@ -179,7 +196,7 @@ export async function loadConfig(root, configFile, prefix, version) {
179
196
  }
180
197
  if (mergedConfig.i18nSourcePath) {
181
198
  if (!path.isAbsolute(mergedConfig.i18nSourcePath)) {
182
- mergedConfig.i18nSourcePath = path.resolve(configFilePath ?? mergedConfig.root, mergedConfig.i18nSourcePath);
199
+ mergedConfig.i18nSourcePath = path.resolve(configFilePath ? path.dirname(configFilePath) : mergedConfig.root, mergedConfig.i18nSourcePath);
183
200
  }
184
201
  }
185
202
  else {
@@ -190,6 +207,9 @@ export async function loadConfig(root, configFile, prefix, version) {
190
207
  addTrailingSlash(mergedConfig.outDir) + normalizedVersion;
191
208
  }
192
209
  else {
210
+ const base = prefix
211
+ ? mergedConfig.base.replace(normalizeSlash(prefix), '')
212
+ : mergedConfig.base;
193
213
  mergedConfig.outDir = `dist${normalizedVersion === 'unversioned' ? `/unversioned${base}` : base}`;
194
214
  }
195
215
  if (mergedConfig.builderConfig?.server?.open === true) {
@@ -1,2 +1,3 @@
1
1
  import type { RspressPlugin } from '@rspress/core';
2
- export declare const apiPlugin: () => RspressPlugin;
2
+ import type { ApiPluginOptions } from './types.js';
3
+ export declare const apiPlugin: ({ crds, openapis, references, pathPrefix, }?: ApiPluginOptions) => RspressPlugin;
@@ -3,18 +3,13 @@ import { openapiSchemaToJsonSchema } from '@openapi-contrib/openapi-schema-to-js
3
3
  import { convertObj } from 'swagger2openapi';
4
4
  import { glob } from 'tinyglobby';
5
5
  import { resolveStaticConfig } from '../../utils/index.js';
6
- export const apiPlugin = () => {
6
+ export const apiPlugin = ({ crds, openapis, references, pathPrefix, } = {}) => {
7
7
  const crdsMap = {};
8
8
  const openapisMap = {};
9
9
  const shared = {};
10
10
  return {
11
11
  name: 'doom-api',
12
- async beforeBuild(config_) {
13
- const config = config_;
14
- if (!config.api) {
15
- return;
16
- }
17
- const { crds, openapis, references, pathPrefix } = config.api;
12
+ async beforeBuild(config) {
18
13
  if (crds) {
19
14
  for (const file of await glob(crds, {
20
15
  cwd: config.root,
@@ -1,4 +1,10 @@
1
1
  import { OpenAPIV3 } from 'openapi-types';
2
+ export interface ApiPluginOptions {
3
+ crds?: string[];
4
+ openapis?: string[];
5
+ references?: Record<string, string>;
6
+ pathPrefix?: string;
7
+ }
2
8
  export interface CustomResourceDefinitionVersion {
3
9
  name: string;
4
10
  schema: {
@@ -1,2 +1,5 @@
1
1
  import { type RspressPlugin } from '@rspress/core';
2
- export declare const autoSidebarPlugin: () => RspressPlugin;
2
+ export interface AutoSidebarPluginOptions {
3
+ collapsed?: boolean;
4
+ }
5
+ export declare const autoSidebarPlugin: ({ collapsed, }?: AutoSidebarPluginOptions) => RspressPlugin;
@@ -141,21 +141,21 @@ import { walk } from './walk.js';
141
141
  // }
142
142
  // ]
143
143
  // ```
144
- function processLocales(langs, versions, root, defaultLang, defaultVersion, extensions) {
144
+ function processLocales(langs, versions, root, defaultLang, defaultVersion, extensions, collapsed) {
145
145
  return Promise.all(langs.map(async (lang) => {
146
146
  const walks = versions.length
147
147
  ? await Promise.all(versions.map((version) => {
148
148
  const routePrefix = addTrailingSlash(`${version === defaultVersion ? '' : `/${version}`}${lang === defaultLang ? '' : `/${lang}`}`);
149
- return walk(path.join(root, version, lang), routePrefix, root, extensions);
149
+ return walk(path.join(root, version, lang), routePrefix, root, extensions, collapsed);
150
150
  }))
151
151
  : [
152
- await walk(path.join(root, lang), addTrailingSlash(lang === defaultLang ? '' : `/${lang}`), root, extensions),
152
+ await walk(path.join(root, lang), addTrailingSlash(lang === defaultLang ? '' : `/${lang}`), root, extensions, collapsed),
153
153
  ];
154
154
  return combineWalkResult(walks, versions);
155
155
  }));
156
156
  }
157
157
  const defaultExtensions = ['.mdx', '.md', '.tsx', '.jsx', '.ts', '.js'];
158
- export const autoSidebarPlugin = () => {
158
+ export const autoSidebarPlugin = ({ collapsed, } = {}) => {
159
159
  return {
160
160
  name: 'doom-auto-sidebar',
161
161
  async config(config, utils) {
@@ -171,7 +171,7 @@ export const autoSidebarPlugin = () => {
171
171
  const { default: defaultVersion = '' } = config.multiVersion || {};
172
172
  const { extensions = defaultExtensions } = config.route || {};
173
173
  if (hasLocales) {
174
- const metaInfo = await processLocales(langs, versions, config.root, defaultLang, defaultVersion, extensions);
174
+ const metaInfo = await processLocales(langs, versions, config.root, defaultLang, defaultVersion, extensions, collapsed);
175
175
  config.themeConfig.locales = config.themeConfig.locales.map((item, index) => ({
176
176
  ...item,
177
177
  ...metaInfo[index],
@@ -188,9 +188,9 @@ export const autoSidebarPlugin = () => {
188
188
  const walks = versions.length
189
189
  ? await Promise.all(versions.map((version) => {
190
190
  const routePrefix = addTrailingSlash(version === defaultVersion ? '' : `/${version}`);
191
- return walk(path.join(config.root, version), routePrefix, config.root, extensions);
191
+ return walk(path.join(config.root, version), routePrefix, config.root, extensions, collapsed);
192
192
  }))
193
- : [await walk(config.root, '/', config.root, extensions)];
193
+ : [await walk(config.root, '/', config.root, extensions, collapsed)];
194
194
  const combined = combineWalkResult(walks, versions);
195
195
  config.themeConfig = { ...config.themeConfig, ...combined };
196
196
  }
@@ -11,7 +11,7 @@ export declare function scanSideMeta(workDir: string, rootDir: string, docsDir:
11
11
  index?: DoomSidebarItem;
12
12
  others: DoomSidebar[];
13
13
  }>;
14
- export declare function walk(workDir: string, routePrefix: string | undefined, docsDir: string, extensions: string[]): Promise<{
14
+ export declare function walk(workDir: string, routePrefix: string | undefined, docsDir: string, extensions: string[], collapsed?: boolean): Promise<{
15
15
  nav: never[];
16
16
  sidebar: {
17
17
  [x: string]: DoomSidebar[];
@@ -4,10 +4,9 @@ import { logger } from '@rspress/shared/logger';
4
4
  import path from 'node:path';
5
5
  import { detectFilePath, extractInfoFromFrontmatter } from './utils.js';
6
6
  const sidebarSorter = (a, b) => {
7
- if ('weight' in a && 'weight' in b) {
8
- return a.weight - b.weight;
9
- }
10
- return 0;
7
+ const aWeight = 'weight' in a && a.weight != null ? a.weight : 100;
8
+ const bWeight = 'weight' in b && b.weight != null ? b.weight : 100;
9
+ return aWeight - bWeight;
11
10
  };
12
11
  /**
13
12
  * Split sideMeta into two parts: `index` and `others` and sort `others` by weight
@@ -162,12 +161,14 @@ export async function scanSideMeta(workDir, rootDir, docsDir, routePrefix, exten
162
161
  }
163
162
  // Start walking from the doc directory, scan the `_meta.json` file in each subdirectory
164
163
  // and generate the nav and sidebar config
165
- export async function walk(workDir, routePrefix = '/', docsDir, extensions) {
164
+ export async function walk(workDir, routePrefix = '/', docsDir, extensions, collapsed) {
166
165
  const { index, others } = await scanSideMeta(workDir, workDir, docsDir, routePrefix, extensions, ['assets', 'public', 'shared']);
167
166
  const sidebars = index ? [index, ...others] : others;
168
- for (const sidebarItem of sidebars) {
169
- if ('items' in sidebarItem && sidebarItem.items.length) {
170
- sidebarItem.collapsed = false;
167
+ if (collapsed != null) {
168
+ for (const sidebarItem of sidebars) {
169
+ if ('items' in sidebarItem && sidebarItem.items.length) {
170
+ sidebarItem.collapsed = collapsed;
171
+ }
171
172
  }
172
173
  }
173
174
  // Every sub dir will represent a group of sidebar
@@ -1,2 +1,7 @@
1
1
  import type { RspressPlugin } from '@rspress/core';
2
- export declare const globalPlugin: (version?: string) => RspressPlugin;
2
+ import type { DoomSite } from '../../shared/types.js';
3
+ export interface GlobalPluginOptions {
4
+ sites?: DoomSite[];
5
+ version?: string;
6
+ }
7
+ export declare const globalPlugin: ({ sites, version, }?: GlobalPluginOptions) => RspressPlugin;
@@ -2,8 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { baseResolve, pkgResolve } from '../../utils/index.js';
4
4
  const componentsDir = baseResolve('runtime/components');
5
- export const globalPlugin = (version) => {
6
- let config;
5
+ export const globalPlugin = ({ sites, version, } = {}) => {
7
6
  return {
8
7
  name: 'doom-global',
9
8
  globalStyles: pkgResolve('styles/global.scss'),
@@ -19,11 +18,8 @@ export const globalPlugin = (version) => {
19
18
  })
20
19
  .map((file) => path.resolve(componentsDir, file)),
21
20
  },
22
- beforeBuild(config_) {
23
- config = config_;
24
- },
25
21
  extendPageData(pageData) {
26
- pageData.sites = config.sites;
22
+ pageData.sites = sites;
27
23
  pageData.v = version === 'unversioned' ? undefined : version;
28
24
  },
29
25
  };
@@ -0,0 +1,9 @@
1
+ import type { RspressPlugin } from '@rspress/core';
2
+ import type { ReferenceItem } from './types.js';
3
+ export declare const referencePlugin: ({ base, root, localBasePath, items, force, }: {
4
+ base: string;
5
+ root: string;
6
+ localBasePath: string;
7
+ items?: ReferenceItem[];
8
+ force?: boolean;
9
+ }) => RspressPlugin;
@@ -0,0 +1,54 @@
1
+ import fs from 'node:fs/promises';
2
+ import remarkGfm from 'remark-gfm';
3
+ import remarkMdx from 'remark-mdx';
4
+ import remarkParse from 'remark-parse';
5
+ import remarkStringify from 'remark-stringify';
6
+ import { unified } from 'unified';
7
+ import { remarkPluginNormalizeLink } from './remark-normalize-link.js';
8
+ import { maybeHaveRef, refCache, remarkReplace } from './remark-replace.js';
9
+ import { remarkPluginToc } from './remark-toc.js';
10
+ import { normalizeReferenceItems } from './utils.js';
11
+ const mdProcessor = unified().use(remarkParse).use(remarkGfm);
12
+ const mdxProcessor = mdProcessor().use(remarkMdx);
13
+ export const referencePlugin = ({ base, root, localBasePath, items = [], force, }) => {
14
+ const normalizedItems = normalizeReferenceItems(items);
15
+ return {
16
+ name: 'doom-reference',
17
+ markdown: {
18
+ remarkPlugins: [
19
+ [
20
+ remarkReplace,
21
+ {
22
+ localBasePath,
23
+ items: normalizedItems,
24
+ force,
25
+ },
26
+ ],
27
+ remarkPluginToc,
28
+ [remarkPluginNormalizeLink, { base, root }],
29
+ ],
30
+ },
31
+ async modifySearchIndexData(pages) {
32
+ refCache.clear();
33
+ for (const page of pages) {
34
+ const filepath = page._filepath;
35
+ if (!/\.mdx?$/.test(filepath)) {
36
+ continue;
37
+ }
38
+ const content = await fs.readFile(filepath, 'utf8');
39
+ if (!maybeHaveRef(filepath, content)) {
40
+ continue;
41
+ }
42
+ const processor = filepath.endsWith('.mdx') ? mdxProcessor : mdProcessor;
43
+ const vfile = await processor()
44
+ .use(remarkReplace, { localBasePath, items: normalizedItems, force })
45
+ .use(remarkStringify)
46
+ .process({
47
+ path: filepath,
48
+ value: content,
49
+ });
50
+ page.content = vfile.toString();
51
+ }
52
+ },
53
+ };
54
+ };
@@ -0,0 +1,12 @@
1
+ import type { Root } from 'mdast';
2
+ import type { Plugin } from 'unified';
3
+ /**
4
+ * Remark plugin to normalize a link href
5
+ */
6
+ export declare const remarkPluginNormalizeLink: Plugin<[
7
+ {
8
+ base: string;
9
+ root: string;
10
+ cleanUrls: boolean;
11
+ }
12
+ ], Root>;
@@ -0,0 +1,114 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */
2
+ import { isExternalUrl, normalizeHref, parseUrl, slash } from '@rspress/shared';
3
+ import path from 'node:path';
4
+ import { visit } from 'unist-util-visit';
5
+ import { getASTNodeImport } from './utils.js';
6
+ /**
7
+ * Remark plugin to normalize a link href
8
+ */
9
+ export const remarkPluginNormalizeLink = ({ base, root, cleanUrls }) => (tree, file) => {
10
+ const images = [];
11
+ visit(tree, (node) => node.type === 'link', (node) => {
12
+ if (!node.url) {
13
+ return;
14
+ }
15
+ if (node.url.startsWith('#')) {
16
+ node.url = `#${node.url.slice(1)}`;
17
+ return;
18
+ }
19
+ // eslint-disable-next-line prefer-const
20
+ let { url, hash } = parseUrl(node.url);
21
+ if (isExternalUrl(url)) {
22
+ node.url = url + (hash ? `#${hash}` : '');
23
+ return;
24
+ }
25
+ const extname = path.extname(url);
26
+ if (extname === '.md' || extname === '.mdx') {
27
+ url = url.replace(extname, '');
28
+ }
29
+ const relativePath = path.relative(root, file.path);
30
+ if (url.startsWith('.')) {
31
+ url = path.posix.join(slash(path.dirname(relativePath)), url);
32
+ }
33
+ url = normalizeHref(url, cleanUrls);
34
+ if (hash) {
35
+ url += `#${hash}`;
36
+ }
37
+ node.url = path.posix.join(base, url);
38
+ });
39
+ const normalizeImageUrl = (imageUrl) => {
40
+ if (isExternalUrl(imageUrl) || imageUrl.startsWith('/')) {
41
+ return '';
42
+ }
43
+ return imageUrl;
44
+ };
45
+ const getMdxSrcAttrbute = (tempVar) => {
46
+ return {
47
+ type: 'mdxJsxAttribute',
48
+ name: 'src',
49
+ value: {
50
+ type: 'mdxJsxAttributeValueExpression',
51
+ value: tempVar,
52
+ data: {
53
+ estree: {
54
+ type: 'Program',
55
+ sourceType: 'module',
56
+ body: [
57
+ {
58
+ type: 'ExpressionStatement',
59
+ expression: {
60
+ type: 'Identifier',
61
+ name: tempVar,
62
+ },
63
+ },
64
+ ],
65
+ },
66
+ },
67
+ },
68
+ };
69
+ };
70
+ visit(tree, 'image', (node) => {
71
+ const { url } = node;
72
+ if (!url) {
73
+ return;
74
+ }
75
+ const imagePath = normalizeImageUrl(url);
76
+ if (!imagePath) {
77
+ return;
78
+ }
79
+ // relative path
80
+ const tempVariableName = `image${images.length}`;
81
+ Object.assign(node, {
82
+ type: 'mdxJsxFlowElement',
83
+ name: 'img',
84
+ children: [],
85
+ attributes: [
86
+ node.alt && {
87
+ type: 'mdxJsxAttribute',
88
+ name: 'alt',
89
+ value: node.alt,
90
+ },
91
+ getMdxSrcAttrbute(tempVariableName),
92
+ ].filter(Boolean),
93
+ });
94
+ images.push(getASTNodeImport(tempVariableName, imagePath));
95
+ });
96
+ visit(tree, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {
97
+ // get all img src
98
+ if (node.name !== 'img') {
99
+ return;
100
+ }
101
+ const src = node.attributes.find((attr) => attr.name === 'src');
102
+ if (!src?.value || typeof src?.value !== 'string') {
103
+ return;
104
+ }
105
+ const imagePath = normalizeImageUrl(src.value);
106
+ if (!imagePath) {
107
+ return;
108
+ }
109
+ const tempVariableName = `image${images.length}`;
110
+ Object.assign(src, getMdxSrcAttrbute(tempVariableName));
111
+ images.push(getASTNodeImport(tempVariableName, imagePath));
112
+ });
113
+ tree.children.unshift(...images);
114
+ };
@@ -0,0 +1,14 @@
1
+ import type { Content, Root } from 'mdast';
2
+ import { type Plugin } from 'unified';
3
+ import { NormalizedReferenceSource } from './types.js';
4
+ export declare const MD_REF_PATTERN: RegExp;
5
+ export declare const MDX_REF_PATTERN: RegExp;
6
+ export declare const maybeHaveRef: (filepath: string, content: string) => boolean;
7
+ export declare const refCache: Map<string, Content[] | undefined>;
8
+ export declare const remarkReplace: Plugin<[
9
+ {
10
+ localBasePath: string;
11
+ items: Record<string, NormalizedReferenceSource>;
12
+ force?: boolean;
13
+ }
14
+ ], Root>;
@@ -0,0 +1,121 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { logger } from '@rspress/shared/logger';
5
+ import remarkGfm from 'remark-gfm';
6
+ import remarkMdx from 'remark-mdx';
7
+ import remarkParse from 'remark-parse';
8
+ import { simpleGit } from 'simple-git';
9
+ import { unified } from 'unified';
10
+ import { cyan, red } from 'yoctocolors';
11
+ import { parseToc } from './remark-toc.js';
12
+ import { flatMap } from './utils.js';
13
+ const remotesFolder = path.resolve(os.homedir(), '.doom/remotes');
14
+ const resolveReference = async (localBasePath, source, force) => {
15
+ let sourcePath = source.path;
16
+ if (source.repo) {
17
+ const repoFolder = path.resolve(remotesFolder, source.slug);
18
+ let created = false;
19
+ try {
20
+ const stat = await fs.stat(path.resolve(repoFolder, '.git'));
21
+ if (stat.isDirectory()) {
22
+ created = true;
23
+ }
24
+ }
25
+ catch {
26
+ // ignore
27
+ }
28
+ if (!created) {
29
+ await fs.mkdir(repoFolder, { recursive: true });
30
+ }
31
+ const git = simpleGit(repoFolder);
32
+ if (!created) {
33
+ logger.info(`Cloning remote \`${cyan(source.slug)}\` repository...`);
34
+ await git.clone(source.repo, repoFolder, ['--depth', '1']);
35
+ }
36
+ if (force) {
37
+ logger.info(`Pulling latest changes for \`${cyan(source.slug)}\`...`);
38
+ await git.pull(['--depth', '1', '--force', '--rebase']);
39
+ }
40
+ sourcePath = path.resolve(repoFolder, sourcePath);
41
+ }
42
+ else {
43
+ sourcePath = path.resolve(localBasePath, sourcePath);
44
+ }
45
+ let found = false;
46
+ try {
47
+ const stat = await fs.stat(sourcePath);
48
+ found = stat.isFile();
49
+ }
50
+ catch {
51
+ //
52
+ }
53
+ if (!found) {
54
+ logger.error(`Reference path \`${red(source.path)}\` for \`${red(source.name)}\` not found`);
55
+ }
56
+ const processor = unified().use(remarkParse).use(remarkGfm);
57
+ if (sourcePath.endsWith('.mdx')) {
58
+ processor.use(remarkMdx);
59
+ }
60
+ const root = processor.parse(await fs.readFile(sourcePath));
61
+ if (!source.anchor) {
62
+ return root.children;
63
+ }
64
+ const { toc } = parseToc(root, true);
65
+ const active = toc.find((it) => it.id === source.anchor);
66
+ if (!active) {
67
+ logger.error(`Anchor \`${red(source.anchor)}\` not found in \`${red(source.name)}\``);
68
+ return;
69
+ }
70
+ const nodes = [];
71
+ for (let i = active.index, n = root.children.length; i < n; i++) {
72
+ if (i === active.index && (source.ignoreHeading ?? active.depth === 1)) {
73
+ continue;
74
+ }
75
+ const node = root.children[i];
76
+ if (node.type === 'heading' &&
77
+ node.depth <= active.depth &&
78
+ i > active.index) {
79
+ break;
80
+ }
81
+ nodes.push(node);
82
+ }
83
+ return nodes;
84
+ };
85
+ export const MD_REF_PATTERN = /<!-{2,} reference-include#(.*?) -{2,}>/;
86
+ export const MDX_REF_PATTERN = /\/\*+ reference-include#(.*?) \*+\//;
87
+ export const maybeHaveRef = (filepath, content) => (filepath.endsWith('.mdx') ? MDX_REF_PATTERN : MD_REF_PATTERN).test(content);
88
+ export const refCache = new Map();
89
+ export const remarkReplace = function ({ localBasePath, items, force }) {
90
+ return async (root, vfile) => {
91
+ const filepath = vfile.path;
92
+ const content = vfile.toString();
93
+ if (!maybeHaveRef(filepath, content)) {
94
+ return;
95
+ }
96
+ return flatMap(root, async (node) => {
97
+ let matched = null;
98
+ if (node.type === 'html') {
99
+ matched = node.value.match(MD_REF_PATTERN);
100
+ }
101
+ else if (node.type === 'mdxFlowExpression') {
102
+ matched = node.value.match(MDX_REF_PATTERN);
103
+ }
104
+ const name = matched?.[1];
105
+ if (!name) {
106
+ return;
107
+ }
108
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
109
+ if (!items[name]) {
110
+ logger.error(`Reference \`${red(name)}\` not found`);
111
+ return;
112
+ }
113
+ if (refCache.has(name)) {
114
+ return refCache.get(name);
115
+ }
116
+ const resolved = await resolveReference(localBasePath, items[name], force);
117
+ refCache.set(name, resolved);
118
+ return resolved;
119
+ });
120
+ };
121
+ };
@@ -0,0 +1,19 @@
1
+ import type { Root } from 'mdast';
2
+ import type { Plugin } from 'unified';
3
+ export interface TocItem {
4
+ id: string;
5
+ text: string;
6
+ depth: number;
7
+ index: number;
8
+ }
9
+ export interface PageMeta {
10
+ toc: TocItem[];
11
+ title: string;
12
+ headingTitle: string;
13
+ frontmatter?: Record<string, unknown>;
14
+ }
15
+ export declare const parseToc: (tree: Root, allDepths?: boolean) => {
16
+ title: string;
17
+ toc: TocItem[];
18
+ };
19
+ export declare const remarkPluginToc: Plugin<[], Root>;
@@ -0,0 +1,61 @@
1
+ import Slugger from 'github-slugger';
2
+ import { visitChildren } from 'unist-util-visit-children';
3
+ import { extractTextAndId } from './utils.js';
4
+ export const parseToc = (tree, allDepths) => {
5
+ let title = '';
6
+ const toc = [];
7
+ const slugger = new Slugger();
8
+ visitChildren((node, index) => {
9
+ if (node.type !== 'heading' || !node.depth || !node.children) {
10
+ return;
11
+ }
12
+ // Collect h1 ~ h4 by default
13
+ if (allDepths || node.depth < 5) {
14
+ let customId = '';
15
+ const text = node.children
16
+ .map((child) => {
17
+ if (child.type === 'link') {
18
+ return child.children?.map((item) => item.value).join('');
19
+ }
20
+ if (child.type === 'strong') {
21
+ return `**${child.children?.map((item) => item.value).join('')}**`;
22
+ }
23
+ if (child.type === 'text') {
24
+ const [textPart, idPart] = extractTextAndId(child.value);
25
+ customId = idPart;
26
+ return textPart;
27
+ }
28
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
29
+ if (child.type === 'inlineCode') {
30
+ return `\`${child.value}\``;
31
+ }
32
+ return '';
33
+ })
34
+ .join('');
35
+ if (!allDepths && node.depth === 1) {
36
+ if (!title) {
37
+ title = text;
38
+ }
39
+ }
40
+ else {
41
+ const id = customId ? customId : slugger.slug(text);
42
+ const { depth } = node;
43
+ toc.push({ id, text, depth, index });
44
+ }
45
+ }
46
+ })(tree);
47
+ return {
48
+ title,
49
+ toc,
50
+ };
51
+ };
52
+ export const remarkPluginToc = function () {
53
+ const data = this.data();
54
+ return (tree) => {
55
+ const { toc, title } = parseToc(tree);
56
+ data.pageMeta.toc = toc;
57
+ if (title) {
58
+ data.pageMeta.title = title;
59
+ }
60
+ };
61
+ };
@@ -0,0 +1,14 @@
1
+ export interface ReferenceItemSource {
2
+ name: string;
3
+ path: string;
4
+ ignoreHeading?: boolean;
5
+ }
6
+ export interface ReferenceItem {
7
+ repo?: string;
8
+ sources: ReferenceItemSource[];
9
+ }
10
+ export interface NormalizedReferenceSource extends ReferenceItemSource {
11
+ repo?: string;
12
+ slug?: string;
13
+ anchor?: string;
14
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import type { Root, Parent } from 'mdast';
2
+ import type { Node } from 'unist';
3
+ import type { MdxjsEsm } from 'mdast-util-mdxjs-esm';
4
+ import type { NormalizedReferenceSource, ReferenceItem } from './types.js';
5
+ /**
6
+ * hello world {#custom-id} -> { text: 'hello world', id: 'custom-id' }
7
+ */
8
+ export declare const extractTextAndId: (title: string) => string[];
9
+ export declare const normalizeReferenceItems: (items: ReferenceItem[]) => Record<string, NormalizedReferenceSource>;
10
+ export declare const flatMap: (root: Root, fn: (node: Node, index: number, parent: Parent | null) => Promise<Node | Node[] | undefined> | Node | Node[] | undefined) => Promise<Root>;
11
+ export declare const getASTNodeImport: (name: string, from: string) => MdxjsEsm;
@@ -0,0 +1,88 @@
1
+ import { logger } from '@rspress/shared/logger';
2
+ import { red } from 'yoctocolors';
3
+ /**
4
+ * hello world {#custom-id} -> { text: 'hello world', id: 'custom-id' }
5
+ */
6
+ export const extractTextAndId = (title) => {
7
+ const customIdReg = /{#.*}/;
8
+ const text = title.replace(customIdReg, '').trimEnd();
9
+ const customId = title.match(customIdReg)?.[0]?.slice(2, -1) || '';
10
+ return [text, customId];
11
+ };
12
+ export const normalizeReferenceItems = (items) => items.reduce((acc, curr) => {
13
+ for (const source of curr.sources) {
14
+ if (source.name in acc) {
15
+ logger.error(`Duplicate source name \`${red(source.name)}\` will be deduplicated`);
16
+ }
17
+ const repo = curr.repo;
18
+ const extra = {};
19
+ if (repo) {
20
+ const url = new URL(repo, 'https://gitlab-ce.alauda.cn');
21
+ extra.repo = url.toString();
22
+ extra.slug = url.pathname.slice(1);
23
+ }
24
+ const [path, anchor] = source.path.split('#');
25
+ acc[source.name] = {
26
+ ...source,
27
+ ...extra,
28
+ path,
29
+ anchor,
30
+ };
31
+ }
32
+ return acc;
33
+ }, {});
34
+ export const flatMap = async (root, fn) => {
35
+ const transformed = await transform(root, 0, null);
36
+ if (!transformed) {
37
+ return root;
38
+ }
39
+ return (Array.isArray(transformed) ? transformed[0] : transformed);
40
+ async function transform(node, index, parent) {
41
+ if ('children' in node && node.children.length) {
42
+ const out = [];
43
+ for (let i = 0, n = node.children.length; i < n; i++) {
44
+ const child = node.children[i];
45
+ let xs = await transform(child, i, node);
46
+ if (xs) {
47
+ xs = Array.isArray(xs) ? xs : [xs];
48
+ for (let j = 0, m = xs.length; j < m; j++) {
49
+ out.push(xs[j]);
50
+ }
51
+ }
52
+ else {
53
+ out.push(child);
54
+ }
55
+ }
56
+ node.children = out;
57
+ }
58
+ return fn(node, index, parent);
59
+ }
60
+ };
61
+ // Construct import statement for AST
62
+ // Such as: import image1 from './test.png'
63
+ export const getASTNodeImport = (name, from) => ({
64
+ type: 'mdxjsEsm',
65
+ value: `import ${name} from ${JSON.stringify(from)}`,
66
+ data: {
67
+ estree: {
68
+ type: 'Program',
69
+ sourceType: 'module',
70
+ body: [
71
+ {
72
+ type: 'ImportDeclaration',
73
+ specifiers: [
74
+ {
75
+ type: 'ImportDefaultSpecifier',
76
+ local: { type: 'Identifier', name },
77
+ },
78
+ ],
79
+ source: {
80
+ type: 'Literal',
81
+ value: from,
82
+ raw: JSON.stringify(from),
83
+ },
84
+ },
85
+ ],
86
+ },
87
+ },
88
+ });
@@ -1,11 +1,11 @@
1
1
  import { UserConfig } from '@rspress/core';
2
- import { DoomSite } from '../shared/index.js';
2
+ import type { ApiPluginOptions } from '../plugins/api/types.js';
3
+ import type { AutoSidebarPluginOptions } from '../plugins/index.js';
4
+ import type { ReferenceItem } from '../plugins/reference/types.js';
5
+ import type { DoomSite } from '../shared/index.js';
3
6
  export interface DoomConfig extends UserConfig {
4
- api?: {
5
- crds?: string[];
6
- openapis?: string[];
7
- references?: Record<string, string>;
8
- pathPrefix?: string;
9
- };
7
+ api?: ApiPluginOptions;
10
8
  sites?: DoomSite[];
9
+ reference?: ReferenceItem[];
10
+ sidebar?: AutoSidebarPluginOptions;
11
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alauda/doom",
3
- "version": "0.5.5",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Doctor Doom making docs.",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "clean": "tsc -b src --clean",
30
30
  "dev": "yarn swc-node --watch-path src/cli --watch-path src/plugins src/cli/index.ts",
31
31
  "doom": "yarn swc-node src/cli/index.ts",
32
- "fixture": "yarn doom fixture-docs",
32
+ "fixture": "yarn dev fixture-docs",
33
33
  "lint": "run-p 'lint:*'",
34
34
  "lint:es": "eslint .",
35
35
  "lint:tsc": "tsc -b",