soma-core 2.2.8 → 2.2.9

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.
Files changed (93) hide show
  1. package/core/build/compiler/full-manifest-builder.ts +1 -1
  2. package/core/build/compiler/host-config-sync.cjs +1 -1
  3. package/core/build/compiler/soma-manifest-webpack-plugin.js +2 -6
  4. package/core/build/compiler/soma-precompile.js +80 -4
  5. package/core/client/a11y/announcer.ts +2 -16
  6. package/core/client/base/SomaPageRootBase.ts +2 -2
  7. package/core/client/base/defineSomaView.ts +11 -2
  8. package/core/client/base/runtime-services.types.ts +57 -0
  9. package/core/client/data/role-gate.ts +2 -8
  10. package/core/client/engine/event-engine.ts +1 -0
  11. package/core/client/engines/diff/adapter-jsdiff.ts +27 -8
  12. package/core/client/engines/diff/index.ts +81 -6
  13. package/core/client/engines/diff/items.ts +212 -0
  14. package/core/client/engines/diff/port.ts +140 -3
  15. package/core/client/engines/diff/prose.ts +443 -0
  16. package/core/client/engines/engine-adapters.ts +6 -0
  17. package/core/client/engines/highlight/adapter-lezer.ts +109 -0
  18. package/core/client/engines/highlight/index.ts +135 -0
  19. package/core/client/engines/highlight/port.ts +92 -0
  20. package/core/client/engines/markdown/adapter-markdown-it.ts +65 -0
  21. package/core/client/engines/markdown/blocks.ts +335 -0
  22. package/core/client/engines/markdown/index.ts +51 -0
  23. package/core/client/engines/markdown/port.ts +94 -0
  24. package/core/client/engines/markdown/vendor-modules.d.ts +6 -0
  25. package/core/client/engines/structured/adapter-js-yaml.ts +33 -0
  26. package/core/client/engines/structured/index.ts +139 -0
  27. package/core/client/engines/structured/port.ts +59 -0
  28. package/core/client/infra/http/SomaHttpService.ts +2 -4
  29. package/core/client/infra/notify/DefaultNotifyService.ts +2 -3
  30. package/core/client/infra/permission/SomaPermission.ts +1 -1
  31. package/core/client/render-ports/notify-renderer.ts +2 -46
  32. package/core/client/runtime/SomaRuntimeServices.ts +16 -45
  33. package/core/server/host/app-config-composer.ts +6 -52
  34. package/core/server/host/host-config-paths.cjs +2 -100
  35. package/core/server/host/precompiled-manifest.ts +69 -0
  36. package/core/server/infra/host-config-paths.cjs +100 -0
  37. package/core/server/page-assets.ts +2 -70
  38. package/core/server/runtime-space/bindings.ts +33 -4
  39. package/core/server/runtime-space/store.ts +16 -1
  40. package/core/shared/app-config-merge.ts +59 -0
  41. package/core/shared/registry-generated/limits.ts +80 -4
  42. package/core/shared/types/announcer.types.ts +18 -0
  43. package/core/shared/types/notify.types.ts +26 -0
  44. package/core/shared/types/role-gate.types.ts +11 -0
  45. package/dist/browser/runtime-bundle.manifest.json +50 -7
  46. package/dist/browser/soma-runtime.js +120741 -104799
  47. package/dist/core/index.cjs +113807 -97854
  48. package/dist/host-native/aot-builder.cjs +277 -189
  49. package/dist/host-native/native-server.cjs +196 -72
  50. package/dist/lsp/component-tree.cjs +80 -4
  51. package/dist/types/build/compiler/full-manifest-builder.d.ts +1 -1
  52. package/dist/types/client/a11y/announcer.d.ts +2 -14
  53. package/dist/types/client/base/SomaPageRootBase.d.ts +2 -2
  54. package/dist/types/client/base/runtime-services.types.d.ts +50 -0
  55. package/dist/types/client/data/role-gate.d.ts +2 -8
  56. package/dist/types/client/engines/diff/index.d.ts +1 -1
  57. package/dist/types/client/engines/diff/items.d.ts +24 -0
  58. package/dist/types/client/engines/diff/port.d.ts +124 -2
  59. package/dist/types/client/engines/diff/prose.d.ts +80 -0
  60. package/dist/types/client/engines/engine-adapters.d.ts +6 -0
  61. package/dist/types/client/engines/highlight/adapter-lezer.d.ts +6 -0
  62. package/dist/types/client/engines/highlight/index.d.ts +15 -0
  63. package/dist/types/client/engines/highlight/port.d.ts +64 -0
  64. package/dist/types/client/engines/markdown/adapter-markdown-it.d.ts +6 -0
  65. package/dist/types/client/engines/markdown/blocks.d.ts +29 -0
  66. package/dist/types/client/engines/markdown/index.d.ts +9 -0
  67. package/dist/types/client/engines/markdown/port.d.ts +166 -0
  68. package/dist/types/client/engines/structured/adapter-js-yaml.d.ts +6 -0
  69. package/dist/types/client/engines/structured/index.d.ts +29 -0
  70. package/dist/types/client/engines/structured/port.d.ts +45 -0
  71. package/dist/types/client/infra/http/SomaHttpService.d.ts +1 -1
  72. package/dist/types/client/infra/notify/DefaultNotifyService.d.ts +2 -3
  73. package/dist/types/client/infra/permission/SomaPermission.d.ts +1 -1
  74. package/dist/types/client/render-ports/notify-renderer.d.ts +1 -56
  75. package/dist/types/client/runtime/SomaRuntimeServices.d.ts +9 -44
  76. package/dist/types/server/host/app-config-composer.d.ts +2 -3
  77. package/dist/types/server/host/host-config-paths.d.cts +2 -7
  78. package/dist/types/server/host/precompiled-manifest.d.ts +5 -0
  79. package/dist/types/server/infra/host-config-paths.d.cts +7 -0
  80. package/dist/types/server/page-assets.d.ts +2 -5
  81. package/dist/types/server/runtime-space/store.d.ts +4 -0
  82. package/dist/types/shared/app-config-merge.d.ts +3 -0
  83. package/dist/types/shared/registry-generated/limits.d.ts +78 -4
  84. package/dist/types/shared/types/announcer.types.d.ts +14 -0
  85. package/dist/types/shared/types/notify.types.d.ts +36 -0
  86. package/dist/types/shared/types/role-gate.types.d.ts +8 -0
  87. package/host-native/src/aot-builder.ts +12 -5
  88. package/host-native/src/dev-chunk-gc.ts +104 -0
  89. package/host-native/src/host-prepare.ts +1 -1
  90. package/host-native/src/manifest-http.ts +1 -1
  91. package/host-native/src/page-http.ts +2 -67
  92. package/host-native/src/page-payload-cache.ts +68 -0
  93. package/package.json +16 -2
