base-screen 0.3.0 → 0.4.0

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/dist/_internal/contracts/document/schema.d.ts +7 -0
  2. package/dist/_internal/contracts/document/schema.js +1 -1
  3. package/dist/_internal/contracts/document/validate-value-ref.js +6 -1
  4. package/dist/_internal/contracts/screen-document.schema.json +15 -3
  5. package/dist/_internal/contracts/types/diagnostics.d.ts +1 -1
  6. package/dist/_internal/contracts/types/document.d.ts +3 -1
  7. package/dist/_internal/core/blueprint/runtime-simulate.d.ts +57 -0
  8. package/dist/_internal/core/blueprint/runtime-simulate.js +177 -0
  9. package/dist/_internal/core/blueprint/runtime.d.ts +1 -0
  10. package/dist/_internal/core/blueprint/runtime.js +1 -0
  11. package/dist/_internal/core/commands/apply-collection-commands.d.ts +32 -0
  12. package/dist/_internal/core/commands/apply-collection-commands.js +174 -0
  13. package/dist/_internal/core/commands/apply.js +13 -0
  14. package/dist/_internal/core/commands/parse-command.js +12 -0
  15. package/dist/_internal/core/commands/types.d.ts +29 -1
  16. package/dist/_internal/core/data/data-candidates.d.ts +38 -0
  17. package/dist/_internal/core/data/data-candidates.js +186 -0
  18. package/dist/_internal/core/data/dataset-profile.d.ts +71 -0
  19. package/dist/_internal/core/data/dataset-profile.js +170 -0
  20. package/dist/_internal/core/data/sample-values.d.ts +25 -0
  21. package/dist/_internal/core/data/sample-values.js +45 -0
  22. package/dist/_internal/core/diff/screen-diff.js +6 -0
  23. package/dist/_internal/core/index.d.ts +7 -1
  24. package/dist/_internal/core/index.js +7 -1
  25. package/dist/_internal/core/state/state-preset.d.ts +32 -0
  26. package/dist/_internal/core/state/state-preset.js +37 -0
  27. package/dist/_internal/core/validation/layout-audit.d.ts +17 -0
  28. package/dist/_internal/core/validation/layout-audit.js +228 -0
  29. package/dist/_internal/core/validation/legibility.d.ts +9 -0
  30. package/dist/_internal/core/validation/legibility.js +33 -0
  31. package/dist/_internal/engine/browser/controllers/dataset/designer-dataset-draft-controller.d.ts +6 -1
  32. package/dist/_internal/engine/browser/controllers/designer-change-controller.d.ts +27 -0
  33. package/dist/_internal/engine/browser/dom/change/designer-change-dom.d.ts +21 -5
  34. package/dist/_internal/engine/browser/dom/dataset/designer-data-section-diff.d.ts +4 -6
  35. package/dist/_internal/engine/browser/dom/value-ref/designer-value-ref-types.d.ts +2 -0
  36. package/dist/_internal/engine/browser/viewport/designer-canvas-aids-types.d.ts +3 -3
  37. package/dist/_internal/engine/browser/viewport/designer-canvas-aids.d.ts +5 -3
  38. package/dist/_internal/engine/browser/viewport/designer-canvas-measurements.d.ts +2 -14
  39. package/dist/_internal/engine/browser/viewport/designer-guide-overlay-nodes.d.ts +2 -0
  40. package/dist/_internal/engine/browser/viewport/designer-snap-tuning.d.ts +14 -0
  41. package/dist/_internal/engine/common/operations/change/designer-change-events.d.ts +2 -0
  42. package/dist/_internal/engine/common/operations/change/designer-change-proposal.d.ts +35 -2
  43. package/dist/_internal/engine/common/operations/display/designer-target-display.d.ts +2 -2
  44. package/dist/_internal/engine/common/operations/style/designer-component-states.d.ts +7 -2
  45. package/dist/_internal/engine/common/ui-text/designer-ui-text.d.ts +42 -2
  46. package/dist/_internal/engine/{designer-blueprint-workbench-panel-CJ3iZo5v.js → designer-blueprint-workbench-panel-BWSglfAb.js} +210 -290
  47. package/dist/_internal/engine/{designer-dataset-controller-CrfOg2Ys.js → designer-dataset-controller-DdbY4ILC.js} +619 -561
  48. package/dist/_internal/engine/designer-element/api/designer-element-change.d.ts +24 -0
  49. package/dist/_internal/engine/designer-element/base-screen-designer-element.d.ts +12 -0
  50. package/dist/_internal/engine/designer-element/designer-element-public-api.d.ts +2 -1
  51. package/dist/_internal/engine/designer-element/runtime/designer-element-rendering.d.ts +1 -1
  52. package/dist/_internal/engine/designer-element/runtime/designer-element-runtime.d.ts +4 -1
  53. package/dist/_internal/engine/designer-element/runtime/designer-element-sample-data.d.ts +23 -0
  54. package/dist/_internal/engine/{designer-field-primitives-KBZuWN_D.js → designer-field-primitives-Crn464Qg.js} +44 -3
  55. package/dist/_internal/engine/{designer-left-panel-groups-dom-N2OHOWjl.js → designer-left-panel-groups-dom-DFdLWxxY.js} +2 -2
  56. package/dist/_internal/engine/{host-resource-selection-xo2mLCD4.js → host-resource-selection-CWrPLVOc.js} +2 -2
  57. package/dist/_internal/engine/index.js +4742 -4360
  58. package/dist/_internal/host-kit/index.d.ts +1 -0
  59. package/dist/_internal/host-kit/index.js +1 -0
  60. package/dist/_internal/host-kit/intent/index.d.ts +16 -0
  61. package/dist/_internal/host-kit/intent/index.js +13 -0
  62. package/dist/_internal/host-kit/intent/intent-behavior.d.ts +59 -0
  63. package/dist/_internal/host-kit/intent/intent-behavior.js +812 -0
  64. package/dist/_internal/host-kit/intent/intent-block.d.ts +59 -0
  65. package/dist/_internal/host-kit/intent/intent-block.js +359 -0
  66. package/dist/_internal/host-kit/intent/intent-catalog.d.ts +105 -0
  67. package/dist/_internal/host-kit/intent/intent-catalog.js +60 -0
  68. package/dist/_internal/host-kit/intent/intent-compile-types.d.ts +222 -0
  69. package/dist/_internal/host-kit/intent/intent-compile-types.js +10 -0
  70. package/dist/_internal/host-kit/intent/intent-compile.d.ts +35 -0
  71. package/dist/_internal/host-kit/intent/intent-compile.js +465 -0
  72. package/dist/_internal/host-kit/intent/intent-data-check.d.ts +50 -0
  73. package/dist/_internal/host-kit/intent/intent-data-check.js +163 -0
  74. package/dist/_internal/host-kit/intent/intent-data-context.d.ts +53 -0
  75. package/dist/_internal/host-kit/intent/intent-data-context.js +200 -0
  76. package/dist/_internal/host-kit/intent/intent-dataset.d.ts +52 -0
  77. package/dist/_internal/host-kit/intent/intent-dataset.js +125 -0
  78. package/dist/_internal/host-kit/intent/intent-format.d.ts +33 -0
  79. package/dist/_internal/host-kit/intent/intent-format.js +94 -0
  80. package/dist/_internal/host-kit/intent/intent-kpi-bind.d.ts +29 -0
  81. package/dist/_internal/host-kit/intent/intent-kpi-bind.js +59 -0
  82. package/dist/_internal/host-kit/intent/intent-layout.d.ts +102 -0
  83. package/dist/_internal/host-kit/intent/intent-layout.js +264 -0
  84. package/dist/_internal/host-kit/intent/intent-parse.d.ts +39 -0
  85. package/dist/_internal/host-kit/intent/intent-parse.js +930 -0
  86. package/dist/_internal/host-kit/intent/intent-prepare.d.ts +52 -0
  87. package/dist/_internal/host-kit/intent/intent-prepare.js +104 -0
  88. package/dist/_internal/host-kit/intent/intent-session.d.ts +202 -0
  89. package/dist/_internal/host-kit/intent/intent-session.js +1001 -0
  90. package/dist/_internal/host-kit/intent/intent-stream.d.ts +28 -0
  91. package/dist/_internal/host-kit/intent/intent-stream.js +183 -0
  92. package/dist/_internal/host-kit/intent/intent-style.d.ts +37 -0
  93. package/dist/_internal/host-kit/intent/intent-style.js +77 -0
  94. package/dist/_internal/host-kit/intent/intent-types.d.ts +234 -0
  95. package/dist/_internal/host-kit/intent/intent-types.js +10 -0
  96. package/dist/_internal/material/chart.js +34 -12
  97. package/dist/_internal/material/table.js +52 -21
  98. package/dist/_internal/plugin-sdk/index.d.ts +6 -0
  99. package/dist/_internal/plugin-sdk/index.js +6 -0
  100. package/dist/_internal/plugin-sdk/material-isolated-csp.d.ts +38 -0
  101. package/dist/_internal/plugin-sdk/material-isolated-csp.js +67 -0
  102. package/dist/_internal/plugin-sdk/material-isolated-runtime.d.ts +22 -0
  103. package/dist/_internal/plugin-sdk/material-isolated-runtime.js +262 -0
  104. package/dist/_internal/plugin-sdk/material-isolated.d.ts +94 -0
  105. package/dist/_internal/plugin-sdk/material-isolated.js +1024 -0
  106. package/dist/_internal/plugin-sdk/material-rendered-element.d.ts +10 -2
  107. package/dist/_internal/plugin-sdk/material-rendered-element.js +71 -7
  108. package/dist/_internal/plugin-sdk/material-spec-audit.d.ts +2 -0
  109. package/dist/_internal/plugin-sdk/material-spec-audit.js +26 -6
  110. package/dist/_internal/plugin-sdk/material-spec.d.ts +20 -0
  111. package/dist/_internal/plugin-sdk/material-spec.js +78 -3
  112. package/dist/_internal/plugin-sdk/material-template-audit.d.ts +12 -0
  113. package/dist/_internal/plugin-sdk/material-template-audit.js +302 -0
  114. package/dist/_internal/plugin-sdk/material-template-expression.d.ts +98 -0
  115. package/dist/_internal/plugin-sdk/material-template-expression.js +549 -0
  116. package/dist/_internal/plugin-sdk/material-template-render.d.ts +32 -0
  117. package/dist/_internal/plugin-sdk/material-template-render.js +579 -0
  118. package/dist/_internal/plugin-sdk/material-template.d.ts +185 -0
  119. package/dist/_internal/plugin-sdk/material-template.js +879 -0
  120. package/dist/auto-register.js +10 -10
  121. package/dist/contracts.js +5 -5
  122. package/dist/contrast-DRPezUIl.js +131 -0
  123. package/dist/contrast-DRPezUIl.js.map +1 -0
  124. package/dist/core.js +156 -136
  125. package/dist/core.js.map +1 -1
  126. package/dist/dataset-profile-Dk6xdtsM.js +261 -0
  127. package/dist/dataset-profile-Dk6xdtsM.js.map +1 -0
  128. package/dist/{designer-3Tb0EIDV.js → designer-CFOvOmLn.js} +2 -2
  129. package/dist/{designer-3Tb0EIDV.js.map → designer-CFOvOmLn.js.map} +1 -1
  130. package/dist/designer-auto-register.js +5 -5
  131. package/dist/{designer-blueprint-workbench-panel-CJ3iZo5v-BebifP4x.js → designer-blueprint-workbench-panel-BWSglfAb-ktaj6Ci9.js} +452 -531
  132. package/dist/designer-blueprint-workbench-panel-BWSglfAb-ktaj6Ci9.js.map +1 -0
  133. package/dist/{designer-dataset-controller-CrfOg2Ys-DhKUEJJe.js → designer-dataset-controller-DdbY4ILC-CMdGdGbr.js} +862 -804
  134. package/dist/designer-dataset-controller-DdbY4ILC-CMdGdGbr.js.map +1 -0
  135. package/dist/{designer-field-primitives-KBZuWN_D-B3h4jpYe.js → designer-field-primitives-Crn464Qg-Bi7q8s5J.js} +45 -4
  136. package/dist/designer-field-primitives-Crn464Qg-Bi7q8s5J.js.map +1 -0
  137. package/dist/{designer-left-panel-groups-dom-N2OHOWjl-D8CzGwbF.js → designer-left-panel-groups-dom-DFdLWxxY-BarlWMLY.js} +4 -4
  138. package/dist/{designer-left-panel-groups-dom-N2OHOWjl-D8CzGwbF.js.map → designer-left-panel-groups-dom-DFdLWxxY-BarlWMLY.js.map} +1 -1
  139. package/dist/designer.js +5 -5
  140. package/dist/{dist-6GRboBs-.js → dist-B2bW2Tru.js} +4 -4
  141. package/dist/{dist-6GRboBs-.js.map → dist-B2bW2Tru.js.map} +1 -1
  142. package/dist/{dist-BjLjFUy1.js → dist-CHK9BTXX.js} +3833 -3453
  143. package/dist/dist-CHK9BTXX.js.map +1 -0
  144. package/dist/engine.js +5 -5
  145. package/dist/{fragment-Y6YnW6wy.js → fragment-B-oP0Fru.js} +3 -3
  146. package/dist/{fragment-Y6YnW6wy.js.map → fragment-B-oP0Fru.js.map} +1 -1
  147. package/dist/host-kit.js +3963 -187
  148. package/dist/host-kit.js.map +1 -1
  149. package/dist/{host-resource-selection-xo2mLCD4-BR5XCcim.js → host-resource-selection-CWrPLVOc-DPDq3jau.js} +5 -5
  150. package/dist/{host-resource-selection-xo2mLCD4-BR5XCcim.js.map → host-resource-selection-CWrPLVOc-DPDq3jau.js.map} +1 -1
  151. package/dist/index.js +10 -10
  152. package/dist/legibility-CS28ivEz.js +12 -0
  153. package/dist/legibility-CS28ivEz.js.map +1 -0
  154. package/dist/{level-scale-BzUjE31V.js → level-scale-CwHqFEVd.js} +2 -2
  155. package/dist/{level-scale-BzUjE31V.js.map → level-scale-CwHqFEVd.js.map} +1 -1
  156. package/dist/{manager-Ch0RTu_i.js → manager-CeB4Jnr9.js} +3 -3
  157. package/dist/{manager-Ch0RTu_i.js.map → manager-CeB4Jnr9.js.map} +1 -1
  158. package/dist/{material-UbSfiuZq.js → material-DeVkzSoT.js} +2 -2
  159. package/dist/{material-UbSfiuZq.js.map → material-DeVkzSoT.js.map} +1 -1
  160. package/dist/material-auto-register.js +1 -1
  161. package/dist/material.js +2 -2
  162. package/dist/{migrate-document-D3HhCVlZ.js → migrate-document-BM888PtC.js} +2 -2
  163. package/dist/{migrate-document-D3HhCVlZ.js.map → migrate-document-BM888PtC.js.map} +1 -1
  164. package/dist/{parse-AOTE9WnD.js → parse-Ji7kE9ZT.js} +9 -4
  165. package/dist/parse-Ji7kE9ZT.js.map +1 -0
  166. package/dist/{parse-B1OD1teS.js → parse-aZat9tAS.js} +3 -3
  167. package/dist/{parse-B1OD1teS.js.map → parse-aZat9tAS.js.map} +1 -1
  168. package/dist/{parse-parts-BNrpdG5o.js → parse-parts-qzl4suzk.js} +2 -2
  169. package/dist/{parse-parts-BNrpdG5o.js.map → parse-parts-qzl4suzk.js.map} +1 -1
  170. package/dist/{plugin-DHgh9uHh.js → plugin-CstHQ5ws.js} +4 -4
  171. package/dist/{plugin-DHgh9uHh.js.map → plugin-CstHQ5ws.js.map} +1 -1
  172. package/dist/plugin-core.js +2 -2
  173. package/dist/plugin-manager.js +1 -1
  174. package/dist/plugin-package-DWifuHi1.js +4206 -0
  175. package/dist/plugin-package-DWifuHi1.js.map +1 -0
  176. package/dist/{plugin-registration-rsmb4GvS.js → plugin-registration-DTwBvnHX.js} +2 -2
  177. package/dist/{plugin-registration-rsmb4GvS.js.map → plugin-registration-DTwBvnHX.js.map} +1 -1
  178. package/dist/plugin-sdk.js +6 -6
  179. package/dist/{plugins-DGRHgREK.js → plugins-QDL0yIql.js} +2 -2
  180. package/dist/{plugins-DGRHgREK.js.map → plugins-QDL0yIql.js.map} +1 -1
  181. package/dist/plugins.js +8 -8
  182. package/dist/renderer.js +1 -1
  183. package/dist/{runtime-dispatch-BfnRDtMe.js → runtime-dispatch-C0gyIrTv.js} +2 -2
  184. package/dist/{runtime-dispatch-BfnRDtMe.js.map → runtime-dispatch-C0gyIrTv.js.map} +1 -1
  185. package/dist/runtime-simulate-aSYO9yDX.js +147 -0
  186. package/dist/runtime-simulate-aSYO9yDX.js.map +1 -0
  187. package/dist/{src-Bm7u11mN-_0u6cMEw.js → src-Bm7u11mN-Bi1hDVkh.js} +39 -39
  188. package/dist/{src-Bm7u11mN-_0u6cMEw.js.map → src-Bm7u11mN-Bi1hDVkh.js.map} +1 -1
  189. package/dist/state-preset-DtpygJOH.js +22 -0
  190. package/dist/state-preset-DtpygJOH.js.map +1 -0
  191. package/dist/{text-BNksUr5J.js → text-BSTz0pFQ.js} +87 -34
  192. package/dist/text-BSTz0pFQ.js.map +1 -0
  193. package/dist/{value-ref-BG_MV9C-.js → value-ref-XkLuckGV.js} +2 -2
  194. package/dist/{value-ref-BG_MV9C-.js.map → value-ref-XkLuckGV.js.map} +1 -1
  195. package/dist/{viewer-CrJupI8I-D9dVcNw4.js → viewer-CrJupI8I-BJiz1cvW.js} +4 -4
  196. package/dist/{viewer-CrJupI8I-D9dVcNw4.js.map → viewer-CrJupI8I-BJiz1cvW.js.map} +1 -1
  197. package/dist/viewer-auto-register.js +2 -2
  198. package/dist/viewer.js +2 -2
  199. package/dist/{viewport-CiCKeAQH.js → viewport-BNIRWjiT.js} +354 -155
  200. package/dist/viewport-BNIRWjiT.js.map +1 -0
  201. package/package.json +12 -12
  202. package/dist/designer-blueprint-workbench-panel-CJ3iZo5v-BebifP4x.js.map +0 -1
  203. package/dist/designer-dataset-controller-CrfOg2Ys-DhKUEJJe.js.map +0 -1
  204. package/dist/designer-field-primitives-KBZuWN_D-B3h4jpYe.js.map +0 -1
  205. package/dist/dist-BjLjFUy1.js.map +0 -1
  206. package/dist/parse-AOTE9WnD.js.map +0 -1
  207. package/dist/plugin-package-Dr5ro6h6.js +0 -1221
  208. package/dist/plugin-package-Dr5ro6h6.js.map +0 -1
  209. package/dist/text-BNksUr5J.js.map +0 -1
  210. package/dist/viewport-CiCKeAQH.js.map +0 -1
