@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.2

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 (210) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/LICENSE +21 -0
  3. package/README.md +292 -2
  4. package/README.zh-CN.md +307 -0
  5. package/SKILL.md +261 -0
  6. package/cordis.patch.yml +9 -0
  7. package/demo-prompts.md +118 -0
  8. package/lib/assets/echarts-core.js +43 -0
  9. package/lib/assets/echarts-full.js +72 -0
  10. package/lib/assets/mermaid.js +3591 -0
  11. package/lib/assets/standalone-runtime.js +1506 -0
  12. package/lib/assets/three.js +3844 -0
  13. package/lib/client.js +405 -0
  14. package/lib/index.js +5187 -0
  15. package/lib/invariant.js +19 -0
  16. package/lib/types/client/EChartNode.d.ts +13 -0
  17. package/lib/types/client/ErrorBoundary.d.ts +30 -0
  18. package/lib/types/client/GenuiBlock.d.ts +9 -0
  19. package/lib/types/client/PlotBlock.d.ts +44 -0
  20. package/lib/types/client/TemplateDrawer.d.ts +7 -0
  21. package/lib/types/client/achievement-store.d.ts +35 -0
  22. package/lib/types/client/achievement-toast.d.ts +2 -0
  23. package/lib/types/client/achievements.d.ts +63 -0
  24. package/lib/types/client/action-context.d.ts +7 -0
  25. package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
  26. package/lib/types/client/artifact/create.d.ts +5 -0
  27. package/lib/types/client/artifact/download.d.ts +9 -0
  28. package/lib/types/client/artifact/html.d.ts +5 -0
  29. package/lib/types/client/artifact/index.d.ts +8 -0
  30. package/lib/types/client/artifact/json.d.ts +3 -0
  31. package/lib/types/client/artifact/parse.d.ts +3 -0
  32. package/lib/types/client/artifact/portability.d.ts +4 -0
  33. package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
  34. package/lib/types/client/artifact/types.d.ts +33 -0
  35. package/lib/types/client/asset-echarts-core.d.ts +1 -0
  36. package/lib/types/client/asset-echarts.d.ts +17 -0
  37. package/lib/types/client/asset-loader.d.ts +33 -0
  38. package/lib/types/client/asset-mermaid.d.ts +1 -0
  39. package/lib/types/client/asset-three.d.ts +1 -0
  40. package/lib/types/client/blocks/advanced.d.ts +101 -0
  41. package/lib/types/client/blocks/basic.d.ts +22 -0
  42. package/lib/types/client/blocks/charts.d.ts +53 -0
  43. package/lib/types/client/blocks/checkbox.d.ts +17 -0
  44. package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
  45. package/lib/types/client/blocks/diagram/index.d.ts +5 -0
  46. package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
  47. package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
  48. package/lib/types/client/blocks/forms.d.ts +77 -0
  49. package/lib/types/client/blocks/image.d.ts +6 -0
  50. package/lib/types/client/blocks/render-node.d.ts +10 -0
  51. package/lib/types/client/blocks/state.d.ts +63 -0
  52. package/lib/types/client/blocks/svg.d.ts +4 -0
  53. package/lib/types/client/dom-fence.d.ts +30 -0
  54. package/lib/types/client/echarts-engine.d.ts +4 -0
  55. package/lib/types/client/echarts-lazy.d.ts +18 -0
  56. package/lib/types/client/embed.d.ts +10 -0
  57. package/lib/types/client/fence-render.d.ts +106 -0
  58. package/lib/types/client/gallery.d.ts +7 -0
  59. package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
  60. package/lib/types/client/genui-runtime/index.d.ts +1 -0
  61. package/lib/types/client/genui-runtime/limits.d.ts +54 -0
  62. package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
  63. package/lib/types/client/genui-runtime/schema.d.ts +87 -0
  64. package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
  65. package/lib/types/client/guard.d.ts +144 -0
  66. package/lib/types/client/i18n/en.d.ts +307 -0
  67. package/lib/types/client/i18n/index.d.ts +44 -0
  68. package/lib/types/client/i18n/runtime.d.ts +64 -0
  69. package/lib/types/client/i18n/zh.d.ts +8 -0
  70. package/lib/types/client/index.d.ts +36 -0
  71. package/lib/types/client/inline.d.ts +5 -0
  72. package/lib/types/client/interaction-store.d.ts +48 -0
  73. package/lib/types/client/mermaid-core.d.ts +8 -0
  74. package/lib/types/client/mermaid-lazy.d.ts +9 -0
  75. package/lib/types/client/mermaid-safe.d.ts +52 -0
  76. package/lib/types/client/panel-command.d.ts +34 -0
  77. package/lib/types/client/panel-store.d.ts +94 -0
  78. package/lib/types/client/panel.d.ts +18 -0
  79. package/lib/types/client/parse-partial.d.ts +63 -0
  80. package/lib/types/client/primitive-adapter.d.ts +4 -0
  81. package/lib/types/client/primitive-labels.d.ts +18 -0
  82. package/lib/types/client/safe-math.d.ts +43 -0
  83. package/lib/types/client/scene3d-core.d.ts +21 -0
  84. package/lib/types/client/scene3d-lazy.d.ts +8 -0
  85. package/lib/types/client/session-resolver.d.ts +8 -0
  86. package/lib/types/client/source-fence.d.ts +29 -0
  87. package/lib/types/client/spec.d.ts +709 -0
  88. package/lib/types/client/standalone/asset-loader.d.ts +2 -0
  89. package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
  90. package/lib/types/client/standalone/katex-style.d.ts +1 -0
  91. package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
  92. package/lib/types/client/standalone/runtime.d.ts +2 -0
  93. package/lib/types/client/submission-registry.d.ts +51 -0
  94. package/lib/types/client/svg-fence.d.ts +2 -0
  95. package/lib/types/client/table-details.d.ts +20 -0
  96. package/lib/types/client/templates.d.ts +41 -0
  97. package/lib/types/client/toolview.d.ts +7 -0
  98. package/lib/types/client/walk-spec.d.ts +3 -0
  99. package/lib/types/index.d.ts +1 -0
  100. package/lib/types/plugin/chart-contract.d.ts +9 -0
  101. package/lib/types/plugin/fence-feedback.d.ts +151 -0
  102. package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
  103. package/lib/types/plugin/index.d.ts +35 -0
  104. package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
  105. package/lib/types/plugin/invariant.d.ts +15 -0
  106. package/lib/types/plugin/tool.d.ts +27 -0
  107. package/lib/types/shared/fence-repair.d.ts +78 -0
  108. package/lib/types/shared/fence-resolve.d.ts +39 -0
  109. package/package.json +249 -4
  110. package/src/client/EChartNode.tsx +466 -0
  111. package/src/client/ErrorBoundary.tsx +67 -0
  112. package/src/client/GenuiBlock.module.css +2221 -0
  113. package/src/client/GenuiBlock.tsx +235 -0
  114. package/src/client/PlotBlock.module.css +171 -0
  115. package/src/client/PlotBlock.tsx +492 -0
  116. package/src/client/TemplateDrawer.module.css +152 -0
  117. package/src/client/TemplateDrawer.tsx +147 -0
  118. package/src/client/achievement-store.ts +151 -0
  119. package/src/client/achievement-toast.tsx +71 -0
  120. package/src/client/achievements.ts +160 -0
  121. package/src/client/action-context.ts +32 -0
  122. package/src/client/artifact/ArtifactExport.module.css +64 -0
  123. package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
  124. package/src/client/artifact/create.ts +69 -0
  125. package/src/client/artifact/download.ts +42 -0
  126. package/src/client/artifact/html.ts +157 -0
  127. package/src/client/artifact/index.ts +15 -0
  128. package/src/client/artifact/json.ts +6 -0
  129. package/src/client/artifact/parse.ts +32 -0
  130. package/src/client/artifact/portability.ts +47 -0
  131. package/src/client/artifact/standalone-theme.ts +94 -0
  132. package/src/client/artifact/types.ts +44 -0
  133. package/src/client/asset-echarts-core.ts +39 -0
  134. package/src/client/asset-echarts.ts +27 -0
  135. package/src/client/asset-loader.ts +96 -0
  136. package/src/client/asset-mermaid.ts +13 -0
  137. package/src/client/asset-three.ts +12 -0
  138. package/src/client/blocks/advanced.tsx +537 -0
  139. package/src/client/blocks/basic.tsx +121 -0
  140. package/src/client/blocks/charts.tsx +999 -0
  141. package/src/client/blocks/checkbox.tsx +61 -0
  142. package/src/client/blocks/diagram/geometry.ts +151 -0
  143. package/src/client/blocks/diagram/index.tsx +293 -0
  144. package/src/client/blocks/diagram/layout.ts +202 -0
  145. package/src/client/blocks/diagram/theme.ts +127 -0
  146. package/src/client/blocks/forms.tsx +531 -0
  147. package/src/client/blocks/image.tsx +28 -0
  148. package/src/client/blocks/render-node.tsx +494 -0
  149. package/src/client/blocks/state.ts +65 -0
  150. package/src/client/blocks/svg.tsx +66 -0
  151. package/src/client/dom-fence.tsx +1123 -0
  152. package/src/client/echarts-engine.ts +9 -0
  153. package/src/client/echarts-lazy.ts +41 -0
  154. package/src/client/embed.ts +19 -0
  155. package/src/client/fence-render.tsx +266 -0
  156. package/src/client/gallery.ts +215 -0
  157. package/src/client/genui-runtime/diagnostics.ts +165 -0
  158. package/src/client/genui-runtime/index.ts +1 -0
  159. package/src/client/genui-runtime/limits.ts +54 -0
  160. package/src/client/genui-runtime/normalize.ts +329 -0
  161. package/src/client/genui-runtime/schema.ts +352 -0
  162. package/src/client/genui-runtime/value-utils.ts +67 -0
  163. package/src/client/guard.ts +1965 -0
  164. package/src/client/i18n/en.ts +335 -0
  165. package/src/client/i18n/index.ts +125 -0
  166. package/src/client/i18n/runtime.ts +130 -0
  167. package/src/client/i18n/zh.ts +330 -0
  168. package/src/client/index.tsx +228 -0
  169. package/src/client/inline.ts +106 -0
  170. package/src/client/interaction-store.ts +127 -0
  171. package/src/client/mermaid-core.ts +158 -0
  172. package/src/client/mermaid-lazy.ts +31 -0
  173. package/src/client/mermaid-safe.ts +122 -0
  174. package/src/client/panel-command.ts +138 -0
  175. package/src/client/panel-store.ts +471 -0
  176. package/src/client/panel.tsx +287 -0
  177. package/src/client/parse-partial.ts +170 -0
  178. package/src/client/primitive-adapter.ts +13 -0
  179. package/src/client/primitive-labels.ts +55 -0
  180. package/src/client/safe-math.ts +298 -0
  181. package/src/client/scene3d-core.ts +195 -0
  182. package/src/client/scene3d-lazy.ts +26 -0
  183. package/src/client/session-resolver.ts +33 -0
  184. package/src/client/source-fence.ts +70 -0
  185. package/src/client/spec.ts +896 -0
  186. package/src/client/standalone/asset-loader.ts +9 -0
  187. package/src/client/standalone/bootstrap-types.ts +11 -0
  188. package/src/client/standalone/katex-style.ts +1 -0
  189. package/src/client/standalone/primitive-adapter.tsx +94 -0
  190. package/src/client/standalone/runtime.tsx +27 -0
  191. package/src/client/submission-registry.ts +150 -0
  192. package/src/client/svg-fence.tsx +39 -0
  193. package/src/client/table-details.ts +151 -0
  194. package/src/client/templates.ts +322 -0
  195. package/src/client/toolview.tsx +67 -0
  196. package/src/client/walk-spec.ts +43 -0
  197. package/src/css-modules.d.ts +5 -0
  198. package/src/index.ts +9 -0
  199. package/src/plugin/chart-contract.ts +13 -0
  200. package/src/plugin/fence-feedback.ts +655 -0
  201. package/src/plugin/genui-diagnostic.ts +112 -0
  202. package/src/plugin/index.ts +224 -0
  203. package/src/plugin/inline-content-diagnostic.ts +178 -0
  204. package/src/plugin/invariant.ts +30 -0
  205. package/src/plugin/node-shims.d.ts +31 -0
  206. package/src/plugin/tool.ts +424 -0
  207. package/src/shared/fence-repair.ts +536 -0
  208. package/src/shared/fence-resolve.ts +80 -0
  209. package/tsconfig.json +35 -0
  210. package/tsdown.config.ts +275 -0