@@ -0,0 +1,135 @@
1
+ // 代码高亮端口:`createHighlightPort(adapter?, options?)`;缺省 Lezer 适配器(动态加载)。
2
+ // 端口在适配器之上做:语言推断(确定性)、输入校验、上限(design `limits.json#contentEngines.highlight`)、按行切分与降级。
3
+ // 不新增 soma-core 的 exports 子路径:kit 经 `services.engines.highlight` 取用。
4
+ export type {
5
+ CodeFallback, CodeHighlightOptions, CodeLanguageHint, CodeLanguageSpec, CodeResult, CodeSpan, CodeToken, CodeTokenKind,
6
+ SomaHighlightAdapter, SomaHighlightPort,
7
+ } from './port';
8
+ export { CODE_LANGUAGES, CODE_TOKEN_KINDS, assertHighlightAdapter } from './port';
9
+
10
+ import { SomaEngineError } from '../../../shared/engines/engine-error';
11
+ import { SOMA_PIPELINE_LIMITS } from '../../../shared/registry-generated/limits';
12
+ import type { EngineLoadTelemetry } from '../load';
13
+ import { createLezerAdapter } from './adapter-lezer';
14
+ import {
15
+ CODE_LANGUAGES, assertHighlightAdapter, type CodeFallback, type CodeHighlightOptions, type CodeLanguageHint, type CodeResult,
16
+ type CodeSpan, type CodeToken, type SomaHighlightAdapter, type SomaHighlightPort,
17
+ } from './port';
18
+
19
+ export interface HighlightPortOptions { readonly telemetry?: EngineLoadTelemetry }
20
+
21
+ const LIMITS = SOMA_PIPELINE_LIMITS.contentEngines.highlight;
22
+
23
+ const capOr = (v: unknown, ceiling: number): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.min(v, ceiling) : ceiling);
24
+ const now = (): number => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now());
25
+
26
+ const BY_ALIAS = new Map<string, string>();
27
+ const BY_EXT = new Map<string, string>();
28
+ const BY_NAME = new Map<string, string>();
29
+ const LABEL = new Map<string, string>();
30
+ for (const spec of CODE_LANGUAGES) {
31
+ LABEL.set(spec.id, spec.label);
32
+ BY_ALIAS.set(spec.id, spec.id);
33
+ for (const a of spec.aliases) BY_ALIAS.set(a.toLowerCase(), spec.id);
34
+ for (const e of spec.extensions) BY_EXT.set(e.toLowerCase(), spec.id);
35
+ for (const n of spec.filenames) BY_NAME.set(n.toLowerCase(), spec.id);
36
+ }
37
+ const SHEBANG: readonly [RegExp, string][] = [[/\bpython[0-9.]*\b/u, 'python'], [/\b(node|deno|bun)\b/u, 'javascript']];
38
+
39
+ /** 确定性语言推断(纯函数):显式 → 整文件名 → 扩展名 → 围栏信息串 → shebang → 整体可 JSON.parse → text */
40
+ export function resolveCodeLanguage(hint: CodeLanguageHint): string {
41
+ const lang = typeof hint.language === 'string' ? hint.language.trim().toLowerCase() : '';
42
+ if (lang !== '') return BY_ALIAS.get(lang) ?? 'text';
43
+ const file = typeof hint.filename === 'string' ? hint.filename.trim() : '';
44
+ if (file !== '') {
45
+ const base = file.split(/[\\/]/u).pop()!.toLowerCase();
46
+ const byName = BY_NAME.get(base) ?? BY_NAME.get(base.replace(/\.[^.]*$/u, ''));
47
+ if (byName !== undefined) return byName;
48
+ const dot = base.lastIndexOf('.');
49
+ if (dot > 0) { const byExt = BY_EXT.get(base.slice(dot + 1)); if (byExt !== undefined) return byExt; }
50
+ }
51
+ const fence = typeof hint.fence === 'string' ? hint.fence.trim().split(/[\s{,]/u)[0]!.toLowerCase() : '';
52
+ if (fence !== '') { const byFence = BY_ALIAS.get(fence); if (byFence !== undefined) return byFence; }
53
+ const first = typeof hint.firstLine === 'string' ? hint.firstLine : typeof hint.sample === 'string' ? hint.sample.split('\n', 1)[0]! : '';
54
+ if (first.startsWith('#!')) for (const [re, id] of SHEBANG) if (re.test(first)) return id;
55
+ const sample = typeof hint.sample === 'string' ? hint.sample.trim() : '';
56
+ if (sample !== '' && sample.length <= LIMITS.jsonSniffMaxChars && (sample.startsWith('{') || sample.startsWith('['))) {
57
+ try { JSON.parse(sample); return 'json'; } catch { /* 不是 JSON */ }
58
+ }
59
+ return 'text';
60
+ }
61
+
62
+ /** 记号区间 → 按行的记号数组(区间之间的空隙是 plain;跨行的区间在换行处拆开) */
63
+ export function spansToLines(code: string, spans: readonly CodeSpan[], maxLines: number, maxLineLength: number): { lines: CodeToken[][]; plainFrom: number } {
64
+ const rawLines = code.split('\n');
65
+ const lines: CodeToken[][] = [];
66
+ let lineStart = 0;
67
+ let si = 0;
68
+ const plainFrom = rawLines.length > maxLines ? maxLines : -1;
69
+ for (let li = 0; li < rawLines.length; li += 1) {
70
+ const text = rawLines[li]!;
71
+ const lineEnd = lineStart + text.length;
72
+ if (li >= maxLines || text.length > maxLineLength) {
73
+ lines.push(text === '' ? [] : [{ text, kind: 'plain' }]);
74
+ } else {
75
+ const row: CodeToken[] = [];
76
+ let pos = lineStart;
77
+ while (si < spans.length && spans[si]!.to <= lineStart) si += 1;
78
+ let k = si;
79
+ while (k < spans.length && spans[k]!.from < lineEnd) {
80
+ const s = spans[k]!;
81
+ const from = Math.max(s.from, lineStart);
82
+ const to = Math.min(s.to, lineEnd);
83
+ if (from > pos) row.push({ text: code.slice(pos, from), kind: 'plain' });
84
+ if (to > from) row.push({ text: code.slice(from, to), kind: s.kind });
85
+ pos = Math.max(pos, to);
86
+ if (s.to > lineEnd) break;
87
+ k += 1;
88
+ }
89
+ if (pos < lineEnd) row.push({ text: code.slice(pos, lineEnd), kind: 'plain' });
90
+ lines.push(row);
91
+ }
92
+ lineStart = lineEnd + 1;
93
+ }
94
+ return { lines, plainFrom };
95
+ }
96
+
97
+ function plainResult(code: string, language: string, fallback: CodeFallback | undefined, maxLines: number): CodeResult {
98
+ const rawLines = code.split('\n');
99
+ const out: CodeResult = { language, lines: rawLines.map((t) => (t === '' ? [] : [{ text: t, kind: 'plain' as const }])), plainFrom: rawLines.length > maxLines ? maxLines : -1 };
100
+ return fallback !== undefined ? { ...out, fallback } : out;
101
+ }
102
+
103
+ export function createHighlightPort(adapter?: SomaHighlightAdapter, options: HighlightPortOptions = {}): SomaHighlightPort {
104
+ const impl = adapter ?? createLezerAdapter({ telemetry: options.telemetry });
105
+ assertHighlightAdapter(impl);
106
+ return {
107
+ resolveLanguage: (hint) => resolveCodeLanguage(hint ?? {}),
108
+ supportedLanguages: () => [...impl.languages(), 'text'],
109
+ languageLabel: (id) => LABEL.get(id) ?? id,
110
+ async highlight(code: string, language: string, hlOptions?: CodeHighlightOptions): Promise<CodeResult> {
111
+ if (typeof code !== 'string') throw new SomaEngineError('CORE-ENGINE-ADAPTER', 'highlight', '代码必须是字符串');
112
+ const lang = BY_ALIAS.get(String(language ?? '').trim().toLowerCase()) ?? 'text';
113
+ const maxLines = capOr(hlOptions?.maxLines, LIMITS.maxLines);
114
+ const maxLineLength = capOr(hlOptions?.maxLineLength, LIMITS.maxLineLength);
115
+ if (lang === 'text') return plainResult(code, 'text', String(language ?? '').trim() === '' || BY_ALIAS.has(String(language).trim().toLowerCase()) ? undefined : 'unknown-language', maxLines);
116
+ if (!impl.languages().includes(lang)) return plainResult(code, 'text', 'unknown-language', maxLines);
117
+ if (code.length > LIMITS.maxChars) return plainResult(code, lang, 'too-large', maxLines);
118
+ // 只解析前 maxLines 行(其余按纯文本),与超长行一起由 spansToLines 处理
119
+ const head = code.split('\n', maxLines).join('\n');
120
+ const started = now();
121
+ let spans: readonly CodeSpan[] | 'unsupported' | 'timeout';
122
+ try {
123
+ spans = await impl.tokenize(head, lang, { deadline: started + capOr(hlOptions?.timeoutMs, LIMITS.timeoutMs) });
124
+ } catch {
125
+ return plainResult(code, lang, 'engine-load-failed', maxLines);
126
+ }
127
+ options.telemetry?.record('engine.highlight.tokenize', now() - started);
128
+ if (spans === 'unsupported') return plainResult(code, 'text', 'unknown-language', maxLines);
129
+ if (spans === 'timeout') return plainResult(code, lang, 'timeout', maxLines);
130
+ const { lines, plainFrom } = spansToLines(code, spans, maxLines, maxLineLength);
131
+ const out: CodeResult = { language: lang, lines, plainFrom };
132
+ return plainFrom >= 0 ? { ...out, fallback: 'too-large' } : out;
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,92 @@
1
+ // 代码高亮端口(内容展示批次 ③;端口标准形式见 docs/03 soma-core 类设计 §4「引擎端口的标准形式」)。
2
+ // 缺省适配器 Lezer(`@lezer/highlight` + 各语言 Lezer 语法,动态 import);与第 ⑤ 批的 CodeMirror 6 编辑器共用同一套语法。
3
+ // 输出:按行的记号数组,记号种类是 14 种闭集(颜色由组件用 `--tok-*` 令牌给),不出 HTML、不带样式。
4
+ // 失败语义:未知语言、引擎加载失败、超时、超长 → 不抛,返回全 `plain` 的按行结果 + `fallback` 标记(组件照常显示行号与复制)。
5
+
6
+ import { assertAdapterMethods } from '../../../shared/engines/engine-error';
7
+
8
+ /** 记号种类闭集(14 种) */
9
+ export const CODE_TOKEN_KINDS = [
10
+ 'plain', 'comment', 'keyword', 'string', 'number', 'constant', 'function', 'type',
11
+ 'variable', 'property', 'operator', 'punctuation', 'tag', 'attribute',
12
+ ] as const;
13
+ export type CodeTokenKind = (typeof CODE_TOKEN_KINDS)[number];
14
+
15
+ /** 语言闭集:规范 id → 别名 / 扩展名 / 整文件名(`resolveLanguage` 只做确定性推断,不猜内容) */
16
+ export interface CodeLanguageSpec {
17
+ readonly id: string;
18
+ readonly label: string;
19
+ readonly aliases: readonly string[];
20
+ readonly extensions: readonly string[];
21
+ readonly filenames: readonly string[];
22
+ }
23
+
24
+ export const CODE_LANGUAGES: readonly CodeLanguageSpec[] = Object.freeze([
25
+ { id: 'json', label: 'JSON', aliases: ['json', 'jsonc', 'json5'], extensions: ['json', 'jsonc', 'json5', 'map'], filenames: ['package.json', 'tsconfig.json', '.eslintrc'] },
26
+ { id: 'yaml', label: 'YAML', aliases: ['yaml', 'yml'], extensions: ['yaml', 'yml'], filenames: [] },
27
+ { id: 'javascript', label: 'JavaScript', aliases: ['javascript', 'js', 'mjs', 'cjs', 'node'], extensions: ['js', 'mjs', 'cjs'], filenames: [] },
28
+ { id: 'typescript', label: 'TypeScript', aliases: ['typescript', 'ts', 'mts', 'cts'], extensions: ['ts', 'mts', 'cts'], filenames: [] },
29
+ { id: 'jsx', label: 'JSX', aliases: ['jsx'], extensions: ['jsx'], filenames: [] },
30
+ { id: 'tsx', label: 'TSX', aliases: ['tsx'], extensions: ['tsx'], filenames: [] },
31
+ { id: 'python', label: 'Python', aliases: ['python', 'py', 'python3'], extensions: ['py', 'pyw', 'pyi'], filenames: [] },
32
+ { id: 'css', label: 'CSS', aliases: ['css'], extensions: ['css'], filenames: [] },
33
+ { id: 'html', label: 'HTML', aliases: ['html', 'htm', 'xhtml'], extensions: ['html', 'htm'], filenames: [] },
34
+ { id: 'xml', label: 'XML', aliases: ['xml', 'svg', 'xsd', 'xsl', 'plist'], extensions: ['xml', 'svg', 'xsd', 'xsl', 'plist', 'pom'], filenames: [] },
35
+ { id: 'markdown', label: 'Markdown', aliases: ['markdown', 'md', 'mdown'], extensions: ['md', 'markdown'], filenames: ['README', 'CHANGELOG'] },
36
+ { id: 'java', label: 'Java', aliases: ['java'], extensions: ['java'], filenames: [] },
37
+ { id: 'go', label: 'Go', aliases: ['go', 'golang'], extensions: ['go'], filenames: [] },
38
+ { id: 'text', label: 'Plain text', aliases: ['text', 'txt', 'plain', 'plaintext'], extensions: ['txt', 'log'], filenames: [] },
39
+ ]);
40
+
41
+ export interface CodeLanguageHint {
42
+ readonly language?: string;
43
+ readonly filename?: string;
44
+ /** Markdown 围栏信息串(如 ```ts title=a.ts) */
45
+ readonly fence?: string;
46
+ /** 第一行(只认 shebang) */
47
+ readonly firstLine?: string;
48
+ /** 全文(只用于「整体能 JSON.parse」这一条确定性推断) */
49
+ readonly sample?: string;
50
+ }
51
+
52
+ export interface CodeHighlightOptions {
53
+ /** 缺省取 design `limits.json#contentEngines.highlight`;调用方只能更小 */
54
+ readonly maxLines?: number;
55
+ readonly maxLineLength?: number;
56
+ readonly timeoutMs?: number;
57
+ }
58
+
59
+ export interface CodeToken { readonly text: string; readonly kind: CodeTokenKind }
60
+
61
+ export type CodeFallback = 'unknown-language' | 'too-large' | 'timeout' | 'engine-load-failed';
62
+
63
+ export interface CodeResult {
64
+ /** 实际使用的语言(未知时 'text') */
65
+ readonly language: string;
66
+ /** 第一维是行;每行是记号数组(拼起来 = 该行原文,不含换行) */
67
+ readonly lines: readonly (readonly CodeToken[])[];
68
+ /** 被截断成纯文本的起始行号(0 起;超过 maxLines 的行);没有截断为 -1 */
69
+ readonly plainFrom: number;
70
+ readonly fallback?: CodeFallback;
71
+ }
72
+
73
+ /** 适配器:把一段代码切成「起止 + 种类」的记号区间;语言不支持返回 'unsupported',超时返回 'timeout' */
74
+ export interface CodeSpan { readonly from: number; readonly to: number; readonly kind: CodeTokenKind }
75
+ export interface SomaHighlightAdapter {
76
+ /** 适配器能高亮的规范语言 id(`text` 不在其中) */
77
+ languages(): readonly string[];
78
+ tokenize(code: string, language: string, options: { readonly deadline: number }): Promise<readonly CodeSpan[] | 'unsupported' | 'timeout'>;
79
+ }
80
+
81
+ export interface SomaHighlightPort {
82
+ /** 显式 language → 整文件名 → 扩展名 → 围栏信息串 → shebang → 整体可 JSON.parse → 'text';纯函数、同步 */
83
+ resolveLanguage(hint: CodeLanguageHint): string;
84
+ highlight(code: string, language: string, options?: CodeHighlightOptions): Promise<CodeResult>;
85
+ supportedLanguages(): readonly string[];
86
+ /** 规范 id → 显示名(未知 id 原样返回) */
87
+ languageLabel(id: string): string;
88
+ }
89
+
90
+ export function assertHighlightAdapter(adapter: unknown): void {
91
+ assertAdapterMethods('highlight', adapter, ['languages', 'tokenize']);
92
+ }
@@ -0,0 +1,65 @@
1
+ /// <reference path="./vendor-modules.d.ts" />
2
+ // markdown-it 缺省适配器(内容展示批次 ④):全仓唯一 import `markdown-it` / `markdown-it-cjk-friendly` / `markdown-it-footnote` 的文件,只用动态 import()。
3
+ // 配置:CommonMark + GFM 表格 / 删除线 + 自动链接(linkify);html: true 只为让原始 HTML 成为单独的令牌(端口把它按文字保留并计数,绝不渲染);
4
+ // typographer 关(不改写用户的引号与破折号);breaks 关(单换行是软换行,由端口按 CJK 规则拼接)。
5
+
6
+ import { loadEngineModule, type EngineLoadTelemetry } from '../load';
7
+ import type { MdToken, SomaMarkdownAdapter } from './port';
8
+
9
+ interface MdItToken {
10
+ type: string; tag: string; nesting: number; content: string; info: string; markup: string;
11
+ map: [number, number] | null; attrs: [string, string][] | null; hidden: boolean; meta: unknown; children: MdItToken[] | null;
12
+ }
13
+ interface MdIt {
14
+ use(plugin: unknown, ...args: unknown[]): MdIt;
15
+ parse(src: string, env: Record<string, unknown>): MdItToken[];
16
+ validateLink: (url: string) => boolean;
17
+ }
18
+ type MdItCtor = new (options: Record<string, unknown>) => MdIt;
19
+
20
+ export interface MarkdownItAdapterOptions { readonly telemetry?: EngineLoadTelemetry }
21
+
22
+ const pick = <T>(mod: unknown): T => ((mod as { default?: T }).default ?? mod) as T;
23
+
24
+ function plain(t: MdItToken): MdToken {
25
+ return {
26
+ type: t.type, tag: t.tag, nesting: t.nesting, content: t.content, info: t.info, markup: t.markup,
27
+ map: t.map ? [t.map[0], t.map[1]] : null,
28
+ attrs: t.attrs ? t.attrs.map((a) => [a[0], a[1]] as const) : null,
29
+ hidden: t.hidden,
30
+ meta: t.meta === null || t.meta === undefined ? null : JSON.parse(JSON.stringify(t.meta)) as unknown,
31
+ children: t.children ? t.children.map(plain) : null,
32
+ };
33
+ }
34
+
35
+ export function createMarkdownItAdapter(options: MarkdownItAdapterOptions = {}): SomaMarkdownAdapter {
36
+ const instances = new Map<boolean, Promise<MdIt>>();
37
+ const load = <T>(key: string, loader: () => Promise<unknown>): Promise<T> =>
38
+ loadEngineModule('markdown', loader, { telemetry: options.telemetry, key }).then((m) => pick<T>(m));
39
+ const instance = (footnotes: boolean): Promise<MdIt> => {
40
+ let hit = instances.get(footnotes);
41
+ if (hit === undefined) {
42
+ hit = (async () => {
43
+ const [Ctor, cjk, footnote] = await Promise.all([
44
+ load<MdItCtor>('core', () => import('markdown-it')),
45
+ load<unknown>('cjk', () => import('markdown-it-cjk-friendly')),
46
+ footnotes ? load<unknown>('footnote', () => import('markdown-it-footnote')) : Promise.resolve(null),
47
+ ]);
48
+ let md = new Ctor({ html: true, linkify: true, typographer: false, breaks: false }).use(cjk);
49
+ // 放行链接词法解析,让 blocks.ts 的 safeMdHref / safeMdImage 统一按白名单拦截危险协议、降级为文字并计入 unsafeUrls
50
+ md.validateLink = () => true;
51
+ if (footnote !== null) md = md.use(footnote);
52
+ return md;
53
+ })();
54
+ hit.catch(() => instances.delete(footnotes));
55
+ instances.set(footnotes, hit);
56
+ }
57
+ return hit;
58
+ };
59
+ return {
60
+ async tokenize(source, opts) {
61
+ const md = await instance(opts.footnotes);
62
+ return md.parse(source, {}).map(plain);
63
+ },
64
+ };
65
+ }
@@ -0,0 +1,335 @@
1
+ // Markdown 令牌 → 块树(纯函数;零 DOM、不 import 任何第三方包,桩与缺省适配器共用)。
2
+ // 做:块 / 行内两级转换、原始 HTML 按文字保留并计数、URL 白名单、任务列表、CJK 软换行、标题 id(md- 前缀、去重)、块数上限、大纲与纯文本。
3
+
4
+ import type { MdAlign, MdBlock, MdInline, MdListItem, MdMeta, MdSrc, MdToken } from './port';
5
+
6
+ // ── 地址白名单(参考文本差异组件笔记 E2) ──
7
+
8
+ const LINK_SCHEMES = new Set(['http:', 'https:', 'mailto:', 'tel:']);
9
+ const IMAGE_SCHEMES = new Set(['http:', 'https:']);
10
+ const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/=\s]+$/iu;
11
+ const SCHEME = /^([a-z][a-z0-9+.-]*):/iu;
12
+ // 控制字符与空白会被浏览器剥掉后再判协议(`java\tscript:`),先去掉再判
13
+ const STRIP = /[\u0000- \u007f-\u009f]/gu;
14
+
15
+ /** 链接地址:http / https / mailto / tel、站内路径(/…)、锚点(#…)、无协议的相对地址;其余(javascript: / data: / vbscript: …)拒绝 → '' */
16
+ export function safeMdHref(raw: string): string {
17
+ const v = raw.trim();
18
+ if (v === '') return '';
19
+ const probe = v.replace(STRIP, '');
20
+ const m = SCHEME.exec(probe);
21
+ if (m) return LINK_SCHEMES.has(m[0].toLowerCase()) ? v : '';
22
+ if (probe.startsWith('//')) return '';
23
+ return v;
24
+ }
25
+
26
+ /** 图片地址:http / https、站内路径、data:image/(png|jpeg|gif|webp);base64;其余拒绝 → '' */
27
+ export function safeMdImage(raw: string): string {
28
+ const v = raw.trim();
29
+ if (v === '') return '';
30
+ const probe = v.replace(STRIP, '');
31
+ if (DATA_IMAGE.test(probe)) return v;
32
+ const m = SCHEME.exec(probe);
33
+ if (m) return IMAGE_SCHEMES.has(m[0].toLowerCase()) ? v : '';
34
+ if (probe.startsWith('//')) return '';
35
+ return v;
36
+ }
37
+
38
+ const isExternal = (href: string): boolean => /^https?:\/\//iu.test(href);
39
+
40
+ // ── CJK 软换行:换行两侧都是东亚宽字符(汉字、假名、谚文、全角标点)时删去,否则变一个空格 ──
41
+
42
+ const WIDE = /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꥠ-꥿가-힣豈-﫿︰-﹏＀-⦆¢-₩]/u;
43
+ export function softBreakJoiner(before: string, after: string): string {
44
+ const a = before.slice(-1);
45
+ const b = after.slice(0, 1);
46
+ return a !== '' && b !== '' && WIDE.test(a) && WIDE.test(b) ? '' : ' ';
47
+ }
48
+
49
+ // ── 标题 id ──
50
+
51
+ export function mdSlug(text: string): string {
52
+ const s = text.trim().toLocaleLowerCase().replace(/\s+/gu, '-').replace(/[^\p{L}\p{N}_-]/gu, '').replace(/-+/gu, '-');
53
+ return s === '' ? 'section' : s;
54
+ }
55
+
56
+ // ── 行内 ──
57
+
58
+ interface Ctx {
59
+ html: number;
60
+ unsafeUrls: number;
61
+ images: number;
62
+ links: number;
63
+ fnIndex: Map<string, number>;
64
+ ids: Map<string, number>;
65
+ }
66
+
67
+ const attr = (t: MdToken, name: string): string => t.attrs?.find((a) => a[0] === name)?.[1] ?? '';
68
+
69
+ function pushText(out: MdInline[], v: string): void {
70
+ if (v === '') return;
71
+ const last = out[out.length - 1];
72
+ if (last && last.t === 'text') out[out.length - 1] = { t: 'text', v: last.v + v };
73
+ else out.push({ t: 'text', v });
74
+ }
75
+
76
+ /** 行内令牌 → 行内节点(容器令牌按 nesting 配对) */
77
+ export function inlineOf(tokens: readonly MdToken[], ctx: Ctx): MdInline[] {
78
+ let i = 0;
79
+ const walk = (closeType: string | null): MdInline[] => {
80
+ const out: MdInline[] = [];
81
+ while (i < tokens.length) {
82
+ const t = tokens[i]!;
83
+ i += 1;
84
+ if (closeType !== null && t.type === closeType) return out;
85
+ switch (t.type) {
86
+ case 'text': pushText(out, t.content); break;
87
+ case 'softbreak': {
88
+ const next = tokens[i];
89
+ const prev = out[out.length - 1];
90
+ pushText(out, softBreakJoiner(prev && prev.t === 'text' ? prev.v : '', next && next.type === 'text' ? next.content : ''));
91
+ break;
92
+ }
93
+ case 'hardbreak': out.push({ t: 'br' }); break;
94
+ case 'code_inline': out.push({ t: 'code', v: t.content }); break;
95
+ case 'html_inline': ctx.html += 1; pushText(out, t.content); break;
96
+ case 'strong_open': out.push({ t: 'strong', c: walk('strong_close') }); break;
97
+ case 'em_open': out.push({ t: 'em', c: walk('em_close') }); break;
98
+ case 's_open': out.push({ t: 'del', c: walk('s_close') }); break;
99
+ case 'link_open': {
100
+ const raw = attr(t, 'href');
101
+ const href = safeMdHref(raw);
102
+ const title = attr(t, 'title');
103
+ const c = walk('link_close');
104
+ if (href === '') { ctx.unsafeUrls += 1; for (const x of c) if (x.t === 'text') pushText(out, x.v); else out.push(x); break; }
105
+ ctx.links += 1;
106
+ out.push({ t: 'link', href, external: isExternal(href), ...(title !== '' ? { title } : {}), c });
107
+ break;
108
+ }
109
+ case 'image': {
110
+ const src = safeMdImage(attr(t, 'src'));
111
+ const alt = (t.children ?? []).map((x) => x.content).join('') || t.content;
112
+ const title = attr(t, 'title');
113
+ if (src === '') { ctx.unsafeUrls += 1; pushText(out, alt); break; }
114
+ ctx.images += 1;
115
+ out.push({ t: 'image', src, alt, ...(title !== '' ? { title } : {}) });
116
+ break;
117
+ }
118
+ case 'footnote_ref': {
119
+ const label = String((t.meta as { label?: unknown } | null)?.label ?? (t.meta as { id?: unknown } | null)?.id ?? '');
120
+ const id = `md-fn-${mdSlug(label)}`;
121
+ if (!ctx.fnIndex.has(id)) ctx.fnIndex.set(id, ctx.fnIndex.size + 1);
122
+ out.push({ t: 'fnref', id, n: ctx.fnIndex.get(id)! });
123
+ break;
124
+ }
125
+ default:
126
+ // 未知行内令牌(插件):按原文文字保留
127
+ if (t.nesting === 0 && t.content !== '') pushText(out, t.content);
128
+ }
129
+ }
130
+ return out;
131
+ };
132
+ return walk(null);
133
+ }
134
+
135
+ export function inlineText(nodes: readonly MdInline[]): string {
136
+ let s = '';
137
+ for (const n of nodes) {
138
+ if (n.t === 'text' || n.t === 'code') s += n.v;
139
+ else if (n.t === 'br') s += '\n';
140
+ else if (n.t === 'image') s += n.alt;
141
+ else if (n.t === 'fnref') s += `[${n.n}]`;
142
+ else s += inlineText(n.c);
143
+ }
144
+ return s;
145
+ }
146
+
147
+ /** 任务列表:列表项首段以 `[ ] ` / `[x] ` 开头 → task false / true,并去掉标记 */
148
+ function takeTask(first: MdInline[]): boolean | null {
149
+ const head = first[0];
150
+ if (!head || head.t !== 'text') return null;
151
+ const m = /^\[([ xX])\]\s+/u.exec(head.v);
152
+ if (!m) return null;
153
+ first[0] = { t: 'text', v: head.v.slice(m[0].length) };
154
+ if ((first[0] as { v: string }).v === '') first.shift();
155
+ return m[1] !== ' ';
156
+ }
157
+
158
+ // ── 块 ──
159
+
160
+ const srcOf = (t: MdToken): MdSrc => (t.map ? [t.map[0], t.map[1]] : [-1, -1]);
161
+ const HEADING_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;
162
+
163
+ export interface MdBuild { blocks: MdBlock[]; meta: MdMeta }
164
+
165
+ /** 令牌流 → 块树 + 元信息 */
166
+ export function buildMarkdown(tokens: readonly MdToken[], source: string, limits: { readonly maxBlocks: number; readonly summaryChars: number }): MdBuild {
167
+ const ctx: Ctx = { html: 0, unsafeUrls: 0, images: 0, links: 0, fnIndex: new Map(), ids: new Map() };
168
+ const outline: { depth: 1 | 2 | 3 | 4 | 5 | 6; text: string; id: string }[] = [];
169
+ let count = 0;
170
+ let truncated = false;
171
+ let codeBlocks = 0;
172
+ let tables = 0;
173
+ let i = 0;
174
+
175
+ const footnotes: { id: string; n: number; blocks: MdBlock[] }[] = [];
176
+ let footSrc: MdSrc = [-1, -1];
177
+
178
+ const blocksUntil = (closeType: string | null, tightList: boolean): MdBlock[] => {
179
+ const out: MdBlock[] = [];
180
+ while (i < tokens.length) {
181
+ const t = tokens[i]!;
182
+ if (closeType !== null && t.type === closeType) { i += 1; return out; }
183
+ i += 1;
184
+ if (count >= limits.maxBlocks && closeType === null) { truncated = true; continue; }
185
+ const b = blockAt(t, tightList);
186
+ if (b !== null) { out.push(b); count += 1; }
187
+ }
188
+ return out;
189
+ };
190
+
191
+ const blockAt = (t: MdToken, tightList: boolean): MdBlock | null => {
192
+ switch (t.type) {
193
+ case 'heading_open': {
194
+ const inl = tokens[i]?.type === 'inline' ? inlineOf(tokens[i]!.children ?? [], ctx) : [];
195
+ i += 2; // inline + heading_close
196
+ const idx = HEADING_TAGS.indexOf(t.tag as (typeof HEADING_TAGS)[number]);
197
+ const depth = (idx >= 0 ? idx + 1 : HEADING_TAGS.length) as 1 | 2 | 3 | 4 | 5 | 6;
198
+ const text = inlineText(inl);
199
+ const base = `md-${mdSlug(text)}`;
200
+ const seen = ctx.ids.get(base) ?? 0;
201
+ ctx.ids.set(base, seen + 1);
202
+ const id = seen === 0 ? base : `${base}-${seen + 1}`;
203
+ outline.push({ depth, text, id });
204
+ return { t: 'heading', depth, id, inline: inl, src: srcOf(t) };
205
+ }
206
+ case 'paragraph_open': {
207
+ const inl = tokens[i]?.type === 'inline' ? inlineOf(tokens[i]!.children ?? [], ctx) : [];
208
+ i += 2;
209
+ return { t: 'paragraph', inline: inl, tight: tightList || t.hidden, src: srcOf(t) };
210
+ }
211
+ case 'bullet_list_open':
212
+ case 'ordered_list_open': {
213
+ const ordered = t.type === 'ordered_list_open';
214
+ const close = ordered ? 'ordered_list_close' : 'bullet_list_close';
215
+ const items: MdListItem[] = [];
216
+ const startRaw = Number(attr(t, 'start'));
217
+ while (i < tokens.length && tokens[i]!.type !== close) {
218
+ const it = tokens[i]!;
219
+ i += 1;
220
+ if (it.type !== 'list_item_open') continue;
221
+ // 紧凑列表:项内段落被 markdown-it 标为 hidden
222
+ const inner = blocksUntil('list_item_close', tokens[i]?.hidden === true);
223
+ let task: boolean | null = null;
224
+ const first = inner[0];
225
+ if (first && first.t === 'paragraph') {
226
+ const inl = [...first.inline];
227
+ task = takeTask(inl);
228
+ if (task !== null) inner[0] = { ...first, inline: inl };
229
+ }
230
+ items.push({ task, blocks: inner });
231
+ }
232
+ i += 1;
233
+ return { t: 'list', ordered, ...(ordered && Number.isInteger(startRaw) && startRaw !== 1 && attr(t, 'start') !== '' ? { start: startRaw } : {}), items, src: srcOf(t) };
234
+ }
235
+ case 'blockquote_open':
236
+ return { t: 'quote', blocks: blocksUntil('blockquote_close', false), src: srcOf(t) };
237
+ case 'fence':
238
+ case 'code_block': {
239
+ codeBlocks += 1;
240
+ const lang = t.type === 'fence' ? t.info.trim().split(/\s+/u)[0] ?? '' : '';
241
+ const text = t.content.endsWith('\n') ? t.content.slice(0, -1) : t.content;
242
+ // 未闭合的围栏:markdown-it 把它延伸到文末;末行不是围栏标记即视为未闭合
243
+ const closed = t.type !== 'fence' || fenceClosed(source, t);
244
+ return { t: 'code', lang, text, closed, src: srcOf(t) };
245
+ }
246
+ case 'table_open': {
247
+ tables += 1;
248
+ const align: MdAlign[] = [];
249
+ const head: MdInline[][] = [];
250
+ const rows: MdInline[][][] = [];
251
+ let row: MdInline[][] | null = null;
252
+ let inHead = false;
253
+ while (i < tokens.length && tokens[i]!.type !== 'table_close') {
254
+ const c = tokens[i]!;
255
+ i += 1;
256
+ if (c.type === 'thead_open') inHead = true;
257
+ else if (c.type === 'thead_close') inHead = false;
258
+ else if (c.type === 'tr_open') row = [];
259
+ else if (c.type === 'tr_close') { if (row !== null && !inHead) rows.push(row); row = null; }
260
+ else if (c.type === 'th_open' || c.type === 'td_open') {
261
+ const style = attr(c, 'style');
262
+ const a = /text-align:\s*(left|center|right)/u.exec(style);
263
+ if (inHead) align.push(a ? (a[1] as MdAlign) : null);
264
+ const inl = tokens[i]?.type === 'inline' ? inlineOf(tokens[i]!.children ?? [], ctx) : [];
265
+ if (tokens[i]?.type === 'inline') i += 1;
266
+ if (inHead) head.push(inl); else row?.push(inl);
267
+ }
268
+ }
269
+ i += 1;
270
+ return { t: 'table', align, head, rows, src: srcOf(t) };
271
+ }
272
+ case 'hr':
273
+ return { t: 'hr', src: srcOf(t) };
274
+ case 'html_block':
275
+ ctx.html += 1;
276
+ return { t: 'html', text: t.content.replace(/\n$/u, ''), src: srcOf(t) };
277
+ case 'footnote_block_open': {
278
+ footSrc = srcOf(t);
279
+ while (i < tokens.length && tokens[i]!.type !== 'footnote_block_close') {
280
+ const f = tokens[i]!;
281
+ i += 1;
282
+ if (f.type !== 'footnote_open') continue;
283
+ const label = String((f.meta as { label?: unknown } | null)?.label ?? (f.meta as { id?: unknown } | null)?.id ?? '');
284
+ const id = `md-fn-${mdSlug(label)}`;
285
+ const inner = blocksUntil('footnote_close', false);
286
+ if (!ctx.fnIndex.has(id)) ctx.fnIndex.set(id, ctx.fnIndex.size + 1);
287
+ footnotes.push({ id, n: ctx.fnIndex.get(id)!, blocks: inner });
288
+ }
289
+ i += 1;
290
+ return null;
291
+ }
292
+ default:
293
+ // footnote_anchor 等装饰令牌、未知插件块:忽略(文字已在 inline 里)
294
+ return null;
295
+ }
296
+ };
297
+
298
+ const blocks = blocksUntil(null, false);
299
+ if (footnotes.length > 0) {
300
+ footnotes.sort((a, b) => a.n - b.n);
301
+ blocks.push({ t: 'footnotes', items: footnotes, src: footSrc });
302
+ }
303
+ const plain = plainOf(blocks);
304
+ const summary = Array.from(plain.replace(/\s+/gu, ' ').trim()).slice(0, limits.summaryChars).join('');
305
+ const meta: MdMeta = {
306
+ outline, plainText: plain, summary,
307
+ counts: { chars: Array.from(source).length, blocks: count, images: ctx.images, links: ctx.links, codeBlocks, tables },
308
+ dropped: { html: ctx.html, unsafeUrls: ctx.unsafeUrls },
309
+ truncated,
310
+ };
311
+ return { blocks, meta };
312
+ }
313
+
314
+ function fenceClosed(source: string, t: MdToken): boolean {
315
+ if (!t.map) return true;
316
+ const lines = source.split('\n');
317
+ const last = (lines[t.map[1] - 1] ?? '').trim();
318
+ return t.map[1] - t.map[0] >= 2 && last.startsWith(t.markup.slice(0, 3)) && last.replace(/[`~]/gu, '').trim() === '';
319
+ }
320
+
321
+ export function plainOf(blocks: readonly MdBlock[]): string {
322
+ const parts: string[] = [];
323
+ for (const b of blocks) {
324
+ switch (b.t) {
325
+ case 'heading': case 'paragraph': parts.push(inlineText(b.inline)); break;
326
+ case 'list': for (const it of b.items) parts.push(plainOf(it.blocks)); break;
327
+ case 'quote': parts.push(plainOf(b.blocks)); break;
328
+ case 'code': case 'html': parts.push(b.text); break;
329
+ case 'table': parts.push([b.head, ...b.rows].map((r) => r.map(inlineText).join('\t')).join('\n')); break;
330
+ case 'footnotes': for (const f of b.items) parts.push(plainOf(f.blocks)); break;
331
+ default: break;
332
+ }
333
+ }
334
+ return parts.filter((p) => p !== '').join('\n');
335
+ }