@ahoo-wang/wow-view-engine 10.0.0-alpha.5 → 10.0.0-alpha.7

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 (631) hide show
  1. package/README.md +60 -16
  2. package/README.zh-CN.md +55 -16
  3. package/dist/{actions-CgaL6eEe.js → actions-BWlediub.js} +3992 -3957
  4. package/dist/actions-BWlediub.js.map +1 -0
  5. package/dist/analysis/additive.d.ts +2 -2
  6. package/dist/analysis/additive.d.ts.map +1 -1
  7. package/dist/analysis/boxplot.d.ts.map +1 -1
  8. package/dist/analysis/bucketChange.d.ts +1 -1
  9. package/dist/analysis/buckets.d.ts +5 -5
  10. package/dist/analysis/buckets.d.ts.map +1 -1
  11. package/dist/analysis/budget.d.ts.map +1 -1
  12. package/dist/analysis/candidates.d.ts +2 -1
  13. package/dist/analysis/candidates.d.ts.map +1 -1
  14. package/dist/analysis/candlestick.d.ts.map +1 -1
  15. package/dist/analysis/capability.d.ts.map +1 -1
  16. package/dist/analysis/cartesian.d.ts.map +1 -1
  17. package/dist/analysis/chartFamilies.d.ts +1 -1
  18. package/dist/analysis/chartOptions.d.ts +13 -2
  19. package/dist/analysis/chartOptions.d.ts.map +1 -1
  20. package/dist/analysis/chartSlots.d.ts.map +1 -1
  21. package/dist/analysis/compile.d.ts +1 -1
  22. package/dist/analysis/compile.d.ts.map +1 -1
  23. package/dist/analysis/currency.d.ts.map +1 -1
  24. package/dist/analysis/dangling.d.ts +2 -1
  25. package/dist/analysis/dangling.d.ts.map +1 -1
  26. package/dist/analysis/defaults.d.ts +10 -9
  27. package/dist/analysis/defaults.d.ts.map +1 -1
  28. package/dist/analysis/derived.d.ts +2 -2
  29. package/dist/analysis/derived.d.ts.map +1 -1
  30. package/dist/analysis/drill.d.ts +12 -6
  31. package/dist/analysis/drill.d.ts.map +1 -1
  32. package/dist/analysis/drillFilter.d.ts.map +1 -1
  33. package/dist/analysis/expand.d.ts +1 -1
  34. package/dist/analysis/expand.d.ts.map +1 -1
  35. package/dist/analysis/expressions.d.ts.map +1 -1
  36. package/dist/analysis/familyRules.d.ts +2 -2
  37. package/dist/analysis/familyRules.d.ts.map +1 -1
  38. package/dist/analysis/familySlots.d.ts +4 -4
  39. package/dist/analysis/fitCharts.d.ts +2 -2
  40. package/dist/analysis/fitCharts.d.ts.map +1 -1
  41. package/dist/analysis/formula.d.ts +10 -9
  42. package/dist/analysis/formula.d.ts.map +1 -1
  43. package/dist/analysis/granularity.d.ts +2 -2
  44. package/dist/analysis/granularity.d.ts.map +1 -1
  45. package/dist/analysis/having.d.ts +2 -1
  46. package/dist/analysis/having.d.ts.map +1 -1
  47. package/dist/analysis/logScale.d.ts +1 -1
  48. package/dist/analysis/metricCard.d.ts +2 -2
  49. package/dist/analysis/metricCard.d.ts.map +1 -1
  50. package/dist/analysis/metricCondition.d.ts +1 -1
  51. package/dist/analysis/metricCondition.d.ts.map +1 -1
  52. package/dist/analysis/metricFormat.d.ts +3 -2
  53. package/dist/analysis/metricFormat.d.ts.map +1 -1
  54. package/dist/analysis/metricOrder.d.ts +2 -2
  55. package/dist/analysis/metricOrder.d.ts.map +1 -1
  56. package/dist/analysis/metricWindow.d.ts.map +1 -1
  57. package/dist/analysis/project.d.ts +8 -3
  58. package/dist/analysis/project.d.ts.map +1 -1
  59. package/dist/analysis/serverLines.d.ts +5 -5
  60. package/dist/analysis/serverLines.d.ts.map +1 -1
  61. package/dist/analysis/splitOther.d.ts +1 -1
  62. package/dist/analysis/timeAxis.d.ts +3 -2
  63. package/dist/analysis/timeAxis.d.ts.map +1 -1
  64. package/dist/analysis/top.d.ts +1 -1
  65. package/dist/analysis/top.d.ts.map +1 -1
  66. package/dist/analysis/validateFamilies.d.ts.map +1 -1
  67. package/dist/analysis/validateGroups.d.ts.map +1 -1
  68. package/dist/analysis/validateLevels.d.ts.map +1 -1
  69. package/dist/analysis/validateMetrics.d.ts.map +1 -1
  70. package/dist/analysis/validateOffers.d.ts.map +1 -1
  71. package/dist/analysis/validateReferences.d.ts +2 -2
  72. package/dist/analysis/validateTop.d.ts +1 -1
  73. package/dist/analysis/validateTop.d.ts.map +1 -1
  74. package/dist/capabilities/aliases.d.ts.map +1 -1
  75. package/dist/capabilities/analysis.d.ts.map +1 -1
  76. package/dist/capabilities/cache.d.ts +3 -20
  77. package/dist/capabilities/cache.d.ts.map +1 -1
  78. package/dist/capabilities/fields.d.ts +2 -2
  79. package/dist/capabilities/fields.d.ts.map +1 -1
  80. package/dist/capabilities/match.d.ts +15 -5
  81. package/dist/capabilities/match.d.ts.map +1 -1
  82. package/dist/capabilities/narrow.d.ts.map +1 -1
  83. package/dist/capabilities/open.d.ts.map +1 -1
  84. package/dist/capabilities/record.d.ts.map +1 -1
  85. package/dist/{cartesianBrush-HLU12ig5.js → cartesianBrush-bgRuE6Ks.js} +3 -5
  86. package/dist/cartesianBrush-bgRuE6Ks.js.map +1 -0
  87. package/dist/dashboard/click.d.ts +9 -9
  88. package/dist/dashboard/click.d.ts.map +1 -1
  89. package/dist/dashboard/clickDraft.d.ts +1 -1
  90. package/dist/dashboard/edit.d.ts +6 -6
  91. package/dist/dashboard/filterEdit.d.ts +5 -6
  92. package/dist/dashboard/filterEdit.d.ts.map +1 -1
  93. package/dist/dashboard/filters.d.ts +9 -10
  94. package/dist/dashboard/filters.d.ts.map +1 -1
  95. package/dist/dashboard/index.d.ts +0 -1
  96. package/dist/dashboard/index.d.ts.map +1 -1
  97. package/dist/dashboard/layout.d.ts +2 -2
  98. package/dist/dashboard/merge.d.ts +2 -2
  99. package/dist/dashboard/panelLook.d.ts +1 -1
  100. package/dist/dashboard/panels.d.ts +1 -1
  101. package/dist/dashboard/timeBindings.d.ts +2 -12
  102. package/dist/dashboard/timeBindings.d.ts.map +1 -1
  103. package/dist/dashboard/validate.d.ts.map +1 -1
  104. package/dist/dashboard/validateFilters.d.ts +2 -2
  105. package/dist/dashboard/wiring.d.ts +5 -5
  106. package/dist/{echarts-HUGzxow7.js → echarts-rjTKpBsf.js} +3 -4
  107. package/dist/{echarts-HUGzxow7.js.map → echarts-rjTKpBsf.js.map} +1 -1
  108. package/dist/{echartsGeo-BWbXo9ef.js → echartsGeo-qZv2ZF9e.js} +2 -3
  109. package/dist/{echartsGeo-BWbXo9ef.js.map → echartsGeo-qZv2ZF9e.js.map} +1 -1
  110. package/dist/{echartsHierarchy-Cm-9-LN9.js → echartsHierarchy-DHNP9W4v.js} +2 -3
  111. package/dist/{echartsHierarchy-Cm-9-LN9.js.map → echartsHierarchy-DHNP9W4v.js.map} +1 -1
  112. package/dist/{echartsStatistics-Lq-BjHez.js → echartsStatistics-DCDWqvde.js} +2 -3
  113. package/dist/{echartsStatistics-Lq-BjHez.js.map → echartsStatistics-DCDWqvde.js.map} +1 -1
  114. package/dist/{echartsTime-gMH0oF0x.js → echartsTime-DIRSRMnr.js} +2 -3
  115. package/dist/{echartsTime-gMH0oF0x.js.map → echartsTime-DIRSRMnr.js.map} +1 -1
  116. package/dist/export-BCADqfu6.js +29 -0
  117. package/dist/export-BCADqfu6.js.map +1 -0
  118. package/dist/filter/describe.d.ts +6 -6
  119. package/dist/filter/describe.d.ts.map +1 -1
  120. package/dist/filter/kinds/array.d.ts.map +1 -1
  121. package/dist/filter/kinds/boolean.d.ts.map +1 -1
  122. package/dist/filter/kinds/dateTime.d.ts.map +1 -1
  123. package/dist/filter/kinds/deletion.d.ts +2 -2
  124. package/dist/filter/kinds/deletion.d.ts.map +1 -1
  125. package/dist/filter/kinds/duration.d.ts.map +1 -1
  126. package/dist/filter/kinds/elementMatch.d.ts.map +1 -1
  127. package/dist/filter/kinds/entries.d.ts.map +1 -1
  128. package/dist/filter/kinds/enum.d.ts.map +1 -1
  129. package/dist/filter/kinds/metadata.d.ts.map +1 -1
  130. package/dist/filter/kinds/number.d.ts.map +1 -1
  131. package/dist/filter/kinds/presence.d.ts +1 -0
  132. package/dist/filter/kinds/presence.d.ts.map +1 -1
  133. package/dist/filter/kinds/reference.d.ts +5 -0
  134. package/dist/filter/kinds/reference.d.ts.map +1 -1
  135. package/dist/filter/kinds/string.d.ts.map +1 -1
  136. package/dist/filter/operatorWords.d.ts +21 -0
  137. package/dist/filter/operatorWords.d.ts.map +1 -0
  138. package/dist/filter/search.d.ts.map +1 -1
  139. package/dist/filter/time.d.ts +2 -2
  140. package/dist/filter/time.d.ts.map +1 -1
  141. package/dist/filter/tree.d.ts.map +1 -1
  142. package/dist/filter/validate.d.ts.map +1 -1
  143. package/dist/filter/values.d.ts +6 -5
  144. package/dist/filter/values.d.ts.map +1 -1
  145. package/dist/index.d.ts +53 -89
  146. package/dist/index.d.ts.map +1 -1
  147. package/dist/index.js +224 -223
  148. package/dist/index.js.map +1 -1
  149. package/dist/model/analysis.d.ts +61 -59
  150. package/dist/model/analysis.d.ts.map +1 -1
  151. package/dist/model/chart.d.ts +16 -6
  152. package/dist/model/chart.d.ts.map +1 -1
  153. package/dist/model/config.d.ts +2 -2
  154. package/dist/model/dashboard.d.ts +28 -48
  155. package/dist/model/dashboard.d.ts.map +1 -1
  156. package/dist/model/definition.d.ts +17 -17
  157. package/dist/model/definition.d.ts.map +1 -1
  158. package/dist/model/field.d.ts +35 -5
  159. package/dist/model/field.d.ts.map +1 -1
  160. package/dist/model/filter.d.ts +5 -5
  161. package/dist/model/filter.d.ts.map +1 -1
  162. package/dist/model/index.d.ts +2 -0
  163. package/dist/model/index.d.ts.map +1 -1
  164. package/dist/model/limits.d.ts +29 -0
  165. package/dist/model/limits.d.ts.map +1 -1
  166. package/dist/model/record.d.ts +7 -6
  167. package/dist/model/record.d.ts.map +1 -1
  168. package/dist/model/text.d.ts +1 -1
  169. package/dist/model/values.d.ts +8 -0
  170. package/dist/model/values.d.ts.map +1 -0
  171. package/dist/model/wire.d.ts +32 -0
  172. package/dist/model/wire.d.ts.map +1 -0
  173. package/dist/react/actionRunner.d.ts +8 -1
  174. package/dist/react/actionRunner.d.ts.map +1 -1
  175. package/dist/react/analysisEditing.d.ts +79 -46
  176. package/dist/react/analysisEditing.d.ts.map +1 -1
  177. package/dist/react/analysisFields.d.ts +5 -5
  178. package/dist/react/analysisFields.d.ts.map +1 -1
  179. package/dist/react/engineContext.d.ts +17 -0
  180. package/dist/react/engineContext.d.ts.map +1 -0
  181. package/dist/react/index.d.ts +17 -15
  182. package/dist/react/index.d.ts.map +1 -1
  183. package/dist/react/issues.d.ts +0 -1
  184. package/dist/react/issues.d.ts.map +1 -1
  185. package/dist/react/manager/wording.d.ts +1 -1
  186. package/dist/react/manager/wording.d.ts.map +1 -1
  187. package/dist/react/recordColumns.d.ts +1 -1
  188. package/dist/react/recordColumns.d.ts.map +1 -1
  189. package/dist/react/recordDraft.d.ts.map +1 -1
  190. package/dist/react/recordEdits.d.ts.map +1 -1
  191. package/dist/react/referenceNames.d.ts +20 -0
  192. package/dist/react/referenceNames.d.ts.map +1 -0
  193. package/dist/react/useAnalysisEditor.d.ts +10 -9
  194. package/dist/react/useAnalysisEditor.d.ts.map +1 -1
  195. package/dist/react/useAnalysisResult.d.ts +17 -3
  196. package/dist/react/useAnalysisResult.d.ts.map +1 -1
  197. package/dist/react/useAutoRefresh.d.ts +8 -6
  198. package/dist/react/useAutoRefresh.d.ts.map +1 -1
  199. package/dist/react/useCreateViewEngine.d.ts +11 -0
  200. package/dist/react/useCreateViewEngine.d.ts.map +1 -0
  201. package/dist/react/useDashboard.d.ts +12 -5
  202. package/dist/react/useDashboard.d.ts.map +1 -1
  203. package/dist/react/useDatasets.d.ts +33 -21
  204. package/dist/react/useDatasets.d.ts.map +1 -1
  205. package/dist/react/useFilterEditor.d.ts.map +1 -1
  206. package/dist/react/{useViewEngine.d.ts → useOpenView.d.ts} +22 -36
  207. package/dist/react/useOpenView.d.ts.map +1 -0
  208. package/dist/react/usePanelFollowUps.d.ts +11 -2
  209. package/dist/react/usePanelFollowUps.d.ts.map +1 -1
  210. package/dist/react/useRecordActions.d.ts +14 -3
  211. package/dist/react/useRecordActions.d.ts.map +1 -1
  212. package/dist/react/useRecordDetail.d.ts +9 -6
  213. package/dist/react/useRecordDetail.d.ts.map +1 -1
  214. package/dist/react/useRecordExport.d.ts +5 -1
  215. package/dist/react/useRecordExport.d.ts.map +1 -1
  216. package/dist/react/useRecordKanban.d.ts +1 -1
  217. package/dist/react/useRecordTable.d.ts +2 -4
  218. package/dist/react/useRecordTable.d.ts.map +1 -1
  219. package/dist/react/useReferenceLabels.d.ts +9 -0
  220. package/dist/react/useReferenceLabels.d.ts.map +1 -0
  221. package/dist/react/useReshape.d.ts +2 -2
  222. package/dist/react/useSaveCommands.d.ts +3 -7
  223. package/dist/react/useSaveCommands.d.ts.map +1 -1
  224. package/dist/react/useValueCandidates.d.ts +17 -6
  225. package/dist/react/useValueCandidates.d.ts.map +1 -1
  226. package/dist/react/useViewList.d.ts +23 -11
  227. package/dist/react/useViewList.d.ts.map +1 -1
  228. package/dist/react/useViewManager.d.ts +6 -1
  229. package/dist/react/useViewManager.d.ts.map +1 -1
  230. package/dist/react/useViewRuntime.d.ts +23 -0
  231. package/dist/react/useViewRuntime.d.ts.map +1 -0
  232. package/dist/react/useWorkbench.d.ts +1 -1
  233. package/dist/react/useWorkbench.d.ts.map +1 -1
  234. package/dist/react/workbench/handOver.d.ts +10 -3
  235. package/dist/react/workbench/handOver.d.ts.map +1 -1
  236. package/dist/react/workbench/releaseDeleted.d.ts +13 -6
  237. package/dist/react/workbench/releaseDeleted.d.ts.map +1 -1
  238. package/dist/react-D1wSQhlr.js +4196 -0
  239. package/dist/react-D1wSQhlr.js.map +1 -0
  240. package/dist/react-router/index.d.ts +1 -0
  241. package/dist/react-router/index.d.ts.map +1 -1
  242. package/dist/react-router.js +1 -2
  243. package/dist/react-router.js.map +1 -1
  244. package/dist/react.js +1 -3
  245. package/dist/record/compile.d.ts.map +1 -1
  246. package/dist/record/kanban.d.ts +2 -2
  247. package/dist/record/kanban.d.ts.map +1 -1
  248. package/dist/record/paging.d.ts +11 -2
  249. package/dist/record/paging.d.ts.map +1 -1
  250. package/dist/record/project.d.ts +17 -1
  251. package/dist/record/project.d.ts.map +1 -1
  252. package/dist/record/summaryCurrency.d.ts.map +1 -1
  253. package/dist/record/validate.d.ts.map +1 -1
  254. package/dist/{routes-DvPNPlQP.js → routes-CMXKbAo2.js} +2 -3
  255. package/dist/{routes-DvPNPlQP.js.map → routes-CMXKbAo2.js.map} +1 -1
  256. package/dist/runtime/actions.d.ts +19 -7
  257. package/dist/runtime/actions.d.ts.map +1 -1
  258. package/dist/runtime/autoApply.d.ts +1 -1
  259. package/dist/runtime/capabilities.d.ts +2 -2
  260. package/dist/runtime/capabilities.d.ts.map +1 -1
  261. package/dist/runtime/dashboard/anchor.d.ts +2 -2
  262. package/dist/runtime/dashboard/anchor.d.ts.map +1 -1
  263. package/dist/runtime/dashboard/canonical.d.ts +2 -2
  264. package/dist/runtime/dashboard/commands.d.ts +2 -2
  265. package/dist/runtime/dashboard/commands.d.ts.map +1 -1
  266. package/dist/runtime/dashboard/contract.d.ts +6 -6
  267. package/dist/runtime/dashboard/contract.d.ts.map +1 -1
  268. package/dist/runtime/dashboard/editing.d.ts +2 -2
  269. package/dist/runtime/dashboard/filterCandidates.d.ts +1 -1
  270. package/dist/runtime/dashboard/filterValues.d.ts +16 -4
  271. package/dist/runtime/dashboard/filterValues.d.ts.map +1 -1
  272. package/dist/runtime/dashboard/grouping.d.ts +4 -4
  273. package/dist/runtime/dashboard/grouping.d.ts.map +1 -1
  274. package/dist/runtime/dashboard/panelRun.d.ts +2 -2
  275. package/dist/runtime/dashboard/panels.d.ts +1 -1
  276. package/dist/runtime/dashboard/press.d.ts +1 -1
  277. package/dist/runtime/dashboard/press.d.ts.map +1 -1
  278. package/dist/runtime/dashboard/references.d.ts +1 -1
  279. package/dist/runtime/dashboard/references.d.ts.map +1 -1
  280. package/dist/runtime/dashboardRuntime.d.ts +5 -2
  281. package/dist/runtime/dashboardRuntime.d.ts.map +1 -1
  282. package/dist/runtime/datasetResources.d.ts +57 -70
  283. package/dist/runtime/datasetResources.d.ts.map +1 -1
  284. package/dist/runtime/define/defineDataset.d.ts +1 -1
  285. package/dist/runtime/define/defineView.d.ts +1 -1
  286. package/dist/runtime/define/defineView.d.ts.map +1 -1
  287. package/dist/runtime/define/fields.d.ts +2 -2
  288. package/dist/runtime/define/fields.d.ts.map +1 -1
  289. package/dist/runtime/define/spec.d.ts +5 -1
  290. package/dist/runtime/define/spec.d.ts.map +1 -1
  291. package/dist/runtime/deprecated.d.ts.map +1 -1
  292. package/dist/runtime/environment.d.ts +95 -47
  293. package/dist/runtime/environment.d.ts.map +1 -1
  294. package/dist/runtime/execute.d.ts +2 -2
  295. package/dist/runtime/execute.d.ts.map +1 -1
  296. package/dist/runtime/exportRows.d.ts +10 -0
  297. package/dist/runtime/exportRows.d.ts.map +1 -1
  298. package/dist/runtime/failure/failures.d.ts +23 -11
  299. package/dist/runtime/failure/failures.d.ts.map +1 -1
  300. package/dist/runtime/failure/queryFailure.d.ts +1 -1
  301. package/dist/runtime/failure/queryFailure.d.ts.map +1 -1
  302. package/dist/runtime/failure/unavailable.d.ts +1 -1
  303. package/dist/runtime/fetchRecord.d.ts.map +1 -1
  304. package/dist/runtime/index.d.ts +5 -3
  305. package/dist/runtime/index.d.ts.map +1 -1
  306. package/dist/runtime/instanceWrites.d.ts +15 -9
  307. package/dist/runtime/instanceWrites.d.ts.map +1 -1
  308. package/dist/runtime/kanban.d.ts +1 -1
  309. package/dist/runtime/labelIds.d.ts +56 -0
  310. package/dist/runtime/labelIds.d.ts.map +1 -0
  311. package/dist/runtime/navigation.d.ts +6 -6
  312. package/dist/runtime/panelViews.d.ts +3 -5
  313. package/dist/runtime/panelViews.d.ts.map +1 -1
  314. package/dist/runtime/pending.d.ts +2 -2
  315. package/dist/runtime/permissions.d.ts +2 -2
  316. package/dist/runtime/preferences.d.ts +2 -2
  317. package/dist/runtime/preferences.d.ts.map +1 -1
  318. package/dist/runtime/queryWeight.d.ts.map +1 -1
  319. package/dist/runtime/recordRuntime.d.ts +10 -1
  320. package/dist/runtime/recordRuntime.d.ts.map +1 -1
  321. package/dist/runtime/referenceLabels.d.ts +170 -0
  322. package/dist/runtime/referenceLabels.d.ts.map +1 -0
  323. package/dist/runtime/resources.d.ts +31 -93
  324. package/dist/runtime/resources.d.ts.map +1 -1
  325. package/dist/runtime/restyle.d.ts +1 -1
  326. package/dist/runtime/runtimeFactory.d.ts +5 -4
  327. package/dist/runtime/runtimeFactory.d.ts.map +1 -1
  328. package/dist/runtime/source.d.ts +55 -48
  329. package/dist/runtime/source.d.ts.map +1 -1
  330. package/dist/runtime/summaries.d.ts +9 -1
  331. package/dist/runtime/summaries.d.ts.map +1 -1
  332. package/dist/runtime/tabMemory.d.ts +1 -1
  333. package/dist/runtime/validateFields.d.ts.map +1 -1
  334. package/dist/runtime/valueCandidates.d.ts.map +1 -1
  335. package/dist/runtime/viewEngine.d.ts +97 -105
  336. package/dist/runtime/viewEngine.d.ts.map +1 -1
  337. package/dist/runtime/viewEngineOptions.d.ts +79 -0
  338. package/dist/runtime/viewEngineOptions.d.ts.map +1 -0
  339. package/dist/runtime/viewRuntime.d.ts +6 -9
  340. package/dist/runtime/viewRuntime.d.ts.map +1 -1
  341. package/dist/runtime/viewRuntimeTypes.d.ts +39 -8
  342. package/dist/runtime/viewRuntimeTypes.d.ts.map +1 -1
  343. package/dist/store/MemoryViewStore.d.ts +16 -16
  344. package/dist/store/MemoryViewStore.d.ts.map +1 -1
  345. package/dist/store/ViewStore.d.ts +31 -19
  346. package/dist/store/ViewStore.d.ts.map +1 -1
  347. package/dist/styles.css +1 -1
  348. package/dist/testing/actions.d.ts +6 -4
  349. package/dist/testing/actions.d.ts.map +1 -1
  350. package/dist/testing/aggregate.d.ts +4 -2
  351. package/dist/testing/aggregate.d.ts.map +1 -1
  352. package/dist/testing/filter.d.ts +3 -3
  353. package/dist/testing/filter.d.ts.map +1 -1
  354. package/dist/testing/index.d.ts +2 -2
  355. package/dist/testing/index.d.ts.map +1 -1
  356. package/dist/testing/source.d.ts +4 -4
  357. package/dist/testing/source.d.ts.map +1 -1
  358. package/dist/testing.js +99 -96
  359. package/dist/testing.js.map +1 -1
  360. package/dist/theme-check.mjs +102 -127
  361. package/dist/ui/DashboardWorkbench.d.ts +2 -2
  362. package/dist/ui/DashboardWorkbench.d.ts.map +1 -1
  363. package/dist/ui/DataWorkbench.d.ts +2 -2
  364. package/dist/ui/DataWorkbench.d.ts.map +1 -1
  365. package/dist/ui/DatasetWorkbench.d.ts +11 -21
  366. package/dist/ui/DatasetWorkbench.d.ts.map +1 -1
  367. package/dist/ui/EmbeddedDashboard.d.ts +1 -1
  368. package/dist/ui/EmbeddedDashboard.d.ts.map +1 -1
  369. package/dist/ui/EmbeddedView.d.ts +1 -1
  370. package/dist/ui/ViewHost.d.ts +6 -6
  371. package/dist/ui/ViewHost.d.ts.map +1 -1
  372. package/dist/ui/actions/ActionSurface.d.ts.map +1 -1
  373. package/dist/ui/actions/BulkStatus.d.ts.map +1 -1
  374. package/dist/ui/actions/kanbanMove.d.ts +1 -1
  375. package/dist/ui/analysis/AnalysisTable.d.ts.map +1 -1
  376. package/dist/ui/analysis/AnalysisToolbar.d.ts +1 -1
  377. package/dist/ui/analysis/AnalysisToolbar.d.ts.map +1 -1
  378. package/dist/ui/analysis/AxesTab.d.ts +1 -1
  379. package/dist/ui/analysis/CardMenu.d.ts +1 -1
  380. package/dist/ui/analysis/ChartOptions.d.ts +1 -1
  381. package/dist/ui/analysis/ChartOptions.d.ts.map +1 -1
  382. package/dist/ui/analysis/ChartPicker.d.ts +1 -1
  383. package/dist/ui/analysis/CompositionOptions.d.ts +1 -1
  384. package/dist/ui/analysis/CurrencyStrip.d.ts.map +1 -1
  385. package/dist/ui/analysis/DataTab.d.ts +1 -1
  386. package/dist/ui/analysis/DimensionCard.d.ts.map +1 -1
  387. package/dist/ui/analysis/DisplayTab.d.ts +1 -1
  388. package/dist/ui/analysis/DisplayTab.d.ts.map +1 -1
  389. package/dist/ui/analysis/DrillMenu.d.ts +1 -1
  390. package/dist/ui/analysis/DroppedNotice.d.ts +1 -1
  391. package/dist/ui/analysis/ElementsSlot.d.ts +1 -1
  392. package/dist/ui/analysis/ExportMenu.d.ts +3 -3
  393. package/dist/ui/analysis/ExportMenu.d.ts.map +1 -1
  394. package/dist/ui/analysis/FormulaCard.d.ts.map +1 -1
  395. package/dist/ui/analysis/HavingRows.d.ts +1 -1
  396. package/dist/ui/analysis/HavingRows.d.ts.map +1 -1
  397. package/dist/ui/analysis/LevelOptions.d.ts +1 -1
  398. package/dist/ui/analysis/MapOptions.d.ts +1 -1
  399. package/dist/ui/analysis/MetricCard.d.ts +1 -1
  400. package/dist/ui/analysis/MetricCard.d.ts.map +1 -1
  401. package/dist/ui/analysis/MetricCondition.d.ts +1 -1
  402. package/dist/ui/analysis/MetricCondition.d.ts.map +1 -1
  403. package/dist/ui/analysis/MetricSlot.d.ts +1 -1
  404. package/dist/ui/analysis/MetricSlot.d.ts.map +1 -1
  405. package/dist/ui/analysis/RangeSlot.d.ts +1 -1
  406. package/dist/ui/analysis/ReferenceOptions.d.ts +1 -1
  407. package/dist/ui/analysis/TermTip.d.ts +1 -1
  408. package/dist/ui/analysis/TopRow.d.ts +1 -1
  409. package/dist/ui/analysis/TopRow.d.ts.map +1 -1
  410. package/dist/ui/analysis/Tray.d.ts +1 -1
  411. package/dist/ui/analysis/Tray.d.ts.map +1 -1
  412. package/dist/ui/analysis/VisualizationPanel.d.ts +2 -2
  413. package/dist/ui/analysis/VisualizationPanel.d.ts.map +1 -1
  414. package/dist/ui/analysis/editing.d.ts +2 -2
  415. package/dist/ui/analysis/editing.d.ts.map +1 -1
  416. package/dist/ui/analysis/exportOffer.d.ts +3 -3
  417. package/dist/ui/analysis/headerSort.d.ts.map +1 -1
  418. package/dist/ui/analysis/imageExport.d.ts +3 -3
  419. package/dist/ui/analysis/imageExport.d.ts.map +1 -1
  420. package/dist/ui/charts/EChart.d.ts +2 -2
  421. package/dist/ui/charts/GeoMap.d.ts +1 -1
  422. package/dist/ui/charts/Heatmap.d.ts +1 -1
  423. package/dist/ui/charts/MetricCard.d.ts.map +1 -1
  424. package/dist/ui/charts/PieSlices.d.ts +1 -1
  425. package/dist/ui/charts/ScatterPoints.d.ts +1 -1
  426. package/dist/ui/charts/ScatterPoints.d.ts.map +1 -1
  427. package/dist/ui/charts/axis.d.ts +2 -2
  428. package/dist/ui/charts/cartesianTooltip.d.ts +2 -2
  429. package/dist/ui/charts/dateTicks.d.ts +2 -2
  430. package/dist/ui/charts/dateTicks.d.ts.map +1 -1
  431. package/dist/ui/charts/family.d.ts +1 -1
  432. package/dist/ui/charts/family.d.ts.map +1 -1
  433. package/dist/ui/charts/familyViews.d.ts +1 -1
  434. package/dist/ui/charts/frameClass.d.ts +2 -2
  435. package/dist/ui/charts/highlight.d.ts +2 -2
  436. package/dist/ui/charts/image.d.ts +22 -6
  437. package/dist/ui/charts/image.d.ts.map +1 -1
  438. package/dist/ui/charts/maps.d.ts +1 -1
  439. package/dist/ui/charts/waterfallOption.d.ts +2 -2
  440. package/dist/ui/colorMode.d.ts +1 -2
  441. package/dist/ui/colorMode.d.ts.map +1 -1
  442. package/dist/ui/columns/ColumnSettings.d.ts +6 -1
  443. package/dist/ui/columns/ColumnSettings.d.ts.map +1 -1
  444. package/dist/ui/dashboard/AddMenu.d.ts +2 -2
  445. package/dist/ui/dashboard/Board.d.ts +1 -1
  446. package/dist/ui/dashboard/BoardDestination.d.ts +2 -2
  447. package/dist/ui/dashboard/BoardFilters.d.ts +1 -1
  448. package/dist/ui/dashboard/BoardWidth.d.ts +1 -1
  449. package/dist/ui/dashboard/ClickSettings.d.ts +4 -4
  450. package/dist/ui/dashboard/ContentEditor.d.ts +1 -1
  451. package/dist/ui/dashboard/DashboardArrange.d.ts +1 -1
  452. package/dist/ui/dashboard/DashboardGrid.d.ts +3 -3
  453. package/dist/ui/dashboard/DashboardGrid.d.ts.map +1 -1
  454. package/dist/ui/dashboard/{DashboardPanel.d.ts → DashboardPanelCard.d.ts} +3 -3
  455. package/dist/ui/dashboard/DashboardPanelCard.d.ts.map +1 -0
  456. package/dist/ui/dashboard/DashboardPanels.d.ts +4 -4
  457. package/dist/ui/dashboard/DashboardPanels.d.ts.map +1 -1
  458. package/dist/ui/dashboard/DashboardTabs.d.ts +1 -1
  459. package/dist/ui/dashboard/EditBar.d.ts +1 -1
  460. package/dist/ui/dashboard/FilterBar.d.ts +1 -1
  461. package/dist/ui/dashboard/FilterOrder.d.ts +1 -1
  462. package/dist/ui/dashboard/FilterReadings.d.ts +1 -1
  463. package/dist/ui/dashboard/FilterReadings.d.ts.map +1 -1
  464. package/dist/ui/dashboard/FilterSettings.d.ts +2 -2
  465. package/dist/ui/dashboard/FilterSettings.d.ts.map +1 -1
  466. package/dist/ui/dashboard/FilterSheet.d.ts +1 -1
  467. package/dist/ui/dashboard/FilterWiring.d.ts +2 -2
  468. package/dist/ui/dashboard/GridBlocksLayer.d.ts +1 -1
  469. package/dist/ui/dashboard/GroupingControl.d.ts +4 -4
  470. package/dist/ui/dashboard/GroupingControl.d.ts.map +1 -1
  471. package/dist/ui/dashboard/NewAnalysisDialog.d.ts +1 -1
  472. package/dist/ui/dashboard/NewAnalysisDialog.d.ts.map +1 -1
  473. package/dist/ui/dashboard/PanelBodies.d.ts +9 -8
  474. package/dist/ui/dashboard/PanelBodies.d.ts.map +1 -1
  475. package/dist/ui/dashboard/PanelExport.d.ts +3 -3
  476. package/dist/ui/dashboard/PanelMenu.d.ts +1 -1
  477. package/dist/ui/dashboard/PresentationDialog.d.ts +1 -1
  478. package/dist/ui/dashboard/PresentationDialog.d.ts.map +1 -1
  479. package/dist/ui/dashboard/ScrollCue.d.ts +1 -1
  480. package/dist/ui/dashboard/ViewPicker.d.ts +1 -1
  481. package/dist/ui/dashboard/ViewPicker.d.ts.map +1 -1
  482. package/dist/ui/dashboard/buildShell.d.ts +2 -2
  483. package/dist/ui/dashboard/building.d.ts +1 -1
  484. package/dist/ui/dashboard/building.d.ts.map +1 -1
  485. package/dist/ui/dashboard/commands.d.ts +4 -4
  486. package/dist/ui/dashboard/commands.d.ts.map +1 -1
  487. package/dist/ui/dashboard/extensions.d.ts +1 -1
  488. package/dist/ui/dashboard/filterModes.d.ts +3 -3
  489. package/dist/ui/dashboard/filterOutcome.d.ts.map +1 -1
  490. package/dist/ui/dashboard/findings.d.ts +1 -1
  491. package/dist/ui/dashboard/gridBlocks.d.ts +1 -1
  492. package/dist/ui/dashboard/panelFit.d.ts +2 -2
  493. package/dist/ui/dashboard/press.d.ts +2 -2
  494. package/dist/ui/dashboard/press.d.ts.map +1 -1
  495. package/dist/ui/dashboard/reveal.d.ts +1 -1
  496. package/dist/ui/dashboard/scrollMore.d.ts +1 -1
  497. package/dist/ui/datasetBindings.d.ts +3 -11
  498. package/dist/ui/datasetBindings.d.ts.map +1 -1
  499. package/dist/ui/embed/EmbedFrame.d.ts +1 -1
  500. package/dist/ui/embed/EmbedFrame.d.ts.map +1 -1
  501. package/dist/ui/embed/EmbedHead.d.ts +5 -5
  502. package/dist/ui/embed/EmbedHead.d.ts.map +1 -1
  503. package/dist/ui/embed/EmbeddedAnalysis.d.ts +4 -4
  504. package/dist/ui/embed/EmbeddedAnalysis.d.ts.map +1 -1
  505. package/dist/ui/embed/EmbeddedRecord.d.ts +1 -1
  506. package/dist/ui/embed/options.d.ts +4 -4
  507. package/dist/ui/embed/options.d.ts.map +1 -1
  508. package/dist/ui/filter/inputs/daterange.d.ts.map +1 -1
  509. package/dist/ui/filter/inputs/duration.d.ts.map +1 -1
  510. package/dist/ui/filter/inputs/remote.d.ts +3 -1
  511. package/dist/ui/filter/inputs/remote.d.ts.map +1 -1
  512. package/dist/ui/index.d.ts +6 -7
  513. package/dist/ui/index.d.ts.map +1 -1
  514. package/dist/ui/kit/ExportDialog.d.ts +2 -2
  515. package/dist/ui/kit/ExportDialog.d.ts.map +1 -1
  516. package/dist/ui/kit/IconButton.d.ts +1 -1
  517. package/dist/ui/kit/MessagesProvider.d.ts +3 -3
  518. package/dist/ui/kit/RenameInput.d.ts +2 -2
  519. package/dist/ui/kit/RenderBoundary.d.ts.map +1 -1
  520. package/dist/ui/kit/RowItem.d.ts +1 -1
  521. package/dist/ui/kit/ViewSurface.d.ts +16 -6
  522. package/dist/ui/kit/ViewSurface.d.ts.map +1 -1
  523. package/dist/ui/kit/alerts.d.ts +2 -2
  524. package/dist/ui/kit/alerts.d.ts.map +1 -1
  525. package/dist/ui/kit/chartFailure.d.ts +1 -3
  526. package/dist/ui/kit/chartFailure.d.ts.map +1 -1
  527. package/dist/ui/kit/datePart.d.ts +2 -2
  528. package/dist/ui/kit/datePart.d.ts.map +1 -1
  529. package/dist/ui/kit/display.d.ts +25 -6
  530. package/dist/ui/kit/display.d.ts.map +1 -1
  531. package/dist/ui/kit/dragPlugins.d.ts +3 -3
  532. package/dist/ui/kit/failureSink.d.ts +1 -1
  533. package/dist/ui/kit/failureSink.d.ts.map +1 -1
  534. package/dist/ui/kit/features.d.ts +2 -2
  535. package/dist/ui/kit/features.d.ts.map +1 -1
  536. package/dist/ui/kit/icon.d.ts +9 -0
  537. package/dist/ui/kit/icon.d.ts.map +1 -0
  538. package/dist/ui/kit/kinds.d.ts +4 -4
  539. package/dist/ui/kit/kinds.d.ts.map +1 -1
  540. package/dist/ui/kit/layout.d.ts +2 -2
  541. package/dist/ui/kit/messages.d.ts.map +1 -1
  542. package/dist/ui/kit/presets.d.ts +2 -2
  543. package/dist/ui/kit/summary.d.ts +8 -10
  544. package/dist/ui/kit/summary.d.ts.map +1 -1
  545. package/dist/ui/kit/surfaceContext.d.ts +4 -3
  546. package/dist/ui/kit/surfaceContext.d.ts.map +1 -1
  547. package/dist/ui/kit/surfaceKeys.d.ts +1 -1
  548. package/dist/ui/kit/toolbar.d.ts +21 -4
  549. package/dist/ui/kit/toolbar.d.ts.map +1 -1
  550. package/dist/ui/kit/variants.d.ts +5 -5
  551. package/dist/ui/manage/DatasetWordingForm.d.ts +2 -2
  552. package/dist/ui/messages/analysis.d.ts +61 -57
  553. package/dist/ui/messages/analysis.d.ts.map +1 -1
  554. package/dist/ui/messages/building.d.ts +1 -1
  555. package/dist/ui/messages/capabilities.d.ts +5 -1
  556. package/dist/ui/messages/capabilities.d.ts.map +1 -1
  557. package/dist/ui/messages/clicks.d.ts +1 -1
  558. package/dist/ui/messages/datasets.d.ts +3 -2
  559. package/dist/ui/messages/datasets.d.ts.map +1 -1
  560. package/dist/ui/messages/definition.d.ts +2 -1
  561. package/dist/ui/messages/definition.d.ts.map +1 -1
  562. package/dist/ui/messages/embed.d.ts +1 -1
  563. package/dist/ui/messages/en.d.ts +240 -222
  564. package/dist/ui/messages/en.d.ts.map +1 -1
  565. package/dist/ui/messages/export.d.ts +1 -1
  566. package/dist/ui/messages/filter.d.ts +99 -98
  567. package/dist/ui/messages/filter.d.ts.map +1 -1
  568. package/dist/ui/messages/filters.d.ts +1 -1
  569. package/dist/ui/messages/record.d.ts +21 -16
  570. package/dist/ui/messages/record.d.ts.map +1 -1
  571. package/dist/ui/messages/view.d.ts +51 -49
  572. package/dist/ui/messages/view.d.ts.map +1 -1
  573. package/dist/ui/messages/wireKey.d.ts +17 -0
  574. package/dist/ui/messages/wireKey.d.ts.map +1 -0
  575. package/dist/ui/messages/zh-CN.d.ts.map +1 -1
  576. package/dist/ui/record/CardSettings.d.ts.map +1 -1
  577. package/dist/ui/record/CardSummaries.d.ts +1 -1
  578. package/dist/ui/record/OffscreenSummary.d.ts +1 -1
  579. package/dist/ui/record/RecordDetail.d.ts +1 -2
  580. package/dist/ui/record/RecordDetail.d.ts.map +1 -1
  581. package/dist/ui/record/RecordKanban.d.ts +1 -1
  582. package/dist/ui/record/RecordPagination.d.ts +3 -1
  583. package/dist/ui/record/RecordPagination.d.ts.map +1 -1
  584. package/dist/ui/record/SelectionBar.d.ts +2 -2
  585. package/dist/ui/record/SortableHeader.d.ts.map +1 -1
  586. package/dist/ui/record/cells.d.ts.map +1 -1
  587. package/dist/ui/record/exportOffer.d.ts +1 -1
  588. package/dist/ui/record/exportOffer.d.ts.map +1 -1
  589. package/dist/ui/record/kanbanDrag.d.ts +2 -2
  590. package/dist/ui/record/offscreenSummaries.d.ts +2 -2
  591. package/dist/ui/record/overflow.d.ts +1 -1
  592. package/dist/ui/record/queryAnnouncement.d.ts.map +1 -1
  593. package/dist/ui/record/resultCount.d.ts +10 -0
  594. package/dist/ui/record/resultCount.d.ts.map +1 -0
  595. package/dist/ui/record/sticky.d.ts +1 -1
  596. package/dist/ui/record/useOffscreenColumns.d.ts +1 -1
  597. package/dist/ui/record/useSummaries.d.ts.map +1 -1
  598. package/dist/ui/sort/SortSettings.d.ts.map +1 -1
  599. package/dist/ui/theme/tokens.d.ts +1 -1
  600. package/dist/ui/viewNavigation.d.ts.map +1 -1
  601. package/dist/ui/workbench/AddToDashboardDialog.d.ts +1 -1
  602. package/dist/ui/workbench/AnalysisParts.d.ts +1 -1
  603. package/dist/ui/workbench/MoreViewActions.d.ts +1 -1
  604. package/dist/ui/workbench/OriginBar.d.ts +1 -1
  605. package/dist/ui/workbench/RefreshControl.d.ts.map +1 -1
  606. package/dist/ui/workbench/ResultBlock.d.ts +1 -1
  607. package/dist/ui/workbench/Sidebar.d.ts +2 -2
  608. package/dist/ui/workbench/StatusLine.d.ts +1 -1
  609. package/dist/ui/workbench/ViewEngineProvider.d.ts +0 -9
  610. package/dist/ui/workbench/ViewEngineProvider.d.ts.map +1 -1
  611. package/dist/ui/workbench/WorkbenchShell.d.ts +3 -3
  612. package/dist/ui/workbench/WorkbenchShell.d.ts.map +1 -1
  613. package/dist/ui/workbench/address.d.ts.map +1 -1
  614. package/dist/ui.js +13798 -13843
  615. package/dist/ui.js.map +1 -1
  616. package/dist/{viewRuntimeTypes-B3B6hbXr.js → viewRuntimeTypes-BCdG5xRp.js} +1950 -2122
  617. package/dist/viewRuntimeTypes-BCdG5xRp.js.map +1 -0
  618. package/package.json +17 -17
  619. package/dist/actions-CgaL6eEe.js.map +0 -1
  620. package/dist/cartesianBrush-HLU12ig5.js.map +0 -1
  621. package/dist/clickDraft-CdUtkL4y.js +0 -184
  622. package/dist/clickDraft-CdUtkL4y.js.map +0 -1
  623. package/dist/dashboard/migrate.d.ts +0 -33
  624. package/dist/dashboard/migrate.d.ts.map +0 -1
  625. package/dist/react/useViewEngine.d.ts.map +0 -1
  626. package/dist/react-BuHt29n6.js +0 -3855
  627. package/dist/react-BuHt29n6.js.map +0 -1
  628. package/dist/runtime/storedViews.d.ts +0 -10
  629. package/dist/runtime/storedViews.d.ts.map +0 -1
  630. package/dist/ui/dashboard/DashboardPanel.d.ts.map +0 -1
  631. package/dist/viewRuntimeTypes-B3B6hbXr.js.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["QueryModelDescriptor","AnalysisCapability","AnalysisSpec","FieldAnalysisSpec","Issue","OpenCapabilities","issue","describedAnalysis","BuiltField","analysisPlan","spec","fields","undefined","narrowed","entry","analysis","plan","NonNullable","elements","own","described","children","entries","Record","child","one","field","name","buildAnalysis","descriptor","findings","map","what","push","TimeUnit","FieldDescriptor","QueryModelDescriptor","TEMPORAL_FIELD_KIND_IDS","FieldDefinition","FieldKindId","FieldOption","FieldTemporal","Issue","PagingMode","issue","describedField","DescribedField","FieldSpec","OptionSpec","FieldBuild","descriptor","paging","findings","BuiltField","field","described","spec","sensitive","children","found","code","params","Record","severity","buildFields","listed","Readonly","scope","build","Object","entries","flatMap","key","given","label","built","buildField","path","undefined","search","searchField","push","raw","fieldDescriptor","canonical","kind","kindOf","name","labelOf","comparable","sorts","sort","cursor","paged","sortsByDefault","sortable","operators","offered","operatorsOffered","operator","has","summary","functions","aggregate","fn","includes","options","optionsOf","temporal","temporalOf","deprecated","message","elements","some","element","map","entry","elementTitle","cell","timePrecision","assign","more","fields","searchFields","mode","searchMode","own","find","relative","slice","length","variants","values","variant","aliases","semantic","type","timeUnit","SECONDS","enum","types","description","ReadonlySet","Set","filter","add","listedOptions","value","option","known","Map","String","said","get","Array","isArray","keys","Exclude","temporalOf","QueryModelDescriptor","DataViewDefinition","FieldDefinition","Issue","PagingMode","RecordCapability","issue","analysisPlan","buildAnalysis","buildFields","BuiltField","narrowDefinition","constructible","builtinFieldKinds","FieldKindRegistry","DefineViewSpec","defineView","descriptor","spec","options","DefineViewOptions","findings","record","recordOf","fields","undefined","paging","definition","id","title","kind","source","map","entry","field","recordNoun","fieldGroups","plan","analysis","timeField","views","sort","flatMap","given","described","sortable","name","operators","openComparisons","withSnapshotComparisons","kinds","Set","version","open","scope","children","path","own","narrowed","ReadonlySet","index","cut","next","has","elements","PAGING","Readonly","Record","PAGED","CURSOR","offered","mode","includes","push","rowKey","identity","layouts","QueryModelDescriptor","DataViewDefinition","defineView","DefineViewOptions","FieldSpec","DefineDatasetSpec","id","source","title","recordNoun","fields","Readonly","Record","defineDataset","descriptor","spec","options","derived","Map","field","scope","undefined","set","path","description","override","Object","entries","label","get","delete","defineDataset","DefineDatasetSpec","WriteContext","ViewSource","DatasetDirectoryEntry","contextName","name","title","version","DatasetCatalog","list","Promise","source","entry","overrides","DatasetOverrides","wordings","DatasetWordingStore","StoredDatasetWording","wording","revision","signal","AbortSignal","ReadonlyMap","set","dataset","context","DatasetWordingEditor","derivedTitle","fields","label","save","Partial","Pick","DatasetRegistrar","definitions","register","resource","definition","ReturnType","unregister","definitionId","DatasetResource","id","catalog","DatasetDuplicate","dropped","kept","DatasetResourcesOptions","onDuplicate","duplicate","onCatalogError","error","Listed","DatasetResources","catalogs","held","Map","worded","stored","derived","descriptor","Parameters","found","constructor","engine","onError","undefined","onWordingError","options","Array","isArray","length","Error","resources","values","duplicates","refresh","readWordings","lists","allSettled","map","every","status","reason","servable","unread","Set","forEach","add","value","get","push","has","keys","delete","all","listed","serve","order","slice","sort","a","b","indexOf","read","index","store","wordingOf","words","JSON","stringify","described","describe","notModified","registerWorded","current","editorOf","plain","ViewInstance","MemorySnapshot","MemoryState","LocalStorageSnapshotOptions","storage","getItem","key","setItem","value","events","addEventListener","type","listener","event","storageArea","removeEventListener","KeptStorage","ReturnType","NonNullable","localStorageSnapshot","options","ambientStorage","undefined","ambientEvents","load","parseState","save","state","JSON","stringify","subscribe","onStorage","readable","globalThis","localStorage","Error","target","Partial","saved","parse","Array","isArray","instances","preferences","filter","isHeld","instance","id","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","ViewStore","list","definitionId","signal","AbortSignal","Promise","get","id","create","input","Omit","context","WriteContext","save","config","revision","rename","title","delete","getPreferences","setPreferences","preferences","changeAudience","audience","permissions","ViewPermissions","listLimit","requestId","createPersonal","createShared","reorder","setDefault","editSystem","editDatasetWording","instance","InstancePermissions","emptyPreferences","order","defaultInstanceId","audienceOf","configBytes","isSystemInstanceId","isSystemScope","MAX_VIEW_CONFIG_BYTES","MAX_VIEW_TITLE_LENGTH","titleProblem","toSummary","ViewStoreError","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","emptyPreferences","ViewPermissions","ViewStore","WriteContext","MemoryViewStoreOptions","instances","preferences","Record","permissions","definitionId","snapshot","MemorySnapshot","listLimit","load","MemoryState","save","state","subscribe","listener","MemoryViewStore","Map","outcomes","preferenceOutcomes","sequence","constructor","options","undefined","restored","restore","reload","list","Promise","summaries","values","filter","instance","map","sort","a","b","AUDIENCE_RANK","scope","limit","resolve","seen","summary","count","get","set","id","copy","reject","create","input","Omit","context","replayed","requestId","refused","titleRefusal","title","configRefusal","config","has","given","stored","trim","revision","const","commit","delete","update","current","rename","changeAudience","audience","boards","sharedBoardsShowing","length","join","readOnlySystem","conflict","expect","persist","getPreferences","setPreferences","held","next","nextRevision","change","changed","kind","panels","Array","isArray","some","panel","shows","push","undo","Object","fromEntries","error","reasonOf","storage","clear","entries","instanceId","owned","opens","click","Readonly","system","shared","personal","test","String","Number","bytes","name","message","value","T","structuredClone","updateAt","resolveDateTimeRange","relativeFields","TEMPORAL_FIELD_KIND_IDS","freeAlias","ANALYSIS_DATE_UNITS","isContentPanel","compileFilter","BUILTIN_FIELD_KINDS","CHART_PICKER_ORDER","audienceOf","withSmooth","MAX_DASHBOARD_FILTERS","takesGroup","isEmptyFilter","variantGroups","formulaFormat","DEFAULT_SEARCH_MODE","valueLabelsOn","CARTESIAN_MISSING","filterControlValue","validateDefinition","describePresence","durationMetric","MAX_TIMER_DELAY_MS","offersStacking","columnHidden","mergeGlobalFilter","isViewCommandError","compileSummaries","isFormula","MAX_VIEW_TITLE_LENGTH","withMovedTo","DASHBOARD_GRID_COLUMNS","fillUrl","ViewWriteError","compileRecord","isDuration","MAX_VIEW_CONFIG_BYTES","stageValues","DASHBOARD_FILTER_TYPES","crossFilterChoices","countLeaves","numberFieldKind","analysisProbeLimit","FILTER_GROUP_OPERATORS","PEAKS_ONLY_FROM","PANEL_PRESENTATION_MEMBERS","FILTER_TYPE_OPERATOR","isSimpleTree","dateFieldKind","metricMeasures","FIELD_CELL_IDS","MAX_CHART_LEVELS","filtersOf","isFilterLeaf","deletionFieldKind","metricFormat","DEFAULT_TEMPORAL","CHART_FAMILY","filterOperatorOf","durationFrom","METADATA_FIELD_KINDS","asksForWhole","isFilterGroupOperator","chartMarks","boardWidth","ONE_DAY_PRESETS","nodeAt","analysisScope","METADATA_FIELD_KIND_IDS","bucketRange","METRIC_HEADLINES","panelFilterTree","mergeFilters","dateTimeFieldKind","momentMetrics","FIELD_TONES","MAX_MOVING_WINDOW","isBlankFilterValue","emptyFilter","enumFieldKind","compileAnalysis","BUILTIN_FIELD_KIND_IDS","familyOf","filterTypeOf","admitFilters","clearFilter","stringFieldKind","chartUnfit","isSystemScope","withStageOrder","MAX_HEADING_LENGTH","validateBoardClick","conditionOf","searchFieldKind","fitCharts","titleProblem","withStagesFrom","MAX_MARKDOWN_LENGTH","validatePanelClick","isViewWriteError","recordProjection","metricReferenceText","VIEW_AUDIENCES","withPercentStack","DASHBOARD_PRESENTATION_MEMBERS","pressableGroups","conditions","referenceFieldKind","shapeChart","toSummary","CHART_FAMILIES","MAX_PANEL_LINKS","sameFilterTree","resolveDateTimeBound","qualify","SUMMARY_FUNCTIONS","ANALYSIS_DATE_PARTS","filterFields","elementFields","compileAnalysisTotals","CURRENCY_CODE_PATTERN","peaksOnlyLabels","compilePresence","pagedPaging","derivedText","DEFAULT_RUNTIME_LIMITS","offersPercentStack","RECORD_PRESENTATION_MEMBERS","mapGlobalFilter","ViewCommandError","isPresenceOperator","FIRST_PAGE","formulaMetric","CODE_REVISION","stacks","DASHBOARD_FILTER_KINDS","boardValueChoices","isFilterNode","impliedDeletion","metricFunctionOf","EPOCH_TIME_UNITS","CHART_TYPES","filterStoredValue","isFilterGroup","DELETION_STATES","metricFieldOf","DEFAULT_STRING_COMPARISON","isAdditiveMetric","CHART_COLOR_SLOTS","filterEditor","isNegation","isDeletionState","metricMeasure","FIELDLESS_FIELD_KIND_IDS","DERIVED_KINDS","filterValueIssues","removeConditionAt","isValidTimeZone","innermostElement","SEARCH_MODES","ANALYSIS_AUTO_RUN_MEMBERS","clickOf","removeAt","elementFilterFields","NUMERIC_TYPES","wallClockAt","REFERENCE_STATISTICS","bindingsOf","sameFilterNode","periodOf","outOfScopeNames","STRING_COMPARISONS","ANALYSIS_DATE_DIFF_UNITS","clicksFilter","isReferenceFilterValue","clampPage","withText","isApproximate","renameTab","validateDataConfigBase","dateDiffUnitsOf","compileKanbanCounts","panelsOf","createFieldKindRegistry","fieldAliasSegment","narrowDefinition","validateFilter","pageAfterShrink","OPERATOR_SIGN","isSmooth","systemInstanceId","validateTimeGrouping","DURATION_COMPARISONS","groupFieldsOf","laneConfig","tabsOf","issue","comboAxis","isFieldlessKind","describedField","isDateTimeFilterValue","cardField","isChartColor","withFieldKinds","summaryFunctionsOf","coversScope","booleanFieldKind","ANALYSIS_PRESENTATION_MEMBERS","groupKeyText","isOwnedPanel","walkFilter","relativeName","TEMPORAL_TYPES","isDurationFilterValue","pageSummaries","validateChart","writeValue","temporalOf","validateDashboard","rowCurrency","approximateMetrics","removeTab","isOrderedRange","recordValue","projectAnalysis","textKeyOf","SYSTEM_INSTANCE_ID_SEPARATOR","moveTab","isGroupItem","MAX_DERIVED_DECIMALS","appendLane","panelTab","EDITOR_INPUTS","withOutOfScope","epochUnitOf","builtinFieldKinds","chartPickerGroups","configBytes","withStacked","MAX_DASHBOARD_TABS","urlPlaceholders","summaryAlias","wordReferences","VIEW_SCOPES","withSlot","DASHBOARD_WIDTHS","setPanelClick","MAX_RELATIVE_DATE_AMOUNT","isValueMetric","laneFields","validateAnalysis","operatorsOf","comboMark","isSingleStringField","isNumberRange","projectSummaries","momentColumns","text","SYSTEM_INSTANCE_ID_PREFIX","addTab","describeFilter","DERIVED_FORMAT_STYLES","validateRecord","isSafeContentUrl","filterIndexes","scopePrefix","aggregationFunctionsOf","validateViewConfigBase","datePartsOf","defaultKanbanSpec","presentationMembersOf","isBlankLeafValue","periodRollover","isDateCell","describedAnalysis","projectRecord","measureColumns","say","limitBounds","DEFAULT_APPROXIMATE_METRICS","validateLayout","negateAt","readInstant","readsAsItsField","MAX_NUMERIC_SCALE","METRIC_AGAINST","isOneDayValue","groupJoinWord","FIELD_METRIC_TYPES","OTHER_LANE_ID","isViewPanel","isRootFilterIssue","unknownOrOutside","currencyPathOf","actions","DATE_TIME_PRESETS","expressionFieldsOf","kanbanLanes","referencedInstance","isKnownEditorInput","isFieldName","constructible","arrayFieldKind","DATE_PART_DOMAINS","maxSortFields","isPresentationMember","walkFilterShape","relativeTree","TIME_PRECISIONS","RELATIVE_DATE_UNITS","projectKanban","readValue","numberFormatOf","isBlankFilter","cursorPaging","metricCondition","VIEW_STORE_ERROR_CODES","isSystemInstanceId","validateTabs","describePresenceParts","expressionText","nearestPageSize","optionTabs","columnPinned","boardFilterChoices","pageWindow","derivedMetric","isViewStoreError","isStacked","MAX_KANBAN_LANES","boardCondition","isExecutableFilter","lastPageInWindow","EXPRESSION_OPERATORS","ViewStoreError","isPercentStacked","parseSystemInstanceId","validateFilterFields","insertAt","elementMatchFieldKind","DATE_SUMMARY_FUNCTIONS","seriesMark","sameFilterType","filterCondition","setBoardWidth","summaryChoices","setFilterDefault","unbindPanels","splitBy","defaultRuntimeEnvironment","resultSpan","removeFixedScope","withElements","removeFilter","nextLevel","setTimeGrouping","defaultPanelSize","aliasOf","wiredOptions","narrowsTo","autoBindings","movePanelToTab","groupFacts","duplicatePanel","defaultAnalysisConfig","bindPanel","setFilterOneDay","drillConditions","setFilterOptions","renameFilter","withLevel","setFilterRequired","drillGroups","replacePanelView","metricWithCondition","filterReach","focusOn","ALWAYS_VISIBLE","recommendDateUnit","moveFilter","nextExpansion","addPanel","DEFAULT_MISSING_KEY","wireableFields","drillFilter","compactTab","DEFAULT_PERCENTILE","removePanel","groupableFields","referToSaved","groupOfType","renamePanel","metricOfSummary","withRootSearch","emptyDashboardConfig","isRecordRuntime","narrowValueCandidates","fitsGrid","autoRunMembers","withHavingRows","isExportCancelledError","valueCandidateLimit","inRows","fitChartSlots","placePanelIn","summaryOf","setPresentation","detailSections","readingOrder","searchFieldOf","withLayouts","rootSearch","stackedLayout","VALUE_CANDIDATE_OPERATORS","compactLayout","setFilterMultiple","retypeFilter","withoutLevelsFrom","valueCandidateNarrowing","overlaps","recordCapabilityOf","reorderPanelIn","hasResult","switchChartType","arrangePanel","ExportCancelledError","readValueCandidates","freeSpot","defaultRecordConfig","reorderPanel","editContent","firstMetric","ViewEngine","VALUE_CANDIDATE_LIMIT","bottomOf","valueCandidateField","grownLayout","hasAsked","leadMetric","STACKED_COLUMNS","valueCandidatesConfig","placePanel","unmarkedErrors","HAVING_OPERATORS","addFilter","levelLabel","presentationMembers","rangeSpan","VIEW_KINDS","havingRows","filtersOnTab","groupFor","draftedClick","valueSourceKey","CSV_BOM","serializeCsv","clickDraftOf","withBoard","fieldGroups","boardValueSources","mappedValues","clickDraftGaps","urlFillable","CLICK_GO_KINDS","bucketChange","analysisPlan","spec","narrowed","entry","plan","fields","own","entries","child","one","buildAnalysis","descriptor","findings","field","found","code","params","severity","buildFields","listed","key","given","built","buildField","scope","build","path","searchField","described","raw","fieldDescriptor","kind","kindOf","labelOf","comparable","sorts","sortsByDefault","offered","operatorsOffered","operator","functions","fn","options","optionsOf","temporal","temporalOf$1","children","element","search","name","relative","variants","variant","semantic","TimeUnit","types","listedOptions","values","value","option","known","said","defineView","record","recordOf","definition","analysis","sort","operators","openComparisons","withSnapshotComparisons","cut","index","next","open","PAGING","mode","paging","defineDataset","derived","override","label","DatasetResources","engine","onError","onWordingError","catalogs","lists","catalog","list","servable","duplicates","unread","id","kept","held","duplicate","order","a","b","read","store","error","words","wording","source","current","title","derivedTitle","revision","context","stored","localStorageSnapshot","storage","ambientStorage","events","ambientEvents","parseState","state","onStorage","event","readable","listener","target","saved","isHeld","instance","emptyPreferences","MemoryViewStore","restored","summaries","definitionId","AUDIENCE_RANK","limit","seen","count","summary","copy","replayed","refused","titleRefusal","input","configRefusal","config","audience","boards","readOnlySystem","conflict","preferences","nextRevision","changed","change","panels","shows","panel","undo","reasonOf","owned","instanceId","opens","click","bytes","message","PRESENCE_OPERATORS","defaultFilters"],"sources":["../src/runtime/define/analysis.ts","../src/runtime/define/fields.ts","../src/runtime/define/defineView.ts","../src/runtime/define/defineDataset.ts","../src/runtime/datasetResources.ts","../src/store/localStorageSnapshot.ts","../src/store/ViewStore.ts","../src/store/MemoryViewStore.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\n/**\n * The analyses of a `defineView` definition: which fields analyse and how\n * the host narrows each is the host's (the plan, `OpenCapabilities`); what\n * each path offers is its source's. Built here over the snapshot — what a\n * source with no descriptor runs on — and read again over a source's own\n * descriptor when it narrows (`reopened`). A narrowing beyond what the\n * snapshot grants is a warning, not an error: another store may grant it.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client/dsl';\nimport type {\n AnalysisCapability,\n AnalysisSpec,\n FieldAnalysisSpec,\n Issue,\n OpenCapabilities,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { describedAnalysis } from '../../capabilities/open.js';\nimport type { BuiltField } from './fields.js';\n\n/** Which fields analyse, and the host's narrowing of each; `undefined` for none. */\nexport function analysisPlan(\n spec: AnalysisSpec | false | undefined,\n fields: readonly BuiltField[],\n): OpenCapabilities['analysis'] {\n if (spec === false) return undefined;\n const narrowed = (entry: BuiltField): FieldAnalysisSpec | null =>\n entry.spec.analysis === false ? null : (entry.spec.analysis ?? {});\n const plan: NonNullable<OpenCapabilities['analysis']> = {\n spec: spec ?? {},\n fields: {},\n elements: {},\n };\n for (const entry of fields) {\n const own = entry.described ? narrowed(entry) : null;\n if (!own) continue;\n if (entry.children) {\n const entries: Record<string, FieldAnalysisSpec> = {};\n for (const child of entry.children) {\n const one = narrowed(child);\n if (one) entries[child.field.name] = one;\n }\n (plan.elements as Record<string, typeof entries>)[entry.field.name] =\n entries;\n } else\n (plan.fields as Record<string, FieldAnalysisSpec>)[entry.field.name] =\n own;\n }\n return plan;\n}\n\n/** The plan's analyses over the snapshot, what it asks beyond said as warnings. */\nexport function buildAnalysis(\n plan: OpenCapabilities['analysis'],\n fields: readonly BuiltField[],\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): AnalysisCapability | undefined {\n if (!plan) return undefined;\n return describedAnalysis(\n plan,\n fields.map(entry => entry.field),\n descriptor,\n (field, what) =>\n findings.push(\n field === null\n ? issue(\n 'definition.analysis.wider',\n ['analysis'],\n { what },\n 'warning',\n )\n : issue(\n 'definition.field.analysis-wider',\n ['analysis'],\n { field, what },\n 'warning',\n ),\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 * A field as `defineView` builds it (host-integration.md 3): its kind, its\n * values and whether it sorts are the descriptor's; its label, its order,\n * its cell and what it narrows are the host's. The operators are left to\n * the kind unless the host narrows them — the engine cuts them to the\n * descriptor in force whenever a view runs (N5), so a list copied here\n * would only go stale.\n */\n\nimport {\n TimeUnit,\n type FieldDescriptor,\n type QueryModelDescriptor,\n} from '@ahoo-wang/wow-client/dsl';\nimport {\n TEMPORAL_FIELD_KIND_IDS,\n type FieldDefinition,\n type FieldKindId,\n type FieldOption,\n type FieldTemporal,\n type Issue,\n type PagingMode,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport {\n describedField,\n type DescribedField,\n} from '../../capabilities/match.js';\nimport type { FieldSpec, OptionSpec } from './spec.js';\n\n/** What building the fields reads, and where it says what it found. */\ninterface FieldBuild {\n descriptor: QueryModelDescriptor;\n paging: PagingMode;\n findings: Issue[];\n}\n\n/** One built field and what it is over, for the analyses to read. */\nexport interface BuiltField {\n field: FieldDefinition;\n described: DescribedField | null;\n spec: FieldSpec;\n /** Whether the value is sensitive: masked, so never grouped or measured. */\n sensitive: boolean;\n /** An array's entries, built as its fields are. */\n children?: BuiltField[];\n}\n\nconst found = (\n code: string,\n params: Record<string, string>,\n severity: Issue['severity'] = 'error',\n): Issue => issue(code, ['fields'], params, severity);\n\n/** The fields listed, built in the order listed; one the descriptor lacks is left out. */\nexport function buildFields(\n listed: Readonly<Record<string, FieldSpec | string>>,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField[] {\n return Object.entries(listed).flatMap(([key, given]) => {\n const spec: FieldSpec =\n typeof given === 'string' ? { label: given } : given;\n const built = buildField(key, spec, scope, build);\n return built ? [built] : [];\n });\n}\n\nfunction buildField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField | null {\n const { descriptor, findings } = build;\n const path = scope === undefined ? key : `${scope}.${key}`;\n if (spec.search) return searchField(key, spec, scope, build);\n\n const described = describedField(descriptor, path, scope);\n if (!described) {\n findings.push(found('definition.field.undescribed', { field: path }));\n return null;\n }\n const raw = fieldDescriptor(descriptor, described.canonical ?? path, scope);\n const kind = spec.kind ?? kindOf(raw, described, spec);\n if (kind === null) {\n findings.push(found('definition.field.kind-unknown', { field: path }));\n return null;\n }\n const field: FieldDefinition = {\n name: key,\n label: labelOf(spec, raw, path, findings),\n kind,\n };\n const comparable = described.comparable !== false;\n\n // An entry's field is read inside its record, not what records are\n // ordered by: offered as a sort only where the host asks.\n const sorts =\n comparable &&\n (build.paging === 'cursor' ? described.sort.cursor : described.sort.paged);\n const sortsByDefault = sorts && scope === undefined;\n if (spec.sortable === true && !sorts)\n findings.push(\n found('definition.field.sort-wider', { field: path }, 'warning'),\n );\n if (sorts && (spec.sortable ?? sortsByDefault)) field.sortable = true;\n\n if (spec.operators) {\n const offered = operatorsOffered(descriptor, described, path);\n for (const operator of spec.operators)\n if (!offered.has(operator))\n findings.push(\n found(\n 'definition.field.operator-wider',\n { field: path, operator },\n 'warning',\n ),\n );\n field.operators = spec.operators;\n } else if (!comparable) field.operators = [];\n\n if (spec.summary) {\n const functions: readonly string[] = described.aggregate?.functions ?? [];\n for (const fn of spec.summary)\n if (fn !== 'COUNT' && !functions.includes(fn))\n findings.push(\n found(\n 'definition.field.summary-wider',\n { field: path, fn },\n 'warning',\n ),\n );\n field.summary = spec.summary;\n }\n\n const options = optionsOf(spec, described, path, findings);\n if (options) field.options = options;\n\n // A time is written in conditions the way the model keeps it, so the field\n // keeps the descriptor's way: a date string, or an epoch in its unit.\n // Without it a dataset's date column read as epoch milliseconds, and the\n // capability check refused the whole dataset (found by analytics/demo).\n const temporal = temporalOf(described);\n if (temporal && TEMPORAL_FIELD_KIND_IDS.includes(kind))\n field.temporal = temporal;\n\n if (described.deprecated) {\n if (!spec.deprecated)\n findings.push(\n found(\n 'definition.field.deprecated',\n { field: path, message: described.deprecated.message ?? '' },\n 'warning',\n ),\n );\n field.deprecated = spec.deprecated ?? described.deprecated;\n }\n\n let children: BuiltField[] | undefined;\n if (spec.elements) {\n if (!descriptor.elements.some(element => element.path === path))\n findings.push(found('definition.field.not-elements', { field: path }));\n children = buildFields(spec.elements, path, build);\n field.elements = children.map(entry => entry.field);\n }\n if (spec.elementTitle !== undefined) field.elementTitle = spec.elementTitle;\n if (spec.cell !== undefined) field.cell = spec.cell;\n if (spec.timePrecision !== undefined)\n field.timePrecision = spec.timePrecision;\n Object.assign(field, spec.more);\n return {\n field,\n described,\n spec,\n sensitive: described.sensitive === true,\n ...(children ? { children } : {}),\n };\n}\n\n/** A search box: its fields must be paths the descriptor has. */\nfunction searchField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField {\n const search = spec.search ?? { fields: [] };\n // An entry's search names its fields within the entry (N4).\n for (const name of search.fields) {\n const path = scope === undefined ? name : `${scope}.${name}`;\n if (!describedField(build.descriptor, path, scope))\n build.findings.push(\n found('definition.field.undescribed', { field: path }),\n );\n }\n const field: FieldDefinition = {\n name: key,\n label: spec.label ?? key,\n kind: 'search',\n searchFields: search.fields,\n };\n if (search.mode) field.searchMode = search.mode;\n return { field, described: null, spec, sensitive: false };\n}\n\n/** The descriptor's own entry for a path, for what `describedField` leaves out. */\nfunction fieldDescriptor(\n descriptor: QueryModelDescriptor,\n path: string,\n scope: string | undefined,\n): FieldDescriptor | undefined {\n const own = descriptor.fields.find(\n entry => entry.path === path && entry.scope === scope,\n );\n if (own || scope === undefined) return own;\n // A variant's fields are listed relative to the element, by path or alias,\n // as `describedField` reads them.\n const relative = path.slice(scope.length + 1);\n const variants = descriptor.variants;\n if (variants?.element !== scope) return undefined;\n return variants.values\n .flatMap(variant => variant.fields)\n .find(\n entry =>\n entry.path === relative || (entry.aliases ?? []).includes(relative),\n );\n}\n\n/**\n * How the descriptor says a time is kept, where it says anything a field\n * must be told: a date string, or an epoch in seconds. Epoch milliseconds\n * is the field's own default (`DEFAULT_TEMPORAL`), so it is left unsaid.\n */\nfunction temporalOf(described: DescribedField): FieldTemporal | undefined {\n const semantic = described.semantic;\n if (semantic?.type === 'TEMPORAL_DATE') return { type: 'date' };\n if (\n semantic?.type === 'TEMPORAL_EPOCH' &&\n semantic.timeUnit === TimeUnit.SECONDS\n )\n return { type: 'epoch', timeUnit: 'SECONDS' };\n return undefined;\n}\n\n/** The kind the descriptor says a path is; `null` where it says none. */\nfunction kindOf(\n raw: FieldDescriptor | undefined,\n described: DescribedField,\n spec: FieldSpec,\n): FieldKindId | null {\n if (spec.elements) return 'elementMatch';\n // A yes-or-no keeps its kind under `options`: there they name its two\n // answers (「新客」「老客」), they do not make it a category.\n if (!described.enum && raw?.types?.length === 1 && raw.types[0] === 'BOOLEAN')\n return 'boolean';\n if (described.enum || spec.options) return 'enum';\n const temporal = described.semantic?.type;\n if (temporal === 'TEMPORAL_DATE') return 'date';\n if (temporal === 'TEMPORAL_EPOCH' || temporal === 'TEMPORAL_FORMATTED')\n return 'datetime';\n const types: readonly string[] = raw?.types ?? [];\n if (types.length !== 1) return null;\n switch (types[0]) {\n case 'BOOLEAN':\n return 'boolean';\n case 'INTEGER':\n case 'DECIMAL':\n return 'number';\n case 'STRING':\n return 'string';\n default:\n return null;\n }\n}\n\n/**\n * The host's word, else the domain's description, else the path — the two\n * fallbacks said, since a reader would see a program's word.\n */\nfunction labelOf(\n spec: FieldSpec,\n raw: FieldDescriptor | undefined,\n path: string,\n findings: Issue[],\n): string {\n if (spec.label !== undefined) return spec.label;\n findings.push(found('definition.field.unlabelled', { field: path }, 'note'));\n return raw?.description ?? path;\n}\n\n/**\n * The comparisons a path admits: its own operators, and a match over its\n * entries where it is an element the model filters by (capabilities.md,\n * `ELEMENT_MATCH` comes from `elements[]`).\n */\nfunction operatorsOffered(\n descriptor: QueryModelDescriptor,\n described: DescribedField,\n path: string,\n): ReadonlySet<string> {\n const offered = new Set(described.operators);\n if (descriptor.elements.some(entry => entry.path === path && entry.filter))\n offered.add('ELEMENT_MATCH');\n return offered;\n}\n\n/**\n * A category's values: the host's listed first, in its order and words,\n * then the rest of the descriptor's under their descriptions; one the host\n * hides left out. Where the descriptor lists none the host's list is the\n * whole of it.\n */\nfunction optionsOf(\n spec: FieldSpec,\n described: DescribedField,\n path: string,\n findings: Issue[],\n): FieldOption[] | undefined {\n const listed = listedOptions(spec.options);\n const values = described.enum;\n if (!values)\n return spec.options\n ? listed.flatMap(([value, given]) =>\n given === false ? [] : [option(value, given)],\n )\n : undefined;\n const known = new Map(values.map(entry => [String(entry.value), entry]));\n const said = new Set<string>();\n const options: FieldOption[] = [];\n for (const [value, given] of listed) {\n const key = String(value);\n const entry = known.get(key);\n if (!entry) {\n findings.push(\n found('definition.option.undescribed', { field: path, value: key }),\n );\n continue;\n }\n said.add(key);\n if (given !== false) options.push(option(entry.value, given));\n }\n for (const entry of values)\n if (!said.has(String(entry.value)))\n options.push({\n value: entry.value as FieldOption['value'],\n label: entry.description ?? String(entry.value),\n });\n return options;\n}\n\n/**\n * The host's values in the order written: a list as it is, a record in its\n * own order — which JavaScript puts integer-like keys first in, so a\n * category of numbers is written as a list.\n */\nfunction listedOptions(\n given: FieldSpec['options'],\n): (readonly [unknown, OptionSpec])[] {\n if (!given) return [];\n if (Array.isArray(given)) return given as (readonly [unknown, OptionSpec])[];\n // Own keys only: a value named like a prototype member is a value.\n return Object.keys(given).map(key => [\n key,\n (given as Readonly<Record<string, OptionSpec>>)[key],\n ]);\n}\n\nfunction option(\n value: unknown,\n given: Exclude<OptionSpec, false>,\n): FieldOption {\n return typeof given === 'string'\n ? { value: value as FieldOption['value'], label: given }\n : { value: value as FieldOption['value'], ...given };\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/dsl';\nimport type {\n DataViewDefinition,\n FieldDefinition,\n Issue,\n PagingMode,\n RecordCapability,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { analysisPlan, buildAnalysis } from './analysis.js';\nimport { buildFields, type BuiltField } from './fields.js';\nimport { narrowDefinition } from '../../capabilities/index.js';\nimport { constructible } from '../../capabilities/analysis.js';\nimport {\n builtinFieldKinds,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport type { DefineViewSpec } from './spec.js';\n\n/**\n * A data definition built from its source's descriptor (host-integration.md\n * 3, D67): the descriptor gives the facts — which paths there are, what\n * each is, what it sorts and feeds — as an upper bound, and `spec` picks,\n * names and narrows within it. A field not listed does not appear. A path\n * or a value the descriptor lacks is an error admission reports\n * (`DataViewDefinition.described`), never a throw: a definition wrong in\n * one place still loads, and says where. A capability asked beyond the\n * snapshot is a warning: what a path sorts and aggregates by is the\n * store's, and another store may grant it.\n *\n * Facts — paths, kinds, values, sensitivity, the entries of an array —\n * are the snapshot's. Capabilities are not baked in: where the host\n * narrows nothing the definition takes whatever its source grants, and\n * where it narrows, its subset of that (`DefinitionDescribed.open`,\n * filled by the narrowing from the source's descriptor). A source with\n * no descriptor runs on the snapshot's.\n *\n * `descriptor` is the snapshot committed beside the definition (Q2): the\n * definition is built at once, when the module loads, and a test builds\n * the same one. The descriptor the source answers at run time narrows it\n * again, as any definition is (N5).\n *\n * The result is an ordinary definition: nothing past this function knows\n * how it was written, and one written in full by hand is still one.\n */\nexport function defineView(\n descriptor: QueryModelDescriptor,\n spec: DefineViewSpec,\n options: DefineViewOptions = {},\n): DataViewDefinition {\n const findings: Issue[] = [];\n const record = recordOf(spec, descriptor, findings);\n const fields = buildFields(spec.fields, undefined, {\n descriptor,\n paging: record?.paging ?? 'paged',\n findings,\n });\n const definition: DataViewDefinition = {\n id: spec.id,\n title: spec.title,\n kind: 'data',\n source: spec.source,\n fields: fields.map(entry => entry.field),\n };\n if (spec.recordNoun !== undefined) definition.recordNoun = spec.recordNoun;\n if (spec.fieldGroups) definition.fieldGroups = spec.fieldGroups;\n if (record) definition.record = record;\n const plan = analysisPlan(spec.analysis, fields);\n const analysis = buildAnalysis(plan, fields, descriptor, findings);\n // A snapshot with no metric at all offers no analyses; a source that\n // grants some fills them in (`reopened`) rather than the definition\n // being refused for one store's word.\n if (analysis && constructible(analysis)) definition.analysis = analysis;\n if (spec.timeField !== undefined) definition.timeField = spec.timeField;\n if (spec.views) definition.views = spec.views;\n // What compares, sorts and aggregates is the store's: left to the source\n // where the host did not narrow it, filled from its descriptor when it\n // narrows (`reopened`), the snapshot's written here for a source that\n // has none.\n const sort = fields.flatMap(({ field, spec: given, described }) =>\n described && given.sortable !== false ? [field.name] : [],\n );\n const operators = openComparisons(fields);\n definition.fields = withSnapshotComparisons(\n definition.fields,\n narrowDefinition(definition, descriptor, options.kinds ?? builtinFieldKinds)\n .definition.fields,\n new Set(operators),\n );\n definition.described = {\n version: descriptor.version,\n findings,\n open: { sort, operators, ...(plan ? { analysis: plan } : {}) },\n };\n return definition;\n}\n\n/**\n * The fields whose comparisons the host left open, by path: every field\n * but one whose operators the host wrote, one that compares nothing (a\n * confidential value), and a search box.\n */\nfunction openComparisons(\n fields: readonly BuiltField[],\n scope?: string,\n): string[] {\n return fields.flatMap(({ field, spec, children }) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n // A search box is the host's to ask for, as written operators are: on\n // a source with no descriptor it is offered as declared, and a source\n // that says whether it searches narrows it.\n const own =\n spec.operators === undefined &&\n field.operators === undefined &&\n field.kind !== 'search'\n ? [path]\n : [];\n return [...own, ...openComparisons(children ?? [], path)];\n });\n}\n\n/**\n * The fields with the snapshot's comparisons written on each one left\n * open: the operators the narrowing against it keeps on each path, so a\n * source with no descriptor offers what the snapshot's store does, and no\n * more.\n */\nfunction withSnapshotComparisons(\n fields: readonly FieldDefinition[],\n narrowed: readonly FieldDefinition[],\n open: ReadonlySet<string>,\n scope?: string,\n): FieldDefinition[] {\n return fields.map((field, index) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n const cut = narrowed[index];\n let next = field;\n if (open.has(path) && cut?.operators !== undefined)\n next = { ...next, operators: cut.operators };\n if (field.elements)\n next = {\n ...next,\n elements: withSnapshotComparisons(\n field.elements,\n cut?.elements ?? [],\n open,\n path,\n ),\n };\n return next;\n });\n}\n\n/**\n * What `defineView` needs beyond the snapshot and the host's choices: the\n * field kinds the host registers (`ViewEngineOptions.kinds`) — the snapshot's\n * comparisons are written on a field of a host's own kind only when its\n * kind is known here, since it is built before any engine is. Left out,\n * the built-in kinds.\n */\nexport interface DefineViewOptions {\n kinds?: FieldKindRegistry;\n}\n\n/** The descriptor's paging modes, as a definition names them. */\nconst PAGING: Readonly<Record<string, PagingMode>> = {\n PAGED: 'paged',\n CURSOR: 'cursor',\n};\n\n/**\n * Records: the host's choices over the descriptor's identity and paging —\n * paged where the model pages, else by cursor — shown as a table unless the\n * host says otherwise. A paging the model does not offer is asked beyond it.\n */\nfunction recordOf(\n spec: DefineViewSpec,\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): RecordCapability | undefined {\n if (spec.record === false) return undefined;\n const given = spec.record ?? {};\n const offered = descriptor.record.paging.flatMap(mode =>\n PAGING[mode] ? [PAGING[mode]] : [],\n );\n const paging =\n given.paging ?? (offered.includes('paged') ? 'paged' : 'cursor');\n if (!offered.includes(paging))\n findings.push(\n issue(\n 'definition.record.paging-wider',\n ['record', 'paging'],\n { paging },\n 'warning',\n ),\n );\n return {\n ...given,\n rowKey: given.rowKey ?? descriptor.record.identity,\n paging,\n layouts: given.layouts ?? ['table'],\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/dsl';\nimport type { DataViewDefinition } from '../../model/index.js';\nimport { defineView, type DefineViewOptions } from './defineView.js';\nimport type { FieldSpec } from './spec.js';\n\n/** What a host says of a dataset beyond its descriptor. */\nexport interface DefineDatasetSpec {\n id: string;\n /** The key a host resolves the definition's source by. */\n source: string;\n /** The dataset's title, such as the dataset directory's. */\n title: string;\n recordNoun?: string;\n /**\n * The host's words over the derived fields, which only narrow and name\n * (D86): a string is a field's label, a `FieldSpec` narrows it as in\n * **defineView**, `false` hides it. The fields named come first, in the\n * order named; the rest follow in the descriptor's order. A path the\n * descriptor no longer lists is ignored, so an override outlives a\n * column the dataset dropped.\n */\n fields?: Readonly<Record<string, FieldSpec | string | false>>;\n}\n\n/**\n * A dataset's definition, derived from its descriptor (host-integration.md\n * 3.2, D84): a dataset is published at run time, so its definition is not\n * code. Every field of the record the descriptor lists appears, in the\n * descriptor's order — a dataset's declaration already chose them, as a\n * column it does not declare is never exposed — labelled by its\n * description, else its path. The rest is **defineView**'s: sensitive\n * fields stay out of analyses, capabilities follow the descriptor in force,\n * and the row key is the descriptor's identity.\n *\n * The result is an ordinary definition, judged as any other when an engine\n * registers it (`ViewEngine.register`).\n */\nexport function defineDataset(\n descriptor: QueryModelDescriptor,\n spec: DefineDatasetSpec,\n options: DefineViewOptions = {},\n): DataViewDefinition {\n const derived = new Map<string, string>();\n for (const field of descriptor.fields)\n if (field.scope === undefined)\n derived.set(field.path, field.description ?? field.path);\n const fields: Record<string, FieldSpec | string> = {};\n for (const [path, override] of Object.entries(spec.fields ?? {})) {\n const label = derived.get(path);\n if (label === undefined) continue;\n derived.delete(path);\n if (override === false) continue;\n fields[path] =\n typeof override === 'string'\n ? override\n : { ...override, label: override.label ?? label };\n }\n for (const [path, label] of derived) fields[path] = label;\n return defineView(\n descriptor,\n {\n id: spec.id,\n source: spec.source,\n title: spec.title,\n ...(spec.recordNoun === undefined ? {} : { recordNoun: spec.recordNoun }),\n fields,\n },\n options,\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 defineDataset,\n type DefineDatasetSpec,\n} from './define/defineDataset.js';\nimport type { WriteContext } from '../store/ViewStore.js';\nimport type { ViewSource } from './source.js';\n\n/**\n * One dataset of a service's directory: where it lives, how it is titled,\n * and the version it was published at (`null` while it is not servable).\n */\nexport interface DatasetDirectoryEntry {\n contextName: string;\n name: string;\n title: string | null;\n version: string | null;\n}\n\n/** What `DatasetResources` reads: the dataset directory, and each dataset's source. */\nexport interface DatasetCatalog {\n /** The datasets the service serves (`GET /dataset`). */\n list(): Promise<readonly DatasetDirectoryEntry[]>;\n /** The source of one, such as wow-client's `DatasetQueryClient`; it must describe itself. */\n source(entry: DatasetDirectoryEntry): ViewSource;\n /**\n * The host's words over one dataset (D86): its title, its noun, and its\n * fields' labels, order and narrowing (`DefineDatasetSpec.fields`).\n */\n overrides?(entry: DatasetDirectoryEntry): DatasetOverrides | undefined;\n /**\n * Where a tenant's administrators keep their wording over the datasets\n * (D91), such as wow-view-store's `WowDatasetWordings`: read whole before\n * each `refresh` registers, by definition id. A dataset's stored wording\n * stands in place of `overrides`. Given, each dataset registers with an\n * editor of its wording (`DatasetWordingEditor`).\n */\n wordings?: DatasetWordingStore;\n}\n\n/** A dataset's wording as stored, and the revision a write expects. */\nexport interface StoredDatasetWording {\n wording: DatasetOverrides;\n /** `'0'` for wording never written. */\n revision: string;\n}\n\n/** Where a dataset's wording is kept (D91); see `DatasetCatalog.wordings`. */\nexport interface DatasetWordingStore {\n /** Every dataset's stored wording, by definition id (`{context}.{dataset}`). */\n list(\n signal?: AbortSignal,\n ): Promise<ReadonlyMap<string, StoredDatasetWording>>;\n /** Writes one whole at the expected revision; answers the new revision. */\n set(\n dataset: string,\n wording: DatasetOverrides,\n revision: string,\n context: WriteContext,\n ): Promise<string>;\n}\n\n/**\n * What a dataset's wording editor reads and writes (D91): the fields the\n * descriptor derives, the wording in force, and a save that stores it and\n * registers the dataset again in the new words.\n */\nexport interface DatasetWordingEditor {\n /** The definition id, and the dataset's key in the store. */\n readonly dataset: string;\n /** The title the directory gives, before any wording. */\n readonly derivedTitle: string;\n /** The descriptor's fields in its order, labelled as derived before any wording. */\n readonly fields: readonly { name: string; label: string }[];\n /** The wording in force: the stored one, else the host's `overrides`. */\n readonly wording: DatasetOverrides;\n /** The revision a save expects. */\n readonly revision: string;\n /** Stores `wording` whole and registers the dataset again in it. */\n save(wording: DatasetOverrides, context: WriteContext): Promise<void>;\n}\n\n/** What a host may say over a dataset's derived definition; see `DatasetCatalog.overrides`. */\nexport type DatasetOverrides = Partial<\n Pick<DefineDatasetSpec, 'title' | 'recordNoun' | 'fields'>\n>;\n\n/** The part of an engine `DatasetResources` drives (`ViewEngine` is one). */\nexport interface DatasetRegistrar {\n readonly definitions: ReadonlyMap<string, unknown>;\n register(resource: {\n definition: ReturnType<typeof defineDataset>;\n source: ViewSource;\n wording?: DatasetWordingEditor;\n }): void;\n unregister(definitionId: string): boolean;\n}\n\n/** A dataset served, as registered: its directory entry and its definition id. */\nexport interface DatasetResource {\n id: string;\n entry: DatasetDirectoryEntry;\n /**\n * Which of the catalogs serves it, by its place in the list\n * `DatasetResources` was given (0 for one catalog).\n *\n * @beta\n */\n catalog: number;\n}\n\n/**\n * A dataset a catalog listed under an id an earlier catalog serves (D238 ⑨):\n * left out, the earlier one's kept.\n *\n * Experimental (D93): it may change before 10.0 GA.\n *\n * @beta\n */\nexport interface DatasetDuplicate {\n /** The definition id both name, `{context}.{dataset}`. */\n id: string;\n /** The entry left out, of the catalog at `dropped`. */\n entry: DatasetDirectoryEntry;\n dropped: number;\n /** The catalog whose dataset of that id is served. */\n kept: number;\n}\n\n/**\n * What `DatasetResources` tells besides a dataset it cannot serve: each\n * duplicate it leaves out, and a catalog whose directory cannot be read.\n *\n * Experimental (D93): it may change before 10.0 GA. Its members are tagged\n * rather than the interface, as the constructor of the public\n * `DatasetResources` names it.\n */\nexport interface DatasetResourcesOptions {\n /**\n * Told of each duplicate a refresh leaves out (`DatasetResources.duplicates`).\n *\n * @beta\n */\n onDuplicate?(duplicate: DatasetDuplicate): void;\n /**\n * Told when the catalog at `catalog` cannot list its datasets: the ones it\n * served stay as they were, and the refresh goes on with the others. Only\n * when no catalog can list does the refresh fail.\n *\n * @beta\n */\n onCatalogError?(catalog: number, error: unknown): void;\n}\n\n/** One catalog's dataset as a refresh finds it. */\ninterface Listed {\n entry: DatasetDirectoryEntry;\n catalog: number;\n}\n\n/**\n * Keeps an engine's datasets in step with services' directories (D85): each\n * `refresh` registers a dataset a directory newly lists, registers again\n * one whose descriptor version changed, and removes one no directory lists\n * any more or whose schema does not compile (`version` `null`). A dataset's\n * definition id is its name, `{context}.{dataset}`, and its title the\n * directory's; a definition the host registered in code under that id wins\n * and the dataset is left out.\n *\n * Given several catalogs — several services' directories, such as the\n * analytics catalog's and a service that serves datasets of its own — it\n * serves them in one engine (D238 ⑨): a dataset two catalogs list is the\n * first one's, and the other is reported (`duplicates`, `onDuplicate`),\n * never dropped silently. A catalog that cannot be read keeps what it served\n * and is reported (`onCatalogError`).\n *\n * `refresh` answers the datasets served, which a host binds routes to\n * (`bind`, `datasetBindings`) so they appear in its navigation: opening\n * one is how a reader starts a view of it.\n */\nexport class DatasetResources {\n private readonly catalogs: readonly DatasetCatalog[];\n private readonly held = new Map<string, DatasetResource>();\n /** The overrides each dataset was registered with, as JSON: new words register it again. */\n private readonly worded = new Map<string, string>();\n /** The wording each catalog's store held when it was last read (`DatasetCatalog.wordings`). */\n private stored: ReadonlyMap<\n number,\n ReadonlyMap<string, StoredDatasetWording>\n > = new Map();\n /** What each dataset was registered from, so a new wording needs no describe. */\n private readonly derived = new Map<\n string,\n {\n entry: DatasetDirectoryEntry;\n catalog: number;\n source: ViewSource;\n descriptor: Parameters<typeof defineDataset>[0];\n }\n >();\n private found: readonly DatasetDuplicate[] = [];\n\n constructor(\n private readonly engine: DatasetRegistrar,\n /** One service's directory, or several, the first winning a dataset two list. */\n catalogs: DatasetCatalog | readonly DatasetCatalog[],\n /** Told of a dataset that could not be described or registered; it is left as it was. */\n private readonly onError: (\n entry: DatasetDirectoryEntry,\n error: unknown,\n ) => void = () => undefined,\n /** Told when the stored wording cannot be read; the wording read last stands. */\n private readonly onWordingError: (error: unknown) => void = () => undefined,\n private readonly options: DatasetResourcesOptions = {},\n ) {\n this.catalogs = Array.isArray(catalogs)\n ? (catalogs as readonly DatasetCatalog[])\n : [catalogs as DatasetCatalog];\n if (this.catalogs.length === 0)\n throw new Error('DatasetResources reads at least one catalog.');\n }\n\n /** The datasets served, in the directories' order. */\n get resources(): readonly DatasetResource[] {\n return [...this.held.values()];\n }\n\n /**\n * The datasets the last refresh left out because an earlier catalog serves\n * their id.\n *\n * @beta\n */\n get duplicates(): readonly DatasetDuplicate[] {\n return this.found;\n }\n\n async refresh(): Promise<readonly DatasetResource[]> {\n await this.readWordings();\n const lists = await Promise.allSettled(\n this.catalogs.map(catalog => catalog.list()),\n );\n if (lists.every(list => list.status === 'rejected')) throw lists[0].reason;\n const servable = new Map<string, Listed>();\n const duplicates: DatasetDuplicate[] = [];\n const unread = new Set<number>();\n lists.forEach((list, catalog) => {\n if (list.status === 'rejected') {\n unread.add(catalog);\n this.options.onCatalogError?.(catalog, list.reason);\n return;\n }\n for (const entry of list.value) {\n if (entry.version === null) continue;\n const id = `${entry.contextName}.${entry.name}`;\n const kept = servable.get(id);\n if (kept) {\n duplicates.push({ id, entry, dropped: catalog, kept: kept.catalog });\n continue;\n }\n servable.set(id, { entry, catalog });\n }\n });\n // A catalog that could not be read keeps what it served, unless a catalog\n // read now serves the id.\n for (const [id, held] of this.held)\n if (unread.has(held.catalog) && !servable.has(id))\n servable.set(id, { entry: held.entry, catalog: held.catalog });\n this.found = duplicates;\n for (const duplicate of duplicates) this.options.onDuplicate?.(duplicate);\n for (const id of [...this.held.keys()])\n if (!servable.has(id)) {\n this.engine.unregister(id);\n this.held.delete(id);\n this.worded.delete(id);\n this.derived.delete(id);\n }\n await Promise.all(\n [...servable].map(([id, listed]) => this.serve(id, listed)),\n );\n const order = [...servable.keys()];\n return this.resources\n .slice()\n .sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));\n }\n\n /**\n * Reads the stored wording before a refresh registers; one that cannot be\n * read leaves what was read last, and is told for no dataset in particular.\n */\n private async readWordings(): Promise<void> {\n const read = new Map(this.stored);\n await Promise.all(\n this.catalogs.map(async (catalog, index) => {\n const store = catalog.wordings;\n if (!store) return;\n try {\n read.set(index, await store.list());\n } catch (error) {\n this.onWordingError(error);\n }\n }),\n );\n this.stored = read;\n }\n\n /** The wording a dataset registers in: its catalog's stored one, else the host's. */\n private wordingOf(id: string, listed: Listed): StoredDatasetWording {\n return (\n this.stored.get(listed.catalog)?.get(id) ?? {\n wording: this.catalogs[listed.catalog].overrides?.(listed.entry) ?? {},\n revision: '0',\n }\n );\n }\n\n private async serve(id: string, listed: Listed): Promise<void> {\n const { entry, catalog } = listed;\n const held = this.held.get(id);\n const { wording } = this.wordingOf(id, listed);\n const words = JSON.stringify(wording);\n if (\n held?.catalog === catalog &&\n held.entry.version === entry.version &&\n this.worded.get(id) === words\n )\n return;\n if (!held && this.engine.definitions.has(id)) return;\n try {\n const source = this.catalogs[catalog].source(entry);\n const described = await source.describe?.();\n if (!described || described.notModified)\n throw new Error(`Dataset [${id}] does not describe itself.`);\n this.derived.set(id, {\n entry,\n catalog,\n source,\n descriptor: described.descriptor,\n });\n this.registerWorded(id);\n } catch (error) {\n this.onError(entry, error);\n }\n }\n\n /** Registers dataset `id` from what it was derived from, in the wording in force. */\n private registerWorded(id: string): void {\n const derived = this.derived.get(id);\n if (!derived) return;\n const { entry, catalog, source, descriptor } = derived;\n const current = this.wordingOf(id, { entry, catalog });\n const title = entry.title ?? entry.name;\n const definition = defineDataset(descriptor, {\n id,\n source: id,\n title,\n ...current.wording,\n });\n this.engine.register({\n definition,\n source,\n ...(this.catalogs[catalog].wordings\n ? { wording: this.editorOf(id, catalog, title, descriptor, current) }\n : {}),\n });\n this.held.set(id, { id, entry, catalog });\n this.worded.set(id, JSON.stringify(current.wording));\n }\n\n private editorOf(\n id: string,\n catalog: number,\n derivedTitle: string,\n descriptor: Parameters<typeof defineDataset>[0],\n current: StoredDatasetWording,\n ): DatasetWordingEditor {\n const plain = defineDataset(descriptor, {\n id,\n source: id,\n title: derivedTitle,\n });\n return {\n dataset: id,\n derivedTitle,\n fields: plain.fields.map(({ name, label }) => ({ name, label })),\n wording: current.wording,\n revision: current.revision,\n save: async (wording, context) => {\n const store = this.catalogs[catalog].wordings;\n if (!store) return;\n const revision = await store.set(\n id,\n wording,\n current.revision,\n context,\n );\n const stored = new Map(this.stored);\n stored.set(\n catalog,\n new Map(this.stored.get(catalog)).set(id, { wording, revision }),\n );\n this.stored = stored;\n this.registerWorded(id);\n },\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 { ViewInstance } from '../model/index.js';\nimport type { MemorySnapshot, MemoryState } from './MemoryViewStore.js';\n\n/**\n * Where a `localStorageSnapshot` reads and writes. Both are structural, so\n * this layer names no DOM type, and a test hands in a storage of its own.\n */\nexport interface LocalStorageSnapshotOptions {\n /**\n * The storage, asked for at each read and write rather than once, so a\n * browser that refuses it (private mode, blocked site data) is a refused\n * read or write rather than a failure to make the store. Defaults to\n * `globalThis.localStorage`.\n */\n storage?: () => {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n };\n /**\n * Where another tab's change is announced as a `storage` event. Defaults to\n * `globalThis` — the window — when it has `addEventListener`; `null` listens\n * nowhere, and a write still re-reads what is stored first.\n */\n events?: {\n addEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n removeEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n } | null;\n}\n\ntype KeptStorage = ReturnType<\n NonNullable<LocalStorageSnapshotOptions['storage']>\n>;\n\n/**\n * A `MemoryViewStore` snapshot kept in `localStorage` under `key`: the whole\n * store as one JSON document, `{ instances, preferences }`. For development\n * and single-user hosts until a real backend holds the views (phase 6); it\n * is one browser's, not a second store.\n *\n * Two things a browser does to such a document are the store's to answer,\n * and this is the design (decided 2026-09-28):\n *\n * - **A write storage refuses is a failed write.** `save` throws what\n * `setItem` threw (a full quota, blocked storage), and the store undoes the\n * write and rejects it as `UNAVAILABLE` — which the engine reports to the\n * environment's `onError` as a `store` failure and the UI shows as a save\n * whose outcome needs a retry, the error marked `storage` so the line\n * says the browser's storage is full or turned off rather than that the\n * result never came back. It never pretends a view was kept.\n * - **Tabs do not overwrite each other.** The stamps are the revisions the\n * stored state already carries, one per instance and one per definition's\n * preferences. The store re-reads this document before every write and\n * checks the write's revision against it, so a write merges instance by\n * instance into what another tab stored, and one based on a revision that\n * tab has moved past is a `CONFLICT`, the same flow a stale write in one\n * tab already takes. A `storage` event for `key` reloads the store, so\n * what another tab saved is listed without waiting for a write.\n *\n * A missing, unreadable or malformed document reads as nothing stored — the\n * store starts empty rather than the page breaking — and the next write\n * replaces it. The format is `{ instances, preferences }`.\n */\nexport function localStorageSnapshot(\n key: string,\n options: LocalStorageSnapshotOptions = {},\n): MemorySnapshot {\n const storage = options.storage ?? ambientStorage;\n const events =\n options.events === undefined ? ambientEvents() : options.events;\n return {\n load() {\n try {\n return parseState(storage().getItem(key));\n } catch {\n return undefined;\n }\n },\n save(state) {\n storage().setItem(key, JSON.stringify(state));\n },\n subscribe(listener) {\n if (!events) return () => {};\n const onStorage = (event: {\n key: string | null;\n storageArea?: unknown;\n }) => {\n // `null` is a `clear()`; another area (sessionStorage) is not ours.\n if (event.key !== null && event.key !== key) return;\n if (event.storageArea && event.storageArea !== readable(storage))\n return;\n listener();\n };\n events.addEventListener('storage', onStorage);\n return () => events.removeEventListener('storage', onStorage);\n },\n };\n}\n\nfunction ambientStorage(): KeptStorage {\n const storage = (globalThis as { localStorage?: KeptStorage }).localStorage;\n if (!storage) throw new Error('localStorage is not available');\n return storage;\n}\n\nfunction ambientEvents(): LocalStorageSnapshotOptions['events'] {\n const target = globalThis as Partial<\n NonNullable<LocalStorageSnapshotOptions['events']>\n >;\n return typeof target.addEventListener === 'function'\n ? (target as NonNullable<LocalStorageSnapshotOptions['events']>)\n : null;\n}\n\nfunction readable(storage: () => KeptStorage): KeptStorage | undefined {\n try {\n return storage();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The stored document, or `undefined` when it is not one. Only its outline\n * is checked here — an instance needs an id to be held by it; each config is\n * checked, and migrated, where every view out of a store is read.\n */\nfunction parseState(saved: string | null): MemoryState | undefined {\n if (!saved) return undefined;\n const state = JSON.parse(saved) as Partial<MemoryState> | null;\n if (\n !state ||\n typeof state !== 'object' ||\n !Array.isArray(state.instances) ||\n typeof state.preferences !== 'object' ||\n state.preferences === null ||\n Array.isArray(state.preferences)\n )\n return undefined;\n return {\n instances: state.instances.filter(isHeld),\n preferences: state.preferences,\n };\n}\n\nfunction isHeld(instance: unknown): instance is ViewInstance {\n return (\n typeof instance === 'object' &&\n instance !== null &&\n typeof (instance as { id?: unknown }).id === 'string'\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 ViewAudience,\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n ViewPreferences,\n} from '../model/index.js';\n\n/**\n * The only port a backend must satisfy. Its failure type is `ViewStoreError`\n * from `model`, so both sides of the port speak it.\n *\n * Eight methods, and two a store may leave out (`changeAudience`, and\n * `permissions`, whose absence allows everything but `editSystem`); two\n * consistency rules: a write carries the revision it expects, and a retry\n * reuses its `requestId` so the server can recognise the same intent.\n *\n * Authorization, visibility filtering and deduplication belong to the server.\n * `permissions` only drives which buttons a UI enables.\n */\nexport interface ViewStore {\n /**\n * The definition's views this user sees, as summaries, **in a fixed\n * order**: the backend's system views first, as it declares them, then\n * the shared views, then the user's personal ones, each audience oldest\n * first (the order they were created in; a view moved to the other\n * audience keeps its place by age there). With no preferences, the first\n * of the list is the view that opens by default (`resolveDefault`), so\n * every store answers the same one.\n */\n list(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewInstanceSummary[]>;\n get(id: string, signal?: AbortSignal): Promise<ViewInstance>;\n /**\n * Creates a view for the scope `input` names. `scope: 'system'` creates a\n * **stored system view** (D81) — what 「发布为系统视图」 and 另存为 send\n * when the host grants `editSystem` — and answers it with `stored: true`;\n * a store that keeps no system views refuses it (`FORBIDDEN` or\n * `INVALID`). Publishing is a copy: the view it was made from is not\n * touched. The engine never sends `stored` itself; the store sets it.\n */\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance>;\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n /**\n * Stores the title trimmed. A title blank once trimmed, or longer than\n * `MAX_VIEW_TITLE_LENGTH`, is refused as `INVALID` — so is one passed to\n * `create`, and a config of more than `MAX_VIEW_CONFIG_BYTES` passed to\n * `create` or `save`. The engine refuses both before sending; the store\n * keeps them for every other caller.\n */\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n delete(id: string, revision: string, context: WriteContext): Promise<void>;\n getPreferences(\n definitionId: string,\n signal?: AbortSignal,\n ): Promise<ViewPreferences>;\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences>;\n /**\n * Moves a view to the other audience in place (设为共享/设为个人, D18\n * item 10): the id stays, so a board that shows it keeps showing it.\n *\n * Optional: a store without it has no such entry in the manager, and the\n * engine refuses the command before anything is sent\n * (`view.changeAudience.unsupported`). One that has it keeps the rules of\n * every other instance write — the expected `revision` (`CONFLICT`\n * carrying `instance`), a replayed `requestId` answering the first\n * outcome, a system view refused (`FORBIDDEN`) — a stored one too: a\n * system view never moves audience — a missing one\n * `NOT_FOUND` — and two of its own:\n *\n * - **No change is no write.** Asked for the audience the view already\n * has, it answers the view as it is, revision unmoved (after the\n * revision check, so a stale one still conflicts).\n * - **A view a shared board shows stays shared.** Made personal, it would\n * be blank on that board for every other reader, so the store refuses\n * it as `INVALID` with **`boards`, those boards' titles** as stored (a\n * title written as a key stays one): the engine says the refusal in\n * its own words around them (`view.changeAudience.invalid.shared-boards`),\n * so an adapter whose server answers with ids reads the titles. Only the\n * store sees every board.\n * Deleting such a view stays allowed (the panel alone breaks).\n */\n changeAudience?(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance>;\n /** Synchronous, because the application fetched it before creating the engine. */\n permissions?(definitionId: string): ViewPermissions;\n /**\n * The most views `list` answers of one audience, where the store answers\n * no more (R2-26): `WowViewStore` lists the first 1000 of each. A list\n * holding this many of an audience was cut there, and the workbench says\n * so rather than leaving the rest unmentioned. Left out, a list is whole.\n */\n readonly listLimit?: number;\n}\n\n/**\n * One logical write. A retry after a timeout reuses the same `requestId` and\n * the same payload, which is what lets a server deduplicate it.\n */\nexport interface WriteContext {\n requestId: string;\n signal?: AbortSignal;\n}\n\n/** What the current user may do with one definition's views. */\nexport interface ViewPermissions {\n createPersonal: boolean;\n createShared: boolean;\n reorder: boolean;\n setDefault: boolean;\n /**\n * Whether this user edits the definition's **stored** system views\n * (`stored: true`) and creates new ones (`create({ scope: 'system' })`,\n * 「发布为系统视图」), D81. **Absent is false** — unlike everything else\n * here, where silence allows: a system view reaches every user, so only a\n * host that says so opens it, and a store without `permissions` does not.\n * When true, the `instance(id)` answer below applies to a stored system\n * view (save, rename, delete); a system view never moves audience, and\n * one declared in code or in the backend's configuration stays read-only.\n */\n editSystem?: boolean;\n /**\n * Whether this user edits the wording of the definition's dataset — its\n * title, record noun and field labels, order and hiding — in the view\n * manager (D91), where the dataset was registered with a store of wording.\n * **Absent is false**, as `editSystem`: the wording reaches every reader\n * of the tenant.\n */\n editDatasetWording?: boolean;\n instance(id: string): InstancePermissions;\n}\n\nexport interface InstancePermissions {\n save: boolean;\n rename: boolean;\n delete: boolean;\n /**\n * Whether the view may be moved to the other audience. Absent reads as\n * allowed — silence is not a refusal, as with the rest — and moving it\n * also asks the create permission of the audience it goes to\n * (`createShared` to share it, `createPersonal` to take it back).\n */\n changeAudience?: boolean;\n}\n\n/** An empty preference record, which is what an untouched definition has. */\nexport function emptyPreferences(): ViewPreferences {\n return { order: [], defaultInstanceId: null, revision: '0' };\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 configBytes,\n isSystemInstanceId,\n isSystemScope,\n MAX_VIEW_CONFIG_BYTES,\n MAX_VIEW_TITLE_LENGTH,\n titleProblem,\n toSummary,\n ViewStoreError,\n type ViewAudience,\n type ViewConfig,\n type ViewInstance,\n type ViewInstanceSummary,\n type ViewPreferences,\n} from '../model/index.js';\nimport {\n emptyPreferences,\n type ViewPermissions,\n type ViewStore,\n type WriteContext,\n} from './ViewStore.js';\n\nexport interface MemoryViewStoreOptions {\n instances?: ViewInstance[];\n preferences?: Record<string, ViewPreferences>;\n permissions?: (definitionId: string) => ViewPermissions;\n /** Lets an example keep its data across reloads; not a second store. */\n snapshot?: MemorySnapshot;\n /**\n * The most views `list` answers of one audience, oldest first, as a\n * server with a query budget answers (`ViewStore.listLimit`). Left out,\n * every view is listed. For a test of what a cut list does (R2-26).\n */\n listLimit?: number;\n}\n\n/**\n * Where a `MemoryViewStore` keeps its state between page loads: the whole\n * state, read and written as one document, synchronously.\n *\n * The store reads it when it is made, again before every write, and again\n * whenever `subscribe` says another writer changed it, so every write is\n * checked against what is stored now rather than what this store last saw\n * (see `MemoryViewStore`). `load` answers `undefined` for nothing readable,\n * and the store then keeps what it holds.\n *\n * `save` throws when the state could not be kept — storage full, blocked,\n * refused. The store then undoes the write in memory and rejects it with a\n * `ViewStoreError` (`UNAVAILABLE`), so nobody is told a view was saved that\n * the next page load will not have.\n */\nexport interface MemorySnapshot {\n load(): MemoryState | undefined;\n save(state: MemoryState): void;\n /** Tells the store that another writer changed the state; answers the unsubscribe. */\n subscribe?(listener: () => void): () => void;\n}\n\nexport interface MemoryState {\n instances: ViewInstance[];\n preferences: Record<string, ViewPreferences>;\n}\n\n/**\n * The one implementation this package ships: a synchronous map behind the\n * port, for tests, examples and query-only use.\n *\n * It keeps the two consistency rules honest rather than convenient. A write\n * with a stale revision conflicts, and a replayed `requestId` returns the\n * first outcome instead of writing twice, so code written against it behaves\n * the same against a real backend — as do the port's list order and the\n * server's limits on a title and a config, which it refuses as the server\n * does (`INVALID`).\n *\n * System views come two ways (D81). One seeded with `scope: 'system'` and\n * no `stored` is a configured one, as the backend's configuration serves\n * it: every write to it is refused (`FORBIDDEN`). One created with\n * `scope: 'system'` — 「发布为系统视图」 — or seeded with `stored: true` is\n * a stored one: saved, renamed and deleted like a shared view, never moved\n * to another audience (`FORBIDDEN`). Like the server, the store asks no\n * permission of its own; `editSystem` is the host's to grant and the\n * engine's to ask.\n *\n * With a snapshot, several stores may share one stored state — two tabs over\n * one `localStorage`. The rule between them is the backend's: **re-read, then\n * compare revisions, one instance (or one definition's preferences) at a\n * time.** Before every write the store reloads the stored state, so a write\n * merges into what the other writer left — a board created in one tab\n * survives a reorder in the other, and ids never collide — and a write whose\n * `revision` the other writer has already moved past is refused as\n * `CONFLICT`, carrying what is stored, as any stale write is. Nothing is ever\n * overwritten because this store's copy was old. A write the snapshot could\n * not keep is undone and rejected as `UNAVAILABLE`: it did not land, so a\n * retry under the same `requestId` is safe.\n */\nexport class MemoryViewStore implements ViewStore {\n private readonly instances = new Map<string, ViewInstance>();\n private readonly preferences = new Map<string, ViewPreferences>();\n /** Outcome per logical instance write, so a retry is idempotent. */\n private readonly outcomes = new Map<string, ViewInstance | null>();\n /** The same rule for preferences, whose outcome is no instance. */\n private readonly preferenceOutcomes = new Map<string, ViewPreferences>();\n private readonly snapshot?: MemorySnapshot;\n readonly permissions?: (definitionId: string) => ViewPermissions;\n /** See `MemoryViewStoreOptions.listLimit`; absent unless one was given. */\n readonly listLimit?: number;\n private sequence = 0;\n\n constructor(options: MemoryViewStoreOptions = {}) {\n // Left undefined when the caller declared none, which the port reads as\n // \"everything is allowed\".\n if (options.permissions) this.permissions = options.permissions;\n if (options.listLimit !== undefined) this.listLimit = options.listLimit;\n this.snapshot = options.snapshot;\n\n const restored = options.snapshot?.load();\n this.restore({\n instances: restored?.instances ?? options.instances ?? [],\n preferences: restored?.preferences ?? options.preferences ?? {},\n });\n options.snapshot?.subscribe?.(() => this.reload());\n }\n\n /**\n * In the port's order: system, shared, personal, each oldest first. The\n * map keeps insertion order — the order views were created or seeded in,\n * which a change of audience does not move — and the sort is stable.\n */\n list(definitionId: string): Promise<ViewInstanceSummary[]> {\n const summaries = [...this.instances.values()]\n .filter(instance => instance.definitionId === definitionId)\n .map(toSummary)\n .sort((a, b) => AUDIENCE_RANK[a.scope] - AUDIENCE_RANK[b.scope]);\n const limit = this.listLimit;\n if (limit === undefined) return Promise.resolve(summaries);\n // The first `limit` of each audience, the rest left out as a server's\n // budget would leave them.\n const seen = new Map<string, number>();\n return Promise.resolve(\n summaries.filter(summary => {\n const count = (seen.get(summary.scope) ?? 0) + 1;\n seen.set(summary.scope, count);\n return count <= limit;\n }),\n );\n }\n\n get(id: string): Promise<ViewInstance> {\n const instance = this.instances.get(id);\n return instance\n ? Promise.resolve(copy(instance))\n : Promise.reject(new ViewStoreError('NOT_FOUND', `No such view: ${id}`));\n }\n\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteContext,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n const refused = titleRefusal(input.title) ?? configRefusal(input.config);\n if (refused) return Promise.reject(refused);\n this.reload();\n\n // Seeded instances occupy ids too, so the counter walks past anything\n // already taken rather than overwriting it.\n let id: string;\n do {\n this.sequence += 1;\n id = `${input.definitionId}-${this.sequence}`;\n } while (this.instances.has(id));\n if (isSystemInstanceId(id))\n return Promise.reject(\n new ViewStoreError('INVALID', `Reserved id namespace: ${id}`),\n );\n\n // `stored` is the store's to say, never the caller's: a system view\n // created here is one it keeps, and nothing else is one.\n const given = copy(input);\n delete given.stored;\n const instance: ViewInstance = {\n ...given,\n title: input.title.trim(),\n id,\n revision: '1',\n ...(isSystemScope(input.scope) ? { stored: true as const } : {}),\n };\n this.instances.set(id, instance);\n return this.commit(context, instance, () => this.instances.delete(id));\n }\n\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, config: copy(config) }),\n configRefusal(config),\n );\n }\n\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, title: title.trim() }),\n titleRefusal(title),\n );\n }\n\n /**\n * The port's in-place audience change: personal and shared swap, the id\n * and everything else stay. Asked for the audience the view already has,\n * it answers the view unchanged — no revision spent, nothing written — and\n * remembers that answer under the `requestId` like any other outcome.\n * A view a shared (or system) board shows is refused as `INVALID` when it\n * would become personal, `boards` naming those boards by title. A system\n * view, stored or not, never moves (`FORBIDDEN`).\n */\n changeAudience(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteContext,\n ): Promise<ViewInstance> {\n return this.update(id, revision, context, current => {\n if (isSystemScope(current.scope))\n return new ViewStoreError('FORBIDDEN', 'System views stay system');\n if (audienceOf(current.scope) === audience) return null;\n if (audience === 'personal') {\n const boards = this.sharedBoardsShowing(id);\n if (boards.length > 0)\n return new ViewStoreError(\n 'INVALID',\n `Shared dashboards show view ${id}: ${boards.join(', ')}`,\n { boards },\n );\n }\n return { ...current, scope: audience };\n });\n }\n\n delete(id: string, revision: string, context: WriteContext): Promise<void> {\n if (this.outcomes.has(context.requestId)) return Promise.resolve();\n this.reload();\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n // Deleting a configured system view is refused exactly as overwriting\n // one is: it is declared in code or by operations, and no user write\n // reaches it. A stored one is deleted like a shared view (unpublished).\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n this.instances.delete(id);\n const refused = this.persist(() => this.instances.set(id, current));\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, null);\n return Promise.resolve();\n }\n\n getPreferences(definitionId: string): Promise<ViewPreferences> {\n return Promise.resolve(\n this.preferences.get(definitionId) ?? emptyPreferences(),\n );\n }\n\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteContext,\n ): Promise<ViewPreferences> {\n // A replay answers with the outcome the first attempt produced, as every\n // other write does: a retry after a lost answer is the same logical\n // write, and reporting a conflict for it would be a lie.\n const replayed = this.preferenceOutcomes.get(context.requestId);\n if (replayed) return Promise.resolve(replayed);\n this.reload();\n\n const held = this.preferences.get(definitionId);\n const current = held ?? emptyPreferences();\n if (current.revision !== preferences.revision)\n return Promise.reject(\n new ViewStoreError(\n 'CONFLICT',\n `Preferences for ${definitionId} changed`,\n { preferences: current },\n ),\n );\n\n const next: ViewPreferences = {\n ...preferences,\n revision: nextRevision(current.revision),\n };\n this.preferences.set(definitionId, next);\n const refused = this.persist(() =>\n held\n ? this.preferences.set(definitionId, held)\n : this.preferences.delete(definitionId),\n );\n if (refused) return Promise.reject(refused);\n this.preferenceOutcomes.set(context.requestId, next);\n return Promise.resolve(next);\n }\n\n /**\n * One instance write: replay, the refusal of its input (`refused`, as the\n * server validates a command before it reaches the view), re-read, the\n * three refusals every instance write shares, then `change`. It may answer\n * `null` for a write that changes nothing — the view is answered as it is\n * and the revision is not spent — or a `ViewStoreError` for a refusal of\n * its own.\n */\n private update(\n id: string,\n revision: string,\n context: WriteContext,\n change: (current: ViewInstance) => ViewInstance | ViewStoreError | null,\n refused?: ViewStoreError,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n if (refused) return Promise.reject(refused);\n this.reload();\n\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n const changed = change(current);\n if (changed instanceof ViewStoreError) return Promise.reject(changed);\n if (changed === null) {\n this.outcomes.set(context.requestId, current);\n return Promise.resolve(copy(current));\n }\n const next: ViewInstance = {\n ...changed,\n revision: nextRevision(current.revision),\n };\n this.instances.set(id, next);\n return this.commit(context, next, () => this.instances.set(id, current));\n }\n\n /**\n * The titles of the boards everyone sees that show `id` in a panel — the\n * reference the dashboard kernel's `coversScope` guards from the board's\n * side. Read off the stored configs as the untrusted JSON they are: the\n * store may import nothing but the model.\n */\n private sharedBoardsShowing(id: string): string[] {\n const boards: string[] = [];\n for (const instance of this.instances.values()) {\n const { config } = instance;\n if (\n config.kind !== 'dashboard' ||\n audienceOf(instance.scope) !== 'shared'\n )\n continue;\n const panels: unknown = config.panels;\n if (Array.isArray(panels) && panels.some(panel => shows(panel, id)))\n boards.push(instance.title);\n }\n return boards;\n }\n\n private expect(\n current: ViewInstance,\n revision: string,\n ): ViewStoreError | undefined {\n return current.revision === revision\n ? undefined\n : new ViewStoreError(\n 'CONFLICT',\n `View ${current.id} moved to revision ${current.revision}`,\n { instance: current },\n );\n }\n\n private commit(\n context: WriteContext,\n instance: ViewInstance,\n undo: () => void,\n ): Promise<ViewInstance> {\n const refused = this.persist(undo);\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, instance);\n return Promise.resolve(copy(instance));\n }\n\n /**\n * Hands the state to the snapshot. When it could not be kept, the change\n * just made is undone — memory goes back to what is stored — and the\n * refusal is answered, so the write rejects rather than being reported as\n * saved. No outcome is remembered for it, so a retry writes again.\n */\n private persist(undo: () => void): ViewStoreError | undefined {\n if (!this.snapshot) return undefined;\n try {\n this.snapshot.save({\n instances: [...this.instances.values()].map(instance => copy(instance)),\n preferences: Object.fromEntries(this.preferences),\n });\n return undefined;\n } catch (error) {\n undo();\n return new ViewStoreError(\n 'UNAVAILABLE',\n `The view store could not keep this write: ${reasonOf(error)}`,\n { storage: true },\n );\n }\n }\n\n /**\n * Takes the stored state as it is now, when there is one to read: before a\n * write, so the write is checked against it, and when another writer says\n * it changed. Nothing readable leaves what the store holds as it is.\n */\n private reload(): void {\n const stored = this.snapshot?.load();\n if (stored) this.restore(stored);\n }\n\n private restore(state: MemoryState): void {\n this.instances.clear();\n this.preferences.clear();\n for (const instance of state.instances)\n this.instances.set(instance.id, copy(instance));\n for (const [definitionId, preferences] of Object.entries(state.preferences))\n this.preferences.set(definitionId, preferences);\n }\n}\n\n/**\n * Whether a stored panel references the saved view `id`, by any of the\n * three members the server reads (`ViewConfigs.PANEL_REFERENCES`, and\n * `DashboardPanel`): the view it shows (`instanceId`, unless the board owns\n * the view, `owned`), the view 「在工作台中打开」 opens (`opens`), and the\n * one a press opens (`click.instanceId`).\n */\nfunction shows(panel: unknown, id: string): boolean {\n if (typeof panel !== 'object' || panel === null) return false;\n const { instanceId, owned, opens, click } = panel as {\n instanceId?: unknown;\n owned?: unknown;\n opens?: unknown;\n click?: unknown;\n };\n if (owned === undefined && instanceId === id) return true;\n if (opens === id) return true;\n return (\n typeof click === 'object' &&\n click !== null &&\n (click as { instanceId?: unknown }).instanceId === id\n );\n}\n\n/** A system view no write reaches: configured, not one this store keeps. */\nfunction readOnlySystem(instance: ViewInstance): boolean {\n return isSystemScope(instance.scope) && instance.stored !== true;\n}\n\n/** System views first, then shared, then personal: the port's list order. */\nconst AUDIENCE_RANK: Readonly<Record<ViewInstance['scope'], number>> = {\n system: 0,\n shared: 1,\n personal: 2,\n};\n\n/**\n * The revision after `current`. Revisions are opaque to the port, and a host\n * may seed any string; one this store did not write as a count (`'ops-1'`)\n * starts the count again at `'1'`, which it can never have been, so a write\n * against it still conflicts. A count goes on counting.\n */\nfunction nextRevision(current: string): string {\n return /^(0|[1-9]\\d{0,14})$/.test(current)\n ? String(Number(current) + 1)\n : '1';\n}\n\n/** A title the server refuses (`ViewConfigs.requireTitle`), in its words. */\nfunction titleRefusal(title: string): ViewStoreError | undefined {\n switch (titleProblem(title)) {\n case 'empty':\n return new ViewStoreError('INVALID', \"A view's title must not be blank.\");\n case 'too-long':\n return new ViewStoreError(\n 'INVALID',\n `A view's title is longer than ${MAX_VIEW_TITLE_LENGTH} characters.`,\n );\n default:\n return undefined;\n }\n}\n\n/** A config larger than the server keeps, in its words. */\nfunction configRefusal(config: ViewConfig): ViewStoreError | undefined {\n const bytes = configBytes(config);\n return bytes > MAX_VIEW_CONFIG_BYTES\n ? new ViewStoreError(\n 'INVALID',\n `A view's config is ${bytes} bytes; the limit is ${MAX_VIEW_CONFIG_BYTES}.`,\n )\n : undefined;\n}\n\n/** What a refusal said — a `DOMException` is an `Error` only in some realms. */\nfunction reasonOf(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (typeof message === 'string')\n return typeof name === 'string' ? `${name}: ${message}` : message;\n }\n return String(error);\n}\n\n/**\n * A structural copy, so nothing a caller holds is the object the store keeps.\n * A config handed in or read back is a plain JSON tree, and a caller editing\n * one it still has a reference to must not change what is stored.\n */\nfunction copy<T>(value: T): T {\n return structuredClone(value);\n}\n"],"mappings":";;;;;AA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C1E,IACAoC,KAAAA;AACN;AAGA,SAAS6E,GAASD,GAAwB;CACxC,IAAI,OAAOA,KAAU,YAAYA,GAAgB;EAC/C,IAAM,EAAEiB,SAAMC,eAAYlB;EAC1B,IAAI,OAAOkB,KAAY,UACrB,OAAO,OAAOD,KAAS,WAAW,GAAGA,EAAI,IAAKC,MAAYA;CAC9D;CACA,OAAOJ,OAAOd,CAAK;AACrB;AAOA,SAASpD,EAAQuE,GAAa;CAC5B,OAAOE,gBAAgBF,CAAK;AAC9B"}