@@ -0,0 +1,1024 @@
1
+ import { parseScreenJsonValue, } from '@base-screen/contracts';
2
+ import { BASE_SCREEN_MATERIAL_EVENT, } from '@base-screen/plugin-core';
3
+ import { failure } from './diagnostics.js';
4
+ import { createMaterialDefinition, } from './material-definition.js';
5
+ import { buildBaseScreenIsolatedMetaCsp } from './material-isolated-csp.js';
6
+ import { baseScreenIsolatedRuntime, } from './material-isolated-runtime.js';
7
+ import { formatBaseScreenMaterialNumber } from './material-rendered-element.js';
8
+ import { compileBaseScreenMaterialSpec, createBaseScreenMaterialSpecDataAdapter, normalizeBaseScreenMaterialSpecValue, parseBaseScreenMaterialSpec, } from './material-spec.js';
9
+ import { createBaseScreenMaterialEmptyView, createBaseScreenMaterialErrorView, createBaseScreenMaterialStateView, } from './material-state-view.js';
10
+ export const BASE_SCREEN_ISOLATED_MATERIAL_SOURCE_MAX_BYTES = 200 * 1024;
11
+ const MAX_MESSAGE_BYTES = 64 * 1024;
12
+ const DEFAULT_MAX_FPS = 60;
13
+ const HANDSHAKE_TIMEOUT_MS = 5_000;
14
+ const STALL_TIMEOUT_MS = 2_000;
15
+ const MAX_EVENTS_PER_SECOND = 20;
16
+ const MAX_CONSECUTIVE_ERRORS = 3;
17
+ const MAX_PROTOCOL_VIOLATIONS = 20;
18
+ const RECYCLE_DELAY_MS = 10_000;
19
+ const DPR_RECHECK_MS = 500;
20
+ const LIBRARY_NAME = /^[a-z][a-z0-9-]{0,31}$/;
21
+ const GLOBAL_NAME = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
22
+ const STYLE = ':host{contain:content}.frame{position:relative;box-sizing:border-box;width:100%;height:100%;overflow:hidden}' +
23
+ '.frame>*{box-sizing:border-box;width:100%;height:100%}canvas{display:block}';
24
+ export function createBaseScreenIsolatedMaterialDefinition(options) {
25
+ const spec = parseBaseScreenMaterialSpec(options.spec);
26
+ if (!spec.ok)
27
+ return spec;
28
+ const isolated = spec.value.isolated;
29
+ if (isolated === undefined) {
30
+ return failure('PLUGIN_CORE_LIFECYCLE_INVALID', ['spec', 'isolated'], 'MATERIAL_ISOLATED_REQUIRED:隔离代码物料的规格必须带 isolated。');
31
+ }
32
+ if (typeof options.source !== 'string' ||
33
+ options.source.trim() === '' ||
34
+ new TextEncoder().encode(options.source).byteLength >
35
+ BASE_SCREEN_ISOLATED_MATERIAL_SOURCE_MAX_BYTES) {
36
+ return failure('PLUGIN_CORE_LIFECYCLE_INVALID', ['source'], `组件代码必须是非空文本,最多 ${BASE_SCREEN_ISOLATED_MATERIAL_SOURCE_MAX_BYTES / 1024} KB。`);
37
+ }
38
+ const supplied = new Map((options.libraries ?? []).map((library) => [library.name, library]));
39
+ const libraries = [];
40
+ for (const [index, name] of (isolated.libraries ?? []).entries()) {
41
+ const library = supplied.get(name);
42
+ if (library === undefined ||
43
+ !LIBRARY_NAME.test(library.name) ||
44
+ !GLOBAL_NAME.test(library.global) ||
45
+ typeof library.source !== 'string') {
46
+ return failure('PLUGIN_CORE_LIFECYCLE_INVALID', ['spec', 'isolated', 'libraries', index], `宿主没有提供预置库 ${name}。`);
47
+ }
48
+ libraries.push(library);
49
+ }
50
+ const maxFps = options.maxFps ?? DEFAULT_MAX_FPS;
51
+ if (!Number.isFinite(maxFps) || maxFps < 1 || maxFps > 120) {
52
+ return failure('PLUGIN_CORE_LIFECYCLE_INVALID', ['maxFps'], 'maxFps 必须在 1–120 之间。');
53
+ }
54
+ if (options.sandbox !== undefined && typeof options.sandbox.resolve !== 'function') {
55
+ return failure('PLUGIN_CORE_LIFECYCLE_INVALID', ['sandbox'], 'sandbox.resolve 必须是函数。');
56
+ }
57
+ const manifest = compileBaseScreenMaterialSpec(spec.value, {
58
+ tagName: options.tagName,
59
+ ...(options.libraryVisible === undefined ? {} : { libraryVisible: options.libraryVisible }),
60
+ ...(options.cover === undefined ? {} : { cover: options.cover }),
61
+ });
62
+ if (!manifest.ok)
63
+ return manifest;
64
+ const element = createIsolatedMaterialElement({
65
+ manifest: manifest.value,
66
+ data: spec.value.data,
67
+ bundle: new PackageBundle(options.source, libraries, maxFps),
68
+ tagName: options.tagName,
69
+ ...(options.onAudit === undefined ? {} : { onAudit: options.onAudit }),
70
+ ...(options.onFrame === undefined ? {} : { onFrame: options.onFrame }),
71
+ ...(options.sandbox === undefined ? {} : { sandbox: options.sandbox }),
72
+ });
73
+ return createMaterialDefinition({ manifest: manifest.value, element });
74
+ }
75
+ /**
76
+ * 生成与 `createBaseScreenIsolatedMaterialDefinition` 完全相同的沙箱文档(不注册任何东西)。
77
+ * 宿主可以用它预先把文档放进沙箱路由,测试也用它核对文档恒定。
78
+ */
79
+ export function buildBaseScreenIsolatedSandboxDocument(options) {
80
+ return new PackageBundle(options.source, options.libraries ?? [], options.maxFps ?? DEFAULT_MAX_FPS).document();
81
+ }
82
+ // ---------------------------------------------------------------------------
83
+ // srcdoc 与 CSP
84
+ function escapeScript(source) {
85
+ return source.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--');
86
+ }
87
+ const hashCache = new Map();
88
+ /**
89
+ * 内联脚本的 CSP 哈希源(`'sha256-…'`);库与作者代码按内容缓存。`crypto.subtle` 只在安全上下文
90
+ * 里有:内网用 http 部署的大屏拿不到,退回 SDK 自带的实现。
91
+ */
92
+ function digestText(text) {
93
+ const bytes = new TextEncoder().encode(text);
94
+ const subtle = globalThis.crypto?.subtle;
95
+ return subtle === undefined
96
+ ? Promise.resolve(sha256(bytes))
97
+ : subtle.digest('SHA-256', bytes).then((buffer) => new Uint8Array(buffer));
98
+ }
99
+ function scriptHash(text) {
100
+ let cached = hashCache.get(text);
101
+ if (cached === undefined) {
102
+ const digest = digestText(text);
103
+ cached = digest.then((value) => {
104
+ let binary = '';
105
+ for (const byte of value)
106
+ binary += String.fromCharCode(byte);
107
+ return `'sha256-${btoa(binary)}'`;
108
+ });
109
+ if (hashCache.size > 64)
110
+ hashCache.clear();
111
+ hashCache.set(text, cached);
112
+ }
113
+ return cached;
114
+ }
115
+ const SHA256_K = new Uint32Array([
116
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
117
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
118
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
119
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
120
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
121
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
122
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
123
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
124
+ ]);
125
+ /** FIPS 180-4 SHA-256(只在没有 `crypto.subtle` 时用)。 */
126
+ export function sha256(message) {
127
+ const length = message.length;
128
+ const blocks = Math.ceil((length + 9) / 64);
129
+ const padded = new Uint8Array(blocks * 64);
130
+ padded.set(message);
131
+ padded[length] = 0x80;
132
+ const view = new DataView(padded.buffer);
133
+ view.setUint32(padded.length - 8, Math.floor(length / 0x20000000), false);
134
+ view.setUint32(padded.length - 4, (length * 8) >>> 0, false);
135
+ const hash = new Uint32Array([
136
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
137
+ ]);
138
+ const w = new Uint32Array(64);
139
+ const rotr = (value, bits) => (value >>> bits) | (value << (32 - bits));
140
+ for (let block = 0; block < blocks; block++) {
141
+ for (let index = 0; index < 16; index++)
142
+ w[index] = view.getUint32(block * 64 + index * 4, false);
143
+ for (let index = 16; index < 64; index++) {
144
+ const a = w[index - 15];
145
+ const b = w[index - 2];
146
+ const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);
147
+ const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);
148
+ w[index] = (w[index - 16] + s0 + w[index - 7] + s1) >>> 0;
149
+ }
150
+ let [a, b, c, d, e, f, g, h] = hash;
151
+ for (let index = 0; index < 64; index++) {
152
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
153
+ const choice = (e & f) ^ (~e & g);
154
+ const t1 = (h + s1 + choice + SHA256_K[index] + w[index]) >>> 0;
155
+ const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
156
+ const majority = (a & b) ^
157
+ (a & c) ^
158
+ (b & c);
159
+ const t2 = (s0 + majority) >>> 0;
160
+ h = g;
161
+ g = f;
162
+ f = e;
163
+ e = (d + t1) >>> 0;
164
+ d = c;
165
+ c = b;
166
+ b = a;
167
+ a = (t1 + t2) >>> 0;
168
+ }
169
+ hash[0] = (hash[0] + a) >>> 0;
170
+ hash[1] = (hash[1] + b) >>> 0;
171
+ hash[2] = (hash[2] + c) >>> 0;
172
+ hash[3] = (hash[3] + d) >>> 0;
173
+ hash[4] = (hash[4] + e) >>> 0;
174
+ hash[5] = (hash[5] + f) >>> 0;
175
+ hash[6] = (hash[6] + g) >>> 0;
176
+ hash[7] = (hash[7] + h) >>> 0;
177
+ }
178
+ const out = new Uint8Array(32);
179
+ const outView = new DataView(out.buffer);
180
+ for (let index = 0; index < 8; index++)
181
+ outView.setUint32(index * 4, hash[index], false);
182
+ return out;
183
+ }
184
+ function randomToken() {
185
+ const bytes = new Uint8Array(16);
186
+ crypto.getRandomValues(bytes);
187
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
188
+ }
189
+ const PROBE_TIMEOUT_MS = 1500;
190
+ const sandboxProbes = new WeakMap();
191
+ /**
192
+ * 宿主页面能不能运行 srcdoc 沙箱里按哈希放行的脚本:用一个只有一行 `postMessage` 的最小沙箱试一次。
193
+ * 只在握手失败、且沙箱文档已经加载完时调用,用来区分「宿主 CSP 挡住了沙箱」和组件自身的问题。
194
+ * 每个文档只试一次;探针 iframe 用完即删。
195
+ */
196
+ function probeSandboxScripts(ownerDocument) {
197
+ const cached = sandboxProbes.get(ownerDocument);
198
+ if (cached !== undefined)
199
+ return cached;
200
+ const pending = (async () => {
201
+ const view = ownerDocument.defaultView;
202
+ if (view === null)
203
+ return false;
204
+ const token = randomToken();
205
+ const script = escapeScript(`parent.postMessage({ type: 'bs-sandbox-probe', token: ${JSON.stringify(token)} }, '*');`);
206
+ const hash = await scriptHash(script);
207
+ return new Promise((resolve) => {
208
+ const iframe = ownerDocument.createElement('iframe');
209
+ iframe.setAttribute('sandbox', 'allow-scripts');
210
+ iframe.setAttribute('aria-hidden', 'true');
211
+ iframe.setAttribute('tabindex', '-1');
212
+ iframe.setAttribute('data-base-screen-isolated-probe', '');
213
+ iframe.style.cssText =
214
+ 'position:fixed;left:0;top:0;width:1px;height:1px;border:0;opacity:0;pointer-events:none';
215
+ let settled = false;
216
+ const finish = (ok) => {
217
+ if (settled)
218
+ return;
219
+ settled = true;
220
+ view.removeEventListener('message', onMessage);
221
+ clearTimeout(timer);
222
+ iframe.remove();
223
+ resolve(ok);
224
+ };
225
+ const onMessage = (event) => {
226
+ const data = event.data;
227
+ if (event.source === iframe.contentWindow &&
228
+ data !== null &&
229
+ typeof data === 'object' &&
230
+ data.type === 'bs-sandbox-probe' &&
231
+ data.token === token) {
232
+ finish(true);
233
+ }
234
+ };
235
+ view.addEventListener('message', onMessage);
236
+ const timer = setTimeout(() => finish(false), PROBE_TIMEOUT_MS);
237
+ iframe.srcdoc = [
238
+ '<!doctype html><html><head><meta charset="utf-8">',
239
+ `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src ${hash}">`,
240
+ `</head><body><script>${script}</script></body></html>`,
241
+ ].join('');
242
+ (ownerDocument.body ?? ownerDocument.documentElement).appendChild(iframe);
243
+ });
244
+ })();
245
+ sandboxProbes.set(ownerDocument, pending);
246
+ return pending;
247
+ }
248
+ /** 宿主文档里 `<meta http-equiv="Content-Security-Policy">` 的内容(响应头里的 CSP 读不到)。 */
249
+ function readHostMetaCsp(ownerDocument) {
250
+ const contents = [];
251
+ for (const meta of ownerDocument.querySelectorAll('meta[http-equiv]')) {
252
+ if (meta.getAttribute('http-equiv')?.trim().toLowerCase() !== 'content-security-policy')
253
+ continue;
254
+ const content = meta.getAttribute('content')?.trim();
255
+ if (content !== undefined && content !== '')
256
+ contents.push(content);
257
+ }
258
+ return contents.length === 0 ? undefined : contents.join(' | ');
259
+ }
260
+ const HOST_CSP_MESSAGE = '宿主页面的 CSP 挡住了沙箱脚本(srcdoc 沙箱会继承宿主页面的 CSP),需要改用带独立 CSP 的沙箱路由。';
261
+ const STARTUP_MESSAGE = '组件代码加载后一直没有结束(可能在顶层死循环或执行过久)。';
262
+ const HANDSHAKE_MESSAGE = '沙箱握手超时:沙箱脚本没有回应。';
263
+ const ROUTE_HANDSHAKE_MESSAGE = '沙箱握手超时:沙箱路由可能没有返回这份文档,或响应头里的 CSP 挡住了脚本。';
264
+ /**
265
+ * 一个包的代码与库 → 沙箱文档。文档对同一个包恒定(ADR-0118 D2:握手口令不进文档),只生成一次。
266
+ * 引导是第一段脚本:它最先读取并清空 `window.name` 里的口令,预置库与作者代码都在它之后运行。
267
+ */
268
+ class PackageBundle {
269
+ #source;
270
+ #libraries;
271
+ #config;
272
+ #document;
273
+ constructor(source, libraries, maxFps) {
274
+ this.#source = source;
275
+ this.#libraries = libraries;
276
+ this.#config = {
277
+ libraries: libraries.map((library) => [library.name, library.global]),
278
+ maxFps,
279
+ };
280
+ }
281
+ document() {
282
+ this.#document ??= this.#build();
283
+ return this.#document;
284
+ }
285
+ async #build() {
286
+ const classic = [
287
+ escapeScript(`(${String(baseScreenIsolatedRuntime)})(${JSON.stringify(this.#config)});`),
288
+ ...this.#libraries.map((library) => escapeScript(library.source)),
289
+ escapeScript(`globalThis.__bsFormat = (${String(formatBaseScreenMaterialNumber)});`),
290
+ ];
291
+ // 作者代码是模块:`export function create` 在模块作用域里也是本地绑定,末尾挂到全局给引导取用。
292
+ // 模块脚本在经典脚本之后、load 之前执行;握手发生在 load 之后,所以挂载时 create 已就绪。
293
+ const module = escapeScript(`${this.#source}\n;globalThis.__bsCreate = typeof create === 'function' ? create : undefined;\n`);
294
+ const scriptHashes = await Promise.all([...classic, module].map(scriptHash));
295
+ const html = [
296
+ '<!doctype html><html><head><meta charset="utf-8">',
297
+ `<meta http-equiv="Content-Security-Policy" content="${buildBaseScreenIsolatedMetaCsp(scriptHashes)}">`,
298
+ '<style>html,body{margin:0;overflow:hidden;background:transparent}</style>',
299
+ '</head><body>',
300
+ ...classic.map((script) => `<script>${script}</script>`),
301
+ `<script type="module">${module}</script>`,
302
+ '</body></html>',
303
+ ].join('');
304
+ const digest = await digestText(html);
305
+ const hash = Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('');
306
+ return { html, hash, scriptHashes };
307
+ }
308
+ }
309
+ function exactKeys(value, required, optional = []) {
310
+ const keys = Object.keys(value);
311
+ return (required.every((key) => keys.includes(key)) &&
312
+ keys.every((key) => required.includes(key) || optional.includes(key)));
313
+ }
314
+ const isShortText = (value, limit) => typeof value === 'string' && value.length <= limit;
315
+ function readInbound(input) {
316
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
317
+ return undefined;
318
+ const record = input;
319
+ if (record.type === 'bitmap') {
320
+ return exactKeys(record, ['type', 'id', 'bitmap']) &&
321
+ isShortText(record.id, 64) &&
322
+ record.bitmap instanceof ImageBitmap
323
+ ? { type: 'bitmap', id: record.id, bitmap: record.bitmap }
324
+ : undefined;
325
+ }
326
+ const parsed = parseScreenJsonValue(input, { maxBytes: MAX_MESSAGE_BYTES });
327
+ if (!parsed.ok ||
328
+ parsed.value === null ||
329
+ typeof parsed.value !== 'object' ||
330
+ Array.isArray(parsed.value)) {
331
+ return undefined;
332
+ }
333
+ const message = parsed.value;
334
+ switch (message.type) {
335
+ case 'ready':
336
+ return exactKeys(message, ['type']) ? { type: 'ready' } : undefined;
337
+ case 'tock':
338
+ return exactKeys(message, ['type', 'pending']) &&
339
+ Array.isArray(message.pending) &&
340
+ message.pending.length <= 1024 &&
341
+ message.pending.every((id) => isShortText(id, 64))
342
+ ? { type: 'tock', pending: message.pending }
343
+ : undefined;
344
+ case 'event':
345
+ return exactKeys(message, ['type', 'id', 'name', 'payload']) &&
346
+ isShortText(message.id, 64) &&
347
+ isShortText(message.name, 128)
348
+ ? {
349
+ type: 'event',
350
+ id: message.id,
351
+ name: message.name,
352
+ payload: message.payload,
353
+ }
354
+ : undefined;
355
+ case 'error':
356
+ return exactKeys(message, ['type', 'message'], ['id']) &&
357
+ isShortText(message.message, 200) &&
358
+ (message.id === undefined || isShortText(message.id, 64))
359
+ ? {
360
+ type: 'error',
361
+ message: message.message,
362
+ ...(message.id === undefined ? {} : { id: message.id }),
363
+ }
364
+ : undefined;
365
+ case 'csp':
366
+ return exactKeys(message, ['type', 'directive', 'uri']) &&
367
+ isShortText(message.directive, 64) &&
368
+ isShortText(message.uri, 200)
369
+ ? { type: 'csp', directive: message.directive, uri: message.uri }
370
+ : undefined;
371
+ default:
372
+ return undefined;
373
+ }
374
+ }
375
+ /** 沙箱路由返回的地址必须是 http(s):`about:` / `blob:` / `data:` 会继承宿主 CSP,`javascript:` 更不行。 */
376
+ function readSandboxUrl(input, ownerDocument) {
377
+ if (typeof input !== 'string' || input.trim() === '') {
378
+ throw new Error('沙箱路由没有返回地址。');
379
+ }
380
+ const url = new URL(input, ownerDocument.baseURI);
381
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
382
+ throw new Error(`沙箱路由返回的地址不是 http(s):${url.protocol}`);
383
+ }
384
+ return url;
385
+ }
386
+ /** CSP 违规事件里被拦的地址是不是这个沙箱路由(比较来源与路径;跨源时浏览器可能只给来源)。 */
387
+ function isSandboxTarget(blockedURI, target) {
388
+ try {
389
+ const blocked = new URL(blockedURI);
390
+ return (blocked.origin === target.origin &&
391
+ (blocked.pathname === target.pathname || blocked.pathname === '/'));
392
+ }
393
+ catch {
394
+ return false;
395
+ }
396
+ }
397
+ class PackagePool {
398
+ #config;
399
+ #document;
400
+ #members = new Map();
401
+ #needsFrame = new Set();
402
+ #queue = [];
403
+ #iframe;
404
+ #port;
405
+ #ready = false;
406
+ #failed;
407
+ #tickSentAt;
408
+ #handshakeTimer;
409
+ #recycleTimer;
410
+ #lastDprCheck = 0;
411
+ #lastFrame = 0;
412
+ /** 沙箱文档的 load 事件是否已到(作者模块顶层卡住时 load 不会到)。 */
413
+ #loaded = false;
414
+ /** 网络导航模式(ADR-0118)的沙箱地址;srcdoc 模式为 undefined。 */
415
+ #sandboxUrl;
416
+ #stopWatchingFrames;
417
+ #protocolViolations = 0;
418
+ #release;
419
+ constructor(config, ownerDocument, release) {
420
+ this.#config = config;
421
+ this.#document = ownerDocument;
422
+ this.#release = release;
423
+ void this.#open();
424
+ }
425
+ get failed() {
426
+ return this.#failed;
427
+ }
428
+ async #open() {
429
+ const token = randomToken();
430
+ let sandboxDocument;
431
+ try {
432
+ sandboxDocument = await this.#config.bundle.document();
433
+ }
434
+ catch (error) {
435
+ this.fail(`沙箱文档生成失败:${String(error?.message ?? error)}`);
436
+ return;
437
+ }
438
+ if (this.#failed !== undefined)
439
+ return;
440
+ const sandbox = this.#config.sandbox;
441
+ if (sandbox !== undefined) {
442
+ try {
443
+ this.#sandboxUrl = readSandboxUrl(await sandbox.resolve(sandboxDocument), this.#document);
444
+ }
445
+ catch (error) {
446
+ this.fail(`沙箱文档没能交给宿主的沙箱路由:${String(error?.message ?? error)}`.slice(0, 200), 'sandbox-route');
447
+ return;
448
+ }
449
+ if (this.#failed !== undefined)
450
+ return;
451
+ }
452
+ const iframe = this.#document.createElement('iframe');
453
+ iframe.setAttribute('sandbox', 'allow-scripts');
454
+ iframe.setAttribute('referrerpolicy', 'no-referrer');
455
+ iframe.setAttribute('aria-hidden', 'true');
456
+ iframe.setAttribute('tabindex', '-1');
457
+ iframe.setAttribute('data-base-screen-isolated-package', this.#config.tagName);
458
+ // 留在视口内、不可见:display:none / visibility:hidden 的跨源 iframe 会被节流。
459
+ iframe.style.cssText =
460
+ 'position:fixed;left:0;top:0;width:1px;height:1px;border:0;opacity:0;pointer-events:none';
461
+ // 口令走 name 属性(ADR-0118 D2):要在挂进文档、创建浏览上下文之前设好。
462
+ iframe.name = token;
463
+ if (this.#sandboxUrl !== undefined) {
464
+ this.#watchFrameViolations(this.#sandboxUrl);
465
+ iframe.src = this.#sandboxUrl.href;
466
+ }
467
+ else {
468
+ iframe.srcdoc = sandboxDocument.html;
469
+ }
470
+ iframe.addEventListener('load', () => {
471
+ this.#loaded = true;
472
+ this.#connect(token);
473
+ }, { once: true });
474
+ this.#iframe = iframe;
475
+ (this.#document.body ?? this.#document.documentElement).appendChild(iframe);
476
+ this.#handshakeTimer = setTimeout(() => {
477
+ if (!this.#ready)
478
+ void this.#diagnoseHandshake();
479
+ }, HANDSHAKE_TIMEOUT_MS);
480
+ }
481
+ /**
482
+ * 握手超时的诊断(ADR-0117 §9.8):
483
+ * - 文档没加载完 → 组件代码或预置库在加载阶段没有结束;
484
+ * - 加载完了 → 用最小探针沙箱试一次:探针也跑不起来就是宿主页面的 CSP 挡住了(srcdoc 继承);
485
+ * 探针能跑就是引导本身没有回应。
486
+ * 判断依据只靠 load 事件与探针,不读宿主的响应头(读不到);`<meta>` CSP 有的话一并记进审计。
487
+ */
488
+ async #diagnoseHandshake() {
489
+ if (!this.#loaded) {
490
+ this.fail(STARTUP_MESSAGE, 'startup');
491
+ return;
492
+ }
493
+ if (this.#sandboxUrl !== undefined) {
494
+ // 网络导航模式:宿主 CSP 挡 frame-src 的情况由违规监听当场判定;走到这里就是路由本身的问题。
495
+ // 不跑 srcdoc 探针:宿主带 CSP 时探针必然失败,那不是这条路径的故障原因。
496
+ this.fail(ROUTE_HANDSHAKE_MESSAGE, 'handshake', ` 沙箱地址:${this.#sandboxUrl.href.slice(0, 160)}`);
497
+ return;
498
+ }
499
+ const scriptsRun = await probeSandboxScripts(this.#document);
500
+ if (this.#ready || this.#failed !== undefined)
501
+ return;
502
+ if (scriptsRun) {
503
+ this.fail(HANDSHAKE_MESSAGE, 'handshake');
504
+ return;
505
+ }
506
+ const meta = readHostMetaCsp(this.#document);
507
+ this.fail(HOST_CSP_MESSAGE, 'host-csp', meta === undefined
508
+ ? '宿主页面没有 <meta> CSP,挡住沙箱的 CSP 多半在 HTTP 响应头里。'
509
+ : `宿主页面的 <meta> CSP:${meta.slice(0, 200)}`);
510
+ }
511
+ /**
512
+ * 握手完成前监听宿主文档的 `frame-src` 违规(ADR-0118 §3.6):被拦的正是这个沙箱地址,就是宿主页面
513
+ * 的 CSP 没有放行沙箱路由,当场熔断并写明要放行的来源,不必等握手超时。
514
+ */
515
+ #watchFrameViolations(target) {
516
+ const listener = (event) => {
517
+ if (this.#ready || this.#failed !== undefined)
518
+ return;
519
+ const directive = event.effectiveDirective;
520
+ if (directive !== 'frame-src' && directive !== 'child-src' && directive !== 'default-src')
521
+ return;
522
+ if (!isSandboxTarget(event.blockedURI, target))
523
+ return;
524
+ this.fail(`宿主页面的 CSP 没有放行沙箱路由(${directive}),需要在宿主 CSP 的 frame-src 里放行 ${target.origin}。`, 'host-csp', ` 被拦地址:${String(event.blockedURI).slice(0, 160)}`);
525
+ };
526
+ this.#document.addEventListener('securitypolicyviolation', listener);
527
+ this.#stopWatchingFrames = () => this.#document.removeEventListener('securitypolicyviolation', listener);
528
+ }
529
+ #connect(token) {
530
+ const target = this.#iframe?.contentWindow;
531
+ if (target === null || target === undefined || this.#failed !== undefined)
532
+ return;
533
+ const channel = new MessageChannel();
534
+ this.#port = channel.port1;
535
+ this.#port.onmessage = (event) => this.#receive(event.data);
536
+ // 不透明源只能用 '*' 投递;身份靠口令 + 只认父窗口,之后全走私有端口。
537
+ target.postMessage({ type: 'bs-connect', token }, '*', [channel.port2]);
538
+ }
539
+ #audit(kind, message, componentId, cause) {
540
+ this.#config.onAudit?.({
541
+ kind,
542
+ tagName: this.#config.tagName,
543
+ message,
544
+ ...(componentId === undefined ? {} : { componentId }),
545
+ ...(cause === undefined ? {} : { cause }),
546
+ });
547
+ }
548
+ #receive(input) {
549
+ if (this.#failed !== undefined)
550
+ return;
551
+ const message = readInbound(input);
552
+ if (message === undefined) {
553
+ if (input !== null &&
554
+ typeof input === 'object' &&
555
+ input.bitmap instanceof ImageBitmap) {
556
+ input.bitmap.close();
557
+ }
558
+ this.#protocolViolations += 1;
559
+ this.#audit('protocol', '沙箱消息格式不合法,已丢弃。');
560
+ if (this.#protocolViolations > MAX_PROTOCOL_VIOLATIONS)
561
+ this.fail('沙箱消息格式反复不合法。', 'protocol');
562
+ return;
563
+ }
564
+ switch (message.type) {
565
+ case 'ready':
566
+ if (this.#ready)
567
+ return;
568
+ this.#ready = true;
569
+ if (this.#handshakeTimer !== undefined)
570
+ clearTimeout(this.#handshakeTimer);
571
+ this.#stopWatchingFrames?.();
572
+ this.#stopWatchingFrames = undefined;
573
+ for (const [queued, transfer] of this.#queue.splice(0))
574
+ this.#port?.postMessage(queued, transfer);
575
+ hostClock(this.#document).add(this);
576
+ return;
577
+ case 'tock':
578
+ this.#tickSentAt = undefined;
579
+ for (const id of message.pending)
580
+ if (this.#members.has(id))
581
+ this.#needsFrame.add(id);
582
+ return;
583
+ case 'bitmap': {
584
+ const member = this.#members.get(message.id);
585
+ if (member === undefined)
586
+ message.bitmap.close();
587
+ else
588
+ member.receiveBitmap(message.bitmap);
589
+ return;
590
+ }
591
+ case 'event':
592
+ this.#members.get(message.id)?.dispatchMaterialEvent(message.name, message.payload);
593
+ return;
594
+ case 'error': {
595
+ const member = message.id === undefined ? undefined : this.#members.get(message.id);
596
+ this.#audit('error', message.message, member?.componentId);
597
+ member?.receiveError(message.message);
598
+ return;
599
+ }
600
+ case 'csp':
601
+ this.#audit('csp', `${message.directive} ${message.uri}`);
602
+ return;
603
+ }
604
+ }
605
+ post(message, transfer = []) {
606
+ if (this.#failed !== undefined)
607
+ return;
608
+ if (this.#ready && this.#port !== undefined)
609
+ this.#port.postMessage(message, transfer);
610
+ else
611
+ this.#queue.push([message, transfer]);
612
+ }
613
+ join(member, state) {
614
+ if (this.#recycleTimer !== undefined) {
615
+ clearTimeout(this.#recycleTimer);
616
+ this.#recycleTimer = undefined;
617
+ }
618
+ if (this.#failed !== undefined) {
619
+ member.shutdown(this.#failed);
620
+ return;
621
+ }
622
+ this.#members.set(member.instanceId, member);
623
+ this.#needsFrame.add(member.instanceId);
624
+ this.post({ type: 'mount', id: member.instanceId, state });
625
+ }
626
+ update(member, state) {
627
+ if (!this.#members.has(member.instanceId))
628
+ return;
629
+ this.#needsFrame.add(member.instanceId);
630
+ this.post({ type: 'update', id: member.instanceId, state });
631
+ }
632
+ leave(member) {
633
+ if (!this.#members.delete(member.instanceId))
634
+ return;
635
+ this.#needsFrame.delete(member.instanceId);
636
+ this.post({ type: 'unmount', id: member.instanceId });
637
+ if (this.#members.size === 0) {
638
+ this.#recycleTimer = setTimeout(() => {
639
+ if (this.#members.size === 0)
640
+ this.dispose();
641
+ }, RECYCLE_DELAY_MS);
642
+ }
643
+ }
644
+ /** 宿主时钟回调:一个包一条 tick;上一条还没回 tock 时不再发(自然背压),并检查卡死。 */
645
+ tick(now) {
646
+ if (!this.#ready || this.#failed !== undefined)
647
+ return;
648
+ const wall = performance.now();
649
+ // 页面在后台时 rAF 停了:回到前台的第一帧重新起算等待时间,不误判卡死。
650
+ const resumed = this.#lastFrame !== 0 && now - this.#lastFrame > 500;
651
+ this.#lastFrame = now;
652
+ if (this.#tickSentAt !== undefined) {
653
+ if (resumed)
654
+ this.#tickSentAt = wall;
655
+ else if (wall - this.#tickSentAt > STALL_TIMEOUT_MS)
656
+ this.fail('组件代码长时间没有响应(疑似死循环)。', 'stall');
657
+ return;
658
+ }
659
+ if (wall - this.#lastDprCheck > DPR_RECHECK_MS) {
660
+ this.#lastDprCheck = wall;
661
+ for (const member of this.#members.values()) {
662
+ const next = member.recheckDpr();
663
+ if (next !== undefined)
664
+ this.update(member, next);
665
+ }
666
+ }
667
+ const ids = [];
668
+ for (const member of this.#members.values()) {
669
+ if (member.continuous() || this.#needsFrame.has(member.instanceId))
670
+ ids.push(member.instanceId);
671
+ }
672
+ this.#needsFrame.clear();
673
+ if (ids.length === 0)
674
+ return;
675
+ this.#tickSentAt = wall;
676
+ this.#port?.postMessage({ type: 'tick', now, ids });
677
+ }
678
+ /**
679
+ * 熔断:整个包的实例换成错误视图。`reason` 是给作者看的短句(进错误视图);`detail` 只进审计记录。
680
+ */
681
+ fail(reason, cause, detail) {
682
+ if (this.#failed !== undefined)
683
+ return;
684
+ this.#failed = reason;
685
+ this.#audit('circuit', detail === undefined ? reason : `${reason}${detail}`, undefined, cause);
686
+ for (const member of this.#members.values())
687
+ member.shutdown(reason);
688
+ this.#teardown();
689
+ }
690
+ dispose() {
691
+ this.#teardown();
692
+ this.#release();
693
+ }
694
+ #teardown() {
695
+ hostClock(this.#document).delete(this);
696
+ this.#stopWatchingFrames?.();
697
+ this.#stopWatchingFrames = undefined;
698
+ if (this.#handshakeTimer !== undefined)
699
+ clearTimeout(this.#handshakeTimer);
700
+ if (this.#recycleTimer !== undefined)
701
+ clearTimeout(this.#recycleTimer);
702
+ this.#port?.close();
703
+ this.#port = undefined;
704
+ this.#iframe?.remove();
705
+ this.#iframe = undefined;
706
+ this.#queue.length = 0;
707
+ }
708
+ }
709
+ const clocks = new WeakMap();
710
+ /** 每个文档一个 rAF 循环,给所有就绪的包下发 tick;没有包时停下。 */
711
+ function hostClock(ownerDocument) {
712
+ const existing = clocks.get(ownerDocument);
713
+ if (existing !== undefined)
714
+ return existing;
715
+ const pools = new Set();
716
+ const view = ownerDocument.defaultView;
717
+ let running = false;
718
+ const loop = (now) => {
719
+ if (pools.size === 0) {
720
+ running = false;
721
+ return;
722
+ }
723
+ for (const pool of pools)
724
+ pool.tick(now);
725
+ view?.requestAnimationFrame(loop);
726
+ };
727
+ const clock = {
728
+ add(pool) {
729
+ pools.add(pool);
730
+ if (!running && view !== null) {
731
+ running = true;
732
+ view.requestAnimationFrame(loop);
733
+ }
734
+ },
735
+ delete(pool) {
736
+ pools.delete(pool);
737
+ },
738
+ };
739
+ clocks.set(ownerDocument, clock);
740
+ return clock;
741
+ }
742
+ const poolsByDocument = new WeakMap();
743
+ function poolFor(config, ownerDocument) {
744
+ let pools = poolsByDocument.get(ownerDocument);
745
+ if (pools === undefined) {
746
+ pools = new Map();
747
+ poolsByDocument.set(ownerDocument, pools);
748
+ }
749
+ const existing = pools.get(config.tagName);
750
+ if (existing !== undefined)
751
+ return existing;
752
+ const created = new PackagePool(config, ownerDocument, () => {
753
+ if (pools.get(config.tagName) === created)
754
+ pools.delete(config.tagName);
755
+ });
756
+ pools.set(config.tagName, created);
757
+ return created;
758
+ }
759
+ // ---------------------------------------------------------------------------
760
+ // 外层物料元素
761
+ let instanceCounter = 0;
762
+ function createIsolatedMaterialElement(config) {
763
+ const ElementBase = globalThis.HTMLElement ??
764
+ class {
765
+ };
766
+ const events = new Set(config.manifest.events);
767
+ class IsolatedMaterialElement extends ElementBase {
768
+ instanceId = `i${++instanceCounter}`;
769
+ #model;
770
+ #pool;
771
+ #frame;
772
+ #canvas;
773
+ #bitmapContext = null;
774
+ #state;
775
+ #hasFrame = false;
776
+ #visible = true;
777
+ #observer;
778
+ #consecutiveErrors = 0;
779
+ #eventWindow = 0;
780
+ #eventCount = 0;
781
+ #shutdown;
782
+ #reducedMotion;
783
+ get componentId() {
784
+ return this.#model?.componentId ?? '';
785
+ }
786
+ get model() {
787
+ if (this.#model === undefined)
788
+ throw new Error('Material model has not been set.');
789
+ return this.#model;
790
+ }
791
+ set model(value) {
792
+ this.#model = value;
793
+ this.setAttribute('data-base-screen-data-state', value.dataState.status);
794
+ this.#sync();
795
+ }
796
+ connectedCallback() {
797
+ if (typeof IntersectionObserver === 'function' && this.#observer === undefined) {
798
+ this.#observer = new IntersectionObserver((entries) => {
799
+ const entry = entries[entries.length - 1];
800
+ if (entry !== undefined)
801
+ this.#visible = entry.isIntersecting;
802
+ });
803
+ this.#observer.observe(this);
804
+ }
805
+ this.#sync();
806
+ }
807
+ disconnectedCallback() {
808
+ this.#observer?.disconnect();
809
+ this.#observer = undefined;
810
+ this.#pool?.leave(this);
811
+ this.#pool = undefined;
812
+ this.#state = undefined;
813
+ this.#hasFrame = false;
814
+ }
815
+ #ensureFrame() {
816
+ if (this.#frame !== undefined)
817
+ return this.#frame;
818
+ const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
819
+ const sheet = this.ownerDocument.createElement('style');
820
+ sheet.textContent = STYLE;
821
+ const frame = this.ownerDocument.createElement('div');
822
+ frame.className = 'frame';
823
+ frame.setAttribute('part', 'frame');
824
+ root.replaceChildren(sheet, frame);
825
+ this.#frame = frame;
826
+ return frame;
827
+ }
828
+ #show(view) {
829
+ this.#ensureFrame().replaceChildren(...(view === undefined ? [] : [view]));
830
+ }
831
+ #ensureCanvas() {
832
+ if (this.#canvas !== undefined)
833
+ return this.#canvas;
834
+ const canvas = this.ownerDocument.createElement('canvas');
835
+ canvas.setAttribute('role', 'img');
836
+ canvas.setAttribute('aria-label', config.manifest.name);
837
+ canvas.addEventListener('click', (event) => {
838
+ const model = this.#model;
839
+ if (model === undefined || model.mode === 'design' || !model.interactive)
840
+ return;
841
+ this.#pool?.post({
842
+ type: 'pointer',
843
+ id: this.instanceId,
844
+ x: event.offsetX,
845
+ y: event.offsetY,
846
+ });
847
+ });
848
+ this.#bitmapContext = canvas.getContext('bitmaprenderer');
849
+ this.#canvas = canvas;
850
+ return canvas;
851
+ }
852
+ #dpr(model) {
853
+ const box = this.getBoundingClientRect();
854
+ const scale = box.width > 0 && model.size.width > 0
855
+ ? Math.max(box.width / model.size.width, box.height / Math.max(1, model.size.height))
856
+ : 1;
857
+ const ratio = (this.ownerDocument.defaultView?.devicePixelRatio ?? 1) * scale;
858
+ return Math.round(Math.min(3, Math.max(0.5, ratio)) * 100) / 100;
859
+ }
860
+ #nextState(model, value) {
861
+ const normalized = normalizeBaseScreenMaterialSpecValue(config.data, value);
862
+ const previous = this.#state;
863
+ // 尺寸没变就沿用上次的像素比(缩放变化由时钟每 500 ms 复查),避免每次写 model 都读布局。
864
+ const dpr = previous !== undefined &&
865
+ previous.w === model.size.width &&
866
+ previous.h === model.size.height
867
+ ? previous.dpr
868
+ : this.#dpr(model);
869
+ return {
870
+ w: model.size.width,
871
+ h: model.size.height,
872
+ dpr,
873
+ props: model.props,
874
+ style: model.style,
875
+ mode: model.mode,
876
+ value: normalized.value,
877
+ rows: normalized.rows,
878
+ interactive: model.interactive,
879
+ };
880
+ }
881
+ #sync() {
882
+ const model = this.#model;
883
+ if (model === undefined || !this.isConnected)
884
+ return;
885
+ this.#ensureFrame();
886
+ if (this.#shutdown !== undefined)
887
+ return;
888
+ const status = model.dataState.status;
889
+ // 四态与 presenter 一致:已有画面时加载与 idle 保持原画面,出错必须让作者看见。
890
+ if (config.data.kind !== 'none' && status !== 'ready') {
891
+ if (this.#hasFrame && status !== 'error')
892
+ return;
893
+ this.#hasFrame = false;
894
+ this.#show(createBaseScreenMaterialStateView(this.ownerDocument, model.dataState));
895
+ return;
896
+ }
897
+ const value = model.dataState.status === 'ready' ? model.dataState.value : undefined;
898
+ const state = this.#nextState(model, value);
899
+ if (config.data.kind === 'rows' && state.rows.length === 0) {
900
+ this.#hasFrame = false;
901
+ this.#show(createBaseScreenMaterialEmptyView(this.ownerDocument));
902
+ return;
903
+ }
904
+ if (!this.#hasFrame)
905
+ this.#show(createBaseScreenMaterialStateView(this.ownerDocument, { status: 'loading' }));
906
+ const first = this.#state === undefined;
907
+ this.#state = state;
908
+ if (first) {
909
+ this.#pool = poolFor(config, this.ownerDocument);
910
+ this.#pool.join(this, state);
911
+ }
912
+ else {
913
+ this.#pool?.update(this, state);
914
+ }
915
+ }
916
+ continuous() {
917
+ const model = this.#model;
918
+ if (model === undefined || model.mode === 'design' || !this.#visible)
919
+ return false;
920
+ if (this.#reducedMotion === undefined) {
921
+ this.#reducedMotion =
922
+ this.ownerDocument.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)') ?? null;
923
+ }
924
+ return this.#reducedMotion?.matches !== true;
925
+ }
926
+ recheckDpr() {
927
+ const model = this.#model;
928
+ const state = this.#state;
929
+ if (model === undefined || state === undefined)
930
+ return undefined;
931
+ const dpr = this.#dpr(model);
932
+ if (Math.abs(dpr - state.dpr) / state.dpr < 0.1)
933
+ return undefined;
934
+ this.#state = { ...state, dpr };
935
+ return this.#state;
936
+ }
937
+ receiveBitmap(bitmap) {
938
+ const state = this.#state;
939
+ // 位图不能比声明的画布大太多。画布被缩小到 dpr < 1 时,库仍可能按 canonical 1×
940
+ // 渲染;下限按 1 算,既不放宽 3× 上限,也不会误杀合法的 1× 画面。
941
+ const pixelRatio = Math.max(1, state?.dpr ?? 1);
942
+ const limitW = Math.ceil((state?.w ?? 0) * pixelRatio * 1.1) + 2;
943
+ const limitH = Math.ceil((state?.h ?? 0) * pixelRatio * 1.1) + 2;
944
+ if (state === undefined ||
945
+ this.#shutdown !== undefined ||
946
+ bitmap.width > limitW ||
947
+ bitmap.height > limitH) {
948
+ bitmap.close();
949
+ return;
950
+ }
951
+ const canvas = this.#ensureCanvas();
952
+ if (canvas.width !== bitmap.width)
953
+ canvas.width = bitmap.width;
954
+ if (canvas.height !== bitmap.height)
955
+ canvas.height = bitmap.height;
956
+ this.#bitmapContext?.transferFromImageBitmap(bitmap);
957
+ this.#consecutiveErrors = 0;
958
+ if (!this.#hasFrame || this.#frame?.firstChild !== canvas)
959
+ this.#show(canvas);
960
+ this.#hasFrame = true;
961
+ config.onFrame?.(this.componentId);
962
+ }
963
+ receiveError(message) {
964
+ this.#consecutiveErrors += 1;
965
+ if (this.#consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
966
+ this.#pool?.fail(`组件代码连续出错:${message}`, 'errors');
967
+ return;
968
+ }
969
+ this.#hasFrame = false;
970
+ this.#show(createBaseScreenMaterialErrorView(this.ownerDocument, 'HOST_DATASET_INVALID', `组件渲染失败:${message}`.slice(0, 160)));
971
+ }
972
+ dispatchMaterialEvent(name, payload) {
973
+ if (!events.has(name)) {
974
+ config.onAudit?.({
975
+ kind: 'protocol',
976
+ tagName: config.tagName,
977
+ componentId: this.componentId,
978
+ message: `事件 ${name} 不在组件声明里,已丢弃。`,
979
+ });
980
+ return;
981
+ }
982
+ const now = performance.now();
983
+ if (now - this.#eventWindow >= 1000) {
984
+ this.#eventWindow = now;
985
+ this.#eventCount = 0;
986
+ }
987
+ this.#eventCount += 1;
988
+ if (this.#eventCount > MAX_EVENTS_PER_SECOND) {
989
+ if (this.#eventCount === MAX_EVENTS_PER_SECOND + 1) {
990
+ config.onAudit?.({
991
+ kind: 'rate',
992
+ tagName: config.tagName,
993
+ componentId: this.componentId,
994
+ message: `事件超过每秒 ${MAX_EVENTS_PER_SECOND} 条,多余的已丢弃。`,
995
+ });
996
+ }
997
+ return;
998
+ }
999
+ this.dispatchEvent(new CustomEvent(BASE_SCREEN_MATERIAL_EVENT, {
1000
+ bubbles: true,
1001
+ composed: true,
1002
+ detail: { name, payload },
1003
+ }));
1004
+ }
1005
+ shutdown(message) {
1006
+ this.#shutdown = message;
1007
+ this.#hasFrame = false;
1008
+ if (!this.isConnected)
1009
+ return;
1010
+ this.#show(createBaseScreenMaterialErrorView(this.ownerDocument, 'HOST_DATASET_INVALID', `组件已停用:${message}`.slice(0, 160)));
1011
+ }
1012
+ }
1013
+ // configurable:宿主「仅更新清单」需要把新 Manifest 挂回同一个构造器(ADR-0090 兼容矩阵)。
1014
+ Object.defineProperty(IsolatedMaterialElement, 'manifest', {
1015
+ value: config.manifest,
1016
+ configurable: true,
1017
+ });
1018
+ const adapter = createBaseScreenMaterialSpecDataAdapter(config.data);
1019
+ if (adapter !== undefined) {
1020
+ Object.defineProperty(IsolatedMaterialElement, 'tabularDataAdapter', { value: adapter });
1021
+ }
1022
+ return IsolatedMaterialElement;
1023
+ }
1024
+ //# sourceMappingURL=material-isolated.js.map