@alauda/doom 0.6.12 → 0.6.14

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.
@@ -19,19 +19,10 @@ const zhLocaleConfig = {
19
19
  prevPageText: '上一页',
20
20
  nextPageText: '下一页',
21
21
  };
22
- const getCommonConfig = (config, cliRoot, prefix, configFilePath, version, force) => {
22
+ const getCommonConfig = (config, cliRoot, configFilePath, version, force) => {
23
23
  const fallbackToZh = 'lang' in config && config.lang == null;
24
24
  const root = resolveDocRoot(CWD, cliRoot, config.root);
25
- let base = addLeadingSlash(config.base || '/');
26
- if (version && version !== 'unversioned') {
27
- base = removeTrailingSlash(base) + `/${version}`;
28
- }
29
- base = addTrailingSlash(base);
30
- if (prefix) {
31
- base = normalizeSlash(prefix) + base;
32
- }
33
25
  return {
34
- base,
35
26
  root,
36
27
  lang: fallbackToZh ? 'zh' : config.lang,
37
28
  route: {
@@ -72,7 +63,6 @@ const getCommonConfig = (config, cliRoot, prefix, configFilePath, version, force
72
63
  version,
73
64
  }),
74
65
  referencePlugin({
75
- base,
76
66
  root,
77
67
  lang: fallbackToZh ? null : (config.lang ?? 'en'),
78
68
  localBasePath: configFilePath ? path.dirname(configFilePath) : root,
@@ -166,11 +156,18 @@ export async function loadConfig(root, configFile, prefix, version, force) {
166
156
  }
167
157
  }
168
158
  const normalizedVersion = normalizeVersion(version);
169
- const commonConfig = getCommonConfig(config, root, prefix, configFilePath, normalizedVersion, force);
159
+ const commonConfig = getCommonConfig(config, root, configFilePath, normalizedVersion, force);
170
160
  const mergedConfig = mergeRsbuildConfig(commonConfig, config, {
171
- base: commonConfig.base,
172
161
  root: commonConfig.root,
173
162
  });
163
+ let base = addLeadingSlash(mergedConfig.base || '/');
164
+ if (normalizedVersion && normalizedVersion !== 'unversioned') {
165
+ base = removeTrailingSlash(base) + `/${normalizedVersion}`;
166
+ }
167
+ mergedConfig.base = base = addTrailingSlash(base);
168
+ if (prefix) {
169
+ mergedConfig.base = normalizeSlash(prefix) + base;
170
+ }
174
171
  let ensureDefaultLogo = false;
175
172
  if (!mergedConfig.logo) {
176
173
  mergedConfig.logo = DEFAULT_LOGO;
@@ -201,9 +198,6 @@ export async function loadConfig(root, configFile, prefix, version, force) {
201
198
  addTrailingSlash(mergedConfig.outDir) + normalizedVersion;
202
199
  }
203
200
  else {
204
- const base = prefix
205
- ? mergedConfig.base.replace(normalizeSlash(prefix), '')
206
- : mergedConfig.base;
207
201
  mergedConfig.outDir = `dist${normalizedVersion === 'unversioned' ? `/unversioned${base}` : base}`;
208
202
  }
209
203
  if (mergedConfig.builderConfig?.server?.open === true) {
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { isProduction, usePageData } from '@rspress/core/runtime';
2
+ import { isProduction, removeTrailingSlash, usePageData, } from '@rspress/core/runtime';
3
3
  import { noop } from 'es-toolkit';
4
4
  import { useEffect, useMemo, useState } from 'react';
5
5
  import { createPortal } from 'react-dom';
@@ -11,7 +11,10 @@ export const VersionsNav = () => {
11
11
  if (!page.v) {
12
12
  return [];
13
13
  }
14
- return [siteData.base.slice(0, -page.v.length - 1), page.v];
14
+ return [
15
+ removeTrailingSlash(siteData.base).slice(0, -page.v.length - 1),
16
+ page.v,
17
+ ];
15
18
  }, [siteData.base, page.v]);
16
19
  const [navMenu, setNavMenu] = useState();
17
20
  const [versions, setVersions] = useState();
@@ -1,7 +1,6 @@
1
1
  import type { RspressPlugin } from '@rspress/core';
2
2
  import type { ReferenceItem, ReleaseNotesOptions } from './types.js';
3
3
  export declare const referencePlugin: ({ root, lang, localBasePath, items, force, releaseNotes, }: {
4
- base: string;
5
4
  root: string;
6
5
  lang: string | null;
7
6
  localBasePath: string;
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import { logger } from '@rspress/shared/logger';
3
- import { MD_RELEASE_COMMENT_PATTERN, MDX_RELEASE_COMMENT_PATTERN, refCache, releaseCache, remarkReplace, } from './remark-replace.js';
3
+ import { MD_RELEASE_COMMENT_PATTERN, MDX_RELEASE_COMMENT_PATTERN, remarkReplace, } from './remark-replace.js';
4
4
  import { mdProcessor, mdxProcessor, normalizeReferenceItems } from './utils.js';
5
5
  export const referencePlugin = ({ root, lang, localBasePath, items = [], force, releaseNotes, }) => {
6
6
  const normalizedItems = normalizeReferenceItems(items);
@@ -21,11 +21,7 @@ export const referencePlugin = ({ root, lang, localBasePath, items = [], force,
21
21
  ],
22
22
  ],
23
23
  },
24
- async modifySearchIndexData(pages, isProd) {
25
- if (!isProd) {
26
- refCache.clear();
27
- releaseCache.clear();
28
- }
24
+ async modifySearchIndexData(pages) {
29
25
  const results = await Promise.allSettled(pages.map(async (page) => {
30
26
  const filepath = page._filepath;
31
27
  if (!/\.mdx?$/.test(filepath)) {
@@ -0,0 +1,10 @@
1
+ import type { Content } from 'mdast';
2
+ import type { NormalizedReferenceSource } from './types.js';
3
+ export declare const normalizeImgSrc: (content: Content, { refSource, localPublicBase, publicBase, sourceBase, targetBase, force, }: {
4
+ refSource: NormalizedReferenceSource;
5
+ localPublicBase: string;
6
+ publicBase: string;
7
+ sourceBase: string;
8
+ targetBase: string;
9
+ force?: boolean;
10
+ }) => Content;
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { isExternalUrl, removeLeadingSlash } from '@rspress/core';
4
+ import { cloneDeep } from 'es-toolkit';
5
+ import { visit } from 'unist-util-visit';
6
+ const RELATIVE_URL_PATTERN = /^\.\.?\//;
7
+ export const normalizeImgSrc = (content, { refSource, localPublicBase, publicBase, sourceBase, targetBase, force, }) => {
8
+ content = cloneDeep(content);
9
+ const resolveImgSrc = (src, force) => {
10
+ if (isExternalUrl(src)) {
11
+ return src;
12
+ }
13
+ if (refSource.repo) {
14
+ const targetDir = path.resolve(localPublicBase, '_remotes', refSource.name);
15
+ let sourcePath;
16
+ let targetPath;
17
+ let imageSrc;
18
+ if (RELATIVE_URL_PATTERN.test(src)) {
19
+ sourcePath = path.resolve(sourceBase, src);
20
+ imageSrc = path.relative(sourceBase, sourcePath);
21
+ targetPath = path.resolve(targetDir, imageSrc);
22
+ }
23
+ else {
24
+ imageSrc = removeLeadingSlash(src);
25
+ sourcePath = path.resolve(publicBase, imageSrc);
26
+ targetPath = path.resolve(targetDir, imageSrc);
27
+ }
28
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
29
+ if (force || !fs.existsSync(targetPath)) {
30
+ fs.copyFileSync(sourcePath, targetPath);
31
+ }
32
+ return `/_remotes/${refSource.name}/${imageSrc}`;
33
+ }
34
+ else if (!RELATIVE_URL_PATTERN.test(src)) {
35
+ return src;
36
+ }
37
+ const targetSrc = path.relative(targetBase, path.resolve(sourceBase, src));
38
+ return RELATIVE_URL_PATTERN.test(targetSrc) ? targetSrc : `./${targetSrc}`;
39
+ };
40
+ visit(content, 'image', (node) => {
41
+ node.url = resolveImgSrc(node.url, force);
42
+ });
43
+ visit(content, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node_) => {
44
+ const node = node_;
45
+ if (node.name !== 'img') {
46
+ return;
47
+ }
48
+ const srcNode = node.attributes.find((attr) => 'name' in attr && attr.name === 'src');
49
+ if (srcNode?.type !== 'mdxJsxAttribute') {
50
+ return;
51
+ }
52
+ const src = srcNode.value;
53
+ if (typeof src !== 'string') {
54
+ return;
55
+ }
56
+ srcNode.value = resolveImgSrc(src, force);
57
+ });
58
+ return content;
59
+ };
@@ -1,8 +1,6 @@
1
- import type { Content, Root } from 'mdast';
1
+ import type { Root } from 'mdast';
2
2
  import { type Plugin } from 'unified';
3
3
  import type { NormalizedReferenceSource, ReleaseNotesOptions } from './types.js';
4
- export declare const refCache: Map<string, Promise<Content[] | undefined>>;
5
- export declare const releaseCache: Map<string, Promise<Record<string, Content | Content[]> | undefined>>;
6
4
  export declare const MD_RELEASE_COMMENT_PATTERN: RegExp;
7
5
  export declare const MDX_RELEASE_COMMENT_PATTERN: RegExp;
8
6
  export declare const maybeHaveRef: (filepath: string, content: string) => boolean | undefined;
@@ -1,211 +1,13 @@
1
1
  import fs from 'node:fs/promises';
2
- import os from 'node:os';
3
2
  import path from 'node:path';
4
3
  import { isProduction } from '@rspress/core';
5
4
  import { logger } from '@rspress/shared/logger';
6
- import { render } from 'ejs';
7
- import { simpleGit } from 'simple-git';
8
5
  import { parse, stringify } from 'yaml';
9
6
  import { cyan, red } from 'yoctocolors';
10
- import { parseToc } from './parse-toc.js';
7
+ import { normalizeImgSrc } from './normalize-img-src.js';
11
8
  import { getFrontmatterNode, mdProcessor, mdxProcessor } from './utils.js';
12
- const remotesFolder = path.resolve(os.homedir(), '.doom/remotes');
13
- export const refCache = new Map();
14
- const resolveReference_ = async (localBasePath, items, refName, force) => {
15
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
16
- if (!items[refName]) {
17
- logger.error(`Reference \`${red(refName)}\` not found`);
18
- return;
19
- }
20
- const source = items[refName];
21
- let sourcePath = source.path;
22
- if (source.repo) {
23
- const repoFolder = path.resolve(remotesFolder, source.slug);
24
- let created = false;
25
- try {
26
- const stat = await fs.stat(path.resolve(repoFolder, '.git'));
27
- if (stat.isDirectory()) {
28
- created = true;
29
- }
30
- }
31
- catch {
32
- // ignore
33
- }
34
- if (!created) {
35
- await fs.mkdir(repoFolder, { recursive: true });
36
- }
37
- const git = simpleGit(repoFolder);
38
- if (!created) {
39
- logger.info(`Cloning remote \`${cyan(source.slug)}\` repository...`);
40
- await git.clone(source.repo, repoFolder, ['--depth', '1']);
41
- }
42
- if (force) {
43
- logger.info(`Pulling latest changes for \`${cyan(source.slug)}\`...`);
44
- await git.pull([
45
- '--depth',
46
- '1',
47
- '--force',
48
- '--rebase',
49
- '--allow-unrelated-histories',
50
- ]);
51
- }
52
- sourcePath = path.resolve(repoFolder, sourcePath);
53
- }
54
- else {
55
- sourcePath = path.resolve(localBasePath, sourcePath);
56
- }
57
- let found = false;
58
- try {
59
- const stat = await fs.stat(sourcePath);
60
- found = stat.isFile();
61
- }
62
- catch {
63
- //
64
- }
65
- if (!found) {
66
- logger.error(`Reference path \`${red(source.path)}\` for \`${red(source.name)}\` not found`);
67
- return;
68
- }
69
- let content = await fs.readFile(sourcePath, 'utf8');
70
- for (const processor of source.processors ?? []) {
71
- switch (processor.type) {
72
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
73
- case 'ejsTemplate': {
74
- content = await render(content, { data: processor.data }, { async: true });
75
- break;
76
- }
77
- }
78
- }
79
- const processor = (sourcePath.endsWith('.ejs')
80
- ? sourcePath.slice(0, -4)
81
- : sourcePath).endsWith('.mdx')
82
- ? mdxProcessor
83
- : mdProcessor;
84
- const root = processor.parse(content);
85
- if (!source.anchor) {
86
- return root.children;
87
- }
88
- const frontmatterNode = getFrontmatterNode(root);
89
- const { toc } = parseToc(root, true);
90
- const active = toc.find((it) => it.id === source.anchor);
91
- if (!active) {
92
- logger.error(`Anchor \`${red(source.anchor)}\` not found in \`${red(source.name)}\``);
93
- return;
94
- }
95
- const nodes = frontmatterNode ? [frontmatterNode] : [];
96
- for (let i = active.index, n = root.children.length; i < n; i++) {
97
- if (i === active.index && (source.ignoreHeading ?? active.depth === 1)) {
98
- continue;
99
- }
100
- const node = root.children[i];
101
- if (node.type === 'heading' &&
102
- node.depth <= active.depth &&
103
- i > active.index) {
104
- break;
105
- }
106
- nodes.push(node);
107
- }
108
- return nodes;
109
- };
110
- const resolveReference = async (localBasePath, items, refName, force) => {
111
- if (refCache.has(refName)) {
112
- return refCache.get(refName);
113
- }
114
- const resolving = resolveReference_(localBasePath, items, refName, force);
115
- refCache.set(refName, resolving);
116
- return resolving;
117
- };
118
- export const releaseCache = new Map();
119
- const FIELD_MAPPER = {
120
- zh: 'customfield_13800',
121
- en: 'customfield_13801',
122
- };
123
- const { CI, JIRA_TOKEN, JIRA_USERNAME, JIRA_PASSWORD } = process.env;
124
- const isCi = CI !== 'false' && !!CI;
125
- const issuesToMdast = (issues, lang) => {
126
- return issues
127
- .map((issue) => {
128
- const description = ((lang !== 'en' && issue.fields[FIELD_MAPPER[lang]]) ||
129
- issue.fields[FIELD_MAPPER.en])?.trim();
130
- if (!description) {
131
- return;
132
- }
133
- return {
134
- type: 'listItem',
135
- children: [
136
- {
137
- type: 'paragraph',
138
- children: description
139
- .split('\n')
140
- .map((line) => {
141
- return {
142
- type: 'text',
143
- value: line,
144
- };
145
- })
146
- .reduce((acc, curr, index) => {
147
- if (index === 0) {
148
- return [curr];
149
- }
150
- return acc.concat({ type: 'html', value: '<br>' }, curr);
151
- }, []),
152
- },
153
- ],
154
- };
155
- })
156
- .filter((_) => !!_);
157
- };
158
- const resolveRelease_ = async (releaseTemplates, releaseQuery) => {
159
- const query = new URLSearchParams(releaseQuery);
160
- const templateName = query.get('template');
161
- if (!templateName) {
162
- logger.error(`Release notes template not found for query \`${red(releaseQuery)}\``);
163
- return;
164
- }
165
- const template = releaseTemplates[templateName];
166
- if (!template) {
167
- logger.error(`Release notes template \`${red(templateName)}\` not found`);
168
- return;
169
- }
170
- let Authorization;
171
- if (JIRA_TOKEN) {
172
- Authorization = `Bearer ${JIRA_TOKEN}`;
173
- }
174
- else if (JIRA_USERNAME && JIRA_PASSWORD) {
175
- Authorization = `Basic ${Buffer.from(`${JIRA_USERNAME}:${JIRA_PASSWORD}`).toString('base64')}`;
176
- }
177
- else {
178
- throw new Error('`JIRA_TOKEN` or `JIRA_USERNAME` and `JIRA_PASSWORD` environments must be set for fetching Jira issues');
179
- }
180
- const data = {};
181
- for (const [key, value] of query.entries()) {
182
- if (key === 'template') {
183
- continue;
184
- }
185
- data[key] = value;
186
- }
187
- const jql = await render(template, data, { async: true });
188
- logger.info(`Fetching release notes for query \`${cyan(releaseQuery)}\``);
189
- const res = await fetch(`https://jira.alauda.cn/rest/api/2/search?${new URLSearchParams({ jql })}`, { headers: { Authorization } });
190
- if (!res.ok) {
191
- logger.error(`Failed to fetch release notes for query \`${red(releaseQuery)}\` with status \`${res.status}\``);
192
- return;
193
- }
194
- const { issues } = (await res.json());
195
- return ['en', 'zh'].reduce((acc, curr) => Object.assign(acc, {
196
- [curr]: { type: 'list', children: issuesToMdast(issues, curr) },
197
- }), {});
198
- };
199
- const resolveRelease = async (releaseTemplates, releaseQuery, lang) => {
200
- if (releaseCache.has(releaseQuery)) {
201
- const cached = await releaseCache.get(releaseQuery);
202
- return cached?.[lang] ?? cached?.en;
203
- }
204
- const resolving = resolveRelease_(releaseTemplates, releaseQuery);
205
- releaseCache.set(releaseQuery, resolving);
206
- const resolved = await resolving;
207
- return resolved?.[lang] ?? resolved?.en;
208
- };
9
+ import { resolveReference } from './resolve-reference.js';
10
+ import { resolveRelease } from './resolve-release.js';
209
11
  const MD_REF_START_COMMENT_PATTERN = /<!-{2,} *reference-start#(.+) *-{2,}>/;
210
12
  const MDX_REF_START_COMMENT_PATTERN = /{\/\*+ *reference-start#(.+) *\*+\/}/;
211
13
  const MDX_REF_START_PATTERN = /\/\*+ *reference-start#(.+) *\*+\//;
@@ -222,6 +24,8 @@ export const maybeHaveRef = (filepath, content) => {
222
24
  ? [MDX_REF_START_COMMENT_PATTERN, MDX_RELEASE_COMMENT_PATTERN]
223
25
  : [MD_REF_START_COMMENT_PATTERN, MD_RELEASE_COMMENT_PATTERN]).some((p) => p.test(content));
224
26
  };
27
+ const { CI } = process.env;
28
+ const isCi = CI !== 'false' && !!CI;
225
29
  export const remarkReplace = function ({ lang, localBasePath, root, items, force, releaseNotes }) {
226
30
  return async (ast, vfile) => {
227
31
  const filepath = vfile.path;
@@ -229,6 +33,8 @@ export const remarkReplace = function ({ lang, localBasePath, root, items, force
229
33
  if (!maybeHaveRef(filepath, content)) {
230
34
  return;
231
35
  }
36
+ const localPublicBase = path.resolve(root, 'public');
37
+ const targetBase = path.dirname(filepath);
232
38
  const isMdx = filepath.endsWith('.mdx');
233
39
  const processor = isMdx ? mdxProcessor : mdProcessor;
234
40
  const originalAst = vfile.data.original
@@ -237,53 +43,55 @@ export const remarkReplace = function ({ lang, localBasePath, root, items, force
237
43
  const frontmatterNode = getFrontmatterNode(originalAst);
238
44
  let frontmatter = frontmatterNode &&
239
45
  parse(frontmatterNode.value);
240
- const newAstChildren = [];
241
46
  const newContentChildren = [];
242
- let index = 0;
243
- let start = null;
47
+ let start = false;
244
48
  let refName = '';
245
49
  let matched;
246
50
  let checkContent = false;
247
51
  const relativePath = path.relative(root, filepath);
248
- const currLang = lang === null ? 'zh' : relativePath.split('/')[0];
249
- for (const node of ast.children) {
250
- index++;
52
+ for (const node of originalAst.children) {
251
53
  if (node.type !== (isMdx ? 'mdxFlowExpression' : 'html')) {
252
54
  if (node.type === 'yaml') {
253
55
  continue;
254
56
  }
255
- newAstChildren.push(node);
256
- if (start == null) {
57
+ if (!start) {
257
58
  newContentChildren.push(node);
258
59
  }
259
60
  continue;
260
61
  }
261
62
  if ((matched = node.value.match(isMdx ? MDX_REF_START_PATTERN : MD_REF_START_COMMENT_PATTERN))) {
262
- if (start != null) {
63
+ if (start) {
263
64
  logger.warn(`Invalid reference start block ${red(node.value)}, nested reference blocks are not allowed`);
264
65
  }
265
66
  else {
266
67
  checkContent = true;
267
- start = index;
68
+ start = true;
268
69
  refName = matched[1].trim();
269
70
  }
270
- newAstChildren.push(node);
271
71
  newContentChildren.push(node);
272
72
  continue;
273
73
  }
274
74
  if ((isMdx ? MDX_REF_END_PATTERN : MD_REF_END_COMMENT_PATTERN).test(node.value)) {
275
- if (start == null) {
276
- logger.warn(`Invalid reference end block ${red(node.value)}, no matching start block found`);
75
+ if (start) {
76
+ start = false;
277
77
  }
278
78
  else {
279
- start = null;
79
+ logger.warn(`Invalid reference end block ${red(node.value)}, no matching start block found`);
280
80
  }
281
- const resolved = await resolveReference(localBasePath, items, refName, force);
81
+ const resolved = await resolveReference(localBasePath, localPublicBase, items, refName, force);
282
82
  if (resolved) {
283
- const { frontmatterMode } = items[refName];
284
- for (const nodeItem of resolved) {
83
+ const refSource = items[refName];
84
+ const { frontmatterMode } = refSource;
85
+ for (const nodeItem of resolved.contents) {
285
86
  if (nodeItem.type !== 'yaml') {
286
- newContentChildren.push(nodeItem);
87
+ newContentChildren.push(normalizeImgSrc(nodeItem, {
88
+ refSource,
89
+ localPublicBase,
90
+ targetBase,
91
+ publicBase: resolved.publicBase,
92
+ sourceBase: resolved.sourceBase,
93
+ force,
94
+ }));
287
95
  continue;
288
96
  }
289
97
  if (!frontmatterMode || frontmatterMode === 'ignore') {
@@ -308,23 +116,14 @@ export const remarkReplace = function ({ lang, localBasePath, root, items, force
308
116
  }
309
117
  }
310
118
  }
311
- newAstChildren.push(node);
312
119
  newContentChildren.push(node);
313
120
  continue;
314
121
  }
315
- if ((matched = node.value.match(isMdx ? MDX_RELEASE_PATTERN : MD_RELEASE_COMMENT_PATTERN))) {
316
- if (start != null) {
317
- logger.warn(`Invalid release-notes-for-bugs comment ${red(refName)}, nested reference blocks are not allowed`);
318
- newAstChildren.push(node);
319
- }
320
- else {
321
- const releaseContent = await resolveRelease(releaseNotes?.queryTemplates ?? {}, matched[1].trim(), currLang);
322
- newAstChildren.push(releaseContent ?? node);
323
- }
122
+ if (!start) {
324
123
  newContentChildren.push(node);
325
124
  }
326
125
  }
327
- if (start != null) {
126
+ if (start) {
328
127
  logger.warn(`Invalid reference start block ${red(refName)}, no matching end block found, adding for you`);
329
128
  newContentChildren.push({
330
129
  type: isMdx ? 'mdxFlowExpression' : 'html',
@@ -340,13 +139,7 @@ export const remarkReplace = function ({ lang, localBasePath, root, items, force
340
139
  if (checkContent) {
341
140
  const newContent = processor.stringify({
342
141
  ...ast,
343
- children: newContentChildren.flat().filter((n) => {
344
- if (n.type !== 'mdxjsEsm') {
345
- return true;
346
- }
347
- const matched = n.value.match(/^import\b.+\bfrom\b\s+(['"])([^'"]+)\1$/);
348
- return !matched?.[2] || !path.isAbsolute(matched[2]);
349
- }),
142
+ children: newContentChildren.flat(),
350
143
  });
351
144
  if (content !== newContent) {
352
145
  await fs.writeFile(filepath, newContent);
@@ -360,6 +153,20 @@ export const remarkReplace = function ({ lang, localBasePath, root, items, force
360
153
  return;
361
154
  }
362
155
  }
156
+ const newAstChildren = [];
157
+ const currLang = lang === null ? 'zh' : relativePath.split('/')[0];
158
+ for (const node of ast.children) {
159
+ if (node.type !== (isMdx ? 'mdxFlowExpression' : 'html')) {
160
+ newAstChildren.push(node);
161
+ continue;
162
+ }
163
+ if ((matched = node.value.match(isMdx ? MDX_RELEASE_PATTERN : MD_RELEASE_COMMENT_PATTERN))) {
164
+ const releaseContent = await resolveRelease(releaseNotes?.queryTemplates ?? {}, matched[1].trim(), currLang);
165
+ newAstChildren.push(releaseContent ?? node);
166
+ continue;
167
+ }
168
+ newAstChildren.push(node);
169
+ }
363
170
  ast.children = newAstChildren.flat();
364
171
  };
365
172
  };
@@ -0,0 +1,8 @@
1
+ import type { Content } from 'mdast';
2
+ import type { NormalizedReferenceSource } from './types.js';
3
+ export interface ResolveReferenceResult {
4
+ publicBase: string;
5
+ sourceBase: string;
6
+ contents: Content[];
7
+ }
8
+ export declare const resolveReference: (localBasePath: string, localPublicBase: string, items: Record<string, NormalizedReferenceSource>, refName: string, force?: boolean) => Promise<ResolveReferenceResult | undefined>;
@@ -0,0 +1,134 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { isProduction } from '@rspress/core';
5
+ import { logger } from '@rspress/shared/logger';
6
+ import { render } from 'ejs';
7
+ import { simpleGit } from 'simple-git';
8
+ import { cyan, red } from 'yoctocolors';
9
+ import { parseToc } from './parse-toc.js';
10
+ import { getFrontmatterNode, mdProcessor, mdxProcessor } from './utils.js';
11
+ const remotesFolder = path.resolve(os.homedir(), '.doom/remotes');
12
+ const refCache = new Map();
13
+ const resolveReference_ = async (localBasePath, localPublicBase, items, refName, force) => {
14
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
15
+ if (!items[refName]) {
16
+ logger.error(`Reference \`${red(refName)}\` not found`);
17
+ return;
18
+ }
19
+ const source = items[refName];
20
+ let publicBase;
21
+ let sourcePath = source.path;
22
+ if (source.repo) {
23
+ const repoFolder = path.resolve(remotesFolder, source.slug);
24
+ let created = false;
25
+ try {
26
+ const stat = await fs.stat(path.resolve(repoFolder, '.git'));
27
+ if (stat.isDirectory()) {
28
+ created = true;
29
+ }
30
+ }
31
+ catch {
32
+ // ignore
33
+ }
34
+ if (!created) {
35
+ await fs.mkdir(repoFolder, { recursive: true });
36
+ }
37
+ const git = simpleGit(repoFolder);
38
+ if (!created) {
39
+ logger.info(`Cloning remote \`${cyan(source.slug)}\` repository...`);
40
+ await git.clone(source.repo, repoFolder, ['--depth', '1']);
41
+ }
42
+ if (force) {
43
+ logger.info(`Pulling latest changes for \`${cyan(source.slug)}\`...`);
44
+ await git.pull([
45
+ '--depth',
46
+ '1',
47
+ '--force',
48
+ '--rebase',
49
+ '--allow-unrelated-histories',
50
+ ]);
51
+ }
52
+ publicBase = path.resolve(repoFolder, source.publicBase ?? 'docs/public');
53
+ sourcePath = path.resolve(repoFolder, sourcePath);
54
+ }
55
+ else {
56
+ publicBase = localPublicBase;
57
+ sourcePath = path.resolve(localBasePath, sourcePath);
58
+ }
59
+ let found = false;
60
+ try {
61
+ const stat = await fs.stat(sourcePath);
62
+ found = stat.isFile();
63
+ }
64
+ catch {
65
+ //
66
+ }
67
+ if (!found) {
68
+ logger.error(`Reference path \`${red(source.path)}\` for \`${red(source.name)}\` not found`);
69
+ return;
70
+ }
71
+ let content = await fs.readFile(sourcePath, 'utf8');
72
+ for (const processor of source.processors ?? []) {
73
+ switch (processor.type) {
74
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
75
+ case 'ejsTemplate': {
76
+ content = await render(content, { data: processor.data }, { async: true });
77
+ break;
78
+ }
79
+ }
80
+ }
81
+ const processor = (sourcePath.endsWith('.ejs')
82
+ ? sourcePath.slice(0, -4)
83
+ : sourcePath).endsWith('.mdx')
84
+ ? mdxProcessor
85
+ : mdProcessor;
86
+ const root = processor.parse(content);
87
+ const sourceBase = path.dirname(sourcePath);
88
+ if (!source.anchor) {
89
+ return {
90
+ publicBase,
91
+ sourceBase,
92
+ contents: root.children,
93
+ };
94
+ }
95
+ const frontmatterNode = getFrontmatterNode(root);
96
+ const { toc } = parseToc(root, true);
97
+ const active = toc.find((it) => it.id === source.anchor) ??
98
+ toc.find((it) => it.text === source.anchor);
99
+ if (!active) {
100
+ logger.error(`Anchor \`${red(source.anchor)}\` not found in \`${red(source.name)}\``);
101
+ return;
102
+ }
103
+ const nodes = frontmatterNode ? [frontmatterNode] : [];
104
+ for (let i = active.index, n = root.children.length; i < n; i++) {
105
+ if (i === active.index && (source.ignoreHeading ?? active.depth === 1)) {
106
+ continue;
107
+ }
108
+ const node = root.children[i];
109
+ if (node.type === 'heading' &&
110
+ node.depth <= active.depth &&
111
+ i > active.index) {
112
+ break;
113
+ }
114
+ nodes.push(node);
115
+ }
116
+ return {
117
+ publicBase,
118
+ sourceBase,
119
+ contents: nodes,
120
+ };
121
+ };
122
+ export const resolveReference = async (localBasePath, localPublicBase, items, refName, force) => {
123
+ if (refCache.has(refName)) {
124
+ return refCache.get(refName);
125
+ }
126
+ const resolving = resolveReference_(localBasePath, localPublicBase, items, refName, force);
127
+ refCache.set(refName, resolving);
128
+ if (!isProduction()) {
129
+ setTimeout(() => {
130
+ refCache.delete(refName);
131
+ }, 5_000);
132
+ }
133
+ return resolving;
134
+ };
@@ -0,0 +1,2 @@
1
+ import type { Content } from 'mdast';
2
+ export declare const resolveRelease: (releaseTemplates: Record<string, string>, releaseQuery: string, lang: string) => Promise<Content | Content[] | undefined>;
@@ -0,0 +1,93 @@
1
+ import { logger } from '@rspress/shared/logger';
2
+ import { render } from 'ejs';
3
+ import { cyan, red } from 'yoctocolors';
4
+ const releaseCache = new Map();
5
+ const FIELD_MAPPER = {
6
+ zh: 'customfield_13800',
7
+ en: 'customfield_13801',
8
+ };
9
+ const { JIRA_TOKEN, JIRA_USERNAME, JIRA_PASSWORD } = process.env;
10
+ const issuesToMdast = (issues, lang) => {
11
+ return issues
12
+ .map((issue) => {
13
+ const description = ((lang !== 'en' && issue.fields[FIELD_MAPPER[lang]]) ||
14
+ issue.fields[FIELD_MAPPER.en])?.trim();
15
+ if (!description) {
16
+ return;
17
+ }
18
+ return {
19
+ type: 'listItem',
20
+ children: [
21
+ {
22
+ type: 'paragraph',
23
+ children: description
24
+ .split('\n')
25
+ .map((line) => {
26
+ return {
27
+ type: 'text',
28
+ value: line,
29
+ };
30
+ })
31
+ .reduce((acc, curr, index) => {
32
+ if (index === 0) {
33
+ return [curr];
34
+ }
35
+ return acc.concat({ type: 'html', value: '<br>' }, curr);
36
+ }, []),
37
+ },
38
+ ],
39
+ };
40
+ })
41
+ .filter((_) => !!_);
42
+ };
43
+ const resolveRelease_ = async (releaseTemplates, releaseQuery) => {
44
+ const query = new URLSearchParams(releaseQuery);
45
+ const templateName = query.get('template');
46
+ if (!templateName) {
47
+ logger.error(`Release notes template not found for query \`${red(releaseQuery)}\``);
48
+ return;
49
+ }
50
+ const template = releaseTemplates[templateName];
51
+ if (!template) {
52
+ logger.error(`Release notes template \`${red(templateName)}\` not found`);
53
+ return;
54
+ }
55
+ let Authorization;
56
+ if (JIRA_TOKEN) {
57
+ Authorization = `Bearer ${JIRA_TOKEN}`;
58
+ }
59
+ else if (JIRA_USERNAME && JIRA_PASSWORD) {
60
+ Authorization = `Basic ${Buffer.from(`${JIRA_USERNAME}:${JIRA_PASSWORD}`).toString('base64')}`;
61
+ }
62
+ else {
63
+ throw new Error('`JIRA_TOKEN` or `JIRA_USERNAME` and `JIRA_PASSWORD` environments must be set for fetching Jira issues');
64
+ }
65
+ const data = {};
66
+ for (const [key, value] of query.entries()) {
67
+ if (key === 'template') {
68
+ continue;
69
+ }
70
+ data[key] = value;
71
+ }
72
+ const jql = await render(template, data, { async: true });
73
+ logger.info(`Fetching release notes for query \`${cyan(releaseQuery)}\``);
74
+ const res = await fetch(`https://jira.alauda.cn/rest/api/2/search?${new URLSearchParams({ jql })}`, { headers: { Authorization } });
75
+ if (!res.ok) {
76
+ logger.error(`Failed to fetch release notes for query \`${red(releaseQuery)}\` with status \`${res.status}\``);
77
+ return;
78
+ }
79
+ const { issues } = (await res.json());
80
+ return ['en', 'zh'].reduce((acc, curr) => Object.assign(acc, {
81
+ [curr]: { type: 'list', children: issuesToMdast(issues, curr) },
82
+ }), {});
83
+ };
84
+ export const resolveRelease = async (releaseTemplates, releaseQuery, lang) => {
85
+ if (releaseCache.has(releaseQuery)) {
86
+ const cached = await releaseCache.get(releaseQuery);
87
+ return cached?.[lang] ?? cached?.en;
88
+ }
89
+ const resolving = resolveRelease_(releaseTemplates, releaseQuery);
90
+ releaseCache.set(releaseQuery, resolving);
91
+ const resolved = await resolving;
92
+ return resolved?.[lang] ?? resolved?.en;
93
+ };
@@ -11,10 +11,12 @@ export interface ReferenceItemSource {
11
11
  }
12
12
  export interface ReferenceItem {
13
13
  repo?: string;
14
+ publicBase?: string;
14
15
  sources: ReferenceItemSource[];
15
16
  }
16
17
  export interface NormalizedReferenceSource extends ReferenceItemSource {
17
18
  repo?: string;
19
+ publicBase?: string;
18
20
  slug?: string;
19
21
  anchor?: string;
20
22
  }
@@ -31,6 +31,7 @@ export const normalizeReferenceItems = (items) => items.reduce((acc, curr) => {
31
31
  acc[source.name] = {
32
32
  ...source,
33
33
  ...extra,
34
+ publicBase: curr.publicBase,
34
35
  path,
35
36
  anchor,
36
37
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alauda/doom",
3
- "version": "0.6.12",
3
+ "version": "0.6.14",
4
4
  "type": "module",
5
5
  "description": "Doctor Doom making docs.",
6
6
  "repository": {