1
+ {"version":3,"file":"index.js","names":["QueryModelDescriptor","AnalysisCapability","AnalysisSpec","FieldAnalysisSpec","Issue","OpenCapabilities","issue","describedAnalysis","BuiltField","analysisPlan","spec","fields","undefined","narrowed","entry","analysis","plan","NonNullable","elements","own","described","children","entries","Record","child","one","field","name","buildAnalysis","descriptor","findings","map","what","push","TimeUnit","FieldDescriptor","QueryModelDescriptor","TEMPORAL_FIELD_KIND_IDS","AggregationMetricTypes","FilterOperators","QuerySemanticTypes","QueryValueTypes","TimeUnits","readsAsNames","FieldDefinition","FieldKindId","FieldOption","FieldTemporal","Issue","RecordPagingMode","issue","describedField","dynamicFieldsOf","DescribedField","FieldSpec","OptionSpec","FieldBuild","descriptor","paging","findings","BuiltField","field","described","spec","sensitive","children","found","code","params","Record","severity","buildFields","listed","Readonly","scope","build","Object","entries","flatMap","key","given","label","built","buildField","path","undefined","search","searchField","push","raw","fieldDescriptor","canonical","kind","kindOf","name","labelOf","comparable","sorts","sort","cursor","paged","byId","remote","more","sortsByDefault","sortable","operators","offered","operatorsOffered","operator","has","summary","functions","aggregate","fn","COUNT","includes","options","optionsOf","temporal","temporalOf","deprecated","message","elements","some","element","map","entry","elementTitle","cell","timePrecision","assign","fields","searchFields","mode","searchMode","RawField","Pick","own","find","dynamicField","relative","slice","length","variants","values","variant","aliases","matched","first","types","Set","semantic","type","TEMPORAL_DATE","TEMPORAL_EPOCH","timeUnit","SECONDS","enum","BOOLEAN","TEMPORAL_FORMATTED","INTEGER","DECIMAL","STRING","description","ReadonlySet","filter","add","ELEMENT_MATCH","listedOptions","value","option","known","Map","String","said","get","Array","isArray","keys","Exclude","QueryModelDescriptor","DataViewDefinition","FieldDefinition","Issue","RecordPagingMode","RecordCapability","issue","analysisPlan","buildAnalysis","buildFields","BuiltField","narrowDefinition","constructible","builtinFieldKinds","FieldKindRegistry","DefineViewSpec","PagingModes","defineView","descriptor","spec","options","DefineViewOptions","findings","record","recordOf","fields","undefined","paging","definition","id","title","kind","source","map","entry","field","recordNoun","fieldGroups","plan","analysis","timeField","views","sort","flatMap","given","described","sortable","name","operators","openComparisons","withSnapshotComparisons","kinds","Set","version","open","scope","children","path","own","narrowed","ReadonlySet","index","cut","next","has","elements","PAGING","Readonly","Record","PAGED","CURSOR","offered","mode","includes","push","rowKey","identity","layouts","QueryModelDescriptor","DataViewDefinition","defineView","DefineViewOptions","FieldSpec","DefineDatasetSpec","id","source","title","recordNoun","fields","Readonly","Record","defineDataset","descriptor","spec","options","derived","Map","field","scope","undefined","set","path","description","override","Object","entries","label","get","delete","defineDataset","DefineDatasetSpec","ReadOptions","WriteOptions","ViewDefinition","ViewSource","ViewResource","DatasetDirectoryEntry","context","dataset","title","version","DatasetCatalog","list","options","Promise","source","entry","overrides","DatasetOverrides","wordings","DatasetWordingStore","StoredDatasetWording","wording","revision","ReadonlyMap","set","DatasetWordingEditor","derivedTitle","fields","name","label","save","Partial","Pick","DatasetRegistrar","definitions","register","resource","unregister","definitionId","DatasetResource","id","catalog","DatasetDuplicate","dropped","kept","DatasetRefresh","datasets","duplicates","DatasetResourcesInit","catalogs","onError","error","onWordingError","onDuplicate","duplicate","onCatalogError","Listed","DatasetResources","held","Map","worded","stored","derived","descriptor","Parameters","constructor","engine","init","Array","isArray","length","Error","resources","values","refresh","readWordings","lists","allSettled","map","signal","throwIfAborted","every","status","reason","servable","unread","Set","forEach","add","value","get","push","has","keys","delete","all","listed","serve","order","sort","a","b","indexOf","read","index","store","wordingOf","words","JSON","stringify","described","describe","undefined","notModified","registerWorded","current","definition","editorOf","plain","ViewInstance","MemorySnapshot","MemoryState","LocalStorageSnapshotOptions","storage","getItem","key","setItem","value","events","addEventListener","type","listener","event","storageArea","removeEventListener","KeptStorage","ReturnType","NonNullable","localStorageSnapshot","options","ambientStorage","undefined","ambientEvents","load","parseState","save","state","JSON","stringify","subscribe","onStorage","readable","globalThis","localStorage","Error","target","Partial","saved","parse","Array","isArray","instances","preferences","filter","isHeld","instance","id","ViewAudience","ViewConfig","ViewInstance","ViewInstanceSummary","ViewPreferences","ViewStore","list","definitionId","options","ViewListOptions","Promise","ViewListPage","get","id","ReadOptions","create","input","Omit","WriteOptions","save","config","revision","rename","title","delete","getPreferences","setPreferences","preferences","changeAudience","audience","permissions","ViewPermissions","signal","AbortSignal","cursor","items","nextCursor","requestId","createPersonal","createShared","reorder","setDefault","editSystem","editDatasetWording","instance","InstancePermissions","emptyPreferences","order","defaultInstanceId","audienceOf","configBytes","isSystemInstanceId","isSystemScope","MAX_VIEW_CONFIG_BYTES","MAX_VIEW_TITLE_LENGTH","titleProblem","toSummary","ViewStoreError","ViewAudience","ViewConfig","ViewInstance","ViewPreferences","ViewListOptions","ViewListPage","ViewPermissions","ViewStore","WriteOptions","emptyPreferences","DEFAULT_PAGE_SIZE","MemoryViewStoreOptions","instances","preferences","Record","permissions","definitionId","snapshot","MemorySnapshot","pageSize","load","MemoryState","save","state","subscribe","listener","MemoryViewStore","Map","outcomes","preferenceOutcomes","sequence","constructor","options","restored","restore","reload","list","Promise","summaries","values","filter","instance","map","sort","a","b","AUDIENCE_RANK","scope","start","cursor","Number","end","resolve","items","slice","nextCursor","length","String","get","id","copy","reject","create","input","Omit","context","replayed","requestId","refused","titleRefusal","title","configRefusal","config","has","given","stored","trim","revision","const","set","commit","delete","update","current","rename","changeAudience","audience","boards","sharedBoardsShowing","join","readOnlySystem","conflict","expect","persist","getPreferences","setPreferences","held","next","nextRevision","change","changed","kind","panels","Array","isArray","some","panel","shows","push","undefined","undo","Object","fromEntries","error","reasonOf","storage","clear","entries","instanceId","owned","opens","click","Readonly","system","shared","personal","test","bytes","name","message","value","T","structuredClone","describedField","isSystemScope","createFieldKindRegistry","withText","validateDefinition","QuerySemanticTypes","isViewCommandError","compileAnalysis","TimeUnits","ViewWriteError","DEFAULT_RUNTIME_LIMITS","ViewStoreError","MAX_VIEW_CONFIG_BYTES","BUILTIN_FIELD_KINDS","text","issue","projectRecord","isViewWriteError","validateRecord","withFieldKinds","constructible","configBytes","textKeyOf","ViewCommandError","VIEW_STORE_ERROR_CODES","isViewStoreError","compileRecord","narrowDefinition","validateFilter","MAX_VIEW_TITLE_LENGTH","TEMPORAL_FIELD_KIND_IDS","describedAnalysis","audienceOf","compileFilter","systemInstanceId","titleProblem","dynamicFieldsOf","CHART_TYPES","EDITOR_INPUTS","isDateTimeFilterValue","AggregationMetricTypes","validateDashboard","validateAnalysis","isSystemInstanceId","builtinFieldKinds","actions","resolveDateTimeRange","projectAnalysis","readsAsNames","toSummary","QueryValueTypes","PagingModes","FilterOperators","inRows","defaultAnalysisConfig","emptyDashboardConfig","ReferenceLabelTimeoutError","ViewEngine","isExportCancelledError","hasResult","fitChartSlots","isRecordRuntime","DEFAULT_MISSING_KEY","isAnalysisRuntime","defaultRecordConfig","ExportCancelledError","hasAsked","defaultRuntimeEnvironment","serializeCsv","analysisPlan","spec","narrowed","entry","plan","fields","own","entries","child","one","buildAnalysis","descriptor","findings","field","found","code","params","severity","buildFields","listed","key","given","built","buildField","scope","build","path","searchField","described","raw","fieldDescriptor","kind","kindOf","labelOf","comparable","sorts","byId","sortsByDefault","offered","operatorsOffered","operator","functions","fn","options","optionsOf","temporal","temporalOf","children","element","search","name","dynamicField","relative","variants","variant","matched","first","semantic","TimeUnit","types","listedOptions","values","value","option","known","said","defineView","record","recordOf","definition","analysis","sort","operators","openComparisons","withSnapshotComparisons","cut","index","next","open","PAGING","mode","paging","defineDataset","derived","override","label","DatasetResources","engine","init","catalogs","lists","catalog","list","servable","duplicates","unread","id","kept","held","duplicate","order","a","b","read","store","error","words","wording","source","current","title","derivedTitle","revision","context","stored","localStorageSnapshot","storage","ambientStorage","events","ambientEvents","parseState","state","onStorage","event","readable","listener","target","saved","isHeld","instance","emptyPreferences","DEFAULT_PAGE_SIZE","MemoryViewStore","restored","summaries","definitionId","AUDIENCE_RANK","start","end","copy","replayed","refused","titleRefusal","input","configRefusal","config","audience","boards","readOnlySystem","conflict","preferences","nextRevision","changed","change","panels","shows","panel","undo","reasonOf","owned","instanceId","opens","click","bytes","message"],"sources":["../src/runtime/define/analysis.ts","../src/runtime/define/fields.ts","../src/runtime/define/defineView.ts","../src/runtime/define/defineDataset.ts","../src/runtime/datasetResources.ts","../src/store/localStorageSnapshot.ts","../src/store/ViewStore.ts","../src/store/MemoryViewStore.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\n/**\n * The analyses of a `defineView` definition: which fields analyse and how\n * the host narrows each is the host's (the plan, `OpenCapabilities`); what\n * each path offers is its source's. Built here over the snapshot — what a\n * source with no descriptor runs on — and read again over a source's own\n * descriptor when it narrows (`reopened`). A narrowing beyond what the\n * snapshot grants is a warning, not an error: another store may grant it.\n */\n\nimport type { QueryModelDescriptor } from '@ahoo-wang/wow-client/dsl';\nimport type {\n AnalysisCapability,\n AnalysisSpec,\n FieldAnalysisSpec,\n Issue,\n OpenCapabilities,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { describedAnalysis } from '../../capabilities/open.js';\nimport type { BuiltField } from './fields.js';\n\n/** Which fields analyse, and the host's narrowing of each; `undefined` for none. */\nexport function analysisPlan(\n spec: AnalysisSpec | false | undefined,\n fields: readonly BuiltField[],\n): OpenCapabilities['analysis'] {\n if (spec === false) return undefined;\n const narrowed = (entry: BuiltField): FieldAnalysisSpec | null =>\n entry.spec.analysis === false ? null : (entry.spec.analysis ?? {});\n const plan: NonNullable<OpenCapabilities['analysis']> = {\n spec: spec ?? {},\n fields: {},\n elements: {},\n };\n for (const entry of fields) {\n const own = entry.described ? narrowed(entry) : null;\n if (!own) continue;\n if (entry.children) {\n const entries: Record<string, FieldAnalysisSpec> = {};\n for (const child of entry.children) {\n const one = narrowed(child);\n if (one) entries[child.field.name] = one;\n }\n (plan.elements as Record<string, typeof entries>)[entry.field.name] =\n entries;\n } else\n (plan.fields as Record<string, FieldAnalysisSpec>)[entry.field.name] =\n own;\n }\n return plan;\n}\n\n/** The plan's analyses over the snapshot, what it asks beyond said as warnings. */\nexport function buildAnalysis(\n plan: OpenCapabilities['analysis'],\n fields: readonly BuiltField[],\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): AnalysisCapability | undefined {\n if (!plan) return undefined;\n return describedAnalysis(\n plan,\n fields.map(entry => entry.field),\n descriptor,\n (field, what) =>\n findings.push(\n field === null\n ? issue(\n 'definition.analysis.wider',\n ['analysis'],\n { what },\n 'warning',\n )\n : issue(\n 'definition.field.analysis-wider',\n ['analysis'],\n { field, what },\n 'warning',\n ),\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 * A field as `defineView` builds it (host-integration.md 3): its kind, its\n * values and whether it sorts are the descriptor's; its label, its order,\n * its cell and what it narrows are the host's. The operators are left to\n * the kind unless the host narrows them — the engine cuts them to the\n * descriptor in force whenever a view runs (N5), so a list copied here\n * would only go stale.\n */\n\nimport {\n TimeUnit,\n type FieldDescriptor,\n type QueryModelDescriptor,\n} from '@ahoo-wang/wow-client/dsl';\nimport {\n TEMPORAL_FIELD_KIND_IDS,\n AggregationMetricTypes,\n FilterOperators,\n QuerySemanticTypes,\n QueryValueTypes,\n TimeUnits,\n readsAsNames,\n type FieldDefinition,\n type FieldKindId,\n type FieldOption,\n type FieldTemporal,\n type Issue,\n type RecordPagingMode,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport {\n describedField,\n dynamicFieldsOf,\n type DescribedField,\n} from '../../capabilities/match.js';\nimport type { FieldSpec, OptionSpec } from './spec.js';\n\n/** What building the fields reads, and where it says what it found. */\ninterface FieldBuild {\n descriptor: QueryModelDescriptor;\n paging: RecordPagingMode;\n findings: Issue[];\n}\n\n/** One built field and what it is over, for the analyses to read. */\nexport interface BuiltField {\n field: FieldDefinition;\n described: DescribedField | null;\n spec: FieldSpec;\n /** Whether the value is sensitive: masked, so never grouped or measured. */\n sensitive: boolean;\n /** An array's entries, built as its fields are. */\n children?: BuiltField[];\n}\n\nconst found = (\n code: string,\n params: Record<string, string>,\n severity: Issue['severity'] = 'error',\n): Issue => issue(code, ['fields'], params, severity);\n\n/** The fields listed, built in the order listed; one the descriptor lacks is left out. */\nexport function buildFields(\n listed: Readonly<Record<string, FieldSpec | string>>,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField[] {\n return Object.entries(listed).flatMap(([key, given]) => {\n const spec: FieldSpec =\n typeof given === 'string' ? { label: given } : given;\n const built = buildField(key, spec, scope, build);\n return built ? [built] : [];\n });\n}\n\nfunction buildField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField | null {\n const { descriptor, findings } = build;\n const path = scope === undefined ? key : `${scope}.${key}`;\n if (spec.search) return searchField(key, spec, scope, build);\n\n const described = describedField(descriptor, path, scope);\n if (!described) {\n findings.push(found('definition.field.undescribed', { field: path }));\n return null;\n }\n const raw = fieldDescriptor(descriptor, described.canonical ?? path, scope);\n const kind = spec.kind ?? kindOf(raw, described, spec);\n if (kind === null) {\n findings.push(found('definition.field.kind-unknown', { field: path }));\n return null;\n }\n const field: FieldDefinition = {\n name: key,\n label: labelOf(spec, raw, path, findings),\n kind,\n };\n const comparable = described.comparable !== false;\n\n // An entry's field is read inside its record, not what records are\n // ordered by: offered as a sort only where the host asks.\n const sorts =\n comparable &&\n (build.paging === 'cursor' ? described.sort.cursor : described.sort.paged);\n // A reference read as names sorts by its stored id, which no reader\n // sees: offered only where the host asks, and then said.\n const byId = readsAsNames({ kind, remote: spec.more?.remote });\n const sortsByDefault = sorts && scope === undefined && !byId;\n if (spec.sortable === true && !sorts)\n findings.push(\n found('definition.field.sort-wider', { field: path }, 'warning'),\n );\n if (sorts && (spec.sortable ?? sortsByDefault)) field.sortable = true;\n\n if (spec.operators) {\n const offered = operatorsOffered(descriptor, described, path);\n for (const operator of spec.operators)\n if (!offered.has(operator))\n findings.push(\n found(\n 'definition.field.operator-wider',\n { field: path, operator },\n 'warning',\n ),\n );\n field.operators = spec.operators;\n } else if (!comparable) field.operators = [];\n\n if (spec.summary) {\n const functions: readonly string[] = described.aggregate?.functions ?? [];\n for (const fn of spec.summary)\n if (fn !== AggregationMetricTypes.COUNT && !functions.includes(fn))\n findings.push(\n found(\n 'definition.field.summary-wider',\n { field: path, fn },\n 'warning',\n ),\n );\n field.summary = spec.summary;\n }\n\n const options = optionsOf(spec, described, path, findings);\n if (options) field.options = options;\n\n // A time is written in conditions the way the model keeps it, so the field\n // keeps the descriptor's way: a date string, or an epoch in its unit.\n // Without it a dataset's date column read as epoch milliseconds, and the\n // capability check refused the whole dataset (found by analytics/demo).\n const temporal = temporalOf(described);\n if (temporal && TEMPORAL_FIELD_KIND_IDS.includes(kind))\n field.temporal = temporal;\n\n if (described.deprecated) {\n if (!spec.deprecated)\n findings.push(\n found(\n 'definition.field.deprecated',\n { field: path, message: described.deprecated.message ?? '' },\n 'warning',\n ),\n );\n field.deprecated = spec.deprecated ?? described.deprecated;\n }\n\n let children: BuiltField[] | undefined;\n if (spec.elements) {\n if (!descriptor.elements.some(element => element.path === path))\n findings.push(found('definition.field.not-elements', { field: path }));\n children = buildFields(spec.elements, path, build);\n field.elements = children.map(entry => entry.field);\n }\n if (spec.elementTitle !== undefined) field.elementTitle = spec.elementTitle;\n if (spec.cell !== undefined) field.cell = spec.cell;\n if (spec.timePrecision !== undefined)\n field.timePrecision = spec.timePrecision;\n Object.assign(field, spec.more);\n return {\n field,\n described,\n spec,\n sensitive: described.sensitive === true,\n ...(children ? { children } : {}),\n };\n}\n\n/** A search box: its fields must be paths the descriptor has. */\nfunction searchField(\n key: string,\n spec: FieldSpec,\n scope: string | undefined,\n build: FieldBuild,\n): BuiltField {\n const search = spec.search ?? { fields: [] };\n // An entry's search names its fields within the entry (N4).\n for (const name of search.fields) {\n const path = scope === undefined ? name : `${scope}.${name}`;\n if (!describedField(build.descriptor, path, scope))\n build.findings.push(\n found('definition.field.undescribed', { field: path }),\n );\n }\n const field: FieldDefinition = {\n name: key,\n label: spec.label ?? key,\n kind: 'search',\n searchFields: search.fields,\n };\n if (search.mode) field.searchMode = search.mode;\n return { field, described: null, spec, sensitive: false };\n}\n\n/** What building a field reads of the descriptor's entry for its path. */\ntype RawField = Pick<FieldDescriptor, 'types' | 'kind' | 'description'>;\n\n/**\n * The descriptor's own entry for a path, for what `describedField` leaves\n * out; a map's key under a dynamic pattern (`state.tags.{key}`) has the\n * pattern's types, so its kind is read off them as a field's is.\n */\nfunction fieldDescriptor(\n descriptor: QueryModelDescriptor,\n path: string,\n scope: string | undefined,\n): RawField | undefined {\n const own = descriptor.fields.find(\n entry => entry.path === path && entry.scope === scope,\n );\n if (own) return own;\n if (scope === undefined) return dynamicField(descriptor, path);\n // A variant's fields are listed relative to the element, by path or alias,\n // as `describedField` reads them.\n const relative = path.slice(scope.length + 1);\n const variants = descriptor.variants;\n if (variants?.element !== scope) return undefined;\n return variants.values\n .flatMap(variant => variant.fields)\n .find(\n entry =>\n entry.path === relative || (entry.aliases ?? []).includes(relative),\n );\n}\n\n/**\n * The patterns a key falls under, as one entry: their types together, so\n * two patterns that disagree name no single kind.\n */\nfunction dynamicField(\n descriptor: QueryModelDescriptor,\n path: string,\n): RawField | undefined {\n const matched = dynamicFieldsOf(descriptor, path);\n const first = matched[0];\n if (!first) return undefined;\n return {\n types: [...new Set(matched.flatMap(entry => entry.types))],\n kind: first.kind,\n };\n}\n\n/**\n * How the descriptor says a time is kept, where it says anything a field\n * must be told: a date string, or an epoch in seconds. Epoch milliseconds\n * is the field's own default (`DEFAULT_TEMPORAL`), so it is left unsaid.\n */\nfunction temporalOf(described: DescribedField): FieldTemporal | undefined {\n const semantic = described.semantic;\n if (semantic?.type === QuerySemanticTypes.TEMPORAL_DATE)\n return { type: 'date' };\n if (\n semantic?.type === QuerySemanticTypes.TEMPORAL_EPOCH &&\n semantic.timeUnit === TimeUnit.SECONDS\n )\n return { type: 'epoch', timeUnit: TimeUnits.SECONDS };\n return undefined;\n}\n\n/** The kind the descriptor says a path is; `null` where it says none. */\nfunction kindOf(\n raw: RawField | undefined,\n described: DescribedField,\n spec: FieldSpec,\n): FieldKindId | null {\n if (spec.elements) return 'elementMatch';\n // A yes-or-no keeps its kind under `options`: there they name its two\n // answers (「新客」「老客」), they do not make it a category.\n if (\n !described.enum &&\n raw?.types?.length === 1 &&\n raw.types[0] === QueryValueTypes.BOOLEAN\n )\n return 'boolean';\n if (described.enum || spec.options) return 'enum';\n const temporal = described.semantic?.type;\n if (temporal === QuerySemanticTypes.TEMPORAL_DATE) return 'date';\n if (\n temporal === QuerySemanticTypes.TEMPORAL_EPOCH ||\n temporal === QuerySemanticTypes.TEMPORAL_FORMATTED\n )\n return 'datetime';\n const types: readonly string[] = raw?.types ?? [];\n if (types.length !== 1) return null;\n switch (types[0]) {\n case QueryValueTypes.BOOLEAN:\n return 'boolean';\n case QueryValueTypes.INTEGER:\n case QueryValueTypes.DECIMAL:\n return 'number';\n case QueryValueTypes.STRING:\n return 'string';\n default:\n return null;\n }\n}\n\n/**\n * The host's word, else the domain's description, else the path — the two\n * fallbacks said, since a reader would see a program's word.\n */\nfunction labelOf(\n spec: FieldSpec,\n raw: RawField | undefined,\n path: string,\n findings: Issue[],\n): string {\n if (spec.label !== undefined) return spec.label;\n findings.push(found('definition.field.unlabelled', { field: path }, 'note'));\n return raw?.description ?? path;\n}\n\n/**\n * The comparisons a path admits: its own operators, and a match over its\n * entries where it is an element the model filters by (capabilities.md,\n * `ELEMENT_MATCH` comes from `elements[]`).\n */\nfunction operatorsOffered(\n descriptor: QueryModelDescriptor,\n described: DescribedField,\n path: string,\n): ReadonlySet<string> {\n const offered = new Set(described.operators);\n if (descriptor.elements.some(entry => entry.path === path && entry.filter))\n offered.add(FilterOperators.ELEMENT_MATCH);\n return offered;\n}\n\n/**\n * A category's values: the host's listed first, in its order and words,\n * then the rest of the descriptor's under their descriptions; one the host\n * hides left out. Where the descriptor lists none the host's list is the\n * whole of it.\n */\nfunction optionsOf(\n spec: FieldSpec,\n described: DescribedField,\n path: string,\n findings: Issue[],\n): FieldOption[] | undefined {\n const listed = listedOptions(spec.options);\n const values = described.enum;\n if (!values)\n return spec.options\n ? listed.flatMap(([value, given]) =>\n given === false ? [] : [option(value, given)],\n )\n : undefined;\n const known = new Map(values.map(entry => [String(entry.value), entry]));\n const said = new Set<string>();\n const options: FieldOption[] = [];\n for (const [value, given] of listed) {\n const key = String(value);\n const entry = known.get(key);\n if (!entry) {\n findings.push(\n found('definition.option.undescribed', { field: path, value: key }),\n );\n continue;\n }\n said.add(key);\n if (given !== false) options.push(option(entry.value, given));\n }\n for (const entry of values)\n if (!said.has(String(entry.value)))\n options.push({\n value: entry.value as FieldOption['value'],\n label: entry.description ?? String(entry.value),\n });\n return options;\n}\n\n/**\n * The host's values in the order written: a list as it is, a record in its\n * own order — which JavaScript puts integer-like keys first in, so a\n * category of numbers is written as a list.\n */\nfunction listedOptions(\n given: FieldSpec['options'],\n): (readonly [unknown, OptionSpec])[] {\n if (!given) return [];\n if (Array.isArray(given)) return given as (readonly [unknown, OptionSpec])[];\n // Own keys only: a value named like a prototype member is a value.\n return Object.keys(given).map(key => [\n key,\n (given as Readonly<Record<string, OptionSpec>>)[key],\n ]);\n}\n\nfunction option(\n value: unknown,\n given: Exclude<OptionSpec, false>,\n): FieldOption {\n return typeof given === 'string'\n ? { value: value as FieldOption['value'], label: given }\n : { value: value as FieldOption['value'], ...given };\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/dsl';\nimport type {\n DataViewDefinition,\n FieldDefinition,\n Issue,\n RecordPagingMode,\n RecordCapability,\n} from '../../model/index.js';\nimport { issue } from '../../filter/index.js';\nimport { analysisPlan, buildAnalysis } from './analysis.js';\nimport { buildFields, type BuiltField } from './fields.js';\nimport { narrowDefinition } from '../../capabilities/index.js';\nimport { constructible } from '../../capabilities/analysis.js';\nimport {\n builtinFieldKinds,\n type FieldKindRegistry,\n} from '../../filter/index.js';\nimport type { DefineViewSpec } from './spec.js';\nimport { PagingModes } from '../../model/index.js';\n\n/**\n * A data definition built from its source's descriptor (host-integration.md\n * 3): the descriptor gives the facts — which paths there are, what\n * each is, what it sorts and feeds — as an upper bound, and `spec` picks,\n * names and narrows within it. A field not listed does not appear. A path\n * or a value the descriptor lacks is an error admission reports\n * (`DataViewDefinition.described`), never a throw: a definition wrong in\n * one place still loads, and says where. A capability asked beyond the\n * snapshot is a warning: what a path sorts and aggregates by is the\n * store's, and another store may grant it.\n *\n * Facts — paths, kinds, values, sensitivity, the entries of an array —\n * are the snapshot's. Capabilities are not baked in: where the host\n * narrows nothing the definition takes whatever its source grants, and\n * where it narrows, its subset of that (`DefinitionDescribed.open`,\n * filled by the narrowing from the source's descriptor). A source with\n * no descriptor runs on the snapshot's.\n *\n * `descriptor` is the snapshot committed beside the definition (Q2): the\n * definition is built at once, when the module loads, and a test builds\n * the same one. The descriptor the source answers at run time narrows it\n * again, as any definition is (N5).\n *\n * The result is an ordinary definition: nothing past this function knows\n * how it was written, and one written in full by hand is still one.\n */\nexport function defineView(\n descriptor: QueryModelDescriptor,\n spec: DefineViewSpec,\n options: DefineViewOptions = {},\n): DataViewDefinition {\n const findings: Issue[] = [];\n const record = recordOf(spec, descriptor, findings);\n const fields = buildFields(spec.fields, undefined, {\n descriptor,\n paging: record?.paging ?? 'paged',\n findings,\n });\n const definition: DataViewDefinition = {\n id: spec.id,\n title: spec.title,\n kind: 'data',\n source: spec.source,\n fields: fields.map(entry => entry.field),\n };\n if (spec.recordNoun !== undefined) definition.recordNoun = spec.recordNoun;\n if (spec.fieldGroups) definition.fieldGroups = spec.fieldGroups;\n if (record) definition.record = record;\n const plan = analysisPlan(spec.analysis, fields);\n const analysis = buildAnalysis(plan, fields, descriptor, findings);\n // A snapshot with no metric at all offers no analyses; a source that\n // grants some fills them in (`reopened`) rather than the definition\n // being refused for one store's word.\n if (analysis && constructible(analysis)) definition.analysis = analysis;\n if (spec.timeField !== undefined) definition.timeField = spec.timeField;\n if (spec.views) definition.views = spec.views;\n // What compares, sorts and aggregates is the store's: left to the source\n // where the host did not narrow it, filled from its descriptor when it\n // narrows (`reopened`), the snapshot's written here for a source that\n // has none.\n const sort = fields.flatMap(({ field, spec: given, described }) =>\n described && given.sortable !== false ? [field.name] : [],\n );\n const operators = openComparisons(fields);\n definition.fields = withSnapshotComparisons(\n definition.fields,\n narrowDefinition(definition, descriptor, options.kinds ?? builtinFieldKinds)\n .definition.fields,\n new Set(operators),\n );\n definition.described = {\n version: descriptor.version,\n findings,\n open: { sort, operators, ...(plan ? { analysis: plan } : {}) },\n };\n return definition;\n}\n\n/**\n * The fields whose comparisons the host left open, by path: every field\n * but one whose operators the host wrote, one that compares nothing (a\n * confidential value), and a search box.\n */\nfunction openComparisons(\n fields: readonly BuiltField[],\n scope?: string,\n): string[] {\n return fields.flatMap(({ field, spec, children }) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n // A search box is the host's to ask for, as written operators are: on\n // a source with no descriptor it is offered as declared, and a source\n // that says whether it searches narrows it.\n const own =\n spec.operators === undefined &&\n field.operators === undefined &&\n field.kind !== 'search'\n ? [path]\n : [];\n return [...own, ...openComparisons(children ?? [], path)];\n });\n}\n\n/**\n * The fields with the snapshot's comparisons written on each one left\n * open: the operators the narrowing against it keeps on each path, so a\n * source with no descriptor offers what the snapshot's store does, and no\n * more.\n */\nfunction withSnapshotComparisons(\n fields: readonly FieldDefinition[],\n narrowed: readonly FieldDefinition[],\n open: ReadonlySet<string>,\n scope?: string,\n): FieldDefinition[] {\n return fields.map((field, index) => {\n const path = scope === undefined ? field.name : `${scope}.${field.name}`;\n const cut = narrowed[index];\n let next = field;\n if (open.has(path) && cut?.operators !== undefined)\n next = { ...next, operators: cut.operators };\n if (field.elements)\n next = {\n ...next,\n elements: withSnapshotComparisons(\n field.elements,\n cut?.elements ?? [],\n open,\n path,\n ),\n };\n return next;\n });\n}\n\n/**\n * What `defineView` needs beyond the snapshot and the host's choices: the\n * field kinds the host registers (`ViewEngineOptions.kinds`) — the snapshot's\n * comparisons are written on a field of a host's own kind only when its\n * kind is known here, since it is built before any engine is. Left out,\n * the built-in kinds.\n */\nexport interface DefineViewOptions {\n kinds?: FieldKindRegistry;\n}\n\n/** The descriptor's paging modes, as a definition names them. */\nconst PAGING: Readonly<Record<string, RecordPagingMode>> = {\n [PagingModes.PAGED]: 'paged',\n [PagingModes.CURSOR]: 'cursor',\n};\n\n/**\n * Records: the host's choices over the descriptor's identity and paging —\n * paged where the model pages, else by cursor — shown as a table unless the\n * host says otherwise. A paging the model does not offer is asked beyond it.\n */\nfunction recordOf(\n spec: DefineViewSpec,\n descriptor: QueryModelDescriptor,\n findings: Issue[],\n): RecordCapability | undefined {\n if (spec.record === false) return undefined;\n const given = spec.record ?? {};\n const offered = descriptor.record.paging.flatMap(mode =>\n PAGING[mode] ? [PAGING[mode]] : [],\n );\n const paging =\n given.paging ?? (offered.includes('paged') ? 'paged' : 'cursor');\n if (!offered.includes(paging))\n findings.push(\n issue(\n 'definition.record.paging-wider',\n ['record', 'paging'],\n { paging },\n 'warning',\n ),\n );\n return {\n ...given,\n rowKey: given.rowKey ?? descriptor.record.identity,\n paging,\n layouts: given.layouts ?? ['table'],\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/dsl';\nimport type { DataViewDefinition } from '../../model/index.js';\nimport { defineView, type DefineViewOptions } from './defineView.js';\nimport type { FieldSpec } from './spec.js';\n\n/** What a host says of a dataset beyond its descriptor. */\nexport interface DefineDatasetSpec {\n id: string;\n /** The key a host resolves the definition's source by. */\n source: string;\n /** The dataset's title, such as the dataset directory's. */\n title: string;\n recordNoun?: string;\n /**\n * The host's words over the derived fields, which only narrow and name\n * (D86): a string is a field's label, a `FieldSpec` narrows it as in\n * **defineView**, `false` hides it. The fields named come first, in the\n * order named; the rest follow in the descriptor's order. A path the\n * descriptor no longer lists is ignored, so an override outlives a\n * column the dataset dropped.\n */\n fields?: Readonly<Record<string, FieldSpec | string | false>>;\n}\n\n/**\n * A dataset's definition, derived from its descriptor (host-integration.md\n * 3.2): a dataset is published at run time, so its definition is not\n * code. Every field of the record the descriptor lists appears, in the\n * descriptor's order — a dataset's declaration already chose them, as a\n * column it does not declare is never exposed — labelled by its\n * description, else its path. The rest is **defineView**'s: sensitive\n * fields stay out of analyses, capabilities follow the descriptor in force,\n * and the row key is the descriptor's identity.\n *\n * The result is an ordinary definition, judged as any other when an engine\n * registers it (`ViewEngine.register`).\n */\nexport function defineDataset(\n descriptor: QueryModelDescriptor,\n spec: DefineDatasetSpec,\n options: DefineViewOptions = {},\n): DataViewDefinition {\n const derived = new Map<string, string>();\n for (const field of descriptor.fields)\n if (field.scope === undefined)\n derived.set(field.path, field.description ?? field.path);\n const fields: Record<string, FieldSpec | string> = {};\n for (const [path, override] of Object.entries(spec.fields ?? {})) {\n const label = derived.get(path);\n if (label === undefined) continue;\n derived.delete(path);\n if (override === false) continue;\n fields[path] =\n typeof override === 'string'\n ? override\n : { ...override, label: override.label ?? label };\n }\n for (const [path, label] of derived) fields[path] = label;\n return defineView(\n descriptor,\n {\n id: spec.id,\n source: spec.source,\n title: spec.title,\n ...(spec.recordNoun === undefined ? {} : { recordNoun: spec.recordNoun }),\n fields,\n },\n options,\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 defineDataset,\n type DefineDatasetSpec,\n} from './define/defineDataset.js';\nimport type { ReadOptions, WriteOptions } from '../store/ViewStore.js';\nimport type { ViewDefinition } from '../model/index.js';\nimport type { ViewSource } from './source.js';\nimport type { ViewResource } from './viewEngineOptions.js';\n\n/**\n * One dataset of a service's directory, named as wow-client's `DatasetEntry`\n * names it: the bounded context it lives in, its name there, and its title.\n * A directory lists only what it serves. `version` is the directory's own\n * version of the dataset where it keeps one; a refresh registers the\n * dataset again when it moves. Without one, a changed dataset is told by\n * its descriptor's version, which the engine checks on its own schedule.\n */\nexport interface DatasetDirectoryEntry {\n context: string;\n dataset: string;\n title?: string;\n version?: string;\n}\n\n/** What `DatasetResources` reads: the dataset directory, and each dataset's source. */\nexport interface DatasetCatalog {\n /** The datasets the service serves (`GET /wow/dataset`). */\n list(options?: ReadOptions): Promise<readonly DatasetDirectoryEntry[]>;\n /** The source of one, such as wow-client's `DatasetQueryClient`; it must describe itself. */\n source(entry: DatasetDirectoryEntry): ViewSource;\n /**\n * The host's words over one dataset (D86): its title, its noun, and its\n * fields' labels, order and narrowing (`DefineDatasetSpec.fields`).\n */\n overrides?(entry: DatasetDirectoryEntry): DatasetOverrides | undefined;\n /**\n * Where a tenant's administrators keep their wording over the datasets\n * (D91), such as wow-view-store's `WowDatasetWordings`: read whole before\n * each `refresh` registers, by definition id. A dataset's stored wording\n * stands in place of `overrides`. Given, each dataset registers with an\n * editor of its wording (`DatasetWordingEditor`).\n */\n wordings?: DatasetWordingStore;\n}\n\n/** A dataset's wording as stored, and the revision a write expects. */\nexport interface StoredDatasetWording {\n wording: DatasetOverrides;\n /** `'0'` for wording never written. */\n revision: string;\n}\n\n/** Where a dataset's wording is kept; see `DatasetCatalog.wordings`. */\nexport interface DatasetWordingStore {\n /** Every dataset's stored wording, by definition id (`{context}.{dataset}`). */\n list(\n options?: ReadOptions,\n ): Promise<ReadonlyMap<string, StoredDatasetWording>>;\n /** Writes one whole at the expected revision; answers the new revision. */\n set(\n dataset: string,\n wording: DatasetOverrides,\n revision: string,\n context: WriteOptions,\n ): Promise<string>;\n}\n\n/**\n * What a dataset's wording editor reads and writes: the fields the\n * descriptor derives, the wording in force, and a save that stores it and\n * registers the dataset again in the new words.\n */\nexport interface DatasetWordingEditor {\n /** The definition id, and the dataset's key in the store. */\n readonly dataset: string;\n /** The title the directory gives, before any wording. */\n readonly derivedTitle: string;\n /** The descriptor's fields in its order, labelled as derived before any wording. */\n readonly fields: readonly { name: string; label: string }[];\n /** The wording in force: the stored one, else the host's `overrides`. */\n readonly wording: DatasetOverrides;\n /** The revision a save expects. */\n readonly revision: string;\n /** Stores `wording` whole and registers the dataset again in it. */\n save(wording: DatasetOverrides, context: WriteOptions): Promise<void>;\n}\n\n/** What a host may say over a dataset's derived definition; see `DatasetCatalog.overrides`. */\nexport type DatasetOverrides = Partial<\n Pick<DefineDatasetSpec, 'title' | 'recordNoun' | 'fields'>\n>;\n\n/** The part of an engine `DatasetResources` drives (`ViewEngine` is one). */\nexport interface DatasetRegistrar {\n readonly definitions: ReadonlyMap<string, ViewDefinition>;\n register(resource: ViewResource): void;\n unregister(definitionId: string): boolean;\n}\n\n/** A dataset served, as registered: its directory entry and its definition id. */\nexport interface DatasetResource {\n id: string;\n entry: DatasetDirectoryEntry;\n /**\n * Which of the catalogs serves it, by its place in the list\n * `DatasetResources` was given (0 for one catalog).\n */\n catalog: number;\n}\n\n/**\n * A dataset a catalog listed under an id an earlier catalog serves:\n * left out, the earlier one's kept.\n */\nexport interface DatasetDuplicate {\n /** The definition id both name, `{context}.{dataset}`. */\n id: string;\n /** The entry left out, of the catalog at `dropped`. */\n entry: DatasetDirectoryEntry;\n dropped: number;\n /** The catalog whose dataset of that id is served. */\n kept: number;\n}\n\n/** What one `DatasetResources.refresh` found. */\nexport interface DatasetRefresh {\n /** The datasets served, in the directories' order. */\n datasets: readonly DatasetResource[];\n /** The datasets it left out because an earlier catalog serves their id. */\n duplicates: readonly DatasetDuplicate[];\n}\n\n/**\n * What `DatasetResources` reads and whom it tells: the catalogs, and the\n * callbacks for what it cannot serve. Every callback is optional; one left\n * out hears nothing, and the refresh goes on as it would.\n */\nexport interface DatasetResourcesInit {\n /** One service's directory, or several, the first winning a dataset two list. */\n catalogs: DatasetCatalog | readonly DatasetCatalog[];\n /** Told of a dataset that could not be described or registered; it is left as it was. */\n onError?(entry: DatasetDirectoryEntry, error: unknown): void;\n /** Told when the stored wording cannot be read; the wording read last stands. */\n onWordingError?(error: unknown): void;\n /** Told of each duplicate a refresh leaves out (`DatasetRefresh.duplicates`). */\n onDuplicate?(duplicate: DatasetDuplicate): void;\n /**\n * Told when the catalog at `catalog` cannot list its datasets: the ones it\n * served stay as they were, and the refresh goes on with the others. Only\n * when no catalog can list does the refresh fail.\n */\n onCatalogError?(catalog: number, error: unknown): void;\n}\n\n/** One catalog's dataset as a refresh finds it. */\ninterface Listed {\n entry: DatasetDirectoryEntry;\n catalog: number;\n}\n\n/**\n * Keeps an engine's datasets in step with services' directories: each\n * `refresh` registers a dataset a directory newly lists, registers again\n * one whose version changed, and removes one no directory lists any more.\n * A dataset's\n * definition id is its name, `{context}.{dataset}`, and its title the\n * directory's; a definition the host registered in code under that id wins\n * and the dataset is left out.\n *\n * Given several catalogs — several services' directories, such as the\n * analytics catalog's and a service that serves datasets of its own — it\n * serves them in one engine (D238 ⑨): a dataset two catalogs list is the\n * first one's, and the other is reported (`DatasetRefresh.duplicates`,\n * `onDuplicate`), never dropped silently. A catalog that cannot be read\n * keeps what it served and is reported (`onCatalogError`).\n *\n * `refresh` answers the datasets served and the duplicates it left out\n * (`DatasetRefresh`); a host binds routes to the datasets (`bind`,\n * `datasetBindings`) so they appear in its navigation: opening one is how a\n * reader starts a view of it.\n */\nexport class DatasetResources {\n private readonly catalogs: readonly DatasetCatalog[];\n private readonly held = new Map<string, DatasetResource>();\n /** The overrides each dataset was registered with, as JSON: new words register it again. */\n private readonly worded = new Map<string, string>();\n /** The wording each catalog's store held when it was last read (`DatasetCatalog.wordings`). */\n private stored: ReadonlyMap<\n number,\n ReadonlyMap<string, StoredDatasetWording>\n > = new Map();\n /** What each dataset was registered from, so a new wording needs no describe. */\n private readonly derived = new Map<\n string,\n {\n entry: DatasetDirectoryEntry;\n catalog: number;\n source: ViewSource;\n descriptor: Parameters<typeof defineDataset>[0];\n }\n >();\n private readonly options: DatasetResourcesInit;\n\n constructor(\n private readonly engine: DatasetRegistrar,\n init: DatasetResourcesInit,\n ) {\n this.options = init;\n const { catalogs } = init;\n this.catalogs = Array.isArray(catalogs)\n ? (catalogs as readonly DatasetCatalog[])\n : [catalogs as DatasetCatalog];\n if (this.catalogs.length === 0)\n throw new Error('DatasetResources reads at least one catalog.');\n }\n\n /** The datasets served, in the directories' order. */\n get resources(): readonly DatasetResource[] {\n return [...this.held.values()];\n }\n\n /**\n * Reads every catalog and brings the engine in step with what they list;\n * answers the datasets served and the ones left out as duplicates.\n */\n async refresh(options: ReadOptions = {}): Promise<DatasetRefresh> {\n await this.readWordings(options);\n const lists = await Promise.allSettled(\n this.catalogs.map(catalog => catalog.list(options)),\n );\n options.signal?.throwIfAborted();\n if (lists.every(list => list.status === 'rejected')) throw lists[0].reason;\n const servable = new Map<string, Listed>();\n const duplicates: DatasetDuplicate[] = [];\n const unread = new Set<number>();\n lists.forEach((list, catalog) => {\n if (list.status === 'rejected') {\n unread.add(catalog);\n this.options.onCatalogError?.(catalog, list.reason);\n return;\n }\n for (const entry of list.value) {\n const id = `${entry.context}.${entry.dataset}`;\n const kept = servable.get(id);\n if (kept) {\n duplicates.push({ id, entry, dropped: catalog, kept: kept.catalog });\n continue;\n }\n servable.set(id, { entry, catalog });\n }\n });\n // A catalog that could not be read keeps what it served, unless a catalog\n // read now serves the id.\n for (const [id, held] of this.held)\n if (unread.has(held.catalog) && !servable.has(id))\n servable.set(id, { entry: held.entry, catalog: held.catalog });\n for (const duplicate of duplicates) this.options.onDuplicate?.(duplicate);\n for (const id of [...this.held.keys()])\n if (!servable.has(id)) {\n this.engine.unregister(id);\n this.held.delete(id);\n this.worded.delete(id);\n this.derived.delete(id);\n }\n await Promise.all(\n [...servable].map(([id, listed]) => this.serve(id, listed, options)),\n );\n const order = [...servable.keys()];\n const datasets = [...this.held.values()].sort(\n (a, b) => order.indexOf(a.id) - order.indexOf(b.id),\n );\n return { datasets, duplicates };\n }\n\n /**\n * Reads the stored wording before a refresh registers; one that cannot be\n * read leaves what was read last, and is told for no dataset in particular.\n */\n private async readWordings(options: ReadOptions): Promise<void> {\n const read = new Map(this.stored);\n await Promise.all(\n this.catalogs.map(async (catalog, index) => {\n const store = catalog.wordings;\n if (!store) return;\n try {\n read.set(index, await store.list(options));\n } catch (error) {\n this.options.onWordingError?.(error);\n }\n }),\n );\n this.stored = read;\n }\n\n /** The wording a dataset registers in: its catalog's stored one, else the host's. */\n private wordingOf(id: string, listed: Listed): StoredDatasetWording {\n return (\n this.stored.get(listed.catalog)?.get(id) ?? {\n wording: this.catalogs[listed.catalog].overrides?.(listed.entry) ?? {},\n revision: '0',\n }\n );\n }\n\n private async serve(\n id: string,\n listed: Listed,\n options: ReadOptions,\n ): Promise<void> {\n const { entry, catalog } = listed;\n const held = this.held.get(id);\n const { wording } = this.wordingOf(id, listed);\n const words = JSON.stringify(wording);\n if (\n held?.catalog === catalog &&\n held.entry.version === entry.version &&\n this.worded.get(id) === words\n )\n return;\n if (!held && this.engine.definitions.has(id)) return;\n try {\n const source = this.catalogs[catalog].source(entry);\n const described = await source.describe?.(undefined, options);\n if (!described || described.notModified)\n throw new Error(`Dataset [${id}] does not describe itself.`);\n this.derived.set(id, {\n entry,\n catalog,\n source,\n descriptor: described.descriptor,\n });\n this.registerWorded(id);\n } catch (error) {\n this.options.onError?.(entry, error);\n }\n }\n\n /** Registers dataset `id` from what it was derived from, in the wording in force. */\n private registerWorded(id: string): void {\n const derived = this.derived.get(id);\n if (!derived) return;\n const { entry, catalog, source, descriptor } = derived;\n const current = this.wordingOf(id, { entry, catalog });\n const title = entry.title ?? entry.dataset;\n const definition = defineDataset(descriptor, {\n id,\n source: id,\n title,\n ...current.wording,\n });\n this.engine.register({\n definition,\n source,\n ...(this.catalogs[catalog].wordings\n ? { wording: this.editorOf(id, catalog, title, descriptor, current) }\n : {}),\n });\n this.held.set(id, { id, entry, catalog });\n this.worded.set(id, JSON.stringify(current.wording));\n }\n\n private editorOf(\n id: string,\n catalog: number,\n derivedTitle: string,\n descriptor: Parameters<typeof defineDataset>[0],\n current: StoredDatasetWording,\n ): DatasetWordingEditor {\n const plain = defineDataset(descriptor, {\n id,\n source: id,\n title: derivedTitle,\n });\n return {\n dataset: id,\n derivedTitle,\n fields: plain.fields.map(({ name, label }) => ({ name, label })),\n wording: current.wording,\n revision: current.revision,\n save: async (wording, context) => {\n const store = this.catalogs[catalog].wordings;\n if (!store) return;\n const revision = await store.set(\n id,\n wording,\n current.revision,\n context,\n );\n const stored = new Map(this.stored);\n stored.set(\n catalog,\n new Map(this.stored.get(catalog)).set(id, { wording, revision }),\n );\n this.stored = stored;\n this.registerWorded(id);\n },\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 { ViewInstance } from '../model/index.js';\nimport type { MemorySnapshot, MemoryState } from './MemoryViewStore.js';\n\n/**\n * Where a `localStorageSnapshot` reads and writes. Both are structural, so\n * this layer names no DOM type, and a test hands in a storage of its own.\n */\nexport interface LocalStorageSnapshotOptions {\n /**\n * The storage, asked for at each read and write rather than once, so a\n * browser that refuses it (private mode, blocked site data) is a refused\n * read or write rather than a failure to make the store. Defaults to\n * `globalThis.localStorage`.\n */\n storage?: () => {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n };\n /**\n * Where another tab's change is announced as a `storage` event. Defaults to\n * `globalThis` — the window — when it has `addEventListener`; `null` listens\n * nowhere, and a write still re-reads what is stored first.\n */\n events?: {\n addEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n removeEventListener(\n type: 'storage',\n listener: (event: { key: string | null; storageArea?: unknown }) => void,\n ): void;\n } | null;\n}\n\ntype KeptStorage = ReturnType<\n NonNullable<LocalStorageSnapshotOptions['storage']>\n>;\n\n/**\n * A `MemoryViewStore` snapshot kept in `localStorage` under `key`: the whole\n * store as one JSON document, `{ instances, preferences }`. For development\n * and single-user hosts until a real backend holds the views (phase 6); it\n * is one browser's, not a second store.\n *\n * Two things a browser does to such a document are the store's to answer,\n * and this is the design (decided 2026-09-28):\n *\n * - **A write storage refuses is a failed write.** `save` throws what\n * `setItem` threw (a full quota, blocked storage), and the store undoes the\n * write and rejects it as `UNAVAILABLE` — which the engine reports to the\n * environment's `onError` as a `store` failure and the UI shows as a save\n * whose outcome needs a retry, the error marked `storage` so the line\n * says the browser's storage is full or turned off rather than that the\n * result never came back. It never pretends a view was kept.\n * - **Tabs do not overwrite each other.** The stamps are the revisions the\n * stored state already carries, one per instance and one per definition's\n * preferences. The store re-reads this document before every write and\n * checks the write's revision against it, so a write merges instance by\n * instance into what another tab stored, and one based on a revision that\n * tab has moved past is a `CONFLICT`, the same flow a stale write in one\n * tab already takes. A `storage` event for `key` reloads the store, so\n * what another tab saved is listed without waiting for a write.\n *\n * A missing, unreadable or malformed document reads as nothing stored — the\n * store starts empty rather than the page breaking — and the next write\n * replaces it. The format is `{ instances, preferences }`.\n */\nexport function localStorageSnapshot(\n key: string,\n options: LocalStorageSnapshotOptions = {},\n): MemorySnapshot {\n const storage = options.storage ?? ambientStorage;\n const events =\n options.events === undefined ? ambientEvents() : options.events;\n return {\n load() {\n try {\n return parseState(storage().getItem(key));\n } catch {\n return undefined;\n }\n },\n save(state) {\n storage().setItem(key, JSON.stringify(state));\n },\n subscribe(listener) {\n if (!events) return () => {};\n const onStorage = (event: {\n key: string | null;\n storageArea?: unknown;\n }) => {\n // `null` is a `clear()`; another area (sessionStorage) is not ours.\n if (event.key !== null && event.key !== key) return;\n if (event.storageArea && event.storageArea !== readable(storage))\n return;\n listener();\n };\n events.addEventListener('storage', onStorage);\n return () => events.removeEventListener('storage', onStorage);\n },\n };\n}\n\nfunction ambientStorage(): KeptStorage {\n const storage = (globalThis as { localStorage?: KeptStorage }).localStorage;\n if (!storage) throw new Error('localStorage is not available');\n return storage;\n}\n\nfunction ambientEvents(): LocalStorageSnapshotOptions['events'] {\n const target = globalThis as Partial<\n NonNullable<LocalStorageSnapshotOptions['events']>\n >;\n return typeof target.addEventListener === 'function'\n ? (target as NonNullable<LocalStorageSnapshotOptions['events']>)\n : null;\n}\n\nfunction readable(storage: () => KeptStorage): KeptStorage | undefined {\n try {\n return storage();\n } catch {\n return undefined;\n }\n}\n\n/**\n * The stored document, or `undefined` when it is not one. Only its outline\n * is checked here — an instance needs an id to be held by it; each config is\n * checked, and migrated, where every view out of a store is read.\n */\nfunction parseState(saved: string | null): MemoryState | undefined {\n if (!saved) return undefined;\n const state = JSON.parse(saved) as Partial<MemoryState> | null;\n if (\n !state ||\n typeof state !== 'object' ||\n !Array.isArray(state.instances) ||\n typeof state.preferences !== 'object' ||\n state.preferences === null ||\n Array.isArray(state.preferences)\n )\n return undefined;\n return {\n instances: state.instances.filter(isHeld),\n preferences: state.preferences,\n };\n}\n\nfunction isHeld(instance: unknown): instance is ViewInstance {\n return (\n typeof instance === 'object' &&\n instance !== null &&\n typeof (instance as { id?: unknown }).id === 'string'\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 ViewAudience,\n ViewConfig,\n ViewInstance,\n ViewInstanceSummary,\n ViewPreferences,\n} from '../model/index.js';\n\n/**\n * The only port a backend must satisfy. Its failure type is `ViewStoreError`\n * from `model`, so both sides of the port speak it.\n *\n * Eight methods, and two a store may leave out (`changeAudience`, and\n * `permissions`, whose absence allows everything but `editSystem`); two\n * consistency rules: a write carries the revision it expects, and a retry\n * reuses its `requestId` so the server can recognise the same intent.\n *\n * Authorization, visibility filtering and deduplication belong to the server.\n * `permissions` only drives which buttons a UI enables.\n */\nexport interface ViewStore {\n /**\n * The definition's views this user sees, as summaries, **in a fixed\n * order**: the backend's system views first, as it declares them, then\n * the shared views, then the user's personal ones, each audience oldest\n * first (the order they were created in; a view moved to the other\n * audience keeps its place by age there). With no preferences, the first\n * of the list is the view that opens by default (`resolveDefault`), so\n * every store answers the same one.\n *\n * A page at a time: the first without a `cursor`, each next one with the\n * `nextCursor` the page before answered, until that is `null`. The order\n * holds across pages. A store chooses its own page size; the engine reads\n * pages in turn until the end or `RuntimeLimits.listedViews`.\n */\n list(definitionId: string, options?: ViewListOptions): Promise<ViewListPage>;\n get(id: string, options?: ReadOptions): Promise<ViewInstance>;\n /**\n * Creates a view for the scope `input` names. `scope: 'system'` creates a\n * **stored system view** (D81) — what 「发布为系统视图」 and 另存为 send\n * when the host grants `editSystem` — and answers it with `stored: true`;\n * a store that keeps no system views refuses it (`FORBIDDEN` or\n * `INVALID`). Publishing is a copy: the view it was made from is not\n * touched. The engine never sends `stored` itself; the store sets it.\n */\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n options: WriteOptions,\n ): Promise<ViewInstance>;\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n options: WriteOptions,\n ): Promise<ViewInstance>;\n /**\n * Stores the title trimmed. A title blank once trimmed, or longer than\n * `MAX_VIEW_TITLE_LENGTH`, is refused as `INVALID` — so is one passed to\n * `create`, and a config of more than `MAX_VIEW_CONFIG_BYTES` passed to\n * `create` or `save`. The engine refuses both before sending; the store\n * keeps them for every other caller.\n */\n rename(\n id: string,\n title: string,\n revision: string,\n options: WriteOptions,\n ): Promise<ViewInstance>;\n delete(id: string, revision: string, options: WriteOptions): Promise<void>;\n getPreferences(\n definitionId: string,\n options?: ReadOptions,\n ): Promise<ViewPreferences>;\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n options: WriteOptions,\n ): Promise<ViewPreferences>;\n /**\n * Moves a view to the other audience in place (设为共享/设为个人, D18\n * item 10): the id stays, so a board that shows it keeps showing it.\n *\n * Optional: a store without it has no such entry in the manager, and the\n * engine refuses the command before anything is sent\n * (`view.changeAudience.unsupported`). One that has it keeps the rules of\n * every other instance write — the expected `revision` (`CONFLICT`\n * carrying `instance`), a replayed `requestId` answering the first\n * outcome, a system view refused (`FORBIDDEN`) — a stored one too: a\n * system view never moves audience — a missing one\n * `NOT_FOUND` — and two of its own:\n *\n * - **No change is no write.** Asked for the audience the view already\n * has, it answers the view as it is, revision unmoved (after the\n * revision check, so a stale one still conflicts).\n * - **A view a shared board shows stays shared.** Made personal, it would\n * be blank on that board for every other reader, so the store refuses\n * it as `INVALID` with **`boards`, those boards' titles** as stored (a\n * title written as a key stays one): the engine says the refusal in\n * its own words around them (`view.changeAudience.invalid.shared-boards`),\n * so an adapter whose server answers with ids reads the titles. Only the\n * store sees every board.\n * Deleting such a view stays allowed (the panel alone breaks).\n */\n changeAudience?(\n id: string,\n audience: ViewAudience,\n revision: string,\n options: WriteOptions,\n ): Promise<ViewInstance>;\n /** Synchronous, because the application fetched it before creating the engine. */\n permissions?(definitionId: string): ViewPermissions;\n}\n\n/** What every read of a store takes: the signal that cancels it. */\nexport interface ReadOptions {\n readonly signal?: AbortSignal;\n}\n\n/** One page of `ViewStore.list` to read. */\nexport interface ViewListOptions extends ReadOptions {\n /** The `nextCursor` of the page before; absent or `null` for the first. */\n readonly cursor?: string | null;\n}\n\n/** One page of a definition's views, in the port's order. */\nexport interface ViewListPage {\n items: ViewInstanceSummary[];\n /** The cursor of the next page, or `null` after the last. */\n nextCursor: string | null;\n}\n\n/**\n * One logical write. A retry after a timeout reuses the same `requestId` and\n * the same payload, which is what lets a server deduplicate it.\n */\nexport interface WriteOptions extends ReadOptions {\n readonly requestId: string;\n}\n\n/** What the current user may do with one definition's views. */\nexport interface ViewPermissions {\n createPersonal: boolean;\n createShared: boolean;\n reorder: boolean;\n setDefault: boolean;\n /**\n * Whether this user edits the definition's **stored** system views\n * (`stored: true`) and creates new ones (`create({ scope: 'system' })`,\n * 「发布为系统视图」), D81. **Absent is false** — unlike everything else\n * here, where silence allows: a system view reaches every user, so only a\n * host that says so opens it, and a store without `permissions` does not.\n * When true, the `instance(id)` answer below applies to a stored system\n * view (save, rename, delete); a system view never moves audience, and\n * one declared in code or in the backend's configuration stays read-only.\n */\n editSystem?: boolean;\n /**\n * Whether this user edits the wording of the definition's dataset — its\n * title, record noun and field labels, order and hiding — in the view\n * manager (D91), where the dataset was registered with a store of wording.\n * **Absent is false**, as `editSystem`: the wording reaches every reader\n * of the tenant.\n */\n editDatasetWording?: boolean;\n instance(id: string): InstancePermissions;\n}\n\nexport interface InstancePermissions {\n save: boolean;\n rename: boolean;\n delete: boolean;\n /**\n * Whether the view may be moved to the other audience. Absent reads as\n * allowed — silence is not a refusal, as with the rest — and moving it\n * also asks the create permission of the audience it goes to\n * (`createShared` to share it, `createPersonal` to take it back).\n */\n changeAudience?: boolean;\n}\n\n/** An empty preference record, which is what an untouched definition has. */\nexport function emptyPreferences(): ViewPreferences {\n return { order: [], defaultInstanceId: null, revision: '0' };\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 configBytes,\n isSystemInstanceId,\n isSystemScope,\n MAX_VIEW_CONFIG_BYTES,\n MAX_VIEW_TITLE_LENGTH,\n titleProblem,\n toSummary,\n ViewStoreError,\n type ViewAudience,\n type ViewConfig,\n type ViewInstance,\n type ViewPreferences,\n} from '../model/index.js';\nimport {\n type ViewListOptions,\n type ViewListPage,\n type ViewPermissions,\n type ViewStore,\n type WriteOptions,\n emptyPreferences,\n} from './ViewStore.js';\n\n/** The views one page of `MemoryViewStore.list` answers by default. */\nconst DEFAULT_PAGE_SIZE = 100;\n\nexport interface MemoryViewStoreOptions {\n instances?: ViewInstance[];\n preferences?: Record<string, ViewPreferences>;\n permissions?: (definitionId: string) => ViewPermissions;\n /** Lets an example keep its data across reloads; not a second store. */\n snapshot?: MemorySnapshot;\n /**\n * The views one page of `list` answers; 100 when left out. A test sets it\n * low to read a list across pages, as a server's own page size makes it.\n */\n pageSize?: number;\n}\n\n/**\n * Where a `MemoryViewStore` keeps its state between page loads: the whole\n * state, read and written as one document, synchronously.\n *\n * The store reads it when it is made, again before every write, and again\n * whenever `subscribe` says another writer changed it, so every write is\n * checked against what is stored now rather than what this store last saw\n * (see `MemoryViewStore`). `load` answers `undefined` for nothing readable,\n * and the store then keeps what it holds.\n *\n * `save` throws when the state could not be kept — storage full, blocked,\n * refused. The store then undoes the write in memory and rejects it with a\n * `ViewStoreError` (`UNAVAILABLE`), so nobody is told a view was saved that\n * the next page load will not have.\n */\nexport interface MemorySnapshot {\n load(): MemoryState | undefined;\n save(state: MemoryState): void;\n /** Tells the store that another writer changed the state; answers the unsubscribe. */\n subscribe?(listener: () => void): () => void;\n}\n\nexport interface MemoryState {\n instances: ViewInstance[];\n preferences: Record<string, ViewPreferences>;\n}\n\n/**\n * The one implementation this package ships: a synchronous map behind the\n * port, for tests, examples and query-only use.\n *\n * It keeps the two consistency rules honest rather than convenient. A write\n * with a stale revision conflicts, and a replayed `requestId` returns the\n * first outcome instead of writing twice, so code written against it behaves\n * the same against a real backend — as do the port's list order and the\n * server's limits on a title and a config, which it refuses as the server\n * does (`INVALID`).\n *\n * System views come two ways (D81). One seeded with `scope: 'system'` and\n * no `stored` is a configured one, as the backend's configuration serves\n * it: every write to it is refused (`FORBIDDEN`). One created with\n * `scope: 'system'` — 「发布为系统视图」 — or seeded with `stored: true` is\n * a stored one: saved, renamed and deleted like a shared view, never moved\n * to another audience (`FORBIDDEN`). Like the server, the store asks no\n * permission of its own; `editSystem` is the host's to grant and the\n * engine's to ask.\n *\n * With a snapshot, several stores may share one stored state — two tabs over\n * one `localStorage`. The rule between them is the backend's: **re-read, then\n * compare revisions, one instance (or one definition's preferences) at a\n * time.** Before every write the store reloads the stored state, so a write\n * merges into what the other writer left — a board created in one tab\n * survives a reorder in the other, and ids never collide — and a write whose\n * `revision` the other writer has already moved past is refused as\n * `CONFLICT`, carrying what is stored, as any stale write is. Nothing is ever\n * overwritten because this store's copy was old. A write the snapshot could\n * not keep is undone and rejected as `UNAVAILABLE`: it did not land, so a\n * retry under the same `requestId` is safe.\n */\nexport class MemoryViewStore implements ViewStore {\n private readonly instances = new Map<string, ViewInstance>();\n private readonly preferences = new Map<string, ViewPreferences>();\n /** Outcome per logical instance write, so a retry is idempotent. */\n private readonly outcomes = new Map<string, ViewInstance | null>();\n /** The same rule for preferences, whose outcome is no instance. */\n private readonly preferenceOutcomes = new Map<string, ViewPreferences>();\n private readonly snapshot?: MemorySnapshot;\n readonly permissions?: (definitionId: string) => ViewPermissions;\n /** See `MemoryViewStoreOptions.pageSize`. */\n private readonly pageSize: number;\n private sequence = 0;\n\n constructor(options: MemoryViewStoreOptions = {}) {\n // Left undefined when the caller declared none, which the port reads as\n // \"everything is allowed\".\n if (options.permissions) this.permissions = options.permissions;\n this.pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;\n this.snapshot = options.snapshot;\n\n const restored = options.snapshot?.load();\n this.restore({\n instances: restored?.instances ?? options.instances ?? [],\n preferences: restored?.preferences ?? options.preferences ?? {},\n });\n options.snapshot?.subscribe?.(() => this.reload());\n }\n\n /**\n * In the port's order: system, shared, personal, each oldest first. The\n * map keeps insertion order — the order views were created or seeded in,\n * which a change of audience does not move — and the sort is stable. A\n * page is `pageSize` of them; the cursor is where the next page starts.\n */\n list(\n definitionId: string,\n options: ViewListOptions = {},\n ): Promise<ViewListPage> {\n const summaries = [...this.instances.values()]\n .filter(instance => instance.definitionId === definitionId)\n .map(toSummary)\n .sort((a, b) => AUDIENCE_RANK[a.scope] - AUDIENCE_RANK[b.scope]);\n const start = options.cursor ? Number(options.cursor) : 0;\n const end = start + this.pageSize;\n return Promise.resolve({\n items: summaries.slice(start, end),\n nextCursor: end < summaries.length ? String(end) : null,\n });\n }\n\n get(id: string): Promise<ViewInstance> {\n const instance = this.instances.get(id);\n return instance\n ? Promise.resolve(copy(instance))\n : Promise.reject(new ViewStoreError('NOT_FOUND', `No such view: ${id}`));\n }\n\n create(\n input: Omit<ViewInstance, 'id' | 'revision'>,\n context: WriteOptions,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n const refused = titleRefusal(input.title) ?? configRefusal(input.config);\n if (refused) return Promise.reject(refused);\n this.reload();\n\n // Seeded instances occupy ids too, so the counter walks past anything\n // already taken rather than overwriting it.\n let id: string;\n do {\n this.sequence += 1;\n id = `${input.definitionId}-${this.sequence}`;\n } while (this.instances.has(id));\n if (isSystemInstanceId(id))\n return Promise.reject(\n new ViewStoreError('INVALID', `Reserved id namespace: ${id}`),\n );\n\n // `stored` is the store's to say, never the caller's: a system view\n // created here is one it keeps, and nothing else is one.\n const given = copy(input);\n delete given.stored;\n const instance: ViewInstance = {\n ...given,\n title: input.title.trim(),\n id,\n revision: '1',\n ...(isSystemScope(input.scope) ? { stored: true as const } : {}),\n };\n this.instances.set(id, instance);\n return this.commit(context, instance, () => this.instances.delete(id));\n }\n\n save(\n id: string,\n config: ViewConfig,\n revision: string,\n context: WriteOptions,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, config: copy(config) }),\n configRefusal(config),\n );\n }\n\n rename(\n id: string,\n title: string,\n revision: string,\n context: WriteOptions,\n ): Promise<ViewInstance> {\n return this.update(\n id,\n revision,\n context,\n current => ({ ...current, title: title.trim() }),\n titleRefusal(title),\n );\n }\n\n /**\n * The port's in-place audience change: personal and shared swap, the id\n * and everything else stay. Asked for the audience the view already has,\n * it answers the view unchanged — no revision spent, nothing written — and\n * remembers that answer under the `requestId` like any other outcome.\n * A view a shared (or system) board shows is refused as `INVALID` when it\n * would become personal, `boards` naming those boards by title. A system\n * view, stored or not, never moves (`FORBIDDEN`).\n */\n changeAudience(\n id: string,\n audience: ViewAudience,\n revision: string,\n context: WriteOptions,\n ): Promise<ViewInstance> {\n return this.update(id, revision, context, current => {\n if (isSystemScope(current.scope))\n return new ViewStoreError('FORBIDDEN', 'System views stay system');\n if (audienceOf(current.scope) === audience) return null;\n if (audience === 'personal') {\n const boards = this.sharedBoardsShowing(id);\n if (boards.length > 0)\n return new ViewStoreError(\n 'INVALID',\n `Shared dashboards show view ${id}: ${boards.join(', ')}`,\n { boards },\n );\n }\n return { ...current, scope: audience };\n });\n }\n\n delete(id: string, revision: string, context: WriteOptions): Promise<void> {\n if (this.outcomes.has(context.requestId)) return Promise.resolve();\n this.reload();\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n // Deleting a configured system view is refused exactly as overwriting\n // one is: it is declared in code or by operations, and no user write\n // reaches it. A stored one is deleted like a shared view (unpublished).\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n this.instances.delete(id);\n const refused = this.persist(() => this.instances.set(id, current));\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, null);\n return Promise.resolve();\n }\n\n getPreferences(definitionId: string): Promise<ViewPreferences> {\n return Promise.resolve(\n this.preferences.get(definitionId) ?? emptyPreferences(),\n );\n }\n\n setPreferences(\n definitionId: string,\n preferences: ViewPreferences,\n context: WriteOptions,\n ): Promise<ViewPreferences> {\n // A replay answers with the outcome the first attempt produced, as every\n // other write does: a retry after a lost answer is the same logical\n // write, and reporting a conflict for it would be a lie.\n const replayed = this.preferenceOutcomes.get(context.requestId);\n if (replayed) return Promise.resolve(replayed);\n this.reload();\n\n const held = this.preferences.get(definitionId);\n const current = held ?? emptyPreferences();\n if (current.revision !== preferences.revision)\n return Promise.reject(\n new ViewStoreError(\n 'CONFLICT',\n `Preferences for ${definitionId} changed`,\n { preferences: current },\n ),\n );\n\n const next: ViewPreferences = {\n ...preferences,\n revision: nextRevision(current.revision),\n };\n this.preferences.set(definitionId, next);\n const refused = this.persist(() =>\n held\n ? this.preferences.set(definitionId, held)\n : this.preferences.delete(definitionId),\n );\n if (refused) return Promise.reject(refused);\n this.preferenceOutcomes.set(context.requestId, next);\n return Promise.resolve(next);\n }\n\n /**\n * One instance write: replay, the refusal of its input (`refused`, as the\n * server validates a command before it reaches the view), re-read, the\n * three refusals every instance write shares, then `change`. It may answer\n * `null` for a write that changes nothing — the view is answered as it is\n * and the revision is not spent — or a `ViewStoreError` for a refusal of\n * its own.\n */\n private update(\n id: string,\n revision: string,\n context: WriteOptions,\n change: (current: ViewInstance) => ViewInstance | ViewStoreError | null,\n refused?: ViewStoreError,\n ): Promise<ViewInstance> {\n const replayed = this.outcomes.get(context.requestId);\n if (replayed) return Promise.resolve(copy(replayed));\n if (refused) return Promise.reject(refused);\n this.reload();\n\n const current = this.instances.get(id);\n if (!current)\n return Promise.reject(\n new ViewStoreError('NOT_FOUND', `No such view: ${id}`),\n );\n if (readOnlySystem(current))\n return Promise.reject(\n new ViewStoreError('FORBIDDEN', 'System views are read-only'),\n );\n const conflict = this.expect(current, revision);\n if (conflict) return Promise.reject(conflict);\n\n const changed = change(current);\n if (changed instanceof ViewStoreError) return Promise.reject(changed);\n if (changed === null) {\n this.outcomes.set(context.requestId, current);\n return Promise.resolve(copy(current));\n }\n const next: ViewInstance = {\n ...changed,\n revision: nextRevision(current.revision),\n };\n this.instances.set(id, next);\n return this.commit(context, next, () => this.instances.set(id, current));\n }\n\n /**\n * The titles of the boards everyone sees that show `id` in a panel — the\n * reference the dashboard kernel's `coversScope` guards from the board's\n * side. Read off the stored configs as the untrusted JSON they are: the\n * store may import nothing but the model.\n */\n private sharedBoardsShowing(id: string): string[] {\n const boards: string[] = [];\n for (const instance of this.instances.values()) {\n const { config } = instance;\n if (\n config.kind !== 'dashboard' ||\n audienceOf(instance.scope) !== 'shared'\n )\n continue;\n const panels: unknown = config.panels;\n if (Array.isArray(panels) && panels.some(panel => shows(panel, id)))\n boards.push(instance.title);\n }\n return boards;\n }\n\n private expect(\n current: ViewInstance,\n revision: string,\n ): ViewStoreError | undefined {\n return current.revision === revision\n ? undefined\n : new ViewStoreError(\n 'CONFLICT',\n `View ${current.id} moved to revision ${current.revision}`,\n { instance: current },\n );\n }\n\n private commit(\n context: WriteOptions,\n instance: ViewInstance,\n undo: () => void,\n ): Promise<ViewInstance> {\n const refused = this.persist(undo);\n if (refused) return Promise.reject(refused);\n this.outcomes.set(context.requestId, instance);\n return Promise.resolve(copy(instance));\n }\n\n /**\n * Hands the state to the snapshot. When it could not be kept, the change\n * just made is undone — memory goes back to what is stored — and the\n * refusal is answered, so the write rejects rather than being reported as\n * saved. No outcome is remembered for it, so a retry writes again.\n */\n private persist(undo: () => void): ViewStoreError | undefined {\n if (!this.snapshot) return undefined;\n try {\n this.snapshot.save({\n instances: [...this.instances.values()].map(instance => copy(instance)),\n preferences: Object.fromEntries(this.preferences),\n });\n return undefined;\n } catch (error) {\n undo();\n return new ViewStoreError(\n 'UNAVAILABLE',\n `The view store could not keep this write: ${reasonOf(error)}`,\n { storage: true },\n );\n }\n }\n\n /**\n * Takes the stored state as it is now, when there is one to read: before a\n * write, so the write is checked against it, and when another writer says\n * it changed. Nothing readable leaves what the store holds as it is.\n */\n private reload(): void {\n const stored = this.snapshot?.load();\n if (stored) this.restore(stored);\n }\n\n private restore(state: MemoryState): void {\n this.instances.clear();\n this.preferences.clear();\n for (const instance of state.instances)\n this.instances.set(instance.id, copy(instance));\n for (const [definitionId, preferences] of Object.entries(state.preferences))\n this.preferences.set(definitionId, preferences);\n }\n}\n\n/**\n * Whether a stored panel references the saved view `id`, by any of the\n * three members the server reads (`ViewConfigs.PANEL_REFERENCES`, and\n * `DashboardPanel`): the view it shows (`instanceId`, unless the board owns\n * the view, `owned`), the view 「在工作台中打开」 opens (`opens`), and the\n * one a press opens (`click.instanceId`).\n */\nfunction shows(panel: unknown, id: string): boolean {\n if (typeof panel !== 'object' || panel === null) return false;\n const { instanceId, owned, opens, click } = panel as {\n instanceId?: unknown;\n owned?: unknown;\n opens?: unknown;\n click?: unknown;\n };\n if (owned === undefined && instanceId === id) return true;\n if (opens === id) return true;\n return (\n typeof click === 'object' &&\n click !== null &&\n (click as { instanceId?: unknown }).instanceId === id\n );\n}\n\n/** A system view no write reaches: configured, not one this store keeps. */\nfunction readOnlySystem(instance: ViewInstance): boolean {\n return isSystemScope(instance.scope) && instance.stored !== true;\n}\n\n/** System views first, then shared, then personal: the port's list order. */\nconst AUDIENCE_RANK: Readonly<Record<ViewInstance['scope'], number>> = {\n system: 0,\n shared: 1,\n personal: 2,\n};\n\n/**\n * The revision after `current`. Revisions are opaque to the port, and a host\n * may seed any string; one this store did not write as a count (`'ops-1'`)\n * starts the count again at `'1'`, which it can never have been, so a write\n * against it still conflicts. A count goes on counting.\n */\nfunction nextRevision(current: string): string {\n return /^(0|[1-9]\\d{0,14})$/.test(current)\n ? String(Number(current) + 1)\n : '1';\n}\n\n/** A title the server refuses (`ViewConfigs.requireTitle`), in its words. */\nfunction titleRefusal(title: string): ViewStoreError | undefined {\n switch (titleProblem(title)) {\n case 'empty':\n return new ViewStoreError('INVALID', \"A view's title must not be blank.\");\n case 'too-long':\n return new ViewStoreError(\n 'INVALID',\n `A view's title is longer than ${MAX_VIEW_TITLE_LENGTH} characters.`,\n );\n default:\n return undefined;\n }\n}\n\n/** A config larger than the server keeps, in its words. */\nfunction configRefusal(config: ViewConfig): ViewStoreError | undefined {\n const bytes = configBytes(config);\n return bytes > MAX_VIEW_CONFIG_BYTES\n ? new ViewStoreError(\n 'INVALID',\n `A view's config is ${bytes} bytes; the limit is ${MAX_VIEW_CONFIG_BYTES}.`,\n )\n : undefined;\n}\n\n/** What a refusal said — a `DOMException` is an `Error` only in some realms. */\nfunction reasonOf(error: unknown): string {\n if (typeof error === 'object' && error !== null) {\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (typeof message === 'string')\n return typeof name === 'string' ? `${name}: ${message}` : message;\n }\n return String(error);\n}\n\n/**\n * A structural copy, so nothing a caller holds is the object the store keeps.\n * A config handed in or read back is a plain JSON tree, and a caller editing\n * one it still has a reference to must not change what is stored.\n */\nfunction copy<T>(value: T): T {\n return structuredClone(value);\n}\n"],"mappings":";;;;;AAmCA,SAAgBS,GACdC,GACAC,GAC8B;CAC9B,IAAID,MAAS,IAAO;CACpB,IAAMG,KAAYC,MAChBA,EAAMJ,KAAKK,aAAa,KAAQ,OAAQD,EAAMJ,KAAKK,YAAY,CAAC,GAC5DC,IAAkD;EACtDN,MAAMA,KAAQ,CAAC;EACfC,QAAQ,CAAC;EACTO,UAAU,CAAC;CACb;CACA,KAAK,IAAMJ,KAASH,GAAQ;EAC1B,IAAMQ,IAAML,EAAMM,YAAYP,EAASC,CAAK,IAAI;EAChD,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