@@ -0,0 +1,100 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import type { BlockInteractionState } from '../interaction-store.ts'
3
+ import { useT } from '../i18n/index.ts'
4
+ import { GenuiBlock } from '../GenuiBlock.tsx'
5
+ import type { GenuiBlockProps } from '../blocks/state.ts'
6
+ import { analyzeGenuiPortability } from './portability.ts'
7
+ import { createGenuiArtifact } from './create.ts'
8
+ import { downloadGenuiArtifactHtml, downloadGenuiArtifactJson } from './download.ts'
9
+ import { GenuiExportError } from './types.ts'
10
+ import css from './ArtifactExport.module.css'
11
+
12
+ interface ArtifactExportMenuProps {
13
+ getArtifact: () => ReturnType<typeof createGenuiArtifact>
14
+ }
15
+
16
+ /** 提供 JSON 和 HTML 的本地化导出菜单。 */
17
+ function ArtifactExportMenu({ getArtifact }: ArtifactExportMenuProps) {
18
+ const t = useT()
19
+ const rootRef = useRef<HTMLDivElement>(null)
20
+ const [open, setOpen] = useState(false)
21
+ const [errorMessage, setErrorMessage] = useState('')
22
+ const report = analyzeGenuiPortability(getArtifact().spec)
23
+
24
+ useEffect(() => {
25
+ if (!open) return
26
+ const closeOutside = (event: PointerEvent): void => {
27
+ if (event.target instanceof Node && !rootRef.current?.contains(event.target)) setOpen(false)
28
+ }
29
+ const closeEscape = (event: KeyboardEvent): void => {
30
+ if (event.key === 'Escape') setOpen(false)
31
+ }
32
+ document.addEventListener('pointerdown', closeOutside)
33
+ document.addEventListener('keydown', closeEscape)
34
+ return () => {
35
+ document.removeEventListener('pointerdown', closeOutside)
36
+ document.removeEventListener('keydown', closeEscape)
37
+ }
38
+ }, [open])
39
+
40
+ /** 执行用户选择的下载并更新辅助说明。 */
41
+ const exportAs = async (format: 'html' | 'json'): Promise<void> => {
42
+ setOpen(false)
43
+ setErrorMessage('')
44
+ try {
45
+ const artifact = getArtifact()
46
+ if (format === 'html') await downloadGenuiArtifactHtml(artifact)
47
+ else downloadGenuiArtifactJson(artifact)
48
+ } catch (error) {
49
+ if (error instanceof GenuiExportError) {
50
+ if (error.code === 'unsupported-custom-component') {
51
+ console.warn('[dsh-genui] standalone export rejected:', error.message)
52
+ setErrorMessage(t('artifact.unsupportedCustom', { types: report.customTypes.join(', ') }))
53
+ } else {
54
+ console.warn('[dsh-genui] artifact export failed:', error.code, error.message)
55
+ setErrorMessage(t('artifact.exportFailed'))
56
+ }
57
+ } else {
58
+ console.warn('[dsh-genui] artifact export failed:', error instanceof Error ? error.message : 'unknown error')
59
+ setErrorMessage(t('artifact.exportFailed'))
60
+ }
61
+ }
62
+ }
63
+
64
+ return (
65
+ <div className={css.chrome} ref={rootRef} data-genui-export>
66
+ {report.externalMedia.length > 0 && <span className={css.notice}>{t('artifact.externalMediaNotice')}</span>}
67
+ {errorMessage !== '' && <span className={css.statusError} aria-live="polite">{errorMessage}</span>}
68
+ <button type="button" className={css.trigger} aria-haspopup="menu" aria-expanded={open} onClick={() => setOpen(value => !value)}>
69
+ {t('artifact.export')}
70
+ </button>
71
+ {open && (
72
+ <div className={css.menu} role="menu">
73
+ <button type="button" role="menuitem" className={css.item} disabled={report.customTypes.length > 0} onClick={() => void exportAs('html')}>{t('artifact.exportHtml')}</button>
74
+ {report.customTypes.length > 0 && <span className={css.menuNotice}>{t('artifact.unsupportedCustom', { types: report.customTypes.join(', ') })}</span>}
75
+ <button type="button" role="menuitem" className={css.item} onClick={() => void exportAs('json')}>{t('artifact.exportJson')}</button>
76
+ </div>
77
+ )}
78
+ </div>
79
+ )
80
+ }
81
+
82
+ export interface ExportableGenuiBlockProps extends GenuiBlockProps {
83
+ exportEnabled?: boolean
84
+ }
85
+
86
+ /** 在完成态 GenUI 外层显示 artifact 导出菜单。 */
87
+ export function ExportableGenuiBlock(props: ExportableGenuiBlockProps) {
88
+ const stateRef = useRef<BlockInteractionState | undefined>(undefined)
89
+ const captureState = useCallback((state: BlockInteractionState) => {
90
+ stateRef.current = state
91
+ }, [])
92
+ const getArtifact = useCallback(() => createGenuiArtifact(props.spec, stateRef.current), [props.spec])
93
+ const { exportEnabled = true, ...blockProps } = props
94
+ return (
95
+ <div data-genui-artifact>
96
+ <GenuiBlock {...blockProps} onStateSnapshot={captureState} />
97
+ {exportEnabled && <ArtifactExportMenu getArtifact={getArtifact} />}
98
+ </div>
99
+ )
100
+ }
@@ -0,0 +1,69 @@
1
+ import { currentLocale } from '../i18n/index.ts'
2
+ import { processGenuiSpec } from '../guard.ts'
3
+ import type { BlockInteractionState } from '../interaction-store.ts'
4
+ import type { GenuiNode, GenuiSpec } from '../spec.ts'
5
+ import { GenuiExportError, GENUI_ARTIFACT_FORMAT, GENUI_ARTIFACT_VERSION, type CreateGenuiArtifactOptions, type GenuiArtifactTheme, type GenuiArtifactV1 } from './types.ts'
6
+
7
+ /** 复制 durable 状态并移除密码字段。 */
8
+ function safeState(state: BlockInteractionState | undefined, secretIds: Set<string>): BlockInteractionState | undefined {
9
+ if (state === undefined) return undefined
10
+ const fields = Object.fromEntries(Object.entries(state.fields ?? {}).filter(([id]) => !secretIds.has(id)))
11
+ return {
12
+ ...(state.answers === undefined ? {} : { answers: { ...state.answers } }),
13
+ ...(state.multiAnswers === undefined ? {} : { multiAnswers: Object.fromEntries(Object.entries(state.multiAnswers).map(([id, values]) => [id, [...values]])) }),
14
+ ...(state.locked === undefined ? {} : { locked: state.locked }),
15
+ ...(Object.keys(fields).length === 0 ? {} : { fields }),
16
+ }
17
+ }
18
+
19
+ /** 复制节点树并递归移除密码默认值。 */
20
+ function sanitizeNodes(items: GenuiNode[], secretIds: Set<string>): GenuiNode[] {
21
+ return items.map(item => {
22
+ const node = JSON.parse(JSON.stringify(item)) as GenuiNode & Record<string, unknown>
23
+ if (node.type === 'input' && node.inputType === 'password') {
24
+ if (typeof node.id === 'string') secretIds.add(node.id)
25
+ delete node.value
26
+ }
27
+ if (Array.isArray(node.items)) {
28
+ if (node.type === 'list') {
29
+ node.items = node.items.map(child => {
30
+ if (typeof child === 'object' && child !== null && 'type' in child) {
31
+ return sanitizeNodes([child as GenuiNode], secretIds)[0]!
32
+ }
33
+ return child
34
+ }) as typeof node.items
35
+ } else {
36
+ node.items = sanitizeNodes(node.items as GenuiNode[], secretIds)
37
+ }
38
+ }
39
+ if (Array.isArray(node.tabs)) {
40
+ node.tabs = node.tabs.map(tab => ({ ...tab, items: sanitizeNodes(tab.items, secretIds) }))
41
+ }
42
+ if (node.type === 'table' && Array.isArray(node.details)) {
43
+ node.details = node.details.map(row => row === null ? null : sanitizeNodes(row, secretIds))
44
+ }
45
+ return node
46
+ })
47
+ }
48
+
49
+ /** 创建规范化 artifact,并清除密码默认值及对应的持久化字段。 */
50
+ export function createGenuiArtifact(
51
+ spec: GenuiSpec,
52
+ state?: BlockInteractionState,
53
+ options: CreateGenuiArtifactOptions = {},
54
+ ): GenuiArtifactV1 {
55
+ const processed = processGenuiSpec(spec)
56
+ if (processed.spec === null) throw new GenuiExportError('artifact-invalid', 'invalid GenUI spec')
57
+ const { panel: _panel, append: _append, ...portableSpec } = processed.spec
58
+ const secretIds = new Set<string>()
59
+ const sanitizedSpec = { ...portableSpec, items: sanitizeNodes(portableSpec.items, secretIds) }
60
+ const theme: GenuiArtifactTheme = options.theme ?? (typeof document !== 'undefined' && document.body.hasAttribute('data-ds-dark-theme') ? 'dark' : 'light')
61
+ const sanitizedState = safeState(state, secretIds)
62
+ return {
63
+ format: GENUI_ARTIFACT_FORMAT,
64
+ version: GENUI_ARTIFACT_VERSION,
65
+ spec: sanitizedSpec,
66
+ ...(sanitizedState === undefined ? {} : { state: sanitizedState }),
67
+ presentation: { locale: options.locale ?? currentLocale(), theme },
68
+ }
69
+ }
@@ -0,0 +1,42 @@
1
+ import { GenuiExportError, type GenuiArtifactV1 } from './types.ts'
2
+ import { serializeGenuiArtifact } from './json.ts'
3
+ import { buildStandaloneHtml } from './html.ts'
4
+
5
+ /** 过滤文件名中的路径符号、控制字符和危险标点。 */
6
+ export function sanitizeArtifactFilename(title: string | undefined, extension: '.html' | '.genui.json'): string {
7
+ const base = (title ?? '').replace(/[\\/:*?"<>|\u0000-\u001f\u007f]/g, '').trim().replace(/\s+/g, ' ').slice(0, 120).replace(/[. ]+$/g, '')
8
+ return `${base || 'genui'}${extension}`
9
+ }
10
+
11
+ /** 触发浏览器下载并释放临时地址。 */
12
+ export function downloadBlob(blob: Blob, filename: string): void {
13
+ const url = URL.createObjectURL(blob)
14
+ const anchor = document.createElement('a')
15
+ anchor.href = url
16
+ anchor.download = filename
17
+ anchor.style.display = 'none'
18
+ document.body.appendChild(anchor)
19
+ anchor.click()
20
+ anchor.remove()
21
+ window.setTimeout(() => URL.revokeObjectURL(url), 0)
22
+ }
23
+
24
+ /** 下载规范化 GenUI JSON artifact。 */
25
+ export function downloadGenuiArtifactJson(artifact: GenuiArtifactV1): void {
26
+ try {
27
+ downloadBlob(new Blob([serializeGenuiArtifact(artifact)], { type: 'application/json;charset=utf-8' }), sanitizeArtifactFilename(artifact.spec.title, '.genui.json'))
28
+ } catch (error) {
29
+ throw new GenuiExportError('download-failed', error instanceof Error ? error.message : 'artifact download failed')
30
+ }
31
+ }
32
+
33
+ /** 生成并下载独立 HTML。 */
34
+ export async function downloadGenuiArtifactHtml(artifact: GenuiArtifactV1): Promise<void> {
35
+ try {
36
+ const html = await buildStandaloneHtml(artifact)
37
+ downloadBlob(new Blob([html], { type: 'text/html;charset=utf-8' }), sanitizeArtifactFilename(artifact.spec.title, '.html'))
38
+ } catch (error) {
39
+ if (error instanceof GenuiExportError) throw error
40
+ throw new GenuiExportError('download-failed', error instanceof Error ? error.message : 'artifact download failed')
41
+ }
42
+ }
@@ -0,0 +1,157 @@
1
+ import { assetUrl } from '../asset-loader.ts'
2
+ import { parseGenuiArtifact } from './parse.ts'
3
+ import { analyzeGenuiPortability } from './portability.ts'
4
+ import { GenuiExportError, type GenuiArtifactV1, type GenuiStandaloneAsset } from './types.ts'
5
+ import { STANDALONE_THEME_CSS } from './standalone-theme.ts'
6
+ import type { GenuiSpec } from '../spec.ts'
7
+
8
+ const bundleCache = new Map<string, Promise<Uint8Array>>()
9
+
10
+ /** 将二进制内容编码为不会闭合 script 标签的 Base64。 */
11
+ function bytesToBase64(bytes: Uint8Array): string {
12
+ let binary = ''
13
+ const chunkSize = 0x8000
14
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
15
+ binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
16
+ }
17
+ return btoa(binary)
18
+ }
19
+
20
+ /** 转义 HTML 属性和标题中的文本。 */
21
+ function escapeHtml(value: string): string {
22
+ return value.replace(/[&<>"']/g, character => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]!)
23
+ }
24
+
25
+ /** 获取并缓存构建产物字节,失败时保留可识别的导出错误。 */
26
+ function cachedBundle(name: string, code: GenuiStandaloneAsset | 'runtime'): Promise<Uint8Array> {
27
+ const existing = bundleCache.get(name)
28
+ if (existing !== undefined) return existing
29
+ const task = fetch(assetUrl(name)).then(async response => {
30
+ if (!response.ok) throw new GenuiExportError(code === 'runtime' ? 'runtime-fetch-failed' : 'asset-fetch-failed', `${name}: HTTP ${response.status}`)
31
+ return new Uint8Array(await response.arrayBuffer())
32
+ }).catch(error => {
33
+ bundleCache.delete(name)
34
+ if (error instanceof GenuiExportError) throw error
35
+ throw new GenuiExportError(code === 'runtime' ? 'runtime-fetch-failed' : 'asset-fetch-failed', `${name}: ${error instanceof Error ? error.message : 'fetch failed'}`)
36
+ })
37
+ bundleCache.set(name, task)
38
+ return task
39
+ }
40
+
41
+ /** 创建仅存放 Base64 数据的非执行 payload 节点。 */
42
+ function bundleElement(name: string, bytes: Uint8Array): string {
43
+ return `<script type="application/octet-stream" data-genui-bundle="${name}">${bytesToBase64(bytes)}</script>`
44
+ }
45
+
46
+ /** 将媒体相对地址转换为导出页面所在站点的绝对地址。 */
47
+ function resolveMediaUrls(spec: GenuiSpec, baseURI: string): GenuiSpec {
48
+ const copy = structuredClone(spec)
49
+ /** 遍历规范中的嵌套节点和容器。 */
50
+ function visit(value: unknown): void {
51
+ if (Array.isArray(value)) {
52
+ for (const item of value) visit(item)
53
+ return
54
+ }
55
+ if (typeof value !== 'object' || value === null) return
56
+ const node = value as Record<string, unknown>
57
+ if (node.type === 'image' || node.type === 'audio' || node.type === 'video') {
58
+ for (const field of node.type === 'video' ? ['src', 'poster'] : ['src']) {
59
+ const media = node[field]
60
+ if (typeof media !== 'string' || /^https?:\/\//i.test(media)) continue
61
+ const url = new URL(media, baseURI)
62
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new GenuiExportError('artifact-invalid', `media URL cannot be exported: ${media}`)
63
+ node[field] = url.href
64
+ }
65
+ }
66
+ for (const child of Object.values(node)) visit(child)
67
+ }
68
+ visit(copy.items)
69
+ return copy
70
+ }
71
+
72
+ /** 返回执行内嵌 bundle 的静态启动代码。 */
73
+ function bootstrapSource(): string {
74
+ return `
75
+ async function loadBundle(element) {
76
+ const binary = atob(element.textContent.trim());
77
+ const bytes = new Uint8Array(binary.length);
78
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
79
+ const url = URL.createObjectURL(new Blob([bytes], { type: 'text/javascript' }));
80
+ try {
81
+ await new Promise((resolve, reject) => {
82
+ const script = document.createElement('script');
83
+ script.src = url;
84
+ script.onload = resolve;
85
+ script.onerror = reject;
86
+ document.head.appendChild(script);
87
+ });
88
+ } finally {
89
+ URL.revokeObjectURL(url);
90
+ }
91
+ }
92
+ async function start() {
93
+ for (const element of document.querySelectorAll('[data-genui-bundle]')) await loadBundle(element);
94
+ const encoded = document.querySelector('#genui-artifact').textContent.trim();
95
+ const artifact = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded), character => character.charCodeAt(0))));
96
+ window.__GenuiStandalone__.mount(document.querySelector('#genui-root'), artifact);
97
+ }
98
+ start().catch(error => {
99
+ const root = document.querySelector('#genui-root');
100
+ root.textContent = error instanceof Error ? error.message : 'GenUI could not start';
101
+ root.setAttribute('role', 'alert');
102
+ });
103
+ `
104
+ }
105
+
106
+ /** 使用已下载的运行文件生成完整的独立 HTML 文档。 */
107
+ export function createStandaloneHtmlDocument(
108
+ artifact: GenuiArtifactV1,
109
+ bundles: ReadonlyMap<string, Uint8Array>,
110
+ baseURI = document.baseURI,
111
+ ): string {
112
+ const htmlArtifact = { ...artifact, spec: resolveMediaUrls(artifact.spec, baseURI) }
113
+ const encodedArtifact = bytesToBase64(new TextEncoder().encode(JSON.stringify(htmlArtifact)))
114
+ const engines = artifactPortabilityAssets(artifact).map(name => {
115
+ const bytes = bundles.get(`${name}.js`)
116
+ if (bytes === undefined) throw new GenuiExportError('asset-fetch-failed', `${name}.js: bundle unavailable`)
117
+ return bundleElement(name, bytes)
118
+ }).join('\n')
119
+ const runtime = bundles.get('standalone-runtime.js')
120
+ if (runtime === undefined) throw new GenuiExportError('runtime-fetch-failed', 'standalone-runtime.js: bundle unavailable')
121
+ const csp = "default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline'; font-src data:; img-src 'self' data: blob: https: http:; media-src 'self' data: blob: https: http:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"
122
+ return `<!doctype html>
123
+ <html lang="${artifact.presentation.locale === 'zh' ? 'zh-CN' : 'en'}">
124
+ <head>
125
+ <meta charset="utf-8">
126
+ <meta name="viewport" content="width=device-width,initial-scale=1">
127
+ <title>${escapeHtml(artifact.spec.title ?? 'GenUI')}</title>
128
+ <meta http-equiv="Content-Security-Policy" content="${csp}">
129
+ <style>${STANDALONE_THEME_CSS}</style>
130
+ </head>
131
+ <body${artifact.presentation.theme === 'dark' ? ' data-ds-dark-theme' : ''}>
132
+ <main id="genui-root"></main>
133
+ <script type="application/octet-stream" id="genui-artifact">${encodedArtifact}</script>
134
+ ${engines}
135
+ ${bundleElement('runtime', runtime)}
136
+ <script>${bootstrapSource()}</script>
137
+ </body>
138
+ </html>`
139
+ }
140
+
141
+ /** 返回 artifact 所需图形引擎名称。 */
142
+ function artifactPortabilityAssets(artifact: GenuiArtifactV1): GenuiStandaloneAsset[] {
143
+ return analyzeGenuiPortability(artifact.spec).requiredAssets
144
+ }
145
+
146
+ /** 获取独立运行文件及规格实际使用的图形引擎,生成单文件 HTML。 */
147
+ export async function buildStandaloneHtml(rawArtifact: GenuiArtifactV1): Promise<string> {
148
+ const artifact = parseGenuiArtifact(rawArtifact)
149
+ if (artifact === null) throw new GenuiExportError('artifact-invalid', 'invalid GenUI artifact')
150
+ const report = analyzeGenuiPortability(artifact.spec)
151
+ if (report.customTypes.length > 0) {
152
+ throw new GenuiExportError('unsupported-custom-component', `custom components: ${report.customTypes.join(', ')}`)
153
+ }
154
+ const names = [...report.requiredAssets.map(name => `${name}.js`), 'standalone-runtime.js']
155
+ const results = await Promise.all(names.map(async name => [name, await cachedBundle(name, name === 'standalone-runtime.js' ? 'runtime' : name.slice(0, -3) as GenuiStandaloneAsset)] as const))
156
+ return createStandaloneHtmlDocument(artifact, new Map(results))
157
+ }
@@ -0,0 +1,15 @@
1
+ export { createGenuiArtifact } from './create.ts'
2
+ export { buildStandaloneHtml } from './html.ts'
3
+ export { downloadGenuiArtifactHtml, downloadGenuiArtifactJson } from './download.ts'
4
+ export { parseGenuiArtifact } from './parse.ts'
5
+ export { analyzeGenuiPortability } from './portability.ts'
6
+ export { serializeGenuiArtifact } from './json.ts'
7
+ export { GenuiExportError } from './types.ts'
8
+ export type {
9
+ CreateGenuiArtifactOptions,
10
+ GenuiArtifactTheme,
11
+ GenuiArtifactV1,
12
+ GenuiExportErrorCode,
13
+ GenuiPortabilityReport,
14
+ GenuiStandaloneAsset,
15
+ } from './types.ts'
@@ -0,0 +1,6 @@
1
+ import type { GenuiArtifactV1 } from './types.ts'
2
+
3
+ /** 以稳定缩进序列化 GenUI artifact。 */
4
+ export function serializeGenuiArtifact(artifact: GenuiArtifactV1): string {
5
+ return JSON.stringify(artifact, null, 2)
6
+ }
@@ -0,0 +1,32 @@
1
+ import { processGenuiSpec } from '../guard.ts'
2
+ import type { BlockInteractionState } from '../interaction-store.ts'
3
+ import { GENUI_ARTIFACT_FORMAT, GENUI_ARTIFACT_VERSION, type GenuiArtifactTheme, type GenuiArtifactV1 } from './types.ts'
4
+ import { createGenuiArtifact } from './create.ts'
5
+
6
+ /** 判断值是否为普通记录对象。 */
7
+ function isRecord(value: unknown): value is Record<string, unknown> {
8
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
9
+ }
10
+
11
+ /** 验证 artifact 持久化交互状态的字段类型。 */
12
+ function validState(value: unknown): boolean {
13
+ if (!isRecord(value)) return false
14
+ if (value.answers !== undefined && (!isRecord(value.answers) || !Object.values(value.answers).every(item => typeof item === 'string'))) return false
15
+ if (value.multiAnswers !== undefined && (!isRecord(value.multiAnswers) || !Object.values(value.multiAnswers).every(item => Array.isArray(item) && item.every(entry => typeof entry === 'string')))) return false
16
+ if (value.locked !== undefined && typeof value.locked !== 'boolean') return false
17
+ return value.fields === undefined || (isRecord(value.fields) && Object.values(value.fields).every(item => typeof item === 'string'))
18
+ }
19
+
20
+ /** 校验 artifact 格式并重新执行当前 GenUI 规范化流程。 */
21
+ export function parseGenuiArtifact(value: unknown): GenuiArtifactV1 | null {
22
+ if (!isRecord(value) || value.format !== GENUI_ARTIFACT_FORMAT || value.version !== GENUI_ARTIFACT_VERSION || !isRecord(value.presentation)) return null
23
+ if (value.presentation.locale !== 'en' && value.presentation.locale !== 'zh') return null
24
+ if (value.presentation.theme !== 'light' && value.presentation.theme !== 'dark') return null
25
+ if (value.state !== undefined && !validState(value.state)) return null
26
+ const processed = processGenuiSpec(value.spec)
27
+ if (processed.spec === null || processed.errors.length > 0) return null
28
+ return createGenuiArtifact(processed.spec, value.state as BlockInteractionState | undefined, {
29
+ locale: value.presentation.locale,
30
+ theme: value.presentation.theme as GenuiArtifactTheme,
31
+ })
32
+ }
@@ -0,0 +1,47 @@
1
+ import { echartEngineFor } from '../echarts-engine.ts'
2
+ import type { GenuiNode, GenuiSpec } from '../spec.ts'
3
+ import { GENUI_NATIVE_TYPES } from '../genui-runtime/schema.ts'
4
+ import { safeMediaSrc } from '../genui-runtime/value-utils.ts'
5
+ import type { GenuiPortabilityReport, GenuiStandaloneAsset } from './types.ts'
6
+
7
+ const ASSET_ORDER: GenuiStandaloneAsset[] = ['mermaid', 'three', 'echarts-core', 'echarts-full']
8
+
9
+ /** 递归收集当前节点树依赖的引擎和媒体信息。 */
10
+ function scan(items: unknown[], report: GenuiPortabilityReport, assets: Set<GenuiStandaloneAsset>): void {
11
+ for (const item of items) {
12
+ if (typeof item !== 'object' || item === null || !('type' in item) || typeof item.type !== 'string') continue
13
+ const node = item as GenuiNode & Record<string, unknown>
14
+ if (!GENUI_NATIVE_TYPES.has(node.type)) report.customTypes.push(node.type)
15
+ if (node.type === 'mermaid') assets.add('mermaid')
16
+ if (node.type === 'scene3d') assets.add('three')
17
+ if (node.type === 'echart') assets.add(echartEngineFor(node as Extract<GenuiNode, { type: 'echart' }>))
18
+ if (typeof node.action === 'string' || node.type === 'submit' && (typeof node.action === 'string' || typeof node.resetAction === 'string')) report.hasModelActions = true
19
+ if (node.type === 'image' || node.type === 'audio' || node.type === 'video') {
20
+ const src = safeMediaSrc(node.src)
21
+ if (src !== undefined) report.externalMedia.push(src)
22
+ if (node.type === 'video') {
23
+ const poster = safeMediaSrc(node.poster)
24
+ if (poster !== undefined) report.externalMedia.push(poster)
25
+ }
26
+ }
27
+ if (Array.isArray(node.items)) {
28
+ if (node.type === 'list') scan(node.items.filter(child => typeof child === 'object' && child !== null && 'type' in child) as unknown[], report, assets)
29
+ else if (node.type === 'accordion') {
30
+ for (const section of node.items) if (typeof section === 'object' && section !== null && 'items' in section && Array.isArray(section.items)) scan(section.items, report, assets)
31
+ } else scan(node.items, report, assets)
32
+ }
33
+ if (Array.isArray(node.tabs)) for (const tab of node.tabs) if (typeof tab === 'object' && tab !== null && 'items' in tab && Array.isArray(tab.items)) scan(tab.items, report, assets)
34
+ if (node.type === 'table' && Array.isArray(node.details)) for (const row of node.details) if (Array.isArray(row)) scan(row, report, assets)
35
+ }
36
+ }
37
+
38
+ /** 扫描嵌套 GenUI 节点,选择运行资源并列出独立页面限制。 */
39
+ export function analyzeGenuiPortability(spec: GenuiSpec): GenuiPortabilityReport {
40
+ const report: GenuiPortabilityReport = { requiredAssets: [], customTypes: [], externalMedia: [], hasModelActions: false }
41
+ const assets = new Set<GenuiStandaloneAsset>()
42
+ scan(spec.items, report, assets)
43
+ report.requiredAssets = ASSET_ORDER.filter(name => assets.has(name))
44
+ report.customTypes = [...new Set(report.customTypes)]
45
+ report.externalMedia = [...new Set(report.externalMedia)]
46
+ return report
47
+ }
@@ -0,0 +1,94 @@
1
+ /** standalone 页面使用的基础颜色和版面样式。 */
2
+ export const STANDALONE_THEME_CSS = `
3
+ :root {
4
+ color-scheme: light;
5
+ --dsw-static-neutral-bluish-00: rgb(255, 255, 255);
6
+ --dsw-static-neutral-bluish-50: rgb(249, 250, 251);
7
+ --dsw-static-neutral-bluish-300: rgb(207, 211, 214);
8
+ --dsw-static-neutral-bluish-400: rgb(173, 178, 184);
9
+ --dsw-static-neutral-bluish-600: rgb(129, 133, 140);
10
+ --dsw-static-neutral-bluish-700: rgb(97, 102, 107);
11
+ --dsw-static-neutral-bluish-800: rgb(53, 54, 56);
12
+ --dsw-static-neutral-bluish-850: rgb(44, 44, 46);
13
+ --dsw-static-neutral-bluish-875: rgb(35, 35, 36);
14
+ --dsw-static-neutral-bluish-900: rgb(27, 27, 28);
15
+ --dsw-static-neutral-bluish-950: rgb(21, 21, 23);
16
+ --dsw-static-neutral-bluish-1000: rgb(15, 17, 21);
17
+ --dsw-alias-bg-base: var(--dsw-static-neutral-bluish-00);
18
+ --dsw-alias-bg-layer-1: var(--dsw-static-neutral-bluish-00);
19
+ --dsw-alias-bg-layer-2: var(--dsw-static-neutral-bluish-00);
20
+ --dsw-alias-bg-layer-3: var(--dsw-static-neutral-bluish-00);
21
+ --dsw-alias-border-l1: rgba(0, 0, 0, 0.04);
22
+ --dsw-alias-border-l2: rgba(0, 0, 0, 0.1);
23
+ --dsw-alias-fill-hover: #eef2f7;
24
+ --dsw-alias-label-primary: var(--dsw-static-neutral-bluish-1000);
25
+ --dsw-alias-label-secondary: var(--dsw-static-neutral-bluish-700);
26
+ --dsw-alias-label-tertiary: var(--dsw-static-neutral-bluish-600);
27
+ --dsw-alias-label-caption: var(--dsw-static-neutral-bluish-400);
28
+ --dsw-alias-markdown-code-block: var(--dsw-static-neutral-bluish-50);
29
+ --dsw-alias-markdown-hr: #cbd5e1;
30
+ /* DSH 静态调色板供语义状态别名使用。 */
31
+ --dsw-static-deepseek-100: rgb(228, 237, 253);
32
+ --dsw-static-deepseek-400: rgb(122, 170, 255);
33
+ --dsw-static-deepseek-500: rgb(65, 118, 230);
34
+ --dsw-static-deepseek-800: rgb(52, 65, 91);
35
+ --dsw-static-green-100: rgb(230, 250, 237);
36
+ --dsw-static-green-400: rgb(78, 209, 126);
37
+ --dsw-static-green-500: rgb(34, 197, 94);
38
+ --dsw-static-green-900: rgb(35, 60, 44);
39
+ --dsw-static-amber-100: rgb(254, 245, 231);
40
+ --dsw-static-amber-400: rgb(247, 173, 49);
41
+ --dsw-static-amber-500: rgb(245, 158, 11);
42
+ --dsw-static-amber-600: rgb(221, 134, 41);
43
+ --dsw-static-amber-900: rgb(39, 36, 31);
44
+ --dsw-static-red-400: rgb(242, 90, 90);
45
+ --dsw-static-red-600: rgb(236, 19, 19);
46
+
47
+ /* DSH 浅色主题语义状态别名。 */
48
+ --dsw-alias-state-business-primary: var(--dsw-static-deepseek-500);
49
+ --dsw-alias-state-business-tertiary: var(--dsw-static-deepseek-100);
50
+ --dsw-alias-state-success-primary: var(--dsw-static-green-500);
51
+ --dsw-alias-state-success-secondary: var(--dsw-static-green-400);
52
+ --dsw-alias-state-success-tertiary: var(--dsw-static-green-100);
53
+ --dsw-alias-state-warn-label: var(--dsw-static-amber-600);
54
+ --dsw-alias-state-warn-primary: var(--dsw-static-amber-500);
55
+ --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400);
56
+ --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-100);
57
+ --dsw-alias-state-error-primary: var(--dsw-static-red-600);
58
+ --dsw-alias-state-error-secondary: var(--dsw-static-red-400);
59
+ --dsw-static-deepseek-300: rgb(183, 200, 254);
60
+ --dsw-static-deepseek-450: rgb(86, 134, 254);
61
+ --dsw-static-blue-450: rgb(77, 147, 248);
62
+ }
63
+ body[data-ds-dark-theme] {
64
+ color-scheme: dark;
65
+ --dsw-alias-bg-base: var(--dsw-static-neutral-bluish-950);
66
+ --dsw-alias-bg-layer-1: var(--dsw-static-neutral-bluish-875);
67
+ --dsw-alias-bg-layer-2: var(--dsw-static-neutral-bluish-850);
68
+ --dsw-alias-bg-layer-3: var(--dsw-static-neutral-bluish-800);
69
+ --dsw-alias-border-l1: rgba(255, 255, 255, 0.06);
70
+ --dsw-alias-border-l2: rgba(255, 255, 255, 0.12);
71
+ --dsw-alias-fill-hover: #2b3542;
72
+ --dsw-alias-label-primary: var(--dsw-static-neutral-bluish-50);
73
+ --dsw-alias-label-secondary: var(--dsw-static-neutral-bluish-300);
74
+ --dsw-alias-label-tertiary: var(--dsw-static-neutral-bluish-400);
75
+ --dsw-alias-label-caption: var(--dsw-static-neutral-bluish-600);
76
+ --dsw-alias-markdown-code-block: var(--dsw-static-neutral-bluish-900);
77
+ --dsw-alias-markdown-hr: #465365;
78
+ /* DSH 深色主题语义状态别名。 */
79
+ --dsw-alias-state-business-primary: var(--dsw-static-deepseek-400);
80
+ --dsw-alias-state-business-tertiary: var(--dsw-static-deepseek-800);
81
+ --dsw-alias-state-success-primary: var(--dsw-static-green-500);
82
+ --dsw-alias-state-success-secondary: var(--dsw-static-green-400);
83
+ --dsw-alias-state-success-tertiary: var(--dsw-static-green-900);
84
+ --dsw-alias-state-warn-label: var(--dsw-static-amber-600);
85
+ --dsw-alias-state-warn-primary: var(--dsw-static-amber-500);
86
+ --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400);
87
+ --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-900);
88
+ --dsw-alias-state-error-primary: var(--dsw-static-red-400);
89
+ --dsw-alias-state-error-secondary: var(--dsw-static-red-400);
90
+ }
91
+ html { min-height: 100%; }
92
+ body { margin: 0; min-height: 100vh; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
93
+ #genui-root { width: min(1200px, calc(100% - 32px)); margin: 0 auto; padding: 32px 0 56px; }
94
+ `
@@ -0,0 +1,44 @@
1
+ import type { LocaleId } from '../i18n/runtime.ts'
2
+ import type { GenuiSpec } from '../spec.ts'
3
+ import type { BlockInteractionState } from '../interaction-store.ts'
4
+
5
+ export const GENUI_ARTIFACT_FORMAT = 'dsh-genui'
6
+ export const GENUI_ARTIFACT_VERSION = 1 as const
7
+
8
+ export type GenuiArtifactTheme = 'light' | 'dark'
9
+ export type GenuiStandaloneAsset = 'mermaid' | 'three' | 'echarts-core' | 'echarts-full'
10
+
11
+ export interface GenuiArtifactV1 {
12
+ format: typeof GENUI_ARTIFACT_FORMAT
13
+ version: typeof GENUI_ARTIFACT_VERSION
14
+ spec: GenuiSpec
15
+ state?: BlockInteractionState
16
+ presentation: { locale: LocaleId; theme: GenuiArtifactTheme }
17
+ }
18
+
19
+ export interface GenuiPortabilityReport {
20
+ requiredAssets: GenuiStandaloneAsset[]
21
+ customTypes: string[]
22
+ externalMedia: string[]
23
+ hasModelActions: boolean
24
+ }
25
+
26
+ export type GenuiExportErrorCode =
27
+ | 'unsupported-custom-component'
28
+ | 'runtime-fetch-failed'
29
+ | 'asset-fetch-failed'
30
+ | 'artifact-invalid'
31
+ | 'download-failed'
32
+
33
+ /** 导出流程遇到可供界面识别的错误时使用。 */
34
+ export class GenuiExportError extends Error {
35
+ constructor(readonly code: GenuiExportErrorCode, message: string) {
36
+ super(message)
37
+ this.name = 'GenuiExportError'
38
+ }
39
+ }
40
+
41
+ export interface CreateGenuiArtifactOptions {
42
+ locale?: LocaleId
43
+ theme?: GenuiArtifactTheme
44
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * ECharts CORE asset bundle — the tree-shaken engine used by the common
3
+ * presets (bar / line / area / pie / scatter / bigline).
4
+ *
5
+ * Progressive disclosure for the engine: the full ECharts build is ~1 MB, and
6
+ * most answers only ever draw a bar or line chart. This bundle registers the
7
+ * same `createChart` surface with only the chart types and components those
8
+ * presets touch, so a basic chart downloads a fraction of the payload; the
9
+ * full engine (`echarts-full.js`) is fetched only when a spec needs a type
10
+ * outside this set or ships a raw `option`.
11
+ * @module @changfenhuang/dsh-genui/client/asset-echarts-core
12
+ */
13
+ import * as echarts from 'echarts/core'
14
+ import { BarChart, LineChart, PieChart, ScatterChart } from 'echarts/charts'
15
+ import {
16
+ DataZoomComponent, DatasetComponent, GridComponent, LegendComponent, MarkAreaComponent,
17
+ MarkLineComponent, MarkPointComponent, TitleComponent, TooltipComponent, TransformComponent,
18
+ } from 'echarts/components'
19
+ import { CanvasRenderer } from 'echarts/renderers'
20
+ import type { EChartsCoreOption, EChartsType } from 'echarts/core'
21
+
22
+ echarts.use([
23
+ BarChart, LineChart, PieChart, ScatterChart,
24
+ GridComponent, TooltipComponent, LegendComponent, TitleComponent,
25
+ DataZoomComponent, MarkLineComponent, MarkAreaComponent, MarkPointComponent,
26
+ DatasetComponent, TransformComponent,
27
+ CanvasRenderer,
28
+ ])
29
+
30
+ function createChart(el: HTMLElement, option: EChartsCoreOption, opts?: { height?: number }): EChartsType {
31
+ const initOpts = opts !== undefined && opts.height !== undefined ? { height: opts.height } : undefined
32
+ const instance = echarts.init(el, undefined, initOpts)
33
+ instance.setOption(option)
34
+ return instance
35
+ }
36
+
37
+ const win = globalThis as unknown as { __GenuiAssets__?: Record<string, unknown> }
38
+ const assets = win.__GenuiAssets__ ?? (win.__GenuiAssets__ = {})
39
+ assets.echartsCore = { createChart }