@ahoo-wang/wow-view-engine 9.2.0-rc.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 (1421) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1182 -0
  3. package/README.zh-CN.md +1171 -0
  4. package/THIRD_PARTY_NOTICES.md +196 -0
  5. package/dist/actions-DK1yfiI8.js +9986 -0
  6. package/dist/actions-DK1yfiI8.js.map +1 -0
  7. package/dist/analysis/boxplot.d.ts +80 -0
  8. package/dist/analysis/boxplot.d.ts.map +1 -0
  9. package/dist/analysis/bucketChange.d.ts +25 -0
  10. package/dist/analysis/bucketChange.d.ts.map +1 -0
  11. package/dist/analysis/budget.d.ts +37 -0
  12. package/dist/analysis/budget.d.ts.map +1 -0
  13. package/dist/analysis/candidates.d.ts +96 -0
  14. package/dist/analysis/candidates.d.ts.map +1 -0
  15. package/dist/analysis/candlestick.d.ts +73 -0
  16. package/dist/analysis/candlestick.d.ts.map +1 -0
  17. package/dist/analysis/capability.d.ts +129 -0
  18. package/dist/analysis/capability.d.ts.map +1 -0
  19. package/dist/analysis/cartesian.d.ts +102 -0
  20. package/dist/analysis/cartesian.d.ts.map +1 -0
  21. package/dist/analysis/chart.d.ts +108 -0
  22. package/dist/analysis/chart.d.ts.map +1 -0
  23. package/dist/analysis/chartFamilies.d.ts +175 -0
  24. package/dist/analysis/chartFamilies.d.ts.map +1 -0
  25. package/dist/analysis/chartOptions.d.ts +113 -0
  26. package/dist/analysis/chartOptions.d.ts.map +1 -0
  27. package/dist/analysis/chartRefs.d.ts +31 -0
  28. package/dist/analysis/chartRefs.d.ts.map +1 -0
  29. package/dist/analysis/chartRows.d.ts +39 -0
  30. package/dist/analysis/chartRows.d.ts.map +1 -0
  31. package/dist/analysis/chartSlots.d.ts +73 -0
  32. package/dist/analysis/chartSlots.d.ts.map +1 -0
  33. package/dist/analysis/chartSwitch.d.ts +34 -0
  34. package/dist/analysis/chartSwitch.d.ts.map +1 -0
  35. package/dist/analysis/compile.d.ts +55 -0
  36. package/dist/analysis/compile.d.ts.map +1 -0
  37. package/dist/analysis/currency.d.ts +68 -0
  38. package/dist/analysis/currency.d.ts.map +1 -0
  39. package/dist/analysis/dangling.d.ts +52 -0
  40. package/dist/analysis/dangling.d.ts.map +1 -0
  41. package/dist/analysis/defaults.d.ts +168 -0
  42. package/dist/analysis/defaults.d.ts.map +1 -0
  43. package/dist/analysis/derived.d.ts +81 -0
  44. package/dist/analysis/derived.d.ts.map +1 -0
  45. package/dist/analysis/drill.d.ts +142 -0
  46. package/dist/analysis/drill.d.ts.map +1 -0
  47. package/dist/analysis/drillFilter.d.ts +34 -0
  48. package/dist/analysis/drillFilter.d.ts.map +1 -0
  49. package/dist/analysis/expand.d.ts +51 -0
  50. package/dist/analysis/expand.d.ts.map +1 -0
  51. package/dist/analysis/expressions.d.ts +12 -0
  52. package/dist/analysis/expressions.d.ts.map +1 -0
  53. package/dist/analysis/fitCharts.d.ts +93 -0
  54. package/dist/analysis/fitCharts.d.ts.map +1 -0
  55. package/dist/analysis/formula.d.ts +65 -0
  56. package/dist/analysis/formula.d.ts.map +1 -0
  57. package/dist/analysis/funnel.d.ts +48 -0
  58. package/dist/analysis/funnel.d.ts.map +1 -0
  59. package/dist/analysis/gauge.d.ts +34 -0
  60. package/dist/analysis/gauge.d.ts.map +1 -0
  61. package/dist/analysis/granularity.d.ts +22 -0
  62. package/dist/analysis/granularity.d.ts.map +1 -0
  63. package/dist/analysis/having.d.ts +38 -0
  64. package/dist/analysis/having.d.ts.map +1 -0
  65. package/dist/analysis/hierarchy.d.ts +73 -0
  66. package/dist/analysis/hierarchy.d.ts.map +1 -0
  67. package/dist/analysis/index.d.ts +29 -0
  68. package/dist/analysis/index.d.ts.map +1 -0
  69. package/dist/analysis/logScale.d.ts +20 -0
  70. package/dist/analysis/logScale.d.ts.map +1 -0
  71. package/dist/analysis/map.d.ts +28 -0
  72. package/dist/analysis/map.d.ts.map +1 -0
  73. package/dist/analysis/metricCard.d.ts +155 -0
  74. package/dist/analysis/metricCard.d.ts.map +1 -0
  75. package/dist/analysis/metricCondition.d.ts +41 -0
  76. package/dist/analysis/metricCondition.d.ts.map +1 -0
  77. package/dist/analysis/metricFormat.d.ts +136 -0
  78. package/dist/analysis/metricFormat.d.ts.map +1 -0
  79. package/dist/analysis/metricOrder.d.ts +47 -0
  80. package/dist/analysis/metricOrder.d.ts.map +1 -0
  81. package/dist/analysis/metricWindow.d.ts +28 -0
  82. package/dist/analysis/metricWindow.d.ts.map +1 -0
  83. package/dist/analysis/profiles.d.ts +53 -0
  84. package/dist/analysis/profiles.d.ts.map +1 -0
  85. package/dist/analysis/project.d.ts +242 -0
  86. package/dist/analysis/project.d.ts.map +1 -0
  87. package/dist/analysis/queryFilter.d.ts +32 -0
  88. package/dist/analysis/queryFilter.d.ts.map +1 -0
  89. package/dist/analysis/references.d.ts +41 -0
  90. package/dist/analysis/references.d.ts.map +1 -0
  91. package/dist/analysis/splitOther.d.ts +80 -0
  92. package/dist/analysis/splitOther.d.ts.map +1 -0
  93. package/dist/analysis/timeAxis.d.ts +173 -0
  94. package/dist/analysis/timeAxis.d.ts.map +1 -0
  95. package/dist/analysis/timeCharts.d.ts +76 -0
  96. package/dist/analysis/timeCharts.d.ts.map +1 -0
  97. package/dist/analysis/treemap.d.ts +36 -0
  98. package/dist/analysis/treemap.d.ts.map +1 -0
  99. package/dist/analysis/validate.d.ts +19 -0
  100. package/dist/analysis/validate.d.ts.map +1 -0
  101. package/dist/analysis/validateAliases.d.ts +16 -0
  102. package/dist/analysis/validateAliases.d.ts.map +1 -0
  103. package/dist/analysis/validateChart.d.ts +60 -0
  104. package/dist/analysis/validateChart.d.ts.map +1 -0
  105. package/dist/analysis/validateElements.d.ts +20 -0
  106. package/dist/analysis/validateElements.d.ts.map +1 -0
  107. package/dist/analysis/validateGroups.d.ts +5 -0
  108. package/dist/analysis/validateGroups.d.ts.map +1 -0
  109. package/dist/analysis/validateHaving.d.ts +9 -0
  110. package/dist/analysis/validateHaving.d.ts.map +1 -0
  111. package/dist/analysis/validateLevels.d.ts +33 -0
  112. package/dist/analysis/validateLevels.d.ts.map +1 -0
  113. package/dist/analysis/validateLimits.d.ts +3 -0
  114. package/dist/analysis/validateLimits.d.ts.map +1 -0
  115. package/dist/analysis/validateMetrics.d.ts +5 -0
  116. package/dist/analysis/validateMetrics.d.ts.map +1 -0
  117. package/dist/analysis/validateOffers.d.ts +12 -0
  118. package/dist/analysis/validateOffers.d.ts.map +1 -0
  119. package/dist/analysis/validateReferences.d.ts +16 -0
  120. package/dist/analysis/validateReferences.d.ts.map +1 -0
  121. package/dist/analysis/validateShape.d.ts +14 -0
  122. package/dist/analysis/validateShape.d.ts.map +1 -0
  123. package/dist/analysis/validateSort.d.ts +3 -0
  124. package/dist/analysis/validateSort.d.ts.map +1 -0
  125. package/dist/analysis/waterfall.d.ts +33 -0
  126. package/dist/analysis/waterfall.d.ts.map +1 -0
  127. package/dist/capabilities/aliases.d.ts +36 -0
  128. package/dist/capabilities/aliases.d.ts.map +1 -0
  129. package/dist/capabilities/analysis.d.ts +19 -0
  130. package/dist/capabilities/analysis.d.ts.map +1 -0
  131. package/dist/capabilities/cache.d.ts +69 -0
  132. package/dist/capabilities/cache.d.ts.map +1 -0
  133. package/dist/capabilities/fields.d.ts +50 -0
  134. package/dist/capabilities/fields.d.ts.map +1 -0
  135. package/dist/capabilities/index.d.ts +13 -0
  136. package/dist/capabilities/index.d.ts.map +1 -0
  137. package/dist/capabilities/limits.d.ts +24 -0
  138. package/dist/capabilities/limits.d.ts.map +1 -0
  139. package/dist/capabilities/match.d.ts +52 -0
  140. package/dist/capabilities/match.d.ts.map +1 -0
  141. package/dist/capabilities/narrow.d.ts +27 -0
  142. package/dist/capabilities/narrow.d.ts.map +1 -0
  143. package/dist/capabilities/open.d.ts +25 -0
  144. package/dist/capabilities/open.d.ts.map +1 -0
  145. package/dist/capabilities/record.d.ts +13 -0
  146. package/dist/capabilities/record.d.ts.map +1 -0
  147. package/dist/capabilities/violations.d.ts +19 -0
  148. package/dist/capabilities/violations.d.ts.map +1 -0
  149. package/dist/cartesianBrush-HLU12ig5.js +122 -0
  150. package/dist/cartesianBrush-HLU12ig5.js.map +1 -0
  151. package/dist/clickDraft-DQDQn4x-.js +184 -0
  152. package/dist/clickDraft-DQDQn4x-.js.map +1 -0
  153. package/dist/dashboard/boardFields.d.ts +11 -0
  154. package/dist/dashboard/boardFields.d.ts.map +1 -0
  155. package/dist/dashboard/click.d.ts +105 -0
  156. package/dist/dashboard/click.d.ts.map +1 -0
  157. package/dist/dashboard/clickDraft.d.ts +84 -0
  158. package/dist/dashboard/clickDraft.d.ts.map +1 -0
  159. package/dist/dashboard/declared.d.ts +29 -0
  160. package/dist/dashboard/declared.d.ts.map +1 -0
  161. package/dist/dashboard/defaults.d.ts +14 -0
  162. package/dist/dashboard/defaults.d.ts.map +1 -0
  163. package/dist/dashboard/edit.d.ts +118 -0
  164. package/dist/dashboard/edit.d.ts.map +1 -0
  165. package/dist/dashboard/filterEdit.d.ts +60 -0
  166. package/dist/dashboard/filterEdit.d.ts.map +1 -0
  167. package/dist/dashboard/filters.d.ts +104 -0
  168. package/dist/dashboard/filters.d.ts.map +1 -0
  169. package/dist/dashboard/index.d.ts +26 -0
  170. package/dist/dashboard/index.d.ts.map +1 -0
  171. package/dist/dashboard/layout.d.ts +184 -0
  172. package/dist/dashboard/layout.d.ts.map +1 -0
  173. package/dist/dashboard/merge.d.ts +32 -0
  174. package/dist/dashboard/merge.d.ts.map +1 -0
  175. package/dist/dashboard/migrate.d.ts +33 -0
  176. package/dist/dashboard/migrate.d.ts.map +1 -0
  177. package/dist/dashboard/panelFieldNames.d.ts +20 -0
  178. package/dist/dashboard/panelFieldNames.d.ts.map +1 -0
  179. package/dist/dashboard/panelLook.d.ts +18 -0
  180. package/dist/dashboard/panelLook.d.ts.map +1 -0
  181. package/dist/dashboard/panels.d.ts +78 -0
  182. package/dist/dashboard/panels.d.ts.map +1 -0
  183. package/dist/dashboard/placeholders.d.ts +3 -0
  184. package/dist/dashboard/placeholders.d.ts.map +1 -0
  185. package/dist/dashboard/tabs.d.ts +28 -0
  186. package/dist/dashboard/tabs.d.ts.map +1 -0
  187. package/dist/dashboard/timeBindings.d.ts +42 -0
  188. package/dist/dashboard/timeBindings.d.ts.map +1 -0
  189. package/dist/dashboard/validate.d.ts +80 -0
  190. package/dist/dashboard/validate.d.ts.map +1 -0
  191. package/dist/dashboard/validateFilters.d.ts +15 -0
  192. package/dist/dashboard/validateFilters.d.ts.map +1 -0
  193. package/dist/dashboard/wiring.d.ts +103 -0
  194. package/dist/dashboard/wiring.d.ts.map +1 -0
  195. package/dist/echarts-HUGzxow7.js +35 -0
  196. package/dist/echarts-HUGzxow7.js.map +1 -0
  197. package/dist/echartsGeo-BWbXo9ef.js +14 -0
  198. package/dist/echartsGeo-BWbXo9ef.js.map +1 -0
  199. package/dist/echartsHierarchy-Cm-9-LN9.js +14 -0
  200. package/dist/echartsHierarchy-Cm-9-LN9.js.map +1 -0
  201. package/dist/echartsStatistics-Lq-BjHez.js +20 -0
  202. package/dist/echartsStatistics-Lq-BjHez.js.map +1 -0
  203. package/dist/echartsTime-gMH0oF0x.js +15 -0
  204. package/dist/echartsTime-gMH0oF0x.js.map +1 -0
  205. package/dist/filter/compile.d.ts +23 -0
  206. package/dist/filter/compile.d.ts.map +1 -0
  207. package/dist/filter/configBase.d.ts +23 -0
  208. package/dist/filter/configBase.d.ts.map +1 -0
  209. package/dist/filter/describe.d.ts +234 -0
  210. package/dist/filter/describe.d.ts.map +1 -0
  211. package/dist/filter/fieldGroups.d.ts +17 -0
  212. package/dist/filter/fieldGroups.d.ts.map +1 -0
  213. package/dist/filter/fieldKind.d.ts +244 -0
  214. package/dist/filter/fieldKind.d.ts.map +1 -0
  215. package/dist/filter/index.d.ts +21 -0
  216. package/dist/filter/index.d.ts.map +1 -0
  217. package/dist/filter/issuePath.d.ts +21 -0
  218. package/dist/filter/issuePath.d.ts.map +1 -0
  219. package/dist/filter/kinds/array.d.ts +18 -0
  220. package/dist/filter/kinds/array.d.ts.map +1 -0
  221. package/dist/filter/kinds/boolean.d.ts +3 -0
  222. package/dist/filter/kinds/boolean.d.ts.map +1 -0
  223. package/dist/filter/kinds/dateTime.d.ts +39 -0
  224. package/dist/filter/kinds/dateTime.d.ts.map +1 -0
  225. package/dist/filter/kinds/deletion.d.ts +42 -0
  226. package/dist/filter/kinds/deletion.d.ts.map +1 -0
  227. package/dist/filter/kinds/duration.d.ts +27 -0
  228. package/dist/filter/kinds/duration.d.ts.map +1 -0
  229. package/dist/filter/kinds/elementMatch.d.ts +34 -0
  230. package/dist/filter/kinds/elementMatch.d.ts.map +1 -0
  231. package/dist/filter/kinds/entries.d.ts +20 -0
  232. package/dist/filter/kinds/entries.d.ts.map +1 -0
  233. package/dist/filter/kinds/enum.d.ts +7 -0
  234. package/dist/filter/kinds/enum.d.ts.map +1 -0
  235. package/dist/filter/kinds/index.d.ts +18 -0
  236. package/dist/filter/kinds/index.d.ts.map +1 -0
  237. package/dist/filter/kinds/metadata.d.ts +3 -0
  238. package/dist/filter/kinds/metadata.d.ts.map +1 -0
  239. package/dist/filter/kinds/number.d.ts +3 -0
  240. package/dist/filter/kinds/number.d.ts.map +1 -0
  241. package/dist/filter/kinds/options.d.ts +44 -0
  242. package/dist/filter/kinds/options.d.ts.map +1 -0
  243. package/dist/filter/kinds/presence.d.ts +18 -0
  244. package/dist/filter/kinds/presence.d.ts.map +1 -0
  245. package/dist/filter/kinds/reference.d.ts +8 -0
  246. package/dist/filter/kinds/reference.d.ts.map +1 -0
  247. package/dist/filter/kinds/search.d.ts +15 -0
  248. package/dist/filter/kinds/search.d.ts.map +1 -0
  249. package/dist/filter/kinds/string.d.ts +3 -0
  250. package/dist/filter/kinds/string.d.ts.map +1 -0
  251. package/dist/filter/marks.d.ts +28 -0
  252. package/dist/filter/marks.d.ts.map +1 -0
  253. package/dist/filter/search.d.ts +28 -0
  254. package/dist/filter/search.d.ts.map +1 -0
  255. package/dist/filter/time.d.ts +57 -0
  256. package/dist/filter/time.d.ts.map +1 -0
  257. package/dist/filter/tree.d.ts +186 -0
  258. package/dist/filter/tree.d.ts.map +1 -0
  259. package/dist/filter/validate.d.ts +42 -0
  260. package/dist/filter/validate.d.ts.map +1 -0
  261. package/dist/filter/values.d.ts +111 -0
  262. package/dist/filter/values.d.ts.map +1 -0
  263. package/dist/index.d.ts +138 -0
  264. package/dist/index.d.ts.map +1 -0
  265. package/dist/index.js +478 -0
  266. package/dist/index.js.map +1 -0
  267. package/dist/model/analysis.d.ts +327 -0
  268. package/dist/model/analysis.d.ts.map +1 -0
  269. package/dist/model/chart.d.ts +503 -0
  270. package/dist/model/chart.d.ts.map +1 -0
  271. package/dist/model/config.d.ts +68 -0
  272. package/dist/model/config.d.ts.map +1 -0
  273. package/dist/model/currency.d.ts +55 -0
  274. package/dist/model/currency.d.ts.map +1 -0
  275. package/dist/model/dashboard.d.ts +454 -0
  276. package/dist/model/dashboard.d.ts.map +1 -0
  277. package/dist/model/definition.d.ts +373 -0
  278. package/dist/model/definition.d.ts.map +1 -0
  279. package/dist/model/field.d.ts +432 -0
  280. package/dist/model/field.d.ts.map +1 -0
  281. package/dist/model/filter.d.ts +54 -0
  282. package/dist/model/filter.d.ts.map +1 -0
  283. package/dist/model/index.d.ts +21 -0
  284. package/dist/model/index.d.ts.map +1 -0
  285. package/dist/model/instance.d.ts +118 -0
  286. package/dist/model/instance.d.ts.map +1 -0
  287. package/dist/model/issue.d.ts +33 -0
  288. package/dist/model/issue.d.ts.map +1 -0
  289. package/dist/model/json.d.ts +34 -0
  290. package/dist/model/json.d.ts.map +1 -0
  291. package/dist/model/limits.d.ts +133 -0
  292. package/dist/model/limits.d.ts.map +1 -0
  293. package/dist/model/record.d.ts +114 -0
  294. package/dist/model/record.d.ts.map +1 -0
  295. package/dist/model/storeError.d.ts +105 -0
  296. package/dist/model/storeError.d.ts.map +1 -0
  297. package/dist/model/text.d.ts +58 -0
  298. package/dist/model/text.d.ts.map +1 -0
  299. package/dist/react/actionRunner.d.ts +161 -0
  300. package/dist/react/actionRunner.d.ts.map +1 -0
  301. package/dist/react/actions.d.ts +112 -0
  302. package/dist/react/actions.d.ts.map +1 -0
  303. package/dist/react/analysisEditing.d.ts +122 -0
  304. package/dist/react/analysisEditing.d.ts.map +1 -0
  305. package/dist/react/analysisFields.d.ts +38 -0
  306. package/dist/react/analysisFields.d.ts.map +1 -0
  307. package/dist/react/environment.d.ts +10 -0
  308. package/dist/react/environment.d.ts.map +1 -0
  309. package/dist/react/index.d.ts +41 -0
  310. package/dist/react/index.d.ts.map +1 -0
  311. package/dist/react/issues.d.ts +14 -0
  312. package/dist/react/issues.d.ts.map +1 -0
  313. package/dist/react/manager/abilities.d.ts +38 -0
  314. package/dist/react/manager/abilities.d.ts.map +1 -0
  315. package/dist/react/manager/order.d.ts +60 -0
  316. package/dist/react/manager/order.d.ts.map +1 -0
  317. package/dist/react/manager/outcomes.d.ts +55 -0
  318. package/dist/react/manager/outcomes.d.ts.map +1 -0
  319. package/dist/react/manager/queue.d.ts +56 -0
  320. package/dist/react/manager/queue.d.ts.map +1 -0
  321. package/dist/react/manager/useCommandRunner.d.ts +74 -0
  322. package/dist/react/manager/useCommandRunner.d.ts.map +1 -0
  323. package/dist/react/recordColumns.d.ts +68 -0
  324. package/dist/react/recordColumns.d.ts.map +1 -0
  325. package/dist/react/recordDraft.d.ts +31 -0
  326. package/dist/react/recordDraft.d.ts.map +1 -0
  327. package/dist/react/recordEdits.d.ts +58 -0
  328. package/dist/react/recordEdits.d.ts.map +1 -0
  329. package/dist/react/recordSelection.d.ts +46 -0
  330. package/dist/react/recordSelection.d.ts.map +1 -0
  331. package/dist/react/useAnalysisEditor.d.ts +183 -0
  332. package/dist/react/useAnalysisEditor.d.ts.map +1 -0
  333. package/dist/react/useAnalysisResult.d.ts +168 -0
  334. package/dist/react/useAnalysisResult.d.ts.map +1 -0
  335. package/dist/react/useAutoRefresh.d.ts +115 -0
  336. package/dist/react/useAutoRefresh.d.ts.map +1 -0
  337. package/dist/react/useDashboard.d.ts +204 -0
  338. package/dist/react/useDashboard.d.ts.map +1 -0
  339. package/dist/react/useFilterEditor.d.ts +255 -0
  340. package/dist/react/useFilterEditor.d.ts.map +1 -0
  341. package/dist/react/usePanelFollowUps.d.ts +31 -0
  342. package/dist/react/usePanelFollowUps.d.ts.map +1 -0
  343. package/dist/react/useRecordActions.d.ts +126 -0
  344. package/dist/react/useRecordActions.d.ts.map +1 -0
  345. package/dist/react/useRecordDetail.d.ts +76 -0
  346. package/dist/react/useRecordDetail.d.ts.map +1 -0
  347. package/dist/react/useRecordExport.d.ts +104 -0
  348. package/dist/react/useRecordExport.d.ts.map +1 -0
  349. package/dist/react/useRecordTable.d.ts +309 -0
  350. package/dist/react/useRecordTable.d.ts.map +1 -0
  351. package/dist/react/useReshape.d.ts +54 -0
  352. package/dist/react/useReshape.d.ts.map +1 -0
  353. package/dist/react/useSaveCommands.d.ts +119 -0
  354. package/dist/react/useSaveCommands.d.ts.map +1 -0
  355. package/dist/react/useSearchBox.d.ts +34 -0
  356. package/dist/react/useSearchBox.d.ts.map +1 -0
  357. package/dist/react/useUnavailable.d.ts +19 -0
  358. package/dist/react/useUnavailable.d.ts.map +1 -0
  359. package/dist/react/useValueCandidates.d.ts +41 -0
  360. package/dist/react/useValueCandidates.d.ts.map +1 -0
  361. package/dist/react/useViewEngine.d.ts +93 -0
  362. package/dist/react/useViewEngine.d.ts.map +1 -0
  363. package/dist/react/useViewList.d.ts +75 -0
  364. package/dist/react/useViewList.d.ts.map +1 -0
  365. package/dist/react/useViewManager.d.ts +92 -0
  366. package/dist/react/useViewManager.d.ts.map +1 -0
  367. package/dist/react/useWorkbench.d.ts +334 -0
  368. package/dist/react/useWorkbench.d.ts.map +1 -0
  369. package/dist/react/workbench/handOver.d.ts +73 -0
  370. package/dist/react/workbench/handOver.d.ts.map +1 -0
  371. package/dist/react/workbench/instanceSync.d.ts +55 -0
  372. package/dist/react/workbench/instanceSync.d.ts.map +1 -0
  373. package/dist/react/workbench/leaveGuard.d.ts +65 -0
  374. package/dist/react/workbench/leaveGuard.d.ts.map +1 -0
  375. package/dist/react/workbench/newView.d.ts +35 -0
  376. package/dist/react/workbench/newView.d.ts.map +1 -0
  377. package/dist/react/workbench/releaseDeleted.d.ts +19 -0
  378. package/dist/react/workbench/releaseDeleted.d.ts.map +1 -0
  379. package/dist/react/writes.d.ts +134 -0
  380. package/dist/react/writes.d.ts.map +1 -0
  381. package/dist/react-DzstAsWB.js +3648 -0
  382. package/dist/react-DzstAsWB.js.map +1 -0
  383. package/dist/react-router/index.d.ts +12 -0
  384. package/dist/react-router/index.d.ts.map +1 -0
  385. package/dist/react-router.js +27 -0
  386. package/dist/react-router.js.map +1 -0
  387. package/dist/react.js +3 -0
  388. package/dist/record/compile.d.ts +56 -0
  389. package/dist/record/compile.d.ts.map +1 -0
  390. package/dist/record/defaults.d.ts +9 -0
  391. package/dist/record/defaults.d.ts.map +1 -0
  392. package/dist/record/detail.d.ts +27 -0
  393. package/dist/record/detail.d.ts.map +1 -0
  394. package/dist/record/export.d.ts +78 -0
  395. package/dist/record/export.d.ts.map +1 -0
  396. package/dist/record/index.d.ts +12 -0
  397. package/dist/record/index.d.ts.map +1 -0
  398. package/dist/record/paging.d.ts +89 -0
  399. package/dist/record/paging.d.ts.map +1 -0
  400. package/dist/record/path.d.ts +13 -0
  401. package/dist/record/path.d.ts.map +1 -0
  402. package/dist/record/project.d.ts +245 -0
  403. package/dist/record/project.d.ts.map +1 -0
  404. package/dist/record/summaryCurrency.d.ts +18 -0
  405. package/dist/record/summaryCurrency.d.ts.map +1 -0
  406. package/dist/record/validate.d.ts +30 -0
  407. package/dist/record/validate.d.ts.map +1 -0
  408. package/dist/routes-DvPNPlQP.js +23 -0
  409. package/dist/routes-DvPNPlQP.js.map +1 -0
  410. package/dist/runtime/abort.d.ts +3 -0
  411. package/dist/runtime/abort.d.ts.map +1 -0
  412. package/dist/runtime/actions.d.ts +241 -0
  413. package/dist/runtime/actions.d.ts.map +1 -0
  414. package/dist/runtime/admission.d.ts +35 -0
  415. package/dist/runtime/admission.d.ts.map +1 -0
  416. package/dist/runtime/autoApply.d.ts +51 -0
  417. package/dist/runtime/autoApply.d.ts.map +1 -0
  418. package/dist/runtime/capabilities.d.ts +98 -0
  419. package/dist/runtime/capabilities.d.ts.map +1 -0
  420. package/dist/runtime/commandChecks.d.ts +22 -0
  421. package/dist/runtime/commandChecks.d.ts.map +1 -0
  422. package/dist/runtime/dashboard/anchor.d.ts +46 -0
  423. package/dist/runtime/dashboard/anchor.d.ts.map +1 -0
  424. package/dist/runtime/dashboard/canonical.d.ts +31 -0
  425. package/dist/runtime/dashboard/canonical.d.ts.map +1 -0
  426. package/dist/runtime/dashboard/children.d.ts +127 -0
  427. package/dist/runtime/dashboard/children.d.ts.map +1 -0
  428. package/dist/runtime/dashboard/commands.d.ts +172 -0
  429. package/dist/runtime/dashboard/commands.d.ts.map +1 -0
  430. package/dist/runtime/dashboard/contract.d.ts +250 -0
  431. package/dist/runtime/dashboard/contract.d.ts.map +1 -0
  432. package/dist/runtime/dashboard/editing.d.ts +197 -0
  433. package/dist/runtime/dashboard/editing.d.ts.map +1 -0
  434. package/dist/runtime/dashboard/filterCandidates.d.ts +38 -0
  435. package/dist/runtime/dashboard/filterCandidates.d.ts.map +1 -0
  436. package/dist/runtime/dashboard/filterValues.d.ts +117 -0
  437. package/dist/runtime/dashboard/filterValues.d.ts.map +1 -0
  438. package/dist/runtime/dashboard/grouping.d.ts +26 -0
  439. package/dist/runtime/dashboard/grouping.d.ts.map +1 -0
  440. package/dist/runtime/dashboard/history.d.ts +78 -0
  441. package/dist/runtime/dashboard/history.d.ts.map +1 -0
  442. package/dist/runtime/dashboard/opening.d.ts +17 -0
  443. package/dist/runtime/dashboard/opening.d.ts.map +1 -0
  444. package/dist/runtime/dashboard/owned.d.ts +38 -0
  445. package/dist/runtime/dashboard/owned.d.ts.map +1 -0
  446. package/dist/runtime/dashboard/panelRun.d.ts +101 -0
  447. package/dist/runtime/dashboard/panelRun.d.ts.map +1 -0
  448. package/dist/runtime/dashboard/panels.d.ts +155 -0
  449. package/dist/runtime/dashboard/panels.d.ts.map +1 -0
  450. package/dist/runtime/dashboard/presentation.d.ts +25 -0
  451. package/dist/runtime/dashboard/presentation.d.ts.map +1 -0
  452. package/dist/runtime/dashboard/press.d.ts +150 -0
  453. package/dist/runtime/dashboard/press.d.ts.map +1 -0
  454. package/dist/runtime/dashboard/references.d.ts +97 -0
  455. package/dist/runtime/dashboard/references.d.ts.map +1 -0
  456. package/dist/runtime/dashboardRuntime.d.ts +235 -0
  457. package/dist/runtime/dashboardRuntime.d.ts.map +1 -0
  458. package/dist/runtime/define/analysis.d.ts +8 -0
  459. package/dist/runtime/define/analysis.d.ts.map +1 -0
  460. package/dist/runtime/define/defineView.d.ts +42 -0
  461. package/dist/runtime/define/defineView.d.ts.map +1 -0
  462. package/dist/runtime/define/fields.d.ts +23 -0
  463. package/dist/runtime/define/fields.d.ts.map +1 -0
  464. package/dist/runtime/define/spec.d.ts +88 -0
  465. package/dist/runtime/define/spec.d.ts.map +1 -0
  466. package/dist/runtime/definitions.d.ts +35 -0
  467. package/dist/runtime/definitions.d.ts.map +1 -0
  468. package/dist/runtime/deprecated.d.ts +3 -0
  469. package/dist/runtime/deprecated.d.ts.map +1 -0
  470. package/dist/runtime/environment.d.ts +95 -0
  471. package/dist/runtime/environment.d.ts.map +1 -0
  472. package/dist/runtime/execute.d.ts +70 -0
  473. package/dist/runtime/execute.d.ts.map +1 -0
  474. package/dist/runtime/exportRows.d.ts +67 -0
  475. package/dist/runtime/exportRows.d.ts.map +1 -0
  476. package/dist/runtime/failures.d.ts +57 -0
  477. package/dist/runtime/failures.d.ts.map +1 -0
  478. package/dist/runtime/fetchRecord.d.ts +20 -0
  479. package/dist/runtime/fetchRecord.d.ts.map +1 -0
  480. package/dist/runtime/index.d.ts +35 -0
  481. package/dist/runtime/index.d.ts.map +1 -0
  482. package/dist/runtime/issueReport.d.ts +25 -0
  483. package/dist/runtime/issueReport.d.ts.map +1 -0
  484. package/dist/runtime/issues.d.ts +35 -0
  485. package/dist/runtime/issues.d.ts.map +1 -0
  486. package/dist/runtime/listeners.d.ts +36 -0
  487. package/dist/runtime/listeners.d.ts.map +1 -0
  488. package/dist/runtime/navigation.d.ts +139 -0
  489. package/dist/runtime/navigation.d.ts.map +1 -0
  490. package/dist/runtime/openRuntimes.d.ts +34 -0
  491. package/dist/runtime/openRuntimes.d.ts.map +1 -0
  492. package/dist/runtime/panelViews.d.ts +42 -0
  493. package/dist/runtime/panelViews.d.ts.map +1 -0
  494. package/dist/runtime/pending.d.ts +75 -0
  495. package/dist/runtime/pending.d.ts.map +1 -0
  496. package/dist/runtime/permissions.d.ts +80 -0
  497. package/dist/runtime/permissions.d.ts.map +1 -0
  498. package/dist/runtime/preferences.d.ts +37 -0
  499. package/dist/runtime/preferences.d.ts.map +1 -0
  500. package/dist/runtime/publish.d.ts +38 -0
  501. package/dist/runtime/publish.d.ts.map +1 -0
  502. package/dist/runtime/queryFailure.d.ts +59 -0
  503. package/dist/runtime/queryFailure.d.ts.map +1 -0
  504. package/dist/runtime/queryWeight.d.ts +29 -0
  505. package/dist/runtime/queryWeight.d.ts.map +1 -0
  506. package/dist/runtime/recordRuntime.d.ts +88 -0
  507. package/dist/runtime/recordRuntime.d.ts.map +1 -0
  508. package/dist/runtime/refreshTimer.d.ts +72 -0
  509. package/dist/runtime/refreshTimer.d.ts.map +1 -0
  510. package/dist/runtime/requestId.d.ts +11 -0
  511. package/dist/runtime/requestId.d.ts.map +1 -0
  512. package/dist/runtime/requestRunner.d.ts +58 -0
  513. package/dist/runtime/requestRunner.d.ts.map +1 -0
  514. package/dist/runtime/resources.d.ts +73 -0
  515. package/dist/runtime/resources.d.ts.map +1 -0
  516. package/dist/runtime/restyle.d.ts +21 -0
  517. package/dist/runtime/restyle.d.ts.map +1 -0
  518. package/dist/runtime/routes.d.ts +99 -0
  519. package/dist/runtime/routes.d.ts.map +1 -0
  520. package/dist/runtime/runtimeFactory.d.ts +80 -0
  521. package/dist/runtime/runtimeFactory.d.ts.map +1 -0
  522. package/dist/runtime/runtimeStore.d.ts +187 -0
  523. package/dist/runtime/runtimeStore.d.ts.map +1 -0
  524. package/dist/runtime/savedConditions.d.ts +11 -0
  525. package/dist/runtime/savedConditions.d.ts.map +1 -0
  526. package/dist/runtime/scope.d.ts +50 -0
  527. package/dist/runtime/scope.d.ts.map +1 -0
  528. package/dist/runtime/source.d.ts +108 -0
  529. package/dist/runtime/source.d.ts.map +1 -0
  530. package/dist/runtime/sourceReason.d.ts +65 -0
  531. package/dist/runtime/sourceReason.d.ts.map +1 -0
  532. package/dist/runtime/storedViews.d.ts +17 -0
  533. package/dist/runtime/storedViews.d.ts.map +1 -0
  534. package/dist/runtime/summaries.d.ts +25 -0
  535. package/dist/runtime/summaries.d.ts.map +1 -0
  536. package/dist/runtime/tabMemory.d.ts +39 -0
  537. package/dist/runtime/tabMemory.d.ts.map +1 -0
  538. package/dist/runtime/text.d.ts +20 -0
  539. package/dist/runtime/text.d.ts.map +1 -0
  540. package/dist/runtime/unavailable.d.ts +13 -0
  541. package/dist/runtime/unavailable.d.ts.map +1 -0
  542. package/dist/runtime/validateDefinition.d.ts +43 -0
  543. package/dist/runtime/validateDefinition.d.ts.map +1 -0
  544. package/dist/runtime/validateFields.d.ts +9 -0
  545. package/dist/runtime/validateFields.d.ts.map +1 -0
  546. package/dist/runtime/valueCandidates.d.ts +58 -0
  547. package/dist/runtime/valueCandidates.d.ts.map +1 -0
  548. package/dist/runtime/viewChanges.d.ts +39 -0
  549. package/dist/runtime/viewChanges.d.ts.map +1 -0
  550. package/dist/runtime/viewEngine.d.ts +292 -0
  551. package/dist/runtime/viewEngine.d.ts.map +1 -0
  552. package/dist/runtime/viewRuntime.d.ts +199 -0
  553. package/dist/runtime/viewRuntime.d.ts.map +1 -0
  554. package/dist/runtime/viewRuntimeTypes.d.ts +445 -0
  555. package/dist/runtime/viewRuntimeTypes.d.ts.map +1 -0
  556. package/dist/runtime/write.d.ts +96 -0
  557. package/dist/runtime/write.d.ts.map +1 -0
  558. package/dist/runtime/writeLedger.d.ts +134 -0
  559. package/dist/runtime/writeLedger.d.ts.map +1 -0
  560. package/dist/shadcn-bridge.css +107 -0
  561. package/dist/store/MemoryViewStore.d.ts +134 -0
  562. package/dist/store/MemoryViewStore.d.ts.map +1 -0
  563. package/dist/store/ViewStore.d.ts +116 -0
  564. package/dist/store/ViewStore.d.ts.map +1 -0
  565. package/dist/store/index.d.ts +10 -0
  566. package/dist/store/index.d.ts.map +1 -0
  567. package/dist/store/localStorageSnapshot.d.ts +65 -0
  568. package/dist/store/localStorageSnapshot.d.ts.map +1 -0
  569. package/dist/styles.css +3 -0
  570. package/dist/styles.d.ts +1 -0
  571. package/dist/styles.d.ts.map +1 -0
  572. package/dist/styles.js +0 -0
  573. package/dist/testing/actions.d.ts +78 -0
  574. package/dist/testing/actions.d.ts.map +1 -0
  575. package/dist/testing/aggregate.d.ts +24 -0
  576. package/dist/testing/aggregate.d.ts.map +1 -0
  577. package/dist/testing/calendar.d.ts +41 -0
  578. package/dist/testing/calendar.d.ts.map +1 -0
  579. package/dist/testing/expression.d.ts +17 -0
  580. package/dist/testing/expression.d.ts.map +1 -0
  581. package/dist/testing/filter.d.ts +48 -0
  582. package/dist/testing/filter.d.ts.map +1 -0
  583. package/dist/testing/index.d.ts +13 -0
  584. package/dist/testing/index.d.ts.map +1 -0
  585. package/dist/testing/source.d.ts +52 -0
  586. package/dist/testing/source.d.ts.map +1 -0
  587. package/dist/testing/values.d.ts +14 -0
  588. package/dist/testing/values.d.ts.map +1 -0
  589. package/dist/testing.js +725 -0
  590. package/dist/testing.js.map +1 -0
  591. package/dist/theme-check.mjs +6972 -0
  592. package/dist/theme-source.css +1393 -0
  593. package/dist/theme-tokens.json +5335 -0
  594. package/dist/themes/azure.css +126 -0
  595. package/dist/themes/contrast.css +122 -0
  596. package/dist/themes/neutral.css +2 -0
  597. package/dist/themes/porcelain.css +136 -0
  598. package/dist/themes.css +389 -0
  599. package/dist/ui/DashboardWorkbench.d.ts +133 -0
  600. package/dist/ui/DashboardWorkbench.d.ts.map +1 -0
  601. package/dist/ui/DataWorkbench.d.ts +155 -0
  602. package/dist/ui/DataWorkbench.d.ts.map +1 -0
  603. package/dist/ui/EmbeddedDashboard.d.ts +103 -0
  604. package/dist/ui/EmbeddedDashboard.d.ts.map +1 -0
  605. package/dist/ui/EmbeddedView.d.ts +76 -0
  606. package/dist/ui/EmbeddedView.d.ts.map +1 -0
  607. package/dist/ui/ViewHost.d.ts +94 -0
  608. package/dist/ui/ViewHost.d.ts.map +1 -0
  609. package/dist/ui/actions/ActionButtons.d.ts +49 -0
  610. package/dist/ui/actions/ActionButtons.d.ts.map +1 -0
  611. package/dist/ui/actions/ActionDialog.d.ts +35 -0
  612. package/dist/ui/actions/ActionDialog.d.ts.map +1 -0
  613. package/dist/ui/actions/ActionSurface.d.ts +60 -0
  614. package/dist/ui/actions/ActionSurface.d.ts.map +1 -0
  615. package/dist/ui/actions/BulkStatus.d.ts +41 -0
  616. package/dist/ui/actions/BulkStatus.d.ts.map +1 -0
  617. package/dist/ui/analysis/AnalysisChart.d.ts +71 -0
  618. package/dist/ui/analysis/AnalysisChart.d.ts.map +1 -0
  619. package/dist/ui/analysis/AnalysisTable.d.ts +54 -0
  620. package/dist/ui/analysis/AnalysisTable.d.ts.map +1 -0
  621. package/dist/ui/analysis/AnalysisToolbar.d.ts +68 -0
  622. package/dist/ui/analysis/AnalysisToolbar.d.ts.map +1 -0
  623. package/dist/ui/analysis/AxesTab.d.ts +11 -0
  624. package/dist/ui/analysis/AxesTab.d.ts.map +1 -0
  625. package/dist/ui/analysis/CardMenu.d.ts +41 -0
  626. package/dist/ui/analysis/CardMenu.d.ts.map +1 -0
  627. package/dist/ui/analysis/ChartOptions.d.ts +38 -0
  628. package/dist/ui/analysis/ChartOptions.d.ts.map +1 -0
  629. package/dist/ui/analysis/ChartPicker.d.ts +86 -0
  630. package/dist/ui/analysis/ChartPicker.d.ts.map +1 -0
  631. package/dist/ui/analysis/CompactSelect.d.ts +28 -0
  632. package/dist/ui/analysis/CompactSelect.d.ts.map +1 -0
  633. package/dist/ui/analysis/CompositionOptions.d.ts +18 -0
  634. package/dist/ui/analysis/CompositionOptions.d.ts.map +1 -0
  635. package/dist/ui/analysis/CurrencyStrip.d.ts +19 -0
  636. package/dist/ui/analysis/CurrencyStrip.d.ts.map +1 -0
  637. package/dist/ui/analysis/DataTab.d.ts +10 -0
  638. package/dist/ui/analysis/DataTab.d.ts.map +1 -0
  639. package/dist/ui/analysis/DimensionCard.d.ts +13 -0
  640. package/dist/ui/analysis/DimensionCard.d.ts.map +1 -0
  641. package/dist/ui/analysis/DisplayTab.d.ts +26 -0
  642. package/dist/ui/analysis/DisplayTab.d.ts.map +1 -0
  643. package/dist/ui/analysis/DrillMenu.d.ts +73 -0
  644. package/dist/ui/analysis/DrillMenu.d.ts.map +1 -0
  645. package/dist/ui/analysis/DroppedNotice.d.ts +28 -0
  646. package/dist/ui/analysis/DroppedNotice.d.ts.map +1 -0
  647. package/dist/ui/analysis/ElementsSlot.d.ts +22 -0
  648. package/dist/ui/analysis/ElementsSlot.d.ts.map +1 -0
  649. package/dist/ui/analysis/EmptyResult.d.ts +50 -0
  650. package/dist/ui/analysis/EmptyResult.d.ts.map +1 -0
  651. package/dist/ui/analysis/ExportMenu.d.ts +35 -0
  652. package/dist/ui/analysis/ExportMenu.d.ts.map +1 -0
  653. package/dist/ui/analysis/FormulaCard.d.ts +46 -0
  654. package/dist/ui/analysis/FormulaCard.d.ts.map +1 -0
  655. package/dist/ui/analysis/HavingRows.d.ts +50 -0
  656. package/dist/ui/analysis/HavingRows.d.ts.map +1 -0
  657. package/dist/ui/analysis/LevelOptions.d.ts +21 -0
  658. package/dist/ui/analysis/LevelOptions.d.ts.map +1 -0
  659. package/dist/ui/analysis/MapOptions.d.ts +8 -0
  660. package/dist/ui/analysis/MapOptions.d.ts.map +1 -0
  661. package/dist/ui/analysis/MetricCard.d.ts +29 -0
  662. package/dist/ui/analysis/MetricCard.d.ts.map +1 -0
  663. package/dist/ui/analysis/MetricCondition.d.ts +73 -0
  664. package/dist/ui/analysis/MetricCondition.d.ts.map +1 -0
  665. package/dist/ui/analysis/MetricSlot.d.ts +35 -0
  666. package/dist/ui/analysis/MetricSlot.d.ts.map +1 -0
  667. package/dist/ui/analysis/OrderedCards.d.ts +39 -0
  668. package/dist/ui/analysis/OrderedCards.d.ts.map +1 -0
  669. package/dist/ui/analysis/RangeSlot.d.ts +26 -0
  670. package/dist/ui/analysis/RangeSlot.d.ts.map +1 -0
  671. package/dist/ui/analysis/ReferenceOptions.d.ts +12 -0
  672. package/dist/ui/analysis/ReferenceOptions.d.ts.map +1 -0
  673. package/dist/ui/analysis/ResultSlot.d.ts +31 -0
  674. package/dist/ui/analysis/ResultSlot.d.ts.map +1 -0
  675. package/dist/ui/analysis/SeriesList.d.ts +35 -0
  676. package/dist/ui/analysis/SeriesList.d.ts.map +1 -0
  677. package/dist/ui/analysis/SkeletonResult.d.ts +36 -0
  678. package/dist/ui/analysis/SkeletonResult.d.ts.map +1 -0
  679. package/dist/ui/analysis/StatisticalOptions.d.ts +31 -0
  680. package/dist/ui/analysis/StatisticalOptions.d.ts.map +1 -0
  681. package/dist/ui/analysis/TermTip.d.ts +32 -0
  682. package/dist/ui/analysis/TermTip.d.ts.map +1 -0
  683. package/dist/ui/analysis/Tray.d.ts +45 -0
  684. package/dist/ui/analysis/Tray.d.ts.map +1 -0
  685. package/dist/ui/analysis/VisualizationPanel.d.ts +68 -0
  686. package/dist/ui/analysis/VisualizationPanel.d.ts.map +1 -0
  687. package/dist/ui/analysis/chartIcons.d.ts +19 -0
  688. package/dist/ui/analysis/chartIcons.d.ts.map +1 -0
  689. package/dist/ui/analysis/drag.d.ts +39 -0
  690. package/dist/ui/analysis/drag.d.ts.map +1 -0
  691. package/dist/ui/analysis/editing.d.ts +69 -0
  692. package/dist/ui/analysis/editing.d.ts.map +1 -0
  693. package/dist/ui/analysis/exportOffer.d.ts +60 -0
  694. package/dist/ui/analysis/exportOffer.d.ts.map +1 -0
  695. package/dist/ui/analysis/headerSort.d.ts +66 -0
  696. package/dist/ui/analysis/headerSort.d.ts.map +1 -0
  697. package/dist/ui/analysis/imageExport.d.ts +40 -0
  698. package/dist/ui/analysis/imageExport.d.ts.map +1 -0
  699. package/dist/ui/analysis/issueNames.d.ts +39 -0
  700. package/dist/ui/analysis/issueNames.d.ts.map +1 -0
  701. package/dist/ui/analysis/listFocus.d.ts +42 -0
  702. package/dist/ui/analysis/listFocus.d.ts.map +1 -0
  703. package/dist/ui/analysis/optionControls.d.ts +200 -0
  704. package/dist/ui/analysis/optionControls.d.ts.map +1 -0
  705. package/dist/ui/analysis/tableColumns.d.ts +79 -0
  706. package/dist/ui/analysis/tableColumns.d.ts.map +1 -0
  707. package/dist/ui/analysis/virtualRows.d.ts +66 -0
  708. package/dist/ui/analysis/virtualRows.d.ts.map +1 -0
  709. package/dist/ui/charts/Boxplot.d.ts +10 -0
  710. package/dist/ui/charts/Boxplot.d.ts.map +1 -0
  711. package/dist/ui/charts/Candlestick.d.ts +9 -0
  712. package/dist/ui/charts/Candlestick.d.ts.map +1 -0
  713. package/dist/ui/charts/Cartesian.d.ts +9 -0
  714. package/dist/ui/charts/Cartesian.d.ts.map +1 -0
  715. package/dist/ui/charts/ChartLegend.d.ts +47 -0
  716. package/dist/ui/charts/ChartLegend.d.ts.map +1 -0
  717. package/dist/ui/charts/ChartNotes.d.ts +14 -0
  718. package/dist/ui/charts/ChartNotes.d.ts.map +1 -0
  719. package/dist/ui/charts/ChartReading.d.ts +15 -0
  720. package/dist/ui/charts/ChartReading.d.ts.map +1 -0
  721. package/dist/ui/charts/EChart.d.ts +177 -0
  722. package/dist/ui/charts/EChart.d.ts.map +1 -0
  723. package/dist/ui/charts/Funnel.d.ts +27 -0
  724. package/dist/ui/charts/Funnel.d.ts.map +1 -0
  725. package/dist/ui/charts/Gauge.d.ts +9 -0
  726. package/dist/ui/charts/Gauge.d.ts.map +1 -0
  727. package/dist/ui/charts/GeoMap.d.ts +11 -0
  728. package/dist/ui/charts/GeoMap.d.ts.map +1 -0
  729. package/dist/ui/charts/Heatmap.d.ts +9 -0
  730. package/dist/ui/charts/Heatmap.d.ts.map +1 -0
  731. package/dist/ui/charts/Hierarchy.d.ts +12 -0
  732. package/dist/ui/charts/Hierarchy.d.ts.map +1 -0
  733. package/dist/ui/charts/MetricCard.d.ts +4 -0
  734. package/dist/ui/charts/MetricCard.d.ts.map +1 -0
  735. package/dist/ui/charts/PieSlices.d.ts +26 -0
  736. package/dist/ui/charts/PieSlices.d.ts.map +1 -0
  737. package/dist/ui/charts/Profiles.d.ts +11 -0
  738. package/dist/ui/charts/Profiles.d.ts.map +1 -0
  739. package/dist/ui/charts/ScatterPoints.d.ts +5 -0
  740. package/dist/ui/charts/ScatterPoints.d.ts.map +1 -0
  741. package/dist/ui/charts/TimeCharts.d.ts +10 -0
  742. package/dist/ui/charts/TimeCharts.d.ts.map +1 -0
  743. package/dist/ui/charts/Treemap.d.ts +12 -0
  744. package/dist/ui/charts/Treemap.d.ts.map +1 -0
  745. package/dist/ui/charts/Waterfall.d.ts +11 -0
  746. package/dist/ui/charts/Waterfall.d.ts.map +1 -0
  747. package/dist/ui/charts/axis.d.ts +101 -0
  748. package/dist/ui/charts/axis.d.ts.map +1 -0
  749. package/dist/ui/charts/boxplotOption.d.ts +33 -0
  750. package/dist/ui/charts/boxplotOption.d.ts.map +1 -0
  751. package/dist/ui/charts/candlestickOption.d.ts +42 -0
  752. package/dist/ui/charts/candlestickOption.d.ts.map +1 -0
  753. package/dist/ui/charts/cartesianBrush.d.ts +84 -0
  754. package/dist/ui/charts/cartesianBrush.d.ts.map +1 -0
  755. package/dist/ui/charts/cartesianFit.d.ts +72 -0
  756. package/dist/ui/charts/cartesianFit.d.ts.map +1 -0
  757. package/dist/ui/charts/cartesianMarks.d.ts +116 -0
  758. package/dist/ui/charts/cartesianMarks.d.ts.map +1 -0
  759. package/dist/ui/charts/cartesianOption.d.ts +32 -0
  760. package/dist/ui/charts/cartesianOption.d.ts.map +1 -0
  761. package/dist/ui/charts/cartesianPlan.d.ts +263 -0
  762. package/dist/ui/charts/cartesianPlan.d.ts.map +1 -0
  763. package/dist/ui/charts/cartesianSeries.d.ts +41 -0
  764. package/dist/ui/charts/cartesianSeries.d.ts.map +1 -0
  765. package/dist/ui/charts/cartesianTooltip.d.ts +14 -0
  766. package/dist/ui/charts/cartesianTooltip.d.ts.map +1 -0
  767. package/dist/ui/charts/cartesianZoom.d.ts +60 -0
  768. package/dist/ui/charts/cartesianZoom.d.ts.map +1 -0
  769. package/dist/ui/charts/categoryFrame.d.ts +106 -0
  770. package/dist/ui/charts/categoryFrame.d.ts.map +1 -0
  771. package/dist/ui/charts/dateTicks.d.ts +36 -0
  772. package/dist/ui/charts/dateTicks.d.ts.map +1 -0
  773. package/dist/ui/charts/echarts.d.ts +16 -0
  774. package/dist/ui/charts/echarts.d.ts.map +1 -0
  775. package/dist/ui/charts/echartsGeo.d.ts +5 -0
  776. package/dist/ui/charts/echartsGeo.d.ts.map +1 -0
  777. package/dist/ui/charts/echartsHierarchy.d.ts +2 -0
  778. package/dist/ui/charts/echartsHierarchy.d.ts.map +1 -0
  779. package/dist/ui/charts/echartsStatistics.d.ts +2 -0
  780. package/dist/ui/charts/echartsStatistics.d.ts.map +1 -0
  781. package/dist/ui/charts/echartsTime.d.ts +2 -0
  782. package/dist/ui/charts/echartsTime.d.ts.map +1 -0
  783. package/dist/ui/charts/family.d.ts +176 -0
  784. package/dist/ui/charts/family.d.ts.map +1 -0
  785. package/dist/ui/charts/frameClass.d.ts +18 -0
  786. package/dist/ui/charts/frameClass.d.ts.map +1 -0
  787. package/dist/ui/charts/funnelFit.d.ts +67 -0
  788. package/dist/ui/charts/funnelFit.d.ts.map +1 -0
  789. package/dist/ui/charts/funnelOption.d.ts +94 -0
  790. package/dist/ui/charts/funnelOption.d.ts.map +1 -0
  791. package/dist/ui/charts/gaugeOption.d.ts +32 -0
  792. package/dist/ui/charts/gaugeOption.d.ts.map +1 -0
  793. package/dist/ui/charts/heatmapOption.d.ts +38 -0
  794. package/dist/ui/charts/heatmapOption.d.ts.map +1 -0
  795. package/dist/ui/charts/hierarchyOption.d.ts +85 -0
  796. package/dist/ui/charts/hierarchyOption.d.ts.map +1 -0
  797. package/dist/ui/charts/highlight.d.ts +26 -0
  798. package/dist/ui/charts/highlight.d.ts.map +1 -0
  799. package/dist/ui/charts/image.d.ts +96 -0
  800. package/dist/ui/charts/image.d.ts.map +1 -0
  801. package/dist/ui/charts/legend.d.ts +11 -0
  802. package/dist/ui/charts/legend.d.ts.map +1 -0
  803. package/dist/ui/charts/load.d.ts +29 -0
  804. package/dist/ui/charts/load.d.ts.map +1 -0
  805. package/dist/ui/charts/mapOption.d.ts +39 -0
  806. package/dist/ui/charts/mapOption.d.ts.map +1 -0
  807. package/dist/ui/charts/maps.d.ts +53 -0
  808. package/dist/ui/charts/maps.d.ts.map +1 -0
  809. package/dist/ui/charts/markWords.d.ts +38 -0
  810. package/dist/ui/charts/markWords.d.ts.map +1 -0
  811. package/dist/ui/charts/measure.d.ts +2 -0
  812. package/dist/ui/charts/measure.d.ts.map +1 -0
  813. package/dist/ui/charts/motion.d.ts +15 -0
  814. package/dist/ui/charts/motion.d.ts.map +1 -0
  815. package/dist/ui/charts/optionMerge.d.ts +10 -0
  816. package/dist/ui/charts/optionMerge.d.ts.map +1 -0
  817. package/dist/ui/charts/palette.d.ts +43 -0
  818. package/dist/ui/charts/palette.d.ts.map +1 -0
  819. package/dist/ui/charts/patterns.d.ts +29 -0
  820. package/dist/ui/charts/patterns.d.ts.map +1 -0
  821. package/dist/ui/charts/periodSpan.d.ts +11 -0
  822. package/dist/ui/charts/periodSpan.d.ts.map +1 -0
  823. package/dist/ui/charts/pieOption.d.ts +107 -0
  824. package/dist/ui/charts/pieOption.d.ts.map +1 -0
  825. package/dist/ui/charts/print.d.ts +16 -0
  826. package/dist/ui/charts/print.d.ts.map +1 -0
  827. package/dist/ui/charts/profileOption.d.ts +47 -0
  828. package/dist/ui/charts/profileOption.d.ts.map +1 -0
  829. package/dist/ui/charts/reading.d.ts +66 -0
  830. package/dist/ui/charts/reading.d.ts.map +1 -0
  831. package/dist/ui/charts/readingStatistics.d.ts +58 -0
  832. package/dist/ui/charts/readingStatistics.d.ts.map +1 -0
  833. package/dist/ui/charts/scale.d.ts +42 -0
  834. package/dist/ui/charts/scale.d.ts.map +1 -0
  835. package/dist/ui/charts/scatterOption.d.ts +44 -0
  836. package/dist/ui/charts/scatterOption.d.ts.map +1 -0
  837. package/dist/ui/charts/sentence.d.ts +19 -0
  838. package/dist/ui/charts/sentence.d.ts.map +1 -0
  839. package/dist/ui/charts/sentenceParts.d.ts +36 -0
  840. package/dist/ui/charts/sentenceParts.d.ts.map +1 -0
  841. package/dist/ui/charts/sizes.d.ts +25 -0
  842. package/dist/ui/charts/sizes.d.ts.map +1 -0
  843. package/dist/ui/charts/sparklineOption.d.ts +19 -0
  844. package/dist/ui/charts/sparklineOption.d.ts.map +1 -0
  845. package/dist/ui/charts/theme.d.ts +179 -0
  846. package/dist/ui/charts/theme.d.ts.map +1 -0
  847. package/dist/ui/charts/timeOption.d.ts +54 -0
  848. package/dist/ui/charts/timeOption.d.ts.map +1 -0
  849. package/dist/ui/charts/tooltip.d.ts +51 -0
  850. package/dist/ui/charts/tooltip.d.ts.map +1 -0
  851. package/dist/ui/charts/treemapOption.d.ts +56 -0
  852. package/dist/ui/charts/treemapOption.d.ts.map +1 -0
  853. package/dist/ui/charts/waterfallOption.d.ts +58 -0
  854. package/dist/ui/charts/waterfallOption.d.ts.map +1 -0
  855. package/dist/ui/colorMode.d.ts +39 -0
  856. package/dist/ui/colorMode.d.ts.map +1 -0
  857. package/dist/ui/columns/ColumnRow.d.ts +79 -0
  858. package/dist/ui/columns/ColumnRow.d.ts.map +1 -0
  859. package/dist/ui/columns/ColumnSettings.d.ts +51 -0
  860. package/dist/ui/columns/ColumnSettings.d.ts.map +1 -0
  861. package/dist/ui/columns/WidthInput.d.ts +39 -0
  862. package/dist/ui/columns/WidthInput.d.ts.map +1 -0
  863. package/dist/ui/columns/drag.d.ts +34 -0
  864. package/dist/ui/columns/drag.d.ts.map +1 -0
  865. package/dist/ui/columns/rows.d.ts +155 -0
  866. package/dist/ui/columns/rows.d.ts.map +1 -0
  867. package/dist/ui/columns/sections.d.ts +55 -0
  868. package/dist/ui/columns/sections.d.ts.map +1 -0
  869. package/dist/ui/components/alert-dialog.d.ts +19 -0
  870. package/dist/ui/components/alert-dialog.d.ts.map +1 -0
  871. package/dist/ui/components/alert.d.ts +11 -0
  872. package/dist/ui/components/alert.d.ts.map +1 -0
  873. package/dist/ui/components/badge.d.ts +8 -0
  874. package/dist/ui/components/badge.d.ts.map +1 -0
  875. package/dist/ui/components/button-group.d.ts +11 -0
  876. package/dist/ui/components/button-group.d.ts.map +1 -0
  877. package/dist/ui/components/button.d.ts +9 -0
  878. package/dist/ui/components/button.d.ts.map +1 -0
  879. package/dist/ui/components/calendar.d.ts +11 -0
  880. package/dist/ui/components/calendar.d.ts.map +1 -0
  881. package/dist/ui/components/card.d.ts +12 -0
  882. package/dist/ui/components/card.d.ts.map +1 -0
  883. package/dist/ui/components/checkbox.d.ts +4 -0
  884. package/dist/ui/components/checkbox.d.ts.map +1 -0
  885. package/dist/ui/components/collapsible.d.ts +6 -0
  886. package/dist/ui/components/collapsible.d.ts.map +1 -0
  887. package/dist/ui/components/combobox.d.ts +25 -0
  888. package/dist/ui/components/combobox.d.ts.map +1 -0
  889. package/dist/ui/components/dialog.d.ts +18 -0
  890. package/dist/ui/components/dialog.d.ts.map +1 -0
  891. package/dist/ui/components/dropdown-menu.d.ts +30 -0
  892. package/dist/ui/components/dropdown-menu.d.ts.map +1 -0
  893. package/dist/ui/components/empty.d.ts +12 -0
  894. package/dist/ui/components/empty.d.ts.map +1 -0
  895. package/dist/ui/components/field.d.ts +25 -0
  896. package/dist/ui/components/field.d.ts.map +1 -0
  897. package/dist/ui/components/input-group.d.ts +19 -0
  898. package/dist/ui/components/input-group.d.ts.map +1 -0
  899. package/dist/ui/components/input.d.ts +4 -0
  900. package/dist/ui/components/input.d.ts.map +1 -0
  901. package/dist/ui/components/item.d.ts +23 -0
  902. package/dist/ui/components/item.d.ts.map +1 -0
  903. package/dist/ui/components/label.d.ts +4 -0
  904. package/dist/ui/components/label.d.ts.map +1 -0
  905. package/dist/ui/components/pagination.d.ts +18 -0
  906. package/dist/ui/components/pagination.d.ts.map +1 -0
  907. package/dist/ui/components/popover.d.ts +10 -0
  908. package/dist/ui/components/popover.d.ts.map +1 -0
  909. package/dist/ui/components/progress.d.ts +8 -0
  910. package/dist/ui/components/progress.d.ts.map +1 -0
  911. package/dist/ui/components/radio-group.d.ts +6 -0
  912. package/dist/ui/components/radio-group.d.ts.map +1 -0
  913. package/dist/ui/components/select.d.ts +16 -0
  914. package/dist/ui/components/select.d.ts.map +1 -0
  915. package/dist/ui/components/separator.d.ts +4 -0
  916. package/dist/ui/components/separator.d.ts.map +1 -0
  917. package/dist/ui/components/sheet.d.ts +15 -0
  918. package/dist/ui/components/sheet.d.ts.map +1 -0
  919. package/dist/ui/components/skeleton.d.ts +3 -0
  920. package/dist/ui/components/skeleton.d.ts.map +1 -0
  921. package/dist/ui/components/spinner.d.ts +3 -0
  922. package/dist/ui/components/spinner.d.ts.map +1 -0
  923. package/dist/ui/components/table.d.ts +11 -0
  924. package/dist/ui/components/table.d.ts.map +1 -0
  925. package/dist/ui/components/tabs.d.ts +11 -0
  926. package/dist/ui/components/tabs.d.ts.map +1 -0
  927. package/dist/ui/components/textarea.d.ts +4 -0
  928. package/dist/ui/components/textarea.d.ts.map +1 -0
  929. package/dist/ui/components/toast.d.ts +17 -0
  930. package/dist/ui/components/toast.d.ts.map +1 -0
  931. package/dist/ui/components/toggle-group.d.ts +12 -0
  932. package/dist/ui/components/toggle-group.d.ts.map +1 -0
  933. package/dist/ui/components/toggle.d.ts +9 -0
  934. package/dist/ui/components/toggle.d.ts.map +1 -0
  935. package/dist/ui/components/tooltip.d.ts +7 -0
  936. package/dist/ui/components/tooltip.d.ts.map +1 -0
  937. package/dist/ui/dashboard/AddMenu.d.ts +28 -0
  938. package/dist/ui/dashboard/AddMenu.d.ts.map +1 -0
  939. package/dist/ui/dashboard/Board.d.ts +49 -0
  940. package/dist/ui/dashboard/Board.d.ts.map +1 -0
  941. package/dist/ui/dashboard/BoardDestination.d.ts +48 -0
  942. package/dist/ui/dashboard/BoardDestination.d.ts.map +1 -0
  943. package/dist/ui/dashboard/BoardFilters.d.ts +58 -0
  944. package/dist/ui/dashboard/BoardFilters.d.ts.map +1 -0
  945. package/dist/ui/dashboard/BoardWidth.d.ts +15 -0
  946. package/dist/ui/dashboard/BoardWidth.d.ts.map +1 -0
  947. package/dist/ui/dashboard/ClickSettings.d.ts +30 -0
  948. package/dist/ui/dashboard/ClickSettings.d.ts.map +1 -0
  949. package/dist/ui/dashboard/ContentEditor.d.ts +40 -0
  950. package/dist/ui/dashboard/ContentEditor.d.ts.map +1 -0
  951. package/dist/ui/dashboard/DashboardArrange.d.ts +101 -0
  952. package/dist/ui/dashboard/DashboardArrange.d.ts.map +1 -0
  953. package/dist/ui/dashboard/DashboardGrid.d.ts +96 -0
  954. package/dist/ui/dashboard/DashboardGrid.d.ts.map +1 -0
  955. package/dist/ui/dashboard/DashboardPanel.d.ts +143 -0
  956. package/dist/ui/dashboard/DashboardPanel.d.ts.map +1 -0
  957. package/dist/ui/dashboard/DashboardPanels.d.ts +93 -0
  958. package/dist/ui/dashboard/DashboardPanels.d.ts.map +1 -0
  959. package/dist/ui/dashboard/DashboardTabs.d.ts +43 -0
  960. package/dist/ui/dashboard/DashboardTabs.d.ts.map +1 -0
  961. package/dist/ui/dashboard/EditBar.d.ts +55 -0
  962. package/dist/ui/dashboard/EditBar.d.ts.map +1 -0
  963. package/dist/ui/dashboard/EditableTabs.d.ts +32 -0
  964. package/dist/ui/dashboard/EditableTabs.d.ts.map +1 -0
  965. package/dist/ui/dashboard/FilterBar.d.ts +82 -0
  966. package/dist/ui/dashboard/FilterBar.d.ts.map +1 -0
  967. package/dist/ui/dashboard/FilterOrder.d.ts +40 -0
  968. package/dist/ui/dashboard/FilterOrder.d.ts.map +1 -0
  969. package/dist/ui/dashboard/FilterReadings.d.ts +41 -0
  970. package/dist/ui/dashboard/FilterReadings.d.ts.map +1 -0
  971. package/dist/ui/dashboard/FilterSettings.d.ts +32 -0
  972. package/dist/ui/dashboard/FilterSettings.d.ts.map +1 -0
  973. package/dist/ui/dashboard/FilterSheet.d.ts +24 -0
  974. package/dist/ui/dashboard/FilterSheet.d.ts.map +1 -0
  975. package/dist/ui/dashboard/FilterWiring.d.ts +47 -0
  976. package/dist/ui/dashboard/FilterWiring.d.ts.map +1 -0
  977. package/dist/ui/dashboard/GridBlocksLayer.d.ts +17 -0
  978. package/dist/ui/dashboard/GridBlocksLayer.d.ts.map +1 -0
  979. package/dist/ui/dashboard/GroupingControl.d.ts +10 -0
  980. package/dist/ui/dashboard/GroupingControl.d.ts.map +1 -0
  981. package/dist/ui/dashboard/NewAnalysisDialog.d.ts +41 -0
  982. package/dist/ui/dashboard/NewAnalysisDialog.d.ts.map +1 -0
  983. package/dist/ui/dashboard/PanelBodies.d.ts +101 -0
  984. package/dist/ui/dashboard/PanelBodies.d.ts.map +1 -0
  985. package/dist/ui/dashboard/PanelExport.d.ts +35 -0
  986. package/dist/ui/dashboard/PanelExport.d.ts.map +1 -0
  987. package/dist/ui/dashboard/PanelMarks.d.ts +43 -0
  988. package/dist/ui/dashboard/PanelMarks.d.ts.map +1 -0
  989. package/dist/ui/dashboard/PanelMenu.d.ts +56 -0
  990. package/dist/ui/dashboard/PanelMenu.d.ts.map +1 -0
  991. package/dist/ui/dashboard/PanelUnavailable.d.ts +45 -0
  992. package/dist/ui/dashboard/PanelUnavailable.d.ts.map +1 -0
  993. package/dist/ui/dashboard/PresentationDialog.d.ts +36 -0
  994. package/dist/ui/dashboard/PresentationDialog.d.ts.map +1 -0
  995. package/dist/ui/dashboard/ScrollCue.d.ts +21 -0
  996. package/dist/ui/dashboard/ScrollCue.d.ts.map +1 -0
  997. package/dist/ui/dashboard/ViewPicker.d.ts +59 -0
  998. package/dist/ui/dashboard/ViewPicker.d.ts.map +1 -0
  999. package/dist/ui/dashboard/buildShell.d.ts +44 -0
  1000. package/dist/ui/dashboard/buildShell.d.ts.map +1 -0
  1001. package/dist/ui/dashboard/building.d.ts +44 -0
  1002. package/dist/ui/dashboard/building.d.ts.map +1 -0
  1003. package/dist/ui/dashboard/commands.d.ts +131 -0
  1004. package/dist/ui/dashboard/commands.d.ts.map +1 -0
  1005. package/dist/ui/dashboard/extensions.d.ts +66 -0
  1006. package/dist/ui/dashboard/extensions.d.ts.map +1 -0
  1007. package/dist/ui/dashboard/filterModes.d.ts +60 -0
  1008. package/dist/ui/dashboard/filterModes.d.ts.map +1 -0
  1009. package/dist/ui/dashboard/filterOutcome.d.ts +24 -0
  1010. package/dist/ui/dashboard/filterOutcome.d.ts.map +1 -0
  1011. package/dist/ui/dashboard/findings.d.ts +24 -0
  1012. package/dist/ui/dashboard/findings.d.ts.map +1 -0
  1013. package/dist/ui/dashboard/gridBlocks.d.ts +55 -0
  1014. package/dist/ui/dashboard/gridBlocks.d.ts.map +1 -0
  1015. package/dist/ui/dashboard/gridPlacement.d.ts +38 -0
  1016. package/dist/ui/dashboard/gridPlacement.d.ts.map +1 -0
  1017. package/dist/ui/dashboard/gridWidth.d.ts +33 -0
  1018. package/dist/ui/dashboard/gridWidth.d.ts.map +1 -0
  1019. package/dist/ui/dashboard/history.d.ts +56 -0
  1020. package/dist/ui/dashboard/history.d.ts.map +1 -0
  1021. package/dist/ui/dashboard/landing.d.ts +13 -0
  1022. package/dist/ui/dashboard/landing.d.ts.map +1 -0
  1023. package/dist/ui/dashboard/panelFit.d.ts +43 -0
  1024. package/dist/ui/dashboard/panelFit.d.ts.map +1 -0
  1025. package/dist/ui/dashboard/press.d.ts +50 -0
  1026. package/dist/ui/dashboard/press.d.ts.map +1 -0
  1027. package/dist/ui/dashboard/reveal.d.ts +21 -0
  1028. package/dist/ui/dashboard/reveal.d.ts.map +1 -0
  1029. package/dist/ui/dashboard/scrollMore.d.ts +92 -0
  1030. package/dist/ui/dashboard/scrollMore.d.ts.map +1 -0
  1031. package/dist/ui/dashboard/touchGate.d.ts +30 -0
  1032. package/dist/ui/dashboard/touchGate.d.ts.map +1 -0
  1033. package/dist/ui/embed/EmbedFrame.d.ts +29 -0
  1034. package/dist/ui/embed/EmbedFrame.d.ts.map +1 -0
  1035. package/dist/ui/embed/EmbedHead.d.ts +81 -0
  1036. package/dist/ui/embed/EmbedHead.d.ts.map +1 -0
  1037. package/dist/ui/embed/EmbeddedAnalysis.d.ts +20 -0
  1038. package/dist/ui/embed/EmbeddedAnalysis.d.ts.map +1 -0
  1039. package/dist/ui/embed/EmbeddedRecord.d.ts +33 -0
  1040. package/dist/ui/embed/EmbeddedRecord.d.ts.map +1 -0
  1041. package/dist/ui/embed/options.d.ts +118 -0
  1042. package/dist/ui/embed/options.d.ts.map +1 -0
  1043. package/dist/ui/filter/AddEntry.d.ts +25 -0
  1044. package/dist/ui/filter/AddEntry.d.ts.map +1 -0
  1045. package/dist/ui/filter/AppliedBar.d.ts +39 -0
  1046. package/dist/ui/filter/AppliedBar.d.ts.map +1 -0
  1047. package/dist/ui/filter/ConditionPill.d.ts +38 -0
  1048. package/dist/ui/filter/ConditionPill.d.ts.map +1 -0
  1049. package/dist/ui/filter/FieldChecklist.d.ts +56 -0
  1050. package/dist/ui/filter/FieldChecklist.d.ts.map +1 -0
  1051. package/dist/ui/filter/FilterActions.d.ts +49 -0
  1052. package/dist/ui/filter/FilterActions.d.ts.map +1 -0
  1053. package/dist/ui/filter/FilterModes.d.ts +39 -0
  1054. package/dist/ui/filter/FilterModes.d.ts.map +1 -0
  1055. package/dist/ui/filter/FilterPanel.d.ts +76 -0
  1056. package/dist/ui/filter/FilterPanel.d.ts.map +1 -0
  1057. package/dist/ui/filter/FilterValueEditor.d.ts +103 -0
  1058. package/dist/ui/filter/FilterValueEditor.d.ts.map +1 -0
  1059. package/dist/ui/filter/GroupBlock.d.ts +49 -0
  1060. package/dist/ui/filter/GroupBlock.d.ts.map +1 -0
  1061. package/dist/ui/filter/conditionFocus.d.ts +39 -0
  1062. package/dist/ui/filter/conditionFocus.d.ts.map +1 -0
  1063. package/dist/ui/filter/enter.d.ts +20 -0
  1064. package/dist/ui/filter/enter.d.ts.map +1 -0
  1065. package/dist/ui/filter/groupOperators.d.ts +12 -0
  1066. package/dist/ui/filter/groupOperators.d.ts.map +1 -0
  1067. package/dist/ui/filter/inputs/calendar.d.ts +26 -0
  1068. package/dist/ui/filter/inputs/calendar.d.ts.map +1 -0
  1069. package/dist/ui/filter/inputs/candidates.d.ts +27 -0
  1070. package/dist/ui/filter/inputs/candidates.d.ts.map +1 -0
  1071. package/dist/ui/filter/inputs/chips.d.ts +56 -0
  1072. package/dist/ui/filter/inputs/chips.d.ts.map +1 -0
  1073. package/dist/ui/filter/inputs/date.d.ts +35 -0
  1074. package/dist/ui/filter/inputs/date.d.ts.map +1 -0
  1075. package/dist/ui/filter/inputs/daterange.d.ts +28 -0
  1076. package/dist/ui/filter/inputs/daterange.d.ts.map +1 -0
  1077. package/dist/ui/filter/inputs/duration.d.ts +16 -0
  1078. package/dist/ui/filter/inputs/duration.d.ts.map +1 -0
  1079. package/dist/ui/filter/inputs/number.d.ts +47 -0
  1080. package/dist/ui/filter/inputs/number.d.ts.map +1 -0
  1081. package/dist/ui/filter/inputs/relative.d.ts +23 -0
  1082. package/dist/ui/filter/inputs/relative.d.ts.map +1 -0
  1083. package/dist/ui/filter/inputs/remote.d.ts +20 -0
  1084. package/dist/ui/filter/inputs/remote.d.ts.map +1 -0
  1085. package/dist/ui/filter/inputs/select.d.ts +26 -0
  1086. package/dist/ui/filter/inputs/select.d.ts.map +1 -0
  1087. package/dist/ui/filter/inputs/shared.d.ts +79 -0
  1088. package/dist/ui/filter/inputs/shared.d.ts.map +1 -0
  1089. package/dist/ui/filter/inputs/suggested.d.ts +29 -0
  1090. package/dist/ui/filter/inputs/suggested.d.ts.map +1 -0
  1091. package/dist/ui/filter/inputs/text.d.ts +8 -0
  1092. package/dist/ui/filter/inputs/text.d.ts.map +1 -0
  1093. package/dist/ui/filter/inputs/time.d.ts +29 -0
  1094. package/dist/ui/filter/inputs/time.d.ts.map +1 -0
  1095. package/dist/ui/filter/inputs/timeOfDay.d.ts +38 -0
  1096. package/dist/ui/filter/inputs/timeOfDay.d.ts.map +1 -0
  1097. package/dist/ui/filter/inputs/unsupported.d.ts +33 -0
  1098. package/dist/ui/filter/inputs/unsupported.d.ts.map +1 -0
  1099. package/dist/ui/index.d.ts +123 -0
  1100. package/dist/ui/index.d.ts.map +1 -0
  1101. package/dist/ui/kit/Announcer.d.ts +75 -0
  1102. package/dist/ui/kit/Announcer.d.ts.map +1 -0
  1103. package/dist/ui/kit/CopyButton.d.ts +31 -0
  1104. package/dist/ui/kit/CopyButton.d.ts.map +1 -0
  1105. package/dist/ui/kit/DragHandle.d.ts +84 -0
  1106. package/dist/ui/kit/DragHandle.d.ts.map +1 -0
  1107. package/dist/ui/kit/ExportDialog.d.ts +111 -0
  1108. package/dist/ui/kit/ExportDialog.d.ts.map +1 -0
  1109. package/dist/ui/kit/ExportSteps.d.ts +38 -0
  1110. package/dist/ui/kit/ExportSteps.d.ts.map +1 -0
  1111. package/dist/ui/kit/FieldMenu.d.ts +22 -0
  1112. package/dist/ui/kit/FieldMenu.d.ts.map +1 -0
  1113. package/dist/ui/kit/HandOffMenu.d.ts +29 -0
  1114. package/dist/ui/kit/HandOffMenu.d.ts.map +1 -0
  1115. package/dist/ui/kit/IconButton.d.ts +74 -0
  1116. package/dist/ui/kit/IconButton.d.ts.map +1 -0
  1117. package/dist/ui/kit/MessagesProvider.d.ts +135 -0
  1118. package/dist/ui/kit/MessagesProvider.d.ts.map +1 -0
  1119. package/dist/ui/kit/MixedCheckbox.d.ts +16 -0
  1120. package/dist/ui/kit/MixedCheckbox.d.ts.map +1 -0
  1121. package/dist/ui/kit/OutcomeActions.d.ts +78 -0
  1122. package/dist/ui/kit/OutcomeActions.d.ts.map +1 -0
  1123. package/dist/ui/kit/PendingDot.d.ts +39 -0
  1124. package/dist/ui/kit/PendingDot.d.ts.map +1 -0
  1125. package/dist/ui/kit/RenameInput.d.ts +63 -0
  1126. package/dist/ui/kit/RenameInput.d.ts.map +1 -0
  1127. package/dist/ui/kit/RenderBoundary.d.ts +68 -0
  1128. package/dist/ui/kit/RenderBoundary.d.ts.map +1 -0
  1129. package/dist/ui/kit/RowItem.d.ts +31 -0
  1130. package/dist/ui/kit/RowItem.d.ts.map +1 -0
  1131. package/dist/ui/kit/StatusStrip.d.ts +114 -0
  1132. package/dist/ui/kit/StatusStrip.d.ts.map +1 -0
  1133. package/dist/ui/kit/SystemMark.d.ts +32 -0
  1134. package/dist/ui/kit/SystemMark.d.ts.map +1 -0
  1135. package/dist/ui/kit/Truncated.d.ts +25 -0
  1136. package/dist/ui/kit/Truncated.d.ts.map +1 -0
  1137. package/dist/ui/kit/ViewExpansion.d.ts +89 -0
  1138. package/dist/ui/kit/ViewExpansion.d.ts.map +1 -0
  1139. package/dist/ui/kit/ViewSurface.d.ts +100 -0
  1140. package/dist/ui/kit/ViewSurface.d.ts.map +1 -0
  1141. package/dist/ui/kit/alerts.d.ts +60 -0
  1142. package/dist/ui/kit/alerts.d.ts.map +1 -0
  1143. package/dist/ui/kit/anchor.d.ts +16 -0
  1144. package/dist/ui/kit/anchor.d.ts.map +1 -0
  1145. package/dist/ui/kit/badges.d.ts +34 -0
  1146. package/dist/ui/kit/badges.d.ts.map +1 -0
  1147. package/dist/ui/kit/band.d.ts +49 -0
  1148. package/dist/ui/kit/band.d.ts.map +1 -0
  1149. package/dist/ui/kit/chartFailure.d.ts +19 -0
  1150. package/dist/ui/kit/chartFailure.d.ts.map +1 -0
  1151. package/dist/ui/kit/copyText.d.ts +13 -0
  1152. package/dist/ui/kit/copyText.d.ts.map +1 -0
  1153. package/dist/ui/kit/cspNonce.d.ts +19 -0
  1154. package/dist/ui/kit/cspNonce.d.ts.map +1 -0
  1155. package/dist/ui/kit/currency.d.ts +26 -0
  1156. package/dist/ui/kit/currency.d.ts.map +1 -0
  1157. package/dist/ui/kit/datePart.d.ts +11 -0
  1158. package/dist/ui/kit/datePart.d.ts.map +1 -0
  1159. package/dist/ui/kit/display.d.ts +293 -0
  1160. package/dist/ui/kit/display.d.ts.map +1 -0
  1161. package/dist/ui/kit/download.d.ts +29 -0
  1162. package/dist/ui/kit/download.d.ts.map +1 -0
  1163. package/dist/ui/kit/dragAnnounce.d.ts +51 -0
  1164. package/dist/ui/kit/dragAnnounce.d.ts.map +1 -0
  1165. package/dist/ui/kit/dragDrop.d.ts +36 -0
  1166. package/dist/ui/kit/dragDrop.d.ts.map +1 -0
  1167. package/dist/ui/kit/dragPlugins.d.ts +35 -0
  1168. package/dist/ui/kit/dragPlugins.d.ts.map +1 -0
  1169. package/dist/ui/kit/dragWording.d.ts +15 -0
  1170. package/dist/ui/kit/dragWording.d.ts.map +1 -0
  1171. package/dist/ui/kit/failureSink.d.ts +19 -0
  1172. package/dist/ui/kit/failureSink.d.ts.map +1 -0
  1173. package/dist/ui/kit/features.d.ts +38 -0
  1174. package/dist/ui/kit/features.d.ts.map +1 -0
  1175. package/dist/ui/kit/focus.d.ts +54 -0
  1176. package/dist/ui/kit/focus.d.ts.map +1 -0
  1177. package/dist/ui/kit/kinds.d.ts +54 -0
  1178. package/dist/ui/kit/kinds.d.ts.map +1 -0
  1179. package/dist/ui/kit/layout.d.ts +77 -0
  1180. package/dist/ui/kit/layout.d.ts.map +1 -0
  1181. package/dist/ui/kit/messages.d.ts +56 -0
  1182. package/dist/ui/kit/messages.d.ts.map +1 -0
  1183. package/dist/ui/kit/numbers.d.ts +53 -0
  1184. package/dist/ui/kit/numbers.d.ts.map +1 -0
  1185. package/dist/ui/kit/popups.d.ts +83 -0
  1186. package/dist/ui/kit/popups.d.ts.map +1 -0
  1187. package/dist/ui/kit/presets.d.ts +42 -0
  1188. package/dist/ui/kit/presets.d.ts.map +1 -0
  1189. package/dist/ui/kit/roving.d.ts +32 -0
  1190. package/dist/ui/kit/roving.d.ts.map +1 -0
  1191. package/dist/ui/kit/summary.d.ts +45 -0
  1192. package/dist/ui/kit/summary.d.ts.map +1 -0
  1193. package/dist/ui/kit/toolbar.d.ts +92 -0
  1194. package/dist/ui/kit/toolbar.d.ts.map +1 -0
  1195. package/dist/ui/kit/variants.d.ts +464 -0
  1196. package/dist/ui/kit/variants.d.ts.map +1 -0
  1197. package/dist/ui/lib/utils.d.ts +2 -0
  1198. package/dist/ui/lib/utils.d.ts.map +1 -0
  1199. package/dist/ui/manage/DeleteDialog.d.ts +32 -0
  1200. package/dist/ui/manage/DeleteDialog.d.ts.map +1 -0
  1201. package/dist/ui/manage/ViewManager.d.ts +24 -0
  1202. package/dist/ui/manage/ViewManager.d.ts.map +1 -0
  1203. package/dist/ui/manage/ViewManagerRow.d.ts +96 -0
  1204. package/dist/ui/manage/ViewManagerRow.d.ts.map +1 -0
  1205. package/dist/ui/manage/drag.d.ts +33 -0
  1206. package/dist/ui/manage/drag.d.ts.map +1 -0
  1207. package/dist/ui/messages/actions.d.ts +32 -0
  1208. package/dist/ui/messages/actions.d.ts.map +1 -0
  1209. package/dist/ui/messages/analysis.d.ts +684 -0
  1210. package/dist/ui/messages/analysis.d.ts.map +1 -0
  1211. package/dist/ui/messages/building.d.ts +62 -0
  1212. package/dist/ui/messages/building.d.ts.map +1 -0
  1213. package/dist/ui/messages/bulk.d.ts +27 -0
  1214. package/dist/ui/messages/bulk.d.ts.map +1 -0
  1215. package/dist/ui/messages/capabilities.d.ts +38 -0
  1216. package/dist/ui/messages/capabilities.d.ts.map +1 -0
  1217. package/dist/ui/messages/clicks.d.ts +84 -0
  1218. package/dist/ui/messages/clicks.d.ts.map +1 -0
  1219. package/dist/ui/messages/config.d.ts +12 -0
  1220. package/dist/ui/messages/config.d.ts.map +1 -0
  1221. package/dist/ui/messages/dashboard.d.ts +310 -0
  1222. package/dist/ui/messages/dashboard.d.ts.map +1 -0
  1223. package/dist/ui/messages/definition.d.ts +71 -0
  1224. package/dist/ui/messages/definition.d.ts.map +1 -0
  1225. package/dist/ui/messages/embed.d.ts +11 -0
  1226. package/dist/ui/messages/embed.d.ts.map +1 -0
  1227. package/dist/ui/messages/en.d.ts +2098 -0
  1228. package/dist/ui/messages/en.d.ts.map +1 -0
  1229. package/dist/ui/messages/export.d.ts +50 -0
  1230. package/dist/ui/messages/export.d.ts.map +1 -0
  1231. package/dist/ui/messages/filter.d.ts +263 -0
  1232. package/dist/ui/messages/filter.d.ts.map +1 -0
  1233. package/dist/ui/messages/filters.d.ts +78 -0
  1234. package/dist/ui/messages/filters.d.ts.map +1 -0
  1235. package/dist/ui/messages/header.d.ts +14 -0
  1236. package/dist/ui/messages/header.d.ts.map +1 -0
  1237. package/dist/ui/messages/manage.d.ts +35 -0
  1238. package/dist/ui/messages/manage.d.ts.map +1 -0
  1239. package/dist/ui/messages/record.d.ts +172 -0
  1240. package/dist/ui/messages/record.d.ts.map +1 -0
  1241. package/dist/ui/messages/refresh.d.ts +19 -0
  1242. package/dist/ui/messages/refresh.d.ts.map +1 -0
  1243. package/dist/ui/messages/render.d.ts +11 -0
  1244. package/dist/ui/messages/render.d.ts.map +1 -0
  1245. package/dist/ui/messages/reorder.d.ts +19 -0
  1246. package/dist/ui/messages/reorder.d.ts.map +1 -0
  1247. package/dist/ui/messages/save.d.ts +59 -0
  1248. package/dist/ui/messages/save.d.ts.map +1 -0
  1249. package/dist/ui/messages/scope.d.ts +28 -0
  1250. package/dist/ui/messages/scope.d.ts.map +1 -0
  1251. package/dist/ui/messages/status.d.ts +28 -0
  1252. package/dist/ui/messages/status.d.ts.map +1 -0
  1253. package/dist/ui/messages/view.d.ts +160 -0
  1254. package/dist/ui/messages/view.d.ts.map +1 -0
  1255. package/dist/ui/messages/workbench.d.ts +21 -0
  1256. package/dist/ui/messages/workbench.d.ts.map +1 -0
  1257. package/dist/ui/messages/zh-CN.d.ts +12 -0
  1258. package/dist/ui/messages/zh-CN.d.ts.map +1 -0
  1259. package/dist/ui/record/CardSettings.d.ts +34 -0
  1260. package/dist/ui/record/CardSettings.d.ts.map +1 -0
  1261. package/dist/ui/record/CardSummaries.d.ts +15 -0
  1262. package/dist/ui/record/CardSummaries.d.ts.map +1 -0
  1263. package/dist/ui/record/ColumnResizer.d.ts +67 -0
  1264. package/dist/ui/record/ColumnResizer.d.ts.map +1 -0
  1265. package/dist/ui/record/DetailStructure.d.ts +51 -0
  1266. package/dist/ui/record/DetailStructure.d.ts.map +1 -0
  1267. package/dist/ui/record/EmptyResult.d.ts +41 -0
  1268. package/dist/ui/record/EmptyResult.d.ts.map +1 -0
  1269. package/dist/ui/record/Filler.d.ts +47 -0
  1270. package/dist/ui/record/Filler.d.ts.map +1 -0
  1271. package/dist/ui/record/OffscreenSummary.d.ts +46 -0
  1272. package/dist/ui/record/OffscreenSummary.d.ts.map +1 -0
  1273. package/dist/ui/record/RecordCards.d.ts +53 -0
  1274. package/dist/ui/record/RecordCards.d.ts.map +1 -0
  1275. package/dist/ui/record/RecordDetail.d.ts +45 -0
  1276. package/dist/ui/record/RecordDetail.d.ts.map +1 -0
  1277. package/dist/ui/record/RecordPagination.d.ts +32 -0
  1278. package/dist/ui/record/RecordPagination.d.ts.map +1 -0
  1279. package/dist/ui/record/RecordTable.d.ts +118 -0
  1280. package/dist/ui/record/RecordTable.d.ts.map +1 -0
  1281. package/dist/ui/record/RowActions.d.ts +14 -0
  1282. package/dist/ui/record/RowActions.d.ts.map +1 -0
  1283. package/dist/ui/record/RowCheckbox.d.ts +30 -0
  1284. package/dist/ui/record/RowCheckbox.d.ts.map +1 -0
  1285. package/dist/ui/record/SelectionBar.d.ts +26 -0
  1286. package/dist/ui/record/SelectionBar.d.ts.map +1 -0
  1287. package/dist/ui/record/SkeletonCards.d.ts +11 -0
  1288. package/dist/ui/record/SkeletonCards.d.ts.map +1 -0
  1289. package/dist/ui/record/SkeletonRows.d.ts +33 -0
  1290. package/dist/ui/record/SkeletonRows.d.ts.map +1 -0
  1291. package/dist/ui/record/SortableHeader.d.ts +75 -0
  1292. package/dist/ui/record/SortableHeader.d.ts.map +1 -0
  1293. package/dist/ui/record/SummaryRows.d.ts +43 -0
  1294. package/dist/ui/record/SummaryRows.d.ts.map +1 -0
  1295. package/dist/ui/record/cells.d.ts +41 -0
  1296. package/dist/ui/record/cells.d.ts.map +1 -0
  1297. package/dist/ui/record/columns.d.ts +190 -0
  1298. package/dist/ui/record/columns.d.ts.map +1 -0
  1299. package/dist/ui/record/detailPlacement.d.ts +24 -0
  1300. package/dist/ui/record/detailPlacement.d.ts.map +1 -0
  1301. package/dist/ui/record/emptyWayOut.d.ts +59 -0
  1302. package/dist/ui/record/emptyWayOut.d.ts.map +1 -0
  1303. package/dist/ui/record/exportOffer.d.ts +47 -0
  1304. package/dist/ui/record/exportOffer.d.ts.map +1 -0
  1305. package/dist/ui/record/headerRoving.d.ts +57 -0
  1306. package/dist/ui/record/headerRoving.d.ts.map +1 -0
  1307. package/dist/ui/record/issueNames.d.ts +25 -0
  1308. package/dist/ui/record/issueNames.d.ts.map +1 -0
  1309. package/dist/ui/record/offscreenSummaries.d.ts +81 -0
  1310. package/dist/ui/record/offscreenSummaries.d.ts.map +1 -0
  1311. package/dist/ui/record/openRows.d.ts +43 -0
  1312. package/dist/ui/record/openRows.d.ts.map +1 -0
  1313. package/dist/ui/record/overflow.d.ts +39 -0
  1314. package/dist/ui/record/overflow.d.ts.map +1 -0
  1315. package/dist/ui/record/pinCap.d.ts +68 -0
  1316. package/dist/ui/record/pinCap.d.ts.map +1 -0
  1317. package/dist/ui/record/queryAnnouncement.d.ts +47 -0
  1318. package/dist/ui/record/queryAnnouncement.d.ts.map +1 -0
  1319. package/dist/ui/record/roomBelowRows.d.ts +24 -0
  1320. package/dist/ui/record/roomBelowRows.d.ts.map +1 -0
  1321. package/dist/ui/record/sticky.d.ts +227 -0
  1322. package/dist/ui/record/sticky.d.ts.map +1 -0
  1323. package/dist/ui/record/summaryText.d.ts +10 -0
  1324. package/dist/ui/record/summaryText.d.ts.map +1 -0
  1325. package/dist/ui/record/useOffscreenColumns.d.ts +36 -0
  1326. package/dist/ui/record/useOffscreenColumns.d.ts.map +1 -0
  1327. package/dist/ui/record/useSummaries.d.ts +31 -0
  1328. package/dist/ui/record/useSummaries.d.ts.map +1 -0
  1329. package/dist/ui/sort/SortSettings.d.ts +47 -0
  1330. package/dist/ui/sort/SortSettings.d.ts.map +1 -0
  1331. package/dist/ui/sort/drag.d.ts +53 -0
  1332. package/dist/ui/sort/drag.d.ts.map +1 -0
  1333. package/dist/ui/theme/brandDocs.d.ts +15 -0
  1334. package/dist/ui/theme/brandDocs.d.ts.map +1 -0
  1335. package/dist/ui/theme/densityDocs.d.ts +9 -0
  1336. package/dist/ui/theme/densityDocs.d.ts.map +1 -0
  1337. package/dist/ui/theme/pairs.d.ts +138 -0
  1338. package/dist/ui/theme/pairs.d.ts.map +1 -0
  1339. package/dist/ui/theme/stateDocs.d.ts +149 -0
  1340. package/dist/ui/theme/stateDocs.d.ts.map +1 -0
  1341. package/dist/ui/theme/tokenDocs.d.ts +25 -0
  1342. package/dist/ui/theme/tokenDocs.d.ts.map +1 -0
  1343. package/dist/ui/theme/tokens.d.ts +1526 -0
  1344. package/dist/ui/theme/tokens.d.ts.map +1 -0
  1345. package/dist/ui/viewNavigation.d.ts +39 -0
  1346. package/dist/ui/viewNavigation.d.ts.map +1 -0
  1347. package/dist/ui/workbench/AnalysisParts.d.ts +57 -0
  1348. package/dist/ui/workbench/AnalysisParts.d.ts.map +1 -0
  1349. package/dist/ui/workbench/ConditionBlock.d.ts +20 -0
  1350. package/dist/ui/workbench/ConditionBlock.d.ts.map +1 -0
  1351. package/dist/ui/workbench/ConflictConfirm.d.ts +21 -0
  1352. package/dist/ui/workbench/ConflictConfirm.d.ts.map +1 -0
  1353. package/dist/ui/workbench/EditorBand.d.ts +73 -0
  1354. package/dist/ui/workbench/EditorBand.d.ts.map +1 -0
  1355. package/dist/ui/workbench/LeaveGuard.d.ts +27 -0
  1356. package/dist/ui/workbench/LeaveGuard.d.ts.map +1 -0
  1357. package/dist/ui/workbench/NewView.d.ts +40 -0
  1358. package/dist/ui/workbench/NewView.d.ts.map +1 -0
  1359. package/dist/ui/workbench/NoViews.d.ts +22 -0
  1360. package/dist/ui/workbench/NoViews.d.ts.map +1 -0
  1361. package/dist/ui/workbench/OpeningSkeleton.d.ts +35 -0
  1362. package/dist/ui/workbench/OpeningSkeleton.d.ts.map +1 -0
  1363. package/dist/ui/workbench/OriginBar.d.ts +20 -0
  1364. package/dist/ui/workbench/OriginBar.d.ts.map +1 -0
  1365. package/dist/ui/workbench/RecordParts.d.ts +135 -0
  1366. package/dist/ui/workbench/RecordParts.d.ts.map +1 -0
  1367. package/dist/ui/workbench/RefreshControl.d.ts +70 -0
  1368. package/dist/ui/workbench/RefreshControl.d.ts.map +1 -0
  1369. package/dist/ui/workbench/ResultBlock.d.ts +88 -0
  1370. package/dist/ui/workbench/ResultBlock.d.ts.map +1 -0
  1371. package/dist/ui/workbench/ResultToolbar.d.ts +109 -0
  1372. package/dist/ui/workbench/ResultToolbar.d.ts.map +1 -0
  1373. package/dist/ui/workbench/SaveActions.d.ts +76 -0
  1374. package/dist/ui/workbench/SaveActions.d.ts.map +1 -0
  1375. package/dist/ui/workbench/SaveAsDialog.d.ts +66 -0
  1376. package/dist/ui/workbench/SaveAsDialog.d.ts.map +1 -0
  1377. package/dist/ui/workbench/SearchBox.d.ts +18 -0
  1378. package/dist/ui/workbench/SearchBox.d.ts.map +1 -0
  1379. package/dist/ui/workbench/Sidebar.d.ts +50 -0
  1380. package/dist/ui/workbench/Sidebar.d.ts.map +1 -0
  1381. package/dist/ui/workbench/StatusLine.d.ts +31 -0
  1382. package/dist/ui/workbench/StatusLine.d.ts.map +1 -0
  1383. package/dist/ui/workbench/TitleBar.d.ts +39 -0
  1384. package/dist/ui/workbench/TitleBar.d.ts.map +1 -0
  1385. package/dist/ui/workbench/Unopenable.d.ts +19 -0
  1386. package/dist/ui/workbench/Unopenable.d.ts.map +1 -0
  1387. package/dist/ui/workbench/ViewEngineProvider.d.ts +93 -0
  1388. package/dist/ui/workbench/ViewEngineProvider.d.ts.map +1 -0
  1389. package/dist/ui/workbench/ViewHeader.d.ts +123 -0
  1390. package/dist/ui/workbench/ViewHeader.d.ts.map +1 -0
  1391. package/dist/ui/workbench/ViewList.d.ts +71 -0
  1392. package/dist/ui/workbench/ViewList.d.ts.map +1 -0
  1393. package/dist/ui/workbench/ViewSwitcher.d.ts +49 -0
  1394. package/dist/ui/workbench/ViewSwitcher.d.ts.map +1 -0
  1395. package/dist/ui/workbench/WorkbenchShell.d.ts +291 -0
  1396. package/dist/ui/workbench/WorkbenchShell.d.ts.map +1 -0
  1397. package/dist/ui/workbench/WriteOutcome.d.ts +51 -0
  1398. package/dist/ui/workbench/WriteOutcome.d.ts.map +1 -0
  1399. package/dist/ui/workbench/address.d.ts +84 -0
  1400. package/dist/ui/workbench/address.d.ts.map +1 -0
  1401. package/dist/ui/workbench/bindings.d.ts +45 -0
  1402. package/dist/ui/workbench/bindings.d.ts.map +1 -0
  1403. package/dist/ui/workbench/configRemedy.d.ts +28 -0
  1404. package/dist/ui/workbench/configRemedy.d.ts.map +1 -0
  1405. package/dist/ui/workbench/describeConfig.d.ts +23 -0
  1406. package/dist/ui/workbench/describeConfig.d.ts.map +1 -0
  1407. package/dist/ui/workbench/panelsToFix.d.ts +43 -0
  1408. package/dist/ui/workbench/panelsToFix.d.ts.map +1 -0
  1409. package/dist/ui/workbench/parts.d.ts +33 -0
  1410. package/dist/ui/workbench/parts.d.ts.map +1 -0
  1411. package/dist/ui/workbench/useEditorFold.d.ts +26 -0
  1412. package/dist/ui/workbench/useEditorFold.d.ts.map +1 -0
  1413. package/dist/ui/workbench/useSidebarFold.d.ts +57 -0
  1414. package/dist/ui/workbench/useSidebarFold.d.ts.map +1 -0
  1415. package/dist/ui/workbench/useWorkbenchFolds.d.ts +44 -0
  1416. package/dist/ui/workbench/useWorkbenchFolds.d.ts.map +1 -0
  1417. package/dist/ui.js +43488 -0
  1418. package/dist/ui.js.map +1 -0
  1419. package/dist/viewRuntimeTypes-yK2rlUjK.js +5482 -0
  1420. package/dist/viewRuntimeTypes-yK2rlUjK.js.map +1 -0
  1421. package/package.json +168 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"viewRuntimeTypes-yK2rlUjK.js","names":["ANALYSIS_AUTO_RUN_MEMBERS","ANALYSIS_PRESENTATION_MEMBERS","AnalysisViewConfig","DASHBOARD_PRESENTATION_MEMBERS","DashboardViewConfig","FilterMode","FilterTree","RECORD_PRESENTATION_MEMBERS","RecordViewConfig","ViewConfigBase","refresh","RefreshConfig","DataViewConfigBase","filter","filterMode","interval","ViewConfig","DataViewConfig","ViewKind","VIEW_KINDS","ConfigOfKind","Extract","kind","K","DATA_PRESENTATION_MEMBERS","const","BY_KIND","Record","record","analysis","dashboard","presentationMembers","AUTO_RUN_BY_KIND","autoRunMembers","Issue","code","severity","IssueSeverity","path","IssuePath","params","Record","LIST_PARAM_SEPARATOR","listParam","items","join","Issue","IssuePath","FilterPath","isRootFilterIssue","found","path","length","filterIndexes","filter","segment","FilterNode","FilterTree","Issue","filterIndexes","isFilterGroup","isFilterLeaf","nodeAt","FilterPath","unmarkedErrors","issues","tree","filter","found","severity","isMarked","code","startsWith","path","conditionAt","node","index","group","groupOf","value","FieldDefinition","FilterLeaf","FilterNode","FilterTree","rootSearch","tree","field","op","leaf","children","find","node","isLeaf","value","withRootSearch","text","blank","trim","length","root","at","findIndex","filter","_","i","operator","map","searchFieldOf","fields","kind","operators","isFieldlessKind","DEFAULT_RUNTIME_LIMITS","DataViewDefinition","RecordCapability","RecordViewConfig","RuntimeLimits","ViewDefinition","nearestPageSize","emptyFilter","recordCapabilityOf","definition","kind","record","undefined","defaultRecordConfig","limits","capability","Error","id","names","fields","filter","field","map","name","defaults","layout","layouts","pageSize","Math","min","cardPageSizes","defaultPageSize","maxPageSize","filterMode","refresh","interval","sort","summaries","table","columns","slice","defaultColumns","card","title","rowKey","defaultCardFields","isFieldlessKind","DataViewDefinition","cardField","RecordCardField","DetailSection","id","label","fields","detailSections","definition","Pick","valued","filter","field","kind","byName","Map","map","name","placed","Set","sections","group","fieldGroups","flatMap","get","has","add","length","push","rest","AggregationGroupType","DEFAULT_RUNTIME_LIMITS","isSingleStringField","AnalysisGroup","AnalysisMetric","AnalysisViewConfig","DataViewDefinition","FieldDefinition","FilterOperatorName","RecordData","RuntimeLimits","operatorsOf","FieldKindRegistry","fitChartSlots","analysisProbeLimit","limitBounds","VALUE_CANDIDATE_LIMIT","VALUE_CANDIDATE_OPERATORS","ValueCandidate","value","count","ValueCandidates","values","complete","VALUE","COUNT","valueCandidateField","definition","name","kinds","capability","analysis","field","fields","find","entry","options","remote","kind","get","groupable","some","groups","includes","TERMS","valueCandidateNarrowing","offered","valueCandidateLimit","limits","Math","min","max","valueCandidatesConfig","query","text","trim","narrowing","group","type","alias","metric","filter","op","children","operator","filterMode","refresh","interval","metrics","sort","metricSort","direction","limit","layout","table","columns","chart","Set","readValueCandidates","config","rows","Pick","probe","length","slice","flatMap","row","narrowValueCandidates","sensitive","stringComparison","fold","toLowerCase","wanted","prefix","startsWith","isValueMetric","AnalysisHavingExpression","AnalysisMetric","AnalysisViewConfig","DanglingFacts","moments","ReadonlySet","havingMetrics","WithoutDangling","metrics","having","removed","Shape","Pick","DanglingBefore","shape","facts","withoutDangling","before","dangling","danglingIn","was","untouched","metric","undefined","some","entry","has","alias","filter","map","length","includes","now","comparableIn","then","stands","ungrouped","groups","kept","Set","readable","type","derivedRefs","expression","every","add","node","Array","isArray","operands","operand","at","left","Extract","right","kept","groupFieldsOf","AnalysisCapability","AnalysisElement","AnalysisGroup","AnalysisMetric","AnalysisViewConfig","DataViewDefinition","FieldDefinition","filterFields","analysisScope","AnalysisScope","withoutDangling","firstMetric","momentMetrics","withElements","config","elements","definition","capability","Rescoped","scope","inScope","field","fields","has","groups","filter","group","every","kept","metrics","metric","measuresInScope","map","type","withoutFilter","derivable","moments","shape","facts","next","length","count","aggregations","values","stays","Set","alias","dropped","includes","Dropped","Pick","withLevel","path","withoutLevelsFrom","index","slice","Math","max","nextExpansion","declaredChain","holderFields","depth","outer","name","absolute","levelLabel","level","find","label","nextLevel","undefined","orderBy","expressionFields","expression","Extract","left","right","from","to","AnalysisDateUnit","AnalysisGroup","FilterTree","RecordData","readInstant","bucketRange","appliedWindow","UNIT_MS","Record","SECOND","MINUTE","HOUR","DAY","WEEK","MONTH","QUARTER","YEAR","FINE_TO_COARSE","MIN_BUCKETS","recommendDateUnit","span","offered","first","Number","isFinite","candidates","filter","unit","includes","length","at","rangeSpan","field","now","Date","timeZone","from","to","end","getTime","resultSpan","rows","groups","group","find","entry","type","last","row","start","alias","ms","undefined","Math","min","max","AnalysisHavingExpression","HavingOperator","Extract","type","HAVING_OPERATOR_ORDER","Record","GT","GTE","LT","LTE","EQ","NE","HAVING_OPERATORS","Object","keys","HavingRow","metric","operator","value","havingRows","having","rows","operand","operands","inner","push","withHavingRows","complete","filter","row","conditions","map","length","undefined","DASHBOARD_GRID_COLUMNS","DashboardViewConfig","emptyFilter","emptyDashboardConfig","refresh","interval","kind","columns","width","fixed","tabs","fields","panels","DASHBOARD_GRID_COLUMNS","hasFixedHeight","DashboardPanel","DashboardViewConfig","PanelLayout","isPlainObject","panelsOf","panelTab","validateLayout","ArrangeStep","fitsGrid","layout","columns","length","PlacedPanel","id","overlaps","a","b","x","w","y","h","bottomOf","panels","reduce","bottom","panel","Math","max","compactLayout","compactAround","placePanel","at","findIndex","held","geometry","others","arrangePanel","step","find","entry","resting","reach","distance","target","stepped","placed","samePlacement","freeSpot","size","fromRow","min","boxes","map","spot","some","box","settle","placePanelIn","config","grown","ReadonlyMap","tabBoxes","shown","grownLayout","saved","savedPlacement","withLayouts","fixedHeight","undefined","stored","Map","drawnBefore","heightOf","own","get","resized","read","readingOrder","drawnFloor","savedFloor","above","settled","stacked","set","below","moving","tab","flatMap","moved","changed","next","current","fixed","sameLayout","T","sort","STACKED_COLUMNS","stackedLayout","paired","push","marked","heights","from","to","floor","grownFloor","OrderStep","reorderPanel","order","readOf","indexOf","other","wanted","best","cost","consider","shuffled","disturbance","before","traded","mover","reorderPanelIn","Number","isInteger","skip","out","_","index","filter","hit","one","two","corner","place","pairs","forEach","i","slice","pair","rows","includes","abs","differs","value","every","DASHBOARD_GRID_COLUMNS","DASHBOARD_WIDTHS","DEFAULT_RUNTIME_LIMITS","DashboardWidth","DashboardContentPanel","DashboardPanel","DashboardViewConfig","DashboardViewPanel","OwnedView","PanelBinding","PanelPresentation","ViewConfig","hasFixedHeight","overlaid","without","isPlainObject","compactLayout","fitsGrid","freeSpot","withLayouts","PlacedPanel","freshId","isViewPanel","panelTab","NewContentPanel","P","Omit","NewViewPanel","kind","title","bindings","instanceId","owned","NewPanel","NewPanelPlacement","tab","fromRow","size","w","h","view","max","defaultPanelSize","panel","Pick","config","layout","chart","type","addPanel","placement","id","maxDashboardPanels","panels","length","tabOf","boxesOn","map","entry","undefined","added","removePanel","find","rest","filter","compactTab","duplicatePanel","copy","y","withFixedHeight","mapPanel","fixedHeight","renamePanel","name","trim","replacePanelView","mapViewPanel","presentation","opens","stored","Array","isArray","derived","referToSaved","setPresentation","next","Object","keys","editContent","patch","Partial","edited","movePanelToTab","tabs","some","from","moved","setBoardWidth","width","includes","flatMap","wanted","change","without","filterTypeOf","sameFilterType","DashboardField","DashboardPanel","DashboardViewConfig","DashboardViewPanel","FieldDefinition","PanelBinding","isPlainObject","filtersOf","bindingsOf","isViewPanel","panelsOf","timeFilterOf","config","dated","dateFilters","length","isDateFilter","filter","undefined","kind","PanelTime","panel","withTimeBindings","timeOf","changed","panels","map","stored","storedBindings","kept","entry","isDerived","time","ignoresTime","written","some","globalField","name","wire","panelField","auto","derived","next","sameWires","bindings","marked","derivesTime","storedTimeWires","withTimeIgnored","wired","Set","every","has","Array","isArray","one","other","index","JSON","stringify","filterTypeOf","sameFilterType","DashboardField","DashboardPanel","DashboardViewConfig","DashboardViewPanel","FieldDefinition","FieldOption","OwnedView","PanelBinding","without","searchFieldOf","filtersOf","bindingsOf","clicksFilter","isViewPanel","isDateFilter","DataPanelSource","instanceId","owned","title","PanelFields","panel","FilterReach","wired","field","auto","why","wireableFields","Pick","fields","filter","candidate","kind","filterReach","config","Record","reach","bindings","binding","find","entry","globalField","name","panelField","length","filtersOnTab","panels","tab","Readonly","Set","reaching","Object","entries","add","bindPanel","panelId","fieldsOf","connected","same","viewPanel","target","dated","map","wire","wiredTo","ignoresTime","match","autoField","push","id","remote","undefined","unbindPanels","panelIds","byHand","changed","time","includes","rest","const","wiredOptions","merged","Map","option","options","key","value","String","has","set","label","size","values","autoBindings","given","some","wiredNames","names","counts","get","sort","a","b","without","DASHBOARD_FILTER_KINDS","MAX_DASHBOARD_FILTERS","filterTypeOf","DashboardField","DashboardFilterType","DashboardTimeGrouping","DashboardViewConfig","FieldOption","FilterValue","without","emptyFilter","isPlainObject","filtersOf","fieldsOf","isOneDayValue","freshId","isViewPanel","unbindPanels","NewFilter","type","label","addFilter","config","filter","name","fields","length","map","field","trim","kind","renameFilter","next","mapFilter","retypeFilter","find","entry","retyped","multiple","const","unwire","removeFilter","some","setFilterDefault","value","default","undefined","setFilterRequired","required","setFilterOneDay","oneDay","start","kept","setFilterMultiple","single","Array","isArray","slice","items","setFilterOptions","options","moveFilter","index","from","findIndex","to","Math","max","min","trunc","moved","splice","setTimeGrouping","grouping","timeGrouping","removeFixedScope","fixed","empty","op","children","change","ids","panels","flatMap","panel","id","byHand","fieldsOf","without","QueryViolation","RecordKey","RuntimeEnvironment","now","Date","timeZone","setTimeout","callback","ms","clearTimeout","handle","visibility","VisibilitySource","onError","event","ViewErrorEvent","ViewErrorKind","ViewErrorContext","operation","recordKey","definitionId","instanceId","runtimeId","requestId","boundary","panelId","componentStack","violation","errorCode","kind","error","context","isVisible","subscribe","listener","ALWAYS_VISIBLE","defaultRuntimeEnvironment","overrides","Partial","Intl","DateTimeFormat","resolvedOptions","globalThis","ReturnType","DEFAULT_RUNTIME_LIMITS","RuntimeLimits","RequestTask","controller","AbortController","Promise","T","RequestSupersededError","Error","key","constructor","name","RequestQueueFullError","limit","isRequestSuperseded","error","Entry","task","resolve","value","reject","reason","started","RequestRunner","maxConcurrent","maxQueued","byKey","Map","queue","running","reserved","limits","maxConcurrentQueries","maxQueuedQueries","active","queued","length","capacity","reserve","slots","held","Math","max","floor","released","run","previous","get","freed","cancel","entry","set","push","pump","delete","at","indexOf","splice","abort","cancelAll","keys","shift","then","settle","deliver","withTimeIgnored","DASHBOARD_GRID_COLUMNS","filterTypeOf","LEGACY_GRID_COLUMNS","DashboardField","DashboardViewConfig","FilterNode","FilterValue","emptyFilter","isEmptyFilter","isFilterGroup","isPlainObject","FILTER_TYPE_OPERATOR","SCALE","migrateDashboardConfig","config","withoutOwnCondition","intoDefaults","onTheWideGrid","stored","panels","columns","tabs","Array","isArray","map","widened","tree","filter","fixed","fields","byName","Map","field","name","set","defaults","kept","child","op","children","leafField","undefined","value","has","default","asDefault","Record","push","without","size","get","joined","conjuncts","node","members","read","member","ReadonlyMap","keys","Object","sort","join","leaf","type","kind","operator","length","multiple","panel","layout","x","scaled","w","conjuncts","filterTypeOf","DataViewConfig","FieldDefinition","boardFieldsOf","view","fields","filter","field","kind","sameJson","AnalysisViewConfig","DashboardPanel","DashboardViewConfig","DashboardViewPanel","isPlainObject","isViewPanel","panelsOf","URL_PLACEHOLDER","PanelRenames","panel","Readonly","Record","OwnedViewRename","config","renamed","withCanonicalPanelFields","renamedOf","ownedView","changed","panels","map","Object","keys","length","next","renamedPanel","name","field","bindings","Array","isArray","entry","panelField","click","renamedClick","owned","kind","url","replace","whole","values","fromEntries","entries","filter","source","dimension","QueryDescriptorResult","QueryModelDescriptor","Describe","previous","Promise","DESCRIPTOR_MAX_AGE_MS","DESCRIBE_DEADLINE_MS","DescriptorCacheOptions","now","changed","key","descriptor","failed","error","maxAge","Entry","describe","checkedAt","inflight","DescriptorCache","options","entries","Map","constructor","current","get","load","entry","set","check","revalidate","force","resolve","stale","revalidateStale","keys","read","answer","version","notModified","before","QueryModelDescriptor","DEFAULT_RUNTIME_LIMITS","RuntimeLimits","SOURCE_LIMIT_NAMES","const","SourceLimitName","sourceLimits","host","Partial","descriptor","base","limits","largestRung","Math","max","defaultPageSize","pageSizes","cardPageSizes","described","Record","maxPageSize","maxPageWindow","Number","POSITIVE_INFINITY","maxAnalysisRows","aggregation","maxLimit","maxQueryFilterNodes","maxFilterNodes","maxFilterValues","next","name","own","undefined","min","QueryErrorCodes","CAPABILITY_CODES","ReadonlySet","Set","UNKNOWN_FIELD","UNSUPPORTED_CAPABILITY","MODEL_SEARCH_UNSUPPORTED","CURSOR_NOT_ALLOWED","ELEMENT_SCOPE_REQUIRED","PROTECTED_AGGREGATION","PROTECTED_COMPARISON","MISSING_KEY_REQUIRES_STRING","ANY_REQUIRES_SINGLE_VALUE","METRIC_FILTER_SEARCH","METRIC_FILTER_ELEMENT_MATCH","METRIC_FILTER_ARRAY_FIELD","INCOMPLETE_PROJECTION","NOT_PROJECTABLE","TEMPORAL_AGGREGATION_UNSUPPORTED","IDENTITY_UNDEFINED","STORAGE_UNSUPPORTED","SIZE_OUT_OF_RANGE","FILTER_TOO_LARGE","EXPENSIVE_OPERATOR_DISABLED","COUNT_REQUIRES_FILTER","SORT_TOO_MANY","BUDGET_REFUSAL","Rejection","code","reason","status","checksDescriptorAgain","rejection","undefined","has","test","parseSystemInstanceId","AnalysisViewConfig","DashboardViewConfig","ViewInstance","withTimeBindings","DataPanelSource","PanelTime","withCanonicalPanelFields","withCanonicalNames","PanelView","DashboardRuntimeState","BoardReading","config","canonicalBoard","viewOf","panel","timeOf","panelTime","definition","narrowing","renamed","canonicalOwned","view","undefined","instance","declared","id","own","definitionId","views","find","entry","viewId","timeField","name","fields","field","canonicalSaved","saved","read","kind","canonicalState","state","Pick","store","isDirty","draft","Partial","applied","next","dirty","Readonly","Record","Listeners","subscribe","listener","args","A","emit","clear","listenerSet","contain","error","subscribed","Set","add","delete","DataViewConfig","FilterTree","Issue","isFilterGroup","isSimpleTree","mergeFilters","NO_REFUSAL","withScopeFilter","config","C","scope","filter","withoutScopeModeWarning","issues","nested","op","simple","flatMap","found","code","path","slice","scopeRefusal","own","merged","carried","isError","map","identity","added","at","indexOf","splice","length","sameRefusal","left","right","every","severity","join","NO_REFUSAL","isError","MAX_TIMER_DELAY_MS","ViewConfig","RuntimeEnvironment","RefreshTimer","handle","delay","due","constructor","environment","fire","sync","stop","undefined","now","getTime","setTimeout","clearTimeout","MomentTimer","spent","syncAt","Math","min","max","refreshIntervalOf","config","Pick","interval","refresh","Number","isFinite","refreshDelayOf","held","dequal","Issue","ViewConfig","ViewInstance","RuntimeEnvironment","listenerSet","NO_REFUSAL","sameRefusal","MomentTimer","RefreshTimer","refreshDelayOf","refreshIntervalOf","ViewRuntimeState","hasError","issues","some","entry","severity","RuntimeStoreHost","admit","draft","S","apply","refresh","holding","interval","release","restored","blocking","expiresAt","ROLLOVER_GRACE_MS","RuntimeStoreOptions","state","environment","refusedScope","RuntimeStore","listeners","host","timer","rollover","unwatchVisibility","current","refusal","stopped","constructor","options","visibility","subscribe","retime","getSnapshot","baseline","stored","Partial","saved","title","scope","dirty","isDirty","disposed","listener","setState","patch","syncTimer","notify","emit","config","refuse","revert","ran","applied","before","dispose","stopTimer","clear","held","editing","isVisible","setDueAt","sync","expires","syncAt","query","status","at","nextRefreshAt","stop","NO_REFUSAL","DataViewConfig","AnalysisDateUnit","AnalysisGroup","DataViewDefinition","Issue","IssuePath","issue","analysisScope","PanelGrouping","regrouped","config","definition","unit","path","grouping","issues","none","undefined","kind","groups","some","group","type","capability","analysis","scope","taken","kept","map","units","aggregations","get","field","dateUnits","includes","push","label","_named","rest","DataViewConfig","Issue","IssuePath","PanelPresentation","issue","isPlainObject","isPresentationMember","validateDataConfig","KernelContext","hasError","MEMBERS","Record","record","analysis","presentedConfig","base","presentation","judge","Pick","path","config","issues","set","Object","keys","filter","length","dropped","allowed","kind","some","key","includes","over","filterTypeOf","AnalysisDateUnit","AnalysisViewConfig","DashboardFilters","DashboardViewConfig","DataViewConfig","FilterLeaf","FilterNode","FilterTree","PanelBinding","filterFields","isDateTimeFilterValue","isFilterGroup","isFilterLeaf","periodOf","resolveDateTimeBound","resolveDateTimeRange","RelativeDateUnit","filtersOf","AnchorClock","now","Date","timeZone","PanelAnchor","binding","config","leaf","panelAnchor","bindings","board","applied","filters","clock","axis","trendAxis","dates","Set","filter","field","kind","map","name","held","panelField","has","globalField","values","length","value","from","start","to","end","undefined","unit","period","at","own","includes","readAt","earliest","periodBefore","operator","type","CLOCK_MS","Partial","Record","SECOND","MINUTE","HOUR","CALENDAR","DAY","WEEK","MONTH","QUARTER","YEAR","calendar","parse","toISOString","amount","chart","trend","metric","headline","groups","Array","isArray","group","find","entry","alias","x","tree","visit","node","children","range","edge","op","Number","isNaN","DashboardFilters","DashboardPanel","DashboardViewConfig","DashboardViewPanel","FilterNode","FilterTree","Issue","PanelBinding","RuntimeLimits","isEmptyFilter","isPlainObject","mergeFilters","FieldKindRegistry","bindingsOf","boardCondition","filterReach","isViewPanel","mapGlobalFilter","panelFilterTree","panelsOf","panelTab","FilterReach","boardFieldsOf","HandOver","hasError","DataViewRuntime","PanelView","DashboardRuntimeState","blocksBoard","clickInForce","panelOf","DashboardPanelState","regrouped","PanelGrouping","presentedConfig","panelAnchor","AnchorClock","PanelAnchor","PanelRun","view","scope","issues","anchor","panelRun","panel","index","board","applied","filters","kinds","limits","clock","presented","config","presentation","definition","grouped","unit","wiredOn","panelScope","bindings","wired","anchoredOut","own","op","children","leaf","filter","binding","globalField","panelHandOver","held","name","scopeFilter","window","page","part","values","Object","fromEntries","entries","conjuncts","length","PanelOutcome","runtime","BoardPanelsHost","tab","viewOf","run","hold","boardPanels","host","blocked","flatMap","found","on","shown","data","runs","outcome","reported","id","waiting","fields","panelReach","boardHandOver","panelId","state","Pick","definitionId","saved","title","find","entry","parts","from","back","kind","instanceId","tree","reach","Record","grouping","DataViewDefinition","FieldDefinition","FilterTree","Issue","IssuePath","dequal","isFilterGroup","issue","RequestQueueFullError","isForbiddenFailure","sourceFailure","SourceFailure","ViewQueryState","failedExecutionIssue","error","definition","filter","Promise","queryFailureIssue","failedQuery","requestId","kept","config","asked","changed","status","conditionsChanged","const","failure","reason","violation","errorCode","unreachable","found","fieldAt","fields","path","params","Record","code","field","label","name","at","conditionOf","root","toLowerCase","FoundField","find","elements","startsWith","rest","slice","length","element","entry","tree","walk","node","index","child","children","entries","undefined","isForbiddenQuery","dequal","autoRunMembers","presentationMembers","Issue","ViewConfig","hasError","AUTO_APPLY_DELAY_MS","AutoApplyState","draft","applied","issues","autoApply","autoApplyDue","state","changed","changedMembers","length","question","kind","every","member","includes","answeringAnew","query","status","result","own","was","Record","now","presentation","Set","Object","keys","filter","DataViewDefinition","FilterTree","ValueCandidates","ValueCandidateSource","ValueCandidateSources","CandidateTarget","panelId","definition","field","scope","CandidateSourceFactory","FilterCandidates","panels","Map","merged","key","source","constructor","make","of","name","targets","unique","target","set","id","entries","map","at","join","held","get","offered","values","flatMap","sources","length","search","query","signal","mergeAnswers","Promise","all","each","reset","answers","counts","answer","value","count","sort","a","b","complete","every","dequal","filterTypeOf","AnalysisDateUnit","DashboardFilters","DashboardViewConfig","FieldOption","FilterValue","Issue","admitFilters","bindingsOf","DataPanelSource","defaultFilters","filtersOf","isViewPanel","panelsOf","wiredOptions","isEmptyFilter","issue","FieldKindRegistry","AUTO_APPLY_DELAY_MS","RuntimeEnvironment","RefreshTimer","ValueCandidateSource","PanelView","HeldFilters","FilterCandidates","CandidateSourceFactory","panelScope","FilterValuesHost","kinds","environment","candidateSources","applied","current","commit","filters","started","run","viewOf","panel","FilterValues","timer","candidates","held","ReadonlySet","Set","heldUnit","constructor","host","set","name","value","has","heldIssue","put","with","press","panelId","hold","refused","moved","values","next","Object","keys","grouping","unit","undefined","size","some","reset","defaults","wanted","entries","start","holds","clear","Record","from","length","take","stop","sync","on","config","candidatesOf","filter","find","field","kind","options","optionsOf","targets","flatMap","binding","entry","globalField","view","scope","board","now","id","tree","heldValues","definition","panelField","of","fields","fromEntries","dequal","filterTypeOf","sameFilterType","DashboardField","DashboardFilters","DashboardViewConfig","ViewInstance","DashboardViewPanel","FieldDefinition","FilterLeaf","FilterNode","FilterTree","FilterValue","Issue","IssuePath","RecordData","filterFields","isReferenceFilterValue","issue","readInstant","FieldKindRegistry","drillGroups","DrilledGroup","drillSpan","bindingsOf","crossFilterChoices","defaultFilters","fillUrl","filterValueIssues","filtersOf","isViewPanel","panelsOf","tabsOf","takesGroup","BoardClick","PanelReference","DataViewRuntime","DashboardPanelState","HandOver","ViewNavigation","CrossFilterOutcome","kind","filter","PressDestination","to","refused","fallback","DestinationBoard","config","PressHost","kinds","applied","filters","child","panelId","press","name","value","held","panel","reference","instanceId","Promise","handOver","Pressed","index","groups","PanelPresses","constructor","host","crossFilter","row","target","filterOf","field","valueOf","current","from","values","length","pressed","found","panelOf","byName","Map","map","some","binding","get","globalField","panelField","within","spanFilters","ran","getSnapshot","result","elements","dates","group","type","choice","pressSpan","through","find","entry","spanned","fields","timeZone","environment","filterValueOf","destination","state","click","clickFinding","pressedOn","at","url","groupTexts","toBoard","instance","carries","carriedOnto","conditions","flatMap","drilled","undefined","handed","own","kept","definitionId","scopeFilter","tree","board","id","source","Object","entries","groupValue","dimension","tab","panels","findIndex","ReturnType","condition","operator","items","label","String","inner","outer","a","absoluteWindow","b","Array","isArray","window","Date","parse","Number","isNaN","conjuncts","op","children","node","every","Record","texts","instant","ms","toISOString","dequal","overlaid","DashboardViewConfig","EditCommand","EditStep","command","subject","EditHistoryState","undo","redo","NO_HISTORY","Change","before","Partial","after","Entry","step","draft","applied","BURSTS","ReadonlySet","Set","BUILT_MEMBERS","const","outsideHistory","patch","rest","member","EDIT_HISTORY_DEPTH","EditHistory","done","undone","state","length","record","change","diff","isEmpty","last","has","merged","pop","push","shift","Rewind","entry","clear","rewound","config","members","keys","Object","every","key","set","first","then","out","value","Record","DashboardFilterType","DashboardTimeGrouping","DashboardViewConfig","DashboardWidth","FieldOption","FilterValue","PanelClick","PanelLayout","PanelPresentation","ViewConfig","ViewInstance","isPlainObject","addFilter","addPanel","filtersOf","addTab","autoBindings","timeFilterOf","PanelTime","bindPanel","moveFilter","removeFilter","renameFilter","retypeFilter","setFilterDefault","setFilterMultiple","setFilterOneDay","setFilterOptions","setFilterRequired","setTimeGrouping","unbindPanels","NewFilter","PanelFields","duplicatePanel","editContent","movePanelToTab","moveTab","referToSaved","removeFixedScope","removePanel","removeTab","renamePanel","setBoardWidth","renameTab","replacePanelView","setPanelClick","setPresentation","placePanelIn","reorderPanelIn","NewContentPanel","NewPanel","NewPanelPlacement","EditHistory","rewound","EditCommand","EditHistoryState","EditStep","DashboardEditing","panel","placement","panelId","title","instanceId","editPanelContent","patch","Partial","tabId","presentation","instance","click","firstTitle","index","place","layout","grown","ReadonlyMap","reorderPanel","to","setWidth","width","undo","redo","DashboardFilterEditing","filter","name","label","type","value","required","multiple","oneDay","options","panelField","panelIds","byHand","grouping","EditingHost","building","draft","maxPanels","viewConfig","seed","fieldsOf","timeOf","applied","commit","history","BoardEdits","forget","defaultOf","boardEditing","host","draftFor","edit","command","subject","change","config","next","const","record","state","rewind","way","step","added","from","result","id","panels","find","entry","undefined","fields","kind","timed","wired","bindings","binding","globalField","max","view","clear","field","default","connected","AnalysisDateUnit","DashboardField","DashboardFilters","DashboardFilterType","DashboardTimeGrouping","DashboardViewConfig","DashboardWidth","FieldOption","FilterValue","Issue","PanelClick","PanelLayout","PanelPresentation","RecordData","RuntimeLimits","ViewInstance","refreshIntervalOf","storedTimeWires","NewContentPanel","NewFilter","NewPanel","NewPanelPlacement","EditStep","DashboardRuntimeState","HeldFilters","BoardEdits","DashboardEditing","DashboardFilterEditing","FilterValues","CrossFilterOutcome","DestinationBoard","PanelPresses","PressDestination","NO_REFUSAL","BoardRulesHost","limits","edits","values","disposed","snapshot","patch","state","Partial","retime","reread","edit","apply","showTab","tabId","BoardRules","autoRefresh","openingRefusal","constructor","host","building","setBuilding","active","readerRefresh","history","forget","setAutoRefresh","on","holdsTimer","intervalInForce","applied","refresh","setRefreshInterval","interval","minRefreshInterval","min","maxRefreshInterval","max","Number","isInteger","setFilterDefault","name","value","set","followed","step","command","subject","defaultOf","holdFilters","held","refused","moved","hold","opensOn","tab","filters","taken","take","length","refusedFilters","BoardCommands","stored","config","presses","rules","getSnapshot","setAutoApply","autoApply","setEditing","editing","undo","redo","addPanel","panel","placement","removePanel","panelId","duplicatePanel","renamePanel","title","replacePanelView","instanceId","editPanelContent","movePanelToTab","setPresentation","look","referToSaved","instance","setPanelClick","click","addTab","firstTitle","renameTab","moveTab","index","removeTab","addFilter","filter","renameFilter","label","retypeFilter","type","removeFilter","setFilterRequired","required","setFilterMultiple","multiple","setFilterOneDay","oneDay","setFilterOptions","options","moveFilter","bindPanel","panelField","unbindPanels","panelIds","byHand","setTimeGrouping","grouping","removeFixedScope","place","layout","grown","ReadonlyMap","reorderPanel","to","setWidth","width","setFilterValue","setGroupingUnit","unit","clearFilters","clear","setFilters","wiredOptions","optionsOf","crossFilter","row","kind","pressed","spanFilters","pressSpan","through","destination","Promise","destinationBoard","board","dequal","DataViewConfig","presentationMembers","DataViewDefinition","FilterTree","Issue","ViewInstance","ViewScope","isPlainObject","DataPanelSource","PanelDefinition","PanelReference","DataViewRuntime","hasError","atPanel","panelIssues","PanelView","instance","definition","config","title","scope","panelView","panel","reference","instanceId","definitions","definitionId","board","owned","undefined","found","kind","loaded","PanelRuntimeFactory","view","scopeFilter","PanelChild","runtime","unsubscribe","index","own","missed","PanelChildren","children","Map","constructor","create","notified","panelId","get","runtimeOf","sync","issues","existing","sameView","changed","asks","drawsOnly","edit","replacing","rescoped","refused","getSnapshot","push","setScopeFilter","apply","refresh","drop","refusedScope","dispose","subscribe","set","hold","held","keepOnly","live","ReadonlySet","keys","has","child","delete","disposeAll","values","clear","shown","skip","rolloverAt","soonest","at","loading","query","status","previous","next","Partial","patch","Record","key","Object","drawn","before","after","Set","every","includes","id","revision","isViewStoreError","DashboardViewConfig","Issue","panelsOf","referencedInstance","PanelReference","panelFailure","reasonOf","isViewCommandError","PanelResolver","instanceId","Promise","PanelReferences","references","Map","failures","pending","constructor","resolve","settled","known","ReadonlyMap","resolving","size","get","failure","load","config","awaited","wanted","Set","map","filter","id","undefined","has","start","fetch","catch","retryFailed","failed","keys","retry","length","delete","restate","found","index","path","instance","params","code","loading","then","reference","resolved","error","gone","unreadable","set","ready","all","values","seed","reason","reasonOf","DashboardViewConfig","Issue","ViewInstance","ViewScope","FieldKindRegistry","admitFilters","ViewQueryState","DashboardRuntimeState","NO_HISTORY","shownTab","IDLE","status","openingState","opening","saved","title","scope","config","issues","kinds","draft","applied","dirty","query","result","selection","write","editing","autoApply","nextRefreshAt","panels","resolving","tab","filters","history","building","readerRefresh","filtersRun","IDLE","dequal","overlaid","DashboardDefinition","DashboardFilters","DashboardViewConfig","DashboardViewPanel","FieldDefinition","FilterTree","Issue","RuntimeLimits","ViewInstance","ViewScope","issue","FieldKindRegistry","filtersOf","referencedInstance","DataPanelSource","PanelTime","boardFieldsOf","canonicalBoard","canonicalSaved","canonicalState","panelTime","BoardReading","boardHandOver","boardPanels","panelRun","PanelAnchor","isForbiddenQuery","FilterValues","PanelPresses","boardEditing","BoardEdits","BoardCommands","BoardRules","outsideHistory","EditHistoryState","ValueCandidateSource","RuntimeEnvironment","hasError","RuntimeStore","OptionSource","PanelChildren","panelView","PanelView","blocksBoard","panelFailure","reissued","samePanels","shownTab","PanelReferences","openingState","admitBoard","WriteState","DataViewRuntime","ManagedViewRuntime","HandOver","PanelResolver","PanelRuntimeFactory","DashboardPanelState","boardFindings","stopsSave","DashboardEditing","DashboardFilterEditing","PanelGrouping","HeldFilters","DashboardRuntime","DashboardRuntimeOptions","DashboardRuntimeState","CrossFilterOutcome","DestinationBoard","PressDestination","DashboardViewRuntime","id","kind","const","definition","kinds","limits","environment","store","options","references","children","edits","values","presses","rules","requestedTab","synced","filtersOut","anchors","Map","canonical","timeOf","panel","viewOf","constructor","resolve","settled","createPanelRuntime","panelId","retime","refreshPanelIssues","building","draft","disposed","state","maxPanels","maxDashboardPanels","viewConfig","get","instance","config","seed","found","definitions","definitionId","fieldsOf","view","fields","applied","commit","history","candidateSources","current","filters","setState","started","run","sync","filtersRun","child","panelRuntime","press","name","value","held","holds","panels","find","entry","handOver","reference","fetch","snapshot","patch","reread","edit","apply","showTab","tab","saved","title","scope","issues","admit","blocking","refresh","rerun","refusedTheReader","holding","holdsTimer","loading","interval","intervalInForce","expiresAt","rolloverAt","onTab","release","stop","disposeAll","restored","load","refusedScope","scopeFilter","getSnapshot","subscribe","listener","optionSource","remote","resolveOptions","valueCandidates","candidatesOf","ready","Promise","Partial","dirty","isDirty","revert","forget","skip","retryFailed","resolving","size","some","tabId","edited","shown","preload","instanceId","refreshPanel","retry","runtimeOf","setScopeFilter","tree","refuse","anchor","issuesAt","markSaved","moveBaseline","write","stored","moved","baseline","adoptSaved","unavailable","removeUnavailable","setWrite","dispose","known","map","restate","awaited","on","index","own","syncPanel","hold","keepOnly","Set","flatMap","runtime","failure","undefined","code","clock","now","timeZone","set","delete","this","query","error","configBytes","MAX_VIEW_CONFIG_BYTES","MAX_VIEW_TITLE_LENGTH","titleProblem","Issue","ViewConfig","issue","stopsSave","ManagedViewRuntime","ViewCommandError","requireTitle","title","max","trim","storable","runtime","draft","requireStorable","stored","config","C","bytes","size","Math","ceil","requireSavable","issues","kind","RuntimeLimits","ViewConfig","ViewInstance","ViewScope","isOwnedPanel","isViewPanel","issue","FieldKindRegistry","requireStorable","requireTitle","DashboardViewRuntime","DefinitionRegistry","validateDataConfig","PermissionGuard","ViewCommandError","WriteLedger","PanelViewsHost","registry","kinds","limits","guard","ledger","PanelViewSource","REFUSED","Record","owned","saved","PanelViews","constructor","host","save","target","panelId","from","input","title","scope","Promise","board","view","sourceOf","panel","definitionId","config","definition","require","kind","found","some","entry","severity","requireCreate","instance","dispatch","action","intent","undefined","referToSaved","getSnapshot","draft","panels","find","id","panelRuntime","instanceId","newRequestId","source","globalThis","crypto","randomUUID","bytes","Uint8Array","getRandomValues","hex","Array","from","byte","toString","padStart","slice","join","isSystemInstanceId","isSystemScope","listParam","ViewConfig","ViewInstance","ViewScope","isViewPanel","issue","requireStorable","ViewStore","PermissionGuard","SummaryCache","ViewCommandError","WriteLedger","ReferenceOf","id","Promise","scope","title","publishCopy","guard","ledger","read","source","action","definitionId","config","requireCreate","dispatch","input","intent","undefined","requireSystemPanels","referenceOf","kind","named","panel","panels","ids","owned","instanceId","opens","click","filter","all","map","const","every","found","shown","push","length","count","readReferences","summaries","store","get","catch","isViewStoreError","Issue","ViewInstance","ViewStoreError","ViewPreferences","issue","listParam","newRequestId","ViewStore","WriteContext","ManagedViewRuntime","ViewRuntime","ViewChange","requireSystemPanels","ReferenceOf","ViewCommandError","ViewWriteError","WriteHandle","WritePayload","WriteState","WriteTarget","ConflictChoice","WriteResult","WriteLedgerHost","store","newId","noteInstance","instance","dropInstance","id","owner","notePreferences","definitionId","preferences","readPreferences","Promise","holders","noteChange","change","referenceOf","WriteLedger","host","writes","Map","inFlight","Set","owners","constructor","pendingWrites","ReadonlyMap","dispatch","payload","runtime","into","action","input","config","scope","getSnapshot","replay","retryWrite","target","requestId","state","requireWrite","get","abandonWrite","kind","remote","settle","resolveConflict","choice","reload","withRevision","key","writeKey","has","requireNoUnknownWrite","add","context","set","result","send","applyEffect","error","toWriteState","mayShow","setWrite","delete","shown","write","intent","markSaved","announce","holder","moveBaseline","create","save","revision","rename","title","changeAudience","audience","setPreferences","next","code","storage","reason","message","reachable","fetchRemote","refusalIssue","getPreferences","Extract","adoptSaved","isRuntime","undefined","pendingId","pending","toLowerCase","boards","length","count","issue","Issue","listenerSet","ViewChangeKind","ViewChange","definitionId","kind","id","ViewChangeListener","change","ViewChanges","listeners","error","report","reason","reasonOf","found","constructor","subscribe","listener","emit","clear","Error","message","String","audienceOf","isSystemInstanceId","isSystemScope","ViewInstanceSummary","ViewScope","issue","InstancePermissions","ViewPermissions","ViewStore","ViewCommandError","ALLOW_ALL","createPersonal","createShared","reorder","setDefault","instance","save","rename","delete","changeAudience","NO_INSTANCE_WRITES","Required","INSTANCE_ACTION_SET","Record","INSTANCE_ACTIONS","Object","keys","InstanceAbilities","readOnly","instanceAbilities","summary","id","scope","stored","permissions","undefined","editableSystemView","remove","granted","into","editSystem","PermissionGuard","store","constructor","of","definitionId","requireCreate","require","mayCreate","requireInstance","Pick","action","abilities","allowed","code","ViewInstanceSummary","ViewPreferences","ViewStore","PreferenceCache","store","cache","Map","notes","constructor","read","definitionId","Promise","before","get","preferences","getPreferences","newer","set","note","current","orderSummaries","summaries","byId","map","summary","id","ordered","order","flatMap","delete","values","resolveDefault","explicit","ids","Set","has","defaultInstanceId","abortWith","signal","AbortSignal","AbortController","controller","aborted","abort","reason","addEventListener","once","dequal","AnalysisViewConfig","FieldDefinition","FilterTree","compileAnalysis","narrowValueCandidates","readValueCandidates","validateAnalysis","valueCandidateField","valueCandidateNarrowing","valueCandidatesConfig","ValueCandidates","KernelContext","abortWith","isCalledOff","hasError","withScopeFilter","ValueCandidateSource","field","search","query","signal","AbortSignal","Promise","ValueCandidateSources","sources","Map","answers","generation","askedUnder","constructor","context","scope","of","name","has","definition","kinds","set","get","reset","clear","scoped","text","trim","ask","whole","keyOf","narrowable","complete","all","values","key","known","limits","environment","source","config","issues","Error","filter","found","severity","map","code","join","now","timeZone","rows","aggregate","undefined","catch","error","queryFailed","throwIfAborted","answer","keyOf","issue","isViewStoreError","Issue","ViewStoreError","sourceReason","isViewCommandError","isViewWriteError","toIssue","error","code","commandIssue","messageIssue","sourceIssue","Promise","reason","state","kind","storeOutcome","message","outcome","toLowerCase","reachable","Error","String","recordReadIssue","refused","exchange","response","status","undefined","without","AnalysisViewConfig","DataViewConfig","FilterTree","Issue","IssuePath","isEmptyFilter","isFilterGroup","isFilterLeaf","nodeAt","removeConditionAt","sameFilterTree","updateAt","walkFilter","FilterPath","unavailableIssues","effective","declared","known","Set","filter","isError","map","found","keyOf","has","code","withoutFirstUnavailable","config","C","issues","next","without1","head","index","member","path","removedAt","sort","_","i","kind","having","undefined","group","groups","entry","metric","metrics","trimmed","tree","inner","slice","field","params","paths","visit","node","push","step","length","changed","reverse","reduce","Level","at","levels","levelsOf","current","value","leaf","level","before","after","severity","JSON","stringify","without","dequal","DataViewConfig","overlaid","FieldDefinition","FilterTree","Issue","RecordPageTarget","RuntimeLimits","ViewInstance","FieldKindRegistry","periodRollover","NO_REFUSAL","scopeRefusal","withScopeFilter","withoutScopeModeWarning","RuntimeEnvironment","ViewErrorKind","failureReporter","queryFailureReporter","viewPlace","FailureReporter","hasError","RuntimeStore","AUTO_APPLY_DELAY_MS","autoApplyDue","sourceFailure","SourceFailure","failedExecutionIssue","failedQuery","isForbiddenQuery","RefreshTimer","isRequestSuperseded","RequestQueueFullError","RequestRunner","OptionSource","ProjectedView","executeDataConfig","validateDataConfig","KernelContext","ValueCandidateSources","ValueCandidateSource","WriteState","toIssue","checksDescriptorAgain","withCanonicalState","unavailableIssues","withoutFirstUnavailable","DefinitionFor","ManagedViewRuntime","RuntimeCapabilities","ViewQueryState","ViewRuntimeOptions","ViewRuntimeState","IDLE","status","MAX_REMOVALS","DataViewRuntime","C","id","kind","kinds","environment","store","context","runner","resolveOptions","key","autoRefresh","capabilities","stopFollowing","refusal","refreshing","autoTimer","candidates","injectedScope","appliedAdmitted","requestSeq","constructor","options","config","apply","definition","limits","source","queryFailed","saved","wanted","scopeFilter","own","admit","merged","refusedScope","refused","length","issues","state","title","scope","draft","applied","dirty","query","result","selection","write","editing","autoApply","nextRefreshAt","refresh","holding","error","holds","release","cancel","expiresAt","rolloverAt","watch","renarrow","data","askedAt","receivedAt","elapsedMs","left","chart","view","rows","timeZone","now","Date","undefined","disposed","fields","getSnapshot","subscribe","listener","optionSource","remote","valueCandidates","field","of","edit","patch","Partial","setState","isDirty","syncAutoApply","stop","restyle","startOver","execute","keepSelection","revert","setAutoApply","on","sync","revalidate","reset","setEditing","active","setAutoRefresh","retime","setScopeFilter","tree","refuse","issuesAt","markSaved","instance","moveBaseline","stored","baseline","adoptSaved","setWrite","dispose","unavailable","declared","removeUnavailable","step","next","unavailableOf","effective","renameFields","narrowing","renamed","Readonly","Record","scoped","pageNow","settle","found","fetch","controller","AbortController","Promise","quiet","getTime","requestId","run","then","onSuccess","onFailure","isCurrent","settled","Math","max","failed","failure","reason","violation","code","recheck","recovers","filter","issue","reporter","NO_REFUSAL","ViewInstance","issue","DataViewRuntime","ManagedViewRuntime","ViewRuntime","DashboardViewRuntime","ViewCommandError","OpenRuntimes","runtimes","Set","add","runtime","R","all","prune","require","isManagedRuntime","has","holders","id","first","found","filter","entry","getSnapshot","saved","close","forget","dispose","delete","disposeAll","clear","disposed","isSystemInstanceId","toSummary","Issue","ViewInstance","ViewInstanceSummary","ViewStore","toIssue","storedSummaries","store","definitionId","reserved","id","Promise","stored","failed","listed","list","filter","summary","error","SummaryCache","cache","Map","noteAll","summaries","set","note","instance","drop","delete","get","ViewConfig","ViewInstance","ViewPreferences","tabsOf","isViewWriteError","WriteHandle","TabMemoryHost","current","definitionId","Promise","write","next","abandon","handle","TabMemory","wanted","Map","writing","Set","constructor","host","remember","instanceId","tabId","key","set","has","add","get","undefined","lastTabs","error","delete","opensOn","instance","asked","config","kind","hasTab","preferences","tab","id","some","entry","CursorQuery","FilterPagedQuery","FIRST_PAGE","compileRecord","lastPageInWindow","pageWindow","FilterCompileContext","DEFAULT_RUNTIME_LIMITS","isNamedError","RecordCapability","RecordData","RecordPageTarget","RecordViewConfig","RuntimeLimits","KernelContext","ExportRowsOptions","signal","AbortSignal","onProgress","fetched","total","max","ExportedRows","rows","capped","ExportCancelledError","Error","constructor","name","isExportCancelledError","error","exportPlan","limits","Pick","Partial","capability","asked","size","wanted","exportMax","Number","isFinite","Math","floor","window","min","maxPageSize","Infinity","pages","undefined","fetchExportRows","context","config","options","Promise","definition","kinds","environment","record","filterContext","now","timeZone","paged","pageSize","cursored","paging","target","cursor","length","done","stopIfCancelled","query","page","fetchPage","push","list","next","controller","AbortController","unlink","follow","source","nextCursor","index","slice","aborted","abort","onAbort","addEventListener","once","removeEventListener","FilterCompileContext","without","FilterTree","RecordData","RecordKey","RecordViewConfig","FIRST_PAGE","compileRecord","KernelContext","withScopeFilter","abortWith","fetchRecord","context","config","scope","key","signal","AbortSignal","Promise","definition","kinds","environment","source","capability","record","Error","id","one","filter","op","children","field","rowKey","operator","value","sort","pageSize","filterContext","now","timeZone","cursored","paging","query","whole","cursor","paged","controller","page","undefined","list","Q","bare","projection","without","dequal","columnHidden","presentationMembers","RecordViewConfig","restyledOnly","ran","next","question","summaries","config","Record","rest","member","kind","columns","table","shown","filter","column","hidden","map","field","sort","QueryErrorCodes","dequal","DataViewConfig","RecordData","RecordKey","RecordPageTarget","RecordViewConfig","pageAfterShrink","restyleRecord","executeSummaries","firstPageOf","fetchExportRows","isExportCancelledError","ExportRowsOptions","ExportedRows","fetchRecord","isCalledOff","restyledOnly","withScopeFilter","SourceFailure","ProjectedView","DataViewRuntime","RecordViewRuntime","ViewRuntime","ViewRuntimeOptions","ViewRuntimeState","RecordDataViewRuntime","target","restarted","exportFailed","reporter","constructor","options","definition","page","disposed","appliedAdmitted","store","setState","selection","execute","keepSelection","select","keys","available","resultKeys","filter","key","has","exportRows","Promise","reject","Error","id","context","state","applied","scopeFilter","catch","error","signal","AbortSignal","queryFailed","restyle","draft","result","query","status","own","data","kind","change","view","quiet","fetch","config","controller","startOver","Partial","pageNow","recovers","failure","cursor","isInvalidCursor","settle","back","shrunkTo","index","retainSelection","holds","length","paging","rows","Set","map","row","retained","INVALID_CURSOR","violation","code","undefined","reason","includes","dataViewRuntime","isRecordRuntime","runtime","queryFailureReporter","panelsOf","PanelDefinition","DataViewConfig","DashboardViewConfig","FieldDefinition","FilterTree","RuntimeLimits","ViewConfig","ViewDefinition","ViewInstance","ViewScope","issue","FieldKindRegistry","RuntimeEnvironment","RequestRunner","OptionSource","ViewSource","DataViewRuntime","dataViewRuntime","ManagedViewRuntime","RuntimeCapabilities","DashboardViewRuntime","PanelResolver","PanelRuntimeFactory","DefinitionRegistry","SourceCapabilities","withCanonicalNames","ValueCandidateSources","ViewCommandError","RuntimeIdentity","title","scope","saved","RuntimeFactoryHost","definitions","kinds","limits","environment","runner","resolveSource","key","resolveOptions","readInstance","instanceId","Promise","capabilities","QUERIES_PER_PANEL","RuntimeFactory","host","sequence","constructor","build","definition","config","identity","scopeFilter","kind","buildData","board","buildDashboard","setScopeFilter","capabilityOf","id","effective","renamed","narrowing","newRuntimeId","canonicalInstance","source","follow","resolve","resolvePanel","panelDefinition","createPanelRuntime","candidateSources","queryFailed","definitionId","holdRoom","error","dispose","roomFor","getSnapshot","draft","length","held","release","reserve","stop","subscribe","disposed","room","instance","declared","require","prepare","admitted","fields","panelFields","registry","has","view","autoRefresh","get","undefined","watch","listener","revalidate","recheck","code","Readonly","Record","record","analysis","isViewStoreError","ViewStoreError","DashboardViewConfig","ViewInstance","isPlainObject","migrateDashboardConfig","ViewStore","readStored","instance","config","kind","read","readingStore","store","list","definitionId","signal","get","id","create","input","context","written","save","revision","rename","title","delete","getPreferences","setPreferences","preferences","changeAudience","audience","permissions","write","Promise","T","answer","error","conflictRead","code","message","QueryModelDescriptor","DataViewDefinition","Issue","RuntimeLimits","ViewDefinition","ViewInstance","issue","FieldKindRegistry","isOwnedPanel","panelsOf","DESCRIBE_DEADLINE_MS","DescriptorCache","narrowDefinition","sourceLimits","Describe","NarrowedDefinition","RuntimeEnvironment","ViewSource","ViewCommandError","CapabilityHost","kinds","limits","Partial","environment","resolveSource","key","declared","id","report","found","EffectiveDefinition","definition","SourceCapabilities","fallback","host","cache","narrowed","Map","version","result","limitsBySource","stopWatching","watchers","Set","constructor","now","getTime","failed","source","changed","listener","get","visibility","subscribe","isVisible","revalidateStale","prepareFor","instance","Promise","definitionId","kind","prepare","config","owned","filter","map","panel","entry","undefined","all","describe","describer","timer","late","resolve","setTimeout","race","load","clearTimeout","warm","watch","listeners","set","add","delete","revalidate","recheck","code","before","current","after","effective","descriptor","findings","narrow","errors","severity","length","issues","limitsOf","dispose","resolved","previous","given","held","params","TextResolver","EngineText","resolver","knownKeys","ReadonlySet","constructor","start","known","set","resolve","key","saysAny","undefined","Issue","IssueReporter","found","resource","IssueConsole","groupCollapsed","data","groupEnd","warn","error","info","HINTS","issueHint","code","entry","startsWith","length","consoleIssueReporter","sink","pending","Map","flush","at","path","join","hint","line","severity","params","clear","key","stringParam","size","Promise","resolve","then","list","get","push","set","name","value","undefined","process","env","NODE_ENV","inDevelopment","defaultIssueReporter","console","textKeysIn","Issue","TextResolver","ViewDefinition","issue","sayDefinition","OptionSource","ViewSource","EngineText","defaultIssueReporter","IssueReporter","ViewCommandError","ResourceHost","resources","definition","source","resolveOptions","key","text","onIssue","EngineResources","registered","ReadonlyMap","sources","Map","lacking","Set","reporter","constructor","host","found","values","kind","has","set","definitions","startingWord","start","setText","language","findings","flatMap","map","id","String","params","says","saysAny","filled","resolve","undefined","code","told","add","report","startsWith","delete","resource","hasSource","resolveSource","get","audienceOf","FilterTree","parseSystemInstanceId","toSummary","Issue","RuntimeLimits","ViewConfig","ViewDefinition","ViewInstance","ViewAudience","ViewInstanceSummary","ViewPreferences","ViewScope","builtinFieldKinds","issue","FieldKindRegistry","InstancePermissions","ViewPermissions","ViewStore","defaultRuntimeEnvironment","RuntimeEnvironment","RequestRunner","OptionSource","ViewSource","AnyViewRuntime","CreateInput","ManagedViewRuntime","OpenOptions","RuntimeFor","ViewRuntime","DashboardViewRuntime","PanelViews","ViewCommandError","WritePayload","WriteState","WriteLedger","ConflictChoice","WriteLedgerHost","WriteTarget","ViewChanges","ViewChangeListener","DefinitionRegistry","systemInstances","PermissionGuard","PreferenceCache","resolveDefault","OpenRuntimes","storedSummaries","SummaryCache","TabMemory","RuntimeFactory","RuntimeIdentity","readingStore","SourceCapabilities","EngineResources","reportingStore","requireSavable","requireTitle","storable","publishCopy","readReferences","ViewResource","definition","source","ViewEngineOptions","resources","store","resolveOptions","key","kinds","text","limits","Partial","environment","newId","onIssue","ViewListing","items","failed","ViewEngine","options","runner","capabilities","registry","registered","ReadonlyMap","guard","preferenceCache","runtimes","factory","ledger","panelViews","changes","found","report","summaries","tabs","current","definitionId","write","next","writePreferences","abandon","handle","abandonWrite","constructor","resolveSource","declared","id","definitions","get","fallback","ledgerHost","map","hasSource","resource","readInstance","definitionIssues","issues","permissions","of","list","Promise","require","stored","noteAll","subscribe","listener","preferences","read","open","instanceId","instance","ofDefinition","prepareFor","tab","opensOn","runtime","attach","scopeFilter","filters","held","ready","error","forget","apply","systemInstance","viewId","create","input","C","title","warm","build","config","scope","saved","save","target","state","getSnapshot","issuesAt","draft","requireCreate","dispatch","action","intent","requireInstance","payload","revision","saveAs","saveOwnedView","dashboard","panelId","copyPanelView","publishAsSystem","rename","locate","changeAudience","audience","delete","reorder","order","setDefault","defaultInstanceId","setAutoRun","autoRun","rememberTab","tabId","remember","explicit","pendingWrites","retryWrite","resolveConflict","choice","openRuntimes","all","close","dispose","disposeAll","cancelAll","clear","identity","add","undefined","noteInstance","note","dropInstance","owner","drop","holder","holders","notePreferences","readPreferences","referenceOf","noteChange","change","emit","prune","known","summary","DataViewConfig","AnalysisViewConfig","DashboardDefinition","DashboardFilters","DashboardViewConfig","DataViewDefinition","FieldDefinition","FilterTree","Issue","PagingMode","RecordData","RecordKey","RecordPageTarget","RecordViewConfig","RuntimeLimits","ViewAudience","ViewConfig","ViewInstance","ViewScope","FieldKindRegistry","RuntimeEnvironment","RequestRunner","OptionSource","ProjectedView","ViewSource","ExportRowsOptions","ExportedRows","ValueCandidateSource","WriteState","DashboardRuntime","HeldFilters","ViewRuntime","id","kind","C","definition","DefinitionFor","fields","kinds","limits","optionSource","remote","valueCandidates","field","getSnapshot","ViewRuntimeState","subscribe","listener","edit","patch","Partial","unavailable","removeUnavailable","apply","revert","refresh","setEditing","active","setAutoRefresh","on","setAutoApply","setScopeFilter","tree","refusedScope","scopeFilter","environment","dispose","disposed","RecordViewRuntime","page","target","P","select","keys","exportRows","options","Promise","fetchRecord","key","signal","AbortSignal","AnyViewRuntime","ManagedViewRuntime","issuesAt","scope","markSaved","instance","moveBaseline","adoptSaved","stored","config","setWrite","write","RuntimeFor","QueryStatus","ViewQueryState","status","error","requestId","conditionsChanged","ViewResult","own","data","receivedAt","elapsedMs","saved","title","draft","applied","issues","dirty","query","result","selection","editing","autoApply","nextRefreshAt","hasResult","state","hasAsked","ViewRuntimeOptions","source","runner","resolveOptions","autoRefresh","capabilities","RuntimeCapabilities","declared","effective","watch","revalidate","recheck","code","CreateInput","OpenOptions","tab","filters","held","definitionId","isForbiddenFailure","momentMetrics","clickInForce","overlaid","compileRecord","analysisProbeLimit","audienceOf","filterFields","appliedWindow","ViewCommandError","lastPageInWindow","MAX_TIMER_DELAY_MS","crossFilterChoices","atPanel","DASHBOARD_PRESENTATION_MEMBERS","takesGroup","isViewWriteError","MAX_VIEW_CONFIG_BYTES","setPanelClick","reissued","builtinFieldKinds","defaultFilters","panelFilterTree","executeSummaries","isEmptyFilter","limitBounds","filtersOf","samePanels","filterTypeOf","queryFailureReporter","mergeFilters","ANALYSIS_AUTO_RUN_MEMBERS","clicksFilter","failureReporter","drillSpan","bindingsOf","shownTab","fitChartSlots","firstMetric","hasFixedHeight","panelIssues","without$1","compileAnalysis","isSystemScope","FILTER_TYPE_OPERATOR","panelOf","titleProblem","blocksBoard","DASHBOARD_WIDTHS","reasonOf$1","toSummary","admitFilters","viewPlace","removeConditionAt","ANALYSIS_PRESENTATION_MEMBERS","isPresentationMember","stopsSave","sameFilterType","admitBoard","DEFAULT_RUNTIME_LIMITS","columnHidden","isViewCommandError","pageWindow","firstPageOf","isFilterGroup","executeDataConfig","bucketRange","filterValueIssues","validateDataConfig","isFilterLeaf","drillGroups","isOneDayValue","nodeAt","freshId","reportingStore","readInstant","isOwnedPanel","tabsOf","systemInstances","isPlainObject","restyleRecord","isNamedError","issue","isFieldlessKind","addTab","isViewPanel","sameFilterTree","moveTab","textKeysIn","isDateTimeFilterValue","cardField","referencedInstance","panelFailure","sameJson","configBytes","URL_PLACEHOLDER","FIRST_PAGE","operatorsOf","isSingleStringField","renameTab","resolveDateTimeBound","panelsOf","walkFilter","narrowDefinition","groupFieldsOf","validateAnalysis","withCanonicalNames","removeTab","isCalledOff","isSimpleTree","resolveDateTimeRange","isValueMetric","withCanonicalState","periodOf","analysisScope","panelTab","updateAt","sourceReason","validateLayout","DefinitionRegistry","isSystemInstanceId","boardCondition","ViewWriteError","pageAfterShrink","periodRollover","nearestPageSize","DASHBOARD_FILTER_KINDS","fillUrl","isReferenceFilterValue","isViewStoreError","RECORD_PRESENTATION_MEMBERS","sayDefinition","ViewStoreError","parseSystemInstanceId","mapGlobalFilter","emptyFilter","VIEW_KINDS","DATA_PRESENTATION_MEMBERS","BY_KIND","presentationMembers","kind","AUTO_RUN_BY_KIND","autoRunMembers","listParam","items","isRootFilterIssue","found","filterIndexes","path","segment","unmarkedErrors","issues","isMarked","tree","conditionAt","node","index","group","groupOf","rootSearch","leaf","isLeaf","field","withRootSearch","blank","text","root","at","i","children","searchFieldOf","fields","recordCapabilityOf","definition","defaultRecordConfig","capability","names","defaults","layout","pageSize","limits","name","detailSections","valued","byName","placed","sections","rest","VALUE_CANDIDATE_LIMIT","VALUE_CANDIDATE_OPERATORS","VALUE","COUNT","valueCandidateField","entry","kinds","AggregationGroupType","valueCandidateNarrowing","offered","valueCandidateLimit","valueCandidatesConfig","query","narrowing","metric","readValueCandidates","complete","config","rows","value","row","count","narrowValueCandidates","values","sensitive","fold","wanted","prefix","withoutDangling","dangling","danglingIn","shape","facts","was","before","untouched","removed","metrics","now","comparableIn","then","stands","ungrouped","kept$1","readable","derivedRefs","alias","moments","havingMetrics","operands","operand","left","expression","withElements","scope","inScope","groups","measuresInScope","withoutFilter","derivable","next","stays","elements","withLevel","withoutLevelsFrom","nextExpansion","declaredChain","holderFields","depth","outer","levelLabel","level","nextLevel","expressionFields","UNIT_MS","FINE_TO_COARSE","MIN_BUCKETS","recommendDateUnit","first","span","candidates","unit","rangeSpan","filter","timeZone","from","end","to","resultSpan","last","start","HAVING_OPERATORS","havingRows","having","inner","withHavingRows","conditions","emptyDashboardConfig","fitsGrid","columns","overlaps","a","b","bottomOf","panels","bottom","panel","compactLayout","compactAround","placePanel","id","held","geometry","others","arrangePanel","resting","reach","step","distance","target","stepped","samePlacement","freeSpot","w","size","h","boxes","y","fromRow","x","spot","box","settle","placePanelIn","tabBoxes","shown","grown","grownLayout","saved","savedPlacement","withLayouts","stored","drawnBefore","heightOf","own","read","readingOrder","drawnFloor","savedFloor","above","settled","stacked","below","moving","tab","moved","changed","current","fixed","sameLayout","STACKED_COLUMNS","stackedLayout","paired","marked","heights","grownFloor","reorderPanel","order","readOf","other","best","consider","cost","shuffled","disturbance","traded","mover","reorderPanelIn","out","skip","hit","one","two","corner","place","pairs","pair","differs","defaultPanelSize","view","addPanel","max","placement","tabOf","boxesOn","added","removePanel","find","compactTab","duplicatePanel","withFixedHeight","mapPanel","renamePanel","title","replacePanelView","mapViewPanel","instanceId","bindings","referToSaved","setPresentation","presentation","editContent","edited","patch","movePanelToTab","setBoardWidth","width","change","timeFilterOf","dated","dateFilters","isDateFilter","withTimeBindings","storedBindings","kept","isDerived","time","timeOf","written","wire","sameWires","storedTimeWires","withTimeIgnored","wired","wireableFields","candidate","filterReach","binding","filtersOnTab","reaching","bindPanel","same","viewPanel","panelId","fieldsOf","panelField","connected","wiredTo","match","autoField","remote","unbindPanels","byHand","panelIds","wiredOptions","merged","option","key","autoBindings","given","wiredNames","counts","auto","addFilter","renameFilter","label","mapFilter","retypeFilter","type","retyped","unwire","removeFilter","setFilterDefault","setFilterRequired","required","setFilterOneDay","oneDay","setFilterMultiple","multiple","single","setFilterOptions","options","moveFilter","setTimeGrouping","grouping","removeFixedScope","ALWAYS_VISIBLE","defaultRuntimeEnvironment","callback","ms","handle","overrides","RequestSupersededError","RequestQueueFullError","limit","isRequestSuperseded","error","RequestRunner","slots","released","previous","freed","deliver","SCALE","migrateDashboardConfig","withoutOwnCondition","intoDefaults","onTheWideGrid","widened","child","leafField","asDefault","without","joined","conjuncts$1","members","member","operator","scaled","boardFieldsOf","withCanonicalPanelFields","renamed","renamedOf","renamedPanel","ownedView","click","renamedClick","owned","whole","source","DESCRIBE_DEADLINE_MS","DescriptorCache","force","maxAge","answer","SOURCE_LIMIT_NAMES","sourceLimits","base","host","descriptor","largestRung","described","CAPABILITY_CODES","QueryErrorCodes","BUDGET_REFUSAL","checksDescriptorAgain","rejection","canonicalBoard","panelTime","viewOf","canonicalOwned","declared","instance","canonicalSaved","canonicalState","state","draft","applied","store","listenerSet","subscribed","listener","args","contain","NO_REFUSAL$1","withScopeFilter","withoutScopeModeWarning","nested","simple","scopeRefusal","carried","isError$1","identity","sameRefusal","right","RefreshTimer","environment","fire","delay","MomentTimer","due","refreshIntervalOf","interval","refreshDelayOf","hasError","ROLLOVER_GRACE_MS","RuntimeStore","dequal","refusal","ran","expires","regrouped","none","taken","_named","MEMBERS","presentedConfig","set","dropped","allowed","over","judge","panelAnchor","axis","trendAxis","dates","board","clock","period","readAt","earliest","periodBefore","CLOCK_MS","CALENDAR","calendar","chart","trend","visit","range","edge","panelRun","presented","grouped","filters","anchor","wiredOn","panelScope","anchoredOut","panelHandOver","window","page","part","conjuncts","boardPanels","blocked","on","data","runs","outcome","reported","runtime","panelReach","boardHandOver","parts","failedExecutionIssue","queryFailureIssue","sourceFailure","failedQuery","asked","failure","violation","fieldAt","params","conditionOf","element","walk","isForbiddenQuery","autoApplyDue","changedMembers","question","answeringAnew","FilterCandidates","make","unique","targets","sources","mergeAnswers","each","signal","answers","FilterValues","heldIssue","refused","PanelPresses","within","choice","spanned","through","filterValueOf","pressed","url","groupTexts","reference","carries","carriedOnto","drilled","handed","condition","absoluteWindow","texts","instant","NO_HISTORY","BURSTS","BUILT_MEMBERS","outsideHistory","EditHistory","undo","redo","diff","isEmpty","rewound","after","keys","boardEditing","history","draftFor","edit","rewind","way","result","command","timed","tabId","firstTitle","NO_REFUSAL","BoardRules","active","readerRefresh","min","BoardCommands","look","panelView","definitions","loaded","PanelChildren","create","notified","existing","sameView","asks","drawsOnly","replacing","rescoped","unsubscribe","live","soonest","drawn","PanelReferences","resolve","awaited","pending","failed","loading","gone","reason","IDLE$1","openingState","opening","DashboardViewRuntime","refusedTheReader","canonical","filtersRun","run","requireTitle","storable","requireStorable","bytes","requireSavable","REFUSED","PanelViews","sourceOf","definitionId","input","newRequestId","hex","byte","publishCopy","guard","ledger","requireSystemPanels","named","ids","referenceOf","readReferences","summaries","WriteLedger","into","payload","requestId","withRevision","writeKey","context","holder","refusalIssue","isRuntime","pendingId","owner","boards","ViewChanges","reasonOf","report","ALLOW_ALL","NO_INSTANCE_WRITES","instanceAbilities","summary","editableSystemView","permissions","remove","save","rename","granted","PermissionGuard","mayCreate","abilities","action","code","PreferenceCache","preferences","newer","orderSummaries","byId","resolveDefault","explicit","abortWith","controller","ValueCandidateSources","keyOf$1","narrowable","all","known","generation","toIssue","commandIssue","messageIssue","sourceIssue","storeOutcome","recordReadIssue","response","exchange","status","unavailableIssues","isError","keyOf","effective","withoutFirstUnavailable","without1","head","removedAt","sort","trimmed","paths","levels","levelsOf","IDLE","MAX_REMOVALS","DataViewRuntime","refusedScope","askedAt","restyle","scoped","keepSelection","receivedAt","OpenRuntimes","isManagedRuntime","storedSummaries","reserved","SummaryCache","TabMemory","hasTab","ExportCancelledError","isExportCancelledError","exportPlan","pages","fetchExportRows","filterContext","paged","cursored","total","done","fetchPage","stopIfCancelled","unlink","follow","capped","onAbort","fetchRecord","restyledOnly","table","column","RecordDataViewRuntime","available","selection","isInvalidCursor","back","retained","INVALID_CURSOR","dataViewRuntime","isRecordRuntime","QUERIES_PER_PANEL","RuntimeFactory","canonicalInstance","panelFields","registry","scopeFilter","capabilityOf","panelDefinition","roomFor","release","stop","room","capabilities","readStored","readingStore","revision","audience","write","conflictRead","SourceCapabilities","visibility","describe","timer","late","listeners","narrowed","errors","findings","resolved","EngineText","resolver","HINTS","issueHint","consoleIssueReporter","flush","resource","hint","line","sink","stringParam","list","inDevelopment","defaultIssueReporter","EngineResources","says","lacking","filled","told","language","ViewEngine","dashboard","hasResult","hasAsked"],"sources":["../src/model/config.ts","../src/model/issue.ts","../src/filter/issuePath.ts","../src/filter/marks.ts","../src/filter/search.ts","../src/record/defaults.ts","../src/record/detail.ts","../src/analysis/candidates.ts","../src/analysis/dangling.ts","../src/analysis/expand.ts","../src/analysis/granularity.ts","../src/analysis/having.ts","../src/dashboard/defaults.ts","../src/dashboard/layout.ts","../src/dashboard/edit.ts","../src/dashboard/timeBindings.ts","../src/dashboard/wiring.ts","../src/dashboard/filterEdit.ts","../src/runtime/environment.ts","../src/runtime/requestRunner.ts","../src/dashboard/migrate.ts","../src/dashboard/boardFields.ts","../src/dashboard/panelFieldNames.ts","../src/capabilities/cache.ts","../src/capabilities/limits.ts","../src/capabilities/violations.ts","../src/runtime/dashboard/canonical.ts","../src/runtime/listeners.ts","../src/runtime/scope.ts","../src/runtime/refreshTimer.ts","../src/runtime/runtimeStore.ts","../src/runtime/dashboard/grouping.ts","../src/runtime/dashboard/presentation.ts","../src/runtime/dashboard/anchor.ts","../src/runtime/dashboard/panelRun.ts","../src/runtime/queryFailure.ts","../src/runtime/autoApply.ts","../src/runtime/dashboard/filterCandidates.ts","../src/runtime/dashboard/filterValues.ts","../src/runtime/dashboard/press.ts","../src/runtime/dashboard/history.ts","../src/runtime/dashboard/editing.ts","../src/runtime/dashboard/commands.ts","../src/runtime/dashboard/children.ts","../src/runtime/dashboard/references.ts","../src/runtime/dashboard/opening.ts","../src/runtime/dashboardRuntime.ts","../src/runtime/commandChecks.ts","../src/runtime/panelViews.ts","../src/runtime/requestId.ts","../src/runtime/publish.ts","../src/runtime/writeLedger.ts","../src/runtime/viewChanges.ts","../src/runtime/permissions.ts","../src/runtime/preferences.ts","../src/runtime/abort.ts","../src/runtime/valueCandidates.ts","../src/runtime/issues.ts","../src/runtime/unavailable.ts","../src/runtime/viewRuntime.ts","../src/runtime/openRuntimes.ts","../src/runtime/summaries.ts","../src/runtime/tabMemory.ts","../src/runtime/exportRows.ts","../src/runtime/fetchRecord.ts","../src/runtime/restyle.ts","../src/runtime/recordRuntime.ts","../src/runtime/runtimeFactory.ts","../src/runtime/storedViews.ts","../src/runtime/capabilities.ts","../src/runtime/text.ts","../src/runtime/issueReport.ts","../src/runtime/resources.ts","../src/runtime/viewEngine.ts","../src/runtime/viewRuntimeTypes.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ANALYSIS_AUTO_RUN_MEMBERS,\n ANALYSIS_PRESENTATION_MEMBERS,\n type AnalysisViewConfig,\n} from './analysis.js';\nimport {\n DASHBOARD_PRESENTATION_MEMBERS,\n type DashboardViewConfig,\n} from './dashboard.js';\nimport type { FilterMode, FilterTree } from './filter.js';\nimport {\n RECORD_PRESENTATION_MEMBERS,\n type RecordViewConfig,\n} from './record.js';\n\n/**\n * What every view kind stores. It belongs to the view rather than to the\n * person looking at it, so it is saved with the config.\n */\nexport interface ViewConfigBase {\n refresh: RefreshConfig;\n}\n\n/**\n * What a view that asks one question of its own — a record view, an\n * analysis — stores besides: its conditions, and the editor mode they are\n * shown in.\n *\n * A dashboard has neither (D27). Its panels ask the questions, a reader\n * narrows them through the board's filters (`DashboardField`), and what no\n * reader changes is its fixed scope (`DashboardViewConfig.fixed`) — so a\n * condition of the board's own would be a third place saying the same thing.\n */\nexport interface DataViewConfigBase extends ViewConfigBase {\n filter: FilterTree;\n /** The editor mode travels with the view: `simple` cannot show an OR tree. */\n filterMode: FilterMode;\n}\n\n/**\n * Auto-refresh interval in seconds, or `null` when off. A non-null value is a\n * finite integer between `minRefreshInterval` and `maxRefreshInterval`.\n */\nexport interface RefreshConfig {\n interval: number | null;\n}\n\n/** What a user saves: the way of observing, never a data snapshot. */\nexport type ViewConfig =\n RecordViewConfig | AnalysisViewConfig | DashboardViewConfig;\n\n/**\n * The two kinds that ask a question of their own (`DataViewConfigBase`) and\n * that a `ViewRuntime` executes; a dashboard owns child runtimes.\n */\nexport type DataViewConfig = RecordViewConfig | AnalysisViewConfig;\n\nexport type ViewKind = ViewConfig['kind'];\n\nexport const VIEW_KINDS: readonly ViewKind[] = [\n 'record',\n 'analysis',\n 'dashboard',\n];\n\n/** Narrows a config union member by its kind. */\nexport type ConfigOfKind<K extends ViewKind> = Extract<ViewConfig, { kind: K }>;\n\n/**\n * The presentation-only members every kind shares.\n *\n * A presentation member draws the result that already came back and never\n * reaches the query, so a draft that differs from the applied config only\n * there is not \"changed, not applied\": there is nothing left to apply, and a\n * dot asking for an Apply with nothing to run teaches the user to press\n * buttons that change nothing (`runtime/pending.ts`).\n *\n * The editor's simple/advanced mode is the one both data views have: it\n * decides what the condition builder can show, and the tree it submits is\n * the same tree either way.\n */\nconst DATA_PRESENTATION_MEMBERS = [\n 'filterMode',\n] as const satisfies readonly (keyof DataViewConfigBase)[];\n\nconst BY_KIND: Record<ViewKind, readonly string[]> = {\n record: [...DATA_PRESENTATION_MEMBERS, ...RECORD_PRESENTATION_MEMBERS],\n analysis: [...DATA_PRESENTATION_MEMBERS, ...ANALYSIS_PRESENTATION_MEMBERS],\n dashboard: DASHBOARD_PRESENTATION_MEMBERS,\n};\n\n/**\n * Which members of one kind's config are presentation only — declared beside\n * the type each is a member of rather than string-compared where they are\n * read, so a `satisfies` refuses a member the config does not have (A6).\n *\n * A config arrives from a store, so its `kind` may be none of the three;\n * such a config has no member known to only draw, since no member is\n * presentation for every kind.\n */\nexport function presentationMembers(kind: ViewKind): readonly string[] {\n return BY_KIND[kind] ?? [];\n}\n\nconst AUTO_RUN_BY_KIND: Record<ViewKind, readonly string[]> = {\n record: [],\n analysis: ANALYSIS_AUTO_RUN_MEMBERS,\n dashboard: [],\n};\n\n/**\n * Which members of one kind's config run again on their own a moment after\n * they change (「改了就跑」, D20) — declared beside the type each is a member\n * of, like `presentationMembers`, so the runtime carries no rule of any one\n * kind and a kind that runs nothing on its own declares nothing.\n *\n * Only an analysis has any: its question. A record view's edits — a sort, a\n * page size — are cheap to apply and wait for the press as they always did;\n * a dashboard edits its layout, not a question.\n */\nexport function autoRunMembers(kind: ViewKind): readonly string[] {\n return AUTO_RUN_BY_KIND[kind] ?? [];\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A validation finding. Every kernel reports problems this way.\n *\n * Wording lives in the UI layer: `code` is the branching key and `params`\n * carries the values a message needs, so the model stays free of copy.\n */\nexport interface Issue {\n /** Stable machine-readable key, e.g. `record.sort.field-not-sortable`. */\n code: string;\n severity: IssueSeverity;\n /** Location inside the config, e.g. `['sort', 0, 'field']`. */\n path: IssuePath;\n params?: Record<string, string | number>;\n}\n\n/**\n * `error` blocks apply and save; `warning` is reported without blocking —\n * something is wrong, or the answer could be misread; `note` is something\n * true about the answer a reader should know, and nothing is wrong: the\n * groups a view's own limit left out, when every row shown is whole.\n */\nexport type IssueSeverity = 'error' | 'warning' | 'note';\n\nexport type IssuePath = (string | number)[];\n\n/** What separates the items of a list parameter (`listParam`). */\nexport const LIST_PARAM_SEPARATOR = '\\u001E';\n\n/**\n * A parameter that is a list — the titles of the boards that keep a view\n * shared — as one string the model can carry. Joining it is wording: the\n * catalogue's formatter joins the items as the surface's language joins a\n * list (`Intl.ListFormat`, a conjunction: 「A、B和C」, \"A, B, and C\"), after\n * which a title written as a key is said where it is shown (D2).\n */\nexport function listParam(items: readonly string[]): string {\n return items.join(LIST_PARAM_SEPARATOR);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * How an issue path reads against a filter tree.\n *\n * A finding names where it is, as a path of config keys and indexes, and two\n * questions get asked of that path all over this package: **is it about the\n * tree I am showing**, and **which node of it**. Both were spelled out\n * wherever they were needed — in the editor, in the pending report, on a\n * condition pill, in the applied bar — and a spelling is exactly the kind of\n * thing that drifts: a metric's filter reports the same codes under\n * `['metrics', …]`, so a predicate that forgets to ask would mark the root\n * tree for a nested tree's error.\n */\nimport type { Issue, IssuePath } from '../model/index.js';\nimport type { FilterPath } from './tree.js';\n\n/**\n * Whether a finding is about the config's own filter tree rather than a\n * nested one.\n *\n * The root tree's findings sit either at the config root — the tree as a\n * whole was refused, for its size or its shape — or under `['children', …]`,\n * which addresses one of its nodes. A metric's, an element's or a dashboard\n * panel's filter is validated in its own scope and re-pathed under\n * `['metrics', …]`, `['elements', …]` or `['panels', …]`, so the first\n * segment is what tells the two apart.\n */\nexport function isRootFilterIssue(found: Issue): boolean {\n return found.path.length === 0 || found.path[0] === 'children';\n}\n\n/**\n * The node a path addresses, as the tree's own addressing: an issue path\n * interleaves the `children` key with each index (`['children', 1]`), and a\n * `FilterPath` is the indexes alone (`[1]`).\n */\nexport function filterIndexes(path: IssuePath): FilterPath {\n return path.filter(\n (segment): segment is number => typeof segment === 'number',\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterNode, FilterTree, Issue } from '../model/index.js';\nimport { filterIndexes } from './issuePath.js';\nimport {\n isFilterGroup,\n isFilterLeaf,\n nodeAt,\n type FilterPath,\n} from './tree.js';\n\n/**\n * The errors a condition editor is not already marking.\n *\n * A wrong condition is marked on its own pill and counted on the Apply\n * button, which is both nearer to the mistake and the only place the mistake\n * can be corrected; repeating it in a strip above says the same thing twice\n * and further from the fix. Everything else — a column the definition\n * dropped, a page size it no longer admits — has no pill to sit on, and a\n * strip is the only way it is ever seen.\n *\n * Which is why the draft tree is asked rather than the path alone: a\n * condition-shaped path is not the same thing as a pill. An editor draws a\n * node only when the tree really holds one there — a malformed child is\n * skipped, and a group carries no marker of its own — so an error addressing\n * anything but a rendered condition is marked nowhere and belongs in the\n * strip. Apply is still refused for it: `blocked` counts every\n * condition-level error, whether or not a pill could be found for it.\n *\n * It lives here rather than beside the editor because it is a question about\n * the tree and nothing else: which paths resolve to a condition a renderer\n * can draw. `useFilterEditor` hands the answer out as `unmarked`, the pair of\n * `blocked`.\n */\nexport function unmarkedErrors(\n issues: readonly Issue[],\n /** The draft the editor beside this strip is showing. */\n tree: FilterTree,\n): Issue[] {\n return issues.filter(\n found => found.severity === 'error' && !isMarked(found, tree),\n );\n}\n\n/** Whether a condition editor puts this finding on a pill of its own. */\nfunction isMarked(found: Issue, tree: FilterTree): boolean {\n if (!found.code.startsWith('filter.') || found.path[0] !== 'children')\n return false;\n // Only a condition wears a mark; a group's own findings wear none.\n return isFilterLeaf(conditionAt(tree, filterIndexes(found.path)));\n}\n\n/**\n * The node a path addresses, descending into a predicate leaf's own tree as\n * the panel does: an element match renders the group its value carries, and\n * the findings inside it are marked on the conditions of that group.\n */\nfunction conditionAt(tree: FilterTree, path: FilterPath): FilterNode | null {\n let node: FilterNode | null = tree;\n for (const index of path) {\n const group = groupOf(node);\n if (group === null) return null;\n node = nodeAt(group, [index]);\n }\n return node;\n}\n\n/** The group a node holds conditions in, its own or a predicate's. */\nfunction groupOf(node: FilterNode | null): FilterTree | null {\n if (node === null) return null;\n if (isFilterGroup(node)) return node;\n return isFilterGroup(node.value) ? node.value : null;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n FieldDefinition,\n FilterLeaf,\n FilterNode,\n FilterTree,\n} from '../model/index.js';\n\n/**\n * The search a view keeps on hand: the text of the search condition on the\n * tree's root, which is where a search box reads and writes it.\n *\n * One condition, on the root: a search box is one box, and a search nested\n * in a group is a condition somebody composed in the editor — the box\n * neither reads it as its own nor overwrites it. `''` when there is none.\n */\nexport function rootSearch(tree: FilterTree, field: string): string {\n if (tree.op !== 'and') return '';\n const leaf = tree.children.find(\n (node): node is FilterLeaf => isLeaf(node) && node.field === field,\n );\n return leaf && typeof leaf.value === 'string' ? leaf.value : '';\n}\n\n/**\n * The tree with its root search set to `text`: the condition's value\n * replaced where it is, added at the end where there was none, and taken\n * out when the text is blank — an empty search is no condition, and a pill\n * left behind for it would be one the reader never added.\n *\n * A root that is not an `and` — an advanced tree whose top is an `or` —\n * keeps its meaning: it becomes the first child of a new `and`, next to the\n * search, so the search narrows it rather than joining its alternatives.\n */\nexport function withRootSearch(\n tree: FilterTree,\n field: string,\n text: string,\n): FilterTree {\n const blank = text.trim().length === 0;\n const root: FilterTree =\n tree.op === 'and' || (blank && tree.children.length === 0)\n ? tree\n : { op: 'and', children: tree.children.length > 0 ? [tree] : [] };\n const at = root.children.findIndex(\n node => isLeaf(node) && node.field === field,\n );\n if (blank)\n return at < 0\n ? root\n : { ...root, children: root.children.filter((_, i) => i !== at) };\n const leaf: FilterLeaf = { field, operator: 'SEARCH', value: text };\n const children =\n at < 0\n ? [...root.children, leaf]\n : root.children.map((node, i) => (i === at ? leaf : node));\n return { ...root, children };\n}\n\n/**\n * The definition's search field — the first, where it declares several —\n * that still searches: one narrowed to no operator (its source offers no\n * search it can use, capabilities.md 4.2, G15) draws no search box.\n */\nexport function searchFieldOf(\n fields: readonly FieldDefinition[],\n): FieldDefinition | null {\n return (\n fields.find(\n field => field.kind === 'search' && field.operators?.length !== 0,\n ) ?? null\n );\n}\n\nfunction isLeaf(node: FilterNode): node is FilterLeaf {\n return 'field' in node;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n isFieldlessKind,\n DEFAULT_RUNTIME_LIMITS,\n type DataViewDefinition,\n type RecordCapability,\n type RecordViewConfig,\n type RuntimeLimits,\n type ViewDefinition,\n nearestPageSize,\n} from '../model/index.js';\nimport { emptyFilter } from '../filter/index.js';\n\nexport function recordCapabilityOf(\n definition: ViewDefinition,\n): RecordCapability | undefined {\n return definition.kind === 'data' ? definition.record : undefined;\n}\n\n/**\n * A complete starting config, because `create` takes a config rather than\n * inventing one: a definition that `validateDefinition` accepted always has a\n * layout and a row key to build from.\n */\nexport function defaultRecordConfig(\n definition: DataViewDefinition,\n limits: RuntimeLimits = DEFAULT_RUNTIME_LIMITS,\n): RecordViewConfig {\n const capability = definition.record;\n if (!capability)\n throw new Error(\n `Definition ${definition.id} declares no record capability`,\n );\n\n // A field-less kind's name is a handle for the editor, not a path into a\n // row, so a column on one would be empty for every record ever shown.\n const names = definition.fields\n .filter(field => !isFieldlessKind(field.kind))\n .map(field => field.name);\n const defaults = capability.defaults ?? {};\n const layout = defaults.layout ?? capability.layouts[0];\n // A view that opens as cards starts on the card ladder's nearest rung, so\n // its first page is whole rows; a size the definition names is its own.\n const pageSize = Math.min(\n defaults.pageSize ??\n (layout === 'card'\n ? nearestPageSize(limits.cardPageSizes, limits.defaultPageSize)\n : limits.defaultPageSize),\n limits.maxPageSize,\n );\n\n return {\n filter: defaults.filter ?? emptyFilter(),\n filterMode: defaults.filterMode ?? 'simple',\n refresh: defaults.refresh ?? { interval: null },\n kind: 'record',\n sort: defaults.sort ?? [],\n pageSize,\n // Written only when there is one. A config is JSON, and a `summaries`\n // member that is `undefined` is not the same object as no member at\n // all — which is what `dirty` compares, and what a store round-trips.\n ...(defaults.summaries ? { summaries: defaults.summaries } : {}),\n layout,\n table: defaults.table ?? {\n columns: names.slice(0, limits.defaultColumns).map(field => ({ field })),\n },\n card: defaults.card ?? {\n title: capability.rowKey,\n fields: names\n .filter(name => name !== capability.rowKey)\n .slice(0, limits.defaultCardFields),\n },\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isFieldlessKind, type DataViewDefinition } from '../model/index.js';\nimport { cardField, type RecordCardField } from './project.js';\n\n/** One titled part of a record's detail: the fields a group gathers. */\nexport interface DetailSection {\n /** The field group's id, or `null` for the fields no group gathers. */\n id: string | null;\n /** The group's label; `null` where the fields gathered no group. */\n label: string | null;\n /**\n * Its fields, resolved the way a card's are — a detail is a card that\n * holds every field — so a value reads there as it does on the card.\n */\n fields: RecordCardField[];\n}\n\n/**\n * How a record's detail is laid out: every field the definition declares,\n * under the groups it declares, in their order — the order the field\n * pickers list them in, so the detail reads like the author arranged the\n * record — and the fields no group gathers after them, in declaration\n * order. A field is listed once, under the first group that names it.\n *\n * Only fields that are a **value on the record** are listed: a fieldless\n * kind — full-text search, the deletion switch, the metadata handles — is a\n * way to filter, and has no value to show.\n */\nexport function detailSections(\n definition: Pick<DataViewDefinition, 'fields' | 'fieldGroups'>,\n): DetailSection[] {\n const valued = definition.fields.filter(\n field => !isFieldlessKind(field.kind),\n );\n const byName = new Map(valued.map(field => [field.name, field]));\n const placed = new Set<string>();\n const sections: DetailSection[] = [];\n for (const group of definition.fieldGroups ?? []) {\n const fields = group.fields.flatMap(name => {\n const field = byName.get(name);\n if (!field || placed.has(name)) return [];\n placed.add(name);\n return [cardField(field)];\n });\n if (fields.length > 0)\n sections.push({ id: group.id, label: group.label, fields });\n }\n const rest = valued.filter(field => !placed.has(field.name));\n if (rest.length > 0)\n sections.push({ id: null, label: null, fields: rest.map(cardField) });\n return sections;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregationGroupType } from '@ahoo-wang/wow-client';\nimport {\n DEFAULT_RUNTIME_LIMITS,\n isSingleStringField,\n type AnalysisGroup,\n type AnalysisMetric,\n type AnalysisViewConfig,\n type DataViewDefinition,\n type FieldDefinition,\n type FilterOperatorName,\n type RecordData,\n type RuntimeLimits,\n} from '../model/index.js';\nimport { operatorsOf, type FieldKindRegistry } from '../filter/index.js';\nimport { fitChartSlots } from './chartSlots.js';\nimport { analysisProbeLimit } from './compile.js';\nimport { limitBounds } from './defaults.js';\n\n/**\n * How many of a field's values a condition is offered, most frequent first:\n * enough that a field with a few dozen values (a processor, an error code)\n * lists every one, few enough that the list is read rather than scrolled.\n * The definition's own `maxLimit` still caps it.\n */\nexport const VALUE_CANDIDATE_LIMIT = 50;\n\n/**\n * The operators whose value is one of the field's own values: equal to it,\n * not equal to it, among them, not among them. A substring or a prefix is a\n * piece of text the user writes — offering whole values there would pick a\n * value where a fragment was meant — so those stay typed.\n */\nexport const VALUE_CANDIDATE_OPERATORS: readonly FilterOperatorName[] = [\n 'EQ',\n 'NE',\n 'IN',\n 'NOT_IN',\n];\n\n/** One value the data holds, and how many records hold it. */\nexport interface ValueCandidate {\n value: string;\n count: number;\n}\n\n/** What one candidate query answered. */\nexport interface ValueCandidates {\n /** Most frequent first; ties by value, so the order is stable. */\n values: ValueCandidate[];\n /**\n * Whether these are every value the question matches. False when the\n * source had more than the limit, so a value that is not listed may still\n * exist — the list is the most frequent, and typing narrows it.\n */\n complete: boolean;\n}\n\n/** The aliases the candidate query names its two columns by. */\nconst VALUE = 'value';\nconst COUNT = 'count';\n\n/**\n * The field a condition's values can be offered for from the data, or\n * `null` when they cannot.\n *\n * Offered when the data can be asked for them and nothing better answers:\n * the definition lets the field be grouped by value (`TERMS`) and records be\n * counted, so the question is one Wow already takes; a record holds one\n * string there, so a group's key is a value an equality can compare against;\n * and the field declares neither `options` (a closed set lists itself, with\n * its labels) nor `remote` (the host searches it). A field inside an array's\n * elements is not a root field and is never offered: its values would be\n * counted over records, not over the elements a predicate tests.\n */\nexport function valueCandidateField(\n definition: DataViewDefinition,\n name: string,\n kinds: FieldKindRegistry,\n): FieldDefinition | null {\n const capability = definition.analysis;\n if (!capability?.count) return null;\n const field = definition.fields.find(entry => entry.name === name);\n if (!field || field.options || field.remote) return null;\n const kind = kinds.get(field.kind);\n if (!kind || !isSingleStringField(field, kind)) return null;\n const groupable = capability.fields.some(\n entry =>\n entry.field === name && entry.groups.includes(AggregationGroupType.TERMS),\n );\n return groupable ? field : null;\n}\n\n/**\n * How a typed fragment narrows the candidates at the source, or `null` when\n * the field lets no condition do it and the list is narrowed where it is.\n *\n * A substring is what a user typing into a list means — 「saga」 should find\n * 「QuotationSaga」 — so `CONTAINS` wins where the field offers it; a prefix\n * is the next best. Either compiles as the field's own conditions do,\n * case and all (`stringComparison`), so the source answers what the list\n * would have shown had it held every value.\n */\nexport function valueCandidateNarrowing(\n field: FieldDefinition,\n kinds: FieldKindRegistry,\n): 'CONTAINS' | 'STARTS_WITH' | null {\n const kind = kinds.get(field.kind);\n const offered = kind ? operatorsOf(field, kind) : [];\n if (offered.includes('CONTAINS')) return 'CONTAINS';\n if (offered.includes('STARTS_WITH')) return 'STARTS_WITH';\n return null;\n}\n\n/** The number of values one candidate query asks for, under every ceiling. */\nexport function valueCandidateLimit(\n definition: DataViewDefinition,\n limits: RuntimeLimits = DEFAULT_RUNTIME_LIMITS,\n): number {\n return Math.min(\n VALUE_CANDIDATE_LIMIT,\n limitBounds(definition.analysis, limits).max,\n );\n}\n\n/**\n * The candidates of `field` as an analysis: records counted by the field's\n * value, the most frequent first, the first `valueCandidateLimit` of them —\n * narrowed to the values holding `query` where the field allows it.\n *\n * It is an ordinary analysis config on purpose, so it is admitted by\n * `validateAnalysis` and compiled by `compileAnalysis` like any other, and a\n * host scope is merged into it by the same `withScopeFilter` — there is no\n * second spelling of a Wow aggregation to keep in step with the first.\n *\n * Its dimension carries no sentinel bucket, unlike the one `groupOfType`\n * builds: a view that counts by value must not drop the records missing it,\n * but a list of values to compare against has no use for them — 「has no\n * value」 is `IS_NULL`, a condition of its own, not a value to pick.\n */\nexport function valueCandidatesConfig(\n definition: DataViewDefinition,\n field: FieldDefinition,\n kinds: FieldKindRegistry,\n query = '',\n limits: RuntimeLimits = DEFAULT_RUNTIME_LIMITS,\n): AnalysisViewConfig {\n const text = query.trim();\n const narrowing = text ? valueCandidateNarrowing(field, kinds) : null;\n const group: AnalysisGroup = {\n type: 'TERMS',\n field: field.name,\n alias: VALUE,\n };\n const metric: AnalysisMetric = { type: 'COUNT', alias: COUNT };\n return {\n kind: 'analysis',\n filter: {\n op: 'and',\n children: narrowing\n ? [{ field: field.name, operator: narrowing, value: text }]\n : [],\n },\n filterMode: 'advanced',\n refresh: { interval: null },\n groups: [group],\n metrics: [metric],\n // Most frequent first, unless the source orders groups by their keys\n // alone (`metricSort`): then alphabetically.\n sort:\n definition.analysis?.metricSort === false\n ? [{ alias: VALUE, direction: 'ASC' }]\n : [\n { alias: COUNT, direction: 'DESC' },\n { alias: VALUE, direction: 'ASC' },\n ],\n limit: valueCandidateLimit(definition, limits),\n layout: 'table',\n table: { columns: [] },\n chart: fitChartSlots({ type: 'bar' }, [group], [metric], new Set()),\n };\n}\n\n/**\n * The rows a candidate query answered, as candidates.\n *\n * A key that is not a non-empty string is left out: an empty string is not a\n * value an equality condition takes (`IS_EMPTY_STRING` asks for it), and a\n * key of any other type cannot be what a text condition compares with.\n *\n * Whether the list is whole is read off the probe row `compileAnalysis` asks\n * for (`analysisProbeLimit`): it came back, so there are more values than the\n * limit. With no probe — the limit already on a ceiling — a full list is\n * called incomplete, since it may be.\n */\nexport function readValueCandidates(\n definition: DataViewDefinition,\n config: AnalysisViewConfig,\n rows: readonly RecordData[],\n limits?: Pick<RuntimeLimits, 'maxAnalysisRows'>,\n): ValueCandidates {\n const probe = analysisProbeLimit(definition, config, limits);\n const complete =\n probe > config.limit\n ? rows.length <= config.limit\n : rows.length < config.limit;\n const values = rows.slice(0, config.limit).flatMap(row => {\n const value = row[VALUE];\n const count = row[COUNT];\n return typeof value === 'string' && value !== ''\n ? [{ value, count: typeof count === 'number' ? count : 0 }]\n : [];\n });\n return { values, complete };\n}\n\n/**\n * The candidates in hand narrowed to those holding `query`, the way the\n * source would narrow them: ignoring case unless the field says its case\n * carries meaning, by substring or by prefix as `valueCandidateNarrowing`\n * picks — by substring where the source cannot narrow at all.\n */\nexport function narrowValueCandidates(\n values: readonly ValueCandidate[],\n field: FieldDefinition,\n kinds: FieldKindRegistry,\n query: string,\n): ValueCandidate[] {\n const text = query.trim();\n if (!text) return [...values];\n const sensitive = field.stringComparison === 'CASE_SENSITIVE';\n const fold = (value: string) => (sensitive ? value : value.toLowerCase());\n const wanted = fold(text);\n const prefix = valueCandidateNarrowing(field, kinds) === 'STARTS_WITH';\n return values.filter(({ value }) =>\n prefix ? fold(value).startsWith(wanted) : fold(value).includes(wanted),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n isValueMetric,\n type AnalysisHavingExpression,\n type AnalysisMetric,\n type AnalysisViewConfig,\n} from '../model/index.js';\n\n/** What a metric may be read by, beyond its being there. */\nexport interface DanglingFacts {\n /** The metrics that are moments (`momentMetrics`): no operand, no having. */\n moments?: ReadonlySet<string>;\n /** The metric types 「只保留」 may compare (`havingMetrics`); all when absent. */\n havingMetrics?: readonly string[];\n}\n\nexport interface WithoutDangling {\n metrics: AnalysisViewConfig['metrics'];\n /** The same object when nothing in it moved; `undefined` when none is left. */\n having: AnalysisHavingExpression | undefined;\n /** The aliases of the derived metrics that left with what they read. */\n removed: string[];\n}\n\ntype Shape = Pick<AnalysisViewConfig, 'groups' | 'metrics' | 'having'>;\n\n/** The config an edit started from, and what its metrics were read by. */\nexport interface DanglingBefore {\n shape: Pick<AnalysisViewConfig, 'groups' | 'metrics'>;\n facts?: DanglingFacts;\n}\n\n/**\n * The metrics and the having an edit to what is grouped or measured leaves\n * reading something: the one rule every such edit follows, the way the\n * chart, the sort and the table columns follow the aliases.\n *\n * - **A derived metric leaves with an operand it can no longer read**: one\n * gone, turned into a sample value or a moment, or declared after it —\n * the rules `analysis.derived.unknown-metric` and `…moment-operand` hold\n * it to. Walked in order, so a derived metric reading one that just left\n * leaves too.\n * - **A having rule on a metric it can no longer compare no longer\n * constrains**: it leaves an `AND`, and an `OR` it sits in leaves with it\n * (one side holding for every group keeps every group). No rule left, no\n * having; no dimension left, no having either — Wow has no groups to\n * keep (`analysis.having.requires-group`).\n *\n * Only what the edit broke goes (`before`, the config it started from): a\n * derived metric or a rule that already read nothing stays, for admission\n * to point at, rather than vanishing under an edit about something else,\n * and so does a metric the edit itself changed (not the object `before`\n * held) — the card being typed into is not fallout.\n * Without `before`, everything that reads nothing goes. The metrics may\n * come out empty: the caller says what an empty question becomes.\n */\nexport function withoutDangling(\n shape: Shape,\n facts: DanglingFacts = {},\n before?: DanglingBefore,\n): WithoutDangling {\n const dangling = danglingIn(shape.metrics, facts);\n const was = before && danglingIn(before.shape.metrics, before.facts ?? {});\n // Fallout is a metric this edit left as it was that reads nothing now and\n // read something before; one it changed is the author's, mid-edit, and\n // stays for admission to point at, as one broken already does.\n const untouched = (metric: AnalysisMetric) =>\n before === undefined ||\n before.shape.metrics.some(\n entry => entry === metric && !was?.has(entry.alias),\n );\n const removed = shape.metrics\n .filter(metric => dangling.has(metric.alias) && untouched(metric))\n .map(metric => metric.alias);\n const metrics =\n removed.length === 0\n ? shape.metrics\n : (shape.metrics.filter(\n metric => !removed.includes(metric.alias),\n ) as AnalysisViewConfig['metrics']);\n // A rule stands unless it compared something before and cannot now.\n const now = comparableIn(metrics, facts);\n const then = before && comparableIn(before.shape.metrics, before.facts ?? {});\n const stands = (metric: string) =>\n now.has(metric) || (then !== undefined && !then.has(metric));\n const ungrouped =\n shape.groups.length === 0 &&\n (before === undefined || before.shape.groups.length > 0);\n const having =\n shape.having === undefined || ungrouped\n ? undefined\n : kept(shape.having, stands);\n return { metrics, having, removed };\n}\n\n/** The derived metrics of a list that read nothing, in cascade. */\nfunction danglingIn(\n metrics: readonly AnalysisMetric[],\n { moments = new Set() }: DanglingFacts,\n): Set<string> {\n const readable = new Set<string>();\n const dangling = new Set<string>();\n for (const metric of metrics) {\n if (\n metric.type === 'DERIVED' &&\n !derivedRefs(metric.expression).every(alias => readable.has(alias))\n )\n dangling.add(metric.alias);\n else if (!isValueMetric(metric) && !moments.has(metric.alias))\n readable.add(metric.alias);\n }\n return dangling;\n}\n\n/**\n * The metrics a having may compare, as admission reads them\n * (`validateHaving`): any but a sample value or a moment, of a type the\n * source compares.\n */\nfunction comparableIn(\n metrics: readonly AnalysisMetric[],\n { moments = new Set(), havingMetrics }: DanglingFacts,\n): Set<string> {\n return new Set(\n metrics\n .filter(\n metric =>\n !isValueMetric(metric) &&\n !moments.has(metric.alias) &&\n (havingMetrics === undefined || havingMetrics.includes(metric.type)),\n )\n .map(metric => metric.alias),\n );\n}\n\n/** The node less the rules that no longer stand; `undefined` when it keeps all. */\nfunction kept(\n node: AnalysisHavingExpression,\n stands: (metric: string) => boolean,\n): AnalysisHavingExpression | undefined {\n // A shape admission refuses is left for admission to say.\n if (typeof node !== 'object' || node === null) return node;\n if (!('operands' in node)) return stands(node.metric) ? node : undefined;\n if (!Array.isArray(node.operands)) return node;\n const operands = node.operands.map(operand => kept(operand, stands));\n if (operands.every((operand, at) => operand === node.operands[at]))\n return node;\n if (node.type === 'OR' && operands.includes(undefined)) return undefined;\n const left = operands.filter(\n (operand): operand is AnalysisHavingExpression => operand !== undefined,\n );\n return left.length === 0\n ? undefined\n : {\n ...node,\n operands: left as [\n AnalysisHavingExpression,\n ...AnalysisHavingExpression[],\n ],\n };\n}\n\n/** The aliases a derived expression reads. */\nexport function derivedRefs(\n expression: Extract<AnalysisMetric, { type: 'DERIVED' }>['expression'],\n): string[] {\n switch (expression?.type) {\n case 'METRIC_REF':\n return [expression.metric];\n case 'BINARY':\n return [\n ...derivedRefs(expression.left),\n ...derivedRefs(expression.right),\n ];\n default:\n return [];\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n groupFieldsOf,\n type AnalysisCapability,\n type AnalysisElement,\n type AnalysisGroup,\n type AnalysisMetric,\n type AnalysisViewConfig,\n type DataViewDefinition,\n type FieldDefinition,\n} from '../model/index.js';\nimport { filterFields } from '../filter/index.js';\nimport { analysisScope, type AnalysisScope } from './capability.js';\nimport { withoutDangling } from './dangling.js';\nimport { firstMetric } from './defaults.js';\nimport { momentMetrics } from './metricFormat.js';\n\n/**\n * The config re-scoped to a new expansion chain (D20 屏 G).\n *\n * Expanding an array changes the counting unit: after `orders → lines` the\n * dimensions and the metrics can only name the line's fields, and a\n * dimension over the order's warehouse is a question about the wrong thing\n * (Wow refuses it as outside the element scope). So a step into or out of\n * the chain takes with it every dimension and metric that no longer names\n * a field of the new unit — and a metric's own condition that names one —\n * and, when that leaves nothing to measure, starts the metrics again from\n * the first thing the new unit can count, as a fresh analysis would. What\n * still names a field of the unit is kept as it was.\n *\n * A derived metric that read a metric that left goes too, and one that read\n * it after it (`withoutDangling`); one that read nothing before the step\n * stays for admission to point at. The chart, the sort, the table columns\n * and the having follow the survivors the way they follow any change of\n * groups and metrics (`useAnalysisEditor`'s reshape), so this answers only\n * what is grouped and measured — and, in `dropped`, what the step took\n * away, so the editor can say so and offer it back (D71: no confirmation,\n * an undo).\n */\nexport function withElements(\n config: AnalysisViewConfig,\n elements: AnalysisElement[],\n definition: DataViewDefinition,\n capability: AnalysisCapability,\n): Rescoped {\n const scope = analysisScope(definition, capability, { elements });\n const inScope = (field: string) => scope.fields.has(field);\n const groups = config.groups.filter(group =>\n groupFieldsOf(group).every(inScope),\n );\n const kept = config.metrics.filter(metric =>\n measuresInScope(metric, inScope),\n );\n const metrics = kept.map(metric => {\n if (metric.type === 'DERIVED' || !metric.filter) return metric;\n // A condition naming a field outside the new unit asks about the wrong\n // thing; the metric stays, its condition goes.\n return filterFields(metric.filter).every(inScope)\n ? metric\n : withoutFilter(metric);\n });\n // A derived metric that read one that left goes with it, in cascade;\n // one that read nothing before the step is not the step's to take.\n const { metrics: derivable } = withoutDangling(\n { groups, metrics: metrics as AnalysisViewConfig['metrics'] },\n { moments: momentMetrics(metrics, scope.fields) },\n {\n shape: config,\n facts: {\n moments: momentMetrics(\n config.metrics,\n analysisScope(definition, capability, config).fields,\n ),\n },\n },\n );\n const next: AnalysisViewConfig['metrics'] =\n derivable.length > 0\n ? derivable\n : [firstMetric(capability.count, [...scope.aggregations.values()])];\n const stays = new Set(next.map(metric => metric.alias));\n return {\n elements: elements.length === 0 ? [] : elements,\n groups,\n metrics: next,\n dropped: {\n groups: config.groups.filter(group => !groups.includes(group)),\n metrics: config.metrics.filter(metric => !stays.has(metric.alias)),\n },\n };\n}\n\n/** What a step of the chain took out of the question. */\nexport interface Dropped {\n groups: AnalysisGroup[];\n metrics: AnalysisMetric[];\n}\n\n/** The config re-scoped to a chain, and what the step took away. */\nexport interface Rescoped extends Pick<\n AnalysisViewConfig,\n 'elements' | 'groups' | 'metrics'\n> {\n dropped: Dropped;\n}\n\n/** The chain one level deeper: the declared next step, with no gate yet. */\nexport function withLevel(\n elements: readonly AnalysisElement[],\n path: string,\n): AnalysisElement[] {\n return [...elements, { path }];\n}\n\n/** The chain cut at `index`: that level and every level inside it leave. */\nexport function withoutLevelsFrom(\n elements: readonly AnalysisElement[],\n index: number,\n): AnalysisElement[] {\n return elements.slice(0, Math.max(0, index));\n}\n\n/**\n * The next level the capability declares beyond what is expanded, or none:\n * the chain is one line, so there is at most one thing to expand into.\n */\nexport function nextExpansion(\n declaredChain: readonly string[],\n elements: readonly AnalysisElement[],\n): string | undefined {\n return declaredChain[elements.length];\n}\n\n/**\n * The fields the level at `depth` is chosen from, under their own names:\n * the definition's for the first level, the level outside it for the rest.\n * The array a level expands is one of these, and its label is what the\n * level is called.\n */\nfunction holderFields(\n definition: DataViewDefinition,\n scope: AnalysisScope,\n depth: number,\n): readonly FieldDefinition[] {\n if (depth === 0) return definition.fields;\n const outer = scope.elements[depth - 1];\n if (!outer) return [];\n return [...outer.fields.values()].map(field => ({\n ...field,\n name: field.name.slice(outer.absolute.length + 1),\n }));\n}\n\n/** What the level at `index` is called: its array's label, else its path. */\nexport function levelLabel(\n definition: DataViewDefinition,\n scope: AnalysisScope,\n index: number,\n): string {\n const level = scope.elements[index];\n if (!level) return '';\n return (\n holderFields(definition, scope, index).find(\n field => field.name === level.path,\n )?.label ?? level.path\n );\n}\n\n/** The next step of the declared chain, named, or none. */\nexport function nextLevel(\n definition: DataViewDefinition,\n scope: AnalysisScope,\n elements: readonly AnalysisElement[],\n): { path: string; label: string } | undefined {\n const path = nextExpansion(scope.declaredChain, elements);\n if (path === undefined) return undefined;\n const label =\n holderFields(definition, scope, elements.length).find(\n field => field.name === path,\n )?.label ?? path;\n return { path, label };\n}\n\nfunction measuresInScope(\n metric: AnalysisMetric,\n inScope: (field: string) => boolean,\n): boolean {\n switch (metric.type) {\n case 'COUNT':\n case 'DERIVED':\n return true;\n case 'ANY':\n return inScope(metric.field);\n case 'FIRST':\n case 'LAST':\n return (\n inScope(metric.field) &&\n (metric.orderBy === undefined || inScope(metric.orderBy))\n );\n default:\n return expressionFields(metric.expression).every(inScope);\n }\n}\n\nfunction expressionFields(\n expression: Extract<AnalysisMetric, { type: 'NUMERIC' }>['expression'],\n): string[] {\n switch (expression.type) {\n case 'FIELD':\n return [expression.field];\n case 'BINARY':\n return [\n ...expressionFields(expression.left),\n ...expressionFields(expression.right),\n ];\n case 'DATE_DIFF':\n return [expression.from, expression.to];\n default:\n return [];\n }\n}\n\nfunction withoutFilter(metric: AnalysisMetric): AnalysisMetric {\n const next = { ...metric } as AnalysisMetric & { filter?: unknown };\n delete next.filter;\n return next;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AnalysisDateUnit,\n AnalysisGroup,\n FilterTree,\n RecordData,\n} from '../model/index.js';\nimport { readInstant } from '../filter/index.js';\nimport { bucketRange } from './drill.js';\nimport { appliedWindow } from './timeAxis.js';\n\n/**\n * Which granularity a time dimension starts at (K4). A fresh dimension used\n * to start at the first unit the field offers, whatever the range: a year\n * of orders cut by the hour is eight thousand buckets nobody asked for, and\n * a week cut by the month is one. The recommendation reads the span the\n * analysis is over — the applied range's conditions on the field first,\n * failing that the buckets a result already has on it — and picks the\n * coarsest offered unit that still cuts it into a readable number of\n * buckets. A hand-picked unit always wins over it; this only answers what a\n * new dimension starts as.\n */\n\n/** Roughly how long each unit is, for counting buckets across a span. */\nconst UNIT_MS: Record<AnalysisDateUnit, number> = {\n SECOND: 1000,\n MINUTE: 60_000,\n HOUR: 3_600_000,\n DAY: 86_400_000,\n WEEK: 7 * 86_400_000,\n MONTH: 30.4375 * 86_400_000,\n QUARTER: 91.3125 * 86_400_000,\n YEAR: 365.25 * 86_400_000,\n};\n\n/** Every unit, finest first. */\nconst FINE_TO_COARSE: readonly AnalysisDateUnit[] = [\n 'SECOND',\n 'MINUTE',\n 'HOUR',\n 'DAY',\n 'WEEK',\n 'MONTH',\n 'QUARTER',\n 'YEAR',\n];\n\n/** Fewer buckets than this and the chart is a couple of bars; the unit is too coarse. */\nconst MIN_BUCKETS = 6;\n\n/**\n * The coarsest offered unit that cuts `span` milliseconds into at least a\n * handful of buckets, or the finest offered one when nothing does, or the\n * first offered one when there is no span to read.\n */\nexport function recommendDateUnit(\n span: number | null,\n offered: readonly AnalysisDateUnit[],\n): AnalysisDateUnit {\n const first = offered[0] ?? 'DAY';\n if (span === null || !Number.isFinite(span) || span <= 0) return first;\n const candidates = FINE_TO_COARSE.filter(unit => offered.includes(unit));\n if (candidates.length === 0) return first;\n for (let at = candidates.length - 1; at >= 0; at -= 1) {\n const unit = candidates[at];\n if (span / UNIT_MS[unit] >= MIN_BUCKETS) return unit;\n }\n return candidates[0];\n}\n\n/**\n * The span the applied range pins on `field`, in milliseconds, or null when\n * it pins none. Only the conditions the tree ANDs together count — a\n * condition under an OR is one alternative, not a bound — and a window\n * needs both ends: a lower bound alone runs to now, an upper bound alone\n * says nothing about where the data starts.\n */\nexport function rangeSpan(\n filter: FilterTree,\n field: string,\n now: Date,\n timeZone: string,\n): number | null {\n const { from, to } = appliedWindow(filter, field, now, timeZone);\n if (from === null) return null;\n const end = to ?? now.getTime();\n return end > from ? end - from : null;\n}\n\n/**\n * The span a result already cut on `field`, from its first bucket's start\n * to its last bucket's end, or null when the result has no time dimension\n * on the field or no rows.\n */\nexport function resultSpan(\n rows: readonly RecordData[],\n groups: readonly AnalysisGroup[],\n field: string,\n timeZone: string,\n): number | null {\n const group = groups.find(\n entry => entry.type === 'DATE_HISTOGRAM' && entry.field === field,\n );\n if (!group || group.type !== 'DATE_HISTOGRAM') return null;\n let first: number | null = null;\n let last: number | null = null;\n for (const row of rows) {\n const start = readInstant(row[group.alias])?.ms;\n if (start === undefined) continue;\n first = first === null ? start : Math.min(first, start);\n last = last === null ? start : Math.max(last, start);\n }\n if (first === null || last === null) return null;\n const end = bucketRange(group.unit, last, group.timeZone ?? timeZone).to;\n return end > first ? end - first : null;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AnalysisHavingExpression } from '../model/index.js';\n\n/**\n * 「只保留」 (D20 屏 B; Wow `having`): the grouped rows kept, said as rows of\n * one comparison each — 「金额总和 大于 10,000」 — all of which must hold.\n * Wow's having is a small expression language (conditions, ranges, sets,\n * null checks, and/or trees); the tray offers the one shape an analyst\n * reaches for, a conjunction of comparisons, and reads any other shape a\n * stored config holds as \"not editable here\" rather than flattening it\n * into something it is not.\n */\n\n/** The comparisons one row may make: the model's, never listed again. */\nexport type HavingOperator = Extract<\n AnalysisHavingExpression,\n { type: 'CONDITION' }\n>['operator'];\n\n/**\n * Every comparison, in the order the select lists them. A `Record` over the\n * operator type rather than an array, so an operator Wow adds is a compile\n * error here until it is given a place — not a choice the tray silently\n * never offers.\n */\nconst HAVING_OPERATOR_ORDER: Record<HavingOperator, true> = {\n GT: true,\n GTE: true,\n LT: true,\n LTE: true,\n EQ: true,\n NE: true,\n};\n\nexport const HAVING_OPERATORS = Object.keys(\n HAVING_OPERATOR_ORDER,\n) as readonly HavingOperator[];\n\n/** One row of the editor: keep the groups whose metric compares so. */\nexport interface HavingRow {\n metric: string;\n operator: HavingOperator;\n /** `null` while the row is being filled in. */\n value: number | null;\n}\n\n/**\n * The rows a having expression is made of, or `null` when it is a shape the\n * rows cannot say: a range, a set, a null check, an OR anywhere. A stored\n * config may hold those; the editor then shows the expression is there\n * and offers to clear it, but does not pretend to edit it.\n */\nexport function havingRows(\n having: AnalysisHavingExpression | undefined,\n): HavingRow[] | null {\n if (!having) return [];\n if (having.type === 'CONDITION')\n return [\n {\n metric: having.metric,\n operator: having.operator,\n value: having.value,\n },\n ];\n if (having.type !== 'AND') return null;\n const rows: HavingRow[] = [];\n for (const operand of having.operands) {\n const inner = havingRows(operand);\n if (inner === null || operand.type === 'AND') return null;\n rows.push(...inner);\n }\n return rows;\n}\n\n/**\n * The expression the rows say: one condition on its own, several under\n * one AND, none at all as no having. A row still being filled in — no\n * value yet — is written as a condition on `NaN` is not: it is left out\n * of the query and kept only by the editor, so the config on disk is\n * always one Wow accepts.\n */\nexport function withHavingRows(\n rows: readonly HavingRow[],\n): AnalysisHavingExpression | undefined {\n const complete = rows.filter(\n (row): row is HavingRow & { value: number } => row.value !== null,\n );\n const conditions: AnalysisHavingExpression[] = complete.map(row => ({\n type: 'CONDITION',\n metric: row.metric,\n operator: row.operator,\n value: row.value,\n }));\n if (conditions.length === 0) return undefined;\n if (conditions.length === 1) return conditions[0];\n return {\n type: 'AND',\n operands: conditions as [\n AnalysisHavingExpression,\n ...AnalysisHavingExpression[],\n ],\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DASHBOARD_GRID_COLUMNS,\n type DashboardViewConfig,\n} from '../model/index.js';\nimport { emptyFilter } from '../filter/index.js';\n\n/**\n * A complete starting config, the dashboard counterpart of the two\n * `default*Config` functions.\n *\n * It takes no definition: a dashboard owns no data, so there is nothing to\n * read from a capability. An empty dashboard is valid, and the user fills it\n * by adding panels.\n *\n * A new board is laid out at the fixed width, centred (D31, as Metabase's\n * new dashboards are); only a board saved before it could say is full.\n */\nexport function emptyDashboardConfig(): DashboardViewConfig {\n return {\n refresh: { interval: null },\n kind: 'dashboard',\n columns: DASHBOARD_GRID_COLUMNS,\n width: 'fixed',\n fixed: emptyFilter(),\n tabs: [],\n fields: [],\n panels: [],\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Where panels may go: the one set of geometry rules the runtime places by\n * and the grid previews by.\n *\n * A panel is placed by hand in three ways — dragged, resized by its corner,\n * or stepped by a keyboard command — and each lands on the same thing, a new\n * `PanelLayout` for one panel. What happens to the others is decided here,\n * once, and it is what a Metabase board does (D22, batch-A walk): the panel\n * placed takes the cells it asked for, whatever it covers makes way, and\n * then every panel of its tab floats up as far as it can, so a move leaves\n * no hole behind — the vertical compaction react-grid-layout would run,\n * written here so the keyboard and the pointer land on one answer.\n *\n * Only a hand compacts. A stored board is drawn as it was saved, holes and\n * all, and opening it never moves a panel; the first placement tidies the\n * tab it happens on.\n */\n\nimport {\n DASHBOARD_GRID_COLUMNS,\n hasFixedHeight,\n type DashboardPanel,\n type DashboardViewConfig,\n type PanelLayout,\n} from '../model/index.js';\nimport { isPlainObject } from '../filter/index.js';\nimport { panelsOf, panelTab } from './panels.js';\nimport { validateLayout } from './validate.js';\n\n/** One keyboard command: a step of one grid cell, or a size one cell bigger or smaller. */\nexport type ArrangeStep =\n | 'left'\n | 'right'\n | 'up'\n | 'down'\n | 'wider'\n | 'narrower'\n | 'taller'\n | 'shorter';\n\n/**\n * Whether a layout is one admission accepts: `x` and `y` non-negative\n * integers, `w` and `h` positive ones, and `x + w` inside the grid. The\n * same rule `validateDashboard` reports against, so nothing placed here can\n * come back from it as an error.\n */\nexport function fitsGrid(\n layout: unknown,\n columns: number = DASHBOARD_GRID_COLUMNS,\n): layout is PanelLayout {\n return (\n isPlainObject(layout) &&\n validateLayout(layout as unknown as PanelLayout, [], columns).length === 0\n );\n}\n\n/** A panel's geometry under its id: what `placePanel` reads and returns. */\nexport interface PlacedPanel extends PanelLayout {\n id: string;\n}\n\n/** Whether two boxes share at least one cell. */\nexport function overlaps(a: PanelLayout, b: PanelLayout): boolean {\n return (\n a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h\n );\n}\n\n/** The first row below every panel: where a board ends. */\nexport function bottomOf(panels: readonly PanelLayout[]): number {\n return panels.reduce(\n (bottom, panel) => Math.max(bottom, panel.y + panel.h),\n 0,\n );\n}\n\n/**\n * The panels floated up: each, in reading order, rises as far as it can\n * without touching one already settled, and one that overlaps a settled\n * panel (a stored config may hold two on one cell) drops below it instead.\n * No panel passes another on the way up, so the order a reader sees down a\n * column is kept; only the holes go.\n */\nexport function compactLayout(panels: readonly PlacedPanel[]): PlacedPanel[] {\n return compactAround(panels, [], -1);\n}\n\n/**\n * The panels after one of them is put at `layout`, or `null` when the\n * placement is not one the grid admits or names no panel.\n *\n * The panel placed is held at the cells it asked for while the others are\n * compacted around it, in their reading order: one it covers drops below it,\n * one it has moved out from under rises into the room it left. Then it is\n * let go, and the whole tab is compacted — the panel placed rises too, until\n * something is above it. So a panel dropped past the one under it trades\n * places with it, and one dropped into empty space below the rest comes up\n * to rest under them.\n */\nexport function placePanel(\n panels: readonly PlacedPanel[],\n id: string,\n layout: PanelLayout,\n columns: number = DASHBOARD_GRID_COLUMNS,\n): PlacedPanel[] | null {\n const at = panels.findIndex(panel => panel.id === id);\n if (at < 0 || !fitsGrid(layout, columns)) return null;\n const held: PlacedPanel = { id, ...geometry(layout) };\n const others = [...panels];\n others[at] = held;\n return compactLayout(compactAround(others, [held], at, held));\n}\n\n/**\n * Where one keyboard command puts the panel, as the layout to hand `place`,\n * or `null` when it would change nothing the reader could see.\n *\n * Sideways and in size, one command is one cell, as a drag snaps to one.\n * Up and down are what a compacted board makes of them: a panel stepped one\n * row down into the one under it floats straight back, so \"down\" is the\n * smallest drop that lands it somewhere else — past the panel below — and\n * the bottom panel of a column has nowhere to go down. Up is the same the\n * other way. A step off the grid is `null` as well, so a menu disables it\n * rather than offering a command that does nothing.\n */\nexport function arrangePanel(\n panels: readonly PlacedPanel[],\n id: string,\n step: ArrangeStep,\n columns: number = DASHBOARD_GRID_COLUMNS,\n): PanelLayout | null {\n const panel = panels.find(entry => entry.id === id);\n // Where it rests now: the baseline a command has to differ from.\n const resting = panel && placePanel(panels, id, panel, columns);\n if (!panel || !resting) return null;\n const reach = step === 'up' || step === 'down' ? bottomOf(panels) + 1 : 1;\n for (let distance = 1; distance <= reach; distance += 1) {\n const target = stepped(panel, step, distance);\n const placed = placePanel(panels, id, target, columns);\n if (!placed) return null;\n if (!samePlacement(placed, resting)) return target;\n }\n return null;\n}\n\n/**\n * The first place a new panel of this size can go: free, at rest (the\n * compaction a later placement runs would not lift it), and at or below\n * `fromRow` — the first row the reader has on screen, so what they add\n * lands where they are looking (D22 A). Rows top to bottom, each left to\n * right. When nothing down to the board's end will take it, it goes under\n * everything and rises to rest there.\n */\nexport function freeSpot(\n panels: readonly PanelLayout[],\n size: { w: number; h: number },\n columns: number = DASHBOARD_GRID_COLUMNS,\n fromRow = 0,\n): PanelLayout {\n const w = Math.min(Math.max(1, size.w), columns);\n const h = Math.max(1, size.h);\n const boxes = panels.map(panel => ({ id: '', ...geometry(panel) }));\n const bottom = bottomOf(panels);\n for (let y = Math.max(0, fromRow); y < bottom; y += 1)\n for (let x = 0; x + w <= columns; x += 1) {\n const spot = { x, y, w, h };\n if (boxes.some(box => overlaps(box, spot))) continue;\n if (settle({ id: '', ...spot }, boxes).y === y) return spot;\n }\n return geometry(settle({ id: '', x: 0, y: bottom, w, h }, boxes));\n}\n\n/**\n * A config with one panel placed and the rest of its tab compacted around\n * it, or the same config when the placement changes nothing or cannot be\n * made.\n *\n * Only the panel's own tab moves: another tab is another grid, whose\n * panels share no cell with these whatever their numbers say. Read as the\n * untrusted thing a stored config is: an entry that is no panel, or a panel\n * whose layout admission would refuse, takes no part — it is not moved and\n * moves nothing — and is handed back untouched.\n *\n * `grown` is the rows each panel is drawn tall where the screen grew it\n * past what is saved (`grownLayout`, D52): a hand places against the board\n * it sees, so the placement lands on the tab as drawn. What is written back\n * is only what the hand moved (D68): the panel placed, and where another\n * panel had to go — the row it is saved at, chosen so that the board grown\n * again draws it where the author saw it. No untouched panel's saved height\n * changes, since a grown height is one day's data, not a size anyone chose;\n * and a panel only moved keeps its saved height too. A placement that moves\n * nothing hands the same config back. A `layout` that says `fixedHeight`\n * marks the panel sized by hand; one that does not say keeps what the panel\n * had, as every other panel does.\n */\nexport function placePanelIn(\n config: DashboardViewConfig,\n id: string,\n layout: PanelLayout,\n columns: number = DASHBOARD_GRID_COLUMNS,\n grown?: ReadonlyMap<string, number>,\n): DashboardViewConfig {\n const boxes = tabBoxes(config, id, columns);\n const shown = boxes && grown ? grownLayout(boxes, grown) : boxes;\n const placed = shown && placePanel(shown, id, layout, columns);\n if (!boxes || !shown || !placed) return config;\n const saved = savedPlacement(boxes, shown, placed, id, layout);\n return withLayouts(\n config,\n layout.fixedHeight === undefined\n ? saved\n : saved.map(box =>\n box.id === id ? { ...box, fixedHeight: layout.fixedHeight } : box,\n ),\n );\n}\n\n/**\n * The saved boxes behind a placement made on the tab as drawn: `boxes` as\n * saved, `shown` as drawn before the hand, `placed` as drawn after it.\n *\n * Each panel keeps its saved height — except the one placed when the hand\n * changed its height, or sized it (`fixedHeight`) — and keeps, below the\n * lowest of the panels above it, the rows it is drawn clear of the lowest\n * of them drawn: the one thing `grownLayout` reads a saved row by. So the\n * board grown again is exactly the board the author let go of (D68), for\n * every placement: read in the same order, each panel lands on the same\n * panels above it, as far below the lowest of them as it was let go. A\n * panel neither placed nor pushed comes out with the row it had, and no\n * two saved panels share a cell, since each is saved under every panel\n * that is drawn above it.\n */\nfunction savedPlacement(\n boxes: readonly PlacedPanel[],\n shown: readonly PlacedPanel[],\n placed: readonly PlacedPanel[],\n id: string,\n layout: PanelLayout,\n): PlacedPanel[] {\n const stored = new Map(boxes.map(box => [box.id, box]));\n const drawnBefore = new Map(shown.map(box => [box.id, box]));\n const heightOf = (box: PlacedPanel): number => {\n const own = stored.get(box.id)!;\n if (box.id !== id) return own.h;\n const resized =\n layout.fixedHeight === true ||\n hasFixedHeight(own) ||\n box.h !== drawnBefore.get(box.id)!.h;\n return resized ? box.h : own.h;\n };\n const saved = new Map<string, PlacedPanel>();\n const read = readingOrder(placed.map(box => ({ box, layout: box })));\n for (const { box } of read) {\n // The lowest panel drawn above it, drawn and saved.\n let drawnFloor = -1;\n let savedFloor = 0;\n for (const { box: above } of read) {\n const settled = saved.get(above.id);\n if (!settled || !stacked(above, box)) continue;\n drawnFloor = Math.max(drawnFloor, above.y + above.h);\n savedFloor = Math.max(savedFloor, settled.y + settled.h);\n }\n const y = drawnFloor < 0 ? box.y : savedFloor + (box.y - drawnFloor);\n saved.set(box.id, { id: box.id, x: box.x, y, w: box.w, h: heightOf(box) });\n }\n return placed.map(box => saved.get(box.id)!);\n}\n\n/** Whether `above` stands wholly over `below`, sharing a column with it. */\nfunction stacked(above: PanelLayout, below: PanelLayout): boolean {\n return (\n above.y + above.h <= below.y &&\n above.x < below.x + below.w &&\n below.x < above.x + above.w\n );\n}\n\n/**\n * The boxes of the panels on the tab of the panel `id`, or `null` when the\n * config holds no such panel: only its own tab moves with it, since another\n * tab is another grid.\n */\nfunction tabBoxes(\n config: DashboardViewConfig,\n id: string,\n columns: number,\n): PlacedPanel[] | null {\n const panels: readonly unknown[] = panelsOf(config);\n const moving = panels.find(\n (panel): panel is DashboardPanel => isPlainObject(panel) && panel.id === id,\n );\n if (!moving) return null;\n const tab = panelTab(config, moving);\n return panels.flatMap((panel): PlacedPanel[] =>\n isPlainObject(panel) &&\n typeof panel.id === 'string' &&\n fitsGrid(panel.layout, columns) &&\n panelTab(config, panel) === tab\n ? [{ id: panel.id, ...geometry(panel.layout) }]\n : [],\n );\n}\n\n/**\n * A config with these boxes written into the panels they name, or the same\n * config when none of them moves. A panel no box names, or whose stored\n * layout is not one the grid admits, is left as it is. A box that says\n * `fixedHeight` sets it; one that does not keeps the panel's own (D68).\n */\nexport function withLayouts(\n config: DashboardViewConfig,\n boxes: readonly PlacedPanel[],\n columns: number = DASHBOARD_GRID_COLUMNS,\n): DashboardViewConfig {\n const panels: readonly unknown[] = panelsOf(config);\n const moved = new Map(boxes.map(box => [box.id, box]));\n let changed = false;\n const next = panels.map(panel => {\n if (!isPlainObject(panel) || typeof panel.id !== 'string') return panel;\n const box = moved.get(panel.id);\n const current = panel.layout;\n if (!box || !fitsGrid(current, columns)) return panel;\n const fixed = hasFixedHeight(box.fixedHeight === undefined ? current : box);\n const layout = fixed\n ? { ...geometry(box), fixedHeight: true }\n : geometry(box);\n if (sameLayout(current, layout) && hasFixedHeight(current) === fixed)\n return panel;\n changed = true;\n return { ...panel, layout };\n });\n return changed ? { ...config, panels: next as DashboardPanel[] } : config;\n}\n\n/**\n * The panels in reading order: rows top to bottom, each left to right — the\n * order a reader counts them in and the grid draws them in, whatever order\n * the config lists them. Stable, so two panels an author stacked on the same\n * cell keep the order they were saved in.\n */\nexport function readingOrder<T extends { layout: PanelLayout }>(\n panels: readonly T[],\n): T[] {\n return [...panels].sort(\n (a, b) => a.layout.y - b.layout.y || a.layout.x - b.layout.x,\n );\n}\n\n/** How many columns the narrow reading lays panels in: a pair of cards shares a row. */\nexport const STACKED_COLUMNS = 2;\n\n/**\n * The layout read as one column, for a screen too narrow for the grid: each\n * panel the full width of the column and as tall as it was saved, stacked\n * in reading order — except that two cards next to each other in reading\n * order (`paired`, the metric cards) share a row, half the width each, as\n * tall as the taller of them. A card is a number and a few words; a phone\n * stacking eleven of them one per screen-wide row, each at its desktop\n * height, made the reader scroll past a screen of white for every two\n * figures. A card with no card after it takes the row alone.\n *\n * A panel sized by hand keeps its mark (`fixedHeight`, D68), so the\n * narrow reading draws it at the height its author set, as the wide one\n * does, rather than growing it back.\n *\n * The column is `STACKED_COLUMNS` wide. A reading of the layout, not a\n * placement — it is never handed to `place`, because nothing in it maps\n * back to the wide layout the config holds.\n */\nexport function stackedLayout(\n panels: readonly PlacedPanel[],\n paired: (id: string) => boolean = () => false,\n): PlacedPanel[] {\n const read = readingOrder(panels.map(panel => ({ panel, layout: panel })));\n const stacked: PlacedPanel[] = [];\n let y = 0;\n for (let at = 0; at < read.length; at += 1) {\n const { panel } = read[at];\n const next = read[at + 1]?.panel;\n if (next && paired(panel.id) && paired(next.id)) {\n const h = Math.max(panel.h, next.h);\n stacked.push(marked(panel, { id: panel.id, x: 0, y, w: 1, h }));\n stacked.push(marked(next, { id: next.id, x: 1, y, w: 1, h }));\n y += h;\n at += 1;\n continue;\n }\n stacked.push(\n marked(panel, { id: panel.id, x: 0, y, w: STACKED_COLUMNS, h: panel.h }),\n );\n y += panel.h;\n }\n return stacked;\n}\n\n/**\n * The layout read with some panels taller than saved (`heights`, rows by\n * panel id): each grows to the height asked for, never shorter than it was\n * saved, and whatever stood under it moves down with it. A panel is read\n * as resting on the panels above it: it keeps the rows it had under the\n * lowest of them (its nearest blocker), below the lowest of them as grown\n * — so every panel under a grown one still reads where the author put it\n * relative to what it sat on, and a saved row the placement writes back\n * (`placePanelIn`) always reads as the row it was let go at (D68). Nothing\n * rises, nothing moves sideways, and two panels a stored config put on\n * one cell stay on it: only a panel that was clear of another is kept\n * clear of it. With nothing grown it is the layout as saved.\n *\n * A reading, like `stackedLayout`, never a placement: a table panel shown\n * whole while the board is read (P1-3) is not a layout its author chose,\n * and nothing hands it to `place`.\n */\nexport function grownLayout(\n panels: readonly PlacedPanel[],\n heights: ReadonlyMap<string, number>,\n): PlacedPanel[] {\n const grown = new Map<string, PlacedPanel>();\n const settled: { from: PlacedPanel; to: PlacedPanel }[] = [];\n const read = readingOrder(panels.map(panel => ({ panel, layout: panel })));\n for (const { panel: from } of read) {\n const h = Math.max(from.h, Math.floor(heights.get(from.id) ?? 0));\n // The lowest panel above it, as saved and as grown.\n let savedFloor = -1;\n let grownFloor = 0;\n for (const { from: above, to } of settled)\n if (stacked(above, from)) {\n savedFloor = Math.max(savedFloor, above.y + above.h);\n grownFloor = Math.max(grownFloor, to.y + to.h);\n }\n const y = savedFloor < 0 ? from.y : grownFloor + (from.y - savedFloor);\n const to = { ...from, y, h };\n grown.set(from.id, to);\n settled.push({ from, to });\n }\n return panels.map(panel => grown.get(panel.id) ?? panel);\n}\n\n/** `box`, carrying `from`'s mark when its author sized it by hand (D68). */\nfunction marked(from: PanelLayout, box: PlacedPanel): PlacedPanel {\n return hasFixedHeight(from) ? { ...box, fixedHeight: true } : box;\n}\n\n/** One step along the one-column reading: before the panel read before it, or after the one read after it. */\nexport type OrderStep = 'up' | 'down';\n\n/**\n * The panels after one of them trades places with its neighbour in reading\n * order — the one-column reading's 「上移」/「下移」 (D22 J) written back\n * onto the grid — or `null` when there is no neighbour that way, or no such\n * panel.\n *\n * The column is a reading of the layout, so a move in it has to come out as\n * a layout that reads that way: the panel one place further along, and as\n * near as can be every other panel where it was. The candidates are the two\n * at each other's corner (two panels of one size side by side swap and\n * nothing else moves), then every place either could be put by hand\n * (`placePanel`) — moving one up past the other is moving the other down\n * past it. Each is compacted, as every placement by hand is, so what comes\n * back is at rest; and compacting can carry a third panel into the room one\n * of the two left, which on a board whose columns do not line up puts it on\n * the other side of them. So among the candidates that land the panel where\n * it was asked to go, the one wins that reads least out of the order asked\n * for (pairs of panels the other way round), then moves fewest other panels,\n * then changes fewest rows, then moves them least far — on a board of plain\n * rows that is the order asked for exactly. Where no candidate lands it\n * there at all (a board whose rows interlock), the panels are stacked down\n * the first column in the order asked for: the one layout that always reads\n * right, at the cost of the board's columns.\n */\nexport function reorderPanel(\n panels: readonly PlacedPanel[],\n id: string,\n step: OrderStep,\n columns: number = DASHBOARD_GRID_COLUMNS,\n): PlacedPanel[] | null {\n const order = readOf(panels);\n const at = order.indexOf(id);\n const to = step === 'up' ? at - 1 : at + 1;\n if (at < 0 || to < 0 || to >= order.length) return null;\n const other = order[to];\n const wanted = [...order];\n wanted[at] = other;\n wanted[to] = id;\n let best: { placed: PlacedPanel[]; cost: number[] } | null = null;\n const consider = (placed: PlacedPanel[] | null) => {\n if (!placed) return;\n const read = readOf(placed);\n if (read[to] !== id) return;\n const cost = [\n shuffled(wanted, read),\n ...disturbance(panels, placed, [id, other]),\n ];\n if (!best || before(cost, best.cost)) best = { placed, cost };\n };\n consider(traded(panels, id, other, columns));\n const bottom = bottomOf(panels);\n for (const mover of [id, other]) {\n const box = panels.find(entry => entry.id === mover)!;\n for (let y = 0; y <= bottom; y += 1)\n for (let x = 0; x + box.w <= columns; x += 1)\n consider(placePanel(panels, mover, { x, y, w: box.w, h: box.h }));\n }\n if (best) return (best as { placed: PlacedPanel[] }).placed;\n // Down the first column, one under another: nothing passes anything.\n let y = 0;\n const stacked = new Map(\n wanted.map(entry => {\n const box = panels.find(panel => panel.id === entry)!;\n const placed = { ...box, x: 0, y };\n y += box.h;\n return [entry, placed];\n }),\n );\n return panels.map(panel => stacked.get(panel.id)!);\n}\n\n/**\n * A config with one panel moved to place `to` (from 0) along the reading\n * order of its tab, or the same config when it is already there or `to` is\n * no place on the tab. The one-column reading carries a panel by a handle\n * (D22 J): a drop names any place, an arrow key or the handle's menu one\n * place along or either end. It gets there one place at a time\n * (`reorderPanel`), each step the layout that reads that way and disturbs\n * the rest least, so a move of several places is the steps it passes\n * through — never a jump the grid could not have taken one place at a\n * time. Read as untrusted like `placePanelIn`: an entry that is no panel,\n * or whose layout admission would refuse, takes no part.\n */\nexport function reorderPanelIn(\n config: DashboardViewConfig,\n id: string,\n to: number,\n columns: number = DASHBOARD_GRID_COLUMNS,\n): DashboardViewConfig {\n let boxes = tabBoxes(config, id, columns);\n if (!boxes || !Number.isInteger(to) || to < 0 || to >= boxes.length)\n return config;\n const from = readOf(boxes).indexOf(id);\n if (from < 0 || from === to) return config;\n const step: OrderStep = to < from ? 'up' : 'down';\n for (let at = from; at !== to; at += step === 'up' ? -1 : 1) {\n const placed = reorderPanel(boxes, id, step, columns);\n if (!placed) break;\n boxes = placed;\n }\n return withLayouts(config, boxes);\n}\n\n/** Whether two layouts are the same four numbers. */\nfunction sameLayout(a: PanelLayout, b: PanelLayout): boolean {\n return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;\n}\n\n/**\n * `panels` with every box but `skip` settled in reading order against\n * `settled` and each other; `skip` keeps its place (`-1` skips nothing).\n * `held` is the panel a hand is placing, if any (see `settle`).\n */\nfunction compactAround(\n panels: readonly PlacedPanel[],\n settled: PlacedPanel[],\n skip: number,\n held?: PlacedPanel,\n): PlacedPanel[] {\n const out = [...panels];\n const order = panels\n .map((_, index) => index)\n .filter(index => index !== skip)\n .sort(\n (a, b) => panels[a].y - panels[b].y || panels[a].x - panels[b].x || a - b,\n );\n for (const index of order) {\n const box = settle(panels[index], settled, held);\n out[index] = box;\n settled.push(box);\n }\n return out;\n}\n\n/**\n * One box floated up until the row above it is taken, then dropped below\n * whatever it still overlaps.\n *\n * Except that a box the panel in hand has landed on first tries the room\n * just above that panel, as react-grid-layout's vertical compactor does for\n * the item being dragged: so a panel put down squarely on the one below it\n * trades places with it, rather than both going back where they were.\n */\nfunction settle(\n box: PlacedPanel,\n settled: readonly PlacedPanel[],\n held?: PlacedPanel,\n): PlacedPanel {\n let y = box.y;\n while (y > 0 && !settled.some(other => overlaps(other, { ...box, y: y - 1 })))\n y -= 1;\n let placed = y === box.y ? box : { ...box, y };\n if (held && overlaps(held, placed)) {\n const above = { ...placed, y: held.y - placed.h };\n if (above.y >= 0 && !settled.some(other => overlaps(other, above)))\n return settle(above, settled);\n }\n let hit = settled.find(other => overlaps(other, placed));\n while (hit) {\n placed = { ...placed, y: hit.y + hit.h };\n hit = settled.find(other => overlaps(other, placed));\n }\n return placed;\n}\n\n/** The layout `distance` cells away in the direction of `step`. */\nfunction stepped(\n { x, y, w, h }: PanelLayout,\n step: ArrangeStep,\n distance: number,\n): PanelLayout {\n switch (step) {\n case 'left':\n return { x: x - distance, y, w, h };\n case 'right':\n return { x: x + distance, y, w, h };\n case 'up':\n return { x, y: y - distance, w, h };\n case 'down':\n return { x, y: y + distance, w, h };\n case 'wider':\n return { x, y, w: w + distance, h };\n case 'narrower':\n return { x, y, w: w - distance, h };\n case 'taller':\n return { x, y, w, h: h + distance };\n case 'shorter':\n return { x, y, w, h: h - distance };\n }\n}\n\n/** The ids of these boxes in reading order. */\nfunction readOf(panels: readonly PlacedPanel[]): string[] {\n return readingOrder(panels.map(box => ({ id: box.id, layout: box }))).map(\n entry => entry.id,\n );\n}\n\n/**\n * Two panels each put at the other's corner — pulled left where it would\n * run off the grid — and the tab compacted around them.\n */\nfunction traded(\n panels: readonly PlacedPanel[],\n a: string,\n b: string,\n columns: number,\n): PlacedPanel[] {\n const one = panels.find(box => box.id === a)!;\n const two = panels.find(box => box.id === b)!;\n const at = (box: PlacedPanel, corner: PlacedPanel): PlacedPanel => ({\n ...box,\n x: Math.min(corner.x, columns - box.w),\n y: corner.y,\n });\n return compactLayout(\n panels.map(box =>\n box.id === a ? at(one, two) : box.id === b ? at(two, one) : box,\n ),\n );\n}\n\n/**\n * How far a reading order is from the one asked for: the pairs of panels\n * it reads the other way round.\n */\nfunction shuffled(wanted: readonly string[], read: readonly string[]): number {\n const place = new Map(read.map((entry, index) => [entry, index]));\n let pairs = 0;\n wanted.forEach((a, i) => {\n for (const b of wanted.slice(i + 1))\n if (place.get(a)! > place.get(b)!) pairs += 1;\n });\n return pairs;\n}\n\n/**\n * How much a placement disturbs the board, most telling first: the panels\n * other than the two trading places that moved at all, the panels that\n * changed row, and how far everything went.\n */\nfunction disturbance(\n from: readonly PlacedPanel[],\n to: readonly PlacedPanel[],\n pair: readonly string[],\n): number[] {\n let others = 0;\n let rows = 0;\n let distance = 0;\n from.forEach((box, index) => {\n const moved = to[index];\n if (!pair.includes(box.id) && !sameLayout(box, moved)) others += 1;\n if (box.y !== moved.y) rows += 1;\n distance += Math.abs(box.x - moved.x) + Math.abs(box.y - moved.y);\n });\n return [others, rows, distance];\n}\n\n/** Whether one cost is lower than another, compared member by member. */\nfunction before(a: readonly number[], b: readonly number[]): boolean {\n const differs = a.findIndex((value, index) => value !== b[index]);\n return differs >= 0 && a[differs] < b[differs];\n}\n\nfunction samePlacement(\n a: readonly PlacedPanel[],\n b: readonly PlacedPanel[],\n): boolean {\n return a.every((box, index) => sameLayout(box, b[index]));\n}\n\nfunction geometry({ x, y, w, h }: PanelLayout): PanelLayout {\n return { x, y, w, h };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What building a board does to its config (D22 A–E): add a panel, remove,\n * duplicate, rename it, replace the view it shows, move it to a tab, and\n * override or reset how it looks. Each is a pure function from the config\n * to the next one, so the runtime applies one edit to its draft and to what\n * is on screen alike, and a test reads each rule off its function.\n *\n * An edit that names nothing there — a panel id the board lacks, a tab it\n * has not — hands the same config back rather than throwing: the gesture\n * that asked for it raced a change, and there is nothing to do.\n */\n\nimport {\n DASHBOARD_GRID_COLUMNS,\n DASHBOARD_WIDTHS,\n DEFAULT_RUNTIME_LIMITS,\n type DashboardWidth,\n type DashboardContentPanel,\n type DashboardPanel,\n type DashboardViewConfig,\n type DashboardViewPanel,\n type OwnedView,\n type PanelBinding,\n type PanelPresentation,\n type ViewConfig,\n hasFixedHeight,\n overlaid,\n without,\n} from '../model/index.js';\nimport { isPlainObject } from '../filter/index.js';\nimport {\n compactLayout,\n fitsGrid,\n freeSpot,\n withLayouts,\n type PlacedPanel,\n} from './layout.js';\nimport { freshId, isViewPanel, panelTab } from './panels.js';\n\n/** A content panel as it is added: what it holds, and optionally a title. */\nexport type NewContentPanel = DashboardContentPanel extends infer P\n ? P extends DashboardContentPanel\n ? Omit<P, 'id' | 'layout' | 'tab'>\n : never\n : never;\n\n/** A data panel as it is added: a saved view, or one the board owns. */\nexport type NewViewPanel = {\n kind: 'view';\n title?: string;\n bindings?: PanelBinding[];\n} & ({ instanceId: string } | { owned: OwnedView });\n\nexport type NewPanel = NewViewPanel | NewContentPanel;\n\n/** Where a new panel goes; every member has a default. */\nexport interface NewPanelPlacement {\n /** The tab it goes on; the first when left out or not the board's. */\n tab?: string;\n /** The first row on screen: it lands there or below (D22 A). */\n fromRow?: number;\n /** Its size; `defaultPanelSize` when left out. */\n size?: { w: number; h: number };\n /** The config of the saved view it shows, when known, for its size. */\n view?: ViewConfig | null;\n /** The most panels the board may hold; admission's limit by default. */\n max?: number;\n}\n\n/**\n * How big a new panel starts, in cells of the 24-column grid (D22 A): a\n * metric card a quarter, a chart half, a table the full width; a heading a\n * full-width line, a note or a picture beside a chart. `view` is the config\n * the panel shows, when it is known — an owned view's own, a saved one's\n * once loaded; without it a data panel starts as a chart.\n */\nexport function defaultPanelSize(\n panel: Pick<NewPanel, 'kind'> & { owned?: OwnedView },\n view?: ViewConfig | null,\n): { w: number; h: number } {\n switch (panel.kind) {\n case 'heading':\n return { w: 24, h: 1 };\n case 'markdown':\n return { w: 12, h: 3 };\n case 'image':\n return { w: 8, h: 4 };\n case 'links':\n return { w: 8, h: 3 };\n }\n const config = panel.owned?.config ?? view;\n if (config?.kind === 'record') return { w: 24, h: 5 };\n if (config?.kind === 'analysis') {\n if (config.layout === 'table') return { w: 24, h: 4 };\n if (config.chart?.type === 'metric') return { w: 6, h: 2 };\n }\n return { w: 12, h: 4 };\n}\n\n/**\n * The board with one more panel and its id, or `null` when it holds as many\n * as it may. The panel goes on the tab asked for, at the first free place at\n * or below the row on screen (`freeSpot`), under the first id `panel-n` not\n * taken.\n */\nexport function addPanel(\n config: DashboardViewConfig,\n panel: NewPanel,\n placement: NewPanelPlacement = {},\n): { config: DashboardViewConfig; id: string } | null {\n const max = placement.max ?? DEFAULT_RUNTIME_LIMITS.maxDashboardPanels;\n if (config.panels.length >= max) return null;\n const tab = tabOf(config, placement.tab);\n const size = placement.size ?? defaultPanelSize(panel, placement.view);\n const layout = freeSpot(\n boxesOn(config, tab),\n size,\n DASHBOARD_GRID_COLUMNS,\n placement.fromRow ?? 0,\n );\n const id = freshId(\n config.panels.map(entry => (isPlainObject(entry) ? entry.id : undefined)),\n 'panel',\n );\n const added = {\n ...(panel.kind === 'view' ? { bindings: [] } : {}),\n ...panel,\n id,\n layout,\n ...(tab === null ? {} : { tab }),\n } as DashboardPanel;\n return { config: { ...config, panels: [...config.panels, added] }, id };\n}\n\n/** The board without one panel, its tab compacted where the panel stood. */\nexport function removePanel(\n config: DashboardViewConfig,\n id: string,\n): DashboardViewConfig {\n const panel = find(config, id);\n if (!panel) return config;\n const tab = panelTab(config, panel);\n const rest = {\n ...config,\n panels: config.panels.filter(entry => entry !== panel),\n };\n return compactTab(rest, tab);\n}\n\n/**\n * The board with a copy of one panel beside it and the copy's id, or `null`\n * when there is no such panel or no room for one more. The copy keeps the\n * title, the view, the wiring and the override, and lands at the first free\n * place from the original's row — next to it when there is room, under it\n * when there is not, and as tall: sized by hand if the original was (D68).\n * An owned view is copied with it: the copy is its own question from then\n * on, as a copied panel is its own panel.\n */\nexport function duplicatePanel(\n config: DashboardViewConfig,\n id: string,\n max: number = DEFAULT_RUNTIME_LIMITS.maxDashboardPanels,\n): { config: DashboardViewConfig; id: string } | null {\n const panel = find(config, id);\n if (!panel || !fitsGrid(panel.layout)) return null;\n const layout = panel.layout;\n const tab = panelTab(config, panel);\n const copy = without(without(without(panel, 'id'), 'layout'), 'tab');\n const added = addPanel(config, copy as NewPanel, {\n tab: tab ?? undefined,\n fromRow: layout.y,\n size: { w: layout.w, h: layout.h },\n max,\n });\n return added && hasFixedHeight(layout)\n ? { ...added, config: withFixedHeight(added.config, added.id) }\n : added;\n}\n\n/** The board with one panel marked sized by hand (D68). */\nfunction withFixedHeight(\n config: DashboardViewConfig,\n id: string,\n): DashboardViewConfig {\n return mapPanel(config, id, panel => ({\n ...panel,\n layout: { ...panel.layout, fixedHeight: true },\n }));\n}\n\n/** A panel's title set, or taken off for a blank one so it is named by what it shows. */\nexport function renamePanel(\n config: DashboardViewConfig,\n id: string,\n title: string,\n): DashboardViewConfig {\n const name = title.trim();\n return mapPanel(config, id, panel => {\n if (name === (panel.title ?? '')) return panel;\n return (\n name.length > 0 ? { ...panel, title: name } : without(panel, 'title')\n ) as DashboardPanel;\n });\n}\n\n/**\n * A data panel showing another saved view (D22 D, 「替换视图」). The title\n * and the wiring stay the panel's — a replaced view is usually the same\n * data asked better, and a binding the new view cannot carry is reported by\n * admission. The override goes: it said how to look at the view replaced;\n * so does `opens`.\n * An owned view is let go with it.\n */\nexport function replacePanelView(\n config: DashboardViewConfig,\n id: string,\n instanceId: string,\n): DashboardViewConfig {\n return mapViewPanel(config, id, panel => {\n if (\n panel.instanceId === instanceId &&\n panel.presentation === undefined &&\n panel.opens === undefined\n )\n return panel;\n // So does a view opened in its stead: it stood for the one replaced.\n const rest = without(\n without(without(panel, 'owned'), 'presentation'),\n 'opens',\n );\n // And a time wire made from the old view (D1), whatever the board's\n // filters: the new one's, if it says when its records happen, is made\n // when the board is read.\n const stored: unknown = panel.bindings;\n const bindings = Array.isArray(stored)\n ? (stored as unknown[]).filter(\n entry => !(isPlainObject(entry) && entry.derived === true),\n )\n : stored;\n return { ...rest, instanceId, bindings } as DashboardViewPanel;\n });\n}\n\n/**\n * A data panel pointing at a saved view that is the very view it showed:\n * its own analysis just saved as a view (「另存为视图」, D22 C), or the\n * personal view it stood on just copied for the board's audience\n * (「复制为共享视图并替换」, D22 B). Unlike a replacement it keeps the\n * override, the click and the wiring: the panel shows the same thing, and\n * should look and answer the same.\n */\nexport function referToSaved(\n config: DashboardViewConfig,\n id: string,\n instanceId: string,\n): DashboardViewConfig {\n return mapViewPanel(config, id, panel => {\n if (panel.owned === undefined && panel.instanceId === instanceId)\n return panel;\n return { ...without(panel, 'owned'), instanceId };\n });\n}\n\n/**\n * A data panel's override of how it looks (D22 D), or its override taken\n * off (`null`, or one setting nothing): 「恢复为视图的样子」.\n */\nexport function setPresentation(\n config: DashboardViewConfig,\n id: string,\n presentation: PanelPresentation | null,\n): DashboardViewConfig {\n const next =\n presentation && Object.keys(presentation).length > 0 ? presentation : null;\n return mapViewPanel(config, id, panel => {\n if (next === null && panel.presentation === undefined) return panel;\n return (\n next === null\n ? without(panel, 'presentation')\n : { ...panel, presentation: next }\n ) as DashboardViewPanel;\n });\n}\n\n/**\n * A content panel with what it holds changed — a note's text, a picture, a\n * list of links. Its kind stays: a note does not become a picture by an\n * edit, and a data panel is not a content panel to edit this way. A member\n * the patch sets to `undefined` is taken off, and a `title` is read as\n * `renamePanel` reads one — blank takes it off — so the form a panel is\n * written in is one edit, title and all.\n */\nexport function editContent(\n config: DashboardViewConfig,\n id: string,\n patch: Partial<NewContentPanel>,\n): DashboardViewConfig {\n const edited = mapPanel(config, id, panel => {\n if (\n panel.kind === 'view' ||\n (patch.kind !== undefined && patch.kind !== panel.kind)\n )\n return panel;\n // The title is `renamePanel`'s to read, below.\n return overlaid(panel, 'title' in patch ? without(patch, 'title') : patch);\n });\n const panel = find(edited, id);\n return 'title' in patch && panel && panel.kind !== 'view'\n ? renamePanel(edited, id, patch.title ?? '')\n : edited;\n}\n\n/**\n * A panel moved onto another tab, at the first free place there, and the\n * tab it left compacted. The same board for a tab it lacks or the tab the\n * panel is already on.\n */\nexport function movePanelToTab(\n config: DashboardViewConfig,\n id: string,\n tab: string,\n): DashboardViewConfig {\n const panel = find(config, id);\n if (!panel || !config.tabs.some(entry => entry.id === tab)) return config;\n const from = panelTab(config, panel);\n if (from === tab || !fitsGrid(panel.layout)) return config;\n // As tall as it was, and sized by hand if it was (D68).\n const layout = freeSpot(boxesOn(config, tab), panel.layout);\n const moved = mapPanel(config, id, entry => ({\n ...entry,\n tab,\n layout: hasFixedHeight(panel.layout)\n ? { ...layout, fixedHeight: true }\n : layout,\n }));\n return compactTab(moved, from);\n}\n\n/** The panels of one tab floated up, holes and all gone. */\nexport function compactTab(\n config: DashboardViewConfig,\n tab: string | null,\n): DashboardViewConfig {\n return withLayouts(config, compactLayout(boxesOn(config, tab)));\n}\n\n/**\n * The board laid out at another width (D31). It is written even when it is\n * `full` — a board the author chose full for says so, rather than looking\n * like one saved before a board could say — and the same config comes back\n * when the board is already read at that width and says it.\n */\nexport function setBoardWidth(\n config: DashboardViewConfig,\n width: DashboardWidth,\n): DashboardViewConfig {\n if (!DASHBOARD_WIDTHS.includes(width)) return config;\n return config.width === width ? config : { ...config, width };\n}\n\n/** The boxes of the panels on one tab (`null`: a board without tabs). */\nfunction boxesOn(\n config: DashboardViewConfig,\n tab: string | null,\n): PlacedPanel[] {\n return config.panels.flatMap(panel =>\n isPlainObject(panel) &&\n typeof panel.id === 'string' &&\n fitsGrid(panel.layout) &&\n panelTab(config, panel) === tab\n ? [{ id: panel.id, ...panel.layout }]\n : [],\n );\n}\n\n/** The tab asked for when the board has it, its first otherwise. */\nfunction tabOf(\n config: DashboardViewConfig,\n wanted: string | undefined,\n): string | null {\n return panelTab(config, { tab: wanted });\n}\n\nfunction find(\n config: DashboardViewConfig,\n id: string,\n): DashboardPanel | undefined {\n return config.panels.find(panel => isPlainObject(panel) && panel.id === id);\n}\n\nfunction mapPanel(\n config: DashboardViewConfig,\n id: string,\n change: (panel: DashboardPanel) => DashboardPanel,\n): DashboardViewConfig {\n const panel = find(config, id);\n if (!panel) return config;\n const next = change(panel);\n return next === panel\n ? config\n : {\n ...config,\n panels: config.panels.map(entry => (entry === panel ? next : entry)),\n };\n}\n\nfunction mapViewPanel(\n config: DashboardViewConfig,\n id: string,\n change: (panel: DashboardViewPanel) => DashboardViewPanel,\n): DashboardViewConfig {\n return mapPanel(config, id, panel =>\n isViewPanel(panel) ? change(panel) : panel,\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A board's time filter reaching its panels on its own (todo D, D67): every\n * panel over data that says when its records happen\n * (`DataViewDefinition.timeField`, `SystemView.timeField`) is narrowed by\n * the board's time range without a wire written for it. A wire written by\n * hand always wins, and a panel that reads whole says so\n * (`DashboardViewPanel.ignoresTime`).\n *\n * **Derived, never stored** (D1, user 2026-09-28). The wires are read into\n * the board, marked as derived (`derived: true`, with `auto`), where a board\n * is read under its panels' definitions (`canonicalBoard`) — so every part\n * of the engine sees one board — and taken out again when it is saved\n * (`storedTimeWires`): what persists is the wires written by hand or\n * auto-connected (D22 G) and `ignoresTime`. Only a derived wire is ever\n * made again: one auto-connect made to a date filter is the author's, and\n * keeps its field when the board is down to that one date filter.\n *\n * A board stored before this carries no marker (`DashboardViewConfig\n * .derivesTime`), and was read with every unwired panel unwired: its\n * migration (`withTimeIgnored`) says so of each such panel, so its numbers\n * stay what they were.\n */\n\nimport {\n filterTypeOf,\n sameFilterType,\n type DashboardField,\n type DashboardPanel,\n type DashboardViewConfig,\n type DashboardViewPanel,\n type FieldDefinition,\n type PanelBinding,\n} from '../model/index.js';\nimport { isPlainObject } from '../filter/index.js';\nimport { filtersOf } from './filters.js';\nimport { bindingsOf, isViewPanel, panelsOf } from './panels.js';\n\n/**\n * The board's time filter: its one date filter. A board with two — when an\n * order was placed, when it shipped — has no one range to read every panel\n * in, so none is wired on its own there.\n */\nexport function timeFilterOf(\n config: DashboardViewConfig,\n): DashboardField | null {\n const dated = dateFilters(config);\n return dated.length === 1 ? dated[0] : null;\n}\n\n/** Whether a filter is one of dates. */\nexport function isDateFilter(filter: DashboardField | undefined): boolean {\n return filter !== undefined && filterTypeOf(filter.kind) === 'date';\n}\n\nfunction dateFilters(config: DashboardViewConfig): DashboardField[] {\n return filtersOf(config).filter(isDateFilter);\n}\n\n/**\n * What a panel's view says of time: the field its records happen at,\n * `null` for a view read whole, `undefined` where it says nothing — a view\n * not known yet, or a definition that declares no time field, whose wires\n * are all the author's.\n */\nexport type PanelTime = (\n panel: DashboardViewPanel,\n) => FieldDefinition | null | undefined;\n\n/**\n * The board with its time filter wired to every data panel it reaches on\n * its own through `timeOf` (`auto` and `derived`), and every wire derived\n * before that no longer follows taken off: one whose view says otherwise\n * now or is not known, one on a panel that reads whole, and every one while\n * the board has no single date filter. A wire auto-connect made is the\n * author's and is never touched. Without the storage marker; itself when\n * nothing changes — a panel whose wires come out as they were is the same\n * panel.\n */\nexport function withTimeBindings(\n config: DashboardViewConfig,\n timeOf: PanelTime,\n): DashboardViewConfig {\n const filter = timeFilterOf(config);\n let changed = false;\n const panels = panelsOf(config).map(panel => {\n if (!isViewPanel(panel)) return panel;\n const stored = storedBindings(panel);\n const kept = stored.filter(entry => !isDerived(entry));\n const time = filter && panel.ignoresTime !== true ? timeOf(panel) : null;\n const written =\n filter &&\n kept.some(\n entry => isPlainObject(entry) && entry.globalField === filter.name,\n );\n const wire =\n filter && time && !written && sameFilterType(filter.kind, time.kind)\n ? [\n {\n globalField: filter.name,\n panelField: time.name,\n auto: true,\n derived: true,\n },\n ]\n : [];\n const next = [...kept, ...wire];\n if (sameWires(next, stored)) return panel;\n changed = true;\n return { ...panel, bindings: next as PanelBinding[] };\n });\n const marked = 'derivesTime' in config;\n if (!changed && !marked) return config;\n const next = { ...config, panels: changed ? panels : config.panels };\n delete next.derivesTime;\n return next;\n}\n\n/**\n * The board as it is stored: every wire derived from a view taken off —\n * it is made again when read — and the marker that says so.\n */\nexport function storedTimeWires(\n config: DashboardViewConfig,\n): DashboardViewConfig {\n const panels = panelsOf(config).map(panel => {\n if (!isViewPanel(panel)) return panel;\n const stored = storedBindings(panel);\n const kept = stored.filter(entry => !isDerived(entry));\n return kept.length === stored.length\n ? panel\n : { ...panel, bindings: kept as PanelBinding[] };\n });\n return { ...config, panels, derivesTime: true };\n}\n\n/**\n * A board stored before its time wires were derived, read as it was then\n * (D1): unmarked, so each panel over data not wired to every one of its\n * date filters reads whole (`ignoresTime`) — nothing wires it on its own,\n * whichever of those filters is left the board's one. Its wires are the\n * author's, auto-connected ones included, and stay. Marked, so it happens\n * once; a marked board as it is.\n */\nexport function withTimeIgnored(\n config: DashboardViewConfig,\n): DashboardViewConfig {\n const stored: unknown = config;\n if (!isPlainObject(stored) || stored.derivesTime === true) return config;\n const dated = dateFilters(config).map(filter => filter.name);\n const panels = panelsOf(config).map((panel): DashboardPanel => {\n if (dated.length === 0 || !isViewPanel(panel)) return panel;\n const wired = new Set(bindingsOf(panel).map(entry => entry.globalField));\n return dated.every(name => wired.has(name))\n ? panel\n : { ...panel, ignoresTime: true };\n });\n return {\n ...config,\n ...(Array.isArray(stored.panels) ? { panels } : {}),\n derivesTime: true,\n };\n}\n\n/** A panel's stored wires, whatever they hold, for admission to report on. */\nfunction storedBindings(panel: DashboardViewPanel): unknown[] {\n const stored: unknown = panel.bindings;\n return Array.isArray(stored) ? stored : [];\n}\n\n/** Whether a wire is one derived from a view's time field. */\nfunction isDerived(entry: unknown): boolean {\n return isPlainObject(entry) && entry.derived === true;\n}\n\n/** Whether two lists of wires say the same, entry by entry. */\nfunction sameWires(\n one: readonly unknown[],\n other: readonly unknown[],\n): boolean {\n return (\n one.length === other.length &&\n one.every(\n (entry, index) =>\n entry === other[index] ||\n JSON.stringify(entry) === JSON.stringify(other[index]),\n )\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Which field of which panel a board filter narrows (D22 G): the fields a\n * filter can be wired to on a panel, wiring one by hand and auto-connecting\n * the rest — every other panel, on any tab and over any data, with a field\n * of the same name and the same type (user ruling: 同名同类型即接,跨定义也接)\n * — and what reaches each panel, so a panel a filter does not reach can say\n * so (「不受此筛选影响」).\n */\n\nimport {\n filterTypeOf,\n sameFilterType,\n type DashboardField,\n type DashboardPanel,\n type DashboardViewConfig,\n type DashboardViewPanel,\n type FieldDefinition,\n type FieldOption,\n type OwnedView,\n type PanelBinding,\n without,\n} from '../model/index.js';\nimport { searchFieldOf } from '../filter/index.js';\nimport { filtersOf } from './filters.js';\nimport { bindingsOf, clicksFilter, isViewPanel } from './panels.js';\nimport { isDateFilter } from './timeBindings.js';\n\n/**\n * What of a data panel says which view it shows: the saved one it points\n * at, or the one it owns — all a panel being added has yet, before it has\n * an id or a place, and all that finding its fields reads.\n */\nexport interface DataPanelSource {\n instanceId?: string;\n owned?: OwnedView;\n title?: string;\n}\n\n/**\n * The fields of the view a data panel shows that a board filter can be\n * wired to (`boardFieldsOf` in `boardFields.ts`), once it is known; `null` for a panel whose\n * view has not loaded, or cannot be — nothing is said about it.\n */\nexport type PanelFields = (\n panel: DataPanelSource,\n) => readonly FieldDefinition[] | null;\n\n/**\n * What one filter does to one data panel: wired, through which field, and\n * whether auto-connect made the wire; or not wired, and why — its view has\n * no field of the filter's type (「没有可接的字段」), or it has one nobody\n * chose (`unwired`).\n */\nexport type FilterReach =\n | { wired: true; field: string; auto: boolean }\n | { wired: false; why: 'no-field' | 'unwired' };\n\n/**\n * The fields of a panel a filter can be wired to: its view's fields of the\n * filter's type, in the definition's order. Empty for a filter of no type.\n */\nexport function wireableFields(\n field: Pick<DashboardField, 'kind'>,\n fields: readonly FieldDefinition[],\n): FieldDefinition[] {\n return fields.filter(candidate => sameFilterType(field.kind, candidate.kind));\n}\n\n/**\n * What every filter of the board does to one panel, by filter name; an\n * empty record for a content panel. A panel whose fields are not known yet\n * (`fields` is `null`) is answered for its wires alone: an unwired filter\n * cannot be told apart from one with nothing to wire, so it is left out.\n */\nexport function filterReach(\n config: DashboardViewConfig,\n panel: DashboardPanel,\n fields: readonly FieldDefinition[] | null,\n): Record<string, FilterReach> {\n const reach: Record<string, FilterReach> = {};\n if (!isViewPanel(panel)) return reach;\n const bindings = bindingsOf(panel);\n for (const field of filtersOf(config)) {\n const binding = bindings.find(entry => entry.globalField === field.name);\n if (binding)\n reach[field.name] = {\n wired: true,\n field: binding.panelField,\n auto: binding.auto === true,\n };\n else if (fields !== null)\n reach[field.name] = {\n wired: false,\n why: wireableFields(field, fields).length > 0 ? 'unwired' : 'no-field',\n };\n }\n return reach;\n}\n\n/**\n * The filters that reach at least one panel on a tab (`null`: a board\n * without tabs). A filter outside it narrows nothing the reader is looking\n * at, which the filter bar shows by dimming it.\n */\nexport function filtersOnTab(\n panels: readonly {\n tab: string | null;\n reach: Readonly<Record<string, FilterReach>>;\n }[],\n tab: string | null,\n): Set<string> {\n const reaching = new Set<string>();\n for (const panel of panels)\n if (panel.tab === tab)\n for (const [name, reach] of Object.entries(panel.reach))\n if (reach.wired) reaching.add(name);\n return reaching;\n}\n\n/**\n * The board with one panel wired by hand to `panelField` for a filter, and\n * every other data panel not yet wired to it connected on its own where its\n * view has a field of that very name and of the filter's type — on any tab,\n * over any data (D22 G). `connected` names the panels auto-connect wired,\n * for the reader to be told how many and to undo them (`unbindPanels`). A\n * search filter connects to every record panel's search box instead,\n * whatever it is called (`autoField`).\n *\n * An id filter with no candidate source of its own takes the one the field\n * wired by hand names. The same board when the filter or the panel is not\n * the board's, or the panel's view has no such field of that type.\n */\nexport function bindPanel(\n config: DashboardViewConfig,\n name: string,\n panelId: string,\n panelField: string,\n fieldsOf: PanelFields,\n): { config: DashboardViewConfig; connected: string[] } {\n const same = { config, connected: [] };\n const filter = filtersOf(config).find(field => field.name === name);\n const panel = viewPanel(config, panelId);\n const fields = panel ? fieldsOf(panel) : null;\n const target = fields?.find(field => field.name === panelField);\n if (!filter || !panel || !target) return same;\n if (!sameFilterType(filter.kind, target.kind)) return same;\n\n const connected: string[] = [];\n const dated = isDateFilter(filter);\n const panels = config.panels.map(entry => {\n // Wired to a date filter by hand, a panel that read whole is timed again.\n if (entry === panel)\n return wire(\n dated ? (without(entry, 'ignoresTime') as DashboardViewPanel) : entry,\n name,\n panelField,\n false,\n );\n if (!isViewPanel(entry) || wiredTo(entry, name)) return entry;\n // A panel that reads whole is not wired to a date on its own.\n if (dated && entry.ignoresTime === true) return entry;\n const match = autoField(filter, fieldsOf(entry) ?? [], [panelField]);\n if (!match) return entry;\n connected.push(entry.id);\n return wire(entry, name, match.name, true);\n });\n const remote =\n filter.remote === undefined && target.remote !== undefined\n ? target.remote\n : undefined;\n return {\n config: {\n ...config,\n fields:\n remote === undefined\n ? config.fields\n : config.fields.map(field =>\n field === filter ? { ...field, remote } : field,\n ),\n panels,\n },\n connected,\n };\n}\n\n/**\n * The board with these panels no longer wired to a filter. Taken off a date\n * filter by hand, a panel reads whole from then on (`ignoresTime`): the\n * board's time filter would otherwise wire it again on its own — now, or\n * once the board is down to that one date filter (D1). A change the author\n * did not make by hand — a filter retyped (`retypeFilter`) — says `byHand:\n * false`, and leaves that alone.\n */\nexport function unbindPanels(\n config: DashboardViewConfig,\n name: string,\n panelIds: readonly string[],\n { byHand = true }: { byHand?: boolean } = {},\n): DashboardViewConfig {\n let changed = false;\n const time =\n byHand &&\n isDateFilter(filtersOf(config).find(field => field.name === name));\n const panels = config.panels.map(panel => {\n if (!isViewPanel(panel) || !panelIds.includes(panel.id)) return panel;\n if (!wiredTo(panel, name)) return panel;\n changed = true;\n // A press that set this filter has no value for it any more (D22 I):\n // the panel goes back to the follow-up menu.\n const rest = clicksFilter(panel, name)\n ? (without(panel, 'click') as DashboardViewPanel)\n : panel;\n return {\n ...rest,\n bindings: bindingsOf(panel).filter(entry => entry.globalField !== name),\n ...(time ? { ignoresTime: true as const } : {}),\n };\n });\n return changed ? { ...config, panels } : config;\n}\n\n/**\n * The fixed list the fields a filter is wired to offer, merged — what a\n * category filter picks from when it has no list of its own (D22 G,\n * 「值从哪来:接上的字段」, as Metabase's category filter does): every\n * option of every wired field that declares some (an `enum`'s), the same\n * code once, under the label it first comes with. A reader picks 「待出库」\n * and the filter holds `PENDING`, which is what the fields store.\n *\n * `null` when no wired field declares a list — then the values the data\n * holds are counted instead (`DashboardRuntime.valueCandidates`), or typed.\n * A wired field without a list beside ones with one is picked for from\n * the list: the list is the declared vocabulary of those values.\n */\nexport function wiredOptions(\n config: DashboardViewConfig,\n name: string,\n fieldsOf: PanelFields,\n): FieldOption[] | null {\n const merged = new Map<string, FieldOption>();\n for (const panel of config.panels) {\n if (!isViewPanel(panel)) continue;\n const binding = bindingsOf(panel).find(entry => entry.globalField === name);\n if (!binding) continue;\n const field = fieldsOf(panel)?.find(\n entry => entry.name === binding.panelField,\n );\n for (const option of field?.options ?? []) {\n const key = `${typeof option.value}:${String(option.value)}`;\n if (!merged.has(key))\n merged.set(key, { value: option.value, label: option.label });\n }\n }\n return merged.size > 0 ? [...merged.values()] : null;\n}\n\n/**\n * The wires auto-connect gives a panel about to be added (D22 G: 以后新加的\n * 面板同样自动接): for each filter it has no wire for, a field of its view\n * with the name the filter is already wired through elsewhere — the most\n * wired name first — or the filter's own name, and of the filter's type;\n * for a search filter, the view's search box (`autoField`).\n */\nexport function autoBindings(\n config: DashboardViewConfig,\n fields: readonly FieldDefinition[],\n given: readonly PanelBinding[] = [],\n): PanelBinding[] {\n const bindings: PanelBinding[] = [];\n for (const filter of filtersOf(config)) {\n if (given.some(entry => entry.globalField === filter.name)) continue;\n const match = autoField(filter, fields, wiredNames(config, filter.name));\n if (match)\n bindings.push({\n globalField: filter.name,\n panelField: match.name,\n auto: true,\n });\n }\n return bindings;\n}\n\n/**\n * The field auto-connect wires a filter through on a panel: the first of\n * `names` the view has a field of the filter's type by. A search filter is\n * the exception: a search field's name is a handle, not a path, so what it\n * is called says nothing — it wires to the view's search box, whatever the\n * definition named it, and only where there is one (a record view's;\n * `boardFieldsOf`).\n */\nfunction autoField(\n filter: DashboardField,\n fields: readonly FieldDefinition[],\n names: readonly string[],\n): FieldDefinition | undefined {\n if (filterTypeOf(filter.kind) === 'search')\n return searchFieldOf(fields) ?? undefined;\n return names\n .map(name => fields.find(field => field.name === name))\n .find(\n field => field !== undefined && sameFilterType(filter.kind, field.kind),\n );\n}\n\n/**\n * The names a filter is wired through on the board, the most used first,\n * then its own name.\n */\nfunction wiredNames(config: DashboardViewConfig, name: string): string[] {\n const counts = new Map<string, number>();\n for (const panel of config.panels)\n if (isViewPanel(panel))\n for (const binding of bindingsOf(panel))\n if (binding.globalField === name)\n counts.set(\n binding.panelField,\n (counts.get(binding.panelField) ?? 0) + 1,\n );\n const names = [...counts.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([field]) => field);\n return names.includes(name) ? names : [...names, name];\n}\n\n/** One panel wired to a filter through `panelField`, any old wire replaced. */\nfunction wire(\n panel: DashboardViewPanel,\n name: string,\n panelField: string,\n auto: boolean,\n): DashboardViewPanel {\n const binding: PanelBinding = auto\n ? { globalField: name, panelField, auto: true }\n : { globalField: name, panelField };\n return {\n ...panel,\n bindings: [\n ...bindingsOf(panel).filter(entry => entry.globalField !== name),\n binding,\n ],\n };\n}\n\nfunction wiredTo(panel: DashboardViewPanel, name: string): boolean {\n return bindingsOf(panel).some(entry => entry.globalField === name);\n}\n\nfunction viewPanel(\n config: DashboardViewConfig,\n id: string,\n): DashboardViewPanel | undefined {\n return config.panels.find(\n (panel): panel is DashboardViewPanel =>\n isViewPanel(panel) && panel.id === id,\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What setting up a board's filters does to its config (D22 G): add one,\n * name it, give it another type, take it off, say what it starts at, whether\n * it is required, takes several values or picks from a list of its own, put\n * it elsewhere in the bar; the board's time grouping; and its fixed scope\n * taken out whole. Each a pure\n * function from the config to the next, as the other edits of a board are\n * (`edit.ts`), so the runtime applies it to its draft and to what is on\n * screen alike.\n *\n * An edit naming a filter the board lacks hands the same config back.\n */\n\nimport {\n DASHBOARD_FILTER_KINDS,\n MAX_DASHBOARD_FILTERS,\n filterTypeOf,\n type DashboardField,\n type DashboardFilterType,\n type DashboardTimeGrouping,\n type DashboardViewConfig,\n type FieldOption,\n type FilterValue,\n without,\n} from '../model/index.js';\nimport { emptyFilter, isPlainObject } from '../filter/index.js';\nimport { filtersOf as fieldsOf, isOneDayValue } from './filters.js';\nimport { freshId, isViewPanel } from './panels.js';\nimport { unbindPanels } from './wiring.js';\n\n/** A filter as it is added: its type and its name on the bar. */\nexport interface NewFilter {\n type: DashboardFilterType;\n label: string;\n}\n\n/**\n * The board with one more filter, last on the bar, and its name — the first\n * `filter-n` not taken — or `null` when the board holds as many as it may.\n * A new filter holds nothing, takes one value, and is wired to no panel yet.\n */\nexport function addFilter(\n config: DashboardViewConfig,\n filter: NewFilter,\n): { config: DashboardViewConfig; name: string } | null {\n const fields = fieldsOf(config);\n if (fields.length >= MAX_DASHBOARD_FILTERS) return null;\n const name = freshId(\n fields.map(field => field.name),\n 'filter',\n );\n const field: DashboardField = {\n name,\n label: filter.label.trim(),\n kind: DASHBOARD_FILTER_KINDS[filter.type][0],\n };\n return { config: { ...config, fields: [...fields, field] }, name };\n}\n\n/** A filter's name on the bar; a blank one is not taken. */\nexport function renameFilter(\n config: DashboardViewConfig,\n name: string,\n label: string,\n): DashboardViewConfig {\n const next = label.trim();\n if (next.length === 0) return config;\n return mapFilter(config, name, field =>\n field.label === next ? field : { ...field, label: next },\n );\n}\n\n/**\n * A filter of another type. What it held and what it started at were of\n * the old type, so both go, and so do its list and its source; its wires go\n * too — each was to a field of the old type. The same type keeps it as it\n * is.\n */\nexport function retypeFilter(\n config: DashboardViewConfig,\n name: string,\n type: DashboardFilterType,\n): DashboardViewConfig {\n const field = fieldsOf(config).find(entry => entry.name === name);\n if (!field || filterTypeOf(field.kind) === type) return config;\n const retyped: DashboardField = {\n name: field.name,\n label: field.label,\n kind: DASHBOARD_FILTER_KINDS[type][0],\n ...(field.multiple &&\n (type === 'text' || type === 'id' || type === 'number')\n ? { multiple: true as const }\n : {}),\n };\n return unwire(\n mapFilter(config, name, () => retyped),\n name,\n );\n}\n\n/** The board without a filter, and without every wire to it. */\nexport function removeFilter(\n config: DashboardViewConfig,\n name: string,\n): DashboardViewConfig {\n const fields = fieldsOf(config);\n if (!fields.some(field => field.name === name)) return config;\n return unwire(\n { ...config, fields: fields.filter(field => field.name !== name) },\n name,\n );\n}\n\n/** What a filter starts at; `null` takes the default off. */\nexport function setFilterDefault(\n config: DashboardViewConfig,\n name: string,\n value: FilterValue | null,\n): DashboardViewConfig {\n return mapFilter(config, name, field => {\n if (value !== null) return { ...field, default: value };\n return field.default === undefined ? field : without(field, 'default');\n });\n}\n\n/** Whether a filter always has a value (and so must have a default). */\nexport function setFilterRequired(\n config: DashboardViewConfig,\n name: string,\n required: boolean,\n): DashboardViewConfig {\n return mapFilter(config, name, field => {\n if (required === (field.required === true)) return field;\n return required ? { ...field, required: true } : without(field, 'required');\n });\n}\n\n/**\n * Whether a date filter holds one day and nothing else\n * (`DashboardField.oneDay`). Turned on, a default that is no one day goes,\n * so the filter is not left refusing its own start; a required one then\n * asks for a default, as it does when it has none.\n */\nexport function setFilterOneDay(\n config: DashboardViewConfig,\n name: string,\n oneDay: boolean,\n): DashboardViewConfig {\n return mapFilter(config, name, field => {\n if (oneDay === (field.oneDay === true)) return field;\n if (!oneDay) return without(field, 'oneDay');\n const start = field.default;\n const kept =\n start === undefined || isOneDayValue(start)\n ? field\n : without(field, 'default');\n return { ...kept, oneDay: true };\n });\n}\n\n/**\n * Whether a filter takes several values. Turned off, a default holding\n * several keeps its first, so the filter is not left refusing its own start.\n */\nexport function setFilterMultiple(\n config: DashboardViewConfig,\n name: string,\n multiple: boolean,\n): DashboardViewConfig {\n return mapFilter(config, name, field => {\n if (multiple === (field.multiple === true)) return field;\n if (multiple) return { ...field, multiple: true };\n const single = without(field, 'multiple');\n const start: unknown = field.default;\n if (Array.isArray(start) && start.length > 1)\n return { ...single, default: start.slice(0, 1) };\n if (isPlainObject(start) && Array.isArray(start.items))\n return start.items.length > 1\n ? { ...single, default: { items: start.items.slice(0, 1) } }\n : single;\n return single;\n });\n}\n\n/**\n * Where a filter's choices come from (D22 G, 「值从哪来」): a list of its\n * own, or — `null` — the values of the fields it is wired to.\n */\nexport function setFilterOptions(\n config: DashboardViewConfig,\n name: string,\n options: FieldOption[] | null,\n): DashboardViewConfig {\n return mapFilter(config, name, field => {\n if (options !== null) return { ...field, options };\n return field.options === undefined ? field : without(field, 'options');\n });\n}\n\n/** A filter moved to `index` on the bar. */\nexport function moveFilter(\n config: DashboardViewConfig,\n name: string,\n index: number,\n): DashboardViewConfig {\n const fields = fieldsOf(config);\n const from = fields.findIndex(field => field.name === name);\n const to = Math.max(0, Math.min(fields.length - 1, Math.trunc(index)));\n if (from < 0 || from === to) return config;\n const next = [...fields];\n const [moved] = next.splice(from, 1);\n next.splice(to, 0, moved);\n return { ...config, fields: next };\n}\n\n/** The board's time grouping set, or taken off with `null`. */\nexport function setTimeGrouping(\n config: DashboardViewConfig,\n grouping: DashboardTimeGrouping | null,\n): DashboardViewConfig {\n if (grouping === null)\n return config.timeGrouping === undefined\n ? config\n : without(config, 'timeGrouping');\n return { ...config, timeGrouping: grouping };\n}\n\n/**\n * The board without its fixed scope (D23 Q16, D26 Q31): the condition a\n * board saved before its filters could not hold, taken out whole by its\n * author — never a reader's to take — and the empty tree left in its place,\n * so the member stays and the board is never read as pre-C again. A board\n * whose fixed scope is empty already comes back as it was.\n */\nexport function removeFixedScope(\n config: DashboardViewConfig,\n): DashboardViewConfig {\n const { fixed } = config;\n const empty =\n isPlainObject(fixed) &&\n fixed.op === 'and' &&\n Array.isArray(fixed.children) &&\n fixed.children.length === 0;\n return empty ? config : { ...config, fixed: emptyFilter() };\n}\n\nfunction mapFilter(\n config: DashboardViewConfig,\n name: string,\n change: (field: DashboardField) => DashboardField,\n): DashboardViewConfig {\n const field = fieldsOf(config).find(entry => entry.name === name);\n if (!field) return config;\n const next = change(field);\n return next === field\n ? config\n : {\n ...config,\n fields: config.fields.map(entry => (entry === field ? next : entry)),\n };\n}\n\n/** Every wire to one filter taken off the panels. */\nfunction unwire(\n config: DashboardViewConfig,\n name: string,\n): DashboardViewConfig {\n const ids = config.panels.flatMap(panel =>\n isViewPanel(panel) ? [panel.id] : [],\n );\n return unbindPanels(config, name, ids, { byHand: false });\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QueryViolation } from '@ahoo-wang/wow-client';\nimport type { RecordKey } from '../model/index.js';\n\n/**\n * The only interface between a runtime and its host. Relative dates, the\n * refresh timer, the \"is anyone looking\" question and the failures a host\n * wants to hear about all pass through it, so `model` through `store` stay\n * free of the DOM and of the system clock, and a test can drive time without\n * faking globals.\n */\nexport interface RuntimeEnvironment {\n now(): Date;\n /** IANA zone used to resolve relative and preset dates. */\n timeZone: string;\n setTimeout(callback: () => void, ms: number): unknown;\n clearTimeout(handle: unknown): void;\n visibility: VisibilitySource;\n /**\n * Told once of every failure the engine meets doing its work — a query, a\n * store call, an export, a render, a chart, a declared action's command —\n * for a host to log or send to\n * its monitoring (D40). The failure is still answered on screen as it\n * always was; this is the host's copy. Whatever it throws is dropped, and\n * left out, nothing is logged anywhere.\n */\n onError?(event: ViewErrorEvent): void;\n}\n\n/** What failed, by the part of the engine it failed in (D40). */\nexport type ViewErrorKind =\n 'query' | 'store' | 'export' | 'render' | 'chart' | 'action';\n\n/**\n * Where a failure happened. `operation` is always said; the rest only where\n * the failing part knows it.\n */\nexport interface ViewErrorContext {\n /**\n * What was being done: for `query` one of `query` (the view's own),\n * `summaries`, `totals`, `split`, `record` (one row read whole) or\n * `candidates` (a condition's values); for `store` the port's method\n * (`list`, `get`, `create`, `save`, `rename`, `delete`, `getPreferences`,\n * `setPreferences`); for `export` `fetch`, `deliver` or `image`; for\n * `render` `render`; for `chart` `load` or `draw`; for `action` the\n * declared action's id (a slot's command: its `operation`, else its\n * title).\n */\n operation: string;\n /** For `action`: the record the command failed on. */\n recordKey?: RecordKey;\n definitionId?: string;\n /** The saved view, when the failing one is saved. */\n instanceId?: string;\n /** The open view (`ViewRuntime.id`) it failed in. */\n runtimeId?: string;\n /** A store write's idempotency key, the same across its retries. */\n requestId?: string;\n /** For `render` and `chart`: the boundary that caught it. */\n boundary?: string;\n /** For `render` and `chart` in a dashboard panel: which panel. */\n panelId?: string;\n /** For `render` and `chart`: React's component stack, where given. */\n componentStack?: string;\n /**\n * For `query`: which rule a Wow service said the query broke and where —\n * its stable `code` (wow-client's `QueryErrorCodes`, an open list), the\n * JSON path or logical field path, and its message. Absent when the\n * source said none: a budget rejection, a failure the service did not\n * answer, a source that is not Wow. The report waits for the body the\n * source answered with to be read, so this is there when it is said.\n */\n violation?: QueryViolation;\n /**\n * For `query`: the `errorCode` the service answered with, as it gave it —\n * `IllegalAccessQueryScope`, `QuerySchemaValidation`, an application's own\n * — when it gave one.\n */\n errorCode?: string;\n}\n\n/** One failure, as `RuntimeEnvironment.onError` is told of it. */\nexport interface ViewErrorEvent {\n kind: ViewErrorKind;\n /** What was thrown or rejected with, as it was: a stack, a code, a body. */\n error: unknown;\n context: ViewErrorContext;\n}\n\nexport interface VisibilitySource {\n isVisible(): boolean;\n subscribe(listener: () => void): () => void;\n}\n\n/** A host that never hides, which is what Node and a test both are. */\nexport const ALWAYS_VISIBLE: VisibilitySource = {\n isVisible: () => true,\n subscribe: () => () => {},\n};\n\n/**\n * The default host: the ambient clock and timers, the ambient zone, and a page\n * that is always visible. `/react` replaces `visibility` with one backed by\n * `document.visibilityState`.\n */\nexport function defaultRuntimeEnvironment(\n overrides: Partial<RuntimeEnvironment> = {},\n): RuntimeEnvironment {\n return {\n now: () => new Date(),\n timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n setTimeout: (callback, ms) => globalThis.setTimeout(callback, ms),\n clearTimeout: handle => {\n globalThis.clearTimeout(handle as ReturnType<typeof setTimeout>);\n },\n visibility: ALWAYS_VISIBLE,\n ...overrides,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_RUNTIME_LIMITS, type RuntimeLimits } from '../model/index.js';\n\nexport type RequestTask<T> = (controller: AbortController) => Promise<T>;\n\n/** A newer request took this key; the caller drops the result silently. */\nexport class RequestSupersededError extends Error {\n readonly key: string;\n\n constructor(key: string) {\n super(`Request superseded: ${key}`);\n this.name = 'RequestSupersededError';\n this.key = key;\n }\n}\n\n/** The queue is full; the caller reports it rather than waiting longer. */\nexport class RequestQueueFullError extends Error {\n readonly key: string;\n\n constructor(key: string, limit: number) {\n super(`Queue is full (${limit}); dropped request for ${key}`);\n this.name = 'RequestQueueFullError';\n this.key = key;\n }\n}\n\nexport function isRequestSuperseded(\n error: unknown,\n): error is RequestSupersededError {\n return error instanceof RequestSupersededError;\n}\n\ninterface Entry<T = unknown> {\n key: string;\n task: RequestTask<T>;\n controller: AbortController;\n resolve(value: T): void;\n reject(reason: unknown): void;\n started: boolean;\n}\n\n/**\n * The one scheduler every data query passes through.\n *\n * Two rules, both from `RuntimeLimits`. A key holds at most one request, so a\n * new page or a new filter aborts the one it replaces instead of racing it;\n * and the whole engine runs a bounded number at once, with a bounded queue\n * behind it, so a dashboard of twenty panels opens without twenty parallel\n * requests.\n */\nexport class RequestRunner {\n private readonly maxConcurrent: number;\n private readonly maxQueued: number;\n private readonly byKey = new Map<string, Entry>();\n private readonly queue: Entry[] = [];\n private running = 0;\n /** Room held beyond `maxQueuedQueries` for the boards open; see `reserve`. */\n private reserved = 0;\n\n constructor(limits: RuntimeLimits = DEFAULT_RUNTIME_LIMITS) {\n this.maxConcurrent = limits.maxConcurrentQueries;\n this.maxQueued = limits.maxQueuedQueries;\n }\n\n /** Requests started and not yet settled. */\n get active(): number {\n return this.running;\n }\n\n /** Requests admitted and waiting for a slot. */\n get queued(): number {\n return this.queue.length;\n }\n\n /** How many requests may wait: the host's budget, and the room held. */\n get capacity(): number {\n return this.maxQueued + this.reserved;\n }\n\n /**\n * Holds room in the queue for `slots` more requests until the returned\n * release is called, once (host-integration.md 4): a board opening asks\n * for its panels' queries all at once, and they wait their turn rather\n * than being refused because the board is larger than the host's budget.\n */\n reserve(slots: number): () => void {\n const held = Math.max(0, Math.floor(slots));\n this.reserved += held;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.reserved -= held;\n };\n }\n\n /**\n * Runs `task` under `key`, superseding whatever that key was doing. The\n * returned promise rejects with `RequestSupersededError` in that case, and\n * with `RequestQueueFullError` when the queue has no room left.\n */\n run<T>(key: string, task: RequestTask<T>): Promise<T> {\n // Capacity is judged before the key is superseded, so a refusal leaves\n // what was running in place: cancelling first would abort the live\n // request and then reject the new one, and the view would sit at\n // `queue-full` with nothing in flight to recover it.\n const previous = this.byKey.get(key);\n // A predecessor still waiting gives its own slot back, so it does not\n // count against the room the new request needs.\n const freed = previous && !previous.started ? 1 : 0;\n if (this.queue.length - freed >= this.capacity)\n return Promise.reject(new RequestQueueFullError(key, this.capacity));\n this.cancel(key);\n\n return new Promise<T>((resolve, reject) => {\n const entry: Entry<T> = {\n key,\n task,\n controller: new AbortController(),\n resolve,\n reject,\n started: false,\n };\n this.byKey.set(key, entry);\n this.queue.push(entry);\n this.pump();\n });\n }\n\n /** Aborts the request under `key`, if any. Safe to call when there is none. */\n cancel(key: string): void {\n const entry = this.byKey.get(key);\n if (!entry) return;\n this.byKey.delete(key);\n if (!entry.started) {\n const at = this.queue.indexOf(entry);\n if (at >= 0) this.queue.splice(at, 1);\n }\n entry.controller.abort();\n entry.reject(new RequestSupersededError(key));\n }\n\n /** Aborts everything; the engine calls it when it is disposed. */\n cancelAll(): void {\n for (const key of [...this.byKey.keys()]) this.cancel(key);\n }\n\n private pump(): void {\n while (this.running < this.maxConcurrent && this.queue.length > 0) {\n const entry = this.queue.shift()!;\n entry.started = true;\n this.running += 1;\n // A task that throws before returning a promise would otherwise unwind\n // through `pump` with the slot still counted, and the scheduler would\n // run one fewer query for the rest of the engine's life.\n try {\n entry.task(entry.controller).then(\n value => this.settle(entry, () => entry.resolve(value)),\n error => this.settle(entry, () => entry.reject(error)),\n );\n } catch (error) {\n this.settle(entry, () => entry.reject(error));\n }\n }\n }\n\n private settle(entry: Entry, deliver: () => void): void {\n this.running -= 1;\n // A superseded entry was already rejected and replaced in the map.\n if (this.byKey.get(entry.key) === entry) this.byKey.delete(entry.key);\n deliver();\n this.pump();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { withTimeIgnored } from './timeBindings.js';\nimport {\n DASHBOARD_GRID_COLUMNS,\n filterTypeOf,\n LEGACY_GRID_COLUMNS,\n type DashboardField,\n type DashboardViewConfig,\n type FilterNode,\n type FilterValue,\n} from '../model/index.js';\nimport {\n emptyFilter,\n isEmptyFilter,\n isFilterGroup,\n isPlainObject,\n} from '../filter/index.js';\nimport { FILTER_TYPE_OPERATOR } from './filters.js';\n\nconst SCALE = DASHBOARD_GRID_COLUMNS / LEGACY_GRID_COLUMNS;\n\n/**\n * A stored config read into the form this engine writes: onto the 24-column\n * grid (D22 E), a pre-C board condition into its filters' defaults and the\n * board's fixed scope (D23 Q16, D26 Q31; `intoDefaults` below), and the\n * board's own condition, which a board no longer has, out of the config\n * (D27; `withoutOwnCondition` below), and a board stored before its time\n * wires were derived read with its unwired panels reading whole (D1;\n * `withTimeIgnored`, `timeBindings.ts`). Each step is marked by the config\n * itself — `columns`, `fixed`, the `filter` member, `derivesTime` — so it\n * happens once: a second read, or a read after any edit, leaves the config\n * alone.\n *\n * A config that does not say which grid it is in (`columns`) was written for\n * the twelve-column grid: every `x` and `w` is doubled and every `y` and `h`\n * kept, which puts each panel on exactly the pixels it had — a column of the\n * new grid and the gap after it are half of one of the old, so a panel\n * twice as many columns wide spans the same width. It gains `columns` and an\n * empty `tabs`, so a save writes the new form and the next read leaves it\n * alone.\n *\n * A config that says anything about `columns` is not guessed at: one naming\n * another grid is left for admission to refuse (`dashboard.grid.unsupported`).\n * A config already in this form comes back as it is (the same object, so\n * nothing downstream sees a change). Nothing here throws on a malformed\n * config either — whatever is not a panel with numbers, or a tree, is\n * carried over untouched and reported where admission reports it.\n *\n * It is called at one place, the engine's read boundary (`readStored`,\n * `runtime/storedViews.ts`), so everything else reads the new form only.\n */\nexport function migrateDashboardConfig(\n config: DashboardViewConfig,\n): DashboardViewConfig {\n return withTimeIgnored(\n withoutOwnCondition(intoDefaults(onTheWideGrid(config))),\n );\n}\n\nfunction onTheWideGrid(config: DashboardViewConfig): DashboardViewConfig {\n const stored: unknown = config;\n if (!isPlainObject(stored) || 'columns' in stored) return config;\n const panels: unknown = stored.panels;\n return {\n ...(stored as unknown as DashboardViewConfig),\n columns: DASHBOARD_GRID_COLUMNS,\n tabs: [],\n panels: (Array.isArray(panels)\n ? panels.map(widened)\n : panels) as DashboardViewConfig['panels'],\n };\n}\n\n/**\n * A board condition written before batch C, read as the filters' defaults\n * where it says what a filter would, and as the board's fixed scope where\n * it does not (D23 Q16, D26 Q31; AGENTS.md's stored-data exception).\n *\n * Before C a board's global filter was one condition tree over its global\n * fields (`config.filter`); from C a filter is a named field with a default\n * a reader can change. A leaf of that tree's top-level AND that one filter\n * could hold — on a global field of one of the six filter types, asked with\n * that type's operator (an `EQ` of one text or number value is the one-entry\n * list the filter stores), on a filter with no default of its own and only\n * one such leaf — becomes that filter's default. The rest becomes `fixed`,\n * the board's fixed scope, which every panel runs under as it ran under\n * `config.filter`; a tree that is not a plain AND is not taken apart and\n * becomes `fixed` whole. `config.filter` is read out and gone.\n *\n * The mark is `fixed` itself. A config that has it was read into this form\n * — or written in it — and is never taken apart again: which leaves a\n * filter \"could hold\" depends on the filters' settings (a default, 「可多选」),\n * and an author changes those after the board was read, so judging again on\n * every read would move a leaf that stayed fixed into a default any reader\n * can clear (A-02). A `filter` that is no tree is not read here: the fixed\n * scope beside it starts empty, and `withoutOwnCondition` carries it over.\n */\nfunction intoDefaults(config: DashboardViewConfig): DashboardViewConfig {\n const stored: unknown = config;\n if (!isPlainObject(stored) || 'fixed' in stored) return config;\n const tree: unknown = stored.filter;\n if (!isFilterGroup(tree)) return { ...config, fixed: emptyFilter() };\n const fields: unknown = stored.fields;\n const byName = new Map<string, DashboardField>();\n if (Array.isArray(fields))\n for (const field of fields)\n if (isPlainObject(field) && typeof field.name === 'string')\n byName.set(field.name, field as unknown as DashboardField);\n\n const defaults = new Map<string, FilterValue>();\n const kept: FilterNode[] = [];\n // Only a plain AND is taken apart: a leaf under an OR says nothing alone.\n for (const child of tree.op === 'and' ? tree.children : []) {\n const field = isPlainObject(child) ? leafField(child, byName) : undefined;\n const value =\n field && !defaults.has(field.name) && field.default === undefined\n ? asDefault(field, child as unknown as Record<string, unknown>)\n : undefined;\n if (field && value !== undefined) defaults.set(field.name, value);\n else kept.push(child);\n }\n return {\n ...without(config, 'filter'),\n fixed: tree.op === 'and' ? { ...tree, children: kept } : tree,\n ...(defaults.size === 0\n ? {}\n : {\n fields: (fields as DashboardField[]).map(field =>\n isPlainObject(field) && defaults.has(field.name)\n ? { ...field, default: defaults.get(field.name) }\n : field,\n ),\n }),\n };\n}\n\n/**\n * A board's own condition (`filter`) and the editor mode it was shown in\n * (`filterMode`) out of a config that still carries them: a board has\n * neither since D27 — its panels ask the questions, a reader narrows them\n * through its filters, and what no reader changes is its fixed scope. A\n * board written between batch C and D27 carries an empty `filter` beside\n * its `fixed`, and nothing wrote into it.\n *\n * The mark is the members themselves: a config that carries either was\n * written before D27, and one read here carries neither, so the step\n * happens once. What the condition said is kept rather than dropped, since\n * every panel ran under it: one that holds any condition is ANDed into the\n * fixed scope after what it holds, exactly as the two were merged when\n * both were read. One that is no tree goes in as a condition of its own, so\n * admission still refuses the board, now at `fixed`, rather than open it\n * under less than it ran under.\n */\nfunction withoutOwnCondition(config: DashboardViewConfig): DashboardViewConfig {\n const stored: unknown = config;\n if (!isPlainObject(stored) || !('filter' in stored || 'filterMode' in stored))\n return config;\n return {\n ...without(config, 'filter', 'filterMode'),\n fixed: joined(stored.fixed, stored.filter) as DashboardViewConfig['fixed'],\n };\n}\n\n/** A board's fixed scope with the condition it carried beside it ANDed on. */\nfunction joined(fixed: unknown, filter: unknown): unknown {\n if (filter === undefined || (isFilterGroup(filter) && isEmptyFilter(filter)))\n return fixed;\n if (isFilterGroup(fixed) && isEmptyFilter(fixed) && isFilterGroup(filter))\n return filter;\n return { op: 'and', children: [...conjuncts(fixed), ...conjuncts(filter)] };\n}\n\n/** The conditions an AND holds, or the node itself as one. */\nfunction conjuncts(node: unknown): unknown[] {\n if (!isFilterGroup(node)) return [node];\n if (isEmptyFilter(node)) return [];\n return node.op === 'and' ? node.children : [node];\n}\n\n/** A copy of a stored config without the members named. */\nfunction without(config: DashboardViewConfig, ...members: string[]) {\n const read: Record<string, unknown> = { ...config };\n for (const member of members) delete read[member];\n return read as unknown as DashboardViewConfig;\n}\n\n/** The global field a plain leaf is on, if it is one. */\nfunction leafField(\n node: Record<string, unknown>,\n byName: ReadonlyMap<string, DashboardField>,\n): DashboardField | undefined {\n const keys = Object.keys(node).sort().join(',');\n if (keys !== 'field,operator,value' || typeof node.field !== 'string')\n return undefined;\n return byName.get(node.field);\n}\n\n/** The leaf's value as the filter's default, or nothing it could hold. */\nfunction asDefault(\n field: DashboardField,\n leaf: Record<string, unknown>,\n): FilterValue | undefined {\n const type = filterTypeOf(field.kind);\n if (type === null) return undefined;\n const value = leaf.value as FilterValue;\n // What the filter's own condition asks with (`filterOperatorOf`).\n const operator = FILTER_TYPE_OPERATOR[type];\n if (leaf.operator === operator) {\n // A filter that takes one value holds a list of one.\n if (\n operator === 'IN' &&\n Array.isArray(value) &&\n value.length > 1 &&\n field.multiple !== true\n )\n return undefined;\n return value;\n }\n if (\n leaf.operator === 'EQ' &&\n (type === 'text' || type === 'number') &&\n value !== null &&\n typeof value !== 'object'\n )\n return [value];\n return undefined;\n}\n\nfunction widened(panel: unknown): unknown {\n if (!isPlainObject(panel) || !isPlainObject(panel.layout)) return panel;\n const layout = panel.layout;\n return {\n ...panel,\n layout: { ...layout, x: scaled(layout.x), w: scaled(layout.w) },\n };\n}\n\nfunction scaled(value: unknown): unknown {\n return typeof value === 'number' ? value * SCALE : value;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * Deliberately not re-exported by `dashboard/index.ts`: only the runtime's\n * `fieldsOf`, the panel reach and the wiring strip read it, so it is not part\n * of the root entry's surface. A host that builds its own wiring UI would be\n * the reason to export it.\n */\n\nimport {\n filterTypeOf,\n type DataViewConfig,\n type FieldDefinition,\n} from '../model/index.js';\n\n/**\n * The fields of a panel's view a board filter can be wired to: its\n * definition's, but a search box (`kind: 'search'`) only on a record view.\n * A board's search finds rows (订单号、买家昵称、商品名) in the detail\n * panels; an analysis panel counts groups, and a search reaching it would\n * quietly change its numbers — so a search filter is never wired to one,\n * by hand or by auto-connect (D36, the search filter on the board).\n */\nexport function boardFieldsOf(\n view: DataViewConfig['kind'],\n fields: readonly FieldDefinition[],\n): readonly FieldDefinition[] {\n return view === 'record'\n ? fields\n : fields.filter(field => filterTypeOf(field.kind) !== 'search');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*\n * Not re-exported by `dashboard/index.ts`: only the dashboard runtime reads\n * a board under the paths its panels' definitions rename aliases to, as it\n * resolves them (capabilities.md 18).\n */\n\nimport {\n sameJson,\n type AnalysisViewConfig,\n type DashboardPanel,\n type DashboardViewConfig,\n type DashboardViewPanel,\n} from '../model/index.js';\nimport { isPlainObject } from '../filter/index.js';\nimport { isViewPanel, panelsOf } from './panels.js';\nimport { URL_PLACEHOLDER } from './placeholders.js';\n\n/** Each field a panel's definition names by an alias, by that alias. */\nexport type PanelRenames = (\n panel: DashboardViewPanel,\n) => Readonly<Record<string, string>> | null | undefined;\n\n/** A view the board owns, read under the paths `renamed` maps to. */\nexport type OwnedViewRename = (\n config: AnalysisViewConfig,\n renamed: Readonly<Record<string, string>>,\n) => AnalysisViewConfig;\n\n/**\n * The board with every name it gives a data panel's field renamed to the\n * path the panel's definition renames it to (#3519): a binding's\n * `panelField`, a dimension another board's filter takes its value from,\n * a `{{field}}` of a page click, and the view the panel owns. The board\n * then agrees with the fields its panels run on — a filter wired by an\n * alias still narrows its panel — and is saved under the paths next time.\n *\n * `renamedOf` says what a panel's definition renamed, `null` while it is\n * not known. A stored config is untrusted: what is not the shape it names\n * is left as it is, for admission to report. Returns the config itself\n * when nothing is renamed.\n */\nexport function withCanonicalPanelFields(\n config: DashboardViewConfig,\n renamedOf: PanelRenames,\n ownedView: OwnedViewRename,\n): DashboardViewConfig {\n let changed = false;\n const panels = panelsOf(config).map(panel => {\n if (!isViewPanel(panel)) return panel;\n const renamed = renamedOf(panel);\n if (!renamed || Object.keys(renamed).length === 0) return panel;\n const next = renamedPanel(panel, renamed, ownedView);\n if (next !== panel) changed = true;\n return next;\n });\n return changed ? { ...config, panels } : config;\n}\n\nfunction renamedPanel(\n panel: DashboardViewPanel,\n renamed: Readonly<Record<string, string>>,\n ownedView: OwnedViewRename,\n): DashboardPanel {\n const name = (field: string) => renamed[field] ?? field;\n const next: Record<string, unknown> = { ...panel };\n const bindings: unknown = panel.bindings;\n if (Array.isArray(bindings))\n next.bindings = bindings.map((entry: unknown) =>\n isPlainObject(entry) && typeof entry.panelField === 'string'\n ? { ...entry, panelField: name(entry.panelField) }\n : entry,\n );\n const click: unknown = panel.click;\n if (isPlainObject(click)) next.click = renamedClick(click, name);\n const owned: unknown = panel.owned;\n if (\n isPlainObject(owned) &&\n isPlainObject(owned.config) &&\n owned.config.kind === 'analysis'\n )\n next.owned = {\n ...owned,\n config: ownedView(owned.config as unknown as AnalysisViewConfig, renamed),\n };\n return sameJson(next, panel) ? panel : (next as unknown as DashboardPanel);\n}\n\nfunction renamedClick(\n click: Record<string, unknown>,\n name: (field: string) => string,\n): Record<string, unknown> {\n if (click.kind === 'url' && typeof click.url === 'string')\n return {\n ...click,\n // The name is the first thing inside the braces, so its first\n // occurrence in the placeholder is the name, spaces kept.\n url: click.url.replace(URL_PLACEHOLDER, (whole, field: string) =>\n whole.replace(field, name(field)),\n ),\n };\n const values: unknown = click.values;\n if (click.kind === 'dashboard' && isPlainObject(values))\n return {\n ...click,\n values: Object.fromEntries(\n Object.entries(values).map(([filter, source]) => [\n filter,\n isPlainObject(source) && typeof source.dimension === 'string'\n ? { ...source, dimension: name(source.dimension) }\n : source,\n ]),\n ),\n };\n return click;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n QueryDescriptorResult,\n QueryModelDescriptor,\n} from '@ahoo-wang/wow-client';\n\n/**\n * Reads one source's descriptor, sending the version already held so an\n * unchanged one answers `notModified` without a body — the shape of\n * wow-client's `describeSnapshot` and `describeEventStream`.\n */\nexport type Describe = (previous?: string) => Promise<QueryDescriptorResult>;\n\n/**\n * How old a descriptor may be before a trigger checks it again: the\n * service's own default revalidation interval\n * (`wow.query.schema.revalidate-interval`), so a check never runs more\n * often than the answer can change.\n */\nexport const DESCRIPTOR_MAX_AGE_MS = 5 * 60 * 1000;\n\n/**\n * How long the first view over a source waits for its descriptor before it\n * opens on the definition as declared (capabilities.md 6「取不到时」). A\n * service that takes the connection and never answers would otherwise hold\n * the opening for ever; the read goes on, and narrows the view when it lands.\n */\nexport const DESCRIBE_DEADLINE_MS = 10 * 1000;\n\nexport interface DescriptorCacheOptions {\n /** Milliseconds since the epoch; the runtime environment's clock. */\n now(): number;\n /**\n * Told when a source's descriptor is read for the first time and whenever\n * its version changes — what the views over it run on has changed.\n */\n changed?(key: string, descriptor: QueryModelDescriptor): void;\n /** Told when reading a source's descriptor failed; what was held is kept. */\n failed?(key: string, error: unknown): void;\n maxAge?: number;\n}\n\ninterface Entry {\n describe: Describe;\n descriptor: QueryModelDescriptor | null;\n /** When the last read settled, answered or failed; `null` before one has. */\n checkedAt: number | null;\n inflight: Promise<void> | null;\n}\n\n/**\n * One descriptor per source key (capabilities.md 6): a board of ten panels\n * over one source reads it once, and reads asked for at the same moment\n * share one request. It is never persisted — a descriptor belongs to the\n * deployment, not to anyone's saved work — and a read that fails keeps\n * whatever was held and is tried again at the next trigger past the\n * maximum age.\n *\n * The last answer wins. Replicas may briefly disagree on the version; the\n * cache does not compare them, and the worst case is one extra narrowing.\n */\nexport class DescriptorCache {\n private readonly options: DescriptorCacheOptions;\n private readonly entries = new Map<string, Entry>();\n\n constructor(options: DescriptorCacheOptions) {\n this.options = options;\n }\n\n /** The descriptor held for a source, or `null` when none has been read. */\n current(key: string): QueryModelDescriptor | null {\n return this.entries.get(key)?.descriptor ?? null;\n }\n\n /**\n * The source's descriptor. The first time, it is read and waited for, so\n * the first query already goes out narrowed; after that the one held is\n * answered at once, and checked again in the background once it is older\n * than the maximum age. `null` while none could be read.\n */\n async load(\n key: string,\n describe: Describe,\n ): Promise<QueryModelDescriptor | null> {\n let entry = this.entries.get(key);\n if (!entry) {\n entry = { describe, descriptor: null, checkedAt: null, inflight: null };\n this.entries.set(key, entry);\n }\n if (entry.checkedAt === null) await this.check(key, entry);\n else void this.revalidate(key);\n return entry.descriptor;\n }\n\n /**\n * Checks a source's descriptor again when it is older than the maximum\n * age, or at once when `force`d. A check already in flight is joined,\n * never doubled.\n */\n revalidate(key: string, force = false): Promise<void> {\n const entry = this.entries.get(key);\n if (!entry) return Promise.resolve();\n if (!force && !this.stale(entry))\n return entry.inflight ?? Promise.resolve();\n return this.check(key, entry);\n }\n\n /** Every source whose descriptor is older than the maximum age, checked again. */\n revalidateStale(): void {\n for (const key of this.entries.keys()) void this.revalidate(key);\n }\n\n private stale(entry: Entry): boolean {\n if (entry.checkedAt === null) return true;\n const maxAge = this.options.maxAge ?? DESCRIPTOR_MAX_AGE_MS;\n return this.options.now() - entry.checkedAt >= maxAge;\n }\n\n private check(key: string, entry: Entry): Promise<void> {\n if (entry.inflight) return entry.inflight;\n const read = async () => {\n try {\n const answer = await entry.describe(entry.descriptor?.version);\n if (answer.notModified) return;\n const before = entry.descriptor?.version;\n entry.descriptor = answer.descriptor;\n if (answer.descriptor.version !== before)\n this.options.changed?.(key, answer.descriptor);\n } catch (error) {\n this.options.failed?.(key, error);\n } finally {\n entry.checkedAt = this.options.now();\n entry.inflight = null;\n }\n };\n entry.inflight = read();\n return entry.inflight;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client';\nimport { DEFAULT_RUNTIME_LIMITS, type RuntimeLimits } from '../model/index.js';\n\n/**\n * The limits that bound what a source accepts rather than what the engine\n * does (capabilities.md 4.5): a source with a descriptor says them, and the\n * host may only lower them.\n */\nconst SOURCE_LIMIT_NAMES = [\n 'maxPageSize',\n 'maxPageWindow',\n 'maxAnalysisRows',\n 'maxQueryFilterNodes',\n 'maxFilterValues',\n] as const;\n\nexport type SourceLimitName = (typeof SOURCE_LIMIT_NAMES)[number];\n\n/**\n * The limits one runtime over a source runs under.\n *\n * Without a descriptor they are the host's over the defaults, exactly as\n * before descriptors existed: the source budgets default to what a Wow\n * service admits at its own defaults (D42). With one, each source budget\n * is the descriptor's, lowered to the host's where the host set one —\n * a host that raised its server's guard need not raise the engine's too.\n * `null` in the descriptor is no bound: a window or a filter size that\n * never stops anything, and a page size at the largest rung the engine\n * ever offers, since a page is still asked for in one piece.\n */\nexport function sourceLimits(\n host: Partial<RuntimeLimits> | undefined,\n descriptor: QueryModelDescriptor | null,\n): RuntimeLimits {\n const base: RuntimeLimits = host\n ? { ...DEFAULT_RUNTIME_LIMITS, ...host }\n : DEFAULT_RUNTIME_LIMITS;\n if (!descriptor) return base;\n\n const { limits } = descriptor;\n const largestRung = Math.max(\n base.defaultPageSize,\n ...base.pageSizes,\n ...base.cardPageSizes,\n );\n const described: Record<SourceLimitName, number> = {\n maxPageSize: limits.maxPageSize ?? largestRung,\n maxPageWindow: limits.maxPageWindow ?? Number.POSITIVE_INFINITY,\n maxAnalysisRows: limits.aggregation.maxLimit,\n maxQueryFilterNodes: limits.maxFilterNodes ?? Number.POSITIVE_INFINITY,\n maxFilterValues: limits.maxFilterValues ?? Number.POSITIVE_INFINITY,\n };\n const next: RuntimeLimits = { ...base };\n for (const name of SOURCE_LIMIT_NAMES) {\n const own = host?.[name];\n next[name] =\n own === undefined ? described[name] : Math.min(own, described[name]);\n }\n return next;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryErrorCodes } from '@ahoo-wang/wow-client';\n\n/**\n * The rejections that say the descriptor may be behind (capabilities.md 7):\n * a query the descriptor admitted was refused for a capability, so the\n * service may have changed since it was read. The value rejections\n * (`VALUE_MISMATCH`, `NOT_COLLECTION`, `NOT_SINGLE_STRING`) are about what\n * was typed, and the decoding ones about what the engine sent; neither\n * says anything about the descriptor.\n */\nconst CAPABILITY_CODES: ReadonlySet<string> = new Set([\n QueryErrorCodes.UNKNOWN_FIELD,\n QueryErrorCodes.UNSUPPORTED_CAPABILITY,\n QueryErrorCodes.MODEL_SEARCH_UNSUPPORTED,\n QueryErrorCodes.CURSOR_NOT_ALLOWED,\n QueryErrorCodes.ELEMENT_SCOPE_REQUIRED,\n QueryErrorCodes.PROTECTED_AGGREGATION,\n QueryErrorCodes.PROTECTED_COMPARISON,\n QueryErrorCodes.MISSING_KEY_REQUIRES_STRING,\n QueryErrorCodes.ANY_REQUIRES_SINGLE_VALUE,\n QueryErrorCodes.METRIC_FILTER_SEARCH,\n QueryErrorCodes.METRIC_FILTER_ELEMENT_MATCH,\n QueryErrorCodes.METRIC_FILTER_ARRAY_FIELD,\n QueryErrorCodes.INCOMPLETE_PROJECTION,\n QueryErrorCodes.NOT_PROJECTABLE,\n QueryErrorCodes.TEMPORAL_AGGREGATION_UNSUPPORTED,\n QueryErrorCodes.IDENTITY_UNDEFINED,\n QueryErrorCodes.STORAGE_UNSUPPORTED,\n // The entry's budget and gates (Wow 9.2 names them): each one the\n // descriptor states, as its limits, its root operators or its analysis.\n QueryErrorCodes.SIZE_OUT_OF_RANGE,\n QueryErrorCodes.FILTER_TOO_LARGE,\n QueryErrorCodes.EXPENSIVE_OPERATOR_DISABLED,\n QueryErrorCodes.COUNT_REQUIRES_FILTER,\n QueryErrorCodes.SORT_TOO_MANY,\n]);\n\n/**\n * What a service older than Wow 9.2 refuses at its entry without a code\n * (wow-query's `QueryBudget`): a budget crossed, named in the message\n * (`HTTP list query limit[2000] must be between 1 and 1000.`); an operator,\n * a metric sort, an expansion or a formula the entry keeps for itself\n * (`… are not allowed.`); a count of every record. Each of those the\n * descriptor says, so a refusal means it is behind. Wow 9.2 names them\n * (`SIZE_OUT_OF_RANGE`, `EXPENSIVE_OPERATOR_DISABLED`, …) and the codes\n * above decide; the words stay the fallback for the older services.\n */\nconst BUDGET_REFUSAL =\n /\\b(?:limit|size|window|nodes|values)\\[\\d+\\]|expensive operators are not allowed|must not match all documents/;\n\n/** What a rejection said, as far as this reads it. */\nexport interface Rejection {\n /** The violation's stable code, where the service named one. */\n code?: string;\n /** The service's own words. */\n reason: string;\n /** The HTTP status, where there was one. */\n status?: number;\n}\n\n/**\n * Whether a rejected query is a reason to check the source's descriptor\n * again at once, rather than at its next scheduled check (capabilities.md\n * 7, C5): a capability violation or a budget or gate the entry refused,\n * by its code, or by its words where an older service gave no code. A\n * failure of the service itself (HTTP 500) says nothing about the\n * descriptor.\n */\nexport function checksDescriptorAgain(rejection: Rejection): boolean {\n if (rejection.code !== undefined) return CAPABILITY_CODES.has(rejection.code);\n return rejection.status === 400 && BUDGET_REFUSAL.test(rejection.reason);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A board read under the paths its panels' definitions rename aliases to\n * (#3519, capabilities.md 18), as far as the panels are known: an owned\n * view's at once, a referenced one's once it has loaded. A filter wired by\n * an alias then narrows its panel through the path the panel runs on, and\n * the board is saved under it next time.\n */\n\nimport {\n parseSystemInstanceId,\n type AnalysisViewConfig,\n type DashboardViewConfig,\n type ViewInstance,\n} from '../../model/index.js';\nimport {\n withTimeBindings,\n type DataPanelSource,\n type PanelTime,\n} from '../../dashboard/index.js';\nimport { withCanonicalPanelFields } from '../../dashboard/panelFieldNames.js';\nimport { withCanonicalNames } from '../../capabilities/index.js';\nimport type { PanelView } from './children.js';\nimport type { DashboardRuntimeState } from './contract.js';\n\n/** Reads one board config under the paths; itself when nothing is renamed. */\nexport type BoardReading = (config: DashboardViewConfig) => DashboardViewConfig;\n\n/**\n * The reading of a board whose panels' views `viewOf` knows so far: under\n * the paths they rename aliases to, then with the board's time filter\n * wired to each panel it reaches on its own (`withTimeBindings`, todo D,\n * D1) — a panel whose view is not known yet is wired once it is.\n */\nexport function canonicalBoard(\n viewOf: (panel: DataPanelSource) => PanelView | null,\n): BoardReading {\n const timeOf = panelTime(viewOf);\n return config =>\n withTimeBindings(\n withCanonicalPanelFields(\n config,\n panel => viewOf(panel)?.definition.narrowing?.renamed,\n canonicalOwned,\n ),\n timeOf,\n );\n}\n\n/**\n * What a panel's view says of time (`PanelTime`): the system view's own\n * field where it names one (`null` for a view read whole), else the\n * definition's; `undefined` for a view not known yet or a definition that\n * names none. A saved copy of a system view is timed as its definition is.\n */\nexport function panelTime(\n viewOf: (panel: DataPanelSource) => PanelView | null,\n): PanelTime {\n return panel => {\n const view = viewOf(panel);\n if (!view) return undefined;\n const { definition, instance } = view;\n const declared = instance ? parseSystemInstanceId(instance.id) : null;\n const own =\n declared?.definitionId === definition.id\n ? definition.views?.find(entry => entry.id === declared.viewId)\n ?.timeField\n : undefined;\n const name = own === undefined ? definition.timeField : own;\n if (name === undefined) return undefined;\n if (name === null) return null;\n return definition.fields.find(field => field.name === name) ?? null;\n };\n}\n\n/** A saved board read so; itself when nothing is renamed. */\nexport function canonicalSaved(\n saved: ViewInstance | null,\n read: BoardReading,\n): ViewInstance | null {\n if (saved?.config.kind !== 'dashboard') return saved;\n const config = read(saved.config);\n return config === saved.config ? saved : { ...saved, config };\n}\n\n/**\n * The draft, the applied board and the baseline read so together, as a\n * patch — the baseline moves with them, so a board saved under an alias\n * does not open dirty. Empty when none of them changes.\n */\nexport function canonicalState(\n state: Pick<DashboardRuntimeState, 'draft' | 'applied' | 'saved'>,\n read: BoardReading,\n store: {\n isDirty(draft: DashboardViewConfig, saved: ViewInstance | null): boolean;\n },\n): Partial<DashboardRuntimeState> {\n const { draft, applied, saved } = state;\n const next = {\n draft: read(draft),\n applied: read(applied),\n saved: canonicalSaved(saved, read),\n };\n if (next.draft === draft && next.applied === applied && next.saved === saved)\n return {};\n return { ...next, dirty: store.isDirty(next.draft, next.saved) };\n}\n\n/**\n * A view the board owns under the paths its definition renames aliases to.\n * One that is not a config at all is left as it is, for admission to report\n * on its panel alone.\n */\nfunction canonicalOwned(\n config: AnalysisViewConfig,\n renamed: Readonly<Record<string, string>>,\n): AnalysisViewConfig {\n try {\n return withCanonicalNames(config, renamed);\n } catch {\n return config;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Who is subscribed, and how they are told — the half of a store that is the\n * same wherever one is written.\n *\n * Every store in this package has the shape `useSyncExternalStore` asks of\n * one: `subscribe` returns the way to stop listening, and a change notifies\n * whoever is still listening. Four of them wrote that out by hand — the two\n * runtimes, the list-change notifications and the countdown React reads a\n * refresh off — and each copy carried the same two rules in a comment of its\n * own: notify **after** the new state is committed, and walk a **copy** of\n * the set, so a listener that unsubscribes from inside its call does not\n * decide who else hears this one.\n *\n * A factory rather than a class, because a store hands `subscribe` over as a\n * bare function: `useSyncExternalStore(store.subscribe, …)` calls it with no\n * receiver, which a method reading `this.listeners` does not survive.\n */\nexport interface Listeners<A extends unknown[] = []> {\n /** Starts listening; the returned function stops. */\n subscribe(listener: (...args: A) => void): () => void;\n /** Tells everyone listening, over a copy of the set. */\n emit(...args: A): void;\n /** Forgets everyone, so a disposed store leaves no listener behind. */\n clear(): void;\n}\n\nexport function listenerSet<A extends unknown[] = []>(\n /**\n * What to do with a listener that throws. Left out, the throw is the\n * caller's, which is what a store whose `emit` is a render's own business\n * wants; given, every listener is heard from whatever the ones before it\n * did — the shape needed where notifying happens inside a write that has\n * already landed, and where letting the throw out would report a confirmed\n * write as one to retry.\n */\n contain?: (error: unknown) => void,\n): Listeners<A> {\n const subscribed = new Set<(...args: A) => void>();\n return {\n subscribe: listener => {\n subscribed.add(listener);\n return () => {\n subscribed.delete(listener);\n };\n },\n emit: (...args) => {\n for (const listener of [...subscribed]) {\n if (!contain) {\n listener(...args);\n continue;\n }\n try {\n listener(...args);\n } catch (error) {\n contain(error);\n }\n }\n },\n clear: () => {\n subscribed.clear();\n },\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What an injected scope filter does to admission, for both runtimes.\n *\n * A host's condition is judged merged into the config it narrows — that is the\n * only way the depth and node budgets can hold — but it is not part of that\n * config, and the two runtimes have to tell the findings apart. This is where\n * that reading lives.\n */\n\nimport type { DataViewConfig, FilterTree, Issue } from '../model/index.js';\nimport { isFilterGroup, isSimpleTree, mergeFilters } from '../filter/index.js';\n\n/** Stable identity for \"nothing was refused\", so a reader can compare. */\nexport const NO_REFUSAL: Issue[] = [];\n\n/**\n * A config as it would run: the scope filter ANDed after its own conditions.\n *\n * A root that is not a group is admission's to report as it stands; merging\n * would turn it into a condition, or lose it.\n */\nexport function withScopeFilter<C extends DataViewConfig>(\n config: C,\n scope: FilterTree | null,\n): C {\n if (!scope || !isFilterGroup(config.filter)) return config;\n return { ...config, filter: mergeFilters(config.filter, scope) };\n}\n\n/**\n * Findings on a config judged with its scope, read as findings on the config.\n *\n * Two things the merge does must not leak into the issues. The `filterMode`\n * warning judges what the editor can show, which is the config's own tree;\n * the merged tree is never simple, so the warning is dropped when the draft\n * itself is simple. And a root that is not `and` rides in the merged tree\n * as its first child, so a finding at `['children', 0, …]` is a finding at\n * `[…]` of the draft, and is addressed so — every reader of `issues` reads\n * a path against the draft.\n */\nexport function withoutScopeModeWarning(\n issues: Issue[],\n config: DataViewConfig,\n scope: FilterTree | null,\n): Issue[] {\n if (!scope || !isFilterGroup(config.filter)) return issues;\n const nested = config.filter.op !== 'and';\n const simple = isSimpleTree(config.filter);\n return issues.flatMap(found => {\n if (simple && found.code === 'config.filterMode.not-simple') return [];\n if (nested && found.path[0] === 'children' && found.path[1] === 0)\n return [{ ...found, path: found.path.slice(2) }];\n return [found];\n });\n}\n\n/**\n * What an injected scope is refused for: the errors admitting the config with\n * it raises that the config does not raise on its own.\n *\n * The merged findings hold both — the host's condition and whatever the saved\n * view already carried — and only the first kind is a refusal (D17-5). A view\n * that needs fixing is not fixed by leaving the host's condition out, so its\n * own errors keep being the view's; and a host told \"this view must be fixed\"\n * has nothing it can do about somebody else's saved config, so a refusal must\n * name the one thing the host can take back.\n *\n * Paths survive the merge — the scope is appended after the config's own\n * conditions, and `withoutScopeModeWarning` puts a nested root's back — so a\n * finding is matched by code and path, and one for one: a config carrying an\n * error twice is not answered by a merged tree raising it three times.\n */\nexport function scopeRefusal(own: Issue[], merged: Issue[]): Issue[] {\n const carried = own.filter(isError).map(identity);\n const added = merged.filter(isError).filter(found => {\n const at = carried.indexOf(identity(found));\n if (at < 0) return true;\n // Answered by one the config raises on its own, and that one only.\n carried.splice(at, 1);\n return false;\n });\n return added.length > 0 ? added : NO_REFUSAL;\n}\n\n/**\n * Whether two refusals say the same thing.\n *\n * Admission builds fresh issues every time, so a runtime that kept every\n * answer would report a change on every injection — and a host passing a\n * condition object built in render would then never stop re-rendering. The\n * refusal on hand is kept while it says the same, and only a different one\n * is a change worth telling anybody about.\n */\nexport function sameRefusal(\n left: readonly Issue[],\n right: readonly Issue[],\n): boolean {\n return (\n left.length === right.length &&\n left.every((found, at) => identity(found) === identity(right[at]))\n );\n}\n\nfunction isError(found: Issue): boolean {\n return found.severity === 'error';\n}\n\nfunction identity(found: Issue): string {\n return `${found.code}\\u0000${found.path.join('\\u0000')}`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MAX_TIMER_DELAY_MS, type ViewConfig } from '../model/index.js';\nimport type { RuntimeEnvironment } from './environment.js';\n\n/**\n * The one auto-refresh timer a runtime holds, however many components watch\n * it.\n *\n * A data view and a dashboard arm it for the same reasons and hold it for\n * the same four — an invalid draft, an editor with focus, a hidden page, a\n * request in flight (any panel's, on a dashboard) — so the arming is one\n * piece of code rather than two copies that drift. The runtime decides the\n * delay (`refreshDelayOf`) and publishes the due time it gets back; the\n * timer only keeps the handle and fires.\n *\n * `sync` is idempotent for an unchanged delay: a state change that leaves\n * the interval alone keeps the timer and its due time, which is what lets a\n * countdown on screen keep counting to the same moment through every\n * selection, sort and scroll.\n */\nexport class RefreshTimer {\n private handle: unknown;\n private delay: number | null = null;\n private due: number | null = null;\n\n constructor(\n private readonly environment: RuntimeEnvironment,\n private readonly fire: () => void,\n ) {}\n\n /**\n * Arms the timer for `delay`, keeps one already armed for the same delay,\n * stops it for `null`; answers the due time the runtime should publish —\n * read from the clock the timer runs on, so the countdown and the refresh\n * answer to one number.\n */\n sync(delay: number | null): number | null {\n if (delay === null) {\n this.stop();\n return null;\n }\n if (this.handle !== undefined && this.delay === delay) return this.due;\n this.stop();\n this.delay = delay;\n this.due = this.environment.now().getTime() + delay;\n this.handle = this.environment.setTimeout(() => {\n this.handle = undefined;\n this.delay = null;\n this.fire();\n }, delay);\n return this.due;\n }\n\n stop(): void {\n this.due = null;\n if (this.handle === undefined) return;\n this.environment.clearTimeout(this.handle);\n this.handle = undefined;\n this.delay = null;\n }\n}\n\n/**\n * A one-shot timer for a moment rather than a cadence: the end of the\n * period a metric card's headline skipped (`periodRollover`). `syncAt` keeps\n * the timer armed for an unchanged moment, however often the state around\n * it changes, and re-arms only when the moment moves; `null` stops it. A\n * moment already past fires at once — a page shown again after midnight\n * asks straight away.\n */\nexport class MomentTimer {\n private handle: unknown;\n private due: number | null = null;\n /**\n * The moment it last fired for. The same moment handed back — the refresh\n * it fired failed, and the answer on screen is still the old one — is not\n * fired for again: that would ask again at once, and again, for as long\n * as the source keeps failing. A new answer brings a new moment.\n */\n private spent: number | null = null;\n\n constructor(\n private readonly environment: RuntimeEnvironment,\n private readonly fire: () => void,\n ) {}\n\n syncAt(due: number | null): void {\n if (due !== null && due === this.spent) return;\n if (due === this.due && (due === null || this.handle !== undefined)) return;\n this.stop();\n if (due === null) return;\n this.due = due;\n // A host's `setTimeout` counts only so far: a moment past it is waited\n // for in steps, and fired for only once it has come.\n const delay = Math.min(\n Math.max(0, due - this.environment.now().getTime()),\n MAX_TIMER_DELAY_MS,\n );\n this.handle = this.environment.setTimeout(() => {\n this.handle = undefined;\n if (this.environment.now().getTime() < due) {\n this.due = null;\n this.syncAt(due);\n return;\n }\n this.due = null;\n this.spent = due;\n this.fire();\n }, delay);\n }\n\n stop(): void {\n this.due = null;\n if (this.handle === undefined) return;\n this.environment.clearTimeout(this.handle);\n this.handle = undefined;\n }\n}\n\n/**\n * The interval a config asks for, read as the untrusted thing it is. A\n * stored config with no `refresh` is admission's to report, and it is\n * reported; every state change still passes through here on the way to the\n * timer, and must not throw before the user can fix it.\n */\nexport function refreshIntervalOf(\n config: Pick<ViewConfig, 'refresh'>,\n): number | null {\n const interval = (config.refresh as { interval?: unknown } | undefined)\n ?.interval;\n return typeof interval === 'number' && Number.isFinite(interval)\n ? interval\n : null;\n}\n\n/**\n * The delay to arm for, or `null` while the timer is held. `held` is the\n * runtime's own reading of its four reasons; the clamp keeps a long\n * interval inside what a host's `setTimeout` can count.\n */\nexport function refreshDelayOf(\n interval: number | null,\n held: boolean,\n): number | null {\n if (held || interval === null) return null;\n return Math.min(interval * 1000, MAX_TIMER_DELAY_MS);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport type { Issue, ViewConfig, ViewInstance } from '../model/index.js';\nimport type { RuntimeEnvironment } from './environment.js';\nimport { listenerSet } from './listeners.js';\nimport { NO_REFUSAL, sameRefusal } from './scope.js';\nimport {\n MomentTimer,\n RefreshTimer,\n refreshDelayOf,\n refreshIntervalOf,\n} from './refreshTimer.js';\nimport type { ViewRuntimeState } from './viewRuntimeTypes.js';\n\n/** An `error` blocks apply and every write; a `warning` only reports. */\nexport function hasError(issues: readonly Issue[]): boolean {\n return issues.some(entry => entry.severity === 'error');\n}\n\n/**\n * What the store asks of the runtime holding it: the few steps that are not\n * the store's to decide.\n *\n * Each one is where the two runtimes genuinely differ. `admit` is the one\n * rule a class holds its configs to — a data view judges against its\n * definition, a dashboard against its panels and their references — and\n * `apply` is what promotion means there: one query, or N children brought\n * into line. The rest is the same both times, and therefore lives in the\n * store rather than in two copies of it.\n */\nexport interface RuntimeStoreHost<S extends ViewRuntimeState<ViewConfig>> {\n /** Admission of a draft as it would run, scope filter included. */\n admit(draft: S['draft']): Issue[];\n /** Promotes the draft and puts it in force; `revert` re-applies through it. */\n apply(): void;\n /** What the refresh timer fires when it comes due. */\n refresh(): void;\n /**\n * The runtime's own reason to hold the timer, beyond the three the store\n * reads for itself (an invalid draft, an editor with focus, a hidden page).\n *\n * That reason is \"a request in flight\", and only the runtime knows whose:\n * a data view's is its own, a dashboard's is any panel's. A data view\n * inside a dashboard answers true for good — the board times every panel,\n * so a panel runs no clock of its own.\n */\n holding(): boolean;\n /**\n * The interval the timer keeps, where it is not `applied`'s: a\n * dashboard's reader may keep one of their own for the opening, beside\n * the draft (D26 Q35). Left out, `applied`'s.\n */\n interval?(): number | null;\n /** Whatever the runtime holds besides the store, let go of on `dispose`. */\n release(): void;\n /**\n * A draft that has just replaced the one on screen without an edit having\n * made it — `revert`. A dashboard starts loading the references the\n * restored panels name; a data view has nothing to do here, which is the\n * one line the two `revert`s used to differ by.\n */\n restored?(draft: S['draft']): void;\n /**\n * Whether these issues stop the runtime from applying, and so hold its\n * timer. Any error does, for a data view — its config is one query. A\n * dashboard answers only for errors about the board itself: a panel's own\n * error stops that panel, and the board keeps applying and refreshing the\n * rest (`blocksBoard`).\n */\n blocking?(issues: readonly Issue[]): boolean;\n /**\n * The moment what is on screen stops being true of its own accord, on the\n * environment's clock — a metric card's headline, once the period it\n * skipped as under way has ended (`periodRollover`) — or `null`. The store\n * refreshes then, whatever the auto-refresh cadence, and held for the\n * same reasons it is: a hidden page asks once it is shown again.\n */\n expiresAt?(): number | null;\n}\n\n/**\n * How long past the moment a period ends the question is asked again: the\n * source has had a second to close the bucket that just ended.\n */\nexport const ROLLOVER_GRACE_MS = 1000;\n\nexport interface RuntimeStoreOptions<\n S extends ViewRuntimeState<ViewConfig>,\n> extends RuntimeStoreHost<S> {\n /** The state the view opens on, already judged by the caller's `admit`. */\n state: S;\n environment: RuntimeEnvironment;\n /**\n * What the scope this view opened under was refused for, or empty while it\n * is in force. It is settled before the store exists — the config and the\n * injected condition are admitted together (D17-5) — so it comes in rather\n * than being asked for.\n */\n refusedScope?: Issue[];\n}\n\n/**\n * The store half of a runtime: the state it holds, who is watching it, the\n * refresh timer's bookkeeping, and whether the draft has moved away from what\n * was saved.\n *\n * A `ViewRuntime` is two things at once. One is a kind of view — a record\n * page with paging and a selection, or a board of panels — and that part is\n * the runtime class's own. The other is a `subscribe` / `getSnapshot` store,\n * and that part was the same code twice over, down to the comments: commit\n * before notifying, keep the previous refusal while it says the same thing,\n * write the due time where the timer is armed and clear it where it stops.\n * Those rules are here now, once, and the two runtimes hold one of these\n * each.\n *\n * It is generic in the whole snapshot rather than in the config, because a\n * dashboard's snapshot is a `ViewRuntimeState` with the panels added: the\n * store patches and hands out whatever its holder declared, without knowing\n * what else is in it.\n */\nexport class RuntimeStore<S extends ViewRuntimeState<ViewConfig>> {\n private readonly listeners = listenerSet();\n private readonly environment: RuntimeEnvironment;\n private readonly host: RuntimeStoreHost<S>;\n private readonly timer: RefreshTimer;\n private readonly rollover: MomentTimer;\n private readonly unwatchVisibility: () => void;\n\n private current: S;\n private refusal: Issue[];\n private stopped = false;\n\n constructor(options: RuntimeStoreOptions<S>) {\n this.current = options.state;\n this.environment = options.environment;\n this.host = options;\n this.refusal = options.refusedScope ?? NO_REFUSAL;\n this.timer = new RefreshTimer(options.environment, () =>\n this.host.refresh(),\n );\n this.rollover = new MomentTimer(options.environment, () =>\n this.host.refresh(),\n );\n this.unwatchVisibility = options.environment.visibility.subscribe(() =>\n this.retime(),\n );\n }\n\n /** The snapshot as it stands, for the runtime's own commands to read. */\n get state(): S {\n return this.current;\n }\n\n /**\n * See `ViewRuntime.getSnapshot`: the state as it is, keys and all\n * (`text(key)`) — whatever shows it says them (D2).\n */\n getSnapshot(): S {\n return this.current;\n }\n\n /** The members a new baseline moves: `stored`, as the store holds it. */\n baseline(stored: ViewInstance): Partial<S> {\n // Members every snapshot has; see `revert`.\n return {\n saved: stored,\n title: stored.title,\n scope: stored.scope,\n dirty: this.isDirty(this.current.draft, stored),\n } as Partial<S>;\n }\n\n /** True once disposed: every command of the runtime is a no-op from then on. */\n get disposed(): boolean {\n return this.stopped;\n }\n\n /** See `ViewRuntime.refusedScope`; written by `refuse`, read through the runtime. */\n get refusedScope(): Issue[] {\n return this.refusal;\n }\n\n subscribe(listener: () => void): () => void {\n return this.listeners.subscribe(listener);\n }\n\n setState(patch: Partial<S>): void {\n this.current = { ...this.current, ...patch };\n this.syncTimer();\n // Commit first, notify second: a listener always reads the new snapshot.\n this.notify();\n }\n\n notify(): void {\n this.listeners.emit();\n }\n\n /**\n * Whether the draft says something other than what was saved.\n *\n * A view that was never saved has nothing to compare against, and closing\n * it would lose everything, so it counts as dirty from the start. Both\n * hold keys where a definition wrote them, so they compare in no language.\n */\n isDirty(draft: S['draft'], saved: ViewInstance | null): boolean {\n return saved === null || !dequal(draft, saved.config);\n }\n\n /**\n * Records what the scope on hand was refused for, and tells the subscribers\n * when that answer changed.\n *\n * A refusal changes nothing else — no state, no query — so without this a\n * screen showing it would have to be told by whoever made the injection,\n * which is how a refusal on open came to say something else entirely. The\n * previous answer is kept while it says the same thing, so a host that\n * builds its condition in render is not re-rendered forever.\n */\n refuse(refusal: Issue[]): Issue[] {\n if (sameRefusal(this.refusal, refusal)) return this.refusal;\n this.refusal = refusal;\n this.notify();\n return this.refusal;\n }\n\n /**\n * Discards the edits and re-runs what was saved.\n *\n * It re-applies rather than only restoring the draft, because the results\n * on screen may already answer a question the user has just taken back —\n * leaving them there would show the reverted config's rows under the saved\n * config's name. A draft the store's own config cannot pass admission for\n * is restored all the same and left for the user to fix, since refusing\n * would strand them on edits they asked to be rid of. A view that was never\n * saved has no baseline to return to, so it is a no-op there.\n */\n revert(): void {\n const saved = this.current.saved;\n if (this.stopped || saved === null) return;\n const draft = saved.config as S['draft'];\n const issues = this.host.admit(draft);\n const ran = this.current.applied;\n // The three members every snapshot has; `Partial<S>` cannot be proven of\n // a literal while `S` is a parameter, and `ViewRuntimeState` declares them.\n this.setState({\n draft,\n issues,\n dirty: this.isDirty(draft, saved),\n } as Partial<S>);\n this.host.restored?.(draft);\n if (!dequal(ran, draft) && !this.blocking(issues)) this.host.apply();\n }\n\n /**\n * Re-syncs the timer for something that is not a state change of the\n * runtime's own — the page being hidden or shown, a panel's query starting\n * or landing — and notifies only if the due time moved.\n *\n * Visibility does not change `draft`, `applied` or the query, so there\n * would be nothing to tell a subscriber about without this, and a countdown\n * on screen would go on counting to a timer that is no longer armed. It is\n * at most twice a round however many panels there are, which is what keeps\n * a grid from re-rendering on every panel request.\n */\n retime(): void {\n const before = this.current;\n this.syncTimer();\n if (this.current === before) return;\n this.notify();\n }\n\n dispose(): void {\n if (this.stopped) return;\n this.stopped = true;\n this.stopTimer();\n this.unwatchVisibility();\n this.host.release();\n // The last notification: a subscriber that reads `disposed` sees it now\n // rather than on some later render it happens to get.\n this.notify();\n this.listeners.clear();\n }\n\n /**\n * Auto-refresh: the four reasons to hold the timer are read here — three of\n * them off the snapshot and the environment, the fourth asked of the runtime\n * (`RuntimeStoreHost.holding`) — and arming is `RefreshTimer`'s. The due\n * time is written into the snapshot without notifying: every caller is\n * either `setState`, which notifies after it, or `retime`, which notifies\n * for it.\n */\n private syncTimer(): void {\n const held =\n this.stopped ||\n this.current.editing ||\n this.blocking(this.current.issues) ||\n !this.environment.visibility.isVisible() ||\n this.host.holding();\n const interval = this.host.interval\n ? this.host.interval()\n : refreshIntervalOf(this.current.applied);\n this.setDueAt(this.timer.sync(refreshDelayOf(interval, held)));\n // The period's end is not a cadence the reader chose, so an editor in\n // focus does not put it off — the question asked again is the one on\n // screen — but a hidden page does, and a broken draft. A request in\n // flight holds it until it lands: its answer is the one to judge.\n const expires = this.host.expiresAt?.() ?? null;\n this.rollover.syncAt(\n this.stopped ||\n this.blocking(this.current.issues) ||\n !this.environment.visibility.isVisible() ||\n this.current.query.status === 'loading' ||\n expires === null\n ? null\n : expires + ROLLOVER_GRACE_MS,\n );\n }\n\n /** See `RuntimeStoreHost.blocking`; any error, unless the runtime says otherwise. */\n private blocking(issues: readonly Issue[]): boolean {\n return this.host.blocking ? this.host.blocking(issues) : hasError(issues);\n }\n\n private setDueAt(at: number | null): void {\n if (this.current.nextRefreshAt === at) return;\n this.current = { ...this.current, nextRefreshAt: at };\n }\n\n private stopTimer(): void {\n this.timer.stop();\n this.rollover.stop();\n this.setDueAt(null);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DataViewConfig,\n AnalysisDateUnit,\n AnalysisGroup,\n DataViewDefinition,\n Issue,\n IssuePath,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { analysisScope } from '../../analysis/index.js';\n\n/**\n * What the board's time grouping does to one panel: its time dimension\n * took the unit (`taken`), or the panel has one that cannot — its\n * definition does not group that field by that unit — and keeps its own\n * (`kept`); `null` for a panel with no time dimension, or a board without a\n * time grouping.\n */\nexport type PanelGrouping = 'taken' | 'kept' | null;\n\n/**\n * The config a panel's child runs under the board's time grouping (D22 F,\n * 整板 按日/周/月): every date-histogram dimension of an analysis set to\n * `unit` where its definition groups that field by it — the one kernel that\n * says what a dimension may be asked by is the analysis kernel's scope, so\n * this reads it rather than a list of its own — and the rest left as they\n * are. A panel that keeps its own says so, a note on the panel: the reader\n * switched the whole board to weeks and this one still reads by month. A\n * dimension that took another unit loses the name the view gave it, which\n * said the old unit, and reads by the one the engine derives.\n */\nexport function regrouped(\n config: DataViewConfig,\n definition: DataViewDefinition,\n unit: AnalysisDateUnit | undefined,\n path: IssuePath,\n): { config: DataViewConfig; grouping: PanelGrouping; issues: Issue[] } {\n const none = { config, grouping: null, issues: [] };\n if (unit === undefined || config.kind !== 'analysis') return none;\n if (!config.groups.some(group => group.type === 'DATE_HISTOGRAM'))\n return none;\n const capability = definition.analysis;\n const scope = capability && analysisScope(definition, capability, config);\n let taken = false;\n const kept: AnalysisDateUnit[] = [];\n const groups = config.groups.map((group): AnalysisGroup => {\n if (group.type !== 'DATE_HISTOGRAM') return group;\n const units = scope?.aggregations.get(group.field)?.dateUnits ?? [];\n if (!(units as readonly string[]).includes(unit)) {\n kept.push(group.unit);\n return group;\n }\n taken = true;\n if (group.unit === unit) return group;\n // A name the view gave the dimension named it at its own unit — 「月份」\n // over what is now days — so it goes, and the dimension is named as the\n // engine names one by its field and unit (「下单时间(按日)」).\n const { label: _named, ...rest } = group;\n void _named;\n return { ...rest, unit };\n });\n if (!taken)\n return {\n config,\n grouping: 'kept',\n issues: [\n issue('dashboard.grouping.kept', path, { unit: kept[0] }, 'note'),\n ],\n };\n return { config: { ...config, groups }, grouping: 'taken', issues: [] };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DataViewConfig,\n Issue,\n IssuePath,\n PanelPresentation,\n} from '../../model/index.js';\nimport { issue, isPlainObject } from '../../filter/index.js';\nimport { isPresentationMember } from '../../dashboard/index.js';\nimport { validateDataConfig, type KernelContext } from '../execute.js';\nimport { hasError } from '../runtimeStore.js';\n\n/**\n * The members of a view's config a panel may look at it through, by kind:\n * a record view's rows as a table or as cards, an analysis's layout, chart\n * and totals row (D22 D). What each kind stores anyway; the rest of the\n * config is the question, which a panel never overrides.\n */\nconst MEMBERS: Record<DataViewConfig['kind'], readonly string[]> = {\n record: ['layout'],\n analysis: ['layout', 'chart', 'table'],\n};\n\n/**\n * The config a panel's child runs: the view's own with the panel's override\n * of how it looks laid over it, and what the panel says about an override\n * it could not use.\n *\n * An override is dropped — whole, with one note, never an error — when it no\n * longer fits the view it is laid over: a member that kind does not have (a\n * chart over a record view), or a chart the view's result cannot be drawn as\n * any more because the view was changed since (the analysis kernel says so,\n * the one that says so for the view itself). The panel then shows the view\n * as the view says, which is what it would show without an override. A view\n * already refused on its own config is left to say so: its override is not\n * what is wrong with it.\n *\n * An override that is no object, or names a member no view has, is the\n * dashboard kernel's to note (`validatePresentation`); here it is read as\n * setting nothing more than the members it may set.\n */\nexport function presentedConfig(\n base: DataViewConfig,\n presentation: PanelPresentation | undefined,\n judge: Pick<KernelContext, 'definition' | 'kinds' | 'limits'>,\n path: IssuePath,\n): { config: DataViewConfig; issues: Issue[] } {\n if (!isPlainObject(presentation)) return { config: base, issues: [] };\n const set = Object.keys(presentation).filter(isPresentationMember);\n if (set.length === 0) return { config: base, issues: [] };\n const dropped = {\n config: base,\n issues: [\n issue('dashboard.panel.presentation-dropped', path, {}, 'warning'),\n ],\n };\n const allowed = MEMBERS[base.kind];\n if (set.some(key => !allowed.includes(key))) return dropped;\n\n const over: Record<string, unknown> = {};\n for (const key of set) over[key] = presentation[key];\n const config = { ...base, ...over };\n if (hasError(validateDataConfig(judge, config)))\n return hasError(validateDataConfig(judge, base))\n ? { config: base, issues: [] }\n : dropped;\n return { config, issues: [] };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n filterTypeOf,\n type AnalysisDateUnit,\n type AnalysisViewConfig,\n type DashboardFilters,\n type DashboardViewConfig,\n type DataViewConfig,\n type FilterLeaf,\n type FilterNode,\n type FilterTree,\n type PanelBinding,\n} from '../../model/index.js';\nimport {\n filterFields,\n isDateTimeFilterValue,\n isFilterGroup,\n isFilterLeaf,\n periodOf,\n resolveDateTimeBound,\n resolveDateTimeRange,\n type RelativeDateUnit,\n} from '../../filter/index.js';\nimport { filtersOf } from '../../dashboard/index.js';\n\n/** The moment and the zone a relative date is read at. */\nexport interface AnchorClock {\n now: Date;\n timeZone: string;\n}\n\n/**\n * A trend card anchored to the day a board's date filter picked (D39): the\n * config its child runs — its own relative dates read as of that day — and,\n * in place of the filter's own condition, the window that ends with it.\n */\nexport interface PanelAnchor {\n /** The binding whose condition the window stands in for. */\n binding: PanelBinding;\n /** The card's config, its own relative dates on the axis read at the anchor. */\n config: DataViewConfig;\n /** The window, on the panel's own field: `BETWEEN` two instants. */\n leaf: FilterLeaf;\n}\n\n/**\n * Where a trend card on a board ends its window (D39).\n *\n * A board's date filter narrows each panel wired to it. Narrowed to one\n * day, a card that reads 「较前一日」 and draws the last 30 days has one\n * bucket: nothing to compare with, no line. So a metric card with a trend\n * read as its last period (`MetricTrend.headline` `last`), whose time axis\n * is wired to a date filter holding exactly one period of the axis's unit\n * — 「昨日」 on a card by the day, 「上月」 on one by the month, as\n * `periodOf` reads it — is anchored to that period instead: its window\n * ends with it, and the headline is it, compared with the one before.\n *\n * How far back the window reaches is the card's own to say, the way it says\n * it anywhere else: a condition of its own on that field (「近 30 天」),\n * read as of the anchored period's last moment, so 「近 30 天」 on a board\n * set to 9 月 21 日 is 8 月 23 日 to 9 月 21 日. A card with no condition of\n * its own on the field reaches back one period, which is what 「较前一日」\n * needs. Every other panel wired to the filter is narrowed as before.\n *\n * `null` when the panel is not such a card, when no date filter wired to\n * its axis holds a value, when two do, or when the value is no one period.\n */\nexport function panelAnchor(\n config: DataViewConfig,\n bindings: readonly PanelBinding[],\n board: { applied: DashboardViewConfig; filters: DashboardFilters },\n clock: AnchorClock,\n): PanelAnchor | null {\n const axis = trendAxis(config);\n if (!axis) return null;\n const dates = new Set(\n filtersOf(board.applied)\n .filter(field => filterTypeOf(field.kind) === 'date')\n .map(field => field.name),\n );\n const held = bindings.filter(\n binding =>\n binding.panelField === axis.field &&\n dates.has(binding.globalField) &&\n isDateTimeFilterValue(board.filters.values[binding.globalField]),\n );\n if (held.length !== 1) return null;\n const [binding] = held;\n const value = board.filters.values[binding.globalField];\n if (!isDateTimeFilterValue(value)) return null;\n const { from: start, to: end } = resolveDateTimeRange(\n value,\n clock.now,\n clock.timeZone,\n );\n if (end === undefined || periodOf(start, end, clock.timeZone) !== axis.unit)\n return null;\n const period = { from: start, to: end };\n\n const at = new Date(end);\n const own = filterFields(config.filter).includes(axis.field);\n const filter = own\n ? readAt(config.filter, axis.field, at, clock.timeZone)\n : config.filter;\n const from =\n (own ? earliest(filter, axis.field, at, clock.timeZone) : undefined) ??\n periodBefore(period, axis.unit, clock.timeZone);\n return {\n binding,\n config: filter === config.filter ? config : { ...config, filter },\n leaf: {\n field: axis.field,\n operator: 'BETWEEN',\n value: {\n type: 'absolute',\n from,\n to: period.to,\n },\n },\n };\n}\n\n/** A clock unit's length; a calendar unit steps the zone's calendar. */\nconst CLOCK_MS: Partial<Record<AnalysisDateUnit, number>> = {\n SECOND: 1000,\n MINUTE: 60_000,\n HOUR: 3_600_000,\n};\n\n/** Each calendar unit as a relative window counts it. */\nconst CALENDAR: Partial<Record<AnalysisDateUnit, RelativeDateUnit>> = {\n DAY: 'day',\n WEEK: 'week',\n MONTH: 'month',\n QUARTER: 'quarter',\n YEAR: 'year',\n};\n\n/**\n * The first moment of the period right before `period`: the start of 「近\n * 2 期」 read at its last moment — a relative window of days or longer is\n * whole days (D39), so two months read at 8 月 31 日 start on 7 月 1 日 —\n * and a clock unit's length before it.\n */\nfunction periodBefore(\n period: { from: string; to: string },\n unit: AnalysisDateUnit,\n timeZone: string,\n): string {\n const clock = CLOCK_MS[unit];\n const calendar = CALENDAR[unit];\n if (clock !== undefined || calendar === undefined)\n return new Date(Date.parse(period.from) - (clock ?? 0)).toISOString();\n return resolveDateTimeRange(\n { type: 'relative', amount: 2, unit: calendar },\n new Date(period.to),\n timeZone,\n ).from;\n}\n\n/**\n * A metric card's trend axis read as its last period: the field and the unit.\n *\n * Total over whatever config it is handed: a panel's view is admitted before\n * the board runs, but this is read while the board syncs, and a view with no\n * chart or no groups has no axis rather than a `TypeError`.\n */\nfunction trendAxis(\n config: DataViewConfig,\n): { field: string; unit: AnalysisDateUnit } | null {\n if (config.kind !== 'analysis') return null;\n const chart = config.chart as AnalysisViewConfig['chart'] | undefined;\n if (chart?.type !== 'metric') return null;\n const trend = chart.metric?.trend;\n if (!trend || trend.headline === 'whole') return null;\n const groups = config.groups as AnalysisViewConfig['groups'] | undefined;\n if (!Array.isArray(groups)) return null;\n const group = groups.find(\n entry => entry.alias === trend.x && entry.type === 'DATE_HISTOGRAM',\n );\n return group?.type === 'DATE_HISTOGRAM'\n ? { field: group.field, unit: group.unit }\n : null;\n}\n\n/**\n * `tree` with every relative or named date on `field` read at `at` and\n * written as the two instants (or the one) it names there; the rest as it\n * was.\n */\nfunction readAt(\n tree: FilterTree,\n field: string,\n at: Date,\n timeZone: string,\n): FilterTree {\n const visit = (node: FilterNode): FilterNode => {\n if (isFilterGroup(node))\n return { ...node, children: node.children.map(visit) };\n if (!isFilterLeaf(node) || node.field !== field) return node;\n const value = node.value;\n if (!isDateTimeFilterValue(value) || value.type === 'absolute') return node;\n if (node.operator === 'BETWEEN') {\n const range = resolveDateTimeRange(value, at, timeZone);\n return { ...node, value: { type: 'absolute', ...range } };\n }\n if (node.operator !== 'GTE' && node.operator !== 'LTE') return node;\n const edge = node.operator === 'GTE' ? 'start' : 'end';\n return {\n ...node,\n value: {\n type: 'absolute',\n from: resolveDateTimeBound(value, at, timeZone, edge),\n },\n };\n };\n return { ...tree, children: tree.children.map(visit) };\n}\n\n/**\n * The lower bound a card's own conditions put on `field` when they all hold\n * — its top-level `BETWEEN`s and `GTE`s, read as instants — or `undefined`\n * when none bounds it from below at the top.\n */\nfunction earliest(\n tree: FilterTree,\n field: string,\n at: Date,\n timeZone: string,\n): string | undefined {\n if (tree.op !== 'and') return undefined;\n let from: number | undefined;\n for (const node of tree.children) {\n if (!isFilterLeaf(node) || node.field !== field) continue;\n if (node.operator !== 'BETWEEN' && node.operator !== 'GTE') continue;\n const value = node.value;\n if (!isDateTimeFilterValue(value)) continue;\n const start = Date.parse(resolveDateTimeRange(value, at, timeZone).from);\n if (!Number.isNaN(start) && (from === undefined || start > from))\n from = start;\n }\n return from === undefined ? undefined : new Date(from).toISOString();\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DashboardFilters,\n DashboardPanel,\n DashboardViewConfig,\n DashboardViewPanel,\n FilterNode,\n FilterTree,\n Issue,\n PanelBinding,\n RuntimeLimits,\n} from '../../model/index.js';\nimport {\n isEmptyFilter,\n isPlainObject,\n mergeFilters,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport {\n bindingsOf,\n boardCondition,\n filterReach,\n isViewPanel,\n mapGlobalFilter,\n panelFilterTree,\n panelsOf,\n panelTab,\n type FilterReach,\n} from '../../dashboard/index.js';\nimport { boardFieldsOf } from '../../dashboard/boardFields.js';\nimport type { HandOver } from '../navigation.js';\nimport { hasError } from '../runtimeStore.js';\nimport type { DataViewRuntime } from '../viewRuntime.js';\nimport type { PanelView } from './children.js';\nimport type { DashboardRuntimeState } from './contract.js';\nimport {\n blocksBoard,\n clickInForce,\n panelOf,\n type DashboardPanelState,\n} from './panels.js';\nimport { regrouped, type PanelGrouping } from './grouping.js';\nimport { presentedConfig } from './presentation.js';\nimport { panelAnchor, type AnchorClock, type PanelAnchor } from './anchor.js';\n\n/** What a panel's child is handed by the board it sits on. */\nexport interface PanelRun {\n /** The view, its config the view's own as the board presents it. */\n view: PanelView;\n /** The condition the board narrows it by, in the view's own field names. */\n scope: FilterTree;\n /** What the board says about it: an override dropped, a unit kept. */\n issues: Issue[];\n /** A trend card anchored to the period a date filter picked (D39). */\n anchor: PanelAnchor | null;\n}\n\n/**\n * What one data panel runs on this board: the view's own config with the\n * panel's override of how it looks laid over it (`presentedConfig`), its\n * time dimension at the board's unit where its definition allows that\n * (`regrouped`, D22 F), and under the board's standing condition and\n * every filter wired to it that holds a value — each in the\n * panel's own field names (`panelFilterTree`) — but one whose value was\n * pressed on this panel (`DashboardFilters.from`). A trend card whose axis\n * a date filter holds one period of runs anchored to it (`panelAnchor`,\n * D39): its own dates read as of that period, the window ending with it.\n */\nexport function panelRun(\n panel: DashboardViewPanel,\n index: number,\n view: PanelView,\n board: {\n applied: DashboardViewConfig;\n filters: DashboardFilters;\n kinds: FieldKindRegistry;\n limits: RuntimeLimits;\n clock: AnchorClock;\n },\n): PanelRun {\n const { applied, filters, kinds, limits, clock } = board;\n const presented = presentedConfig(\n view.config,\n panel.presentation,\n { definition: view.definition, kinds, limits },\n ['panels', index, 'presentation'],\n );\n const grouped = regrouped(presented.config, view.definition, filters.unit, [\n 'panels',\n index,\n ]);\n const anchor = panelAnchor(\n grouped.config,\n wiredOn(panel, filters),\n { applied, filters },\n clock,\n );\n return {\n view: { ...view, config: anchor?.config ?? grouped.config },\n scope: panelScope(panel, { applied, filters, kinds }, anchor),\n issues: [...presented.issues, ...grouped.issues],\n anchor,\n };\n}\n\n/**\n * The one condition a data panel runs under, in its own field names: the\n * board's fixed scope (`boardCondition`: `fixed`, D26 Q31), mapped through\n * the panel's bindings, ANDed with every filter wired to it that holds a\n * value in `filters` (`panelFilterTree`) — but one whose value was pressed\n * on this panel (`DashboardFilters.from`). The panel runs under it with\n * every value in force (`panelRun`); what a text filter offers is counted\n * under it with only the values the host holds\n * (`FilterValues.candidatesOf`), so the two never tell apart what scope a\n * panel is in. An anchored card (`panelAnchor`, D39) runs under its window\n * in place of the date filter's own condition.\n */\nexport function panelScope(\n panel: DashboardViewPanel,\n board: {\n applied: DashboardViewConfig;\n filters: DashboardFilters;\n kinds: FieldKindRegistry;\n },\n anchor: PanelAnchor | null = null,\n): FilterTree {\n const { applied, filters, kinds } = board;\n const bindings = bindingsOf(panel);\n const wired = anchoredOut(wiredOn(panel, filters), anchor);\n const own = panelFilterTree(applied, filters, wired, kinds);\n return mergeFilters(\n mapGlobalFilter(boardCondition(applied), bindings),\n anchor\n ? { op: 'and', children: [...(own?.children ?? []), anchor.leaf] }\n : own,\n );\n}\n\n/** The bindings but the one an anchored card's window stands in for. */\nfunction anchoredOut(\n bindings: PanelBinding[],\n anchor: PanelAnchor | null,\n): PanelBinding[] {\n return anchor\n ? bindings.filter(\n binding => binding.globalField !== anchor.binding.globalField,\n )\n : bindings;\n}\n\n/**\n * The same condition as `panelScope`, in the two parts a view takes off\n * the board (D26 Q30): what is not the reader's — the board's fixed scope\n * (`fixed`, D26 Q31) and what the page holds (`held`) — is the scope the\n * opened view runs under, which nobody there takes off; the rest — the\n * reader's values — becomes the view's own conditions. `null` for a part\n * that holds nothing. An anchored card hands its window over in place of\n * the date filter's condition, in the part that filter's value is in.\n */\nfunction panelHandOver(\n panel: DashboardViewPanel,\n board: {\n applied: DashboardViewConfig;\n filters: DashboardFilters;\n held(name: string): boolean;\n kinds: FieldKindRegistry;\n },\n anchor: PanelAnchor | null = null,\n): { scopeFilter: FilterTree | null; filter: FilterTree | null } {\n const { applied, filters, held, kinds } = board;\n const wired = anchoredOut(wiredOn(panel, filters), anchor);\n const window = (page: boolean) =>\n anchor && held(anchor.binding.globalField) === page ? [anchor.leaf] : [];\n const part = (page: boolean) => ({\n values: Object.fromEntries(\n Object.entries(filters.values).filter(([name]) => held(name) === page),\n ),\n });\n const bindings = bindingsOf(panel);\n // Each one flat \"all of\", the scope with the board's fixed scope first:\n // the conditions a reader then sees one by one.\n const scope = [\n ...conjuncts(mapGlobalFilter(boardCondition(applied), bindings)),\n ...conjuncts(panelFilterTree(applied, part(true), wired, kinds)),\n ...window(true),\n ];\n const own = [\n ...conjuncts(panelFilterTree(applied, part(false), wired, kinds)),\n ...window(false),\n ];\n return {\n scopeFilter: scope.length > 0 ? { op: 'and', children: scope } : null,\n filter: own.length > 0 ? { op: 'and', children: own } : null,\n };\n}\n\n/** A panel's child as the board left it, and what the panel reports. */\nexport interface PanelOutcome {\n runtime: DataViewRuntime | null;\n issues: Issue[];\n}\n\n/**\n * The state of every panel on a board as it now stands (`boardPanels`):\n * what the runtime knows of it, and its two ways of treating a data panel's\n * child — `run` for one on the tab shown, `hold` for one elsewhere.\n */\nexport interface BoardPanelsHost {\n applied: DashboardViewConfig;\n /** Admission of `applied`. */\n issues: readonly Issue[];\n tab: string | null;\n filters: DashboardFilters;\n held(name: string): boolean;\n viewOf(panel: DashboardViewPanel): PanelView | null;\n /** A data panel on the tab shown, its child brought in line with it. */\n run(panel: DashboardViewPanel, index: number, own: Issue[]): PanelOutcome;\n /** A data panel elsewhere: the child it has, kept as it stands, or none. */\n hold(\n panel: DashboardViewPanel,\n index: number,\n own: Issue[],\n ): PanelOutcome | null;\n}\n\n/**\n * Every panel's state on the board as it now stands. Only the tab on\n * screen runs (D22 E): a panel elsewhere keeps the child it has, rows and\n * all, exactly as it stands — neither re-scoped nor re-run — until its tab\n * is shown; one never shown has none yet. A problem with the board itself\n * stops every panel, the rule `apply` follows; a panel's own problem stops\n * only that one. It is judged here because a reference arriving also comes\n * here, and a view waiting to be fixed must not start querying behind it.\n */\nexport function boardPanels(host: BoardPanelsHost): DashboardPanelState[] {\n const { applied, issues, tab, filters } = host;\n // \"Too many panels\" sits at `['panels']` and belongs to no one panel, so\n // it counts against the whole rather than slipping between the two.\n const blocked = blocksBoard(issues);\n return panelsOf(applied).flatMap((panel, index): DashboardPanelState[] => {\n // Admission reports an entry that is no panel at its index; there is\n // no id to build a state under, and nothing to run.\n if (!isPlainObject(panel)) return [];\n const own = issues.filter(found => panelOf(found) === index);\n const on = panelTab(applied, panel);\n const shown = on === tab;\n const data = isViewPanel(panel) ? panel : null;\n const runs = data !== null && !blocked;\n const outcome = !runs\n ? null\n : shown\n ? host.run(data, index, own)\n : host.hold(data, index, own);\n const view = data && host.viewOf(data);\n const { runtime, issues: reported } = outcome ?? {\n runtime: null,\n issues: own,\n };\n return [\n {\n id: panel.id,\n panel,\n runtime,\n issues: reported,\n tab: on,\n waiting: runs && !shown && runtime === null && !hasError(own),\n fields: view?.definition.fields ?? [],\n ...clickInForce(panel, reported, host.held),\n ...panelReach(applied, panel, view, filters),\n },\n ];\n });\n}\n\n/**\n * What one data panel's view takes off the board as it stands\n * (`DashboardRuntime.handOver`): its two parts (`panelHandOver`), and — on\n * a board that was saved — the board it left, for the way back to it with\n * the tab and the filters it was read on. `null` for no such data panel.\n */\nexport function boardHandOver(\n panelId: string,\n state: Pick<\n DashboardRuntimeState,\n 'applied' | 'filters' | 'saved' | 'title' | 'tab'\n >,\n board: {\n definitionId: string;\n held(name: string): boolean;\n kinds: FieldKindRegistry;\n /** The window a panel anchored at its last run (`PanelRun.anchor`). */\n anchor?(panelId: string): PanelAnchor | null;\n },\n): HandOver | null {\n const { applied, filters, saved, title, tab } = state;\n const panel = panelsOf(applied).find(\n (entry): entry is DashboardViewPanel =>\n isViewPanel(entry) && entry.id === panelId,\n );\n if (!panel) return null;\n const parts = panelHandOver(\n panel,\n { ...board, applied, filters },\n board.anchor?.(panelId) ?? null,\n );\n if (!saved) return parts;\n return {\n ...parts,\n from: {\n title,\n back: {\n kind: 'dashboard',\n definitionId: board.definitionId,\n instanceId: saved.id,\n filters,\n tab,\n },\n },\n };\n}\n\n/** The conditions a tree ANDs, one by one; none for an empty or no tree. */\nfunction conjuncts(tree: FilterTree | null): FilterNode[] {\n if (!tree || isEmptyFilter(tree)) return [];\n return tree.op === 'and' ? tree.children : [tree];\n}\n\n/**\n * The panel's bindings but the ones whose value was pressed on this very\n * panel, which do not narrow it (D22 I): the panel keeps every group, and\n * marks the one pressed.\n */\nfunction wiredOn(\n panel: DashboardViewPanel,\n filters: DashboardFilters,\n): PanelBinding[] {\n return bindingsOf(panel).filter(\n binding => filters.from?.[binding.globalField] !== panel.id,\n );\n}\n\n/**\n * What the board's filters and its time grouping do to one panel, for the\n * panel to say (「不受此筛选影响」) and the bar to dim what reaches nothing\n * on the tab: see `filterReach` and `PanelGrouping`.\n */\nfunction panelReach(\n applied: DashboardViewConfig,\n panel: DashboardPanel,\n view: PanelView | null,\n filters: DashboardFilters,\n): { reach: Record<string, FilterReach>; grouping: PanelGrouping } {\n return {\n reach: filterReach(\n applied,\n panel,\n view ? boardFieldsOf(view.config.kind, view.definition.fields) : null,\n ),\n grouping: view\n ? regrouped(view.config, view.definition, filters.unit, []).grouping\n : null,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DataViewDefinition,\n FieldDefinition,\n FilterTree,\n Issue,\n IssuePath,\n} from '../model/index.js';\nimport { dequal } from 'dequal';\nimport { isFilterGroup, issue } from '../filter/index.js';\nimport { RequestQueueFullError } from './requestRunner.js';\nimport {\n isForbiddenFailure,\n sourceFailure,\n type SourceFailure,\n} from './sourceReason.js';\nimport type { ViewQueryState } from './viewRuntimeTypes.js';\n\n/**\n * The Issue a failed execution reports: a request the queue turned away,\n * or what the source said (`queryFailureIssue`), read against the view's\n * own filter.\n */\nexport async function failedExecutionIssue(\n error: unknown,\n definition: DataViewDefinition,\n filter: FilterTree | undefined,\n): Promise<Issue> {\n if (error instanceof RequestQueueFullError)\n return issue('runtime.query.queue-full', []);\n return queryFailureIssue(await sourceFailure(error), definition, filter);\n}\n\n/**\n * The query state a failure leaves. The rows it keeps on screen answer the\n * conditions they were asked under (`kept`, the result on screen); when those are not the ones\n * that just failed (`asked`), the screen has to say so\n * (`ViewQueryState.conditionsChanged`). Scope included, so a board's filter\n * counts.\n */\nexport function failedQuery(\n error: Issue,\n requestId: string,\n kept: { config: { filter?: FilterTree } } | null | undefined,\n asked: { filter?: FilterTree },\n): ViewQueryState {\n const changed = kept != null && !dequal(kept.config.filter, asked.filter);\n return {\n status: 'error',\n error,\n requestId,\n ...(changed ? { conditionsChanged: true as const } : {}),\n };\n}\n\n/**\n * The Issue a failed query shows, from what the source said.\n *\n * A source that refused the reader rather than the query — HTTP 403, or one\n * of Wow's `IllegalAccess*` codes (`isForbiddenFailure`) — is\n * `runtime.query.forbidden`, with `reason` and the service's `errorCode`:\n * the permission state, which a retry does not change.\n *\n * A request that never reached the service (`unreachable`: fetch's own\n * `TypeError`, 「Failed to fetch」) is `runtime.query.unreachable`, said in\n * the reader's words rather than the browser's English; `reason` keeps the\n * browser's for the host.\n *\n * Without a violation it is `runtime.query.failed` with the source's reason.\n * With one — a Wow service naming the rule the query broke — the code is\n * `runtime.query.failed.<code>` (the violation's code in lower case), which\n * the catalogue words per rule; a code it has no wording for falls back\n * along the dots to `runtime.query.failed` and the service's own words, so\n * a rule a newer service adds still reads. The params say:\n *\n * - `reason`: the service's message, always;\n * - `code` and `path`: the violation as the service gave it;\n * - `field`: the field it is about by its label, when the definition\n * declares one at that path (an element field as its array's label and\n * its own), else the path itself;\n * - `name`: that field's name in the definition, when it declares one.\n *\n * The Issue's `path` is the condition of the view's own filter the rule is\n * about (`['children', 1]`), when one names that field — an element-match\n * condition when the field is one of its array's elements — so the editor\n * can mark that row; otherwise `[]`.\n */\nexport function queryFailureIssue(\n failure: SourceFailure,\n definition: DataViewDefinition,\n filter: FilterTree | undefined,\n): Issue {\n const { reason, violation } = failure;\n // Refused the reader, not the query: the permission state, which asking\n // again does not change (`runtime.query.forbidden`).\n if (isForbiddenFailure(failure))\n return issue('runtime.query.forbidden', [], {\n reason,\n ...(failure.errorCode ? { errorCode: failure.errorCode } : {}),\n });\n if (failure.unreachable)\n return issue('runtime.query.unreachable', [], { reason });\n if (!violation) return issue('runtime.query.failed', [], { reason });\n const found = fieldAt(definition.fields, violation.path);\n const params: Record<string, string> = {\n reason,\n code: violation.code,\n path: violation.path,\n field: found?.label ?? violation.path,\n };\n if (found) params.name = found.name;\n const at =\n found && filter ? conditionOf(filter, found.name, found.root) : null;\n return issue(\n `runtime.query.failed.${violation.code.toLowerCase()}`,\n at ?? [],\n params,\n );\n}\n\ninterface FoundField {\n /** The name a condition on it holds: the field's, or `array.element`. */\n name: string;\n label: string;\n /** For an element field, the array's name: an element-match holds it. */\n root?: string;\n}\n\n/**\n * The declared field at a Wow logical path: a root field by its name, or an\n * element of an array of objects as `array.element`.\n */\nfunction fieldAt(\n fields: readonly FieldDefinition[],\n path: string,\n): FoundField | null {\n if (!path) return null;\n const root = fields.find(field => field.name === path);\n if (root) return { name: root.name, label: root.label };\n for (const field of fields) {\n if (!field.elements || !path.startsWith(`${field.name}.`)) continue;\n const rest = path.slice(field.name.length + 1);\n const element = field.elements.find(entry => entry.name === rest);\n if (element)\n return {\n name: path,\n label: `${field.label} · ${element.label}`,\n root: field.name,\n };\n }\n return null;\n}\n\n/**\n * The first condition of `tree` on the field, depth first, as an issue path\n * (`['children', 0, 'children', 2]`); an element field's condition is the\n * element-match on its array.\n */\nfunction conditionOf(\n tree: FilterTree,\n name: string,\n root: string | undefined,\n): IssuePath | null {\n const walk = (node: unknown, at: IssuePath): IssuePath | null => {\n if (isFilterGroup(node)) {\n for (const [index, child] of node.children.entries()) {\n const found = walk(child, [...at, 'children', index]);\n if (found) return found;\n }\n return null;\n }\n const field = (node as { field?: unknown } | null)?.field;\n return field === name || (root !== undefined && field === root) ? at : null;\n };\n return walk(tree, []);\n}\n\n/** Whether a query's Issue is the permission state; see `queryFailureIssue`. */\nexport function isForbiddenQuery(found: Issue | null | undefined): boolean {\n return found?.code === 'runtime.query.forbidden';\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n autoRunMembers,\n presentationMembers,\n type Issue,\n type ViewConfig,\n} from '../model/index.js';\nimport { hasError } from './runtimeStore.js';\n\n/**\n * 「改了就跑」 (D20; todo 批 7): a question that changed runs again on its\n * own, a moment after the last edit, so the analyst reads the answer rather\n * than pressing for it. Which members are the question is the model's to\n * say, beside the types they are members of (`autoRunMembers`): a kind with\n * none declared never runs on its own, and the runtime carries no rule of\n * any one kind. Three things hold a draft back:\n *\n * - the draft is refused — a question that cannot run is not run;\n * - a member outside the question changed — the **range** above all, whose\n * conditions still wait for Apply (D20); and while they wait nothing else\n * runs either, because Apply runs the whole draft and a half-applied draft\n * would say two things at once;\n * - the view has it switched off (`ViewPreferences.autoRun`), in which case\n * Apply is the one way to run.\n *\n * The delay merges a burst of edits — a dimension added and its granularity\n * changed — into one query.\n */\nexport const AUTO_APPLY_DELAY_MS = 300;\n\nexport interface AutoApplyState {\n draft: ViewConfig;\n applied: ViewConfig;\n issues: readonly Issue[];\n autoApply: boolean;\n}\n\n/** Whether the draft is one the runtime should run on its own now. */\nexport function autoApplyDue(state: AutoApplyState): boolean {\n if (!state.autoApply || hasError(state.issues)) return false;\n const changed = changedMembers(state.draft, state.applied);\n if (changed.length === 0) return false;\n const question = autoRunMembers(state.draft.kind);\n return changed.every(member => question.includes(member));\n}\n\n/**\n * Whether the rows on screen answer an older question than the one on its\n * way: a query is in flight and what it asks differs from what the result\n * answered, in a member that does more than draw it.\n *\n * The other half of a result that is out of date. `autoApplyDue` covers the\n * moment before the question is sent — the debounce — and went false the\n * moment it was, so a slow answer left the old rows standing at full\n * strength as though they were the new ones (2026-09-23 audit). A refresh of\n * the same question is not this: its rows are the answer to what is being\n * asked, and they stay as they are until the new ones land.\n */\nexport function answeringAnew(state: {\n applied: ViewConfig;\n query: { status: string };\n result: { own: ViewConfig } | null;\n}): boolean {\n if (state.query.status !== 'loading' || state.result === null) return false;\n return changedMembers(state.applied, state.result.own).length > 0;\n}\n\n/**\n * The members the draft says differently from the applied config, leaving\n * out the ones that only draw the result (`presentationMembers`): those\n * redraw without asking the source, so they neither run nor hold a run.\n */\nfunction changedMembers(draft: ViewConfig, applied: ViewConfig): string[] {\n const was: Record<string, unknown> = { ...applied };\n const now: Record<string, unknown> = { ...draft };\n const presentation = presentationMembers(draft.kind);\n return [...new Set([...Object.keys(now), ...Object.keys(was)])].filter(\n member =>\n !presentation.includes(member) && !dequal(now[member], was[member]),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { DataViewDefinition, FilterTree } from '../../model/index.js';\nimport type { ValueCandidates } from '../../analysis/index.js';\nimport type {\n ValueCandidateSource,\n ValueCandidateSources,\n} from '../valueCandidates.js';\n\n/**\n * One field a filter is wired to, as a candidate source is asked about it:\n * the panel it is on, the definition it belongs to, and the condition its\n * values are counted under — the host's scope, in that panel's names.\n */\nexport interface CandidateTarget {\n panelId: string;\n definition: DataViewDefinition;\n field: string;\n scope: () => FilterTree | null;\n}\n\n/** Builds the candidate sources of one definition under one scope. */\nexport type CandidateSourceFactory = (\n definition: DataViewDefinition,\n scope: () => FilterTree | null,\n) => ValueCandidateSources;\n\n/**\n * What a text filter offers to pick from (D22 G, 「值从哪来:接上的字段」):\n * the values of every field it is wired to, counted from the data the way a\n * text condition's are (`ValueCandidateSources`, #1768), one list across the\n * board. A field wired on two panels of the same data is asked once; the same\n * value in two datasets is one entry, its counts added — the records the\n * filter would find across the board.\n *\n * A source is handed out once per filter for as long as it asks the same\n * fields, so an editor may key an effect on it; the answers belong to the\n * scope they were asked under and are forgotten with it (`reset`).\n */\nexport class FilterCandidates {\n private readonly panels = new Map<string, ValueCandidateSources>();\n private readonly merged = new Map<\n string,\n { key: string; source: ValueCandidateSource | null }\n >();\n\n constructor(private readonly make: CandidateSourceFactory | undefined) {}\n\n /** The source of one filter over its targets; `null` when none offers any. */\n of(\n name: string,\n targets: readonly CandidateTarget[],\n ): ValueCandidateSource | null {\n const make = this.make;\n if (!make) return null;\n const unique = new Map<string, CandidateTarget>();\n for (const target of targets)\n unique.set(`${target.definition.id}\\u0000${target.field}`, target);\n const key = [...unique.entries()]\n .map(([at, target]) => `${at}\\u0000${target.panelId}`)\n .join('\\u0001');\n const held = this.merged.get(name);\n if (held?.key === key) return held.source;\n\n const offered = [...unique.values()].flatMap(target => {\n const at = `${target.panelId}\\u0000${target.definition.id}`;\n let sources = this.panels.get(at);\n if (!sources) {\n sources = make(target.definition, target.scope);\n this.panels.set(at, sources);\n }\n const source = sources.of(target.field);\n return source ? [source] : [];\n });\n const source: ValueCandidateSource | null =\n offered.length === 0\n ? null\n : {\n field: name,\n search: async (query, signal) =>\n mergeAnswers(\n await Promise.all(\n offered.map(each => each.search(query, signal)),\n ),\n ),\n };\n this.merged.set(name, { key, source });\n return source;\n }\n\n /** Forgets every answer: the scope they were asked under changed. */\n reset(): void {\n for (const sources of this.panels.values()) sources.reset();\n }\n}\n\n/** Several answers as one: the same value once, its counts added. */\nfunction mergeAnswers(answers: readonly ValueCandidates[]): ValueCandidates {\n const counts = new Map<string, number>();\n for (const answer of answers)\n for (const { value, count } of answer.values)\n counts.set(value, (counts.get(value) ?? 0) + count);\n const values = [...counts.entries()]\n .map(([value, count]) => ({ value, count }))\n .sort((a, b) =>\n a.count !== b.count ? b.count - a.count : a.value < b.value ? -1 : 1,\n );\n return { values, complete: answers.every(answer => answer.complete) };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n filterTypeOf,\n type AnalysisDateUnit,\n type DashboardFilters,\n type DashboardViewConfig,\n type FieldOption,\n type FilterValue,\n type Issue,\n} from '../../model/index.js';\nimport {\n admitFilters,\n bindingsOf,\n type DataPanelSource,\n defaultFilters,\n filtersOf,\n isViewPanel,\n panelsOf,\n wiredOptions,\n} from '../../dashboard/index.js';\nimport {\n isEmptyFilter,\n issue,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport { AUTO_APPLY_DELAY_MS } from '../autoApply.js';\nimport type { RuntimeEnvironment } from '../environment.js';\nimport { RefreshTimer } from '../refreshTimer.js';\nimport type { ValueCandidateSource } from '../valueCandidates.js';\nimport type { PanelView } from './children.js';\nimport type { HeldFilters } from './contract.js';\nimport {\n FilterCandidates,\n type CandidateSourceFactory,\n} from './filterCandidates.js';\nimport { panelScope } from './panelRun.js';\n\n/** What the filter values need of the runtime that holds the board. */\nexport interface FilterValuesHost {\n kinds: FieldKindRegistry;\n environment: RuntimeEnvironment;\n candidateSources?: CandidateSourceFactory;\n /** The board on screen, which the values are admitted against. */\n applied(): DashboardViewConfig;\n /** What the filters hold now (`DashboardRuntimeState.filters`). */\n current(): DashboardFilters;\n /** Shows new values at once. */\n commit(filters: DashboardFilters): void;\n /** Whether the panels have run yet: until then a value is only noted. */\n started(): boolean;\n /** Runs the panels on the values in force. */\n run(): void;\n /** The view a data panel shows, once known. */\n viewOf(panel: DataPanelSource): PanelView | null;\n}\n\n/**\n * What a board's filters hold, and how a change of it reaches the panels\n * (D22 F): admitted against the board on screen — what it refuses is\n * answered and nothing changes — shown at once, and run a moment later, so a\n * burst of keystrokes is one query per panel (「改了就跑」, the analysis's\n * `AUTO_APPLY_DELAY_MS`). Also what a text filter offers to pick from.\n */\nexport class FilterValues {\n private readonly timer: RefreshTimer;\n private readonly candidates: FilterCandidates;\n /** The filters the host holds, by name (`hold`). */\n private held: ReadonlySet<string> = new Set();\n /** Whether the host holds the time grouping too. */\n private heldUnit = false;\n\n constructor(private readonly host: FilterValuesHost) {\n this.timer = new RefreshTimer(host.environment, () => host.run());\n this.candidates = new FilterCandidates(host.candidateSources);\n }\n\n /**\n * One filter set; `null` clears it — a required one to its default. A\n * value set this way is nobody's press, so where the last one came from\n * goes with it (`DashboardFilters.from`).\n */\n set(name: string, value: FilterValue | null): Issue[] {\n if (this.held.has(name)) return [heldIssue(name)];\n return this.put(this.with(name, value, null));\n }\n\n /**\n * One filter set by a press on a group of `panelId` (D22 I): that panel is\n * then left unnarrowed by it. `null` clears it, and where it came from.\n */\n press(name: string, value: FilterValue | null, panelId: string): Issue[] {\n if (this.held.has(name)) return [heldIssue(name)];\n return this.put(this.with(name, value, value === null ? null : panelId));\n }\n\n /**\n * The filters a host holds (an embed's locked and hidden ones, D22) and\n * what they hold — `null` for a filter's default — and, with `unit`, the\n * time grouping: the reader's commands — a value set, a press, 「清空」, a\n * unit picked — leave them as they are. The values go in at once, as\n * admitted: what the board refuses is left out and answered, every time\n * it is asked, so a host that says the same again hears the same. Answers\n * too whether which filters are held changed, which is what the panels'\n * clicks read. A filter let go keeps its value and is the reader's again.\n */\n hold(held: HeldFilters | null): { refused: Issue[]; moved: boolean } {\n const values = held?.values ?? {};\n const next = new Set(Object.keys(values));\n const grouping = held !== null && held.unit !== undefined;\n const moved =\n next.size !== this.held.size ||\n [...next].some(name => !this.held.has(name)) ||\n grouping !== this.heldUnit;\n this.held = next;\n this.heldUnit = grouping;\n // What was counted under the held values is counted again under the\n // new ones.\n if (moved) this.candidates.reset();\n\n const applied = this.host.applied();\n const current = this.host.current();\n const defaults = defaultFilters(applied);\n const wanted: DashboardFilters = {\n ...current,\n values: { ...current.values },\n };\n for (const [name, value] of Object.entries(values)) {\n const start = value ?? defaults.values[name];\n if (start === undefined) delete wanted.values[name];\n else wanted.values[name] = start;\n }\n if (grouping) {\n const unit = held?.unit ?? defaults.unit;\n if (unit !== undefined) wanted.unit = unit;\n }\n const { filters, refused } = admitFilters(applied, wanted, this.host.kinds);\n if (!dequal(filters, current)) this.commit(filters);\n return { refused, moved };\n }\n\n /** Whether the host holds this filter (`hold`). */\n holds(name: string): boolean {\n return this.held.has(name);\n }\n\n /**\n * 「清空」: every filter the reader holds cleared — a required one back to\n * its default — and the time grouping to its default; what the host holds\n * stays.\n */\n clear(): void {\n const current = this.host.current();\n const values: Record<string, FilterValue> = {};\n for (const name of this.held) {\n const value = current.values[name];\n if (value !== undefined) values[name] = value;\n }\n this.put(\n this.heldUnit && current.unit !== undefined\n ? { values, unit: current.unit }\n : { values },\n );\n }\n\n private with(\n name: string,\n value: FilterValue | null,\n panelId: string | null,\n ): DashboardFilters {\n const current = this.host.current();\n const values = { ...current.values };\n const from = { ...current.from };\n if (value === null) delete values[name];\n else values[name] = value;\n if (panelId === null) delete from[name];\n else from[name] = panelId;\n return { ...current, values, from };\n }\n\n /** The time grouping's unit; one the board does not offer is ignored. */\n unit(unit: AnalysisDateUnit): void {\n if (this.heldUnit) return;\n this.put({ ...this.host.current(), unit });\n }\n\n /**\n * Every filter as asked, all or nothing: a reader's one change (`set`,\n * `press`, a unit) is refused whole, and nothing moves.\n */\n private put(wanted: DashboardFilters): Issue[] {\n const { filters, refused } = admitFilters(\n this.host.applied(),\n wanted,\n this.host.kinds,\n );\n if (refused.length > 0) return refused;\n if (!dequal(filters, this.host.current())) this.commit(filters);\n return [];\n }\n\n /**\n * Every filter at once, as a host's address has them (`setFilters`, and\n * what a board opens on): what the board takes goes in, and what it\n * refuses — a filter renamed or taken off since the address was written,\n * a value its kind cannot read — is left out and answered, so one stale\n * name never costs the reader the rest of the address.\n */\n take(wanted: DashboardFilters): Issue[] {\n const { filters, refused } = admitFilters(\n this.host.applied(),\n wanted,\n this.host.kinds,\n );\n if (!dequal(filters, this.host.current())) this.commit(filters);\n return refused;\n }\n\n /** Shows what the filters hold at once, and runs it a moment later. */\n private commit(filters: DashboardFilters): void {\n this.host.commit(filters);\n if (this.host.started()) {\n this.timer.stop();\n this.timer.sync(AUTO_APPLY_DELAY_MS);\n }\n }\n\n /**\n * The values in force, admitted against `config`: a filter taken off\n * holds nothing, a required one never less than its default; the same\n * object while they say the same, so a re-sync does not tell the host\n * they changed.\n */\n on(config: DashboardViewConfig): DashboardFilters {\n const current = this.host.current();\n const { filters } = admitFilters(config, current, this.host.kinds);\n return dequal(filters, current) ? current : filters;\n }\n\n /**\n * What a text filter offers to pick from: the values of the fields it is\n * wired to, counted, one list across the board (`FilterCandidates`);\n * `null` for a filter of another type, one with a list of its own, or one\n * wired to no field that offers its values.\n */\n candidatesOf(name: string): ValueCandidateSource | null {\n const applied = this.host.applied();\n const filter = filtersOf(applied).find(field => field.name === name);\n if (!filter || filterTypeOf(filter.kind) !== 'text' || filter.options)\n return null;\n // A list the wired fields declare is picked from, never counted.\n if (this.optionsOf(name)) return null;\n const targets = panelsOf(applied).flatMap(panel => {\n if (!isViewPanel(panel)) return [];\n const binding = bindingsOf(panel).find(\n entry => entry.globalField === name,\n );\n const view = binding && this.host.viewOf(panel);\n if (!binding || !view) return [];\n // Counted under the condition the panel runs under (`panelScope`) —\n // the board's fixed scope and the filters the host holds, never the\n // reader's own values — so a board fixed to one\n // region, or a page locked to one customer, offers that one's values\n // and no one else's. Read as it is asked: the source outlives this\n // call, and the board may have changed by then.\n const scope = () => {\n const board = this.host.applied();\n const now =\n panelsOf(board)\n .filter(isViewPanel)\n .find(entry => entry.id === panel.id) ?? panel;\n const tree = panelScope(now, {\n applied: board,\n filters: { values: this.heldValues() },\n kinds: this.host.kinds,\n });\n return isEmptyFilter(tree) ? null : tree;\n };\n return [\n {\n panelId: panel.id,\n definition: view.definition,\n field: binding.panelField,\n scope,\n },\n ];\n });\n return this.candidates.of(name, targets);\n }\n\n /**\n * The list a filter without one of its own picks from: what the fields\n * it is wired to declare, merged (`wiredOptions`); `null` when none does.\n */\n optionsOf(name: string): FieldOption[] | null {\n const applied = this.host.applied();\n const filter = filtersOf(applied).find(field => field.name === name);\n if (!filter || filter.options) return null;\n return wiredOptions(\n applied,\n name,\n panel => this.host.viewOf(panel)?.definition.fields ?? null,\n );\n }\n\n /** What the filters the host holds hold now. */\n private heldValues(): Record<string, FilterValue> {\n const { values } = this.host.current();\n return Object.fromEntries(\n Object.entries(values).filter(([name]) => this.held.has(name)),\n );\n }\n\n stop(): void {\n this.timer.stop();\n }\n}\n\n/** What a reader's command on a filter the host holds is answered with. */\nfunction heldIssue(name: string): Issue {\n return issue('dashboard.filter.held', ['filters', name], { field: name });\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A press on one group of an analysis panel, worked out (D22 H, I): the\n * group's value in a board filter's shape and the filter it sets\n * (cross-filtering), whether a group is the one a filter's value was\n * pressed on, and where a custom destination goes carrying it. The panel's\n * `click` says which; the kernel reads it (`dashboard/click.ts`), and this\n * is the half that needs the analysis kernel — a group's conditions\n * (`drillGroups`) — which the dashboard kernel may not import.\n *\n * Which click is in force is the panel state's to say, never a press's\n * (A-11): admission sets a click aside when it warned of it, or when the\n * host holds the filter it sets, and the state carries the click with the\n * finding (`DashboardPanelState.click`, `clickFinding`). A press reads\n * that and falls back to the follow-up menu with the finding, as the\n * panel's warning says (D22 H).\n */\n\nimport { dequal } from 'dequal';\nimport {\n filterTypeOf,\n sameFilterType,\n type DashboardField,\n type DashboardFilters,\n type DashboardViewConfig,\n type ViewInstance,\n type DashboardViewPanel,\n type FieldDefinition,\n type FilterLeaf,\n type FilterNode,\n type FilterTree,\n type FilterValue,\n type Issue,\n type IssuePath,\n type RecordData,\n} from '../../model/index.js';\nimport {\n filterFields,\n isReferenceFilterValue,\n issue,\n readInstant,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport { drillGroups, type DrilledGroup } from '../../analysis/index.js';\nimport { drillSpan } from '../../analysis/drill.js';\nimport {\n bindingsOf,\n crossFilterChoices,\n defaultFilters,\n fillUrl,\n filterValueIssues,\n filtersOf,\n isViewPanel,\n panelsOf,\n tabsOf,\n takesGroup,\n type BoardClick,\n type PanelReference,\n} from '../../dashboard/index.js';\nimport type { DataViewRuntime } from '../viewRuntime.js';\nimport type { DashboardPanelState } from './panels.js';\nimport type { HandOver, ViewNavigation } from '../navigation.js';\n\n/** What a press that sets a filter did (D22 I). */\nexport type CrossFilterOutcome =\n /** The filter took the group's value, from this panel. */\n | { kind: 'set'; filter: DashboardField }\n /** The same group pressed again: the filter no longer holds it. */\n | { kind: 'cleared'; filter: DashboardField }\n /**\n * Nothing changed: the group holds no value the filter can take (the\n * records without one), or the filter refused it.\n */\n | { kind: 'no-value'; filter: DashboardField }\n /** The panel's press sets no filter. */\n | { kind: 'none' };\n\n/** Where a press on a custom destination goes, or why it goes nowhere. */\nexport type PressDestination =\n | { to: ViewNavigation }\n | { refused: Issue }\n /**\n * The click cannot do what it says — admission warned of it, or, read at\n * the press, a board it opens is gone, or a filter or a dimension it maps\n * is (D23 Q17): the follow-up menu opens on the group instead, and\n * `issue` says why. The board read by the press re-judges the panel, so\n * the warning stays on it and the next press opens the menu directly.\n */\n | { fallback: Issue };\n\n/** Another board as a click reads it: the instance, its config a board's. */\nexport type DestinationBoard = ViewInstance & { config: DashboardViewConfig };\n\n/** What the presses need of the runtime that holds the board. */\nexport interface PressHost {\n kinds: FieldKindRegistry;\n applied(): DashboardViewConfig;\n filters(): DashboardFilters;\n /** A data panel's child, the rows a press is on. */\n child(panelId: string): DataViewRuntime | null;\n /** Sets a filter by a press (`FilterValues.press`). */\n press(name: string, value: FilterValue | null, panelId: string): Issue[];\n /** Whether the host holds this filter, so no press can set it. */\n held(name: string): boolean;\n /**\n * A panel as the board has it now: the click in force and why a click set\n * is not (`DashboardPanelState`); `null` for no such panel.\n */\n panel(panelId: string): DashboardPanelState | null;\n /** A saved view, loaded: what a destination carries its group into. */\n reference(instanceId: string): Promise<PanelReference | null>;\n /** What the panel's view would take off the board (`handOver`). */\n handOver(panelId: string): HandOver | null;\n}\n\n/** The panel, the child and the config its rows ran on. */\ninterface Pressed {\n panel: DashboardViewPanel;\n index: number;\n groups: DrilledGroup[];\n}\n\n/**\n * The presses on a board's panels. Each reads the panel as the board has it\n * now and the child's rows as they last landed — a press is on a group of\n * the result on screen, never of a draft.\n */\nexport class PanelPresses {\n constructor(private readonly host: PressHost) {}\n\n /**\n * Cross-filtering: the filter the panel's press sets takes the group's\n * value, marked as pressed on this panel, so every other panel wired to it\n * runs under it and this one does not; the same group pressed again clears\n * it — a required filter back to its default.\n */\n crossFilter(panelId: string, row: RecordData): CrossFilterOutcome {\n const target = this.filterOf(panelId);\n if (!target) return { kind: 'none' };\n const { filter, field } = target;\n const value = this.valueOf(panelId, filter, field, row);\n if (value === null) return { kind: 'no-value', filter };\n const current = this.host.filters();\n if (\n current.from?.[filter.name] === panelId &&\n dequal(current.values[filter.name], value)\n ) {\n this.host.press(filter.name, null, panelId);\n return { kind: 'cleared', filter };\n }\n const refused = this.host.press(filter.name, value, panelId);\n return refused.length > 0\n ? { kind: 'no-value', filter }\n : { kind: 'set', filter };\n }\n\n /**\n * Whether a filter holds this group's value, set by a press on this very\n * panel — the one its click sets, or a date filter a span of its time\n * axis set (`pressSpan`): the group the panel marks, since it is not\n * narrowed by the value it set. A group whose bucket lies inside the span\n * a date filter holds is one of the groups pressed.\n */\n pressed(panelId: string, row: RecordData): boolean {\n const found = this.panelOf(panelId);\n const current = this.host.filters();\n if (!found || !current.from) return false;\n const byName = new Map(\n filtersOf(this.host.applied()).map(field => [field.name, field]),\n );\n return bindingsOf(found.panel).some(binding => {\n const filter = byName.get(binding.globalField);\n if (!filter || current.from?.[filter.name] !== panelId) return false;\n const value = this.valueOf(panelId, filter, binding.panelField, row);\n const held = current.values[filter.name];\n return value !== null && (dequal(held, value) || within(value, held));\n });\n }\n\n /**\n * The date filters a span of this panel's time axis can set (D33 Q52,\n * 「设为〈筛选〉」): each wired to the panel through the field of a date\n * dimension its rows ran with, and not held by the host. Offered whatever\n * the panel's click says — a brush is not a press, and asks the menu.\n */\n spanFilters(panelId: string): DashboardField[] {\n const found = this.panelOf(panelId);\n const ran = this.host.child(panelId)?.getSnapshot().result?.config;\n if (!found || ran?.kind !== 'analysis' || ran.elements?.length) return [];\n const dates = ran.groups.filter(group => group.type === 'DATE_HISTOGRAM');\n return crossFilterChoices(\n filtersOf(this.host.applied()),\n found.panel,\n dates,\n )\n .map(choice => choice.filter)\n .filter(\n filter =>\n filterTypeOf(filter.kind) === 'date' && !this.host.held(filter.name),\n );\n }\n\n /**\n * A span of a panel's time axis set into one of its `spanFilters`, as a\n * press sets a filter (D22 I): marked as pressed on this panel, so every\n * other panel wired to it runs under it and this one keeps every group,\n * marking the ones inside it (D23 Q18). `row` and `through` are the span's\n * two ends, as `drillSpan` reads them.\n */\n pressSpan(\n panelId: string,\n name: string,\n row: RecordData,\n through: RecordData,\n ): CrossFilterOutcome {\n const filter = this.spanFilters(panelId).find(entry => entry.name === name);\n const found = this.panelOf(panelId);\n const child = this.host.child(panelId);\n const ran = child?.getSnapshot().result?.config;\n if (!filter || !found || !child || ran?.kind !== 'analysis')\n return { kind: 'none' };\n const field = bindingsOf(found.panel).find(\n binding => binding.globalField === name,\n )?.panelField;\n const spanned = drillSpan(\n ran,\n child.fields,\n this.host.kinds,\n row,\n through,\n {\n timeZone: child.environment.timeZone,\n },\n )?.find(\n entry =>\n entry.group.field === field && entry.group.type === 'DATE_HISTOGRAM',\n );\n const value = spanned ? filterValueOf('date', spanned) : null;\n if (value === null) return { kind: 'no-value', filter };\n return this.host.press(name, value, panelId).length > 0\n ? { kind: 'no-value', filter }\n : { kind: 'set', filter };\n }\n\n /**\n * Where a press on a panel with a custom destination goes: a page of the\n * host's, its URL filled with the group; or another saved view, taking\n * what the panel's view would take off the board (D26 Q30) — what the\n * page holds as its scope, the reader's values and the group's\n * conditions as its own — each condition on fields its data has too, by\n * name and by type, the rule auto-connect wires by (D22 G). A view that\n * is gone, or is a dashboard, is refused and said.\n */\n async destination(\n panelId: string,\n row: RecordData,\n ): Promise<PressDestination | null> {\n const state = this.host.panel(panelId);\n const click = state?.click ?? null;\n if (!click)\n return state?.clickFinding ? { fallback: state.clickFinding } : null;\n if (click.kind === 'filter') return null;\n const pressed = this.pressedOn(panelId, row);\n if (!pressed) return null;\n const at = ['panels', pressed.index, 'click'];\n if (click.kind === 'url') {\n const url = fillUrl(click.url, groupTexts(pressed.groups));\n return url === null\n ? { refused: issue('dashboard.click.url-unsafe', at) }\n : { to: { kind: 'url', url } };\n }\n if (click.kind === 'dashboard') return this.toBoard(click, pressed, at);\n const reference = await this.host.reference(click.instanceId);\n if (!reference)\n return {\n refused: issue('dashboard.click.destination-unavailable', at),\n };\n if (reference.instance.config.kind === 'dashboard')\n return {\n refused: issue('dashboard.click.destination-unsupported', at),\n };\n const carries = carriedOnto(\n this.host.child(panelId)?.fields ?? [],\n reference.fields,\n );\n const conditions: FilterLeaf[] = pressed.groups.flatMap(drilled =>\n drilled.group.field !== undefined && carries(drilled.group.field)\n ? drilled.conditions\n : [],\n );\n const handed = this.host.handOver(panelId);\n const own = kept(handed?.filter ?? null, carries);\n return {\n to: {\n kind: 'view',\n definitionId: reference.instance.definitionId,\n instanceId: click.instanceId,\n scopeFilter: tree(kept(handed?.scopeFilter ?? null, carries)),\n filter: tree([...own, ...conditions]),\n ...(handed?.from ? { from: handed.from } : {}),\n },\n };\n }\n\n /**\n * Another board a click opens, read for 「点击时…」 or a press — never\n * when this board opens — through the references the panels load, so\n * the read re-judges the click (a reference settling admits the board\n * again); `null` for one gone, unreadable or not a board.\n */\n async board(instanceId: string): Promise<DestinationBoard | null> {\n const reference = await this.host.reference(instanceId);\n const config = reference?.instance.config;\n return reference && config?.kind === 'dashboard'\n ? { ...reference.instance, config }\n : null;\n }\n\n /**\n * A press that opens another board (D23 Q17): the board read — which\n * re-judges the panel's click against it, so the state says whether the\n * mapping still holds and, if not, why — then each filter mapped set\n * from its source — the group's value on a\n * dimension, in the filter's shape, or what this board's filter holds at\n * the press (its default until a reader set another) — and the rest at\n * the target's defaults, as a board opened without a value for them would\n * start. A source with nothing to give — the records without a value, a\n * filter left blank, a value the target filter refuses (several into one\n * that takes one) — leaves that filter at its default too.\n */\n private async toBoard(\n click: BoardClick,\n pressed: Pressed,\n at: IssuePath,\n ): Promise<PressDestination> {\n const reference = await this.host.reference(click.instanceId);\n const state = this.host.panel(pressed.panel.id);\n const config = reference?.instance.config;\n if (!state?.click || !reference || config?.kind !== 'dashboard')\n return {\n fallback:\n state?.clickFinding ?? issue('dashboard.click.board-gone', at),\n };\n const filters = defaultFilters(config);\n const byName = new Map(filtersOf(config).map(field => [field.name, field]));\n const held = this.host.filters().values;\n for (const [name, source] of Object.entries(click.values)) {\n const filter = byName.get(name);\n if (!filter) continue;\n const value =\n 'filter' in source\n ? (held[source.filter] ?? null)\n : this.groupValue(filter, source.dimension, pressed);\n if (\n value !== null &&\n filterValueIssues(filter, value, this.host.kinds, [name]).length === 0\n )\n filters.values[name] = value;\n }\n return {\n to: {\n kind: 'dashboard',\n definitionId: reference.instance.definitionId,\n instanceId: click.instanceId,\n filters,\n // The tab the author named (D39), while the board still has it;\n // otherwise where its reader last read it.\n ...(click.tab && tabsOf(config).some(tab => tab.id === click.tab)\n ? { tab: click.tab }\n : {}),\n },\n };\n }\n\n /** The group's value on one dimension, in a filter's shape; `null` for none. */\n private groupValue(\n filter: DashboardField,\n field: string,\n pressed: Pressed,\n ): FilterValue | null {\n const type = filterTypeOf(filter.kind);\n const drilled = pressed.groups.find(\n entry =>\n entry.group.field === field && takesGroup(type, entry.group.type),\n );\n return drilled ? filterValueOf(type, drilled) : null;\n }\n\n /** The filter a panel's press sets, and the field it is wired through. */\n private filterOf(\n panelId: string,\n ): { filter: DashboardField; field: string } | null {\n const panel = this.panelOf(panelId)?.panel;\n const click = this.host.panel(panelId)?.click;\n if (!panel || click?.kind !== 'filter') return null;\n const filter = filtersOf(this.host.applied()).find(\n field => field.name === click.filter,\n );\n const binding =\n filter &&\n bindingsOf(panel).find(entry => entry.globalField === filter.name);\n return filter && binding ? { filter, field: binding.panelField } : null;\n }\n\n private panelOf(\n panelId: string,\n ): { panel: DashboardViewPanel; index: number } | null {\n const panels = panelsOf(this.host.applied());\n const index = panels.findIndex(\n panel => isViewPanel(panel) && panel.id === panelId,\n );\n return index < 0\n ? null\n : { panel: panels[index] as DashboardViewPanel, index };\n }\n\n /** The row's groups, as the config the child's rows ran on reads them. */\n private pressedOn(panelId: string, row: RecordData): Pressed | null {\n const found = this.panelOf(panelId);\n const child = this.host.child(panelId);\n const ran = child?.getSnapshot().result?.config;\n // A group of expanded elements names an element's fields, which no\n // board filter narrows (`pressableGroups`): its press is the menu's.\n if (!found || !child || ran?.kind !== 'analysis' || ran.elements?.length)\n return null;\n const groups = drillGroups(ran, child.fields, this.host.kinds, row, {\n timeZone: child.environment.timeZone,\n });\n return groups ? { ...found, groups } : null;\n }\n\n /** The group's value in the filter's shape, or `null` for none. */\n private valueOf(\n panelId: string,\n filter: DashboardField,\n field: string,\n row: RecordData,\n ): FilterValue | null {\n const pressed = this.pressedOn(panelId, row);\n const type = filterTypeOf(filter.kind);\n const drilled = pressed?.groups.find(\n entry =>\n entry.group.field === field && takesGroup(type, entry.group.type),\n );\n return drilled ? filterValueOf(type, drilled) : null;\n }\n}\n\n/**\n * One dimension's value as the filter holds it (D22 I): a date bucket as\n * the window its conditions already are, a yes-or-no as itself, an id as\n * the one item a reference holds, text and numbers as a list of one — the\n * shape each filter type's operator takes (`filterOperatorOf`). The group\n * of records with no value is none: a filter cannot hold 「空」.\n */\nfunction filterValueOf(\n type: ReturnType<typeof filterTypeOf>,\n drilled: DrilledGroup,\n): FilterValue | null {\n const [condition] = drilled.conditions;\n if (!condition || condition.operator === 'IS_NULL') return null;\n const value = drilled.value;\n switch (type) {\n case 'date':\n return condition.value;\n case 'boolean':\n return typeof value === 'boolean' ? value : null;\n case 'id':\n return isReferenceFilterValue(condition.value)\n ? condition.value\n : {\n items: [{ id: value as string | number, label: String(value) }],\n };\n default:\n return typeof value === 'string' || typeof value === 'number'\n ? [value]\n : null;\n }\n}\n\n/**\n * Whether a date filter's value lies inside another's: a bucket inside the\n * span a brush set. Only two absolute windows compare; anything else is not\n * inside.\n */\nfunction within(inner: FilterValue, outer: FilterValue | undefined): boolean {\n const a = absoluteWindow(inner);\n const b = absoluteWindow(outer);\n return a !== null && b !== null && a.from >= b.from && a.to <= b.to;\n}\n\nfunction absoluteWindow(\n value: FilterValue | undefined,\n): { from: number; to: number } | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value))\n return null;\n const window = value as { type?: unknown; from?: unknown; to?: unknown };\n if (\n window.type !== 'absolute' ||\n typeof window.from !== 'string' ||\n typeof window.to !== 'string'\n )\n return null;\n const from = Date.parse(window.from);\n const to = Date.parse(window.to);\n return Number.isNaN(from) || Number.isNaN(to) ? null : { from, to };\n}\n\n/**\n * Whether a condition on a field of the panel's view can be carried onto\n * another view: it has a field of that name and of the same filter type.\n */\nfunction carriedOnto(\n source: readonly FieldDefinition[],\n target: readonly FieldDefinition[],\n): (field: string) => boolean {\n const byName = new Map(target.map(field => [field.name, field]));\n return name => {\n const from = source.find(field => field.name === name);\n const to = byName.get(name);\n return !!from && !!to && sameFilterType(from.kind, to.kind);\n };\n}\n\n/**\n * The conjuncts of a tree another view can carry: each one whose every\n * field it has (`carries`); one that names a field it lacks is left out\n * whole rather than cut down to a question it never asked.\n */\nfunction kept(\n tree: FilterTree | null,\n carries: (field: string) => boolean,\n): FilterNode[] {\n if (!tree) return [];\n const conjuncts = tree.op === 'and' ? tree.children : [tree];\n return conjuncts.filter(node =>\n filterFields({ op: 'and', children: [node] }).every(carries),\n );\n}\n\n/** Conditions as one \"all of\" tree, or `null` for none. */\nfunction tree(children: FilterNode[]): FilterTree | null {\n return children.length > 0 ? { op: 'and', children } : null;\n}\n\n/**\n * What a URL template's `{{field}}` takes from the group pressed, by the\n * field each dimension buckets: a date bucket as the instant it starts, a\n * value as itself; the records with no value as nothing.\n */\nfunction groupTexts(groups: readonly DrilledGroup[]): Record<string, string> {\n const texts: Record<string, string> = {};\n for (const { group, value, conditions } of groups) {\n if (group.field === undefined || conditions[0]?.operator === 'IS_NULL')\n continue;\n const instant =\n group.type === 'DATE_HISTOGRAM' ? readInstant(value)?.ms : undefined;\n texts[group.field] =\n instant === undefined ? String(value) : new Date(instant).toISOString();\n }\n return texts;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport { overlaid, type DashboardViewConfig } from '../../model/index.js';\n\n/**\n * The edits building a board is made of, by the command that makes each —\n * `DashboardEditing` and `DashboardFilterEditing` less the undoing itself.\n */\nexport type EditCommand =\n | 'addPanel'\n | 'removePanel'\n | 'duplicatePanel'\n | 'renamePanel'\n | 'replacePanelView'\n | 'editPanelContent'\n | 'movePanelToTab'\n | 'setPresentation'\n | 'referToSaved'\n | 'setPanelClick'\n | 'place'\n | 'reorderPanel'\n | 'addTab'\n | 'renameTab'\n | 'moveTab'\n | 'removeTab'\n | 'addFilter'\n | 'renameFilter'\n | 'retypeFilter'\n | 'removeFilter'\n | 'setFilterDefault'\n | 'setFilterRequired'\n | 'setFilterMultiple'\n | 'setFilterOneDay'\n | 'setFilterOptions'\n | 'moveFilter'\n | 'bindPanel'\n | 'unbindPanels'\n | 'setTimeGrouping'\n | 'removeFixedScope'\n | 'setWidth';\n\n/**\n * One step of the board's history: the command, and what it was about — a\n * panel's id, a tab's id or a filter's name; `null` for the time grouping,\n * the fixed scope and the board's width.\n * A screen names the step by it (「撤销:移除「北区订单」」).\n */\nexport interface EditStep {\n command: EditCommand;\n subject: string | null;\n}\n\n/** What the history offers now: the step an undo would take back, and a redo. */\nexport interface EditHistoryState {\n undo: EditStep | null;\n redo: EditStep | null;\n}\n\nexport const NO_HISTORY: EditHistoryState = { undo: null, redo: null };\n\n/**\n * The members of one config a step changed, as they were and as they came\n * out; a member a config lacks is `undefined` (configs are JSON, which has\n * no `undefined` of its own).\n */\ninterface Change {\n before: Partial<DashboardViewConfig>;\n after: Partial<DashboardViewConfig>;\n}\n\n/** One step, over both configs an edit writes: the draft and the screen. */\ninterface Entry {\n step: EditStep;\n draft: Change;\n applied: Change;\n}\n\n/**\n * Commands a burst of which is one step: the same command on the same thing\n * again and again is someone typing a name, picking a chart's options or\n * trying defaults, and an undo that took one keystroke back would be no\n * undo at all. Anything else in between ends the burst.\n */\nconst BURSTS: ReadonlySet<EditCommand> = new Set([\n 'renamePanel',\n 'renameTab',\n 'renameFilter',\n 'setFilterDefault',\n 'setFilterOptions',\n 'setPresentation',\n 'setTimeGrouping',\n]);\n\n/**\n * The members of a board the building commands write — each command one\n * step of the history, which keeps these members as they were and came out\n * (A-10). A plain `edit` of the board leaves them to those commands.\n */\nconst BUILT_MEMBERS = [\n 'panels',\n 'tabs',\n 'fields',\n 'timeGrouping',\n 'width',\n] as const satisfies readonly (keyof DashboardViewConfig)[];\n\n/**\n * A patch with the members the building commands own taken out: an undo\n * puts back the whole member a step changed, so a list an `edit` had\n * changed underneath it would be put back too, and silently — the edit\n * noted nowhere, the undo naming another step.\n */\nexport function outsideHistory(\n patch: Partial<DashboardViewConfig>,\n): Partial<DashboardViewConfig> {\n const rest = { ...patch };\n for (const member of BUILT_MEMBERS) delete rest[member];\n return rest;\n}\n\n/** How many steps back an undo reaches. */\nexport const EDIT_HISTORY_DEPTH = 100;\n\n/**\n * The board's history while it is built: one step per edit command, each\n * holding only the members of the config it changed, as they were and as\n * they came out — so an undo puts back what that step changed and nothing\n * else, and a fixed scope changed or a refresh interval set in\n * between stays as it is.\n *\n * The fixed scope is one step's too — its removal (`removeFixedScope`) —\n * yet stays open to a plain `edit`, the one way a host sets it: a host that\n * sets it after the author removed it has it put back by an undo of that\n * removal, which is what the step says it takes back.\n *\n * A redo is the step an undo took back, until the next edit.\n */\nexport class EditHistory {\n private done: Entry[] = [];\n private undone: Entry[] = [];\n\n get state(): EditHistoryState {\n const undo = this.done[this.done.length - 1]?.step ?? null;\n const redo = this.undone[this.undone.length - 1]?.step ?? null;\n return undo === null && redo === null ? NO_HISTORY : { undo, redo };\n }\n\n /**\n * Notes one edit: the configs before it and after it. A step that changed\n * nothing is not one; a burst of one command on one thing is one step,\n * and a burst that came back to where it began is none.\n */\n record(\n step: EditStep,\n draft: [DashboardViewConfig, DashboardViewConfig],\n applied: [DashboardViewConfig, DashboardViewConfig],\n ): void {\n const change = { draft: diff(...draft), applied: diff(...applied) };\n if (isEmpty(change.draft) && isEmpty(change.applied)) return;\n this.undone = [];\n const last = this.done[this.done.length - 1];\n if (\n last &&\n BURSTS.has(step.command) &&\n last.step.command === step.command &&\n last.step.subject === step.subject\n ) {\n last.draft = merged(last.draft, change.draft);\n last.applied = merged(last.applied, change.applied);\n if (isEmpty(last.draft) && isEmpty(last.applied)) this.done.pop();\n return;\n }\n this.done.push({ step, ...change });\n if (this.done.length > EDIT_HISTORY_DEPTH) this.done.shift();\n }\n\n /**\n * Takes the last step back: the members it changed, as they were, to lay\n * over the draft and over the screen; `null` when there is none.\n */\n undo(): Rewind | null {\n const entry = this.done.pop();\n if (!entry) return null;\n this.undone.push(entry);\n return {\n step: entry.step,\n draft: entry.draft.before,\n applied: entry.applied.before,\n };\n }\n\n /** Makes the last step taken back again; `null` when there is none. */\n redo(): Rewind | null {\n const entry = this.undone.pop();\n if (!entry) return null;\n this.done.push(entry);\n return {\n step: entry.step,\n draft: entry.draft.after,\n applied: entry.applied.after,\n };\n }\n\n /** Starts again: after a revert, a save, or a board read anew. */\n clear(): void {\n this.done = [];\n this.undone = [];\n }\n}\n\n/** What an undo or a redo lays over the two configs. */\nexport interface Rewind {\n step: EditStep;\n draft: Partial<DashboardViewConfig>;\n applied: Partial<DashboardViewConfig>;\n}\n\n/**\n * A config with these members laid over it — one `undefined` taken out, as\n * the config it came from did not have it — or the same config when that\n * changes nothing.\n */\nexport function rewound(\n config: DashboardViewConfig,\n members: Partial<DashboardViewConfig>,\n): DashboardViewConfig {\n const keys = Object.keys(members) as (keyof DashboardViewConfig)[];\n return keys.every(key => config[key] === members[key])\n ? config\n : overlaid(config, members);\n}\n\n/**\n * The members one edit changed. An edit hands back what it did not touch as\n * it was; a member made anew the same — a form submitted unchanged — is no\n * change either.\n */\nfunction diff(before: DashboardViewConfig, after: DashboardViewConfig): Change {\n const change: Change = { before: {}, after: {} };\n if (before === after) return change;\n const keys = new Set([...Object.keys(before), ...Object.keys(after)]);\n for (const key of keys as Set<keyof DashboardViewConfig>)\n if (before[key] !== after[key] && !dequal(before[key], after[key])) {\n set(change.before, key, before[key]);\n set(change.after, key, after[key]);\n }\n return change;\n}\n\n/**\n * Two changes one after the other as one: the first's `before`, the\n * second's `after`, and a member that came back to where it began dropped.\n */\nfunction merged(first: Change, then: Change): Change {\n const out: Change = {\n before: { ...first.before },\n after: { ...first.after },\n };\n for (const key of Object.keys(then.after) as (keyof DashboardViewConfig)[]) {\n if (!(key in out.before)) set(out.before, key, then.before[key]);\n set(out.after, key, then.after[key]);\n }\n for (const key of Object.keys(out.after) as (keyof DashboardViewConfig)[])\n if (dequal(out.before[key], out.after[key])) {\n delete out.before[key];\n delete out.after[key];\n }\n return out;\n}\n\nfunction isEmpty(change: Change): boolean {\n return Object.keys(change.after).length === 0;\n}\n\nfunction set(\n members: Partial<DashboardViewConfig>,\n key: keyof DashboardViewConfig,\n value: unknown,\n): void {\n (members as Record<string, unknown>)[key] = value;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DashboardFilterType,\n DashboardTimeGrouping,\n DashboardViewConfig,\n DashboardWidth,\n FieldOption,\n FilterValue,\n PanelClick,\n PanelLayout,\n PanelPresentation,\n ViewConfig,\n ViewInstance,\n} from '../../model/index.js';\nimport { isPlainObject } from '../../filter/index.js';\nimport {\n addFilter,\n addPanel,\n filtersOf,\n addTab,\n autoBindings,\n timeFilterOf,\n type PanelTime,\n bindPanel,\n moveFilter,\n removeFilter,\n renameFilter,\n retypeFilter,\n setFilterDefault,\n setFilterMultiple,\n setFilterOneDay,\n setFilterOptions,\n setFilterRequired,\n setTimeGrouping,\n unbindPanels,\n type NewFilter,\n type PanelFields,\n duplicatePanel,\n editContent,\n movePanelToTab,\n moveTab,\n referToSaved,\n removeFixedScope,\n removePanel,\n removeTab,\n renamePanel,\n setBoardWidth,\n renameTab,\n replacePanelView,\n setPanelClick,\n setPresentation,\n placePanelIn,\n reorderPanelIn,\n type NewContentPanel,\n type NewPanel,\n type NewPanelPlacement,\n} from '../../dashboard/index.js';\nimport {\n EditHistory,\n rewound,\n type EditCommand,\n type EditHistoryState,\n type EditStep,\n} from './history.js';\n\n/**\n * Building the board (D22 A–E, batch B1). Every edit goes into the draft and\n * onto the screen at once — the panels re-run on it as the author works —\n * and nothing is written until the board is saved; `revert` puts back what\n * was. A global filter being composed meanwhile stays pending, as it does\n * under a `place`. An edit that names a panel or a tab the board lacks does\n * nothing.\n *\n * Only while the board is built (`DashboardRuntimeState.building`): outside\n * it every command here is refused — nothing changes, no step is noted, and\n * one that answers answers as a refused one does (`null`, no panels wired).\n * An edit is the building's, and a gesture that outlived it — a view picked,\n * then 「取消」 pressed while it still loaded — must not land on the board\n * read after it (Q-02). A placement is one of them: a grid that is only\n * read has no handles to drag.\n */\nexport interface DashboardEditing {\n /**\n * Adds a panel — a saved view, a view the board owns, or content — at the\n * first free place on its tab at or below `placement.fromRow`, and returns\n * its id; `null` when the board holds as many panels as it may.\n */\n addPanel(panel: NewPanel, placement?: NewPanelPlacement): string | null;\n /** Removes a panel; its tab closes up behind it. */\n removePanel(panelId: string): void;\n /** Copies a panel beside it (or under it) and returns the copy's id. */\n duplicatePanel(panelId: string): string | null;\n /** Sets a panel's title; a blank one names it by what it shows again. */\n renamePanel(panelId: string, title: string): void;\n /** Points a data panel at another saved view; its override goes. */\n replacePanelView(panelId: string, instanceId: string): void;\n /** Changes what a content panel holds. */\n editPanelContent(panelId: string, patch: Partial<NewContentPanel>): void;\n /** Moves a panel to another tab, at the first free place there. */\n movePanelToTab(panelId: string, tabId: string): void;\n /** Overrides how a data panel looks; `null` puts back the view's own look. */\n setPresentation(\n panelId: string,\n presentation: PanelPresentation | null,\n ): void;\n /**\n * Points a data panel at a saved view that is the very view it showed —\n * its own analysis saved as a view (`ViewEngine.saveOwnedView`), or the\n * personal view it stood on copied for the board (`copyPanelView`); the\n * override, the click and the wiring stay.\n */\n referToSaved(panelId: string, instance: ViewInstance): void;\n /**\n * What a press on one group of a data panel does (D22 I, 「点击时…」),\n * or `null` for the follow-up menu.\n */\n setPanelClick(panelId: string, click: PanelClick | null): void;\n /**\n * Adds a tab, last, and returns its id; on a board without tabs the panels\n * go onto a first tab called `firstTitle`. `null` for a blank title or a\n * board that holds as many tabs as it may.\n */\n addTab(title: string, firstTitle: string): string | null;\n renameTab(tabId: string, title: string): void;\n /** Moves a tab to `index` in the bar. */\n moveTab(tabId: string, index: number): void;\n /** Removes a tab and every panel on it; never the board's last tab. */\n removeTab(tabId: string): void;\n /**\n * Puts one panel at `layout` and applies that alone: the panels it now\n * covers make way and its tab floats up behind it (`placePanel`), and\n * every other pending edit — a global filter not yet applied, say — stays\n * pending. A layout the grid does not admit, or a panel id there is none\n * of, is ignored. No panel re-queries for it: a child is kept while its\n * reference and its scope are unchanged, and neither is.\n *\n * `grown` is the rows each panel is drawn tall where the screen grew it\n * past what is saved (D52): the placement lands on the board as drawn,\n * and only what moved is written back (D68, `placePanelIn`) — no\n * untouched panel saves a grown height, and a placement that moves\n * nothing leaves the draft as it was. A layout\n * that says `fixedHeight` marks the panel sized by hand.\n */\n place(\n panelId: string,\n layout: PanelLayout,\n grown?: ReadonlyMap<string, number>,\n ): void;\n /**\n * Moves a panel to place `to` (from 0) along its tab's reading order —\n * the one-column reading's handle (D22 J): a drop, an arrow key, its\n * menu — written back onto the grid as the layout that reads that way and\n * disturbs the rest least (`reorderPanelIn`). Nothing when it is already\n * there or `to` is no place on the tab. One step of the history.\n */\n reorderPanel(panelId: string, to: number): void;\n /**\n * Lays the board out at another width (D31, `setBoardWidth`): its 24\n * columns centred at the fixed width, or across whatever holds it.\n */\n setWidth(width: DashboardWidth): void;\n /**\n * Takes the last edit back — the members of the board it changed, on the\n * draft and on screen alike — and returns the step taken back; `null`\n * when there is none. Every command here and in `DashboardFilterEditing`\n * is one step; a burst of one naming or setting on one thing is one.\n */\n undo(): EditStep | null;\n /** Makes the last step taken back again, until the next edit; `null` when there is none. */\n redo(): EditStep | null;\n}\n\n/**\n * Setting up the board's filters (D22 G), through the draft like every\n * other edit of the board: each goes into the draft and onto the screen at\n * once, and is saved with the board.\n */\nexport interface DashboardFilterEditing {\n /** Adds a filter, last on the bar, and returns its name; `null` when full. */\n addFilter(filter: NewFilter): string | null;\n /** A filter's name on the bar; a blank one is not taken. */\n renameFilter(name: string, label: string): void;\n /** Gives a filter another type; its default, list and wires go. */\n retypeFilter(name: string, type: DashboardFilterType): void;\n /** Removes a filter and every wire to it. */\n removeFilter(name: string): void;\n /** What a filter starts at — and holds now; `null` takes it off. */\n setFilterDefault(name: string, value: FilterValue | null): void;\n setFilterRequired(name: string, required: boolean): void;\n setFilterMultiple(name: string, multiple: boolean): void;\n /** Whether a date filter holds one day and nothing else. */\n setFilterOneDay(name: string, oneDay: boolean): void;\n /** A list of its own to pick from, or `null`: the wired fields' values. */\n setFilterOptions(name: string, options: FieldOption[] | null): void;\n /** Moves a filter to `index` on the bar. */\n moveFilter(name: string, index: number): void;\n /**\n * Wires one panel to a filter through `panelField` by hand, and every\n * other panel with a field of that name and type on its own; returns the\n * panels auto-connect wired (`bindPanel`).\n */\n bindPanel(name: string, panelId: string, panelField: string): string[];\n /**\n * Takes these panels' wires to a filter off. By hand, a date filter's\n * leaves the panel reading whole (`ignoresTime`); an undo of auto-connect\n * (「只接我选的」) says `byHand: false`, and puts the panels back as they\n * were.\n */\n unbindPanels(\n name: string,\n panelIds: readonly string[],\n options?: { byHand?: boolean },\n ): void;\n /** Sets the board's time grouping, or takes it off with `null`. */\n setTimeGrouping(grouping: DashboardTimeGrouping | null): void;\n /**\n * Takes the board's fixed scope out whole (D23 Q16): `fixed` becomes the\n * empty tree, on the draft and on screen, and is saved with the board. The\n * author's alone — a reader never builds, so never takes it.\n */\n removeFixedScope(): void;\n}\n\n/** What the edits need of the runtime that holds the board. */\nexport interface EditingHost {\n /** Whether the board is being built, which every edit asks first. */\n building(): boolean;\n /** The draft an edit works its ids and places out on; `null` once disposed. */\n draft(): DashboardViewConfig | null;\n /** The most panels a board may hold. */\n readonly maxPanels: number;\n /** The config of a saved view already loaded, for the size a panel starts at. */\n viewConfig(instanceId: string): ViewConfig | undefined;\n /** A reference known without loading: the view an owned one was saved as. */\n seed(instance: ViewInstance): void;\n /**\n * The fields of the view a data panel shows, once known — what wiring and\n * auto-connect match a filter against.\n */\n fieldsOf: PanelFields;\n /**\n * What a panel's view says of time (`panelTime`): a panel over a view\n * that says is wired to the board's time filter through it, when the\n * board is read, never by a field's name (D1).\n */\n timeOf?: PanelTime;\n /** What is on screen, which every edit changes with the draft; `null` once disposed. */\n applied(): DashboardViewConfig | null;\n /**\n * The draft and the screen as one edit (or one step taken back) left\n * them, nothing else of either moved, and the history after it\n * (`DashboardViewRuntime.commit`).\n */\n commit(\n draft: DashboardViewConfig,\n applied: DashboardViewConfig,\n history: EditHistoryState,\n ): void;\n}\n\n/** The board's edits, and the history they keep. */\nexport interface BoardEdits extends DashboardEditing, DashboardFilterEditing {\n /** Starts the history again — a revert, a save, a board read anew — and says it is empty. */\n forget(): EditHistoryState;\n /** What a filter starts at in the draft now; `null` for none. */\n defaultOf(name: string): FilterValue | null;\n}\n\n/**\n * The board's edits over one runtime: each a kernel function\n * (`src/dashboard/edit.ts`, `tabs.ts`) handed to `restructure`. An edit that\n * adds works its id and place out once, on the draft, and the screen gets\n * that very panel or tab rather than working both out again.\n */\nexport function boardEditing(host: EditingHost): BoardEdits {\n const history = new EditHistory();\n /**\n * The draft an edit works on, or `null` when it is refused: outside\n * building, or once disposed. A placement is an edit like any other.\n */\n const draftFor = () => (host.building() ? host.draft() : null);\n /** One edit, on the draft and the screen alike, noted as one step of `command` about `subject`. */\n const edit = (\n command: EditCommand,\n subject: string | null,\n change: (config: DashboardViewConfig) => DashboardViewConfig,\n ) => {\n const draft = draftFor();\n const applied = host.applied();\n if (!draft || !applied) return;\n const next = [change(draft), change(applied)] as const;\n if (next[0] === draft && next[1] === applied) return;\n history.record({ command, subject }, [draft, next[0]], [applied, next[1]]);\n host.commit(...next, history.state);\n };\n /**\n * One step taken back or made again: the members it changed laid over the\n * draft and the screen, the same way an edit goes, and nothing else moved.\n * Not held to building by itself: the history is the building's — every\n * step was taken while building, and ending it forgets them\n * (`BoardRules.setBuilding`).\n */\n const rewind = (way: 'undo' | 'redo'): EditStep | null => {\n const draft = host.draft();\n const applied = host.applied();\n if (!draft || !applied) return null;\n const step = way === 'undo' ? history.undo() : history.redo();\n if (!step) return null;\n host.commit(\n rewound(draft, step.draft),\n rewound(applied, step.applied),\n history.state,\n );\n return step.step;\n };\n /** An edit that added one panel to the draft, carried onto the screen. */\n const added = (\n command: EditCommand,\n from: DashboardViewConfig,\n result: { config: DashboardViewConfig; id: string } | null,\n ): string | null => {\n if (!result) return null;\n const panel = result.config.panels.find(\n entry => isPlainObject(entry) && entry.id === result.id,\n );\n edit(command, result.id, config =>\n config === from\n ? result.config\n : panel\n ? { ...config, panels: [...config.panels, panel] }\n : config,\n );\n return result.id;\n };\n\n return {\n addPanel(panel, placement = {}) {\n const draft = draftFor();\n if (!draft) return null;\n const instanceId = 'instanceId' in panel ? panel.instanceId : undefined;\n // A data panel comes onto the board wired to every filter it has a\n // field for, the way auto-connect wires the rest (D22 G).\n const fields = panel.kind === 'view' ? host.fieldsOf(panel) : null;\n const timed =\n panel.kind === 'view' && host.timeOf?.(panel as never) !== undefined\n ? timeFilterOf(draft)?.name\n : undefined;\n const wired =\n panel.kind === 'view' && fields\n ? {\n ...panel,\n bindings: [\n ...(panel.bindings ?? []),\n ...autoBindings(draft, fields, panel.bindings).filter(\n binding => binding.globalField !== timed,\n ),\n ],\n }\n : panel;\n return added(\n 'addPanel',\n draft,\n addPanel(draft, wired, {\n max: host.maxPanels,\n view: instanceId === undefined ? null : host.viewConfig(instanceId),\n ...placement,\n }),\n );\n },\n removePanel: panelId =>\n edit('removePanel', panelId, config => removePanel(config, panelId)),\n duplicatePanel(panelId) {\n const draft = draftFor();\n return draft\n ? added(\n 'duplicatePanel',\n draft,\n duplicatePanel(draft, panelId, host.maxPanels),\n )\n : null;\n },\n renamePanel: (panelId, title) =>\n edit('renamePanel', panelId, config =>\n renamePanel(config, panelId, title),\n ),\n replacePanelView: (panelId, instanceId) =>\n edit('replacePanelView', panelId, config =>\n replacePanelView(config, panelId, instanceId),\n ),\n editPanelContent: (panelId, patch) =>\n edit('editPanelContent', panelId, config =>\n editContent(config, panelId, patch),\n ),\n movePanelToTab: (panelId, tabId) =>\n edit('movePanelToTab', panelId, config =>\n movePanelToTab(config, panelId, tabId),\n ),\n setPresentation: (panelId, presentation) =>\n edit('setPresentation', panelId, config =>\n setPresentation(config, panelId, presentation),\n ),\n setPanelClick: (panelId, click) =>\n edit('setPanelClick', panelId, config =>\n setPanelClick(config, panelId, click),\n ),\n referToSaved(panelId, instance) {\n if (!draftFor()) return;\n host.seed(instance);\n edit('referToSaved', panelId, config =>\n referToSaved(config, panelId, instance.id),\n );\n },\n addTab(title, firstTitle) {\n const draft = draftFor();\n const result = draft && addTab(draft, title, firstTitle);\n if (!draft || !result) return null;\n edit('addTab', result.id, config =>\n config === draft\n ? result.config\n : (addTab(config, title, firstTitle)?.config ?? config),\n );\n return result.id;\n },\n renameTab: (tabId, title) =>\n edit('renameTab', tabId, config => renameTab(config, tabId, title)),\n moveTab: (tabId, index) =>\n edit('moveTab', tabId, config => moveTab(config, tabId, index)),\n removeTab: tabId =>\n edit('removeTab', tabId, config => removeTab(config, tabId)),\n place: (panelId, layout, grown) =>\n edit('place', panelId, config =>\n placePanelIn(config, panelId, layout, undefined, grown),\n ),\n reorderPanel: (panelId, to) =>\n edit('reorderPanel', panelId, config =>\n reorderPanelIn(config, panelId, to),\n ),\n setWidth: width =>\n edit('setWidth', null, config => setBoardWidth(config, width)),\n undo: () => rewind('undo'),\n redo: () => rewind('redo'),\n forget() {\n history.clear();\n return history.state;\n },\n defaultOf(name) {\n const draft = host.draft();\n return (\n (draft &&\n filtersOf(draft).find(field => field.name === name)?.default) ??\n null\n );\n },\n\n addFilter(filter) {\n const draft = draftFor();\n const result = draft && addFilter(draft, filter);\n if (!draft || !result) return null;\n edit('addFilter', result.name, config =>\n config === draft\n ? result.config\n : (addFilter(config, filter)?.config ?? config),\n );\n return result.name;\n },\n renameFilter: (name, label) =>\n edit('renameFilter', name, config => renameFilter(config, name, label)),\n retypeFilter: (name, type) =>\n edit('retypeFilter', name, config => retypeFilter(config, name, type)),\n removeFilter: name =>\n edit('removeFilter', name, config => removeFilter(config, name)),\n setFilterDefault: (name, value) =>\n edit('setFilterDefault', name, config =>\n setFilterDefault(config, name, value),\n ),\n setFilterRequired: (name, required) =>\n edit('setFilterRequired', name, config =>\n setFilterRequired(config, name, required),\n ),\n setFilterMultiple: (name, multiple) =>\n edit('setFilterMultiple', name, config =>\n setFilterMultiple(config, name, multiple),\n ),\n setFilterOneDay: (name, oneDay) =>\n edit('setFilterOneDay', name, config =>\n setFilterOneDay(config, name, oneDay),\n ),\n setFilterOptions: (name, options) =>\n edit('setFilterOptions', name, config =>\n setFilterOptions(config, name, options),\n ),\n moveFilter: (name, index) =>\n edit('moveFilter', name, config => moveFilter(config, name, index)),\n bindPanel(name, panelId, panelField) {\n const draft = draftFor();\n if (!draft) return [];\n const { connected } = bindPanel(\n draft,\n name,\n panelId,\n panelField,\n host.fieldsOf,\n );\n edit(\n 'bindPanel',\n name,\n config =>\n bindPanel(config, name, panelId, panelField, host.fieldsOf).config,\n );\n return connected;\n },\n unbindPanels: (name, panelIds, options) =>\n edit('unbindPanels', name, config =>\n unbindPanels(config, name, panelIds, options),\n ),\n setTimeGrouping: grouping =>\n edit('setTimeGrouping', null, config =>\n setTimeGrouping(config, grouping),\n ),\n removeFixedScope: () =>\n edit('removeFixedScope', null, config => removeFixedScope(config)),\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AnalysisDateUnit,\n DashboardField,\n DashboardFilters,\n DashboardFilterType,\n DashboardTimeGrouping,\n DashboardViewConfig,\n DashboardWidth,\n FieldOption,\n FilterValue,\n Issue,\n PanelClick,\n PanelLayout,\n PanelPresentation,\n RecordData,\n RuntimeLimits,\n ViewInstance,\n} from '../../model/index.js';\nimport { refreshIntervalOf } from '../refreshTimer.js';\nimport {\n storedTimeWires,\n type NewContentPanel,\n type NewFilter,\n type NewPanel,\n type NewPanelPlacement,\n} from '../../dashboard/index.js';\nimport type { EditStep } from './history.js';\nimport type { DashboardRuntimeState, HeldFilters } from './contract.js';\nimport type {\n BoardEdits,\n DashboardEditing,\n DashboardFilterEditing,\n} from './editing.js';\nimport type { FilterValues } from './filterValues.js';\nimport type {\n CrossFilterOutcome,\n DestinationBoard,\n PanelPresses,\n PressDestination,\n} from './press.js';\n\nconst NO_REFUSAL: Issue[] = [];\n\n/** What the rules across the board's parts need of the runtime holding them. */\nexport interface BoardRulesHost {\n readonly limits: RuntimeLimits;\n readonly edits: BoardEdits;\n readonly values: FilterValues;\n disposed(): boolean;\n snapshot(): DashboardRuntimeState;\n /** Patches the snapshot and re-times the board (`RuntimeStore.setState`). */\n patch(state: Partial<DashboardRuntimeState>): void;\n /** Arms or holds the board's one timer again (`RuntimeStore.retime`). */\n retime(): void;\n /** Reads the panels again — their clicks among them — once they were read. */\n reread(): void;\n edit(patch: Partial<DashboardViewConfig>): void;\n apply(): void;\n showTab(tabId: string | null): void;\n}\n\n/**\n * The rules that span the board's parts (A-04), each under its own name and\n * in one place, rather than among the one-line forwards of `BoardCommands`:\n * what building lets through and what it holds, whose refresh interval is\n * in force, a filter's default that is also what it holds, what a host\n * holding a filter does to the panels' clicks, and what a board opens on.\n */\nexport class BoardRules {\n /** Whether the board refreshes itself on its interval (`setAutoRefresh`). */\n private autoRefresh = true;\n /** What the board refused of the filters it opened on (`opensOn`). */\n private openingRefusal: Issue[] = NO_REFUSAL;\n\n constructor(private readonly host: BoardRulesHost) {}\n\n /**\n * Whether an edit is taken: only while the board is built, so a gesture\n * that outlived the building — a view picked, then 「取消」 while it still\n * loaded — does nothing to the board read after it (Q-02).\n */\n building(): boolean {\n return !this.host.disposed() && this.host.snapshot().building;\n }\n\n /**\n * Building holds the timer (D26 Q39: the author's panels are not re-run\n * under them) and lets go of the reader's own interval — what is chosen\n * while building is the board's (Q35). Ending it arms the timer again,\n * refuses every edit from then on and forgets the history: there is no\n * building left to take a step of back.\n */\n setBuilding(active: boolean): void {\n if (this.host.disposed() || this.host.snapshot().building === active)\n return;\n this.host.patch(\n active\n ? { building: true, readerRefresh: null }\n : { building: false, history: this.host.edits.forget() },\n );\n }\n\n setAutoRefresh(on: boolean): void {\n if (this.host.disposed() || this.autoRefresh === on) return;\n this.autoRefresh = on;\n this.host.retime();\n }\n\n /**\n * Whether the board's timer waits for a reason of the board's own: the\n * host turned it off, or the board is being built. A panel's request in\n * flight is the runtime's to add.\n */\n holdsTimer(): boolean {\n return !this.autoRefresh || this.host.snapshot().building;\n }\n\n /** The interval the timer keeps: the reader's own over the board's. */\n intervalInForce(): number | null {\n const { readerRefresh, applied } = this.host.snapshot();\n return refreshIntervalOf(\n readerRefresh ? { refresh: readerRefresh } : applied,\n );\n }\n\n /**\n * The board's own interval while it is built — edited and applied, as\n * any view's is, so the timer reads it and a save writes it — and the\n * reader's for this opening while it is read, beside the draft (D26 Q35).\n */\n setRefreshInterval(interval: number | null): void {\n if (this.host.disposed()) return;\n if (this.host.snapshot().building) {\n this.host.edit({ refresh: { interval } });\n this.host.apply();\n return;\n }\n const { minRefreshInterval: min, maxRefreshInterval: max } =\n this.host.limits;\n if (\n interval !== null &&\n !(Number.isInteger(interval) && interval >= min && interval <= max)\n )\n return;\n this.host.patch({ readerRefresh: { interval } });\n }\n\n /**\n * What a filter starts at is also what it holds from then on: the author\n * setting a default sees the board under it (D22 G). A default refused\n * with the building sets nothing either.\n */\n setFilterDefault(name: string, value: FilterValue | null): void {\n if (!this.building()) return;\n this.host.edits.setFilterDefault(name, value);\n this.host.values.set(name, value);\n }\n\n /**\n * A default taken back or made again is what its filter holds from then\n * on, as setting it was (D22 G).\n */\n followed(step: EditStep | null): EditStep | null {\n if (step?.command === 'setFilterDefault' && step.subject !== null)\n this.host.values.set(\n step.subject,\n this.host.edits.defaultOf(step.subject),\n );\n return step;\n }\n\n /**\n * A click that sets a filter the host now holds is set aside, and one let\n * go is in force again: the panels' clicks are read again.\n */\n holdFilters(held: HeldFilters | null): Issue[] {\n if (this.host.disposed()) return [];\n const { refused, moved } = this.host.values.hold(held);\n if (moved) this.host.reread();\n return refused;\n }\n\n /**\n * Where a board opens, and what its filters hold as it does\n * (`ViewEngine.open`: a host's address says both); what it refused of\n * them is kept (`refusedFilters`).\n */\n opensOn(\n tab: string | null,\n filters?: DashboardFilters | null,\n held?: HeldFilters | null,\n ): void {\n if (tab !== null) this.host.showTab(tab);\n const taken = filters && !this.host.disposed();\n const refused = [\n ...(taken ? this.host.values.take(filters) : []),\n ...(held ? this.holdFilters(held) : []),\n ];\n if (refused.length > 0) this.openingRefusal = refused;\n }\n\n /** See `DashboardRuntime.refusedFilters`. */\n get refusedFilters(): Issue[] {\n return this.openingRefusal;\n }\n}\n\n/**\n * The board's commands as methods of the runtime that holds it, each one\n * call on one of its parts — its edits (`boardEditing`), what its filters\n * hold (`FilterValues`), a press (`PanelPresses`) or a rule that spans them\n * (`BoardRules`) — or one patch of its snapshot, so the forwarding lives\n * beside the parts rather than in the runtime, and decides nothing.\n */\nexport abstract class BoardCommands\n implements DashboardEditing, DashboardFilterEditing\n{\n /** See `ManagedViewRuntime.stored`: the board without its derived time wires (D1). */\n stored(config: DashboardViewConfig): DashboardViewConfig {\n return storedTimeWires(config);\n }\n\n protected abstract readonly edits: BoardEdits;\n protected abstract readonly values: FilterValues;\n protected abstract readonly presses: PanelPresses;\n protected abstract readonly rules: BoardRules;\n abstract get disposed(): boolean;\n abstract getSnapshot(): DashboardRuntimeState;\n /** Patches the snapshot and re-times the board (`RuntimeStore.setState`). */\n protected abstract patch(state: Partial<DashboardRuntimeState>): void;\n\n /**\n * The preference is the user's and is kept like any other; what it may run\n * is the model's to say, and it declares no dashboard member that runs on\n * its own (`autoRunMembers`), so the switch arms nothing here.\n */\n setAutoApply(on: boolean): void {\n if (this.disposed || this.getSnapshot().autoApply === on) return;\n this.patch({ autoApply: on });\n }\n setEditing(active: boolean): void {\n if (this.disposed || this.getSnapshot().editing === active) return;\n this.patch({ editing: active });\n }\n\n // The rules that span the parts: see `BoardRules`.\n setBuilding(active: boolean): void {\n this.rules.setBuilding(active);\n }\n setAutoRefresh(on: boolean): void {\n this.rules.setAutoRefresh(on);\n }\n setRefreshInterval(interval: number | null): void {\n this.rules.setRefreshInterval(interval);\n }\n setFilterDefault(name: string, value: FilterValue | null): void {\n this.rules.setFilterDefault(name, value);\n }\n undo(): EditStep | null {\n return this.rules.followed(this.edits.undo());\n }\n redo(): EditStep | null {\n return this.rules.followed(this.edits.redo());\n }\n holdFilters(held: HeldFilters | null): Issue[] {\n return this.rules.holdFilters(held);\n }\n opensOn(\n tab: string | null,\n filters?: DashboardFilters | null,\n held?: HeldFilters | null,\n ): void {\n this.rules.opensOn(tab, filters, held);\n }\n /** See `DashboardRuntime.refusedFilters`. */\n get refusedFilters(): Issue[] {\n return this.rules.refusedFilters;\n }\n\n // Building the board (D22 A–E): see `boardEditing`.\n addPanel(panel: NewPanel, placement?: NewPanelPlacement): string | null {\n return this.edits.addPanel(panel, placement);\n }\n removePanel(panelId: string): void {\n this.edits.removePanel(panelId);\n }\n duplicatePanel(panelId: string): string | null {\n return this.edits.duplicatePanel(panelId);\n }\n renamePanel(panelId: string, title: string): void {\n this.edits.renamePanel(panelId, title);\n }\n replacePanelView(panelId: string, instanceId: string): void {\n this.edits.replacePanelView(panelId, instanceId);\n }\n editPanelContent(panelId: string, patch: Partial<NewContentPanel>): void {\n this.edits.editPanelContent(panelId, patch);\n }\n movePanelToTab(panelId: string, tabId: string): void {\n this.edits.movePanelToTab(panelId, tabId);\n }\n setPresentation(panelId: string, look: PanelPresentation | null): void {\n this.edits.setPresentation(panelId, look);\n }\n referToSaved(panelId: string, instance: ViewInstance): void {\n this.edits.referToSaved(panelId, instance);\n }\n setPanelClick(panelId: string, click: PanelClick | null): void {\n this.edits.setPanelClick(panelId, click);\n }\n addTab(title: string, firstTitle: string): string | null {\n return this.edits.addTab(title, firstTitle);\n }\n renameTab(tabId: string, title: string): void {\n this.edits.renameTab(tabId, title);\n }\n moveTab(tabId: string, index: number): void {\n this.edits.moveTab(tabId, index);\n }\n removeTab(tabId: string): void {\n this.edits.removeTab(tabId);\n }\n addFilter(filter: NewFilter): string | null {\n return this.edits.addFilter(filter);\n }\n renameFilter(name: string, label: string): void {\n this.edits.renameFilter(name, label);\n }\n retypeFilter(name: string, type: DashboardFilterType): void {\n this.edits.retypeFilter(name, type);\n }\n removeFilter(name: string): void {\n this.edits.removeFilter(name);\n }\n setFilterRequired(name: string, required: boolean): void {\n this.edits.setFilterRequired(name, required);\n }\n setFilterMultiple(name: string, multiple: boolean): void {\n this.edits.setFilterMultiple(name, multiple);\n }\n setFilterOneDay(name: string, oneDay: boolean): void {\n this.edits.setFilterOneDay(name, oneDay);\n }\n setFilterOptions(name: string, options: FieldOption[] | null): void {\n this.edits.setFilterOptions(name, options);\n }\n moveFilter(name: string, index: number): void {\n this.edits.moveFilter(name, index);\n }\n bindPanel(name: string, panelId: string, panelField: string): string[] {\n return this.edits.bindPanel(name, panelId, panelField);\n }\n unbindPanels(\n name: string,\n panelIds: readonly string[],\n options?: { byHand?: boolean },\n ): void {\n this.edits.unbindPanels(name, panelIds, options);\n }\n setTimeGrouping(grouping: DashboardTimeGrouping | null): void {\n this.edits.setTimeGrouping(grouping);\n }\n removeFixedScope(): void {\n this.edits.removeFixedScope();\n }\n place(\n panelId: string,\n layout: PanelLayout,\n grown?: ReadonlyMap<string, number>,\n ): void {\n this.edits.place(panelId, layout, grown);\n }\n reorderPanel(panelId: string, to: number): void {\n this.edits.reorderPanel(panelId, to);\n }\n setWidth(width: DashboardWidth): void {\n this.edits.setWidth(width);\n }\n\n // What the filters hold (D22 F): see `FilterValues`.\n setFilterValue(name: string, value: FilterValue | null): Issue[] {\n return this.disposed ? [] : this.values.set(name, value);\n }\n setGroupingUnit(unit: AnalysisDateUnit): void {\n if (!this.disposed) this.values.unit(unit);\n }\n clearFilters(): void {\n if (!this.disposed) this.values.clear();\n }\n setFilters(filters: DashboardFilters): Issue[] {\n return this.disposed ? [] : this.values.take(filters);\n }\n wiredOptions(name: string): FieldOption[] | null {\n return this.values.optionsOf(name);\n }\n\n // A press on a panel's group (D22 I): see `PanelPresses`.\n crossFilter(panelId: string, row: RecordData): CrossFilterOutcome {\n return this.disposed\n ? { kind: 'none' }\n : this.presses.crossFilter(panelId, row);\n }\n pressed(panelId: string, row: RecordData): boolean {\n return this.presses.pressed(panelId, row);\n }\n spanFilters(panelId: string): DashboardField[] {\n return this.disposed ? [] : this.presses.spanFilters(panelId);\n }\n pressSpan(\n panelId: string,\n name: string,\n row: RecordData,\n through: RecordData,\n ): CrossFilterOutcome {\n return this.disposed\n ? { kind: 'none' }\n : this.presses.pressSpan(panelId, name, row, through);\n }\n destination(\n panelId: string,\n row: RecordData,\n ): Promise<PressDestination | null> {\n return this.presses.destination(panelId, row);\n }\n destinationBoard(instanceId: string): Promise<DestinationBoard | null> {\n return this.presses.board(instanceId);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n type DataViewConfig,\n presentationMembers,\n type DataViewDefinition,\n type FilterTree,\n type Issue,\n type ViewInstance,\n type ViewScope,\n} from '../../model/index.js';\nimport { isPlainObject } from '../../filter/index.js';\nimport type {\n DataPanelSource,\n PanelDefinition,\n PanelReference,\n} from '../../dashboard/index.js';\nimport type { DataViewRuntime } from '../viewRuntime.js';\nimport { hasError } from '../runtimeStore.js';\nimport { atPanel, panelIssues } from './panels.js';\n\n/**\n * What one data panel runs: the view it shows — a saved one, or one the\n * board owns — and the config its child is handed, which is the view's own\n * with the panel's override of how it looks laid over it.\n */\nexport interface PanelView {\n /** The saved view, the child's baseline; `null` for a view the board owns. */\n instance: ViewInstance | null;\n definition: DataViewDefinition;\n config: DataViewConfig;\n /** The view's title, or the panel's for an owned view. */\n title: string;\n /** Who reads the view: the saved view's audience, or the board's own. */\n scope: ViewScope;\n}\n\n/**\n * The view a data panel shows, once there is one to run: the saved view its\n * reference loaded, or the one it owns, judged by the definition this\n * release declares for it. `null` while a reference is loading, and for one\n * admission has already said cannot run. An owned view has no title of its\n * own — the panel's is its name — and is read by the board's audience.\n */\nexport function panelView(\n panel: DataPanelSource,\n reference: (instanceId: string) => PanelReference | null | undefined,\n definitions: (definitionId: string) => PanelDefinition | null,\n board: ViewScope,\n): PanelView | null {\n const owned: unknown = panel.owned;\n if (owned !== undefined) {\n if (!isPlainObject(owned) || typeof owned.definitionId !== 'string')\n return null;\n const found = definitions(owned.definitionId);\n if (found?.definition.kind !== 'data') return null;\n return {\n instance: null,\n definition: found.definition,\n config: owned.config as DataViewConfig,\n title: panel.title ?? '',\n scope: board,\n };\n }\n const loaded =\n typeof panel.instanceId === 'string' ? reference(panel.instanceId) : null;\n if (loaded?.definition.kind !== 'data') return null;\n const { instance, definition } = loaded;\n return {\n instance,\n definition,\n config: instance.config as DataViewConfig,\n title: instance.title,\n scope: instance.scope,\n };\n}\n\n/** Builds the child runtime of one data panel, with its scope already in force. */\nexport type PanelRuntimeFactory = (\n view: PanelView,\n scopeFilter: FilterTree | null,\n) => DataViewRuntime;\n\n/**\n * A child runtime, the subscription that watches it, and what the last sync\n * knew about its panel — its index in the config and the dashboard's own\n * findings about it — so the panel's issues can be rebuilt when the child\n * alone changes.\n */\nexport interface PanelChild {\n runtime: DataViewRuntime;\n /** The view it was built for, and the config it was last handed. */\n view: PanelView;\n unsubscribe: () => void;\n /** The panel's index in the config, where its issues are addressed. */\n index: number;\n /** The dashboard's own findings about the panel, as of the last sync. */\n own: Issue[];\n /**\n * A refresh of the board went by while the panel was on a tab not shown\n * (`PanelChildren.refresh`): its rows are older than the board's, so it\n * is refreshed the next time its tab is shown.\n */\n missed: boolean;\n}\n\n/**\n * The child runtimes of a dashboard's data panels, by panel id, and their\n * lifecycle: brought in line with a panel and its scope on every sync, let\n * go when the panel goes or points elsewhere, disposed with the dashboard.\n *\n * A child admits the scope it is handed like any condition, and a refusal is\n * the panel's problem: the child stops rather than running its previous\n * scope, and the reasons land in the panel's issues where the dashboard's\n * own would. The dashboard is told when a child notifies — its timer waits\n * on its panels, and a panel's issues follow its child — and subscribes to\n * nothing else here; the UI watches each child itself.\n */\nexport class PanelChildren {\n private readonly children = new Map<string, PanelChild>();\n\n constructor(\n private readonly create: PanelRuntimeFactory,\n /** Called whenever a child notifies, with the panel it belongs to. */\n private readonly notified: (panelId: string) => void,\n ) {}\n\n get(panelId: string): PanelChild | undefined {\n return this.children.get(panelId);\n }\n\n /** The child runtime of one panel, for a host that drives a panel itself. */\n runtimeOf(panelId: string): DataViewRuntime | null {\n return this.children.get(panelId)?.runtime ?? null;\n }\n\n /**\n * One panel's child for a view that can be run, and what the panel\n * reports: the existing child re-scoped when it still stands for the same\n * view, a new one otherwise.\n *\n * The same view with another config — the panel's override changed, or\n * the question a board owns was edited — is handed to the child as an\n * edit and run, rather than a new child: the rows on screen stay until the\n * new ones land, instead of the panel blanking to a skeleton for a change\n * of chart. A config the child now refuses stops it, as a refused scope\n * does.\n *\n * A change of how the rows are drawn alone — the layout, the chart\n * (`presentationMembers`) — is an edit and nothing more: presentation\n * never asks the source (D20), and the panel draws the child's draft over\n * the rows it has (`useAnalysisResult`). A child that missed a refresh\n * while its tab was away is refreshed here, unless what changed runs it\n * anyway.\n */\n sync(\n panelId: string,\n index: number,\n own: Issue[],\n view: PanelView,\n scope: FilterTree | null,\n ): { runtime: DataViewRuntime | null; issues: Issue[] } {\n const existing = this.children.get(panelId);\n if (existing && sameView(existing.view, view)) {\n // Before the scope goes in: the child may notify on the spot, and the\n // refresh that answers it reads these.\n existing.index = index;\n existing.own = own;\n const changed = !dequal(existing.view.config, view.config);\n const asks = changed && !drawsOnly(existing.view.config, view.config);\n if (changed)\n existing.runtime.edit(replacing(existing.view.config, view.config));\n existing.view = view;\n const rescoped = !dequal(existing.runtime.scopeFilter, scope ?? null);\n const refused = changed ? [...existing.runtime.getSnapshot().issues] : [];\n if (!hasError(refused))\n refused.push(...existing.runtime.setScopeFilter(scope));\n if (!hasError(refused)) {\n if (asks) existing.runtime.apply();\n else if (existing.missed && !rescoped) existing.runtime.refresh();\n existing.missed = false;\n return {\n runtime: existing.runtime,\n issues: panelIssues(index, own, existing.runtime),\n };\n }\n this.drop(panelId);\n return { runtime: null, issues: [...own, ...atPanel(index, refused)] };\n }\n // The panel points somewhere else now, or the instance was reloaded.\n if (existing) this.drop(panelId);\n\n const runtime = this.create(view, scope);\n // A scope a panel's definition refuses is no longer among that child's\n // issues — it drops what it cannot carry and runs un-narrowed, which is\n // right for a view a host embedded and wrong for a panel of a board: the\n // dashboard's condition is the question the panel was put there to answer,\n // so a panel that cannot carry it shows nothing and says why.\n const refused = [...runtime.refusedScope, ...runtime.getSnapshot().issues];\n if (hasError(refused)) {\n runtime.dispose();\n return { runtime: null, issues: [...own, ...atPanel(index, refused)] };\n }\n const unsubscribe = runtime.subscribe(() => this.notified(panelId));\n this.children.set(panelId, {\n runtime,\n view,\n unsubscribe,\n index,\n own,\n missed: false,\n });\n runtime.apply();\n return { runtime, issues: panelIssues(index, own, runtime) };\n }\n\n /**\n * A panel on a tab not shown: its child, if it has one, is kept as it is —\n * rows and all, neither re-scoped nor re-run (D22 E: only the tab on\n * screen runs) — and only where its findings are addressed moves with the\n * config. `null` for a panel that has never been shown.\n */\n hold(\n panelId: string,\n index: number,\n own: Issue[],\n ): { runtime: DataViewRuntime; issues: Issue[] } | null {\n const held = this.children.get(panelId);\n if (!held) return null;\n held.index = index;\n held.own = own;\n return {\n runtime: held.runtime,\n issues: panelIssues(index, own, held.runtime),\n };\n }\n\n /** Lets go of the children whose panels are no longer among `live`. */\n keepOnly(live: ReadonlySet<string>): void {\n for (const panelId of [...this.children.keys()])\n if (!live.has(panelId)) this.drop(panelId);\n }\n\n drop(panelId: string): void {\n const child = this.children.get(panelId);\n if (!child) return;\n child.unsubscribe();\n child.runtime.dispose();\n this.children.delete(panelId);\n }\n\n disposeAll(): void {\n for (const child of this.children.values()) {\n child.unsubscribe();\n child.runtime.dispose();\n }\n this.children.clear();\n }\n\n /**\n * Re-runs every child on the tab shown on what it has applied; the others\n * are marked to run when their tab is shown again (`sync`). A child\n * `skip` names is left as it is.\n */\n refresh(\n shown: (panelId: string) => boolean = () => true,\n skip: (runtime: DataViewRuntime) => boolean = () => false,\n ): void {\n for (const [panelId, child] of this.children)\n if (skip(child.runtime)) continue;\n else if (shown(panelId)) child.runtime.refresh();\n else child.missed = true;\n }\n\n /**\n * The soonest moment a child on the tab shown stops being true of its own\n * accord (`DataViewRuntime.rolloverAt`) — a metric card whose period has\n * ended — or `null`. The board asks again then, as it refreshes: every\n * panel on screen on one clock.\n */\n rolloverAt(shown: (panelId: string) => boolean): number | null {\n let soonest: number | null = null;\n for (const [panelId, child] of this.children) {\n if (!shown(panelId)) continue;\n const at = child.runtime.rolloverAt();\n if (at !== null && (soonest === null || at < soonest)) soonest = at;\n }\n return soonest;\n }\n\n /** Whether any child has a query in flight. */\n loading(): boolean {\n for (const child of this.children.values())\n if (child.runtime.getSnapshot().query.status === 'loading') return true;\n return false;\n }\n}\n\n/**\n * An edit that turns one config into another: every member of the next,\n * and every member only the previous one has taken off — an edit is a\n * patch, and a member it leaves out would otherwise stay.\n */\nfunction replacing(\n previous: DataViewConfig,\n next: DataViewConfig,\n): Partial<DataViewConfig> {\n const patch: Record<string, unknown> = {};\n for (const key of Object.keys(previous)) patch[key] = undefined;\n return { ...patch, ...next };\n}\n\n/**\n * Whether two configs of one view differ only in how the rows are drawn —\n * the members that never ask the source (`presentationMembers`).\n */\nfunction drawsOnly(previous: DataViewConfig, next: DataViewConfig): boolean {\n const drawn = presentationMembers(next.kind);\n const before: Record<string, unknown> = { ...previous };\n const after: Record<string, unknown> = { ...next };\n const keys = new Set([...Object.keys(before), ...Object.keys(after)]);\n return [...keys].every(\n key => drawn.includes(key) || dequal(before[key], after[key]),\n );\n}\n\n/**\n * Whether a child built for one view still stands for another: the same\n * saved view at the same revision, or a view the board owns of the same\n * definition and kind. Its config may still differ; `sync` hands that over.\n */\nfunction sameView(held: PanelView, next: PanelView): boolean {\n if (held.definition.id !== next.definition.id) return false;\n if (held.config.kind !== next.config.kind) return false;\n if (held.instance === null || next.instance === null)\n return held.instance === next.instance;\n return (\n held.instance.id === next.instance.id &&\n held.instance.revision === next.instance.revision\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n isViewStoreError,\n type DashboardViewConfig,\n type Issue,\n} from '../../model/index.js';\nimport {\n panelsOf,\n referencedInstance,\n type PanelReference,\n} from '../../dashboard/index.js';\nimport { panelFailure, reasonOf } from './panels.js';\nimport { isViewCommandError } from '../write.js';\n\n/** Loads what a panel references; rejects when it is gone or unreadable. */\nexport type PanelResolver = (instanceId: string) => Promise<PanelReference>;\n\n/**\n * The references a dashboard's panels point at, as far as they are known.\n *\n * Three answers per instance id: not asked yet, being loaded, and loaded —\n * where \"loaded\" is a reference or `null` for one that is gone or unreadable.\n * A fourth, kept apart, is a load that failed: a reference that arrived but\n * could not be put to work (its definition names a source the host does not\n * resolve, say), or a read that failed for a reason that may pass — the\n * store unreachable, or answering with an error of its own. Admission cannot\n * see either, so the reason is remembered here and reported against the\n * panel that asked for it (`dashboard.panel.failed`), and `retry` asks again.\n * Only a store's `NOT_FOUND` or `FORBIDDEN` — or another answer that would be\n * the same the next time — says the view is gone (`dashboard.panel.unavailable`).\n *\n * The runtime is told once per settled load — resolved, unreadable, or\n * failed — and re-judges its draft then; what it does with that is its own.\n */\nexport class PanelReferences {\n /** Resolved references by instance id; `null` once known to be unreadable. */\n private readonly references = new Map<string, PanelReference | null>();\n /** Why a resolved reference could not be brought into service, by id. */\n private readonly failures = new Map<string, string>();\n private readonly pending = new Map<string, Promise<void>>();\n\n constructor(\n private readonly resolve: PanelResolver,\n /** Called after each load settles, however it settled. */\n private readonly settled: () => void,\n ) {}\n\n /** What admission validates the panels against. */\n get known(): ReadonlyMap<string, PanelReference | null> {\n return this.references;\n }\n\n /** True while a reference is still being loaded. */\n get resolving(): boolean {\n return this.pending.size > 0;\n }\n\n /** The reference for an id, `null` for an unreadable one, `undefined` for one not loaded yet. */\n get(instanceId: string): PanelReference | null | undefined {\n return this.references.get(instanceId);\n }\n\n /** Why the reference could not be put to work, if it could not. */\n failure(instanceId: string): string | undefined {\n return this.failures.get(instanceId);\n }\n\n /**\n * Starts loading the references a config needs and does not have yet, and\n * says whether it started any.\n *\n * `awaited` says whether anyone is waiting on the outcome. `ready()` waits\n * on what the constructor starts, so a load that cannot be brought into\n * service at all refuses the opening. A load `edit` or `adoptSaved` starts\n * has no such caller: letting it reject would leave an unhandled rejection\n * and no trace on screen, so its failure becomes this panel's issue.\n */\n load(config: DashboardViewConfig, awaited: boolean): boolean {\n const wanted = new Set(\n panelsOf(config)\n .map(referencedInstance)\n .filter(\n (id): id is string =>\n id !== undefined &&\n !this.references.has(id) &&\n !this.pending.has(id),\n ),\n );\n if (wanted.size === 0) return false;\n for (const id of wanted) void this.start(id, awaited);\n return true;\n }\n\n /**\n * Loads one saved view before any panel points at it — the one a board is\n * about to add, so the panel starts at the size of what it shows — and\n * resolves once it has settled, however it settled; `null` when it is\n * already known or on its way, and there is nothing to start.\n */\n fetch(instanceId: string): Promise<void> | null {\n if (this.references.has(instanceId)) return null;\n const pending = this.pending.get(instanceId);\n if (pending) return pending.catch(() => undefined);\n return this.start(instanceId, false);\n }\n\n /**\n * Asks again for every reference whose load failed (`failure`), and says\n * whether there was one: a board's refresh, which a reader presses\n * because something on it looks wrong.\n */\n retryFailed(): boolean {\n const failed = [...this.failures.keys()];\n for (const id of failed) this.retry(id);\n return failed.length > 0;\n }\n\n /**\n * Asks again for one reference whose load failed, forgetting the failure\n * first; `false` when it had not failed, and there is nothing to ask.\n */\n retry(instanceId: string | undefined): boolean {\n if (\n instanceId === undefined ||\n !this.failures.has(instanceId) ||\n this.pending.has(instanceId)\n )\n return false;\n this.failures.delete(instanceId);\n this.references.delete(instanceId);\n void this.start(instanceId, false);\n return true;\n }\n\n /**\n * A finding of admission as the reader should hear it: a view the kernel\n * finds missing (`dashboard.panel.unavailable`) because its read failed —\n * not because the store said it is gone — is that failure\n * (`dashboard.panel.failed`). A reader told the view was deleted, or not\n * shared, would go and ask its owner for nothing.\n */\n restate(found: Issue): Issue {\n const [, index] = found.path;\n const instance = found.params?.instance;\n if (\n found.code !== 'dashboard.panel.unavailable' ||\n typeof index !== 'number' ||\n typeof instance !== 'string'\n )\n return found;\n const failure = this.failures.get(instance);\n return failure === undefined\n ? found\n : panelFailure(index, instance, failure);\n }\n\n private start(id: string, awaited: boolean): Promise<void> {\n // A rejection is an answer too. The instance was deleted, or this user\n // may not read it: only that one panel is affected, and asking again\n // would answer the same. Anything else may pass, and is a failure the\n // panel offers to try again.\n const loading = this.resolve(id).then(\n reference => this.resolved(id, reference),\n (error: unknown) =>\n gone(error)\n ? this.resolved(id, null)\n : this.unreadable(id, reasonOf(error)),\n );\n const settled = awaited\n ? loading\n : loading.catch(error => this.failed(id, error));\n this.pending.set(id, settled);\n return settled;\n }\n\n /**\n * Resolves once every reference the current config needs has been loaded or\n * found unreadable. A reference that arrives may add panels of its own to\n * load, so this drains rather than awaiting one round.\n */\n async ready(): Promise<void> {\n while (this.pending.size > 0) await Promise.all([...this.pending.values()]);\n }\n\n /**\n * A reference known without asking the store — the view a board has just\n * saved one of its own views as — so the panel pointing at it does not\n * blank while it is read back.\n */\n seed(reference: PanelReference): void {\n this.references.set(reference.instance.id, reference);\n this.failures.delete(reference.instance.id);\n }\n\n private resolved(id: string, reference: PanelReference | null): void {\n this.pending.delete(id);\n this.references.set(id, reference);\n this.settled();\n }\n\n private failed(id: string, error: unknown): void {\n this.failures.set(id, reasonOf(error));\n this.settled();\n }\n\n /** A read that failed for a reason that may pass; see `gone`. */\n private unreadable(id: string, reason: string): void {\n this.pending.delete(id);\n this.references.set(id, null);\n this.failures.set(id, reason);\n this.settled();\n }\n}\n\n/**\n * Whether a failed read says the view is not there for this reader — the\n * store's `NOT_FOUND` or `FORBIDDEN`, or another answer it would give again\n * (`INVALID`, `UNSUPPORTED`), or the engine's own refusal (a definition this\n * release does not declare) — rather than that it could not be read just\n * now: the store `UNAVAILABLE`, or a failure nobody named.\n */\nfunction gone(error: unknown): boolean {\n if (isViewStoreError(error)) return error.code !== 'UNAVAILABLE';\n return isViewCommandError(error);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DashboardViewConfig,\n Issue,\n ViewInstance,\n ViewScope,\n} from '../../model/index.js';\nimport type { FieldKindRegistry } from '../../filter/index.js';\nimport { admitFilters } from '../../dashboard/index.js';\nimport type { ViewQueryState } from '../viewRuntimeTypes.js';\nimport type { DashboardRuntimeState } from './contract.js';\nimport { NO_HISTORY } from './history.js';\nimport { shownTab } from './panels.js';\n\nconst IDLE: ViewQueryState = { status: 'idle' };\n\n/**\n * A board's state as it opens: the config as draft and applied alike, its\n * first tab, its filters at their defaults, nothing asked yet, nothing being\n * built — and dirty only when it was never saved.\n */\nexport function openingState(opening: {\n saved: ViewInstance | null;\n title: string;\n scope: ViewScope;\n config: DashboardViewConfig;\n issues: Issue[];\n kinds: FieldKindRegistry;\n}): DashboardRuntimeState {\n const { saved, title, scope, config, issues, kinds } = opening;\n return {\n saved,\n title,\n scope,\n draft: config,\n applied: config,\n issues,\n dirty: saved === null,\n query: IDLE,\n result: null,\n selection: [],\n write: null,\n editing: false,\n autoApply: false,\n nextRefreshAt: null,\n panels: [],\n resolving: false,\n tab: shownTab(config, null),\n filters: admitFilters(config, null, kinds).filters,\n history: NO_HISTORY,\n building: false,\n readerRefresh: null,\n filtersRun: 0,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n overlaid,\n type DashboardDefinition,\n type DashboardFilters,\n type DashboardViewConfig,\n type DashboardViewPanel,\n type FieldDefinition,\n type FilterTree,\n type Issue,\n type RuntimeLimits,\n type ViewInstance,\n type ViewScope,\n} from '../model/index.js';\nimport { issue, type FieldKindRegistry } from '../filter/index.js';\nimport {\n filtersOf,\n referencedInstance,\n type DataPanelSource,\n type PanelTime,\n} from '../dashboard/index.js';\nimport { boardFieldsOf } from '../dashboard/boardFields.js';\nimport {\n canonicalBoard,\n canonicalSaved,\n canonicalState,\n panelTime,\n type BoardReading,\n} from './dashboard/canonical.js';\nimport { boardHandOver, boardPanels, panelRun } from './dashboard/panelRun.js';\nimport type { PanelAnchor } from './dashboard/anchor.js';\nimport { isForbiddenQuery } from './queryFailure.js';\nimport { FilterValues } from './dashboard/filterValues.js';\nimport { PanelPresses } from './dashboard/press.js';\nimport { boardEditing, type BoardEdits } from './dashboard/editing.js';\nimport { BoardCommands, BoardRules } from './dashboard/commands.js';\nimport { outsideHistory, type EditHistoryState } from './dashboard/history.js';\nimport type { ValueCandidateSource } from './valueCandidates.js';\nimport type { RuntimeEnvironment } from './environment.js';\nimport { hasError, RuntimeStore } from './runtimeStore.js';\nimport type { OptionSource } from './source.js';\nimport {\n PanelChildren,\n panelView,\n type PanelView,\n} from './dashboard/children.js';\nimport {\n blocksBoard,\n panelFailure,\n reissued,\n samePanels,\n shownTab,\n} from './dashboard/panels.js';\nimport { PanelReferences } from './dashboard/references.js';\nimport { openingState } from './dashboard/opening.js';\nimport { admitBoard } from './dashboard/owned.js';\nimport type { WriteState } from './write.js';\nimport type { DataViewRuntime } from './viewRuntime.js';\nimport type { ManagedViewRuntime } from './viewRuntimeTypes.js';\nimport type { HandOver } from './navigation.js';\n\nexport type { PanelResolver } from './dashboard/references.js';\nexport type { PanelRuntimeFactory, PanelView } from './dashboard/children.js';\nexport type { DashboardPanelState } from './dashboard/panels.js';\nexport { blocksBoard, boardFindings, stopsSave } from './dashboard/panels.js';\nexport type {\n DashboardEditing,\n DashboardFilterEditing,\n} from './dashboard/editing.js';\nexport type { PanelGrouping } from './dashboard/grouping.js';\nexport type {\n HeldFilters,\n DashboardRuntime,\n DashboardRuntimeOptions,\n DashboardRuntimeState,\n} from './dashboard/contract.js';\nexport type {\n CrossFilterOutcome,\n DestinationBoard,\n PressDestination,\n} from './dashboard/press.js';\nimport type {\n DashboardRuntimeOptions,\n DashboardRuntimeState,\n} from './dashboard/contract.js';\n\n/**\n * The runtime of a dashboard: N child runtimes and the board's filters.\n *\n * What it adds over a data view is composition, and its rules follow from\n * that. The board's filters reach a panel as an injected scope, so the\n * referenced view never becomes dirty and a dashboard's condition is never\n * saved back into it. Every panel keeps its own loading, error and result,\n * because one slow or broken panel must not decide what the others show. And\n * the timer lives here rather than in the children: a referenced view's own\n * refresh interval is ignored inside a dashboard, so there is one clock.\n *\n * The store half of it — the snapshot, the subscribers, that one timer and\n * dirty-against-saved — is the `RuntimeStore` a data view holds as well; what\n * is left here is composition.\n */\nexport class DashboardViewRuntime\n extends BoardCommands\n implements ManagedViewRuntime<DashboardViewConfig>\n{\n readonly id: string;\n readonly kind = 'dashboard' as const;\n readonly definition: DashboardDefinition;\n readonly kinds: FieldKindRegistry;\n readonly limits: RuntimeLimits;\n readonly environment: RuntimeEnvironment;\n\n private readonly store: RuntimeStore<DashboardRuntimeState>;\n private readonly options: DashboardRuntimeOptions;\n /** What the panels point at, as far as it is known; see `PanelReferences`. */\n private readonly references: PanelReferences;\n /** The child runtime of each data panel that runs; see `PanelChildren`. */\n private readonly children: PanelChildren;\n /** Building the board; see `runtime/dashboard/editing.ts`. */\n protected readonly edits: BoardEdits;\n /** What the board's filters hold; see `FilterValues`. */\n protected readonly values: FilterValues;\n /** A press on a panel's group; see `PanelPresses`. */\n protected readonly presses: PanelPresses;\n /** The rules that span the parts above; see `BoardRules`. */\n protected readonly rules: BoardRules;\n\n /** The tab the reader asked for; see `DashboardRuntimeState.tab`. */\n private requestedTab: string | null = null;\n /** Whether the panels were brought in line once: until then a tab is only noted. */\n private synced = false;\n /** The filters the last sync sent the panels; see `filtersRun`. */\n private filtersOut: DashboardFilters | null = null;\n /** The window each anchored trend card ran under at the last sync (D39). */\n private readonly anchors = new Map<string, PanelAnchor>();\n /** The board under the paths its panels rename aliases to. */\n private readonly canonical: BoardReading;\n /** What each panel's view says of time (`panelTime`). */\n private readonly timeOf: PanelTime = panelTime(panel => this.viewOf(panel));\n\n constructor(options: DashboardRuntimeOptions) {\n super();\n this.options = options;\n this.id = options.id;\n this.definition = options.definition;\n this.kinds = options.kinds;\n this.limits = options.limits;\n this.environment = options.environment;\n // Both talk back only through the runtime's own re-sync: a reference\n // settling re-judges the draft, and a child notifying re-times the board\n // and rebuilds its panel's issues.\n this.references = new PanelReferences(options.resolve, () =>\n this.settled(),\n );\n this.canonical = canonicalBoard(panel => this.viewOf(panel));\n this.children = new PanelChildren(options.createPanelRuntime, panelId => {\n this.store.retime();\n this.refreshPanelIssues(panelId);\n });\n this.edits = boardEditing({\n building: () => this.rules.building(),\n draft: () => (this.disposed ? null : this.state.draft),\n maxPanels: options.limits.maxDashboardPanels,\n viewConfig: id => this.references.get(id)?.instance.config,\n seed: instance => {\n const found = options.definitions(instance.definitionId);\n if (found) this.references.seed({ ...found, instance });\n },\n timeOf: panel => this.timeOf(panel),\n fieldsOf: panel => {\n const view = this.viewOf(panel);\n return view\n ? boardFieldsOf(view.config.kind, view.definition.fields)\n : null;\n },\n applied: () => (this.disposed ? null : this.state.applied),\n commit: (draft, applied, history) => this.commit(draft, applied, history),\n });\n this.values = new FilterValues({\n kinds: options.kinds,\n environment: options.environment,\n candidateSources: options.candidateSources,\n applied: () => this.state.applied,\n current: () => this.state.filters,\n commit: filters => this.store.setState({ filters }),\n started: () => this.synced,\n run: () => this.sync({ filtersRun: this.state.filtersRun + 1 }),\n viewOf: panel => this.viewOf(panel),\n });\n this.presses = new PanelPresses({\n kinds: options.kinds,\n applied: () => this.state.applied,\n filters: () => this.state.filters,\n child: panelId => this.panelRuntime(panelId),\n press: (name, value, panelId) => this.values.press(name, value, panelId),\n held: name => this.values.holds(name),\n panel: panelId =>\n this.state.panels.find(entry => entry.id === panelId) ?? null,\n handOver: panelId => this.handOver(panelId),\n reference: async id => {\n await this.references.fetch(id);\n return this.references.get(id) ?? null;\n },\n });\n this.rules = new BoardRules({\n limits: options.limits,\n edits: this.edits,\n values: this.values,\n disposed: () => this.disposed,\n snapshot: () => this.state,\n patch: state => this.store.setState(state),\n retime: () => this.store.retime(),\n reread: () => {\n if (this.synced) this.sync();\n },\n edit: patch => this.edit(patch),\n apply: () => this.apply(),\n showTab: tab => this.showTab(tab),\n });\n\n // A stored board was read into the form this engine writes on its way\n // out of the store (`readStored`), the baseline with the config, so it\n // opens clean rather than dirty with its own migration (D22 E, D26 Q31).\n // And it is read under the paths its panels' definitions rename\n // aliases to, the baseline with it, as far as they are known yet: an\n // owned view's now, a referenced one's once it loads (`settled`).\n const saved = canonicalSaved(options.saved ?? null, this.canonical);\n const config = this.canonical(options.config);\n this.store = new RuntimeStore<DashboardRuntimeState>({\n state: openingState({\n saved,\n title: options.title,\n scope: options.scope,\n config,\n issues: this.admit(config, options.scope),\n kinds: options.kinds,\n }),\n environment: options.environment,\n admit: draft => this.admit(draft, this.state.scope),\n // A panel's own error stops that panel, not the board's timer.\n blocking: blocksBoard,\n apply: () => this.apply(),\n // The board's clock asks again of every panel but one whose source\n // refused the reader: that would only be refused again, and told to\n // the host each time. A press of refresh still asks it.\n refresh: () => this.rerun(refusedTheReader),\n // One clock for the whole board, so a request in flight is any panel's;\n // and it keeps the reader's own interval over the board's (D26 Q35).\n holding: () => this.rules.holdsTimer() || this.children.loading(),\n interval: () => this.rules.intervalInForce(),\n // And one moment a card on the tab shown moves on, the soonest.\n expiresAt: () => this.children.rolloverAt(this.onTab()),\n release: () => {\n this.values.stop();\n this.children.disposeAll();\n },\n // A restored draft may name panels this opening has not resolved yet,\n // so it goes through `load` exactly as an edit does.\n restored: draft => this.load(draft),\n });\n this.load(config, true);\n }\n\n get disposed(): boolean {\n return this.store.disposed;\n }\n\n /** See `ViewRuntime.refusedScope`; the store keeps it. */\n get refusedScope(): Issue[] {\n return this.store.refusedScope;\n }\n\n /** The snapshot the store holds; every command reads it and patches it back. */\n private get state(): DashboardRuntimeState {\n return this.store.state;\n }\n\n /**\n * A dashboard declares its own filters; there is no definition to ask.\n * Only the well-formed entries: a stored `fields` may hold something that\n * is no field, which admission reports, and an editor mapping fields by\n * name must not be the second place to find out.\n */\n get fields(): readonly FieldDefinition[] {\n return filtersOf(this.state.draft);\n }\n\n /**\n * Always `null`: a board takes no outer condition (D26 Q32). A host\n * narrows one filter by filter, through what it holds (`holdFilters`).\n */\n get scopeFilter(): FilterTree | null {\n return null;\n }\n\n getSnapshot(): DashboardRuntimeState {\n return this.store.getSnapshot();\n }\n\n subscribe(listener: () => void): () => void {\n return this.store.subscribe(listener);\n }\n\n optionSource(remote: string): OptionSource | null {\n const resolve = this.options.resolveOptions;\n return resolve ? resolve(remote) : null;\n }\n\n /** What a text filter offers to pick from; see `FilterValues.candidatesOf`. */\n valueCandidates(name: string): ValueCandidateSource | null {\n return this.values.candidatesOf(name);\n }\n\n /**\n * Resolves once every reference the current config needs has been loaded or\n * found unreadable, so `open` can hand back a dashboard that is ready to\n * run rather than one that fills in a moment later.\n */\n async ready(): Promise<void> {\n await this.references.ready();\n }\n\n /**\n * The draft with `patch` over it, a member given as `undefined` taken\n * out (`overlaid`), as a data view's is. What building writes — the\n * panels, the tabs, the filters and the time grouping — is not taken\n * here (`outsideHistory`): each is written by its own command, one step\n * of the history, and an undo puts back the whole member a step changed,\n * so a list this changed underneath it would silently be put back too\n * (A-10). The rest — the fixed scope, a refresh interval — is.\n */\n edit(patch: Partial<DashboardViewConfig>): void {\n if (this.disposed) return;\n const draft = overlaid(this.state.draft, outsideHistory(patch));\n this.store.setState({\n draft,\n issues: this.admit(draft, this.state.scope),\n dirty: this.store.isDirty(draft, this.state.saved),\n });\n }\n\n /**\n * Promotes the draft and brings the panels in line with it.\n *\n * Only an error about the board itself refuses it (`blocksBoard`). A\n * panel in error is promoted with the rest and stays out on its own —\n * `sync` runs nothing for it and its issues say why — so one broken panel\n * cannot hold the global filter back from all the others.\n */\n apply(): void {\n if (this.disposed || blocksBoard(this.state.issues)) return;\n // Promotion and the panels that follow from it commit together, so a\n // subscriber is notified once and never sees the two disagree.\n this.sync({ applied: this.state.draft });\n }\n\n /**\n * Discards the edits and re-runs what was saved; see `RuntimeStore.revert`.\n * The history goes with them: there is nothing left to undo.\n */\n revert(): void {\n if (this.disposed) return;\n this.store.revert();\n this.store.setState({ history: this.edits.forget() });\n }\n\n /**\n * One clock for every panel; a referenced view's own interval is ignored.\n *\n * Like a data view's, this re-runs what was applied, so an invalid draft\n * does not block it: the children that exist are the ones `sync` admitted.\n */\n refresh(): void {\n this.rerun();\n }\n\n /** `refresh`, leaving out the panels `skip` names. */\n private rerun(skip?: (panel: DataViewRuntime) => boolean): void {\n if (this.disposed) return;\n // A view a panel could not read just now is asked for again.\n if (this.references.retryFailed()) this.store.setState({ resolving: true });\n // An anchored card's window was read off the clock at the last sync\n // (D39): 「昨日」 read again after midnight is another day, so the board\n // is brought in line first, as every other panel reads its relative\n // dates again when it runs.\n if (this.anchors.size > 0) this.sync();\n this.children.refresh(this.onTab(), skip);\n }\n\n /** Whether a panel is on the tab shown. */\n private onTab(): (panelId: string) => boolean {\n const { panels, tab } = this.state;\n return id => panels.some(panel => panel.id === id && panel.tab === tab);\n }\n\n showTab(tabId: string | null): void {\n if (this.disposed) return;\n this.requestedTab = tabId;\n // Before the first sync this only says where the board opens: nothing\n // has run yet, and the first sync starts on this tab rather than on the\n // first and then here.\n if (!this.synced) {\n this.store.setState({ tab: shownTab(this.state.applied, tabId) });\n return;\n }\n this.sync();\n }\n\n /**\n * One edit to the board, or one step of its history taken back or made\n * again, applied as a placement is: into the draft and into what is on\n * screen alike, and nothing else of either moves — a global filter still\n * being composed stays pending (D22 A: the panels run on the draft as it\n * is built; saving writes it, `revert` undoes it). A panel the edit adds\n * is loaded like any the draft names.\n *\n * A placement is a gesture that lands at once, like sorting a table, but\n * it is not an apply of the whole draft: going through `edit` + `apply`\n * would also run whatever else was waiting — a global filter the user was\n * still composing ran the moment they nudged a panel. So the layout is\n * written into both the draft and the applied config, the panels it\n * pushes with it, and nothing else in either moves.\n */\n private commit(\n edited: DashboardViewConfig,\n shown: DashboardViewConfig,\n history: EditHistoryState,\n ): void {\n // A step taken back may be one written before a reference had loaded.\n const draft = this.canonical(edited);\n const applied = this.canonical(shown);\n this.sync({\n draft,\n applied,\n issues: this.admit(draft, this.state.scope),\n dirty: this.store.isDirty(draft, this.state.saved),\n history,\n });\n this.load(draft);\n }\n\n async preload(instanceId: string): Promise<void> {\n if (this.disposed) return;\n const loading = this.references.fetch(instanceId);\n if (!loading) return;\n this.store.setState({ resolving: true });\n await loading;\n }\n\n /**\n * Re-runs one panel — the retry a panel whose query failed offers. It is\n * the board's refresh narrowed to one child, so a panel that cannot run\n * has nothing to re-run and this does nothing for it.\n */\n refreshPanel(panelId: string): void {\n if (this.disposed) return;\n // A panel whose view could not be read asks for it again: its retry.\n const panel = this.state.panels.find(entry => entry.id === panelId);\n if (this.references.retry(referencedInstance(panel?.panel)))\n this.store.setState({ resolving: true });\n else this.children.runtimeOf(panelId)?.refresh();\n }\n\n protected patch(state: Partial<DashboardRuntimeState>): void {\n this.store.setState(state);\n }\n\n /**\n * Refuses any condition (D26 Q32): a board is narrowed filter by filter,\n * through what the host holds (`holdFilters`), never by a tree it would\n * have to map onto every panel. `null` is what it has, and is taken.\n */\n setScopeFilter(tree: FilterTree | null): Issue[] {\n if (this.disposed) return this.refusedScope;\n return this.store.refuse(\n tree ? [issue('dashboard.scope.unsupported', [])] : [],\n );\n }\n\n /** See `DashboardRuntime.handOver`. */\n handOver(panelId: string): HandOver | null {\n if (this.disposed) return null;\n return boardHandOver(panelId, this.state, {\n definitionId: this.definition.id,\n held: name => this.values.holds(name),\n kinds: this.kinds,\n anchor: panelId => this.anchors.get(panelId) ?? null,\n });\n }\n\n /**\n * What the draft would be judged as at another scope. Sharing a dashboard\n * widens who sees it, and a panel on a personal view would be blank for\n * them, so the target scope decides rather than the current one.\n */\n issuesAt(scope: ViewScope): Issue[] {\n return scope === this.state.scope\n ? this.state.issues\n : this.admit(this.state.draft, scope);\n }\n\n /**\n * A save is where the history starts again: the board is left as saved\n * (「完成」), and the next building begins from it.\n */\n markSaved(instance: ViewInstance): void {\n if (this.disposed) return;\n this.moveBaseline(instance);\n this.store.setState({ write: null, history: this.edits.forget() });\n }\n\n /**\n * The baseline as this board is read (`canonicalBoard`): a board stores\n * no time wire made from a view (D1), so what came back is read with them.\n */\n moveBaseline(stored: ViewInstance): void {\n if (this.disposed) return;\n const instance = canonicalSaved(stored, this.canonical) ?? stored;\n // A board moved to the other audience (设为共享/设为个人) is judged at\n // the audience it is in now: whether a panel's view is visible where\n // the board is depends on it (`coversScope`).\n const moved = instance.scope !== this.state.scope;\n this.store.setState({\n ...this.store.baseline(instance),\n ...(moved\n ? { issues: this.admit(this.state.draft, instance.scope) }\n : {}),\n });\n }\n\n adoptSaved(stored: ViewInstance): void {\n if (this.disposed) return;\n const instance = canonicalSaved(stored, this.canonical) ?? stored;\n const draft = instance.config as DashboardViewConfig;\n this.store.setState({\n saved: instance,\n title: instance.title,\n scope: instance.scope,\n draft,\n issues: this.admit(draft, instance.scope),\n dirty: false,\n write: null,\n history: this.edits.forget(),\n });\n this.load(draft);\n }\n\n /** A board narrows nothing itself; each panel's view answers for its own. */\n unavailable(): Issue[] {\n return [];\n }\n\n /** See `unavailable`: nothing of the board's own to take out. */\n removeUnavailable(): void {}\n\n setWrite(write: WriteState | null): void {\n if (this.disposed) return;\n this.store.setState({ write });\n }\n\n dispose(): void {\n this.store.dispose();\n }\n\n /** The child runtime of one panel, for a host that drives a panel itself. */\n panelRuntime(panelId: string): DataViewRuntime | null {\n return this.children.runtimeOf(panelId);\n }\n\n /**\n * Admission of a config at a scope, against the references known: the\n * dashboard kernel's, then each analysis the board owns through the\n * analysis kernel (`ownedRefusals`), which the dashboard kernel may not\n * import. Only what `blocksBoard` reads — a finding no panel owns —\n * stops the board; everything under `['panels', i]` is that panel's. A\n * view whose read failed is said as that failure (`restate`).\n */\n private admit(config: DashboardViewConfig, scope: ViewScope): Issue[] {\n return admitBoard(config, scope, this.references.known, this.kinds, {\n limits: this.options.limits,\n definitions: this.options.definitions,\n }).map(found => this.references.restate(found));\n }\n\n /**\n * Starts loading the references a config needs; each one re-judges the\n * draft as it settles (`settled`). `awaited` says whether anyone waits on\n * the outcome — see `PanelReferences.load`.\n */\n private load(config: DashboardViewConfig, awaited = false): void {\n if (this.references.load(config, awaited))\n this.store.setState({ resolving: true });\n }\n\n /** A reference settled — loaded, unreadable or failed — so the draft is re-judged. */\n private settled(): void {\n if (this.disposed) return;\n const canonical = canonicalState(this.state, this.canonical, this.store);\n this.sync({\n ...canonical,\n issues: this.admit(canonical.draft ?? this.state.draft, this.state.scope),\n resolving: this.references.resolving,\n });\n }\n\n /**\n * Brings the child runtimes in line with the applied panels: one per data\n * panel that can run, none for the rest, and the current scope in each.\n */\n private sync(patch: Partial<DashboardRuntimeState> = {}): void {\n if (this.disposed) return;\n this.synced = true;\n const applied = patch.applied ?? this.state.applied;\n const issues = this.admit(applied, this.state.scope);\n // Only the tab on screen runs (D22 E). A panel elsewhere keeps the child\n // it has, rows and all, exactly as it stands — neither re-scoped nor\n // re-run — until its tab is shown; one never shown has none yet.\n const tab = shownTab(applied, this.requestedTab);\n // What the filters hold, read against the board as it now is: a filter\n // taken off holds nothing, a required one never less than its default.\n const filters = this.values.on(applied);\n const panels = boardPanels({\n applied,\n issues,\n tab,\n filters,\n held: name => this.values.holds(name),\n viewOf: panel => this.viewOf(panel),\n run: (panel, index, own) =>\n this.syncPanel(panel, index, applied, filters, own),\n hold: (panel, index, own) => this.children.hold(panel.id, index, own),\n });\n this.children.keepOnly(\n new Set(panels.flatMap(panel => (panel.runtime ? [panel.id] : []))),\n );\n\n // A re-sync that changes nothing keeps the previous array, so a grid\n // bound with `useSyncExternalStore` does not re-render on every apply.\n // After the panels: what a filter change started is running by the\n // time the step is seen. A change's own run is a step whatever it sent.\n const filtersRun =\n patch.filtersRun ??\n this.state.filtersRun + (dequal(filters, this.filtersOut) ? 0 : 1);\n this.filtersOut = filters;\n this.store.setState({\n ...patch,\n tab,\n filters,\n filtersRun,\n panels: samePanels(this.state.panels, panels)\n ? this.state.panels\n : panels,\n });\n }\n\n /**\n * One panel's child, and what the panel reports. A reference that could\n * not be put to work, or a panel with an error of its own, runs nothing;\n * otherwise the child is brought in line with the panel and the scope\n * (`PanelChildren.sync`), and a refusal lands in the panel's issues where\n * the dashboard's own would.\n */\n private syncPanel(\n panel: DashboardViewPanel,\n index: number,\n applied: DashboardViewConfig,\n filters: DashboardFilters,\n own: Issue[],\n ): { runtime: DataViewRuntime | null; issues: Issue[] } {\n const instanceId = referencedInstance(panel) ?? '';\n const failure = this.references.failure(instanceId);\n if (failure !== undefined)\n return {\n runtime: null,\n // Said once: a read that failed is the panel's own finding already.\n issues: own.some(found => found.code === 'dashboard.panel.failed')\n ? own\n : [...own, panelFailure(index, instanceId, failure)],\n };\n\n const view = this.viewOf(panel);\n // A panel with a problem of its own does not query; the others still do.\n if (!view || hasError(own)) return { runtime: null, issues: own };\n\n const run = panelRun(panel, index, view, {\n applied,\n filters,\n kinds: this.kinds,\n limits: this.limits,\n clock: {\n now: this.environment.now(),\n timeZone: this.environment.timeZone,\n },\n });\n if (run.anchor) this.anchors.set(panel.id, run.anchor);\n else this.anchors.delete(panel.id);\n return this.children.sync(\n panel.id,\n index,\n [...own, ...run.issues],\n run.view,\n run.scope,\n );\n }\n\n /** The view a data panel shows, once there is one; see `panelView`. */\n private viewOf(panel: DataPanelSource): PanelView | null {\n return panelView(\n panel,\n id => this.references.get(id),\n this.options.definitions,\n // The board is read once before its store is made, at its own scope.\n (this.store as typeof this.store | undefined)?.getSnapshot().scope ??\n this.options.scope,\n );\n }\n\n /**\n * A child's findings change under a host that drives it through\n * `panelRuntime` — an edit, an apply — and nothing re-syncs the dashboard\n * for that. The panel's issues are rebuilt from what the last sync knew\n * and what the child says now, so a header marker is never a sync behind\n * the body it sits over. Mid-sync the array still holds the previous\n * child, if any, and the sync in progress reports for the new one.\n */\n private refreshPanelIssues(panelId: string): void {\n const panels = reissued(this.state.panels, this.children.get(panelId));\n if (panels) this.store.setState({ panels });\n }\n}\n\n/** A panel whose last query its source refused the reader for. */\nfunction refusedTheReader(panel: DataViewRuntime): boolean {\n return isForbiddenQuery(panel.getSnapshot().query.error);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The refusals a command makes of its own input before anything is sent —\n * nothing here asks the store or a permission.\n */\n\nimport {\n configBytes,\n MAX_VIEW_CONFIG_BYTES,\n MAX_VIEW_TITLE_LENGTH,\n titleProblem,\n type Issue,\n type ViewConfig,\n} from '../model/index.js';\nimport { issue } from '../filter/index.js';\nimport { stopsSave } from './dashboardRuntime.js';\nimport type { ManagedViewRuntime } from './viewRuntimeTypes.js';\nimport { ViewCommandError } from './write.js';\n\n/**\n * A view needs a title, and the store keeps one of at most\n * `MAX_VIEW_TITLE_LENGTH` (`view.title.empty`, `view.title.too-long`): the\n * engine refuses it here rather than send what the store refuses. Answers\n * the title as it is stored, trimmed.\n */\nexport function requireTitle(title: string): string {\n switch (titleProblem(title)) {\n case 'empty':\n throw new ViewCommandError(issue('view.title.empty', ['title']));\n case 'too-long':\n throw new ViewCommandError(\n issue('view.title.too-long', ['title'], { max: MAX_VIEW_TITLE_LENGTH }),\n );\n default:\n return title.trim();\n }\n}\n\n/**\n * The draft as a runtime writes it to the store (`stored`, where its kind\n * stores less than it reads), refused when the store would not keep it.\n */\nexport function storable(\n runtime: ManagedViewRuntime,\n draft: ViewConfig,\n): ViewConfig {\n return requireStorable(runtime.stored?.(draft) ?? draft);\n}\n\n/**\n * A config the store keeps: at most `MAX_VIEW_CONFIG_BYTES` of JSON\n * (`view.config.too-large`). A board of many panels is what reaches it.\n */\nexport function requireStorable<C extends ViewConfig>(config: C): C {\n const bytes = configBytes(config);\n if (bytes > MAX_VIEW_CONFIG_BYTES)\n throw new ViewCommandError(\n issue('view.config.too-large', [], {\n size: Math.ceil(bytes / 1024),\n max: MAX_VIEW_CONFIG_BYTES / 1024,\n }),\n );\n return config;\n}\n\n/** What stops a save of this runtime's kind (`stopsSave`). */\nexport function requireSavable(\n runtime: ManagedViewRuntime,\n issues: readonly Issue[],\n): void {\n if (stopsSave(runtime.kind, issues))\n throw new ViewCommandError(issue('view.config.invalid', []));\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n RuntimeLimits,\n ViewConfig,\n ViewInstance,\n ViewScope,\n} from '../model/index.js';\nimport { isOwnedPanel, isViewPanel } from '../dashboard/index.js';\nimport { issue, type FieldKindRegistry } from '../filter/index.js';\nimport { requireStorable, requireTitle } from './commandChecks.js';\nimport { DashboardViewRuntime } from './dashboardRuntime.js';\nimport type { DefinitionRegistry } from './definitions.js';\nimport { validateDataConfig } from './execute.js';\nimport type { PermissionGuard } from './permissions.js';\nimport { ViewCommandError } from './write.js';\nimport type { WriteLedger } from './writeLedger.js';\n\n/** What saving a panel's view stands on: the engine's own parts. */\nexport interface PanelViewsHost {\n registry: DefinitionRegistry;\n kinds: FieldKindRegistry;\n limits: RuntimeLimits;\n guard: PermissionGuard;\n ledger: WriteLedger;\n}\n\n/**\n * Which view of a panel is saved as a view of its own: the analysis the\n * board owns (「另存为视图」, D22 C), or the saved view it shows, copied for\n * another audience (「复制为共享视图并替换」, D22 B).\n */\nexport type PanelViewSource = 'owned' | 'saved';\n\n/** The refusal for each source, when the panel has none. */\nconst REFUSED: Record<PanelViewSource, string> = {\n owned: 'dashboard.panel.not-owned',\n saved: 'dashboard.panel.not-referenced',\n};\n\n/**\n * A dashboard panel's view saved as a view of its own, the panel pointed at\n * it (`ViewEngine.saveOwnedView`, `ViewEngine.copyPanelView`): the new\n * instance is listed with the definition's other views from then on, and\n * the panel keeps its title, wiring, click and override — it shows the very\n * same view. The board itself is not written: the panel's new reference is\n * an edit of its draft, saved with the board like any other.\n *\n * A saved view is copied as it was saved — not the panel's look over it,\n * nor the board's filters, which stay the panel's — and is left as it is.\n * Judged as any save-as is: the config against its definition, a title,\n * the right to create at that audience. A panel without that source is\n * refused (`dashboard.panel.not-owned`, `dashboard.panel.not-referenced`).\n */\nexport class PanelViews {\n constructor(private readonly host: PanelViewsHost) {}\n\n async save(\n target: unknown,\n panelId: string,\n from: PanelViewSource,\n input: { title: string; scope: ViewScope },\n ): Promise<ViewInstance> {\n const board = target instanceof DashboardViewRuntime ? target : null;\n const view = board && sourceOf(board, panelId, from);\n if (!board || !view)\n throw new ViewCommandError(issue(REFUSED[from], [], { panel: panelId }));\n const { definitionId, config } = view;\n const definition = this.host.registry.require(definitionId);\n const title = requireTitle(input.title);\n if (definition.kind !== 'data' || config.kind === 'dashboard')\n throw new ViewCommandError(\n issue('runtime.kind.not-declared', [], {\n definition: definitionId,\n kind: config.kind,\n }),\n );\n const { kinds, limits } = this.host;\n const found = validateDataConfig({ definition, kinds, limits }, config);\n if (found.some(entry => entry.severity === 'error'))\n throw new ViewCommandError(issue('view.config.invalid', []));\n this.host.guard.requireCreate(definitionId, input.scope);\n\n const { scope } = input;\n requireStorable(config);\n const instance = (await this.host.ledger.dispatch(\n {\n action: 'create',\n input: { definitionId, title, scope, config },\n intent: 'save-as',\n },\n undefined,\n )) as ViewInstance;\n board.referToSaved(panelId, instance);\n return instance;\n }\n}\n\n/**\n * The view a panel would save: what it owns, or the saved view its child\n * has open — which is the one this reader can read, and none while the\n * reference is unread or refused.\n */\nfunction sourceOf(\n board: DashboardViewRuntime,\n panelId: string,\n from: PanelViewSource,\n): { definitionId: string; config: ViewConfig } | null {\n const panel = board\n .getSnapshot()\n .draft.panels.find(entry => entry.id === panelId);\n if (from === 'owned') return isOwnedPanel(panel) ? panel.owned : null;\n const saved = board.panelRuntime(panelId)?.getSnapshot().saved;\n return isViewPanel(panel) &&\n panel.owned === undefined &&\n saved?.id === panel.instanceId\n ? saved\n : null;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A fresh request id: a random (version 4) UUID.\n *\n * `crypto.randomUUID` exists only in a secure context (HTTPS or localhost);\n * a host served over plain HTTP — an intranet console, a dev cluster — has\n * `crypto.getRandomValues` but no `randomUUID`, and every write would fail\n * before it was sent. So the id is made from random bytes when\n * `randomUUID` is missing, in the same shape.\n */\nexport function newRequestId(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === 'function') return source.randomUUID();\n const bytes = new Uint8Array(16);\n source.getRandomValues(bytes);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4).join(''),\n hex.slice(4, 6).join(''),\n hex.slice(6, 8).join(''),\n hex.slice(8, 10).join(''),\n hex.slice(10, 16).join(''),\n ].join('-');\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What a system view is made from (D81): 「发布为系统视图」, a saved view\n * copied as a stored system view, which `ViewEngine.publishAsSystem`\n * sends; and the one rule a system board keeps — every saved view its\n * panels reference is a system view, since system views are read in every\n * tenant and a shared or personal one is not.\n */\n\nimport {\n isSystemInstanceId,\n isSystemScope,\n listParam,\n type ViewConfig,\n type ViewInstance,\n type ViewScope,\n} from '../model/index.js';\nimport { isViewPanel } from '../dashboard/index.js';\nimport { issue } from '../filter/index.js';\nimport { requireStorable } from './commandChecks.js';\nimport type { ViewStore } from '../store/ViewStore.js';\nimport type { PermissionGuard } from './permissions.js';\nimport type { SummaryCache } from './summaries.js';\nimport { ViewCommandError } from './write.js';\nimport type { WriteLedger } from './writeLedger.js';\n\n/** What a saved view a panel references is, as far as it can be read. */\nexport type ReferenceOf = (\n id: string,\n) => Promise<{ scope: ViewScope; title: string } | undefined>;\n\n/**\n * Creates the copy of the saved view `id` (`read`: an open view's saved\n * instance, else the store's) — its title and its saved config, never a\n * draft — as a stored system view. Asked first: that the source is not a\n * system view already (`view.system.read-only`, as the manager offers no\n * such button), `editSystem` (`view.create.forbidden`) and the config's\n * size; a board's panels the ledger asks of every create into the system\n * scope (`requireSystemPanels`). The source is not\n * written; the copy lands like a 另存为 (`save-as`), bound to no open view.\n */\nexport async function publishCopy(\n guard: PermissionGuard,\n ledger: WriteLedger,\n id: string,\n read: () => Promise<ViewInstance>,\n): Promise<ViewInstance> {\n // A view declared in code is refused before anything is read: no store\n // holds it.\n const source = isSystemInstanceId(id) ? null : await read();\n if (!source || isSystemScope(source.scope))\n throw new ViewCommandError(\n issue('view.system.read-only', [], { action: 'publish' }),\n );\n const { definitionId, title, config } = source;\n guard.requireCreate(definitionId, 'system');\n return (await ledger.dispatch(\n {\n action: 'create',\n input: {\n definitionId,\n title,\n scope: 'system',\n config: requireStorable(config),\n },\n intent: 'save-as',\n },\n undefined,\n )) as ViewInstance;\n}\n\n/**\n * Refuses a board headed for the system views when any panel references a\n * saved view that is not a system view — the one it shows, the one\n * 「在工作台中打开」 opens, or the one a press opens — naming those panels\n * (`dashboard.system.non-system-panels`): such a panel would be blank for\n * every reader in every other tenant. A view the board owns, and a view\n * that cannot be read, count as they are: owned is fine, unreadable is not.\n * Asked of a `scope` other than `system`, it lets the board pass.\n */\nexport async function requireSystemPanels(\n config: ViewConfig,\n referenceOf: ReferenceOf,\n scope: ViewScope = 'system',\n): Promise<void> {\n if (!isSystemScope(scope) || config.kind !== 'dashboard') return;\n const named: string[] = [];\n for (const panel of config.panels) {\n if (!isViewPanel(panel)) continue;\n const ids = [\n panel.owned === undefined ? panel.instanceId : undefined,\n panel.opens,\n panel.click && 'instanceId' in panel.click\n ? panel.click.instanceId\n : undefined,\n ].filter((id): id is string => typeof id === 'string' && id !== '');\n const read = await Promise.all(\n ids.map(async id =>\n isSystemInstanceId(id)\n ? { scope: 'system' as const, title: '' }\n : referenceOf(id),\n ),\n );\n if (read.every(found => found !== undefined && isSystemScope(found.scope)))\n continue;\n const shown = panel.owned === undefined ? read[0]?.title : undefined;\n named.push(panel.title ?? shown ?? panel.id);\n }\n if (named.length > 0)\n throw new ViewCommandError(\n issue('dashboard.system.non-system-panels', [], {\n panels: listParam(named),\n count: named.length,\n }),\n );\n}\n\n/**\n * How the engine reads a panel's saved view for `requireSystemPanels`: the\n * summary it last saw, else the store's copy; one that cannot be read is\n * none.\n */\nexport function readReferences(\n summaries: SummaryCache,\n store: ViewStore,\n): ReferenceOf {\n return async id => summaries.get(id) ?? store.get(id).catch(() => undefined);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n isViewStoreError,\n type Issue,\n type ViewInstance,\n type ViewStoreError,\n type ViewPreferences,\n} from '../model/index.js';\nimport { issue } from '../filter/index.js';\nimport { listParam } from '../model/issue.js';\nimport { newRequestId } from './requestId.js';\nimport type { ViewStore, WriteContext } from '../store/ViewStore.js';\nimport type { ManagedViewRuntime, ViewRuntime } from './viewRuntimeTypes.js';\nimport type { ViewChange } from './viewChanges.js';\nimport { requireSystemPanels, type ReferenceOf } from './publish.js';\nimport {\n ViewCommandError,\n ViewWriteError,\n type WriteHandle,\n type WritePayload,\n type WriteState,\n} from './write.js';\n\n/** What a write command is addressed to: an open view, or a handle. */\nexport type WriteTarget = ViewRuntime | WriteHandle;\n\nexport type ConflictChoice = 'reload' | 'overwrite';\n\n/** Everything a write can hand back, by action. */\nexport type WriteResult = ViewInstance | ViewPreferences | void;\n\n/**\n * What the ledger cannot reach on its own.\n *\n * A write's outcome belongs to the ledger, but a *confirmed* write also moves\n * things the ledger does not own: the engine's summary and preference caches,\n * and the other open views of the same instance. The engine hands those over\n * as these few calls rather than letting the ledger hold its registry.\n */\nexport interface WriteLedgerHost {\n /** The port every write goes to. */\n readonly store: ViewStore;\n /** Idempotency keys; overridden in tests to keep them readable. */\n newId?(): string;\n /** Remembers the summary of an instance the store has just confirmed. */\n noteInstance(instance: ViewInstance): void;\n /** Forgets a deleted instance and closes every open view of it, `owner` first. */\n dropInstance(id: string, owner: ManagedViewRuntime | undefined): void;\n /** Remembers preferences the store has just confirmed. */\n notePreferences(definitionId: string, preferences: ViewPreferences): void;\n /** Re-reads preferences through the host, so its cache moves with them too. */\n readPreferences(definitionId: string): Promise<ViewPreferences>;\n /** Open views whose baseline is this instance. */\n holders(id: string): readonly ManagedViewRuntime[];\n /**\n * Says that a confirmed write changed what a definition's list holds. It\n * hangs off the same place the effects do, so a retry and an overwrite\n * announce what the first attempt would have.\n */\n noteChange(change: ViewChange): void;\n /** A panel's saved view, read for a board headed for the system views. */\n referenceOf: ReferenceOf;\n}\n\n/**\n * The write ledger: one account of every write that left and has not been\n * settled, keyed by its `requestId`.\n *\n * Every write leaves through `dispatch`, so the default UI and a hand-built\n * one behave the same, and every non-success outcome lands in the same three\n * recovery actions: `retryWrite`, `abandonWrite`, `resolveConflict`.\n *\n * What the ledger keeps is the *body* of the write rather than the draft it\n * came from, which is what makes those three honest: a retry and an overwrite\n * replay the original intent, so what the user asked for survives whatever\n * they edited while the request was in flight.\n */\nexport class WriteLedger {\n private readonly host: WriteLedgerHost;\n private readonly writes = new Map<string, WriteState>();\n /** Write targets with a request in flight; see `dispatch`. */\n private readonly inFlight = new Set<string>();\n private readonly owners = new Map<string, ManagedViewRuntime>();\n private readonly newId: () => string;\n\n constructor(host: WriteLedgerHost) {\n this.host = host;\n this.newId = host.newId ?? newRequestId;\n }\n\n /** Writes still waiting for a decision, by handle id. */\n pendingWrites(): ReadonlyMap<string, WriteState> {\n return this.writes;\n }\n\n /** A new logical write: a fresh `requestId`, then the one path out. */\n async dispatch(\n payload: WritePayload,\n runtime: ManagedViewRuntime | undefined,\n ): Promise<WriteResult> {\n // Every write of a config into the system scope — a first save, a\n // 另存为, a publish, a save in place of a system board — passes here, so\n // a system board's rule is asked once (D81).\n const into =\n payload.action === 'create'\n ? payload.input\n : payload.action === 'save'\n ? { config: payload.config, scope: runtime?.getSnapshot().scope }\n : null;\n if (into?.scope)\n await requireSystemPanels(into.config, this.host.referenceOf, into.scope);\n return this.replay(payload, this.newId(), runtime);\n }\n\n /** Replays the original intent under its original `requestId`. */\n async retryWrite(target: WriteTarget): Promise<WriteResult> {\n const { requestId, state } = this.requireWrite(target);\n return this.replay(state.payload, requestId, this.owners.get(requestId));\n }\n\n /**\n * Drops the outcome and keeps the draft; a later save is a new intent.\n *\n * A conflict told the engine what the store holds now, and that stays\n * true whatever the reader chose: the cached summary and preferences take\n * the store's revision, so the next command given only an id — a rename\n * from the list, a reorder — is not refused against a revision already\n * known to be gone. An open view keeps its baseline: its draft was written\n * against that one, and only the reader's choice moves it.\n */\n abandonWrite(target: WriteTarget): void {\n const { requestId, state } = this.requireWrite(target);\n if (state.kind === 'conflict') {\n if (state.payload.action === 'preferences')\n this.host.notePreferences(\n state.payload.definitionId,\n state.remote as ViewPreferences,\n );\n else this.host.noteInstance(state.remote as ViewInstance);\n }\n this.settle(requestId);\n }\n\n /**\n * `reload` takes the server's state, losing the draft; `overwrite` replays\n * the original intent against the revision the conflict reported, which is a\n * new logical write and so takes a new `requestId`.\n */\n async resolveConflict(\n target: WriteTarget,\n choice: ConflictChoice,\n ): Promise<WriteResult> {\n const { requestId, state } = this.requireWrite(target);\n if (state.kind !== 'conflict')\n throw new ViewCommandError(\n issue('view.write.not-a-conflict', [], { kind: state.kind }),\n );\n\n const runtime = this.owners.get(requestId);\n if (choice === 'reload') {\n this.settle(requestId);\n return this.reload(state, runtime);\n }\n this.settle(requestId);\n return this.dispatch(withRevision(state.payload, state.remote), runtime);\n }\n\n /**\n * The one place a write leaves the engine. Success clears the outcome;\n * anything else is recorded, attached to the owning runtime and raised as a\n * `ViewWriteError` carrying its own handle.\n *\n * It takes the `requestId` rather than minting one, because a retry is the\n * same logical write and has to carry the key the first attempt used.\n */\n private async replay(\n payload: WritePayload,\n requestId: string,\n runtime: ManagedViewRuntime | undefined,\n ): Promise<WriteResult> {\n // One write at a time per target. Two saves of one view would carry the\n // same expected revision, so the second reports a conflict the user caused\n // by clicking twice; two first saves would each create, leaving a duplicate\n // instance and a runtime bound to only one of them. The idempotent\n // `requestId` cannot help, because each command mints its own: it dedupes\n // a retry of one write, not two writes that mean the same thing.\n const key = writeKey(payload, runtime);\n if (this.inFlight.has(key))\n throw new ViewCommandError(\n issue('view.write.in-flight', [], { action: payload.action }),\n );\n this.requireNoUnknownWrite(key, requestId);\n this.inFlight.add(key);\n\n const context: WriteContext = { requestId };\n if (runtime) this.owners.set(requestId, runtime);\n try {\n const result = await this.send(payload, context);\n this.applyEffect(payload, result, runtime);\n this.settle(requestId);\n return result;\n } catch (error) {\n const state = await this.toWriteState(error, requestId, payload);\n this.writes.set(requestId, state);\n if (runtime && this.mayShow(runtime, payload, requestId))\n runtime.setWrite(state);\n throw new ViewWriteError(state);\n } finally {\n this.inFlight.delete(key);\n }\n }\n\n /**\n * Whether an outcome takes the open view's place for its write. The view's\n * own writes (a save, a first save, a save as) always do — the latest one\n * is what the reader is looking at. A write the manager sent through the\n * view (a rename, a change of audience, a delete) does only where nothing\n * of the view's own is waiting: a conflict the reader has not resolved yet\n * is theirs, and a failed rename from the list must not hide it.\n */\n private mayShow(\n runtime: ManagedViewRuntime,\n payload: WritePayload,\n requestId: string,\n ): boolean {\n if (payload.action === 'create' || payload.action === 'save') return true;\n const shown = runtime.getSnapshot().write;\n return (\n !shown ||\n shown.requestId === requestId ||\n !this.writes.has(shown.requestId)\n );\n }\n\n /**\n * What a confirmed write changes. It hangs off the payload rather than the\n * command, so replaying an intent as a retry or an overwrite advances the\n * same baseline the first attempt would have.\n */\n private applyEffect(\n payload: WritePayload,\n result: WriteResult,\n runtime: ManagedViewRuntime | undefined,\n ): void {\n switch (payload.action) {\n case 'create': {\n const instance = result as ViewInstance;\n this.host.noteInstance(instance);\n if (payload.intent === 'first-save') runtime?.markSaved(instance);\n this.announce('create', instance);\n return;\n }\n case 'save':\n case 'rename':\n case 'changeAudience': {\n const instance = result as ViewInstance;\n this.host.noteInstance(instance);\n // Every open view of this instance moves to the new baseline, not\n // only the one the command came through: the same view open twice\n // would otherwise keep a revision nobody can write against. Only a\n // save is the view's own write, and only it is marked saved — which\n // settles the view's outcome and, on a board, starts its history\n // again. A rename or a change of audience carries no config: it\n // moves the baseline and leaves the draft, the board's undo and any\n // write of the view's own still waiting exactly as they were.\n if (payload.action === 'save') runtime?.markSaved(instance);\n for (const holder of this.host.holders(instance.id))\n if (payload.action !== 'save' || holder !== runtime)\n holder.moveBaseline(instance);\n this.announce(payload.action, instance);\n return;\n }\n case 'delete':\n // Preferences keep the id; a later reorder or default cleans it up.\n this.host.dropInstance(payload.id, runtime);\n this.host.noteChange({\n definitionId: payload.definitionId,\n kind: 'delete',\n id: payload.id,\n });\n return;\n case 'preferences':\n this.host.notePreferences(\n payload.definitionId,\n result as ViewPreferences,\n );\n }\n }\n\n /** The actions that hand back an instance say so the same way. */\n private announce(\n kind: 'create' | 'save' | 'rename' | 'changeAudience',\n instance: ViewInstance,\n ): void {\n this.host.noteChange({\n definitionId: instance.definitionId,\n kind,\n id: instance.id,\n });\n }\n\n /** Each action against its own method on the port. */\n private send(\n payload: WritePayload,\n context: WriteContext,\n ): Promise<WriteResult> {\n const store = this.host.store;\n switch (payload.action) {\n case 'create':\n return store.create(payload.input, context);\n case 'save':\n return store.save(\n payload.id,\n payload.config,\n payload.revision,\n context,\n );\n case 'rename':\n return store.rename(\n payload.id,\n payload.title,\n payload.revision,\n context,\n );\n case 'changeAudience':\n // Only ever dispatched over a store that has the method: the engine\n // refuses the command before anything is sent otherwise.\n return store.changeAudience!(\n payload.id,\n payload.audience,\n payload.revision,\n context,\n );\n case 'delete':\n return store.delete(payload.id, payload.revision, context);\n case 'preferences':\n return store.setPreferences(\n payload.definitionId,\n payload.next,\n context,\n );\n }\n }\n\n /** How a thrown write becomes an outcome the three recovery actions read. */\n private async toWriteState(\n error: unknown,\n requestId: string,\n payload: WritePayload,\n ): Promise<WriteState> {\n if (!isViewStoreError(error))\n // Anything that does not speak the port's language is treated as an\n // unknown outcome rather than a failure. It may well be a bug in the\n // adapter that will fail again on retry, and saying \"unknown\" about it\n // is then misleading — but the other mistake is worse: a write that\n // reached the server, reported as failed, is a view the user saves a\n // second time. Only the store can tell these apart, and it does so by\n // raising a `ViewStoreError`.\n return { kind: 'unknown', requestId, payload };\n\n switch (error.code) {\n case 'UNAVAILABLE':\n // The browser's own storage would not keep it (`storage`): nothing\n // was written, and the retry that follows writes it again once\n // there is room — so it stays the retry-or-abandon outcome, but\n // says why in the reader's words rather than that the result never\n // came back.\n if (error.storage === true)\n return {\n kind: 'unknown',\n requestId,\n payload,\n issue: issue('view.write.storage', [], { reason: error.message }),\n };\n // The server answered with an error of its own: the outcome is\n // still unknown — a 5xx may come after the write — but the reader\n // is told it was the server, with its reason, not the network.\n if (error.reachable === true)\n return {\n kind: 'unknown',\n requestId,\n payload,\n issue: issue('view.write.unavailable.server', [], {\n reason: error.message,\n }),\n };\n return { kind: 'unknown', requestId, payload };\n case 'CONFLICT': {\n // Which of the two the error may carry is decided by what was being\n // written, not by what happens to be on the error: a preference\n // write reads `preferences` and an instance write reads `instance`,\n // so a store that filled in the wrong one reports nothing rather\n // than being believed.\n const remote =\n (payload.action === 'preferences'\n ? error.preferences\n : error.instance) ?? (await this.fetchRemote(payload));\n if (!remote)\n return {\n kind: 'rejected',\n requestId,\n payload,\n issue: issue('view.write.conflict-unreadable', []),\n };\n // A delete that conflicts is answered by confirming again (§7.4), so\n // the summary the user confirms against is the one the store now\n // holds rather than the title and revision they asked to delete.\n if (payload.action === 'delete')\n this.host.noteInstance(remote as ViewInstance);\n return { kind: 'conflict', remote, requestId, payload };\n }\n default:\n return {\n kind: 'rejected',\n requestId,\n payload,\n issue: refusalIssue(payload, error),\n };\n }\n }\n\n /** A store may report a conflict without the state it holds; ask for it. */\n private async fetchRemote(\n payload: WritePayload,\n ): Promise<ViewInstance | ViewPreferences | null> {\n const store = this.host.store;\n try {\n if (payload.action === 'preferences')\n return await store.getPreferences(payload.definitionId);\n if (payload.action === 'create') return null;\n return await store.get(payload.id);\n } catch {\n return null;\n }\n }\n\n /** The `reload` half of `resolveConflict`: take what the server holds. */\n private async reload(\n state: Extract<WriteState, { kind: 'conflict' }>,\n runtime: ManagedViewRuntime | undefined,\n ): Promise<WriteResult> {\n if (state.payload.action === 'preferences')\n return this.host.readPreferences(state.payload.definitionId);\n const remote = state.remote as ViewInstance;\n // Only a `save` was carrying a config, so only reloading that one means\n // taking the server's config and dropping the draft. A rename or a delete\n // carries no config (§7.1), and the edits the user has not saved yet are\n // not theirs to discard: the baseline moves and the draft stays.\n if (state.payload.action === 'save') runtime?.adoptSaved(remote);\n else runtime?.moveBaseline(remote);\n this.host.noteInstance(remote);\n return remote;\n }\n\n /** The entry a recovery action names, whether by open view or by handle. */\n private requireWrite(target: WriteTarget): {\n requestId: string;\n state: WriteState;\n } {\n const requestId = isRuntime(target)\n ? target.getSnapshot().write?.requestId\n : target.id;\n const state = requestId ? this.writes.get(requestId) : undefined;\n if (!requestId || !state)\n throw new ViewCommandError(issue('view.write.not-pending', []));\n return { requestId, state };\n }\n\n /**\n * An unknown outcome is a write that may have landed. Sending another to\n * the same target before it is retried or abandoned is how a first save\n * ends up as two instances, so a new intent waits; only the replay of the\n * unknown write itself, under its own `requestId`, goes through.\n */\n private requireNoUnknownWrite(key: string, requestId: string): void {\n for (const [pendingId, pending] of this.writes) {\n if (pendingId === requestId || pending.kind !== 'unknown') continue;\n if (writeKey(pending.payload, this.owners.get(pendingId)) !== key)\n continue;\n throw new ViewCommandError(\n issue('view.write.unknown-pending', [], {\n action: pending.payload.action,\n }),\n );\n }\n }\n\n /** Closes the account for one write: nothing left to retry or abandon. */\n private settle(requestId: string): void {\n this.writes.delete(requestId);\n const owner = this.owners.get(requestId);\n // Only if the runtime is still reporting *this* write. It may have moved\n // on to a later one — a copy made out of a conflict is a write of its own,\n // and settling the conflict behind it would take the copy's outcome off\n // the screen while the engine went on holding it.\n if (owner?.getSnapshot().write?.requestId === requestId)\n owner.setWrite(null);\n this.owners.delete(requestId);\n }\n}\n\n/**\n * The sentence a refusal is said in. A system view the store would not\n * create is a permission the reader lacks (`view.publish.forbidden`). An\n * audience change the store finds invalid has one reason the reader can act\n * on — a shared board shows the\n * view — so it is said with the store's reason rather than as the bare\n * 「服务端拒绝了这次写入」, and in the engine's own words around the boards'\n * titles when the store names them (`boards`): the titles stay as stored,\n * keys included, said where the sentence is shown (D2). `reason` rides along\n * for a catalogue without the sentence, which falls back to\n * `view.changeAudience.invalid`.\n */\nfunction refusalIssue(payload: WritePayload, error: ViewStoreError): Issue {\n const reason = { reason: error.message };\n // A create into the system scope the gateway refused (D81): the reader\n // may not publish system views, which is not \"you may not write this\n // view\" said under a view of their own.\n if (\n payload.action === 'create' &&\n payload.input.scope === 'system' &&\n error.code === 'FORBIDDEN'\n )\n return issue('view.publish.forbidden', [], reason);\n if (payload.action !== 'changeAudience' || error.code !== 'INVALID')\n return issue(`view.write.${error.code.toLowerCase()}`, [], reason);\n const boards = error.boards ?? [];\n return boards.length > 0\n ? issue('view.changeAudience.invalid.shared-boards', [], {\n ...reason,\n boards: listParam(boards),\n count: boards.length,\n })\n : issue('view.changeAudience.invalid', [], reason);\n}\n\nfunction isRuntime(target: WriteTarget): target is ViewRuntime {\n return typeof (target as ViewRuntime).getSnapshot === 'function';\n}\n\n/**\n * What a write contends for. A runtime is its own target — the design allows\n * one in-flight write per open view, whatever the command — and a write with\n * no runtime behind it contends for the instance or the preferences it names.\n */\nfunction writeKey(\n payload: WritePayload,\n runtime: ManagedViewRuntime | undefined,\n): string {\n if (runtime) return `runtime:${runtime.id}`;\n switch (payload.action) {\n case 'preferences':\n return `preferences:${payload.definitionId}`;\n case 'create':\n return `create:${payload.input.definitionId}:${payload.input.title}`;\n default:\n return `instance:${payload.id}`;\n }\n}\n\n/** The same intent, expecting the revision a conflict reported instead. */\nfunction withRevision(\n payload: WritePayload,\n remote: ViewInstance | ViewPreferences,\n): WritePayload {\n switch (payload.action) {\n case 'preferences':\n return {\n ...payload,\n next: { ...payload.next, revision: remote.revision },\n };\n case 'create':\n return payload;\n default:\n return { ...payload, revision: remote.revision };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { issue } from '../filter/index.js';\nimport type { Issue } from '../model/index.js';\nimport { listenerSet } from './listeners.js';\n\n/**\n * The write that changed a list — **not** the kind of the view it changed.\n *\n * These five are what a list of views can see: one appeared, one was saved,\n * one was renamed, one moved to the other audience (and so to the other\n * group), one is gone.\n * A preference write is not among them: it changes the order and the default,\n * which the caller that wrote them already holds.\n */\nexport type ViewChangeKind =\n 'create' | 'save' | 'rename' | 'changeAudience' | 'delete';\n\n/** What a confirmed write changed about one definition's list of views. */\nexport interface ViewChange {\n definitionId: string;\n kind: ViewChangeKind;\n id: string;\n}\n\nexport type ViewChangeListener = (change: ViewChange) => void;\n\n/**\n * Who is listening for list changes, and what they are told.\n *\n * The engine is the only place that knows when a write lands, so it says so\n * rather than leaving every caller to remember (D15). The shape is a\n * runtime's: `subscribe` returns the way to stop listening.\n */\nexport class ViewChanges {\n /**\n * A listener that throws is contained: `emit` is called from inside a write\n * that has just been confirmed, and letting it out would record a write\n * that landed as an outcome the user is asked to retry.\n */\n private readonly listeners = listenerSet<[ViewChange]>(error =>\n this.report(\n issue('view.change.notify-failed', [], { reason: reasonOf(error) }),\n ),\n );\n private readonly report: (found: Issue) => void;\n\n constructor(report: (found: Issue) => void) {\n this.report = report;\n }\n\n subscribe(listener: ViewChangeListener): () => void {\n return this.listeners.subscribe(listener);\n }\n\n emit(change: ViewChange): void {\n this.listeners.emit(change);\n }\n\n clear(): void {\n this.listeners.clear();\n }\n}\n\nfunction reasonOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What a command is allowed to do, asked before it is dispatched.\n *\n * The store answers synchronously and may answer nothing at all, in which\n * case everything is allowed — bar the system views. A system view is\n * read-only unless the store keeps it (`stored`) and the host grants\n * `editSystem` (D81), whose silence is a refusal; one declared in code is\n * read-only always. That reading is {@link instanceAbilities}, which the\n * view manager's buttons ask as well (D4).\n */\n\nimport {\n audienceOf,\n isSystemInstanceId,\n isSystemScope,\n type ViewInstanceSummary,\n type ViewScope,\n} from '../model/index.js';\nimport { issue } from '../filter/index.js';\nimport type {\n InstancePermissions,\n ViewPermissions,\n ViewStore,\n} from '../store/ViewStore.js';\nimport { ViewCommandError } from './write.js';\n\n/**\n * Everything is allowed when a store declares no permissions — everything a\n * silence allows: `editSystem` is not among it (D81).\n */\nexport const ALLOW_ALL: ViewPermissions = {\n createPersonal: true,\n createShared: true,\n reorder: true,\n setDefault: true,\n instance: () => ({\n save: true,\n rename: true,\n delete: true,\n changeAudience: true,\n }),\n};\n\n/** Nothing may be written, which is what a read-only system view answers to all of them. */\nconst NO_INSTANCE_WRITES: Required<InstancePermissions> = {\n save: false,\n rename: false,\n delete: false,\n changeAudience: false,\n};\n\nconst INSTANCE_ACTION_SET = {\n save: true,\n rename: true,\n delete: true,\n changeAudience: true,\n} satisfies Record<keyof InstancePermissions, true>;\n\n/**\n * Every action an instance permission answers for. The `satisfies` above is\n * what makes it *every* one: a fourth member of `InstancePermissions` does\n * not compile until it is named here, and `test/messages.test.tsx` expands\n * this set into the `view.<action>.forbidden` codes the catalogue owes a\n * sentence to.\n */\nexport const INSTANCE_ACTIONS = Object.keys(\n INSTANCE_ACTION_SET,\n) as readonly (keyof InstancePermissions)[];\n\n/** What may be done to one instance, and — when nothing may — why not. */\nexport interface InstanceAbilities extends Required<InstancePermissions> {\n /**\n * True when the refusal is the view's own nature rather than the store's\n * answer. The guard words that refusal differently\n * (`view.system.read-only`), and it is the one thing a caller cannot fix\n * by being granted more.\n */\n readOnly: boolean;\n}\n\n/**\n * What may be done to one instance: the store's answer for its id, with a\n * system view read-only whatever that answer is — it lives in code or in\n * the backend's configuration, and no store write can reach it — unless it\n * is one the store keeps (`stored`), its id is not a code view's\n * (`system:`), and the host grants `editSystem` (D81). Then the store's\n * answer applies to it as to a shared view, bar `changeAudience`, which is\n * always false: a system view never moves audience.\n *\n * **One reading, for both callers.** D4 has a manager's button exist exactly\n * where the command would be allowed, so the guard and the manager asking\n * separately is two answers to one question: the two spelled the system\n * check out apart from each other, and the pair is only ever one edit away\n * from offering a Rename the guard then refuses.\n *\n * A scope that is not to hand is not a system view: an id the manager's rows\n * do not hold gets the store's answer, and the guard — which always has the\n * scope, because it reads a summary or an instance — is the one that refuses\n * it for certain.\n *\n * `changeAudience` answers for the move the manager offers — to the other\n * audience — so it asks the store's `changeAudience` (silence allows it, as\n * everywhere) **and** the create permission of the audience the view goes\n * to: sharing puts a view in front of everyone, which is what\n * `createShared` guards, however the view came to exist.\n */\nexport function instanceAbilities(\n summary: { id: string; scope?: ViewScope; stored?: boolean },\n permissions: ViewPermissions,\n): InstanceAbilities {\n if (summary.scope !== undefined && isSystemScope(summary.scope)) {\n if (!editableSystemView(summary, permissions))\n return { ...NO_INSTANCE_WRITES, readOnly: true };\n const { save, rename, delete: remove } = permissions.instance(summary.id);\n // Read-only still when the store grants none of the three: the lock and\n // its sentence read this one field, so they never say \"you may change\n // it\" over a view nothing can be done to.\n return {\n save,\n rename,\n delete: remove,\n changeAudience: false,\n readOnly: !(save || rename || remove),\n };\n }\n const granted = permissions.instance(summary.id);\n const into =\n summary.scope === undefined\n ? true\n : audienceOf(summary.scope) === 'personal'\n ? permissions.createShared\n : permissions.createPersonal;\n return {\n save: granted.save,\n rename: granted.rename,\n delete: granted.delete,\n changeAudience: granted.changeAudience !== false && into,\n readOnly: false,\n };\n}\n\n/**\n * Whether a system view is one this user may write: kept by the store\n * (`stored`), not declared in code (a `system:` id never is, whatever a\n * store says of it), and `editSystem` granted — absent is false (D81).\n */\nfunction editableSystemView(\n summary: { id: string; stored?: boolean },\n permissions: ViewPermissions,\n): boolean {\n return (\n summary.stored === true &&\n permissions.editSystem === true &&\n !isSystemInstanceId(summary.id)\n );\n}\n\nexport class PermissionGuard {\n private readonly store: ViewStore;\n\n constructor(store: ViewStore) {\n this.store = store;\n }\n\n /**\n * The store's answer, or everything. A store without `changeAudience` has\n * no such move to permit, so its answer says so for every instance — the\n * one reading the manager's buttons and this guard share (D4).\n */\n of(definitionId: string): ViewPermissions {\n const permissions = this.store.permissions?.(definitionId) ?? ALLOW_ALL;\n if (this.store.changeAudience) return permissions;\n return {\n createPersonal: permissions.createPersonal,\n createShared: permissions.createShared,\n reorder: permissions.reorder,\n setDefault: permissions.setDefault,\n ...(permissions.editSystem === undefined\n ? {}\n : { editSystem: permissions.editSystem }),\n instance: id => ({\n ...permissions.instance(id),\n changeAudience: false,\n }),\n };\n }\n\n /** A system view is created only where `editSystem` is granted (D81). */\n requireCreate(definitionId: string, scope: ViewScope): void {\n this.require(\n mayCreate(this.of(definitionId), scope),\n 'view.create.forbidden',\n );\n }\n\n /**\n * Asks for identity, scope and whether the store keeps it, so an instance\n * answers as well as a summary.\n */\n requireInstance(\n instance: Pick<\n ViewInstanceSummary,\n 'id' | 'definitionId' | 'scope' | 'stored'\n >,\n action: keyof InstancePermissions,\n ): void {\n const abilities = instanceAbilities(\n instance,\n this.of(instance.definitionId),\n );\n if (abilities[action]) return;\n // Two refusals, one decision: `instanceAbilities` says whether the\n // command may run, and `readOnly` says which of the two sentences the\n // user gets — a built-in view nobody can change, or a permission the\n // store withheld.\n throw new ViewCommandError(\n abilities.readOnly\n ? issue('view.system.read-only', [], { action })\n : issue(`view.${action}.forbidden`, []),\n );\n }\n\n require(allowed: boolean, code: string): void {\n if (!allowed) throw new ViewCommandError(issue(code, []));\n }\n}\n\n/**\n * Whether a view may be created in `scope`: the audience's create\n * permission, and for a system view `editSystem`, whose silence refuses.\n */\nexport function mayCreate(\n permissions: ViewPermissions,\n scope: ViewScope,\n): boolean {\n if (isSystemScope(scope)) return permissions.editSystem === true;\n return audienceOf(scope) === 'shared'\n ? permissions.createShared\n : permissions.createPersonal;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Personal preferences per definition: the order of the list, and which view\n * opens by default.\n *\n * A preference write submits the full state, so it needs the state it is\n * changing. Re-reading the store before every reorder would race with the\n * write that just confirmed, so the last value read or confirmed is kept\n * here and a write starts from it.\n */\n\nimport type { ViewInstanceSummary, ViewPreferences } from '../model/index.js';\nimport type { ViewStore } from '../store/ViewStore.js';\n\nexport class PreferenceCache {\n private readonly store: ViewStore;\n private readonly cache = new Map<string, ViewPreferences>();\n /**\n * How many times each definition's preferences were confirmed by a write\n * (`note`). Revisions are opaque, so which of two is newer cannot be read\n * off them; what can be told is that a write confirmed while a read was\n * on its way, and the read then answers the state before it.\n */\n private readonly notes = new Map<string, number>();\n\n constructor(store: ViewStore) {\n this.store = store;\n }\n\n /**\n * Reads through to the store, and remembers what came back — unless a\n * write confirmed newer preferences while the read was on its way: the\n * read started before that write, so it answers the cached ones instead,\n * and the next reorder does not start from a revision already gone.\n */\n async read(definitionId: string): Promise<ViewPreferences> {\n const before = this.notes.get(definitionId) ?? 0;\n const preferences = await this.store.getPreferences(definitionId);\n const newer = this.cache.get(definitionId);\n if (newer && (this.notes.get(definitionId) ?? 0) !== before) return newer;\n this.cache.set(definitionId, preferences);\n return preferences;\n }\n\n /** Remembers preferences a write has just confirmed. */\n note(definitionId: string, preferences: ViewPreferences): void {\n this.cache.set(definitionId, preferences);\n this.notes.set(definitionId, (this.notes.get(definitionId) ?? 0) + 1);\n }\n\n /** What a write starts from: the last value known, else a read. */\n async current(definitionId: string): Promise<ViewPreferences> {\n return this.cache.get(definitionId) ?? (await this.read(definitionId));\n }\n}\n\n/**\n * Preferred order first, then whatever the server returned. An id that no\n * longer exists is ignored rather than removed: the next write cleans it up.\n */\nexport function orderSummaries(\n summaries: readonly ViewInstanceSummary[],\n preferences: ViewPreferences,\n): ViewInstanceSummary[] {\n const byId = new Map(summaries.map(summary => [summary.id, summary]));\n const ordered = preferences.order.flatMap(id => {\n const summary = byId.get(id);\n if (summary) byId.delete(id);\n return summary ? [summary] : [];\n });\n return [...ordered, ...byId.values()];\n}\n\n/**\n * The effective default: an explicit id, else the stored one when it still\n * exists, else the first of the ordered list, which is usually the first\n * system view.\n */\nexport function resolveDefault(\n summaries: readonly ViewInstanceSummary[],\n preferences: ViewPreferences,\n explicit?: string,\n): string | null {\n const ids = new Set(summaries.map(summary => summary.id));\n if (explicit && ids.has(explicit)) return explicit;\n if (preferences.defaultInstanceId && ids.has(preferences.defaultInstanceId))\n return preferences.defaultInstanceId;\n return orderSummaries(summaries, preferences)[0]?.id ?? null;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The controller a source takes, following the caller's signal. */\nexport function abortWith(signal?: AbortSignal): AbortController {\n const controller = new AbortController();\n if (signal?.aborted) controller.abort(signal.reason);\n else\n signal?.addEventListener('abort', () => controller.abort(signal.reason), {\n once: true,\n });\n return controller;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport type {\n AnalysisViewConfig,\n FieldDefinition,\n FilterTree,\n} from '../model/index.js';\nimport {\n compileAnalysis,\n narrowValueCandidates,\n readValueCandidates,\n validateAnalysis,\n valueCandidateField,\n valueCandidateNarrowing,\n valueCandidatesConfig,\n type ValueCandidates,\n} from '../analysis/index.js';\nimport type { KernelContext } from './execute.js';\nimport { abortWith } from './abort.js';\nimport { isCalledOff } from './failures.js';\nimport { hasError } from './runtimeStore.js';\nimport { withScopeFilter } from './scope.js';\n\n/**\n * The values a condition on one field may be picked from, counted from the\n * data (`valueCandidatesConfig`). Handed out by `ViewRuntime.valueCandidates`\n * once per field, so an editor may key an effect on it.\n */\nexport interface ValueCandidateSource {\n /** The field whose values these are, as the condition names it. */\n readonly field: string;\n /**\n * The most frequent values holding `query` (all of them while it is\n * blank). Rejects with what the source threw, and with the signal's reason\n * once it aborts.\n */\n search(query: string, signal?: AbortSignal): Promise<ValueCandidates>;\n}\n\n/**\n * Every candidate source of one data view, and what they have answered.\n *\n * An answer is kept for the life of the view, keyed by field and by what was\n * typed: a condition reopened, or a second condition on the same field, asks\n * nothing again. What narrows without asking is narrowed here — once the\n * unnarrowed list came back whole there is nothing more the source could\n * add, and a field that offers no substring or prefix condition cannot be\n * narrowed by the source at all — so the source is asked only for a question\n * whose answer is not already in hand.\n *\n * The answers belong to the scope they were asked under. A host that\n * narrows the view to another tenant is asking about other records, so\n * `reset` forgets them, and an answer still on its way from before is not\n * kept.\n */\nexport class ValueCandidateSources {\n private readonly sources = new Map<string, ValueCandidateSource | null>();\n private readonly answers = new Map<string, ValueCandidates>();\n private generation = 0;\n /** The scope the answers in hand were asked under (`scoped`). */\n private askedUnder: FilterTree | null = null;\n\n constructor(\n private readonly context: KernelContext,\n private readonly scope: () => FilterTree | null,\n ) {}\n\n /** The source of `field`, or `null` when its values are not offered. */\n of(name: string): ValueCandidateSource | null {\n if (!this.sources.has(name)) {\n const { definition, kinds } = this.context;\n const field = valueCandidateField(definition, name, kinds);\n this.sources.set(\n name,\n field\n ? {\n field: name,\n search: (query, signal) => this.search(field, query, signal),\n }\n : null,\n );\n }\n return this.sources.get(name) ?? null;\n }\n\n /** Forgets every answer: the scope they were asked under has changed. */\n reset(): void {\n this.generation += 1;\n this.answers.clear();\n }\n\n private async search(\n field: FieldDefinition,\n query: string,\n signal?: AbortSignal,\n ): Promise<ValueCandidates> {\n const { kinds } = this.context;\n const scope = this.scoped();\n const text = query.trim();\n if (!text) return this.ask(field, '', scope, signal);\n const whole = this.answers.get(keyOf(field.name, ''));\n const narrowable = valueCandidateNarrowing(field, kinds) !== null;\n if (whole?.complete || !narrowable) {\n const all = whole ?? (await this.ask(field, '', scope, signal));\n return {\n values: narrowValueCandidates(all.values, field, kinds, text),\n complete: all.complete,\n };\n }\n return this.ask(field, text, scope, signal);\n }\n\n /**\n * The scope in force now. Answers asked under another are forgotten, so\n * whatever moved it — a host's condition, a board's fixed scope, a value\n * the host holds — the values are counted again rather than read from\n * before, whether or not anyone called `reset`.\n */\n private scoped(): FilterTree | null {\n const scope = this.scope();\n if (!dequal(scope, this.askedUnder)) {\n this.reset();\n this.askedUnder = scope;\n }\n return scope;\n }\n\n private async ask(\n field: FieldDefinition,\n text: string,\n scope: FilterTree | null,\n signal?: AbortSignal,\n ): Promise<ValueCandidates> {\n const key = keyOf(field.name, text);\n const known = this.answers.get(key);\n if (known) return known;\n const { definition, kinds, limits, environment, source } = this.context;\n const config = withScopeFilter<AnalysisViewConfig>(\n valueCandidatesConfig(definition, field, kinds, text, limits),\n scope,\n );\n // Admitted like any analysis, so a definition that cannot take the\n // question — a ceiling below one row, a scope its fields refuse — is told\n // here rather than by the service.\n const issues = validateAnalysis(definition, config, kinds, { limits });\n if (hasError(issues))\n throw new Error(\n `The values of ${field.name} cannot be asked for: ${issues\n .filter(found => found.severity === 'error')\n .map(found => found.code)\n .join(', ')}`,\n );\n const query = compileAnalysis(\n definition,\n config,\n kinds,\n {\n now: environment.now(),\n timeZone: environment.timeZone,\n },\n limits,\n );\n const generation = this.generation;\n const rows = await source\n .aggregate(query, undefined, abortWith(signal))\n .catch((error: unknown) => {\n // The editor says the values could not be read; the host hears why.\n if (!isCalledOff(error, signal))\n void this.context.queryFailed('candidates', error);\n throw error;\n });\n signal?.throwIfAborted();\n const answer = readValueCandidates(definition, config, rows, limits);\n if (generation === this.generation) this.answers.set(key, answer);\n return answer;\n }\n}\n\nfunction keyOf(field: string, text: string): string {\n return `${field}\\u0000${text}`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { issue } from '../filter/index.js';\nimport {\n isViewStoreError,\n type Issue,\n type ViewStoreError,\n} from '../model/index.js';\nimport { sourceReason } from './sourceReason.js';\nimport { isViewCommandError, isViewWriteError } from './write.js';\n\n/**\n * One Issue for whatever a command threw, so a caller renders a single\n * shape. A refusal already carries its Issue; a store failure keeps its code;\n * anything else keeps its message.\n *\n * It lives here rather than in `/react` because the engine itself has to\n * say what a store's failure was — a list that could not be read is an\n * answer with a reason in it, not an exception (see `ViewEngine.list`).\n */\nexport function toIssue(error: unknown, code: string): Issue {\n return commandIssue(error, code) ?? messageIssue(error, code);\n}\n\n/**\n * `toIssue` for a failure that may have come from a source: a query or an\n * export over the host's data. What the engine's own commands and stores\n * say is read as `toIssue` reads it; anything else is asked for the\n * source's own reason (`sourceReason`), which may take reading a body.\n */\nexport async function sourceIssue(\n error: unknown,\n code: string,\n): Promise<Issue> {\n return (\n commandIssue(error, code) ??\n issue(code, [], { reason: await sourceReason(error) })\n );\n}\n\n/** The issue an engine command or store failure already names, if it is one. */\nfunction commandIssue(error: unknown, code: string): Issue | null {\n if (isViewCommandError(error)) return error.issue;\n if (isViewWriteError(error))\n return error.state.kind === 'rejected'\n ? error.state.issue\n : issue(`${code}.${error.state.kind}`, []);\n if (isViewStoreError(error))\n return issue(`${code}.${storeOutcome(error)}`, [], {\n reason: error.message,\n });\n return null;\n}\n\n/**\n * The outcome a store failure is said by: its code, and for `UNAVAILABLE`\n * whether the server answered (`unavailable.server`, 「服务端暂时无法处理」)\n * or nothing came back (`unavailable`, 「无法连接服务端」) — the two send an\n * operator to different places. A catalogue without the longer key falls\n * back along the dots.\n */\nexport function storeOutcome(error: ViewStoreError): string {\n const outcome = error.code.toLowerCase();\n return error.code === 'UNAVAILABLE' && error.reachable\n ? `${outcome}.server`\n : outcome;\n}\n\nfunction messageIssue(error: unknown, code: string): Issue {\n return issue(code, [], {\n reason: error instanceof Error ? error.message : String(error),\n });\n}\n\n/**\n * Why one whole record could not be read (`fetchRecord`): refused to this\n * reader — the source answered 401 or 403 — or failed, in the source's own\n * words either way. A refusal is its own sentence because it is the one a\n * reader cannot fix by trying again: a link to a record of another tenant\n * says so, rather than \"could not be read\".\n */\nexport async function recordReadIssue(error: unknown): Promise<Issue> {\n return sourceIssue(\n error,\n refused(error) ? 'record.detail.forbidden' : 'record.detail.failed',\n );\n}\n\n/** Whether a source's rejection is an HTTP refusal of the reader. */\nfunction refused(error: unknown): boolean {\n if (typeof error !== 'object' || error === null || !('exchange' in error))\n return false;\n const { exchange } = error as { exchange?: { response?: unknown } };\n const response = exchange?.response;\n const status =\n typeof response === 'object' && response !== null && 'status' in response\n ? response.status\n : undefined;\n return status === 401 || status === 403;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What a view's config uses that its source no longer admits (capabilities.md\n * Q2), and taking it out.\n *\n * The findings are the ones admission raises against the definition as the\n * source's descriptor narrowed it and does not raise against the definition\n * as declared: the config was fine, the deployment is what changed. The\n * view waits to be fixed, as for any error, and nothing is sent; this is the\n * one-click fix 「移除不可用的条件」 offers.\n */\n\nimport {\n without,\n type AnalysisViewConfig,\n type DataViewConfig,\n type FilterTree,\n type Issue,\n type IssuePath,\n} from '../model/index.js';\nimport {\n isEmptyFilter,\n isFilterGroup,\n isFilterLeaf,\n nodeAt,\n removeConditionAt,\n sameFilterTree,\n updateAt,\n walkFilter,\n type FilterPath,\n} from '../filter/index.js';\n\n/** The errors of `effective` that `declared` does not have. */\nexport function unavailableIssues(\n effective: readonly Issue[],\n declared: readonly Issue[],\n): Issue[] {\n const known = new Set(declared.filter(isError).map(found => keyOf(found)));\n return effective.filter(\n found =>\n isError(found) &&\n !known.has(keyOf(found)) &&\n // A view with no condition where the source wants one uses nothing\n // it lacks: it has not asked yet, and says so as its own state (Q3).\n found.code !== 'record.filter.required',\n );\n}\n\n/**\n * The config with the first finding that can be taken out taken out, or\n * `null` when none of them can: a condition goes (a filter's own or a\n * metric's), a sort entry goes, 「只保留」 goes whole, a dimension keeps\n * its field but loses the missing-value group or the filled gaps. A\n * dimension or a metric the source cannot compute stays — taking it out\n * would change the question, not trim it — and is left to the reader.\n */\nexport function withoutFirstUnavailable<C extends DataViewConfig>(\n config: C,\n issues: readonly Issue[],\n): C | null {\n for (const found of issues) {\n const next = without1(config, found);\n if (next) return next;\n }\n return null;\n}\n\nfunction without1<C extends DataViewConfig>(config: C, found: Issue): C | null {\n const [head, index, member] = found.path;\n if (head === 'children') {\n const filter = removedAt(config.filter, found.path);\n return filter ? { ...config, filter } : null;\n }\n if (head === 'sort' && typeof index === 'number') {\n const sort = (config.sort as unknown[]).filter((_, i) => i !== index);\n return { ...config, sort };\n }\n if (config.kind !== 'analysis') return null;\n if (head === 'having' && config.having !== undefined) {\n const next: AnalysisViewConfig = { ...config };\n delete next.having;\n return next as C;\n }\n if (head === 'groups' && typeof index === 'number') {\n const group = config.groups[index];\n if (!group || (member !== 'missingKey' && member !== 'dense')) return null;\n const groups = config.groups.map((entry, i) =>\n i === index ? without(entry as never, member) : entry,\n );\n return { ...config, groups };\n }\n if (head === 'metrics' && typeof index === 'number' && member === 'filter') {\n const metric = config.metrics[index];\n if (!metric || !('filter' in metric) || !metric.filter) return null;\n const filter = trimmed(metric.filter, found);\n if (!filter) return null;\n const metrics = config.metrics.map((entry, i) =>\n i === index ? { ...entry, filter } : entry,\n );\n return { ...config, metrics };\n }\n return null;\n}\n\n/**\n * A metric's condition less what the finding is about: the node it points\n * into, or every condition on the field it names.\n */\nfunction trimmed(tree: FilterTree, found: Issue): FilterTree | null {\n const inner = found.path.slice(3);\n if (inner[0] === 'children') return removedAt(tree, inner);\n const field = found.params?.field;\n if (typeof field !== 'string') return null;\n const paths: FilterPath[] = [];\n for (const visit of walkFilter(tree))\n if (isFilterLeaf(visit.node) && visit.node.field === field)\n paths.push(\n visit.path.filter((step): step is number => typeof step === 'number'),\n );\n if (paths.length === 0) return null;\n // The deepest and last first, so an earlier path still points where it did.\n return changed(\n tree,\n paths.reverse().reduce((next, path) => removeConditionAt(next, path), tree),\n );\n}\n\n/**\n * One tree an issue path passes through, and where in it: the filter\n * itself, then the predicate of each element match the path goes on into.\n */\ninterface Level {\n tree: FilterTree;\n at: FilterPath;\n}\n\n/**\n * The tree without the node an issue path points into, or `null` when the\n * path points at nothing that can go — so a caller never takes an unchanged\n * tree for progress. A path that goes on past a leaf goes into the leaf's\n * predicate (an element match's, #3608): a kind that validates a nested\n * tree reports its findings under the leaf's own path, and the step into\n * `value` is not written out. An element match left with no condition asks\n * nothing of its elements and goes with it.\n */\nfunction removedAt(tree: FilterTree, path: IssuePath): FilterTree | null {\n const levels = levelsOf(tree, path);\n let next: FilterTree | null = null;\n for (let i = levels.length - 1; i >= 0; i -= 1) {\n const { tree: current, at } = levels[i];\n if (next === null) {\n if (at.length === 0) continue;\n next = removeConditionAt(current, at);\n } else if (isEmptyFilter(next)) {\n next = removeConditionAt(current, at);\n } else {\n const value = next;\n next = updateAt(current, at, leaf => ({ ...leaf, value }) as never);\n }\n }\n return next && changed(tree, next);\n}\n\n/** The trees an issue path passes through, outermost first. */\nfunction levelsOf(tree: FilterTree, path: IssuePath): Level[] {\n const levels: Level[] = [{ tree, at: [] }];\n for (let i = 0; i + 1 < path.length && path[i] === 'children';) {\n const index = path[i + 1];\n if (typeof index !== 'number') break;\n const level = levels[levels.length - 1];\n const node = nodeAt(level.tree, level.at);\n if (isFilterGroup(node)) {\n level.at = [...level.at, index];\n i += 2;\n } else if (isFilterLeaf(node) && isFilterGroup(node.value)) {\n levels.push({ tree: node.value, at: [] });\n } else break;\n }\n return levels;\n}\n\n/** `after`, or `null` when it says what `before` did. */\nfunction changed(before: FilterTree, after: FilterTree): FilterTree | null {\n return sameFilterTree(before, after) ? null : after;\n}\n\nfunction isError(found: Issue): boolean {\n return found.severity === 'error';\n}\n\nfunction keyOf(found: Issue): string {\n return `${found.code} ${JSON.stringify(found.path)}`;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n type DataViewConfig,\n overlaid,\n type FieldDefinition,\n type FilterTree,\n type Issue,\n type RecordPageTarget,\n type RuntimeLimits,\n type ViewInstance,\n} from '../model/index.js';\nimport type { FieldKindRegistry } from '../filter/index.js';\nimport { periodRollover } from '../analysis/index.js';\nimport {\n NO_REFUSAL,\n scopeRefusal,\n withScopeFilter,\n withoutScopeModeWarning,\n} from './scope.js';\nimport type { RuntimeEnvironment, ViewErrorKind } from './environment.js';\nimport {\n failureReporter,\n queryFailureReporter,\n viewPlace,\n type FailureReporter,\n} from './failures.js';\nimport { hasError, RuntimeStore } from './runtimeStore.js';\nimport { AUTO_APPLY_DELAY_MS, autoApplyDue } from './autoApply.js';\nimport { sourceFailure, type SourceFailure } from './sourceReason.js';\nimport {\n failedExecutionIssue,\n failedQuery,\n isForbiddenQuery,\n} from './queryFailure.js';\nimport { RefreshTimer } from './refreshTimer.js';\nimport {\n isRequestSuperseded,\n RequestQueueFullError,\n type RequestRunner,\n} from './requestRunner.js';\nimport type { OptionSource, ProjectedView } from './source.js';\nimport {\n executeDataConfig,\n validateDataConfig,\n type KernelContext,\n} from './execute.js';\nimport {\n ValueCandidateSources,\n type ValueCandidateSource,\n} from './valueCandidates.js';\nimport type { WriteState } from './write.js';\nimport { toIssue } from './issues.js';\nimport {\n checksDescriptorAgain,\n withCanonicalState,\n} from '../capabilities/index.js';\nimport { unavailableIssues, withoutFirstUnavailable } from './unavailable.js';\nimport type {\n DefinitionFor,\n ManagedViewRuntime,\n RuntimeCapabilities,\n ViewQueryState,\n ViewRuntimeOptions,\n ViewRuntimeState,\n} from './viewRuntimeTypes.js';\n\nconst IDLE: ViewQueryState = { status: 'idle' };\n\n/** Enough for any config a person wrote; a bound on a loop, not a budget. */\nconst MAX_REMOVALS = 256;\n\n/**\n * The runtime of a data view: an Analysis view as it is, and the shared\n * half of a Record view (`RecordDataViewRuntime`).\n *\n * It owns no persistence: saving is a command of `ViewEngine`, which calls\n * `markSaved` once the store has confirmed it.\n *\n * The store half of it — the snapshot, the subscribers, the refresh timer and\n * dirty-against-saved — is `RuntimeStore`, which the dashboard runtime holds\n * one of as well; what is left here is what it means to be a data view: ask,\n * run, land. What only a Record view has — a page, a selection, an export, a\n * record read whole — is its subclass's, reached through four hooks\n * (`startOver`, `pageNow`, `settle`, `holds`) rather than kind checks here.\n */\nexport class DataViewRuntime<\n C extends DataViewConfig = DataViewConfig,\n> implements ManagedViewRuntime<C> {\n readonly id: string;\n readonly kind: C['kind'];\n readonly kinds: FieldKindRegistry;\n readonly environment: RuntimeEnvironment;\n\n protected readonly store: RuntimeStore<ViewRuntimeState<C>>;\n protected readonly context: KernelContext;\n private readonly runner: RequestRunner;\n private readonly resolveOptions: ((key: string) => OptionSource) | undefined;\n private readonly autoRefresh: boolean;\n /** What the source admits, followed while open; see `renarrow`. */\n private readonly capabilities: RuntimeCapabilities | undefined;\n private readonly stopFollowing: () => void;\n /**\n * Why the definition cannot run at all under the source's current\n * descriptor, said at the head of every admission until it changes again.\n */\n private refusal: Issue | null = null;\n /** Whether a host lets the view refresh itself (`setAutoRefresh`). */\n private refreshing = true;\n /** The one timer behind 「改了就跑」, stopped whenever nothing is due. */\n private readonly autoTimer: RefreshTimer;\n private readonly candidates: ValueCandidateSources;\n\n private injectedScope: FilterTree | null = null;\n /**\n * Whether `applied` merged with the scope passed admission. `apply` and\n * `setScopeFilter` only promote what did, so this is false only for the\n * config a runtime opened on, and it keeps `refresh` and `page` from running\n * what `apply` would refuse.\n */\n protected appliedAdmitted: boolean;\n private requestSeq = 0;\n\n constructor(options: ViewRuntimeOptions<C>) {\n this.id = options.id;\n this.kind = options.config.kind;\n this.kinds = options.kinds;\n this.resolveOptions = options.resolveOptions;\n this.runner = options.runner;\n this.environment = options.environment;\n this.autoRefresh = options.autoRefresh ?? true;\n this.capabilities = options.capabilities;\n this.autoTimer = new RefreshTimer(options.environment, () => this.apply());\n this.context = {\n definition: options.definition,\n kinds: options.kinds,\n limits: options.limits,\n environment: options.environment,\n source: options.source,\n queryFailed: queryFailureReporter(options.environment, () =>\n viewPlace(this),\n ),\n };\n this.candidates = new ValueCandidateSources(\n this.context,\n () => this.injectedScope,\n );\n\n const saved = options.saved ?? null;\n // An injected condition is in force from the first query, so it is\n // admitted with the config rather than after it. Without this, a host\n // that scopes a view to one customer would have its opening query go\n // out unscoped. What the definition refuses, though, is the host's\n // condition and not this view's defect, so it is left out rather than\n // written into the view's issues (D17-5): the view runs un-narrowed and\n // `refusedScope` says which condition did not take — the same answer a\n // scope refused later gets, said in the same words.\n const wanted = options.scopeFilter ?? null;\n const own = this.admit(options.config, null);\n const merged = wanted === null ? own : this.admit(options.config, wanted);\n const refusedScope = scopeRefusal(own, merged);\n const refused = refusedScope.length > 0;\n this.injectedScope = refused ? null : wanted;\n const issues = refused ? own : merged;\n this.appliedAdmitted = !hasError(issues);\n this.store = new RuntimeStore<ViewRuntimeState<C>>({\n state: {\n saved,\n title: options.title,\n scope: options.scope,\n draft: options.config,\n applied: options.config,\n issues,\n dirty: saved === null,\n query: IDLE,\n result: null,\n selection: [],\n write: null,\n editing: false,\n autoApply: false,\n nextRefreshAt: null,\n },\n environment: options.environment,\n refusedScope,\n admit: draft => this.admit(draft),\n apply: () => this.apply(),\n refresh: () => this.refresh(),\n // A panel inside a dashboard is timed by the board, so it holds its own\n // timer for good; otherwise it is held while its one request is in\n // flight, and for whatever reason of its own the kind has (`holds`).\n holding: () =>\n !this.autoRefresh ||\n !this.refreshing ||\n this.state.query.status === 'loading' ||\n // Refused the reader: asking again on a clock would only be refused\n // again, and told to the host each time. A press of refresh, or an\n // apply, still asks.\n isForbiddenQuery(this.state.query.error) ||\n this.holds(),\n release: () => this.runner.cancel(this.id),\n // A panel inside a dashboard is asked again by the board, which reads\n // this for each panel on screen (`rolloverAt`).\n expiresAt: () => (this.autoRefresh ? this.rolloverAt() : null),\n });\n this.stopFollowing =\n options.capabilities?.watch(() => this.renarrow()) ?? (() => {});\n }\n\n /**\n * When the answer on screen stops being true of its own accord: a metric\n * card over a trend skipped the period under way when it was asked, and\n * that period has ended by then (`periodRollover`). The chart read is the\n * draft's — how the rows are looked at is the draft's to say (D20) — over\n * the config that ran them. `null` for anything else.\n */\n rolloverAt(): number | null {\n const result = this.state.result;\n if (!result || result.data.kind !== 'analysis') return null;\n const draft = this.state.draft;\n if (draft.kind !== 'analysis' || result.config.kind !== 'analysis')\n return null;\n const askedAt = result.receivedAt - result.elapsedMs;\n const left = periodRollover(\n { ...result.config, chart: draft.chart },\n result.data.view.rows,\n { timeZone: this.environment.timeZone, now: new Date(askedAt) },\n );\n return left === undefined ? null : askedAt + left;\n }\n\n /** The definition in force: the declared one as the source narrows it now. */\n get definition(): DefinitionFor<C> {\n // `C extends DataViewConfig` makes `DefinitionFor<C>` a data definition,\n // which the compiler cannot prove while `C` is still a parameter.\n return this.context.definition as DefinitionFor<C>;\n }\n\n /** The budgets in force: the host's, and the source's where it says them. */\n get limits(): RuntimeLimits {\n return this.context.limits;\n }\n\n get disposed(): boolean {\n return this.store.disposed;\n }\n\n /** See `ViewRuntime.refusedScope`; the store keeps it. */\n get refusedScope(): Issue[] {\n return this.store.refusedScope;\n }\n\n /** The snapshot the store holds; every command reads it and patches it back. */\n protected get state(): ViewRuntimeState<C> {\n return this.store.state;\n }\n\n get fields(): readonly FieldDefinition[] {\n return this.context.definition.fields;\n }\n\n /** The injected condition in force; see `ViewRuntime.scopeFilter`. */\n get scopeFilter(): FilterTree | null {\n return this.injectedScope;\n }\n\n getSnapshot(): ViewRuntimeState<C> {\n return this.store.getSnapshot();\n }\n\n subscribe(listener: () => void): () => void {\n return this.store.subscribe(listener);\n }\n\n optionSource(remote: string): OptionSource | null {\n return this.resolveOptions ? this.resolveOptions(remote) : null;\n }\n\n valueCandidates(field: string): ValueCandidateSource | null {\n return this.candidates.of(field);\n }\n\n edit(patch: Partial<C>): void {\n if (this.disposed) return;\n // A member given as `undefined` is taken out (`overlaid`): an editor\n // that took the last entry out of an optional list left the view\n // unsaved for the rest of the session otherwise, `dirty` being an\n // equality against the saved config.\n const draft = overlaid(this.state.draft, patch);\n this.store.setState({\n draft,\n issues: this.admit(draft),\n dirty: this.store.isDirty(draft, this.state.saved),\n });\n this.syncAutoApply();\n }\n\n apply(): void {\n if (this.disposed || hasError(this.state.issues)) return;\n this.appliedAdmitted = true;\n this.autoTimer.stop();\n // A draft that asks the source what the rows on screen already answer\n // lands without the page being fetched again (`restyle`).\n const restyle = this.restyle(this.state.draft);\n if (restyle) {\n this.store.setState({ applied: this.state.draft });\n restyle();\n return;\n }\n this.store.setState({ applied: this.state.draft, ...this.startOver() });\n this.execute({ keepSelection: false });\n }\n\n /**\n * How `draft` lands when it changes only how the rows on screen are drawn,\n * or `null` when it is a new question and runs whole. A Record view\n * answers for its columns and its summary row (`restyledOnly`); an\n * analysis has nothing of the kind.\n */\n protected restyle(draft: C): (() => void) | null {\n void draft;\n return null;\n }\n\n /** Discards the edits and re-runs what was saved; see `RuntimeStore.revert`. */\n revert(): void {\n this.store.revert();\n this.syncAutoApply();\n }\n\n setAutoApply(on: boolean): void {\n if (this.disposed || this.state.autoApply === on) return;\n this.store.setState({ autoApply: on });\n this.syncAutoApply();\n }\n\n /**\n * Arms the auto-apply timer while the draft is due to run on its own and\n * stops it otherwise. Re-arming on every edit is what merges a burst of\n * edits into one query: the timer restarts from the last one.\n */\n private syncAutoApply(): void {\n if (this.disposed || !autoApplyDue(this.state)) {\n this.autoTimer.stop();\n return;\n }\n this.autoTimer.stop();\n this.autoTimer.sync(AUTO_APPLY_DELAY_MS);\n }\n\n /**\n * Re-runs what was applied, which was admitted before it ran. An invalid\n * draft therefore does not block it: the editor may be mid-edit and wrong,\n * while the results on screen answer a question that was legal when asked.\n * Auto-refresh still pauses on an invalid draft — it is one of the reasons\n * `syncTimer` below holds the timer — but a user pressing Refresh has asked\n * for exactly this.\n */\n refresh(): void {\n if (this.disposed || !this.appliedAdmitted) return;\n // A refresh is a moment to check what the source admits; a descriptor\n // younger than its maximum age is left alone, so the timer's refreshes\n // cost nothing here (capabilities.md 6).\n this.capabilities?.revalidate();\n // The values a condition is offered are the data's, and a refresh is\n // the data read again: offering them from before it would list values\n // the rows no longer hold, with counts they no longer have.\n this.candidates.reset();\n // A refresh reads the page the reader is on again — the timer's, the\n // button's and the one a command asks for after writing alike: sending\n // them to the first page lost their place in a list they were working\n // through. The selection keeps whatever rows survive.\n this.execute({ keepSelection: true });\n }\n\n setEditing(active: boolean): void {\n if (this.disposed || this.state.editing === active) return;\n this.store.setState({ editing: active });\n }\n\n setAutoRefresh(on: boolean): void {\n if (this.disposed || this.refreshing === on) return;\n this.refreshing = on;\n this.store.retime();\n }\n\n setScopeFilter(tree: FilterTree | null): Issue[] {\n if (this.disposed) return this.refusedScope;\n // Re-injecting the same condition changes nothing, and a dashboard does\n // exactly that whenever a layout edit is applied. What is asked for is\n // what is in force, so nothing stands refused either.\n if (dequal(tree ?? null, this.injectedScope))\n return this.store.refuse(NO_REFUSAL);\n const own = this.admit(this.state.applied, null);\n const merged = this.admit(this.state.applied, tree);\n // An injected condition is admitted exactly like a user's own — but only\n // what it alone breaks keeps it out. A view already waiting to be fixed\n // is not fixed by refusing the host's condition too.\n if (this.store.refuse(scopeRefusal(own, merged)).length > 0)\n return this.refusedScope;\n\n this.injectedScope = tree ?? null;\n this.candidates.reset();\n this.appliedAdmitted = !hasError(merged);\n // The draft is judged with the scope too, so its issues move with it.\n this.store.setState({\n issues: this.admit(this.state.draft),\n ...this.startOver(),\n });\n if (this.appliedAdmitted) this.execute({ keepSelection: false });\n return this.refusedScope;\n }\n\n /** A record or an analysis config means the same thing in every scope. */\n issuesAt(): Issue[] {\n return this.state.issues;\n }\n\n /** Called by `ViewEngine` once a write has been confirmed by the store. */\n markSaved(instance: ViewInstance): void {\n if (this.disposed) return;\n this.moveBaseline(instance);\n this.store.setState({ write: null });\n }\n\n moveBaseline(stored: ViewInstance): void {\n if (this.disposed) return;\n this.store.setState(this.store.baseline(stored));\n }\n\n /** Replaces the draft with the store's state, used by \"reload\" on a conflict. */\n adoptSaved(instance: ViewInstance): void {\n if (this.disposed) return;\n const draft = instance.config as C;\n this.store.setState({\n saved: instance,\n title: instance.title,\n scope: instance.scope,\n draft,\n issues: this.admit(draft),\n dirty: false,\n write: null,\n });\n }\n\n /** Called by `ViewEngine` with the outcome of a write it dispatched. */\n setWrite(write: WriteState | null): void {\n if (this.disposed) return;\n this.store.setState({ write });\n }\n\n dispose(): void {\n this.stopFollowing();\n this.autoTimer.stop();\n this.candidates.reset();\n this.store.dispose();\n }\n\n /** See `ViewRuntime.unavailable`. */\n unavailable(): Issue[] {\n const declared = this.capabilities?.declared;\n if (!declared || declared === this.context.definition) return [];\n const draft = withScopeFilter(this.state.draft, this.injectedScope);\n return unavailableIssues(\n this.state.issues,\n validateDataConfig({ ...this.context, definition: declared }, draft),\n );\n }\n\n /** See `ViewRuntime.removeUnavailable`. */\n removeUnavailable(): void {\n if (this.disposed) return;\n let draft = this.state.draft;\n // One at a time, judged again after each: a condition taken out moves\n // the paths of the ones after it, and may take another finding with it.\n for (let step = 0; step < MAX_REMOVALS; step += 1) {\n const next = withoutFirstUnavailable(draft, this.unavailableOf(draft));\n if (!next) break;\n draft = next;\n }\n if (draft === this.state.draft) return;\n this.store.setState({\n draft,\n issues: this.admit(draft),\n dirty: this.store.isDirty(draft, this.state.saved),\n });\n this.syncAutoApply();\n }\n\n /**\n * Takes the source's current descriptor: the definition and the limits\n * narrowed again, the draft and the applied config judged again. A config\n * still admitted keeps its result on screen — only what the editors offer\n * moves; one that is not waits to be fixed like any error, and nothing\n * more is sent for it (capabilities.md 6「版本变了」, Q2).\n */\n private renarrow(): void {\n if (this.disposed || !this.capabilities) return;\n try {\n const { definition, limits } = this.capabilities.effective();\n this.refusal = null;\n this.context.definition = definition;\n this.context.limits = limits;\n this.renameFields(definition.narrowing?.renamed ?? {});\n } catch (error) {\n this.refusal = toIssue(error, 'view.definition.invalid');\n }\n this.candidates.reset();\n this.appliedAdmitted = !hasError(this.admit(this.state.applied));\n this.store.setState({ issues: this.admit(this.state.draft) });\n this.store.retime();\n }\n\n /**\n * The configs the view holds, read under the paths a new narrowing\n * renames aliases to (#3519): what it applied, what it drafts and what\n * it was saved as, so a view asks by the names the source answers by.\n */\n private renameFields(renamed: Readonly<Record<string, string>>): void {\n const patch = withCanonicalState(this.state, renamed);\n if (patch) this.store.setState(patch);\n }\n\n private unavailableOf(draft: C): Issue[] {\n const declared = this.capabilities?.declared;\n if (!declared) return [];\n const scoped = withScopeFilter(draft, this.injectedScope);\n return unavailableIssues(\n this.admit(draft),\n validateDataConfig({ ...this.context, definition: declared }, scoped),\n );\n }\n\n /**\n * What a new question starts from, merged into the state it is put in\n * force with — by `apply`, and by a new injected scope. An analysis has\n * nothing to reset; a Record view goes back to its first page and lets\n * its selection go.\n */\n protected startOver(): Partial<ViewRuntimeState<C>> {\n return {};\n }\n\n /** The page a query asks for; an analysis has none. */\n protected pageNow(): RecordPageTarget | undefined {\n return undefined;\n }\n\n /**\n * What else a landed answer changes, or `null` to ask again instead — a\n * Record view whose page the result shrank out from under asks for the\n * last page there is. `keepSelection` is whether the query was a refresh.\n */\n protected settle(\n data: ProjectedView,\n keepSelection: boolean,\n ): Partial<ViewRuntimeState<C>> | null {\n void data;\n void keepSelection;\n return {};\n }\n\n /** A reason of the kind's own to hold the refresh timer. */\n protected holds(): boolean {\n return false;\n }\n\n /**\n * Admission of a config together with the scope it would run under. Every\n * judgement in this class goes through here, so the draft, the applied\n * config and an injected condition are all held to one rule.\n */\n private admit(\n config: C,\n scope: FilterTree | null = this.injectedScope,\n ): Issue[] {\n const found = withoutScopeModeWarning(\n validateDataConfig(this.context, withScopeFilter(config, scope)),\n config,\n scope,\n );\n return this.refusal ? [this.refusal, ...found] : found;\n }\n\n protected execute(options: {\n keepSelection: boolean;\n /** When the question was first asked, for a page asked again. */\n askedAt?: number;\n /**\n * What is fetched, when it is less than the whole config: the summary\n * row alone over the rows on screen (`restyle`). The whole query when\n * left out.\n */\n fetch?: (config: C, controller: AbortController) => Promise<ProjectedView>;\n /**\n * Asked without the query turning `loading`: the rows on screen stay the\n * answer while the rest arrives, so nothing says 「正在查询」 over them\n * or draws the table as waiting (the summary row alone, `restyle`).\n */\n quiet?: boolean;\n }): void {\n const askedAt = options.askedAt ?? this.environment.now().getTime();\n // Both halves travel with the request: what ran, and the view's own\n // config it was merged from. `applied` may move on before the answer\n // arrives, and a summary reading it would describe another question.\n const own = this.state.applied;\n const config = withScopeFilter(own, this.injectedScope);\n const requestId = `${this.id}:${(this.requestSeq += 1)}`;\n const status = options.quiet ? 'success' : 'loading';\n this.store.setState({ query: { status, requestId } });\n\n this.runner\n .run(this.id, controller =>\n options.fetch\n ? options.fetch(config, controller)\n : executeDataConfig(this.context, config, this.pageNow(), controller),\n )\n .then(\n data =>\n this.onSuccess(\n requestId,\n config,\n own,\n data,\n options.keepSelection,\n askedAt,\n ),\n error => this.onFailure(requestId, own, config, error),\n );\n }\n\n private onSuccess(\n requestId: string,\n config: C,\n own: C,\n data: ProjectedView,\n keepSelection: boolean,\n askedAt: number,\n ): void {\n if (!this.isCurrent(requestId)) return;\n const settled = this.settle(data, keepSelection);\n if (settled === null) {\n this.execute({ keepSelection, askedAt });\n return;\n }\n const receivedAt = this.environment.now().getTime();\n const elapsedMs = Math.max(0, receivedAt - askedAt);\n const result = { config, own, data, receivedAt, elapsedMs };\n this.store.setState({\n query: { status: 'success', requestId },\n result,\n ...settled,\n });\n }\n\n private onFailure(\n requestId: string,\n own: C,\n config: C,\n error: unknown,\n ): void {\n // A superseded request is the normal outcome of typing; it is not an error.\n if (isRequestSuperseded(error) || !this.isCurrent(requestId)) return;\n if (error instanceof RequestQueueFullError) {\n this.failed(requestId, own, config, error);\n return;\n }\n // The query stays in flight until the body is read, and a newer\n // request that started meanwhile wins. A kind may take the failure\n // back first (`recovers`): then nobody is told of it.\n void sourceFailure(error).then(failure => {\n // A refusal for a capability the descriptor admitted: the descriptor\n // may be behind, so it is checked again now (C5). A new version\n // narrows this view like any other (`renarrow`), and what it asked\n // with then waits to be fixed (Q2); the refusal is said either way,\n // at the condition its path names.\n if (\n this.capabilities &&\n checksDescriptorAgain({\n reason: failure.reason,\n ...(failure.violation ? { code: failure.violation.code } : {}),\n ...(failure.status === undefined ? {} : { status: failure.status }),\n })\n )\n void this.capabilities.recheck(failure.violation?.code);\n if (!this.isCurrent(requestId)) return;\n if (this.recovers(failure)) {\n this.execute({ keepSelection: false });\n return;\n }\n this.failed(requestId, own, config, error);\n });\n }\n\n private failed(requestId: string, own: C, config: C, error: unknown): void {\n // Told once, of a failure that was current when it landed: the host\n // hears of no request that had already been replaced. The report waits\n // for the body the source answered with, so it can say which rule a Wow\n // service said the query broke (D40); the Issue reads the same body.\n void this.context.queryFailed('query', error);\n const { definition } = this.context;\n void failedExecutionIssue(error, definition, own.filter).then(issue => {\n if (!this.isCurrent(requestId)) return;\n const query = failedQuery(issue, requestId, this.state.result, config);\n this.store.setState({ query });\n });\n }\n\n /**\n * Whether a kind takes a failure back and asks again instead: a Record\n * view whose cursor the source no longer reads starts over from the\n * first page, once. Nothing else does.\n */\n protected recovers(failure: SourceFailure): boolean {\n void failure;\n return false;\n }\n\n /**\n * Tells the host of a failure of this view's (D40), saying which view:\n * its definition, its saved id as it is at the moment of the failure, and\n * the runtime it failed in.\n */\n protected reporter(kind: ViewErrorKind): FailureReporter {\n return failureReporter(this.environment, kind, () => viewPlace(this));\n }\n\n private isCurrent(requestId: string): boolean {\n return !this.disposed && this.state.query.requestId === requestId;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The views one engine has open.\n *\n * A command is given a runtime or an instance id, and both have to come back\n * to this set: only a runtime the engine owns may be written through, and a\n * confirmed write concerns every open view of the instance it touched — an\n * instance may be open more than once.\n */\n\nimport type { ViewInstance } from '../model/index.js';\nimport { issue } from '../filter/index.js';\nimport { DataViewRuntime } from './viewRuntime.js';\nimport type { ManagedViewRuntime, ViewRuntime } from './viewRuntimeTypes.js';\nimport { DashboardViewRuntime } from './dashboardRuntime.js';\nimport { ViewCommandError } from './write.js';\n\nexport class OpenRuntimes {\n private readonly runtimes = new Set<ManagedViewRuntime>();\n\n add<R extends ManagedViewRuntime>(runtime: R): R {\n this.runtimes.add(runtime);\n return runtime;\n }\n\n /** Every open view, the ones disposed behind the engine's back dropped. */\n all(): ManagedViewRuntime[] {\n this.prune();\n return [...this.runtimes];\n }\n\n /** The runtime a write command may be addressed to: one the engine owns. */\n require(runtime: ViewRuntime): ManagedViewRuntime {\n if (!isManagedRuntime(runtime) || !this.runtimes.has(runtime))\n throw new ViewCommandError(issue('view.runtime.not-owned', []));\n return runtime;\n }\n\n /**\n * Open runtimes whose baseline is this instance, `first` ahead of the rest.\n * The engine allows an instance to be open more than once, and a confirmed\n * write to it concerns each of them.\n */\n holders(id: string, first?: ManagedViewRuntime): ManagedViewRuntime[] {\n const found = [...this.runtimes].filter(\n entry => entry !== first && entry.getSnapshot().saved?.id === id,\n );\n return first && this.runtimes.has(first) ? [first, ...found] : found;\n }\n\n /**\n * Closes one open view: disposes it and drops it from the registry.\n *\n * A caller that only calls `runtime.dispose()` leaves the engine holding a\n * dead runtime, which then answers `locate` with a revision nobody can write\n * against, so this is the way to let one go.\n */\n close(runtime: ViewRuntime): void {\n if (isManagedRuntime(runtime) && this.runtimes.has(runtime)) {\n this.forget(runtime);\n return;\n }\n runtime.dispose();\n }\n\n forget(runtime: ManagedViewRuntime): void {\n runtime.dispose();\n this.runtimes.delete(runtime);\n }\n\n disposeAll(): void {\n for (const runtime of [...this.runtimes]) runtime.dispose();\n this.runtimes.clear();\n }\n\n /**\n * The instance an open view of `id` was last saved as — its saved config,\n * never its draft — or null when none is open.\n */\n saved(id: string): ViewInstance | null {\n this.prune();\n return this.holders(id)[0]?.getSnapshot().saved ?? null;\n }\n\n /** Drops runtimes a caller disposed directly, which the registry cannot see. */\n prune(): void {\n for (const runtime of [...this.runtimes])\n if (runtime.disposed) this.runtimes.delete(runtime);\n }\n}\n\nfunction isManagedRuntime(runtime: ViewRuntime): runtime is ManagedViewRuntime {\n return (\n runtime instanceof DataViewRuntime ||\n runtime instanceof DashboardViewRuntime\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What the engine knows about instances it is not holding open: the last\n * summary each one was seen as.\n *\n * A command given only an id needs the revision to write against, the\n * definition whose list the view belongs to, and the scope the permission\n * guard judges by. An open runtime carries all three; a view that was only\n * ever listed does not, and re-reading the store for every rename in a list\n * of forty would be forty round trips for state the list just handed over.\n * So a listing is remembered here, a confirmed write updates it, and a\n * delete drops it — the same shape `preferences.ts` has, for the same\n * reason: a cache is one thing and a command surface is another.\n *\n * It is a cache and not a source of truth. `ViewEngine.locate` asks an open\n * runtime first, this second and the store last, and every write it feeds\n * still carries the revision the store will check.\n */\n\nimport {\n isSystemInstanceId,\n toSummary,\n type Issue,\n type ViewInstance,\n type ViewInstanceSummary,\n} from '../model/index.js';\nimport type { ViewStore } from '../store/ViewStore.js';\nimport { toIssue } from './issues.js';\n\n/**\n * The stored half of a definition's list, which may fail on its own: a\n * store that is down takes the saved views with it and nothing else, so the\n * failure is answered beside an empty list rather than thrown (management.md).\n * An id in the reserved `system:` namespace is dropped and handed to\n * `reserved`: only a definition may declare one.\n */\nexport async function storedSummaries(\n store: ViewStore,\n definitionId: string,\n reserved: (id: string) => void,\n): Promise<{ stored: ViewInstanceSummary[]; failed: Issue | null }> {\n try {\n const listed = await store.list(definitionId);\n const stored = listed.filter(summary => {\n if (!isSystemInstanceId(summary.id)) return true;\n reserved(summary.id);\n return false;\n });\n return { stored, failed: null };\n } catch (error) {\n return { stored: [], failed: toIssue(error, 'view.list.failed') };\n }\n}\n\nexport class SummaryCache {\n private readonly cache = new Map<string, ViewInstanceSummary>();\n\n /** Remembers a whole listing, declared system views included. */\n noteAll(summaries: readonly ViewInstanceSummary[]): void {\n for (const summary of summaries) this.cache.set(summary.id, summary);\n }\n\n /** Remembers the instance a write has just confirmed, as its summary. */\n note(instance: ViewInstance): void {\n this.cache.set(instance.id, toSummary(instance));\n }\n\n /** Forgets a view that is gone; nothing may be written against it again. */\n drop(id: string): void {\n this.cache.delete(id);\n }\n\n /** The last summary seen for `id`, or nothing when none ever was. */\n get(id: string): ViewInstanceSummary | undefined {\n return this.cache.get(id);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ViewConfig,\n ViewInstance,\n ViewPreferences,\n} from '../model/index.js';\nimport { tabsOf } from '../dashboard/index.js';\nimport { isViewWriteError, type WriteHandle } from './write.js';\n\n/** What the memory borrows of the engine: the preferences and their writes. */\nexport interface TabMemoryHost {\n /** The preferences a write starts from (`PreferenceCache.current`). */\n current(definitionId: string): Promise<ViewPreferences>;\n /** One preference write through the ledger. */\n write(definitionId: string, next: ViewPreferences): Promise<ViewPreferences>;\n /** Lets an unsettled write go, so it holds nothing else back. */\n abandon(handle: WriteHandle): void;\n}\n\n/**\n * Where each reader last read each dashboard (D22 E): kept in their\n * preferences for the board's definition (`ViewPreferences.lastTabs`), by\n * instance id, and where a board opens when its host names no tab.\n *\n * It is a convenience and nothing more, so it never rejects and never leaves\n * an outcome behind. A burst of tab switches writes the last one, once the\n * write in flight settles — the ledger lets one preference write out at a\n * time. A write that fails is let go: an unsettled preference write would\n * hold back the list's own reorder and default, which matter more than\n * which tab a board opens on.\n */\nexport class TabMemory {\n /** The tab each board is to be remembered on, by definition and instance. */\n private readonly wanted = new Map<string, string>();\n /** The boards whose write is out. */\n private readonly writing = new Set<string>();\n\n constructor(private readonly host: TabMemoryHost) {}\n\n async remember(\n definitionId: string,\n instanceId: string,\n tabId: string,\n ): Promise<void> {\n const key = `${definitionId}\\u0000${instanceId}`;\n this.wanted.set(key, tabId);\n if (this.writing.has(key)) return;\n this.writing.add(key);\n try {\n for (;;) {\n const wanted = this.wanted.get(key);\n const current = await this.host.current(definitionId);\n if (wanted === undefined || current.lastTabs?.[instanceId] === wanted)\n return;\n await this.host.write(definitionId, {\n ...current,\n lastTabs: { ...current.lastTabs, [instanceId]: wanted },\n });\n }\n } catch (error) {\n if (isViewWriteError(error)) this.host.abandon(error.handle);\n } finally {\n this.writing.delete(key);\n this.wanted.delete(key);\n }\n }\n\n /**\n * The tab a board opens on: the one asked for while the board has it,\n * else the one its reader last read it on; `null` for its first, and for\n * any view that is no board.\n */\n async opensOn(\n instance: ViewInstance,\n asked: string | null | undefined,\n ): Promise<string | null> {\n if (instance.config.kind !== 'dashboard') return null;\n if (hasTab(instance.config, asked)) return asked;\n try {\n const preferences = await this.host.current(instance.definitionId);\n const tab: unknown = preferences.lastTabs?.[instance.id];\n return typeof tab === 'string' ? tab : null;\n } catch {\n // The list reports a store that cannot read preferences; a board\n // opens on its first tab meanwhile.\n return null;\n }\n }\n}\n\n/** Whether a stored board has the tab named; a config is read as untrusted. */\nfunction hasTab(\n config: ViewConfig,\n tab: string | null | undefined,\n): tab is string {\n return (\n typeof tab === 'string' &&\n config.kind === 'dashboard' &&\n tabsOf(config).some(entry => entry.id === tab)\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CursorQuery, FilterPagedQuery } from '@ahoo-wang/wow-client';\nimport {\n FIRST_PAGE,\n compileRecord,\n lastPageInWindow,\n pageWindow,\n} from '../record/index.js';\nimport type { FilterCompileContext } from '../filter/index.js';\nimport {\n DEFAULT_RUNTIME_LIMITS,\n isNamedError,\n type RecordCapability,\n type RecordData,\n type RecordPageTarget,\n type RecordViewConfig,\n type RuntimeLimits,\n} from '../model/index.js';\nimport type { KernelContext } from './execute.js';\n\nexport interface ExportRowsOptions {\n /** Stops the run; the promise then rejects with an `ExportCancelledError`. */\n signal?: AbortSignal;\n /**\n * How far it has got: rows in hand, and how many there are in all when the\n * source says. A cursor source never says, which is why the total is\n * optional rather than a number nobody can compute.\n */\n onProgress?(fetched: number, total?: number): void;\n /** The ceiling; `limits.exportMax` when left out. */\n max?: number;\n}\n\nexport interface ExportedRows {\n rows: RecordData[];\n /** What the source said there are in all, when it says at all. */\n total?: number;\n /** True when the ceiling stopped it while the source still had rows. */\n capped: boolean;\n}\n\n/**\n * What a cancelled export rejects with. It is not a failure — nobody has to\n * be told about it — so the caller tells it apart rather than reporting it.\n */\nexport class ExportCancelledError extends Error {\n constructor() {\n super('The export was cancelled');\n this.name = 'ExportCancelledError';\n }\n}\n\n/** By name, as every guard of the engine's errors (`isViewStoreError`). */\nexport function isExportCancelledError(\n error: unknown,\n): error is ExportCancelledError {\n return isNamedError(error, 'ExportCancelledError');\n}\n\n/**\n * How an export pages its source: the size it asks for, and the most rows it\n * may carry away.\n *\n * The ceiling is `limits.exportMax`, and below it a paged source's window\n * (`pageWindow`: the runtime's `maxPageWindow`, or the definition's\n * `maxWindow` where it is the smaller): a page past the\n * window is refused outright, so an export that went on asking would fail on\n * the page after the last one it could have, having fetched every row before\n * it. The size shrinks to the window when the window is the smaller, and the\n * ceiling stops at the last whole page inside it — the same count the pager\n * stops at. `ExportDialog` states this ceiling before anything is fetched.\n */\nexport function exportPlan(\n limits: Pick<RuntimeLimits, 'exportMax' | 'maxPageSize'> &\n Partial<Pick<RuntimeLimits, 'maxPageWindow'>>,\n capability?: Partial<Pick<RecordCapability, 'maxWindow' | 'paging'>>,\n asked?: number,\n): { size: number; max: number } {\n // The ceiling is the one number that ends the fetch loop, so a host that\n // built its limits by hand and left it out gets the default rather than a\n // `NaN` that compares false against everything and pages a backend forever.\n const wanted = asked ?? limits.exportMax;\n const max = Number.isFinite(wanted)\n ? Math.floor(wanted)\n : DEFAULT_RUNTIME_LIMITS.exportMax;\n const window = pageWindow(capability, limits);\n const size = Math.max(\n 1,\n Math.min(\n Math.floor(limits.maxPageSize) || DEFAULT_RUNTIME_LIMITS.maxPageSize,\n window ?? Infinity,\n ),\n );\n const pages = lastPageInWindow(size, window);\n return { size, max: pages === undefined ? max : Math.min(max, pages * size) };\n}\n\n/**\n * Every row the applied conditions match, paged out of the source behind the\n * screen.\n *\n * It is a query of its own and deliberately beside the runtime's: it takes no\n * scheduler slot, never becomes `state.result` and cannot supersede — or be\n * superseded by — what the user is looking at. Export is a read the user asked\n * for *in addition to* the view, and a view that emptied itself because an\n * export was running would be the worse answer.\n *\n * The page size is the runtime's `maxPageSize` rather than the view's, since\n * the page on screen has nothing to do with it: the fewer round trips the\n * better, and that ceiling is exactly what the source was admitted for.\n *\n * `ctx.now` is read once, at the start, so a relative condition means the same\n * thing on the last page as on the first — twenty pages apart, \"today\" must\n * not roll over into tomorrow halfway through one file.\n */\nexport async function fetchExportRows(\n context: KernelContext,\n config: RecordViewConfig,\n options: ExportRowsOptions = {},\n): Promise<ExportedRows> {\n const { definition, kinds, limits, environment } = context;\n const { size, max } = exportPlan(limits, definition.record, options.max);\n const filterContext: FilterCompileContext = {\n now: environment.now(),\n timeZone: environment.timeZone,\n };\n // The config as it ran, paged the export's way. Everything else — the\n // filter, the sort, the scope already merged into it — is left alone, which\n // is what makes the file the rows the screen was showing.\n const paged: RecordViewConfig = { ...config, pageSize: size };\n const cursored = definition.record?.paging === 'cursor';\n\n const rows: RecordData[] = [];\n let total: number | undefined;\n let target: RecordPageTarget = cursored\n ? FIRST_PAGE.cursor\n : FIRST_PAGE.paged;\n\n for (;;) {\n if (rows.length >= max) return done(rows, max, total, true);\n stopIfCancelled(options.signal);\n const query = compileRecord(\n definition,\n paged,\n kinds,\n filterContext,\n target,\n );\n const page = await fetchPage(context, query, target, size, options.signal);\n stopIfCancelled(options.signal);\n\n rows.push(...page.list);\n if (page.total !== undefined) total = page.total;\n options.onProgress?.(Math.min(rows.length, max), total);\n // A page with nothing in it is the end of the result whatever the source\n // said about a next one — and it is what keeps a source that answers\n // every request with an empty page from being asked forever.\n if (page.next === null || page.list.length === 0)\n return done(rows, max, total, false);\n target = page.next;\n }\n}\n\n/** One page, and where the next one is — `null` at the end of the result. */\nasync function fetchPage(\n context: KernelContext,\n query: FilterPagedQuery | CursorQuery,\n target: RecordPageTarget,\n size: number,\n signal: AbortSignal | undefined,\n): Promise<{\n list: readonly RecordData[];\n total?: number;\n next: RecordPageTarget | null;\n}> {\n // `ViewSource` cancels through a controller because that is what Wow's\n // `QueryApi` takes; the caller cancels through a signal because that is what\n // a component holds. One export's controllers all follow the one signal.\n const controller = new AbortController();\n const unlink = follow(signal, controller);\n try {\n if ('cursor' in target) {\n const page = await context.source.cursor(query, undefined, controller);\n return {\n list: page.list,\n next: page.nextCursor === null ? null : { cursor: page.nextCursor },\n };\n }\n const page = await context.source.paged(query, undefined, controller);\n // A short page is the last one. A full page may still be the last, and\n // the next request answers that; asking once more is cheaper than the\n // row a wrong guess would drop.\n return {\n list: page.list,\n ...(typeof page.total === 'number' ? { total: page.total } : {}),\n next: page.list.length < size ? null : { index: target.index + 1 },\n };\n } finally {\n unlink();\n }\n}\n\n/** The result, cut to the ceiling. */\nfunction done(\n rows: RecordData[],\n max: number,\n total: number | undefined,\n capped: boolean,\n): ExportedRows {\n return {\n rows: rows.length > max ? rows.slice(0, max) : rows,\n ...(total === undefined ? {} : { total }),\n capped: capped || rows.length > max,\n };\n}\n\nfunction stopIfCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw new ExportCancelledError();\n}\n\n/** Aborts `controller` when `signal` does, and unsubscribes when it is over. */\nfunction follow(\n signal: AbortSignal | undefined,\n controller: AbortController,\n): () => void {\n if (!signal) return () => {};\n if (signal.aborted) {\n controller.abort();\n return () => {};\n }\n const onAbort = () => controller.abort();\n signal.addEventListener('abort', onAbort, { once: true });\n return () => signal.removeEventListener('abort', onAbort);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FilterCompileContext } from '../filter/index.js';\nimport {\n without,\n type FilterTree,\n type RecordData,\n type RecordKey,\n type RecordViewConfig,\n} from '../model/index.js';\nimport { FIRST_PAGE, compileRecord } from '../record/index.js';\nimport type { KernelContext } from './execute.js';\nimport { withScopeFilter } from './scope.js';\nimport { abortWith } from './abort.js';\n\n/**\n * One record, whole, by its row key — what a detail panel reads.\n *\n * A page of rows carries what the page shows, and a record's detail is\n * everything the definition declares about it: the error message a column\n * clipped, the stack trace no column holds. So it is asked for on its own,\n * the way a service answers \"this one\": the row key equal to `key`, within\n * the scope the host injected (a tenant's view never opens another tenant's\n * record) and **nothing else** — not the conditions the page was found by. A\n * record opened from the page may stop matching them the moment a command\n * changes it (a retried failure is no longer 「失败」), and its detail is\n * about the record, not about the list.\n *\n * Answers `null` when the record is no longer there. Runs beside the view,\n * as an export does: no scheduler slot, and the rows on screen untouched.\n */\nexport async function fetchRecord(\n context: KernelContext,\n config: RecordViewConfig,\n scope: FilterTree | null,\n key: RecordKey,\n signal?: AbortSignal,\n): Promise<RecordData | null> {\n const { definition, kinds, environment, source } = context;\n const capability = definition.record;\n if (!capability)\n throw new Error(\n `Definition ${definition.id} declares no record capability`,\n );\n const one = withScopeFilter<RecordViewConfig>(\n {\n ...config,\n filter: {\n op: 'and',\n children: [{ field: capability.rowKey, operator: 'EQ', value: key }],\n },\n sort: [],\n pageSize: 1,\n },\n scope,\n );\n const filterContext: FilterCompileContext = {\n now: environment.now(),\n timeZone: environment.timeZone,\n };\n const cursored = capability.paging === 'cursor';\n const query = whole(\n compileRecord(\n definition,\n one,\n kinds,\n filterContext,\n cursored ? FIRST_PAGE.cursor : FIRST_PAGE.paged,\n ),\n );\n const controller = abortWith(signal);\n const page = cursored\n ? await source.cursor(query, undefined, controller)\n : await source.paged(query, undefined, controller);\n return page.list[0] ?? null;\n}\n\n/**\n * The query for one whole record: no projection, since a detail is every\n * field and not the page's; and no sort. `compileRecord` ends every page on\n * the row key so a tie cannot repeat a row across pages — a query for one\n * key has one row and no tie, and a sort would only be work for the source.\n */\nfunction whole<Q extends { sort?: unknown }>(query: Q): Q {\n const bare =\n 'projection' in query\n ? (without(query as Q & { projection?: unknown }, 'projection') as Q)\n : query;\n return { ...bare, sort: [] };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { dequal } from 'dequal';\nimport {\n columnHidden,\n presentationMembers,\n type RecordViewConfig,\n} from '../model/index.js';\n\n/**\n * How much of a record view's question an apply changes, measured against\n * the config the rows on screen ran under.\n *\n * - `drawn`: nothing the source is asked. A column made wider, moved or\n * pinned, or a presentation member (`layout`) — the rows stay, and are\n * drawn again under the new config.\n * - `summaries`: that, and the summary row. The aggregation is asked again\n * and the page is not.\n * - `null`: anything else, and the whole query runs.\n *\n * Which columns are **shown** is part of the question: the query projects\n * the fields the table draws (`recordProjection`), so a column switched on\n * is a field the rows do not hold yet. Their order is not, and neither is\n * a width or a pin. Before this, every one of those ran the page again — an\n * Alt+→ on a header was a query, and a reader heard 「正在查询」 and the\n * record count for each step of a column's width, and never the width.\n */\nexport function restyledOnly(\n ran: RecordViewConfig,\n next: RecordViewConfig,\n): 'drawn' | 'summaries' | null {\n if (!dequal(question(ran), question(next))) return null;\n return dequal(ran.summaries ?? [], next.summaries ?? [])\n ? 'drawn'\n : 'summaries';\n}\n\n/** The members of a record config the page's query is compiled from. */\nfunction question(config: RecordViewConfig): Record<string, unknown> {\n const rest: Record<string, unknown> = { ...config };\n for (const member of presentationMembers(config.kind)) delete rest[member];\n delete rest.summaries;\n const { columns = [], ...table } = config.table ?? {};\n rest.table = {\n ...table,\n shown: columns\n .filter(column => !columnHidden(column.hidden))\n .map(column => column.field)\n .sort(),\n };\n return rest;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryErrorCodes } from '@ahoo-wang/wow-client';\nimport { dequal } from 'dequal';\nimport type {\n DataViewConfig,\n RecordData,\n RecordKey,\n RecordPageTarget,\n RecordViewConfig,\n} from '../model/index.js';\nimport { pageAfterShrink, restyleRecord } from '../record/index.js';\nimport { executeSummaries, firstPageOf } from './execute.js';\nimport {\n fetchExportRows,\n isExportCancelledError,\n type ExportRowsOptions,\n type ExportedRows,\n} from './exportRows.js';\nimport { fetchRecord } from './fetchRecord.js';\nimport { isCalledOff } from './failures.js';\nimport { restyledOnly } from './restyle.js';\nimport { withScopeFilter } from './scope.js';\nimport type { SourceFailure } from './sourceReason.js';\nimport type { ProjectedView } from './source.js';\nimport { DataViewRuntime } from './viewRuntime.js';\nimport type {\n RecordViewRuntime,\n ViewRuntime,\n ViewRuntimeOptions,\n ViewRuntimeState,\n} from './viewRuntimeTypes.js';\n\n/**\n * The runtime of a Record view: the shared data view, plus what only rows\n * have — the page a query asks for, the rows picked, every row for an\n * export, one record read whole.\n *\n * Each is here and nowhere else, so an Analysis runtime carries no page it\n * never turns and no `exportRows` it can only refuse.\n */\nexport class RecordDataViewRuntime\n extends DataViewRuntime<RecordViewConfig>\n implements RecordViewRuntime\n{\n /** The page the next query asks for. */\n private target: RecordPageTarget | undefined;\n /**\n * Whether the page on screen is one a refused cursor already sent back\n * to the start; cleared when a page lands, so the fall-back is once per\n * refusal and never a loop.\n */\n private restarted = false;\n /** Tells the host of an export whose rows could not be fetched (D40). */\n private readonly exportFailed = this.reporter('export');\n\n constructor(options: ViewRuntimeOptions<RecordViewConfig>) {\n super(options);\n this.target = firstPageOf(options.definition);\n }\n\n page(target: RecordPageTarget): void {\n if (this.disposed || !this.appliedAdmitted) return;\n this.target = target;\n this.store.setState({ selection: [] });\n this.execute({ keepSelection: false });\n }\n\n select(keys: RecordKey[]): void {\n if (this.disposed) return;\n const available = this.resultKeys();\n const selection = available\n ? keys.filter(key => available.has(key))\n : [...keys];\n this.store.setState({ selection });\n }\n\n /**\n * The applied config's rows, all of them, for an export.\n *\n * It reads `applied` merged with the scope — the very config the result on\n * screen came from — and goes straight to the source: the request runner is\n * the view's own lane and an export must neither queue behind the view nor\n * push it aside.\n */\n exportRows(options: ExportRowsOptions = {}): Promise<ExportedRows> {\n if (this.disposed)\n return Promise.reject(new Error(`View ${this.id} is closed`));\n return fetchExportRows(\n this.context,\n withScopeFilter(this.state.applied, this.scopeFilter),\n options,\n ).catch((error: unknown) => {\n // A cancel is the user's answer, not a failure (`isExportCancelledError`).\n if (!isExportCancelledError(error) && !isCalledOff(error, options.signal))\n this.exportFailed('fetch', error);\n throw error;\n });\n }\n\n fetchRecord(\n key: RecordKey,\n signal?: AbortSignal,\n ): Promise<RecordData | null> {\n if (this.disposed)\n return Promise.reject(new Error(`View ${this.id} is closed`));\n return fetchRecord(\n this.context,\n this.state.applied,\n this.scopeFilter,\n key,\n signal,\n ).catch((error: unknown) => {\n if (!isCalledOff(error, signal))\n void this.context.queryFailed('record', error);\n throw error;\n });\n }\n\n /**\n * A draft that changes only how the rows on screen are drawn keeps them:\n * the page, its selection and the reader's place stay, and only the\n * columns are projected again (`restyleRecord`). One whose summaries\n * changed too asks the source for the summary row alone, quietly: the\n * query stays `success` and the rows stay drawn while it is out. Either\n * way the page is not fetched, and nothing says 「正在查询」 or draws the\n * table as waiting over rows that stay.\n *\n * Only over a result that landed and is current: while a query is out (a\n * quiet one included), or after one failed, the rows on screen are not the answer to the config\n * that ran, and the whole query runs as before. And only for a draft that\n * differs from what ran: an apply that changes nothing — Apply with\n * nothing pending, Enter in the search box, a host's `apply()` — is a\n * request to ask again, and runs whole from the first page.\n */\n protected override restyle(draft: RecordViewConfig): (() => void) | null {\n const result = this.state.result;\n // Settled, and on what is applied: a quiet request (the summary row)\n // leaves the status `success` while `applied` is ahead of the rows.\n const { query, applied } = this.state;\n if (!result || query.status !== 'success' || result.own !== applied)\n return null;\n const data = result.data;\n if (data.kind !== 'record' || dequal(result.own, draft)) return null;\n const change = restyledOnly(result.own, draft);\n if (change === null) return null;\n const view = restyleRecord(this.context.definition, draft, data.view);\n if (change === 'summaries')\n return () =>\n this.execute({\n keepSelection: true,\n quiet: true,\n fetch: (config, controller) =>\n executeSummaries(this.context, config, view, controller),\n });\n const config = withScopeFilter(draft, this.scopeFilter);\n return () =>\n this.store.setState({\n result: { ...result, config, own: draft, data: { ...data, view } },\n });\n }\n\n /** A new question starts on the first page, with nothing picked. */\n protected override startOver(): Partial<ViewRuntimeState<RecordViewConfig>> {\n this.target = firstPageOf(this.context.definition);\n return { selection: [] };\n }\n\n protected override pageNow(): RecordPageTarget | undefined {\n return this.target;\n }\n\n /**\n * A cursor the source no longer reads — a token from before the service\n * changed how it writes one (#3502), or one a replica does not know —\n * sends the view back to the first page once, rather than showing a\n * failure the reader can do nothing about but start over by hand.\n */\n protected override recovers(failure: SourceFailure): boolean {\n const target = this.target;\n if (this.restarted || !target || !('cursor' in target)) return false;\n if (target.cursor === null || !isInvalidCursor(failure)) return false;\n this.restarted = true;\n this.target = firstPageOf(this.context.definition);\n return true;\n }\n\n /**\n * A page the result shrank out from under asks for the last page there is\n * rather than landing empty with rows before it; a refresh keeps whatever\n * picked rows survive it.\n */\n protected override settle(\n data: ProjectedView,\n keepSelection: boolean,\n ): Partial<ViewRuntimeState<RecordViewConfig>> | null {\n this.restarted = false;\n const back = this.shrunkTo(data);\n if (back !== null) {\n this.target = { index: back };\n return null;\n }\n if (!keepSelection) return {};\n const selection = this.retainSelection(data);\n return selection === this.state.selection ? {} : { selection };\n }\n\n /**\n * Picked rows are rows someone is about to act on, and a refresh can move\n * them to another page or out of the result: the clock waits.\n */\n protected override holds(): boolean {\n return this.state.selection.length > 0;\n }\n\n private shrunkTo(data: ProjectedView): number | null {\n const target = this.target;\n if (data.kind !== 'record' || !target || !('index' in target)) return null;\n return pageAfterShrink(\n data.view.paging,\n target.index,\n data.view.rows.length,\n );\n }\n\n private retainSelection(data: ProjectedView): RecordKey[] {\n if (this.state.selection.length === 0 || data.kind !== 'record')\n return this.state.selection;\n const keys = new Set(data.view.rows.map(row => row.key));\n const retained = this.state.selection.filter(key => keys.has(key));\n return retained.length === this.state.selection.length\n ? this.state.selection\n : retained;\n }\n\n private resultKeys(): Set<RecordKey> | null {\n const data = this.state.result?.data;\n if (!data || data.kind !== 'record') return null;\n return new Set(data.view.rows.map(row => row.key));\n }\n}\n\n/**\n * A Wow service's answer to a cursor it cannot read: `INVALID_CURSOR` from\n * Wow 9.2 on, and before that these words alone (`CursorPositions`).\n */\nconst INVALID_CURSOR = 'Invalid cursor.';\n\nfunction isInvalidCursor(failure: SourceFailure): boolean {\n if (failure.violation)\n return failure.violation.code === QueryErrorCodes.INVALID_CURSOR;\n return (\n (failure.status === undefined || failure.status === 400) &&\n failure.reason.includes(INVALID_CURSOR)\n );\n}\n\n/** The runtime a data view of this config's kind runs on. */\nexport function dataViewRuntime(\n options: ViewRuntimeOptions<DataViewConfig>,\n): DataViewRuntime {\n return options.config.kind === 'record'\n ? new RecordDataViewRuntime(options as ViewRuntimeOptions<RecordViewConfig>)\n : new DataViewRuntime(options);\n}\n\n/**\n * Whether a data view's runtime is a Record view's, with its rows' commands:\n * a dashboard panel's runtime (`DashboardPanelState.runtime`) is either kind.\n */\nexport function isRecordRuntime(\n runtime: ViewRuntime<DataViewConfig>,\n): runtime is RecordViewRuntime {\n return runtime instanceof RecordDataViewRuntime;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * How one runtime is assembled: the step between \"which view\" and \"an open\n * view\".\n *\n * Both `open` and `create` end here, with the same two checks — the config's\n * kind must be one the definition declares, and a dashboard config belongs to\n * a dashboard definition — and the same set of injected parts. A dashboard\n * needs three things it cannot reach itself — how to read a referenced\n * instance, the definition a view it owns is of, and how to build a child\n * runtime for either — so this is also where those are built.\n */\n\nimport { queryFailureReporter } from './failures.js';\nimport { panelsOf, type PanelDefinition } from '../dashboard/index.js';\nimport type {\n DataViewConfig,\n DashboardViewConfig,\n FieldDefinition,\n FilterTree,\n RuntimeLimits,\n ViewConfig,\n ViewDefinition,\n ViewInstance,\n ViewScope,\n} from '../model/index.js';\nimport { issue, type FieldKindRegistry } from '../filter/index.js';\nimport type { RuntimeEnvironment } from './environment.js';\nimport type { RequestRunner } from './requestRunner.js';\nimport type { OptionSource, ViewSource } from './source.js';\nimport type { DataViewRuntime } from './viewRuntime.js';\nimport { dataViewRuntime } from './recordRuntime.js';\nimport type {\n ManagedViewRuntime,\n RuntimeCapabilities,\n} from './viewRuntimeTypes.js';\nimport {\n DashboardViewRuntime,\n type PanelResolver,\n type PanelRuntimeFactory,\n} from './dashboardRuntime.js';\nimport type { DefinitionRegistry } from './definitions.js';\nimport type { SourceCapabilities } from './capabilities.js';\nimport { withCanonicalNames } from '../capabilities/index.js';\nimport { ValueCandidateSources } from './valueCandidates.js';\nimport { ViewCommandError } from './write.js';\n\n/** Who a runtime is, apart from the config it holds. */\nexport interface RuntimeIdentity {\n title: string;\n scope: ViewScope;\n saved: ViewInstance | null;\n}\n\n/** What the factory needs from the engine that owns it. */\nexport interface RuntimeFactoryHost {\n readonly definitions: DefinitionRegistry;\n readonly kinds: FieldKindRegistry;\n readonly limits: RuntimeLimits;\n readonly environment: RuntimeEnvironment;\n readonly runner: RequestRunner;\n /** Where a definition's data comes from, by `DataViewDefinition.source`. */\n resolveSource(key: string): ViewSource;\n /** Remote candidates of `reference` fields; absent when the host wired none. */\n resolveOptions?(key: string): OptionSource;\n /** One instance, from the definition's code or from the store. */\n readInstance(instanceId: string): Promise<ViewInstance>;\n /**\n * What each source admits: a definition as its descriptor narrows it and\n * the limits a runtime over it runs under (`effective`, which throws\n * where the descriptor contradicts the definition).\n */\n readonly capabilities: SourceCapabilities;\n}\n\n/** The queries one panel may ask at once; see `RuntimeFactory.holdRoom`. */\nconst QUERIES_PER_PANEL = 3;\n\nexport class RuntimeFactory {\n private readonly host: RuntimeFactoryHost;\n private sequence = 0;\n\n constructor(host: RuntimeFactoryHost) {\n this.host = host;\n }\n\n build(\n definition: ViewDefinition,\n config: ViewConfig,\n identity: RuntimeIdentity,\n scopeFilter: FilterTree | null = null,\n ): ManagedViewRuntime {\n if (config.kind !== 'dashboard')\n return this.buildData(definition, config, identity, scopeFilter);\n // A board takes no outer condition (D26 Q32): one asked for is refused\n // as a later one would be, and `refusedScope` says so from the start.\n const board = this.buildDashboard(definition, config, identity);\n board.setScopeFilter(scopeFilter);\n return board;\n }\n\n private buildData(\n definition: ViewDefinition,\n config: DataViewConfig,\n identity: RuntimeIdentity,\n scopeFilter: FilterTree | null,\n ): DataViewRuntime {\n if (definition.kind !== 'data' || !capabilityOf(definition, config))\n throw new ViewCommandError(\n issue('runtime.kind.not-declared', [], {\n definition: definition.id,\n kind: config.kind,\n }),\n );\n\n const effective = this.host.capabilities.effective(definition);\n // A view saved under a field's alias is read under its path (#3519).\n const renamed = effective.definition.narrowing?.renamed ?? {};\n return dataViewRuntime({\n id: this.newRuntimeId(),\n definition: effective.definition,\n config: withCanonicalNames(config, renamed),\n title: identity.title,\n scope: identity.scope,\n saved: canonicalInstance(identity.saved, renamed),\n kinds: this.host.kinds,\n limits: effective.limits,\n environment: this.host.environment,\n source: this.host.resolveSource(definition.source),\n runner: this.host.runner,\n resolveOptions: this.host.resolveOptions,\n scopeFilter,\n capabilities: this.follow(definition),\n });\n }\n\n private buildDashboard(\n definition: ViewDefinition,\n config: DashboardViewConfig,\n identity: RuntimeIdentity,\n ): DashboardViewRuntime {\n // A dashboard config belongs to a dashboard definition: the catalogue\n // entry it is listed under, which declares no fields of its own.\n if (definition.kind !== 'dashboard')\n throw new ViewCommandError(\n issue('runtime.kind.not-declared', [], {\n definition: definition.id,\n kind: config.kind,\n }),\n );\n\n const board = new DashboardViewRuntime({\n id: this.newRuntimeId(),\n definition,\n config,\n title: identity.title,\n scope: identity.scope,\n saved: identity.saved,\n kinds: this.host.kinds,\n limits: this.host.limits,\n environment: this.host.environment,\n resolve: this.resolvePanel,\n definitions: this.panelDefinition,\n createPanelRuntime: this.createPanelRuntime,\n resolveOptions: this.host.resolveOptions,\n candidateSources: (panelDefinition, scope) =>\n new ValueCandidateSources(\n {\n definition: panelDefinition,\n kinds: this.host.kinds,\n limits: this.host.capabilities.effective(panelDefinition).limits,\n environment: this.host.environment,\n source: this.host.resolveSource(panelDefinition.source),\n // A board filter's values, asked of a panel's source (D40).\n queryFailed: queryFailureReporter(this.host.environment, () => ({\n definitionId: panelDefinition.id,\n })),\n },\n scope,\n ),\n });\n // Built, it holds subscriptions of its own (the words, the page's\n // visibility, its references): one that cannot be finished is let go\n // here, since nobody else was handed it to close.\n try {\n return this.holdRoom(board);\n } catch (error) {\n board.dispose();\n throw error;\n }\n }\n\n /**\n * Holds room in the query queue for a board's panels while it is open\n * (`RequestRunner.reserve`): each may ask up to `QUERIES_PER_PANEL` at\n * once — its own, a split's 「其他」, a cut's probe — so a board of any\n * size opens whole rather than having its last panels refused. The room\n * follows the board as panels are added or taken away, and is given back\n * when it closes.\n */\n private holdRoom(board: DashboardViewRuntime): DashboardViewRuntime {\n const roomFor = () =>\n // A stored board is read as it came: one whose panels are not a list\n // is refused by its admission (`dashboard.shape.invalid`), not here.\n panelsOf(board.getSnapshot().draft).length * QUERIES_PER_PANEL;\n let held = roomFor();\n let release = this.host.runner.reserve(held);\n const stop = board.subscribe(() => {\n if (board.disposed) {\n release();\n stop();\n return;\n }\n const room = roomFor();\n if (room === held) return;\n release();\n held = room;\n release = this.host.runner.reserve(held);\n });\n return board;\n }\n\n /** What a panel references: the instance and the definition behind it. */\n private readonly resolvePanel: PanelResolver = async instanceId => {\n const instance = await this.host.readInstance(instanceId);\n const declared = this.host.definitions.require(instance.definitionId);\n await this.host.capabilities.prepare(declared);\n const definition = this.admitted(declared);\n // The board reads the view as its child runs it: under the paths its\n // definition renames aliases to (#3519), so a press names its groups\n // as a binding names its field.\n const renamed =\n (definition.kind === 'data' && definition.narrowing?.renamed) || {};\n return {\n instance: canonicalInstance(instance, renamed) ?? instance,\n definition,\n fields: panelFields(definition),\n };\n };\n\n /**\n * The definition a view a board owns is of: code, so looked up rather\n * than loaded, and `null` for one this release does not declare or one\n * that failed admission — neither can be run.\n */\n private readonly panelDefinition = (\n definitionId: string,\n ): PanelDefinition | null => {\n const registry = this.host.definitions;\n if (!registry.definitions.has(definitionId)) return null;\n try {\n const definition = this.admitted(registry.require(definitionId));\n return { definition, fields: panelFields(definition) };\n } catch {\n return null;\n }\n };\n\n /**\n * A panel's definition as its source admits it, so the board judges a\n * panel against the same fields its child runtime runs on.\n */\n private admitted(definition: ViewDefinition): ViewDefinition {\n return definition.kind === 'data'\n ? this.host.capabilities.effective(definition).definition\n : definition;\n }\n\n /**\n * One panel's child runtime. It is owned by its dashboard rather than by\n * the engine: it is not saved, renamed or deleted through a command, and it\n * runs no timer of its own, because the dashboard times every panel. A\n * view the board owns has no baseline (`saved` is `null`): it is saved\n * with the board, never on its own.\n */\n private readonly createPanelRuntime: PanelRuntimeFactory = (\n view,\n scopeFilter: FilterTree | null,\n ) => {\n const { instance, definition } = view;\n const renamed =\n (definition.kind === 'data' && definition.narrowing?.renamed) || {};\n return dataViewRuntime({\n id: this.newRuntimeId(),\n definition,\n config: withCanonicalNames(view.config, renamed),\n title: view.title,\n scope: view.scope,\n saved: canonicalInstance(instance, renamed),\n kinds: this.host.kinds,\n limits: this.host.capabilities.effective(definition).limits,\n environment: this.host.environment,\n source: this.host.resolveSource(definition.source),\n runner: this.host.runner,\n resolveOptions: this.host.resolveOptions,\n scopeFilter,\n autoRefresh: false,\n capabilities: this.follow(definition),\n });\n };\n\n /**\n * How a runtime over `definition` follows its source's descriptor: the\n * definition as declared (a panel may hold one already narrowed), what is\n * in force now, and the source's changes.\n */\n private follow(definition: ViewDefinition): RuntimeCapabilities | undefined {\n const declared = this.host.definitions.definitions.get(definition.id);\n if (declared?.kind !== 'data') return undefined;\n const capabilities = this.host.capabilities;\n return {\n declared,\n effective: () => capabilities.effective(declared),\n watch: listener => capabilities.watch(declared.source, listener),\n revalidate: () => capabilities.revalidate(declared.source),\n recheck: code => capabilities.recheck(declared.source, code),\n };\n }\n\n private newRuntimeId(): string {\n return `runtime-${(this.sequence += 1)}`;\n }\n}\n\n/** A saved instance whose data config is read under the paths it renames. */\nfunction canonicalInstance(\n instance: ViewInstance | null,\n renamed: Readonly<Record<string, string>>,\n): ViewInstance | null {\n if (!instance || instance.config.kind === 'dashboard') return instance;\n const config = withCanonicalNames(instance.config, renamed);\n return config === instance.config ? instance : { ...instance, config };\n}\n\nfunction capabilityOf(definition: ViewDefinition, config: ViewConfig): boolean {\n if (definition.kind !== 'data') return false;\n return config.kind === 'record'\n ? definition.record !== undefined\n : definition.analysis !== undefined;\n}\n\n/**\n * What a panel's view is judged against.\n *\n * The definition's own fields, for every kind of view: a dashboard's global\n * filter is merged into the panel's own filter, and that filter is the query\n * root. An analysis expands elements below it, but a root filter reaches an\n * element's entries only through an `elementMatch` condition on the array\n * itself — which is a root field — so an expansion adds nothing a binding\n * could point at.\n */\nfunction panelFields(definition: ViewDefinition): readonly FieldDefinition[] {\n return definition.kind === 'data' ? definition.fields : [];\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The one read boundary of AGENTS.md's stored-data exception (D26 Q31,\n * A-06): every view the engine reads out of the host's store goes through\n * `readStored` once, on its way in, and everything past it — a runtime and\n * its baseline, a panel's reference, another board a click opens, the\n * write ledger's answers and the instance a conflict carries — holds the\n * form this engine writes and migrates nothing itself.\n *\n * A view declared in code is not stored data: TypeScript holds it to the\n * config's shape like any other code, so it is not read through here.\n */\n\nimport {\n isViewStoreError,\n ViewStoreError,\n type DashboardViewConfig,\n type ViewInstance,\n} from '../model/index.js';\nimport { isPlainObject } from '../filter/index.js';\nimport { migrateDashboardConfig } from '../dashboard/index.js';\nimport type { ViewStore } from '../store/ViewStore.js';\n\n/**\n * A stored view read into the form this engine writes — for a dashboard,\n * `migrateDashboardConfig`; the same instance when it already is, so a view\n * in this form is never a different object for having been read.\n */\nexport function readStored(instance: ViewInstance): ViewInstance {\n const config: unknown = instance.config;\n if (!isPlainObject(config) || config.kind !== 'dashboard') return instance;\n const read = migrateDashboardConfig(config as unknown as DashboardViewConfig);\n return read === instance.config ? instance : { ...instance, config: read };\n}\n\n/**\n * The host's store as the engine reads it: every view it hands back — read,\n * created, saved or renamed, or carried by a write's conflict — through\n * `readStored`, and every other call passed on as it is. A method is looked\n * up on the host's store as it is called rather than once, so a store\n * swapped or spied on after the engine was built is still the one asked.\n */\nexport function readingStore(store: ViewStore): ViewStore {\n return {\n list: (definitionId, signal) => store.list(definitionId, signal),\n get: async (id, signal) => readStored(await store.get(id, signal)),\n create: (input, context) => written(() => store.create(input, context)),\n save: (id, config, revision, context) =>\n written(() => store.save(id, config, revision, context)),\n rename: (id, title, revision, context) =>\n written(() => store.rename(id, title, revision, context)),\n delete: (id, revision, context) =>\n written(() => store.delete(id, revision, context)),\n getPreferences: (definitionId, signal) =>\n store.getPreferences(definitionId, signal),\n setPreferences: (definitionId, preferences, context) =>\n store.setPreferences(definitionId, preferences, context),\n // Optional on the port, so present here exactly when the store has it:\n // its absence is what the engine and the manager read (D18 item 10).\n ...(store.changeAudience\n ? {\n changeAudience: (id, audience, revision, context) =>\n written(() =>\n store.changeAudience!(id, audience, revision, context),\n ),\n }\n : {}),\n ...(store.permissions\n ? { permissions: definitionId => store.permissions!(definitionId) }\n : {}),\n };\n}\n\n/**\n * A write's answer read in: the view it returns, or the view the store\n * holds when it refuses the write as a conflict — which the ledger takes\n * as the draft on 「重新加载」, so it is stored data like any other read.\n */\nasync function written<T extends ViewInstance | void>(\n write: () => Promise<T>,\n): Promise<T> {\n try {\n const answer = await write();\n return (answer ? readStored(answer) : answer) as T;\n } catch (error) {\n throw conflictRead(error);\n }\n}\n\n/** A conflict with the view it carries read in; anything else as it is. */\nfunction conflictRead(error: unknown): unknown {\n if (!isViewStoreError(error) || !error.instance) return error;\n const instance = readStored(error.instance);\n if (instance === error.instance) return error;\n return new ViewStoreError(error.code, error.message, {\n instance,\n preferences: error.preferences,\n });\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What each source admits, as one engine holds it (capabilities.md 3, 6):\n * the descriptor cache, the definitions narrowed to it, the limits it says,\n * and when to check it again.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client';\nimport type {\n DataViewDefinition,\n Issue,\n RuntimeLimits,\n ViewDefinition,\n ViewInstance,\n} from '../model/index.js';\nimport { issue, type FieldKindRegistry } from '../filter/index.js';\nimport { isOwnedPanel, panelsOf } from '../dashboard/index.js';\nimport {\n DESCRIBE_DEADLINE_MS,\n DescriptorCache,\n narrowDefinition,\n sourceLimits,\n type Describe,\n type NarrowedDefinition,\n} from '../capabilities/index.js';\nimport type { RuntimeEnvironment } from './environment.js';\nimport type { ViewSource } from './source.js';\nimport { ViewCommandError } from './write.js';\n\n/** What the capabilities read from the engine that owns them. */\nexport interface CapabilityHost {\n readonly kinds: FieldKindRegistry;\n /** The host's own limits, as it gave them; the source budgets may be left out. */\n readonly limits: Partial<RuntimeLimits> | undefined;\n readonly environment: RuntimeEnvironment;\n resolveSource(key: string): ViewSource;\n /** A definition as the application declared it, by id. */\n declared(id: string): ViewDefinition | undefined;\n /** A finding with nobody to reject: `onIssue`. */\n report(found: Issue): void;\n}\n\n/** A definition and the limits a runtime over it runs under. */\nexport interface EffectiveDefinition {\n definition: DataViewDefinition;\n limits: RuntimeLimits;\n}\n\nexport class SourceCapabilities {\n /**\n * The limits of a source with no descriptor: the host's over the\n * defaults, as every source ran under before descriptors.\n */\n readonly fallback: RuntimeLimits;\n private readonly host: CapabilityHost;\n private readonly cache: DescriptorCache;\n /** Each definition narrowed to the version it was narrowed against. */\n private readonly narrowed = new Map<\n string,\n { version: string; result: NarrowedDefinition }\n >();\n private readonly limitsBySource = new Map<\n string,\n { version: string; limits: RuntimeLimits }\n >();\n private readonly stopWatching: () => void;\n /** Who runs on each source, told when its descriptor changes. */\n private readonly watchers = new Map<string, Set<() => void>>();\n\n constructor(host: CapabilityHost) {\n this.host = host;\n this.fallback = sourceLimits(host.limits, null);\n this.cache = new DescriptorCache({\n now: () => host.environment.now().getTime(),\n // Nobody is shown this: the views run on the definition as they did\n // before descriptors, and only a query the source really refuses says\n // anything on screen (capabilities.md 6「取不到时」).\n failed: source =>\n host.report(\n issue('capability.descriptor.unavailable', [], { source }, 'note'),\n ),\n // A view open over the source takes the new narrowing at once\n // (capabilities.md 6「版本变了」): one made before the first read\n // (`create`) is narrowed here for the first time.\n changed: source => {\n for (const listener of [...(this.watchers.get(source) ?? [])])\n listener();\n },\n });\n // Coming back to the page is one of the moments to check again; the\n // cache skips a descriptor younger than its maximum age.\n const visibility = host.environment.visibility;\n this.stopWatching = visibility.subscribe(() => {\n if (visibility.isVisible()) this.cache.revalidateStale();\n });\n }\n\n /**\n * Reads the descriptor of every source the instance's view runs on, the\n * first time a view over it opens, so its first query already goes out\n * narrowed; later openings answer at once and check a stale descriptor\n * in the background. A board's saved views are read as each panel\n * resolves (`prepare`); the views it owns are read here.\n */\n async prepareFor(instance: ViewInstance): Promise<void> {\n const definition = this.host.declared(instance.definitionId);\n if (!definition) return;\n if (definition.kind === 'data') return this.prepare(definition);\n const config = instance.config;\n if (config.kind !== 'dashboard') return;\n const owned = panelsOf(config)\n .filter(isOwnedPanel)\n .map(panel => this.host.declared(panel.owned.definitionId))\n .filter(entry => entry !== undefined);\n await Promise.all(owned.map(entry => this.prepare(entry)));\n }\n\n /**\n * Reads one definition's source descriptor; see `prepareFor`. Waited for\n * no longer than `DESCRIBE_DEADLINE_MS`: past it the view opens on the\n * definition as declared, as it does when the read fails, and the read\n * still in flight narrows it when it lands (`changed`).\n */\n async prepare(definition: ViewDefinition): Promise<void> {\n if (definition.kind !== 'data') return;\n const { source } = definition;\n const describe = this.describer(source);\n if (!describe) return;\n const { environment } = this.host;\n let timer: unknown;\n const late = new Promise<void>(resolve => {\n timer = environment.setTimeout(() => {\n this.host.report(\n issue('capability.descriptor.unavailable', [], { source }, 'note'),\n );\n resolve();\n }, DESCRIBE_DEADLINE_MS);\n });\n try {\n await Promise.race([this.cache.load(source, describe), late]);\n } finally {\n environment.clearTimeout(timer);\n }\n }\n\n /**\n * Starts reading a source's descriptor without waiting, for a view made\n * from nothing (`create`), which cannot wait: it runs on what is held,\n * and the next view over the source on what this read brings.\n */\n warm(definition: ViewDefinition): void {\n void this.prepare(definition);\n }\n\n /**\n * Tells `listener` whenever the descriptor of `source` is first read or\n * changes version. Returns the way to stop.\n */\n watch(source: string, listener: () => void): () => void {\n let listeners = this.watchers.get(source);\n if (!listeners) {\n listeners = new Set();\n this.watchers.set(source, listeners);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n }\n\n /** Checks a source's descriptor again when it is stale: a press of refresh. */\n revalidate(source: string): void {\n void this.cache.revalidate(source);\n }\n\n /**\n * Checks a source's descriptor again at once, because the source refused\n * a query for a capability the descriptor admitted (capabilities.md 7,\n * C5). A new version narrows every view over the source through `watch`;\n * the same version means the descriptor and the service's admission\n * disagree — the service's defect — and it is told to `onIssue` as an\n * error, beside the rejection the view already says. Resolves whether the\n * version changed.\n */\n async recheck(source: string, code: string | undefined): Promise<boolean> {\n const before = this.cache.current(source)?.version;\n if (before === undefined) return false;\n await this.cache.revalidate(source, true);\n const after = this.cache.current(source)?.version;\n if (after !== before) return true;\n this.host.report(\n issue('capability.descriptor.disagrees', [], {\n source,\n code: code ?? '',\n version: before,\n }),\n );\n return false;\n }\n\n /**\n * The definition a runtime over it runs on, and the limits: narrowed to\n * the descriptor held for its source, or as declared while there is\n * none. Refused, as a definition failing admission is, when the\n * descriptor contradicts it (capabilities.md 4.6).\n */\n effective(definition: DataViewDefinition): EffectiveDefinition {\n const descriptor = this.cache.current(definition.source);\n if (!descriptor) return { definition, limits: this.fallback };\n const { definition: narrowed, findings } = this.narrow(\n definition.id,\n definition,\n descriptor,\n );\n const errors = findings.filter(found => found.severity === 'error');\n if (errors.length > 0)\n throw new ViewCommandError(\n issue('view.definition.invalid', [], {\n id: definition.id,\n issues: errors.length,\n }),\n );\n return {\n definition: narrowed,\n limits: this.limitsOf(definition.source, descriptor),\n };\n }\n\n dispose(): void {\n this.stopWatching();\n }\n\n /**\n * How to read a source's descriptor, or `null` without one. A key the\n * host cannot resolve is left to fail where it always has — when a view\n * over it is built — so a board's other panels are not taken down with it.\n */\n private describer(source: string): Describe | null {\n let resolved: ViewSource;\n try {\n resolved = this.host.resolveSource(source);\n } catch {\n return null;\n }\n if (!resolved.describe) return null;\n return previous => resolved.describe!(previous);\n }\n\n /**\n * Narrowed once per descriptor version, and what it found reported once\n * with it (capabilities.md 4.6). The definition narrowed is the declared\n * one, whatever copy the caller holds — a panel's may already be\n * narrowed against an older version.\n */\n private narrow(\n id: string,\n given: DataViewDefinition,\n descriptor: QueryModelDescriptor,\n ): NarrowedDefinition {\n const held = this.narrowed.get(id);\n if (held?.version === descriptor.version) return held.result;\n const declared = this.host.declared(id);\n const definition = declared?.kind === 'data' ? declared : given;\n const result = narrowDefinition(definition, descriptor, this.host.kinds);\n this.narrowed.set(id, { version: descriptor.version, result });\n for (const found of result.findings)\n this.host.report({\n ...found,\n params: { ...found.params, definition: id },\n });\n return result;\n }\n\n private limitsOf(\n source: string,\n descriptor: QueryModelDescriptor,\n ): RuntimeLimits {\n const held = this.limitsBySource.get(source);\n if (held?.version === descriptor.version) return held.limits;\n const limits = sourceLimits(this.host.limits, descriptor);\n this.limitsBySource.set(source, { version: descriptor.version, limits });\n return limits;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The words an engine checks its definitions' keys against (`text(key)`,\n * host-integration.md 3.1, D2).\n *\n * The engine never says a key: the definitions, the stored configs, every\n * runtime's state and everything it hands out keep them, and the UI says\n * them where it shows them (`useSay`). What is here is the other half: the\n * words the engine was built with (`ViewEngineOptions.text`), which a\n * surface falls back on, and the words its Provider set last (`set`), which\n * `setText` checks for keys they lack. A change of words tells no runtime\n * anything — nothing the engine holds is in any language.\n */\n\nimport type { TextResolver } from '../model/index.js';\n\nexport class EngineText {\n private resolver: TextResolver | undefined;\n private knownKeys: ReadonlySet<string> | undefined;\n\n /**\n * `start` is the words the engine was built with, said wherever the words\n * set later lack a key; `known` the keys the definitions write (read once,\n * on first use).\n */\n constructor(\n readonly start: TextResolver | undefined,\n private readonly known: () => ReadonlySet<string>,\n ) {}\n\n /** Checks another language from now on. True when that changed anything. */\n set(resolver: TextResolver | undefined): boolean {\n if (resolver === this.resolver) return false;\n this.resolver = resolver;\n return true;\n }\n\n /** The words for `key` in force: the ones set, else the ones started with. */\n resolve(key: string): string | undefined {\n return this.resolver?.(key) ?? this.start?.(key);\n }\n\n /** Whether `resolver` has words for any key the definitions write. */\n saysAny(resolver: TextResolver): boolean {\n this.knownKeys ??= this.known();\n for (const key of this.knownKeys)\n if (resolver(key) !== undefined) return true;\n return false;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * What the engine says of its findings while a host is being built\n * (host-integration.md 4, 「开发期的 onIssue 缺省」): a host that passes no\n * `onIssue` still hears, in development, what the engine found about the\n * resources it registered — grouped by resource, each finding with how to\n * fix it. In production, and under a test runner, it says nothing.\n */\n\nimport type { Issue } from '../model/index.js';\n\n/** Told of one finding, with the resource it is about where there is one. */\nexport type IssueReporter = (found: Issue, resource?: string) => void;\n\n/** The part of `console` the report writes to. */\nexport interface IssueConsole {\n groupCollapsed(...data: unknown[]): void;\n groupEnd(): void;\n warn(...data: unknown[]): void;\n error(...data: unknown[]): void;\n info(...data: unknown[]): void;\n}\n\n/**\n * How to fix what a code says, by the longest prefix of it listed here.\n * Written for whoever works on the host, never shown to its readers, so it\n * is English only and not in the message catalogue.\n */\nconst HINTS: readonly (readonly [string, string])[] = [\n [\n 'definition.text.unknown',\n \"Give the key words in the Provider's `messages` (or `ViewEngineOptions.text`).\",\n ],\n [\n 'definition.text.fallback',\n \"Give the key words in the Provider's `messages` for this language: the engine's starting words are showing in its place.\",\n ],\n [\n 'definition.source.unregistered',\n 'Register the definition with its source: `resources: [{ definition, source }]`.',\n ],\n [\n 'definition.time',\n 'Name a time field the definition declares, of a temporal kind (`defineView` `timeField`).',\n ],\n [\n 'definition.field',\n 'Fix the field in the definition: `defineView` takes the facts from the descriptor, so narrow it rather than restate it.',\n ],\n [\n 'definition.view',\n 'Fix the system view: a unique id without the separator, of a kind the definition declares.',\n ],\n [\n 'definition.descriptor',\n \"Commit the source's descriptor snapshot and pass it to `admit` in a test.\",\n ],\n [\n 'definition.',\n 'Fix the definition; `admit` from `@ahoo-wang/wow-view-engine/testing` lists every finding in a unit test.',\n ],\n [\n 'capability.descriptor.unavailable',\n \"The source's `describe` failed: the views run on the definition as declared until it answers.\",\n ],\n [\n 'capability.descriptor.disagrees',\n 'The service refused what its own descriptor admits: a defect of the service, not the host.',\n ],\n [\n 'capability.',\n 'The source admits less than the definition declares on this deployment: narrow the definition, or accept that the control is not offered here.',\n ],\n [\n 'view.list.reserved-id',\n \"The store returned an id in the system views' namespace; only a definition declares one.\",\n ],\n [\n 'view.change.notify-failed',\n 'A listener given to `engine.subscribe` threw; the write itself landed.',\n ],\n];\n\n/** The hint for `code`, or `undefined` for a code with none. */\nexport function issueHint(code: string): string | undefined {\n let found: readonly [string, string] | undefined;\n for (const entry of HINTS)\n if (\n code.startsWith(entry[0]) &&\n (!found || entry[0].length > found[0].length)\n )\n found = entry;\n return found?.[1];\n}\n\n/**\n * A reporter that writes to `sink`, one collapsed group per resource for\n * the findings of the same turn — an engine's start reports every\n * definition's at once — each finding on its own line with its hint.\n */\nexport function consoleIssueReporter(sink: IssueConsole): IssueReporter {\n const pending = new Map<string, Issue[]>();\n const flush = () => {\n for (const [resource, found] of pending) {\n sink.groupCollapsed(\n `[view-engine] ${resource}: ${found.length} finding${found.length === 1 ? '' : 's'}`,\n );\n for (const entry of found) {\n const at = entry.path.length > 0 ? ` at ${entry.path.join('.')}` : '';\n const hint = issueHint(entry.code);\n const line = `${entry.code}${at}${hint ? ` — ${hint}` : ''}`;\n if (entry.severity === 'error') sink.error(line, entry.params);\n else if (entry.severity === 'warning') sink.warn(line, entry.params);\n else sink.info(line, entry.params);\n }\n sink.groupEnd();\n }\n pending.clear();\n };\n return (found, resource) => {\n const key =\n resource ??\n stringParam(found, 'definition') ??\n stringParam(found, 'source') ??\n 'engine';\n if (pending.size === 0) void Promise.resolve().then(flush);\n const list = pending.get(key);\n if (list) list.push(found);\n else pending.set(key, [found]);\n };\n}\n\nfunction stringParam(found: Issue, name: string): string | undefined {\n const value = found.params?.[name];\n return typeof value === 'string' ? value : undefined;\n}\n\n// Replaced by the bundler (Vite, webpack, esbuild) as the literal it is; an\n// environment that neither defines nor replaces it is not development.\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/** True in a development build: `NODE_ENV` says `development`. */\nfunction inDevelopment(): boolean {\n try {\n return process.env.NODE_ENV === 'development';\n } catch {\n return false;\n }\n}\n\n/**\n * The reporter an engine uses when its host passes no `onIssue`: the\n * console's, in development; none otherwise.\n */\nexport function defaultIssueReporter(): IssueReporter | undefined {\n return inDevelopment() ? consoleIssueReporter(console) : undefined;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n textKeysIn,\n type Issue,\n type TextResolver,\n type ViewDefinition,\n} from '../model/index.js';\nimport { issue } from '../filter/index.js';\nimport { sayDefinition } from './definitions.js';\nimport type { OptionSource, ViewSource } from './source.js';\nimport { EngineText } from './text.js';\nimport { defaultIssueReporter, type IssueReporter } from './issueReport.js';\nimport { ViewCommandError } from './write.js';\n\n/** What the engine's resources are read from; see `ViewEngineOptions`. */\nexport interface ResourceHost {\n resources: readonly {\n definition: ViewDefinition;\n source?: ViewSource;\n }[];\n resolveOptions?(key: string): OptionSource;\n text?(key: string): string | undefined;\n onIssue?(issue: Issue): void;\n}\n\n/**\n * The half of the engine that is what the host registered\n * (host-integration.md 4): each definition's source, by the key its\n * definitions name it by, and the words its keys are checked against\n * (`EngineText`, D2).\n */\nexport abstract class EngineResources {\n /**\n * The definitions as registered, keys and all: the registry's map rather\n * than the registry, so the engine's public type names nothing it does\n * not export (R2-85).\n */\n protected abstract readonly registered: ReadonlyMap<string, ViewDefinition>;\n /** The words the definitions' keys are checked against; see `EngineText`. */\n private readonly text: EngineText;\n private readonly sources = new Map<string, ViewSource>();\n /** What was told to lack words, by language, code and key; see `setText`. */\n private readonly lacking = new Set<string>();\n /** Where findings go: the host's `onIssue`, or the development default. */\n private readonly reporter: IssueReporter | undefined;\n\n constructor(private readonly host: ResourceHost) {\n // Called on the host's object, as a method.\n this.reporter = host.onIssue\n ? found => host.onIssue?.(found)\n : defaultIssueReporter();\n // Called on the host's object, which a catalogue's method may read.\n this.text = new EngineText(host.text && (key => host.text?.(key)), () =>\n textKeysIn([...this.registered.values()]),\n );\n for (const { definition, source } of host.resources)\n if (\n source &&\n definition.kind === 'data' &&\n !this.sources.has(definition.source)\n )\n this.sources.set(definition.source, source);\n }\n\n /**\n * Every registered definition, by id, as it was declared: its keys\n * (`text(key)`) are said where they are shown (`useSay`, `say`).\n */\n get definitions(): ReadonlyMap<string, ViewDefinition> {\n return this.registered;\n }\n\n /**\n * The words the engine was built with for `key` (`ViewEngineOptions.text`),\n * or `undefined`: what a surface says a key in where its Provider's words\n * lack it.\n */\n startingWord(key: string): string | undefined {\n return this.text.start?.(key);\n }\n\n /**\n * Checks the words a Provider says the definitions' keys in: its\n * `messages`, in its `language` (host-integration.md 3.1, D2). The\n * Provider calls this as they change; nothing is redrawn or rebuilt by\n * it — the keys are said where they are shown.\n *\n * The words set are checked on their own: a key they lack reads as\n * itself (`definition.text.unknown`), or in the words the engine started\n * with (`definition.text.fallback`) — a Chinese page showing an English\n * label is a gap too. A fallback is told only of words that say any of\n * the definitions' keys at all: words that say none (a Provider with no\n * catalogue of the definitions') leave them to the starting words, as\n * the host meant. Each key is told once per language, and again once\n * that language had it and lacks it again.\n */\n setText(text: TextResolver | undefined, language = ''): void {\n if (!this.text.set(text) || !text) return;\n const findings = [...this.registered.values()].flatMap(definition =>\n sayDefinition(definition, text).findings.map(found => ({\n found,\n definition: definition.id,\n key: String(found.params?.key),\n })),\n );\n const says = this.text.saysAny(text);\n const lacking = new Set<string>();\n for (const { found, definition, key } of findings) {\n const filled = this.text.resolve(key) !== undefined;\n if (filled && !says) continue;\n const code = filled\n ? 'definition.text.fallback'\n : 'definition.text.unknown';\n const told = `${language}\\u0000${code}\\u0000${key}`;\n lacking.add(told);\n if (this.lacking.has(told)) continue;\n this.lacking.add(told);\n this.report({ ...found, code }, definition);\n }\n // What this language now has is forgotten, so lacking it again is told.\n for (const told of this.lacking)\n if (told.startsWith(`${language}\\u0000`) && !lacking.has(told))\n this.lacking.delete(told);\n }\n\n /**\n * A finding with nobody to reject (`onIssue`), with the resource it is\n * about where there is one.\n */\n protected report(found: Issue, resource?: string): void {\n this.reporter?.(found, resource);\n }\n\n /** Whether a resource registered a source under `key`. */\n protected hasSource(key: string): boolean {\n return this.sources.has(key);\n }\n\n /** The source registered for a definition's `source` key. */\n resolveSource(key: string): ViewSource {\n const source = this.sources.get(key);\n if (!source)\n throw new ViewCommandError(\n issue('runtime.source.unresolved', [], { source: key }),\n );\n return source;\n }\n\n resolveOptions(key: string): OptionSource {\n const resolve = this.host.resolveOptions;\n if (!resolve)\n throw new ViewCommandError(\n issue('runtime.options.unresolved', [], { source: key }),\n );\n return resolve(key);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n audienceOf,\n type FilterTree,\n parseSystemInstanceId,\n toSummary,\n type Issue,\n type RuntimeLimits,\n type ViewConfig,\n type ViewDefinition,\n type ViewInstance,\n type ViewAudience,\n type ViewInstanceSummary,\n type ViewPreferences,\n type ViewScope,\n} from '../model/index.js';\nimport {\n builtinFieldKinds,\n issue,\n type FieldKindRegistry,\n} from '../filter/index.js';\nimport type {\n InstancePermissions,\n ViewPermissions,\n ViewStore,\n} from '../store/ViewStore.js';\nimport {\n defaultRuntimeEnvironment,\n type RuntimeEnvironment,\n} from './environment.js';\nimport { RequestRunner } from './requestRunner.js';\nimport type { OptionSource, ViewSource } from './source.js';\nimport type {\n AnyViewRuntime,\n CreateInput,\n ManagedViewRuntime,\n OpenOptions,\n RuntimeFor,\n ViewRuntime,\n} from './viewRuntimeTypes.js';\nimport { DashboardViewRuntime } from './dashboardRuntime.js';\nimport { PanelViews } from './panelViews.js';\nimport {\n ViewCommandError,\n type WritePayload,\n type WriteState,\n} from './write.js';\nimport {\n WriteLedger,\n type ConflictChoice,\n type WriteLedgerHost,\n type WriteTarget,\n} from './writeLedger.js';\nimport { ViewChanges, type ViewChangeListener } from './viewChanges.js';\nimport { DefinitionRegistry, systemInstances } from './definitions.js';\nimport { PermissionGuard } from './permissions.js';\nimport { PreferenceCache, resolveDefault } from './preferences.js';\nimport { OpenRuntimes } from './openRuntimes.js';\nimport { storedSummaries, SummaryCache } from './summaries.js';\nimport { TabMemory } from './tabMemory.js';\nimport { RuntimeFactory, type RuntimeIdentity } from './runtimeFactory.js';\nimport { readingStore } from './storedViews.js';\nimport { SourceCapabilities } from './capabilities.js';\nimport { EngineResources } from './resources.js';\nimport { reportingStore } from './failures.js';\nimport { requireSavable, requireTitle, storable } from './commandChecks.js';\nimport { publishCopy, readReferences } from './publish.js';\n\n/**\n * One thing a host registers (host-integration.md 4): a definition, and\n * where its data comes from. A board's definition has no source — it\n * queries nothing of its own.\n */\nexport interface ViewResource {\n definition: ViewDefinition;\n /** Where a data definition's rows come from; a board has none. */\n source?: ViewSource;\n}\n\nexport interface ViewEngineOptions {\n /** What the host registers: each definition, with its data's source. */\n resources: readonly ViewResource[];\n store: ViewStore;\n /** Remote candidates of `reference` fields, by the same key. */\n resolveOptions?(key: string): OptionSource;\n kinds?: FieldKindRegistry;\n /**\n * How the definitions' keys (`text(key)`) are said in the language the\n * engine starts in, for a host with no Provider; a Provider says them in\n * its own (`setText`). Keys stay in the definitions and in every\n * runtime's state, and are read into words as the engine hands them out,\n * so a change of language redraws what is open rather than rebuilding\n * anything (host-integration.md 3.1, D2). Left out, a key reads as\n * itself until a language is set.\n */\n text?(key: string): string | undefined;\n /**\n * The host's budgets over `DEFAULT_RUNTIME_LIMITS`: what is left out keeps\n * its default. The source budgets (`maxPageSize`, `maxPageWindow`,\n * `maxAnalysisRows`, `maxQueryFilterNodes`, `maxFilterValues`) are said by a source's descriptor\n * where it has one, and one given here only lowers it — so leave them out\n * unless the engine should ask for less than the server admits\n * (capabilities.md 4.5).\n */\n limits?: Partial<RuntimeLimits>;\n environment?: RuntimeEnvironment;\n /** Idempotency keys; overridden in tests to keep them readable. */\n newId?(): string;\n /**\n * Findings with no caller to reject and nothing thrown behind them: a\n * definition's admission, a list entry that was dropped, a change\n * listener that threw. Failures — a query, a store call, an export, a\n * render — go to `environment.onError` instead (D40).\n *\n * Left out, a development build (`NODE_ENV` of `development`) writes them\n * to the console, grouped by resource, each with how to fix it; any other\n * build drops them.\n */\n onIssue?(issue: Issue): void;\n}\n\n/**\n * What a definition's list is right now: every view that could be read, and\n * the reason the rest could not. The declared system views are always in\n * `items`; `failed` names the store's failure when the saved ones are not.\n */\nexport interface ViewListing {\n items: ViewInstanceSummary[];\n failed: Issue | null;\n}\n\n/**\n * The registry and the command entry point: definitions in, runtimes and\n * writes out.\n *\n * What the commands stand on lives beside this file, one concern each: the\n * definition registry (`definitions.ts`), the permission checks\n * (`permissions.ts`), the preference cache (`preferences.ts`), the summary\n * cache (`summaries.ts`), the open views (`openRuntimes.ts`), how one runtime\n * is assembled (`runtimeFactory.ts`) and the write ledger\n * (`writeLedger.ts`). What is left here is the command surface itself:\n * admission, then one dispatch.\n *\n * Every write goes through one path, so the default UI and a hand-built one\n * behave the same, and every non-success outcome lands in the same three\n * recovery actions: `retryWrite`, `abandonWrite`, `resolveConflict`.\n *\n * A dashboard is opened by the same commands as a data view. What differs is\n * that it composes other instances, so the engine hands it the two things it\n * cannot reach itself: how to read a referenced instance, and how to build a\n * child runtime for it.\n *\n * Construct it; do not extend it. Its base class is how the file is split,\n * not an extension point.\n *\n * @sealed\n */\nexport class ViewEngine extends EngineResources {\n /**\n * The host's store as the engine reads it: every view it hands back is\n * read into the form this engine writes on its way in (`readingStore`,\n * AGENTS.md's stored-data exception), and nothing past it migrates.\n */\n readonly store: ViewStore;\n readonly environment: RuntimeEnvironment;\n readonly kinds: FieldKindRegistry;\n readonly limits: RuntimeLimits;\n\n private readonly options: ViewEngineOptions;\n private readonly runner: RequestRunner;\n /** What each source admits; see `capabilities.ts`. */\n private readonly capabilities: SourceCapabilities;\n private readonly registry: DefinitionRegistry;\n protected readonly registered: ReadonlyMap<string, ViewDefinition>;\n private readonly guard: PermissionGuard;\n private readonly preferenceCache: PreferenceCache;\n private readonly runtimes = new OpenRuntimes();\n private readonly factory: RuntimeFactory;\n /** Every write that left, and every outcome not yet settled. */\n private readonly ledger: WriteLedger;\n /** Saving a dashboard panel's view as a view of its own; see `panelViews.ts`. */\n private readonly panelViews: PanelViews;\n /** Who is told that a definition's list has changed; see `subscribe`. */\n private readonly changes = new ViewChanges(found => this.report(found));\n /** The last summary seen of each instance; see `summaries.ts`. */\n private readonly summaries = new SummaryCache();\n /** Where each reader last read each board; see `tabMemory.ts`. */\n private readonly tabs = new TabMemory({\n current: definitionId => this.preferenceCache.current(definitionId),\n write: (definitionId, next) => this.writePreferences(definitionId, next),\n abandon: handle => this.ledger.abandonWrite(handle),\n });\n\n constructor(options: ViewEngineOptions) {\n super(options);\n this.options = options;\n this.environment = options.environment ?? defaultRuntimeEnvironment();\n // Read in first, then watched: a store failure is told to the host's\n // `onError` once, whichever command or read it failed under (D40).\n this.store = reportingStore(readingStore(options.store), this.environment);\n this.kinds = options.kinds ?? builtinFieldKinds;\n this.capabilities = new SourceCapabilities({\n kinds: this.kinds,\n limits: options.limits,\n environment: this.environment,\n resolveSource: key => this.resolveSource(key),\n declared: id => this.registry.definitions.get(id),\n report: found => this.report(found),\n });\n // A source with a descriptor runs under its own (`effective`).\n this.limits = this.capabilities.fallback;\n this.runner = new RequestRunner(this.limits);\n this.guard = new PermissionGuard(this.store);\n this.preferenceCache = new PreferenceCache(this.store);\n this.ledger = new WriteLedger(this.ledgerHost());\n this.registry = new DefinitionRegistry(\n {\n definitions: options.resources.map(({ definition }) => definition),\n hasSource: key => this.hasSource(key),\n ...(options.text ? { text: (key: string) => options.text?.(key) } : {}),\n },\n this.kinds,\n this.limits,\n (found, resource) => this.report(found, resource),\n );\n this.registered = this.registry.definitions;\n this.panelViews = new PanelViews({\n registry: this.registry,\n kinds: this.kinds,\n limits: this.limits,\n guard: this.guard,\n ledger: this.ledger,\n });\n this.factory = new RuntimeFactory({\n definitions: this.registry,\n kinds: this.kinds,\n limits: this.limits,\n environment: this.environment,\n runner: this.runner,\n resolveSource: key => this.resolveSource(key),\n // Left out rather than a thrower: a runtime asks whether a source\n // exists, and an editor with no source falls back to typed entry.\n ...(this.options.resolveOptions\n ? { resolveOptions: (key: string) => this.resolveOptions(key) }\n : {}),\n readInstance: id => this.readInstance(id),\n capabilities: this.capabilities,\n });\n }\n\n /** What `validateDefinition` said about one definition, for a host to show. */\n definitionIssues(definitionId: string): Issue[] {\n return this.registry.issues(definitionId);\n }\n\n permissions(definitionId: string): ViewPermissions {\n return this.guard.of(definitionId);\n }\n\n /**\n * Code-declared system views first, then whatever the store holds. An id in\n * the reserved namespace is dropped and reported: only a definition may\n * declare one.\n */\n async list(definitionId: string): Promise<ViewListing> {\n const definition = this.registry.require(definitionId);\n const declared = systemInstances(definition).map(toSummary);\n // The stored half may fail on its own: a store that is down takes the\n // saved views with it and nothing else. The declared views travel with\n // the definition, so they are listed regardless, and the failure is\n // said beside them rather than thrown over them — a list that threw\n // used to take the system views down too, and with them the one view\n // every definition promises to have (management.md).\n // The failure is the host's to hear of through `onError`, which the\n // store's own door already told (`reportingStore`); `onIssue` is for\n // findings with nothing thrown behind them (D40).\n const { stored, failed } = await storedSummaries(\n this.store,\n definitionId,\n id =>\n this.report(issue('view.list.reserved-id', [], { id }), definitionId),\n );\n const items = [...declared, ...stored];\n this.summaries.noteAll(items);\n // Titles as they are, keys and all: whatever shows a list says them.\n return { items, failed };\n }\n\n /**\n * Told whenever a write changes what a definition's list holds — a view\n * created, saved, renamed or deleted, the ledger's retries and overwrites\n * included. Returns the way to stop listening.\n *\n * The engine is the one place that knows when a write lands, so it says so\n * rather than leaving every caller to remember (D15).\n */\n subscribe(listener: ViewChangeListener): () => void {\n return this.changes.subscribe(listener);\n }\n\n async preferences(definitionId: string): Promise<ViewPreferences> {\n return this.preferenceCache.read(definitionId);\n }\n\n /** Opens a saved view, or a code-declared one without touching the store. */\n async open(\n instanceId: string,\n options: OpenOptions = {},\n ): Promise<AnyViewRuntime> {\n const instance = this.registry.ofDefinition(\n await this.readInstance(instanceId),\n options.definitionId,\n );\n // What its sources admit is read before the first query, so that query\n // already goes out narrowed.\n await this.capabilities.prepareFor(instance);\n // A dashboard opens on its tab rather than on its first and then there:\n // only the tab on screen runs, so where it starts is what is asked.\n const tab = await this.tabs.opensOn(instance, options.tab);\n const runtime = this.attach(instance, options.scopeFilter ?? null);\n // A dashboard is judged against the instances it references, so it waits\n // for them before its first apply rather than opening into empty frames —\n // on the tab and under the filters it opens with, noted before that.\n if (runtime instanceof DashboardViewRuntime)\n try {\n runtime.opensOn(tab, options.filters, options.held);\n await runtime.ready();\n } catch (error) {\n // `attach` already registered it, and a dashboard may have children\n // querying by now. Nobody is handed a runtime that failed to open,\n // so nobody could close one: it is dropped here instead of leaking.\n this.runtimes.forget(runtime);\n throw error;\n }\n runtime.apply();\n return runtime as AnyViewRuntime;\n }\n\n /** One instance, from the definition's code or from the store. */\n private async readInstance(instanceId: string): Promise<ViewInstance> {\n const declared = parseSystemInstanceId(instanceId);\n return declared\n ? this.registry.systemInstance(declared.definitionId, declared.viewId)\n : this.store.get(instanceId);\n }\n\n /**\n * An unsaved view. It carries a complete config from the start, produced by\n * `defaultRecordConfig`, `defaultAnalysisConfig` or `emptyDashboardConfig`,\n * and executes at once so the user sees data rather than an empty frame.\n *\n * No permission is asked here: nothing is written until the first save,\n * and `save` asks then. A reader who may create nothing still drills from\n * a chart into the records behind a bar — a view that is only looked at\n * costs the store nothing (H1).\n */\n create<C extends ViewConfig>(\n definitionId: string,\n input: CreateInput<C>,\n ): RuntimeFor<C> {\n const definition = this.registry.require(definitionId);\n requireTitle(input.title);\n // Made at once, so it runs on the descriptor held; one not read yet is\n // read now, for the next view over the source.\n this.capabilities.warm(definition);\n\n const runtime = this.build(\n definition,\n input.config,\n {\n title: input.title,\n scope: input.scope,\n saved: null,\n },\n input.scopeFilter ?? null,\n );\n runtime.apply();\n // The conditional type cannot be proven from a union member; what makes it\n // true is `build` rejecting a config the definition does not declare.\n return runtime as unknown as RuntimeFor<C>;\n }\n\n /** First save creates, later saves overwrite. Both need a clean draft. */\n async save(runtime: ViewRuntime): Promise<ViewInstance> {\n const target = this.runtimes.require(runtime);\n const state = target.getSnapshot();\n requireSavable(target, target.issuesAt(state.scope));\n\n if (!state.saved) {\n const input = {\n definitionId: target.definition.id,\n title: requireTitle(state.title),\n scope: state.scope,\n config: storable(target, state.draft),\n };\n this.guard.requireCreate(target.definition.id, state.scope);\n return (await this.ledger.dispatch(\n { action: 'create', input, intent: 'first-save' },\n target,\n )) as ViewInstance;\n }\n\n const saved = state.saved;\n this.guard.requireInstance(saved, 'save');\n const payload: WritePayload = {\n action: 'save',\n id: saved.id,\n revision: saved.revision,\n config: storable(target, state.draft),\n };\n return (await this.ledger.dispatch(payload, target)) as ViewInstance;\n }\n\n /**\n * A copy under a new title and scope; the source runtime is untouched.\n * `scope: 'system'` makes it a stored system view, which needs\n * `editSystem` (D81).\n */\n async saveAs(\n runtime: ViewRuntime,\n input: { title: string; scope: ViewScope },\n ): Promise<ViewInstance> {\n const target = this.runtimes.require(runtime);\n const state = target.getSnapshot();\n // Judged at the scope it is going to, not the one it came from.\n requireSavable(target, target.issuesAt(input.scope));\n const title = requireTitle(input.title);\n this.guard.requireCreate(target.definition.id, input.scope);\n\n return (await this.ledger.dispatch(\n {\n action: 'create',\n input: {\n definitionId: target.definition.id,\n title,\n scope: input.scope,\n config: storable(target, state.draft),\n },\n intent: 'save-as',\n },\n target,\n )) as ViewInstance;\n }\n\n /**\n * Saves a view a dashboard owns as a view of its own (「另存为视图」, D22 C)\n * and points the panel at it (`PanelViews`). A view the board does not\n * own, or a panel it lacks, is refused (`dashboard.panel.not-owned`).\n */\n saveOwnedView(\n dashboard: ViewRuntime,\n panelId: string,\n input: { title: string; scope: ViewScope },\n ): Promise<ViewInstance> {\n return this.panelViews.save(\n this.runtimes.require(dashboard),\n panelId,\n 'owned',\n input,\n );\n }\n\n /**\n * Copies the saved view a dashboard panel shows into another audience and\n * points the panel at the copy (「复制为共享视图并替换」, D22 B,\n * `PanelViews`): a shared board standing on someone's personal view is\n * blank for every other reader, and the copy is what they can open. A\n * panel showing no saved view this reader has open is refused\n * (`dashboard.panel.not-referenced`).\n */\n copyPanelView(\n dashboard: ViewRuntime,\n panelId: string,\n input: { title: string; scope: ViewScope },\n ): Promise<ViewInstance> {\n return this.panelViews.save(\n this.runtimes.require(dashboard),\n panelId,\n 'saved',\n input,\n );\n }\n\n /**\n * 「发布为系统视图」 (D81): a copy of the saved view `id`, as it is saved —\n * not the draft of an open one — under its own title, created as a stored\n * system view. The view it was made from is left as it is; the copy is\n * the one everyone sees, and the one an admin edits from then on.\n *\n * Asked before anything is sent: `editSystem` (`view.create.forbidden`),\n * and the config's size, as for any create. The manager offers it on\n * personal and shared rows only; a system view is published already.\n */\n publishAsSystem(id: string): Promise<ViewInstance> {\n const read = async () => this.runtimes.saved(id) ?? this.store.get(id);\n return publishCopy(this.guard, this.ledger, id, read);\n }\n\n /** Renaming carries no config, so a draft with errors does not block it. */\n async rename(id: string, title: string): Promise<ViewInstance> {\n title = requireTitle(title);\n const { revision, runtime } = await this.locate(id, 'rename');\n const payload: WritePayload = { action: 'rename', id, revision, title };\n return (await this.ledger.dispatch(payload, runtime)) as ViewInstance;\n }\n\n /**\n * 设为共享/设为个人 (D18 item 10): the saved view moves to `audience` in\n * place, id kept, through the store's optional `changeAudience` — a store\n * without it is refused here (`view.changeAudience.unsupported`), and the\n * manager offers no such button. Like a rename it carries no config, so a\n * draft with errors does not block it, and every open view of the\n * instance moves to the new baseline.\n *\n * Asked before anything is sent: the instance permission and the create\n * permission of the audience it goes to (`instanceAbilities`). Asked for\n * the audience it already has, it answers the view as it is and writes\n * nothing.\n *\n * A board shared over a personal view is not refused, as a shared board's\n * save is not (`validateDashboard`, D22 B): the panel is blank for other\n * readers and says so (`dashboard.panel.scope-too-narrow`, a warning the\n * open board takes up as it moves). The one refusal between the two is the\n * store's: a view a shared board shows is not made personal (`INVALID`).\n */\n async changeAudience(\n id: string,\n audience: ViewAudience,\n ): Promise<ViewInstance> {\n if (!this.store.changeAudience)\n throw new ViewCommandError(issue('view.changeAudience.unsupported', []));\n const { revision, scope, runtime } = await this.locate(\n id,\n 'changeAudience',\n );\n if (audienceOf(scope) === audience)\n return runtime?.getSnapshot().saved ?? this.store.get(id);\n const payload: WritePayload = {\n action: 'changeAudience',\n id,\n revision,\n audience,\n };\n return (await this.ledger.dispatch(payload, runtime)) as ViewInstance;\n }\n\n async delete(id: string): Promise<void> {\n const { definitionId, revision, runtime } = await this.locate(id, 'delete');\n const payload: WritePayload = {\n action: 'delete',\n id,\n definitionId,\n revision,\n };\n await this.ledger.dispatch(payload, runtime);\n }\n\n /** Submits the full visible order, with the revision it was read at. */\n async reorder(\n definitionId: string,\n order: string[],\n ): Promise<ViewPreferences> {\n this.guard.require(\n this.permissions(definitionId).reorder,\n 'view.preferences.reorder-forbidden',\n );\n const current = await this.preferenceCache.current(definitionId);\n return this.writePreferences(definitionId, { ...current, order });\n }\n\n async setDefault(\n definitionId: string,\n instanceId: string | null,\n ): Promise<ViewPreferences> {\n this.guard.require(\n this.permissions(definitionId).setDefault,\n 'view.preferences.default-forbidden',\n );\n const current = await this.preferenceCache.current(definitionId);\n return this.writePreferences(definitionId, {\n ...current,\n defaultInstanceId: instanceId,\n });\n }\n\n /**\n * Whether this user's analyses of the definition run again on their own as\n * they are edited (D20 改了就跑). A personal preference like the order and\n * the default, kept beside them; no permission gates it, because it\n * changes nothing anyone else sees.\n */\n async setAutoRun(\n definitionId: string,\n autoRun: boolean,\n ): Promise<ViewPreferences> {\n const current = await this.preferenceCache.current(definitionId);\n return this.writePreferences(definitionId, { ...current, autoRun });\n }\n\n /**\n * Remembers the tab this reader last read a dashboard on (D22 E), kept\n * with their other preferences for the board's definition and read back\n * by `open`. A convenience: it never rejects and never leaves an outcome\n * behind (`TabMemory`).\n */\n rememberTab(\n definitionId: string,\n instanceId: string,\n tabId: string,\n ): Promise<void> {\n return this.tabs.remember(definitionId, instanceId, tabId);\n }\n\n /**\n * The effective default: an explicit id, else the stored one when it still\n * exists, else the first of the ordered list, which is usually the first\n * system view.\n */\n resolveDefault(\n summaries: readonly ViewInstanceSummary[],\n preferences: ViewPreferences,\n explicit?: string,\n ): string | null {\n return resolveDefault(summaries, preferences, explicit);\n }\n\n /** Writes still waiting for a decision, by handle id. */\n pendingWrites(): ReadonlyMap<string, WriteState> {\n return this.ledger.pendingWrites();\n }\n\n /** Replays the original intent under its original `requestId`. */\n async retryWrite(\n target: WriteTarget,\n ): Promise<ViewInstance | ViewPreferences | void> {\n return this.ledger.retryWrite(target);\n }\n\n /** Drops the outcome and keeps the draft; a later save is a new intent. */\n abandonWrite(target: WriteTarget): void {\n this.ledger.abandonWrite(target);\n }\n\n /**\n * `reload` takes the server's state, losing the draft; `overwrite` replays\n * the original intent against the revision the conflict reported, which is a\n * new logical write and so takes a new `requestId`.\n */\n async resolveConflict(\n target: WriteTarget,\n choice: ConflictChoice,\n ): Promise<ViewInstance | ViewPreferences | void> {\n return this.ledger.resolveConflict(target, choice);\n }\n\n /** Open runtimes, for a workbench that tracks its own tabs. */\n openRuntimes(): readonly ViewRuntime[] {\n return this.runtimes.all();\n }\n\n /**\n * Closes one open view: disposes it and drops it from the registry.\n *\n * A caller that only calls `runtime.dispose()` leaves the engine holding a\n * dead runtime, which then answers `locate` with a revision nobody can write\n * against, so this is the way to let one go.\n */\n close(runtime: ViewRuntime): void {\n this.runtimes.close(runtime);\n }\n\n dispose(): void {\n this.runtimes.disposeAll();\n this.runner.cancelAll();\n this.capabilities.dispose();\n // Nothing more will be written through it, so nothing more is announced:\n // a host that forgot to unsubscribe leaves no listener behind here.\n this.changes.clear();\n }\n\n private attach(\n instance: ViewInstance,\n scopeFilter: FilterTree | null = null,\n ): ManagedViewRuntime {\n const definition = this.registry.require(instance.definitionId);\n return this.build(\n definition,\n instance.config,\n {\n title: instance.title,\n scope: instance.scope,\n saved: instance,\n },\n scopeFilter,\n );\n }\n\n private build(\n definition: ViewDefinition,\n config: ViewConfig,\n identity: RuntimeIdentity,\n scopeFilter: FilterTree | null = null,\n ): ManagedViewRuntime {\n return this.runtimes.add(\n this.factory.build(definition, config, identity, scopeFilter),\n );\n }\n\n private async writePreferences(\n definitionId: string,\n next: ViewPreferences,\n ): Promise<ViewPreferences> {\n const payload: WritePayload = { action: 'preferences', definitionId, next };\n return (await this.ledger.dispatch(payload, undefined)) as ViewPreferences;\n }\n\n /**\n * What the ledger reaches back for. A confirmed write settles in the ledger,\n * but it also moves what only the engine holds — the summary and preference\n * caches, and the open runtimes of the instance it touched — so the engine\n * lends those out as closures rather than as members of its own surface.\n */\n private ledgerHost(): WriteLedgerHost {\n return {\n store: this.store,\n newId: this.options.newId,\n noteInstance: instance => this.summaries.note(instance),\n dropInstance: (id, owner) => {\n this.summaries.drop(id);\n for (const holder of this.runtimes.holders(id, owner))\n this.runtimes.forget(holder);\n },\n notePreferences: (definitionId, preferences) =>\n this.preferenceCache.note(definitionId, preferences),\n readPreferences: definitionId => this.preferences(definitionId),\n holders: id => this.runtimes.holders(id),\n referenceOf: readReferences(this.summaries, this.store),\n noteChange: change => this.changes.emit(change),\n };\n }\n\n /**\n * What a command needs about an instance it was given only the id of: the\n * revision to write against, the definition whose list it belongs to, and\n * the open view it came through, from an open view, the last list, or the\n * store.\n */\n private async locate(\n id: string,\n action: keyof InstancePermissions,\n ): Promise<{\n revision: string;\n definitionId: string;\n scope: ViewScope;\n runtime: ManagedViewRuntime | undefined;\n }> {\n // A code-declared view is not in any store, and no store write can reach it.\n if (parseSystemInstanceId(id))\n throw new ViewCommandError(\n issue('view.system.read-only', [], { action }),\n );\n this.runtimes.prune();\n const [runtime] = this.runtimes.holders(id);\n const known = runtime?.getSnapshot().saved ?? this.summaries.get(id);\n const summary = known ?? (await this.store.get(id));\n this.guard.requireInstance(summary, action);\n return {\n revision: summary.revision,\n definitionId: summary.definitionId,\n scope: summary.scope,\n runtime,\n };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DataViewConfig,\n AnalysisViewConfig,\n DashboardDefinition,\n DashboardFilters,\n DashboardViewConfig,\n DataViewDefinition,\n FieldDefinition,\n FilterTree,\n Issue,\n PagingMode,\n RecordData,\n RecordKey,\n RecordPageTarget,\n RecordViewConfig,\n RuntimeLimits,\n ViewAudience,\n ViewConfig,\n ViewInstance,\n ViewScope,\n} from '../model/index.js';\nimport type { FieldKindRegistry } from '../filter/index.js';\nimport type { RuntimeEnvironment } from './environment.js';\nimport type { RequestRunner } from './requestRunner.js';\nimport type { OptionSource, ProjectedView, ViewSource } from './source.js';\nimport type { ExportRowsOptions, ExportedRows } from './exportRows.js';\nimport type { ValueCandidateSource } from './valueCandidates.js';\nimport type { WriteState } from './write.js';\nimport type { DashboardRuntime } from './dashboardRuntime.js';\nimport type { HeldFilters } from './dashboard/contract.js';\n\n/**\n * One open view. A small store with `subscribe` and `getSnapshot`, so React\n * binds to it with `useSyncExternalStore` and nothing else is needed.\n *\n * The three states it keeps apart are the whole design: `draft` is what the\n * editor shows, `applied` is what was last executed, and `result` is what came\n * back, tagged with the config that produced it.\n */\nexport interface ViewRuntime<C extends ViewConfig = ViewConfig> {\n /** Runtime identity, distinct from the instance id: an unsaved view has one too. */\n readonly id: string;\n readonly kind: C['kind'];\n readonly definition: DefinitionFor<C>;\n /**\n * Fields the filter editor edits against: a data view's own, a dashboard's\n * declared global ones. A dashboard's set follows its draft, so read this\n * on every render rather than once per runtime.\n */\n readonly fields: readonly FieldDefinition[];\n /** The registry admission used, which an editor must edit against. */\n readonly kinds: FieldKindRegistry;\n /**\n * The budgets this view was admitted under. An editor offers within them\n * rather than offering a choice the kernel will then refuse: a page size\n * above `maxPageSize` is an error the user made by picking from a list the\n * UI drew, which is the UI's fault and not theirs.\n */\n readonly limits: RuntimeLimits;\n /**\n * The remote candidates behind a `reference` field's `remote` key, or\n * `null` when the host wired no `resolveOptions`. The editor asks here\n * rather than reaching for the engine: a runtime is what a workbench\n * holds, and a value editor two levels down has no engine to reach.\n */\n optionSource(remote: string): OptionSource | null;\n /**\n * The values a condition on `field` may be picked from, counted from this\n * view's data within the injected scope (`ValueCandidateSources`), or\n * `null` where they are not offered: a field the definition does not let\n * be grouped by value, one with `options` or `remote` of its own, and every\n * field of a dashboard, which has no data of its own to count.\n */\n valueCandidates(field: string): ValueCandidateSource | null;\n getSnapshot(): ViewRuntimeState<C>;\n subscribe(listener: () => void): () => void;\n /**\n * Changes the draft only, synchronously.\n *\n * A member given as `undefined` is **removed** rather than set to it. A\n * config is JSON, where a member that is not there and one that is\n * `undefined` are the same config but not the same object — and `dirty`\n * is an equality against the saved one, so setting it left a view\n * permanently unsaved and the leave guard asking about an edit the user\n * had already undone. An editor that takes the last entry out of an\n * optional list therefore says `undefined` and gets the config back as it\n * was.\n */\n edit(patch: Partial<C>): void;\n /**\n * What the draft uses that its source no longer admits (capabilities.md\n * Q2): the errors admission raises against the definition as the source\n * narrows it and not against the definition as declared. The view waits\n * to be fixed, as for any error, and sends nothing. Empty when nothing\n * narrows the definition, and on a dashboard.\n */\n unavailable(): Issue[];\n /**\n * 「移除不可用的条件」: takes out of the draft what `unavailable` names\n * and can go — a condition, a sort entry, 「只保留」, a dimension's\n * missing-value group or filled gaps — and leaves the rest, which would\n * change the question rather than trim it, to the reader. Nothing runs\n * until the draft is applied.\n */\n removeUnavailable(): void;\n /** Promotes a valid draft to `applied` and executes it. */\n apply(): void;\n /**\n * Takes the draft back to the saved baseline and puts it in force again. A\n * view that was never saved has no baseline to return to, so it is a no-op\n * there; what is on screen is all there is.\n */\n revert(): void;\n /**\n * Re-runs `applied` from the first page. A no-op while `applied` was never\n * admitted: a view opened on a config the definition refuses waits for a\n * fix, and no command runs it as it stands.\n */\n refresh(): void;\n /** Called when an editor takes or loses focus; pauses auto-refresh. */\n setEditing(active: boolean): void;\n /**\n * Whether the view refreshes itself on the interval it applied (on when\n * opened). Off, the timer is held for good — the interval stays what it\n * was, and saving writes it unchanged — until it is on again: an embed\n * whose host asked for no auto-refresh (`EmbeddedView`'s `autoRefresh`).\n * A refresh asked for still runs.\n */\n setAutoRefresh(on: boolean): void;\n /**\n * Whether the draft runs on its own a moment after its question changes\n * (`autoApply.ts`); which members are the question is declared per kind\n * by the model (`autoRunMembers`), and the range still waits for `apply`.\n * Off by default: the workbench switches it on from the user's preference.\n */\n setAutoApply(on: boolean): void;\n /**\n * An outer condition ANDed onto the applied filter; never touches the draft.\n *\n * Returns what the condition was refused for, which is empty when it is in\n * force. A refusal changes nothing: the scope in force stays in force, the\n * result on screen stays on screen, and the host is told — the one thing\n * this view must never do is narrow less than the page asked without\n * saying so.\n */\n setScopeFilter(tree: FilterTree | null): Issue[];\n /**\n * What the scope last asked for was refused for, or empty while what was\n * asked for is in force.\n *\n * A refusal is the host's condition and not the view's defect, so it is not\n * among `state.issues` and does not stop the view (D17-5): a view opened\n * under a scope its definition cannot take runs un-narrowed and says this.\n * Read rather than only returned by `setScopeFilter`, because a scope goes\n * in at construction as well, and a host that opened one through\n * `ViewEngine.open` has no return value to read it from.\n */\n readonly refusedScope: Issue[];\n /**\n * The outer condition in force, as it was last admitted, or `null` while\n * none is — including a scope that was asked for and refused.\n *\n * It is read rather than only written because the conditions the rows came\n * back under are two things and not one: the view's own, which the editor\n * addresses and may take out, and the host's, which are in force and are\n * nobody's here to remove. A summary that reads the merged tree can tell\n * neither apart — see `ViewResult.own`.\n */\n readonly scopeFilter: FilterTree | null;\n /**\n * The host this view runs against: its clock, its timers, its visibility.\n *\n * Read rather than only written because `nextRefreshAt` is a reading of\n * *this* clock and means nothing against another one. A countdown that\n * asked the system clock would drift away from the timer it claims to be\n * counting to the moment a test, a demo or a server-rendered page injected\n * a clock of its own — which is the whole reason the environment exists.\n * `ViewEngine` already hands the same object out for its time zone.\n */\n readonly environment: RuntimeEnvironment;\n dispose(): void;\n /** True once disposed: every command is a no-op from then on. */\n readonly disposed: boolean;\n}\n\n/**\n * The definition a config belongs to. A dashboard owns no data, so its\n * definition is a catalogue entry with no fields and no capabilities.\n */\nexport type DefinitionFor<C extends ViewConfig> = C extends DashboardViewConfig\n ? DashboardDefinition\n : DataViewDefinition;\n\n/** Paging and selection belong to Record alone. */\nexport interface RecordViewRuntime<\n P extends PagingMode = PagingMode,\n> extends ViewRuntime<RecordViewConfig> {\n page(target: RecordPageTarget<P>): void;\n select(keys: RecordKey[]): void;\n /**\n * Every row the **applied** conditions match, paged out behind the screen\n * for an export — the same filter and sort, without the page on screen.\n *\n * It runs beside the view rather than through it: no scheduler slot, no\n * `apply`, and `state.result` is untouched, so the rows the user is reading\n * stay exactly as they are while a long export runs. Stopped by\n * `options.signal`, capped at `limits.exportMax`.\n */\n exportRows(options?: ExportRowsOptions): Promise<ExportedRows>;\n /**\n * One record, whole, by its row key — for a detail panel (`fetchRecord`):\n * every field, within the injected scope and not the page's conditions.\n * `null` when it is no longer there.\n */\n fetchRecord(key: RecordKey, signal?: AbortSignal): Promise<RecordData | null>;\n}\n\n/** What opening an instance returns; narrow it by `runtime.kind`. */\nexport type AnyViewRuntime =\n RecordViewRuntime | ViewRuntime<AnalysisViewConfig> | DashboardRuntime;\n\n/**\n * What `ViewEngine` needs beyond the public contract: admission at the scope\n * a write is headed for, and the three ways an outcome reaches an open view.\n * Both runtime classes implement it, which is how the engine stays\n * indifferent to the kind.\n */\nexport interface ManagedViewRuntime<\n C extends ViewConfig = ViewConfig,\n> extends ViewRuntime<C> {\n /**\n * Admission of the draft as it would stand at a target scope, which is what\n * \"save as shared\" has to ask: a dashboard may reference views the people it\n * would be shared with cannot read.\n */\n issuesAt(scope: ViewScope): Issue[];\n /** Advances the saved baseline once the store has confirmed this view's write. */\n markSaved(instance: ViewInstance): void;\n /**\n * Advances the baseline because a write elsewhere moved it: the same\n * instance open in another view, or renamed from the list. Whatever write\n * of this view's own is still unsettled stays so, for its recovery actions.\n */\n moveBaseline(instance: ViewInstance): void;\n /** Replaces the draft with the store's state, for \"reload\" on a conflict. */\n adoptSaved(instance: ViewInstance): void;\n /**\n * A config as it is written to the store, where that differs from how\n * the view reads it: a board stores no time wire it derives (D1). Left\n * out, as it is.\n */\n stored?(config: C): C;\n setWrite(write: WriteState | null): void;\n}\n\n/**\n * Keeps the narrow type through `create`, which knows its config statically\n * — and, for a config whose kind only the value knows (a union), is what\n * `open` hands back (`AnyViewRuntime`), so no caller has to say it again.\n */\nexport type RuntimeFor<C extends ViewConfig> = [C] extends [RecordViewConfig]\n ? RecordViewRuntime\n : [C] extends [AnalysisViewConfig]\n ? ViewRuntime<AnalysisViewConfig>\n : [C] extends [DashboardViewConfig]\n ? DashboardRuntime\n : AnyViewRuntime;\n\nexport type QueryStatus = 'idle' | 'loading' | 'success' | 'error';\n\nexport interface ViewQueryState {\n status: QueryStatus;\n error?: Issue;\n requestId?: string;\n /**\n * On a failure: the result still on screen was asked under other\n * conditions than the query that failed — the reader changed them (in\n * either filter mode) or a board's filter did, and the new ones did not\n * come back. A failed refresh of the same conditions leaves it out: its\n * rows are only older. The rows stay either way (a view that empties\n * itself on a dropped connection loses what the user was reading), and\n * this is what lets the screen say which conditions they belong to.\n */\n conditionsChanged?: true;\n}\n\nexport interface ViewResult<C> {\n /** The config that produced this data, scope filter included. */\n config: C;\n /**\n * The view's own half of it: the `applied` config as it was promoted,\n * before the scope filter was merged in.\n *\n * A summary of the conditions in force addresses the draft through this one.\n * `mergeFilters` appends the scope as a trailing group, and wraps an `or` or\n * `nor` draft as the first child of an `and`, so a path into `config.filter`\n * addresses neither the draft's tree nor anything the editor may remove —\n * and the host's own condition would sit in the bar looking removable.\n * Equal to `config` when nothing is injected, and for a dashboard, which\n * runs no query of its own.\n */\n own: C;\n data: ProjectedView;\n receivedAt: number;\n /**\n * How long the answer took, in milliseconds on the environment's clock:\n * from the moment it was asked to the moment it landed, a wait in the\n * engine's queue included — that is time the person waited too. A page\n * re-asked because the result shrank out from under it counts from the\n * first asking. The analysis result's footer says it («耗时 0.4 秒»).\n */\n elapsedMs: number;\n}\n\nexport interface ViewRuntimeState<C> {\n /** The saved baseline; `null` while the view has never been saved. */\n saved: ViewInstance | null;\n title: string;\n scope: ViewScope;\n draft: C;\n applied: C;\n /**\n * Admission of the draft as it would run: with the injected scope filter\n * ANDed in, because that is the config `apply` executes. An `error` blocks\n * `apply` and every write. The scope is appended after the draft's own\n * conditions, so a path into the draft's tree is unchanged by it.\n */\n issues: Issue[];\n dirty: boolean;\n query: ViewQueryState;\n result: ViewResult<C> | null;\n /** Row keys of the current result only; cleared when the result changes. */\n selection: RecordKey[];\n write: WriteState | null;\n editing: boolean;\n /** See `ViewRuntime.setAutoApply`. */\n autoApply: boolean;\n /**\n * When the next automatic refresh is due, on the environment's clock, or\n * `null` while no timer is armed — no interval in force, or one of the four\n * reasons the runtime holds it.\n *\n * It is the timer's own due time rather than a second opinion about it: set\n * where the timer is armed, cleared where it is stopped. A control counting\n * down to the next refresh reads this against `environment.now()`, so what\n * it says and what will happen cannot come apart; a countdown run off a\n * clock of its own would.\n */\n nextRefreshAt: number | null;\n}\n\n/**\n * Whether this view ever got a result, even one that is now out of date.\n *\n * Not `rows.length > 0` and not `status === 'success'`: a failed refresh\n * keeps the rows it could not replace and turns to `error`, and a successful\n * result matching zero rows has no rows at all. The table, the applied bar\n * and the result block all ask the same question of the same member, so they\n * ask it here — a spelling of `state.result != null` at every call site is\n * one place each for it to start meaning something else.\n *\n * Structural in its argument, because it is asked of whatever holds a\n * snapshot: a runtime's state, a controller's, or nothing yet.\n */\nexport function hasResult(\n state: { result: unknown } | null | undefined,\n): boolean {\n return state?.result != null;\n}\n\n/**\n * Whether this view has put a question to its source: a result came back,\n * one is on its way, or the last one failed.\n *\n * It is the wider question the chrome around a result asks — the applied\n * conditions, a toolbar that reads the question out — because each of those\n * has something true to say from the moment a query is sent, not only from\n * the moment one lands. Drawn only once rows arrived, they appeared under\n * the reader's eyes as the first answer landed and pushed the result down\n * the page, and a first query that failed left the failure standing alone\n * with nothing around it to act on. A query that was sent was admitted, so\n * `applied` is a config the screen may describe.\n *\n * What it is not: a view whose config was refused before it ran. Nothing\n * was asked there, and the status line is what speaks.\n */\nexport function hasAsked(\n state: { result: unknown; query: { status: QueryStatus } } | null | undefined,\n): boolean {\n if (hasResult(state)) return true;\n const status = state?.query.status;\n return status === 'loading' || status === 'error';\n}\n\nexport interface ViewRuntimeOptions<C extends DataViewConfig> {\n id: string;\n definition: DataViewDefinition;\n config: C;\n title: string;\n scope: ViewScope;\n saved?: ViewInstance | null;\n kinds: FieldKindRegistry;\n limits: RuntimeLimits;\n environment: RuntimeEnvironment;\n source: ViewSource;\n runner: RequestRunner;\n /** See `ViewRuntime.optionSource`. */\n resolveOptions?(key: string): OptionSource;\n /** An outer condition in force from the first execution on. */\n scopeFilter?: FilterTree | null;\n /**\n * False inside a dashboard, which times the refresh of every panel itself\n * rather than letting each one run a timer of its own.\n */\n autoRefresh?: boolean;\n /**\n * What the source admits, followed while the view is open\n * (capabilities.md 6); left out, the view runs on `definition` for good.\n */\n capabilities?: RuntimeCapabilities;\n}\n\n/** How one open data view follows its source's capability descriptor. */\nexport interface RuntimeCapabilities {\n /** The definition as the application declared it, before any narrowing. */\n readonly declared: DataViewDefinition;\n /**\n * The definition and the limits in force now; throws the refusal when\n * the descriptor contradicts the definition.\n */\n effective(): { definition: DataViewDefinition; limits: RuntimeLimits };\n /** Tells `listener` when the descriptor changes; returns the way to stop. */\n watch(listener: () => void): () => void;\n /** Checks the descriptor again when it is stale; a refresh is one moment to. */\n revalidate(): void;\n /**\n * Checks the descriptor again at once after the source refused a query\n * for a capability (`checksDescriptorAgain`); resolves whether it changed.\n */\n recheck(code: string | undefined): Promise<boolean>;\n}\n\n/** What `ViewEngine.create` makes a view from: nothing is saved until `save`. */\nexport interface CreateInput<C extends ViewConfig> {\n title: string;\n /** A user creates for an audience; only a definition declares a system view. */\n scope: ViewAudience;\n config: C;\n /**\n * The host's injected condition, as `open` takes it: a view made from an\n * open one — a drill-through — inherits the scope its origin ran under,\n * so it never shows a row the page around it was narrowed away from.\n */\n scopeFilter?: FilterTree | null;\n}\n\n/** How `ViewEngine.open` opens a view, beyond which one. */\nexport interface OpenOptions {\n /**\n * An outer condition in force from the first query, in the view's own field\n * names. It is admitted with the config rather than after it, so a host that\n * scopes a view — an order page showing one customer's shipments — never\n * lets an unscoped query leave, and never shows rows outside its scope.\n */\n scopeFilter?: FilterTree | null;\n /**\n * The tab a dashboard opens on (D22 E) — a host's route says it. Left out,\n * the one this reader last read the board on (`ViewPreferences.lastTabs`);\n * a tab the board lacks opens its first. Nothing else reads it.\n */\n tab?: string | null;\n /**\n * What a dashboard's filters hold as it opens (D22 F) — a host's address\n * keeps them. Left out, every filter at its default; what the board does\n * not take is left out, the rest taken (`DashboardRuntime.refusedFilters`\n * says what was left out). Nothing else reads it.\n */\n filters?: DashboardFilters | null;\n /**\n * The filters a host holds as the dashboard opens (`holdFilters`): in\n * force from the first query, over `filters` or the defaults. Nothing\n * else reads it.\n */\n held?: HeldFilters | null;\n /**\n * The definition the caller draws views of — a workbench's. An instance\n * of another is refused (`view.open.other-definition`) before anything\n * runs: an id handed over by an address two workbenches share, or by a\n * host, is no view of this page's, and opening it would show another\n * page's view under this one's list. Left out, any definition's.\n */\n definitionId?: string;\n}\n"],"mappings":";;;;AAwEA,IAAamB,KAAkC;CAC7C;CACA;CACA;AAAW,GAmBPK,KAA4B,CAChC,YAAY,GAGRE,KAA+C;CACnDE,QAAQ,CAAC,GAAGJ,IAA2B,GAAGjB,EAA2B;CACrEsB,UAAU,CAAC,GAAGL,IAA2B,GAAGvB,EAA6B;CACzE6B,WAAW3B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