@eifi1/ui-kit 0.51.4 → 0.51.6

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 (759) hide show
  1. package/README.md +5 -5
  2. package/dist/account/account-settings-labels.js.map +1 -1
  3. package/dist/account/account-settings.js +11 -9
  4. package/dist/account/account-settings.js.map +1 -1
  5. package/dist/account/delete-account-setting.js +56 -65
  6. package/dist/account/delete-account-setting.js.map +1 -1
  7. package/dist/account/email-change-setting-labels.js.map +1 -1
  8. package/dist/account/email-change-setting.js.map +1 -1
  9. package/dist/account/passkeys-setting.js.map +1 -1
  10. package/dist/account/sessions-setting.js.map +1 -1
  11. package/dist/admin/admin-action-confirm.js +1 -3
  12. package/dist/admin/admin-action-confirm.js.map +1 -1
  13. package/dist/admin/admin-action-log.js.map +1 -1
  14. package/dist/admin/admin-area-labels.js +4 -1
  15. package/dist/admin/admin-area-labels.js.map +1 -1
  16. package/dist/admin/admin-overview.js +19 -11
  17. package/dist/admin/admin-overview.js.map +1 -1
  18. package/dist/admin/admin-sections.js.map +1 -1
  19. package/dist/admin/admin-tool-links.d.ts +1 -1
  20. package/dist/admin/admin-tool-links.js +7 -1
  21. package/dist/admin/admin-tool-links.js.map +1 -1
  22. package/dist/admin/invitations-panel.js +2 -13
  23. package/dist/admin/invitations-panel.js.map +1 -1
  24. package/dist/admin/mail-test-card.js.map +1 -1
  25. package/dist/admin/reviewer-scope-editor.js +4 -11
  26. package/dist/admin/reviewer-scope-editor.js.map +1 -1
  27. package/dist/admin/role-select.js.map +1 -1
  28. package/dist/admin/user-roster.js +1 -9
  29. package/dist/admin/user-roster.js.map +1 -1
  30. package/dist/auth/accept-invitation.js.map +1 -1
  31. package/dist/auth/auth-errors.js.map +1 -1
  32. package/dist/auth/forgot-password-form.js +23 -31
  33. package/dist/auth/forgot-password-form.js.map +1 -1
  34. package/dist/auth/register-form.js.map +1 -1
  35. package/dist/auth/reset-password-form.js.map +1 -1
  36. package/dist/auth/sign-in-form.js +13 -5
  37. package/dist/auth/sign-in-form.js.map +1 -1
  38. package/dist/auth/verify-email.js +1 -8
  39. package/dist/auth/verify-email.js.map +1 -1
  40. package/dist/billing/billing-banner.js.map +1 -1
  41. package/dist/billing/billing-labels.js.map +1 -1
  42. package/dist/billing/checkout-processing.js.map +1 -1
  43. package/dist/billing/plan-card.js +91 -85
  44. package/dist/billing/plan-card.js.map +1 -1
  45. package/dist/billing/plan-limit-toast.js.map +1 -1
  46. package/dist/billing/plan-limit.js.map +1 -1
  47. package/dist/billing/plan-price.js.map +1 -1
  48. package/dist/billing/plan-switch.js.map +1 -1
  49. package/dist/billing/subscription-actions.js.map +1 -1
  50. package/dist/bin/eifi1-pay-page.mjs +6 -1
  51. package/dist/components/account-chips.js.map +1 -1
  52. package/dist/components/alert-banner.js +1 -5
  53. package/dist/components/alert-banner.js.map +1 -1
  54. package/dist/components/amount-input.js +29 -12
  55. package/dist/components/amount-input.js.map +1 -1
  56. package/dist/components/authed-image.js.map +1 -1
  57. package/dist/components/autocomplete.js.map +1 -1
  58. package/dist/components/bulk-action-bar.js +1 -4
  59. package/dist/components/bulk-action-bar.js.map +1 -1
  60. package/dist/components/button-group.js.map +1 -1
  61. package/dist/components/button-look.js.map +1 -1
  62. package/dist/components/button.js +1 -7
  63. package/dist/components/button.js.map +1 -1
  64. package/dist/components/calculator.js +5 -5
  65. package/dist/components/calculator.js.map +1 -1
  66. package/dist/components/calendar-heatmap.js +4 -10
  67. package/dist/components/calendar-heatmap.js.map +1 -1
  68. package/dist/components/card.js +1 -8
  69. package/dist/components/card.js.map +1 -1
  70. package/dist/components/chart-zoom-core.js +3 -17
  71. package/dist/components/chart-zoom-core.js.map +1 -1
  72. package/dist/components/chart.d.ts +1 -1
  73. package/dist/components/chart.js +4 -22
  74. package/dist/components/chart.js.map +1 -1
  75. package/dist/components/checkbox-group.js +1 -4
  76. package/dist/components/checkbox-group.js.map +1 -1
  77. package/dist/components/chip-input.js +4 -1
  78. package/dist/components/chip-input.js.map +1 -1
  79. package/dist/components/chip.js +10 -5
  80. package/dist/components/chip.js.map +1 -1
  81. package/dist/components/choice-card.js +58 -74
  82. package/dist/components/choice-card.js.map +1 -1
  83. package/dist/components/column-mapper-labels.js.map +1 -1
  84. package/dist/components/column-mapper.js +167 -227
  85. package/dist/components/column-mapper.js.map +1 -1
  86. package/dist/components/combobox-core.js +1 -4
  87. package/dist/components/combobox-core.js.map +1 -1
  88. package/dist/components/combobox.js +1 -4
  89. package/dist/components/combobox.js.map +1 -1
  90. package/dist/components/confirm-dialog.js.map +1 -1
  91. package/dist/components/copy-button.js.map +1 -1
  92. package/dist/components/country-select.d.ts +5 -4
  93. package/dist/components/country-select.js +3 -19
  94. package/dist/components/country-select.js.map +1 -1
  95. package/dist/components/currency-option-list.js +10 -8
  96. package/dist/components/currency-option-list.js.map +1 -1
  97. package/dist/components/currency-select.js +1 -6
  98. package/dist/components/currency-select.js.map +1 -1
  99. package/dist/components/danger-confirm.js.map +1 -1
  100. package/dist/components/data-table-cells.js.map +1 -1
  101. package/dist/components/data-table-column-settings.js.map +1 -1
  102. package/dist/components/data-table-filter-popover.js +2 -18
  103. package/dist/components/data-table-filter-popover.js.map +1 -1
  104. package/dist/components/data-table-filters.js.map +1 -1
  105. package/dist/components/data-table-fit.js.map +1 -1
  106. package/dist/components/data-table-groups.js +3 -1
  107. package/dist/components/data-table-groups.js.map +1 -1
  108. package/dist/components/data-table-head.js +44 -56
  109. package/dist/components/data-table-head.js.map +1 -1
  110. package/dist/components/data-table-mobile.js +31 -44
  111. package/dist/components/data-table-mobile.js.map +1 -1
  112. package/dist/components/data-table-pagination.js.map +1 -1
  113. package/dist/components/data-table-row-actions.js +19 -16
  114. package/dist/components/data-table-row-actions.js.map +1 -1
  115. package/dist/components/data-table-row.js.map +1 -1
  116. package/dist/components/data-table-shared.js.map +1 -1
  117. package/dist/components/data-table-sort.js.map +1 -1
  118. package/dist/components/data-table-virtual.js +4 -1
  119. package/dist/components/data-table-virtual.js.map +1 -1
  120. package/dist/components/data-table.js +30 -39
  121. package/dist/components/data-table.js.map +1 -1
  122. package/dist/components/date-picker.js +1 -6
  123. package/dist/components/date-picker.js.map +1 -1
  124. package/dist/components/date-range-picker.js.map +1 -1
  125. package/dist/components/description-list.js +10 -10
  126. package/dist/components/description-list.js.map +1 -1
  127. package/dist/components/dialog-frame.js +9 -2
  128. package/dist/components/dialog-frame.js.map +1 -1
  129. package/dist/components/disclosure.js +17 -27
  130. package/dist/components/disclosure.js.map +1 -1
  131. package/dist/components/dropdown.js +25 -35
  132. package/dist/components/dropdown.js.map +1 -1
  133. package/dist/components/empty-state.js.map +1 -1
  134. package/dist/components/entity-combobox.js.map +1 -1
  135. package/dist/components/error-boundary.js.map +1 -1
  136. package/dist/components/field-base.js +5 -5
  137. package/dist/components/field-base.js.map +1 -1
  138. package/dist/components/field-parts.d.ts +1 -1
  139. package/dist/components/field-parts.js +10 -14
  140. package/dist/components/field-parts.js.map +1 -1
  141. package/dist/components/field-sync.js +8 -10
  142. package/dist/components/field-sync.js.map +1 -1
  143. package/dist/components/file-button.js.map +1 -1
  144. package/dist/components/file-dropzone.js.map +1 -1
  145. package/dist/components/floating-panel.js +4 -1
  146. package/dist/components/floating-panel.js.map +1 -1
  147. package/dist/components/focus-ring.js.map +1 -1
  148. package/dist/components/form-actions.js.map +1 -1
  149. package/dist/components/grouped-picker.js +6 -8
  150. package/dist/components/grouped-picker.js.map +1 -1
  151. package/dist/components/hover-menu.js +1 -4
  152. package/dist/components/hover-menu.js.map +1 -1
  153. package/dist/components/iban-input-labels.js.map +1 -1
  154. package/dist/components/icon-button.js +4 -1
  155. package/dist/components/icon-button.js.map +1 -1
  156. package/dist/components/icon-picker.js +2 -7
  157. package/dist/components/icon-picker.js.map +1 -1
  158. package/dist/components/image-grid.js +41 -50
  159. package/dist/components/image-grid.js.map +1 -1
  160. package/dist/components/inline-edit-field.js.map +1 -1
  161. package/dist/components/inline-entity-combobox.js +2 -8
  162. package/dist/components/inline-entity-combobox.js.map +1 -1
  163. package/dist/components/input.js +14 -2
  164. package/dist/components/input.js.map +1 -1
  165. package/dist/components/jump-calendar.js +1 -7
  166. package/dist/components/jump-calendar.js.map +1 -1
  167. package/dist/components/legal-labels.js.map +1 -1
  168. package/dist/components/legal-page.js +14 -2
  169. package/dist/components/legal-page.js.map +1 -1
  170. package/dist/components/legal.js +12 -2
  171. package/dist/components/legal.js.map +1 -1
  172. package/dist/components/lightbox.js.map +1 -1
  173. package/dist/components/line-items.js +26 -36
  174. package/dist/components/line-items.js.map +1 -1
  175. package/dist/components/list.js +22 -10
  176. package/dist/components/list.js.map +1 -1
  177. package/dist/components/measured-grid.js +29 -53
  178. package/dist/components/measured-grid.js.map +1 -1
  179. package/dist/components/menu-item.js.map +1 -1
  180. package/dist/components/mini-calendar.js +13 -31
  181. package/dist/components/mini-calendar.js.map +1 -1
  182. package/dist/components/money-field.js.map +1 -1
  183. package/dist/components/month-picker.js +10 -21
  184. package/dist/components/month-picker.js.map +1 -1
  185. package/dist/components/multi-entity-combobox.js +3 -16
  186. package/dist/components/multi-entity-combobox.js.map +1 -1
  187. package/dist/components/multi-select.js.map +1 -1
  188. package/dist/components/nav-pills.js +10 -1
  189. package/dist/components/nav-pills.js.map +1 -1
  190. package/dist/components/number-field.js.map +1 -1
  191. package/dist/components/number-input.js +1 -7
  192. package/dist/components/number-input.js.map +1 -1
  193. package/dist/components/numpad-sheet.js +1 -4
  194. package/dist/components/numpad-sheet.js.map +1 -1
  195. package/dist/components/one-time-code-input.js +1 -7
  196. package/dist/components/one-time-code-input.js.map +1 -1
  197. package/dist/components/page-contents.js +13 -22
  198. package/dist/components/page-contents.js.map +1 -1
  199. package/dist/components/page-header.js +1 -11
  200. package/dist/components/page-header.js.map +1 -1
  201. package/dist/components/password-strength-labels.js.map +1 -1
  202. package/dist/components/password-strength.js +2 -8
  203. package/dist/components/password-strength.js.map +1 -1
  204. package/dist/components/phone-input.js +42 -57
  205. package/dist/components/phone-input.js.map +1 -1
  206. package/dist/components/picker-sheet.js.map +1 -1
  207. package/dist/components/pie-chart.js +1 -8
  208. package/dist/components/pie-chart.js.map +1 -1
  209. package/dist/components/popover.js.map +1 -1
  210. package/dist/components/progress-bar.js +16 -9
  211. package/dist/components/progress-bar.js.map +1 -1
  212. package/dist/components/qr-code.js +1 -8
  213. package/dist/components/qr-code.js.map +1 -1
  214. package/dist/components/row-actions.js +5 -1
  215. package/dist/components/row-actions.js.map +1 -1
  216. package/dist/components/search-field.js.map +1 -1
  217. package/dist/components/select.js +28 -38
  218. package/dist/components/select.js.map +1 -1
  219. package/dist/components/separator.js +1 -5
  220. package/dist/components/separator.js.map +1 -1
  221. package/dist/components/series-chart-axes.js +4 -1
  222. package/dist/components/series-chart-axes.js.map +1 -1
  223. package/dist/components/series-chart-budget.js.map +1 -1
  224. package/dist/components/series-chart-ticks.js.map +1 -1
  225. package/dist/components/series-chart.js +29 -45
  226. package/dist/components/series-chart.js.map +1 -1
  227. package/dist/components/settings-fields.js +21 -17
  228. package/dist/components/settings-fields.js.map +1 -1
  229. package/dist/components/share-card.js +4 -9
  230. package/dist/components/share-card.js.map +1 -1
  231. package/dist/components/sign-chip.js.map +1 -1
  232. package/dist/components/signature-pad.js +4 -13
  233. package/dist/components/signature-pad.js.map +1 -1
  234. package/dist/components/signed-amount.js +12 -5
  235. package/dist/components/signed-amount.js.map +1 -1
  236. package/dist/components/skeleton.js +2 -17
  237. package/dist/components/skeleton.js.map +1 -1
  238. package/dist/components/slider.js +13 -36
  239. package/dist/components/slider.js.map +1 -1
  240. package/dist/components/sparkline.js.map +1 -1
  241. package/dist/components/stat-tile.js +14 -10
  242. package/dist/components/stat-tile.js.map +1 -1
  243. package/dist/components/swatch-picker.js +14 -4
  244. package/dist/components/swatch-picker.js.map +1 -1
  245. package/dist/components/swipeable-row.d.ts +1 -1
  246. package/dist/components/swipeable-row.js +1 -8
  247. package/dist/components/swipeable-row.js.map +1 -1
  248. package/dist/components/table-skeleton.js +4 -1
  249. package/dist/components/table-skeleton.js.map +1 -1
  250. package/dist/components/table.js +12 -9
  251. package/dist/components/table.js.map +1 -1
  252. package/dist/components/tabs.js +5 -24
  253. package/dist/components/tabs.js.map +1 -1
  254. package/dist/components/text-link.js.map +1 -1
  255. package/dist/components/text.js.map +1 -1
  256. package/dist/components/tile-radio.js +1 -7
  257. package/dist/components/tile-radio.js.map +1 -1
  258. package/dist/components/time-input.js.map +1 -1
  259. package/dist/components/toast.js.map +1 -1
  260. package/dist/components/toggle-group.js +6 -1
  261. package/dist/components/toggle-group.js.map +1 -1
  262. package/dist/components/toggle-legend.js +2 -11
  263. package/dist/components/toggle-legend.js.map +1 -1
  264. package/dist/components/tooltip.js +2 -22
  265. package/dist/components/tooltip.js.map +1 -1
  266. package/dist/components/translation-review-editor.js +1 -4
  267. package/dist/components/translation-review-editor.js.map +1 -1
  268. package/dist/components/translation-review-parts.d.ts +1 -1
  269. package/dist/components/translation-review-parts.js +7 -1
  270. package/dist/components/translation-review-parts.js.map +1 -1
  271. package/dist/components/translation-review.js +18 -7
  272. package/dist/components/translation-review.js.map +1 -1
  273. package/dist/components/tree-view.js +14 -10
  274. package/dist/components/tree-view.js.map +1 -1
  275. package/dist/components/treemap.d.ts +24 -2
  276. package/dist/components/treemap.js +28 -4
  277. package/dist/components/treemap.js.map +1 -1
  278. package/dist/components/trigger-aria.js.map +1 -1
  279. package/dist/components/use-table-state.js +14 -11
  280. package/dist/components/use-table-state.js.map +1 -1
  281. package/dist/components/user-avatar.js +3 -26
  282. package/dist/components/user-avatar.js.map +1 -1
  283. package/dist/demo/demo-start.js +8 -4
  284. package/dist/demo/demo-start.js.map +1 -1
  285. package/dist/eslint/index.js +1 -1
  286. package/dist/feedback/feedback-attachment-labels.js.map +1 -1
  287. package/dist/feedback/feedback-attachment.js +1 -8
  288. package/dist/feedback/feedback-attachment.js.map +1 -1
  289. package/dist/feedback/feedback-capture.d.ts +1 -1
  290. package/dist/feedback/feedback-capture.js +3 -1
  291. package/dist/feedback/feedback-capture.js.map +1 -1
  292. package/dist/feedback/feedback-comment-thread.js +27 -13
  293. package/dist/feedback/feedback-comment-thread.js.map +1 -1
  294. package/dist/feedback/feedback-context.js +1 -4
  295. package/dist/feedback/feedback-context.js.map +1 -1
  296. package/dist/feedback/feedback-dialog.js.map +1 -1
  297. package/dist/feedback/feedback-inbox.js.map +1 -1
  298. package/dist/feedback/feedback-public-list.js +7 -1
  299. package/dist/feedback/feedback-public-list.js.map +1 -1
  300. package/dist/feedback/feedback-record.js +1 -5
  301. package/dist/feedback/feedback-record.js.map +1 -1
  302. package/dist/feedback/feedback-replies.js +25 -10
  303. package/dist/feedback/feedback-replies.js.map +1 -1
  304. package/dist/feedback/feedback-row-detail.js.map +1 -1
  305. package/dist/feedback/feedback-status-undo.js.map +1 -1
  306. package/dist/feedback/feedback-submit-dialog.js.map +1 -1
  307. package/dist/feedback/feedback-table.js +4 -1
  308. package/dist/feedback/feedback-table.js.map +1 -1
  309. package/dist/feedback/feedback-thread.js +2 -13
  310. package/dist/feedback/feedback-thread.js.map +1 -1
  311. package/dist/feedback/feedback-vocabulary.js.map +1 -1
  312. package/dist/feedback/feedback-vote-button.js.map +1 -1
  313. package/dist/hooks/use-anchored-rect.js.map +1 -1
  314. package/dist/hooks/use-document-title.js.map +1 -1
  315. package/dist/hooks/use-file-drop.js.map +1 -1
  316. package/dist/hooks/use-file-picker-labels.js.map +1 -1
  317. package/dist/hooks/use-file-picker.js.map +1 -1
  318. package/dist/hooks/use-focus-trap.js.map +1 -1
  319. package/dist/hooks/use-overlay-history.js +10 -5
  320. package/dist/hooks/use-overlay-history.js.map +1 -1
  321. package/dist/hooks/use-row-swipe.d.ts +1 -1
  322. package/dist/hooks/use-row-swipe.js +1 -6
  323. package/dist/hooks/use-row-swipe.js.map +1 -1
  324. package/dist/i18n/defaults.js +1 -4
  325. package/dist/i18n/defaults.js.map +1 -1
  326. package/dist/i18n/german.js +4 -1
  327. package/dist/i18n/german.js.map +1 -1
  328. package/dist/i18n/kit-labels.js +2 -8
  329. package/dist/i18n/kit-labels.js.map +1 -1
  330. package/dist/i18n/languages.js.map +1 -1
  331. package/dist/i18n/locales/en.js +4 -1
  332. package/dist/i18n/locales/en.js.map +2 -2
  333. package/dist/i18n/locales/es.js +4 -1
  334. package/dist/i18n/locales/es.js.map +1 -1
  335. package/dist/i18n/locales/fr.js +4 -1
  336. package/dist/i18n/locales/fr.js.map +1 -1
  337. package/dist/i18n/locales/hu.js +4 -1
  338. package/dist/i18n/locales/hu.js.map +1 -1
  339. package/dist/i18n/locales/it.js +4 -1
  340. package/dist/i18n/locales/it.js.map +1 -1
  341. package/dist/i18n/locales/zh.js.map +1 -1
  342. package/dist/i18n/plurals.js.map +1 -1
  343. package/dist/i18n/review.js +13 -7
  344. package/dist/i18n/review.js.map +1 -1
  345. package/dist/i18n/shared-labels.js.map +1 -1
  346. package/dist/index.d.ts +16 -16
  347. package/dist/index.js +40 -23
  348. package/dist/index.js.map +1 -1
  349. package/dist/landing/access.js +1 -4
  350. package/dist/landing/access.js.map +1 -1
  351. package/dist/landing/landing-sections.js +35 -38
  352. package/dist/landing/landing-sections.js.map +1 -1
  353. package/dist/landing/page-seo.js.map +1 -1
  354. package/dist/lib/calc.js.map +1 -1
  355. package/dist/lib/clipboard-minus.js.map +1 -1
  356. package/dist/lib/dates.js.map +1 -1
  357. package/dist/lib/decimal-marks.js.map +1 -1
  358. package/dist/lib/device-settings.js +2 -1
  359. package/dist/lib/device-settings.js.map +1 -1
  360. package/dist/lib/direction.js.map +1 -1
  361. package/dist/lib/iban.js.map +1 -1
  362. package/dist/lib/logger.js +1 -5
  363. package/dist/lib/logger.js.map +1 -1
  364. package/dist/lib/person-name.js.map +1 -1
  365. package/dist/lib/phone.js.map +1 -1
  366. package/dist/lib/qr-encode.js +344 -8
  367. package/dist/lib/qr-encode.js.map +1 -1
  368. package/dist/lib/session-refresh.js.map +1 -1
  369. package/dist/lib/table-text.js +15 -3
  370. package/dist/lib/table-text.js.map +1 -1
  371. package/dist/lib/text-match.d.ts +4 -0
  372. package/dist/lib/text-match.js.map +1 -1
  373. package/dist/lib/translation-review.js.map +1 -1
  374. package/dist/notifications/notification-inbox.js +63 -44
  375. package/dist/notifications/notification-inbox.js.map +1 -1
  376. package/dist/notifications/notification-parts.js.map +1 -1
  377. package/dist/notifications/notification-types-setting.js.map +1 -1
  378. package/dist/notifications/notifications-labels.js.map +1 -1
  379. package/dist/notifications/push-device-setting.js +6 -1
  380. package/dist/notifications/push-device-setting.js.map +1 -1
  381. package/dist/notifications/push-devices-setting.js.map +1 -1
  382. package/dist/notifications/push-worker.js.map +1 -1
  383. package/dist/notifications/quiet-hours-setting.js.map +1 -1
  384. package/dist/notifications/use-push-device.js +4 -1
  385. package/dist/notifications/use-push-device.js.map +1 -1
  386. package/dist/offline/pwa-update-prompt.d.ts +1 -1
  387. package/dist/offline/pwa-update-prompt.js +7 -1
  388. package/dist/offline/pwa-update-prompt.js.map +1 -1
  389. package/dist/offline/query-persistence.js.map +1 -1
  390. package/dist/offline.d.ts +1 -1
  391. package/dist/offline.js +6 -1
  392. package/dist/offline.js.map +1 -1
  393. package/dist/pay/pay.css +8 -1
  394. package/dist/rhf/fields.d.ts +1 -2
  395. package/dist/rhf/fields.js +1 -10
  396. package/dist/rhf/fields.js.map +1 -1
  397. package/dist/rhf/form-core.js +1 -4
  398. package/dist/rhf/form-core.js.map +1 -1
  399. package/dist/rhf/line-items.js.map +1 -1
  400. package/dist/rhf/use-rhf-wizard-step.js.map +1 -1
  401. package/dist/search/command-palette.js +71 -62
  402. package/dist/search/command-palette.js.map +1 -1
  403. package/dist/search/global-search.js +34 -5
  404. package/dist/search/global-search.js.map +1 -1
  405. package/dist/search/search-index.js.map +1 -1
  406. package/dist/settings/device-reset-setting.js +1 -6
  407. package/dist/settings/device-reset-setting.js.map +1 -1
  408. package/dist/settings/settings-heading.js.map +1 -1
  409. package/dist/settings/settings-layout.js +9 -20
  410. package/dist/settings/settings-layout.js.map +1 -1
  411. package/dist/settings/use-settings-route.js.map +1 -1
  412. package/dist/shell/app-shell.js +62 -31
  413. package/dist/shell/app-shell.js.map +1 -1
  414. package/dist/shell/auth-layout.js +1 -10
  415. package/dist/shell/auth-layout.js.map +1 -1
  416. package/dist/shell/dev-menu.js +12 -6
  417. package/dist/shell/dev-menu.js.map +1 -1
  418. package/dist/shell/option-switcher-menu.js.map +1 -1
  419. package/dist/shell/sync-status-indicator.js +7 -6
  420. package/dist/shell/sync-status-indicator.js.map +1 -1
  421. package/dist/shell/top-bar-parts-labels.js.map +1 -1
  422. package/dist/shell/topbar-action-menu.js.map +1 -1
  423. package/dist/shell/topbar-controls.js +1 -10
  424. package/dist/shell/topbar-controls.js.map +1 -1
  425. package/dist/shell/tour-menu.js +9 -1
  426. package/dist/shell/tour-menu.js.map +1 -1
  427. package/dist/sync/db.js.map +1 -1
  428. package/dist/sync/engine.js +24 -6
  429. package/dist/sync/engine.js.map +1 -1
  430. package/dist/sync.d.ts +2 -2
  431. package/dist/sync.js +7 -1
  432. package/dist/sync.js.map +1 -1
  433. package/dist/testing/css-variables.js.map +1 -1
  434. package/dist/testing/index.d.ts +1 -1
  435. package/dist/testing/index.js +1 -3
  436. package/dist/testing/index.js.map +1 -1
  437. package/dist/testing/react.js.map +1 -1
  438. package/dist/testing/viewport.js +7 -4
  439. package/dist/testing/viewport.js.map +1 -1
  440. package/dist/theme/contrast-tokens.js +13 -2
  441. package/dist/theme/contrast-tokens.js.map +1 -1
  442. package/dist/theme/contrast.d.ts +2 -2
  443. package/dist/theme/palette-derive.d.ts +1 -1
  444. package/dist/theme/palette-derive.js +18 -29
  445. package/dist/theme/palette-derive.js.map +1 -1
  446. package/dist/theme/palette-presets.js.map +1 -1
  447. package/dist/theme/palette-store.js.map +1 -1
  448. package/dist/theme/text-size.js.map +1 -1
  449. package/dist/theme/theme-store.js +1 -3
  450. package/dist/theme/theme-store.js.map +1 -1
  451. package/dist/tour/tour-catalogue.js.map +1 -1
  452. package/dist/tour/tour-dock.js +5 -1
  453. package/dist/tour/tour-dock.js.map +1 -1
  454. package/dist/tour/tour-engine.js +1 -4
  455. package/dist/tour/tour-engine.js.map +1 -1
  456. package/dist/tour/tour.js +21 -12
  457. package/dist/tour/tour.js.map +1 -1
  458. package/dist/tour/use-tour-progress.js.map +1 -1
  459. package/dist/tour/use-tour-url-sync.js.map +1 -1
  460. package/dist/wizard/stepper-nav.js +3 -24
  461. package/dist/wizard/stepper-nav.js.map +1 -1
  462. package/dist/wizard/types.js.map +1 -1
  463. package/dist/wizard/use-wizard.js +24 -28
  464. package/dist/wizard/use-wizard.js.map +1 -1
  465. package/dist/wizard/validation.js.map +1 -1
  466. package/dist/wizard/wizard-context.js.map +1 -1
  467. package/dist/wizard/wizard-step.d.ts +1 -1
  468. package/dist/wizard/wizard-step.js +1 -8
  469. package/dist/wizard/wizard-step.js.map +1 -1
  470. package/dist/wizard/wizard-summary.js.map +1 -1
  471. package/package.json +5 -2
  472. package/src/account/account-settings-labels.ts +1 -2
  473. package/src/account/account-settings.tsx +11 -17
  474. package/src/account/delete-account-setting.tsx +1 -6
  475. package/src/account/email-change-setting-labels.ts +1 -2
  476. package/src/account/email-change-setting.tsx +3 -1
  477. package/src/account/passkeys-setting.tsx +1 -3
  478. package/src/account/sessions-setting.tsx +4 -2
  479. package/src/admin/admin-action-confirm.tsx +4 -7
  480. package/src/admin/admin-action-log.tsx +29 -29
  481. package/src/admin/admin-area-labels.ts +4 -1
  482. package/src/admin/admin-overview.tsx +8 -2
  483. package/src/admin/admin-sections.tsx +3 -1
  484. package/src/admin/admin-tool-links.tsx +7 -1
  485. package/src/admin/invitations-panel.tsx +5 -11
  486. package/src/admin/mail-test-card.tsx +1 -2
  487. package/src/admin/reviewer-scope-editor.tsx +4 -9
  488. package/src/admin/role-select.tsx +4 -2
  489. package/src/admin/user-roster.tsx +2 -11
  490. package/src/auth/accept-invitation.tsx +1 -7
  491. package/src/auth/auth-errors.ts +1 -6
  492. package/src/auth/forgot-password-form.tsx +2 -7
  493. package/src/auth/register-form.tsx +7 -8
  494. package/src/auth/reset-password-form.tsx +2 -5
  495. package/src/auth/sign-in-form.tsx +15 -14
  496. package/src/auth/verify-email.tsx +2 -7
  497. package/src/billing/billing-banner.tsx +3 -7
  498. package/src/billing/billing-labels.ts +6 -4
  499. package/src/billing/checkout-processing.ts +0 -1
  500. package/src/billing/plan-card.tsx +9 -8
  501. package/src/billing/plan-limit-toast.tsx +1 -2
  502. package/src/billing/plan-limit.ts +1 -2
  503. package/src/billing/plan-price.ts +1 -4
  504. package/src/billing/plan-switch.tsx +1 -2
  505. package/src/billing/subscription-actions.tsx +5 -2
  506. package/src/components/account-chips.tsx +1 -7
  507. package/src/components/alert-banner.tsx +2 -8
  508. package/src/components/amount-input.tsx +206 -178
  509. package/src/components/authed-image.tsx +7 -4
  510. package/src/components/autocomplete.tsx +7 -9
  511. package/src/components/bulk-action-bar.tsx +2 -7
  512. package/src/components/button-group.tsx +1 -2
  513. package/src/components/button-look.ts +6 -17
  514. package/src/components/button.tsx +1 -4
  515. package/src/components/calculator.tsx +6 -9
  516. package/src/components/calendar-heatmap.tsx +5 -10
  517. package/src/components/card.tsx +9 -13
  518. package/src/components/chart-zoom-core.tsx +6 -33
  519. package/src/components/chart.tsx +8 -31
  520. package/src/components/checkbox-group.tsx +1 -4
  521. package/src/components/chip-input.tsx +6 -6
  522. package/src/components/chip.tsx +14 -26
  523. package/src/components/choice-card.tsx +4 -18
  524. package/src/components/column-mapper-labels.ts +3 -10
  525. package/src/components/column-mapper.tsx +33 -122
  526. package/src/components/combobox-core.tsx +12 -42
  527. package/src/components/combobox.tsx +2 -6
  528. package/src/components/confirm-dialog.tsx +1 -3
  529. package/src/components/copy-button.tsx +2 -4
  530. package/src/components/country-select.tsx +9 -21
  531. package/src/components/currency-option-list.tsx +13 -14
  532. package/src/components/currency-select.tsx +2 -7
  533. package/src/components/danger-confirm.tsx +8 -9
  534. package/src/components/data-table-cells.tsx +1 -2
  535. package/src/components/data-table-column-settings.tsx +1 -3
  536. package/src/components/data-table-filter-popover.tsx +5 -19
  537. package/src/components/data-table-filters.ts +1 -6
  538. package/src/components/data-table-fit.ts +1 -3
  539. package/src/components/data-table-groups.tsx +3 -1
  540. package/src/components/data-table-head.tsx +27 -45
  541. package/src/components/data-table-mobile.tsx +99 -108
  542. package/src/components/data-table-pagination.tsx +2 -6
  543. package/src/components/data-table-row-actions.tsx +25 -24
  544. package/src/components/data-table-row.tsx +16 -17
  545. package/src/components/data-table-shared.tsx +10 -16
  546. package/src/components/data-table-sort.ts +1 -2
  547. package/src/components/data-table-virtual.ts +9 -4
  548. package/src/components/data-table.tsx +489 -501
  549. package/src/components/date-picker.tsx +1 -7
  550. package/src/components/date-range-picker.tsx +3 -13
  551. package/src/components/description-list.tsx +7 -13
  552. package/src/components/dialog-frame.tsx +12 -3
  553. package/src/components/disclosure.tsx +8 -12
  554. package/src/components/dropdown.tsx +3 -11
  555. package/src/components/empty-state.tsx +1 -3
  556. package/src/components/entity-combobox.tsx +2 -6
  557. package/src/components/error-boundary.tsx +7 -7
  558. package/src/components/field-base.tsx +8 -14
  559. package/src/components/field-parts.tsx +12 -23
  560. package/src/components/field-sync.tsx +7 -11
  561. package/src/components/file-button.tsx +7 -3
  562. package/src/components/file-dropzone.tsx +7 -12
  563. package/src/components/floating-panel.tsx +44 -51
  564. package/src/components/focus-ring.ts +1 -2
  565. package/src/components/form-actions.tsx +1 -4
  566. package/src/components/grouped-picker.tsx +6 -8
  567. package/src/components/hover-menu.tsx +1 -4
  568. package/src/components/iban-input-labels.ts +1 -2
  569. package/src/components/icon-button.tsx +46 -48
  570. package/src/components/icon-picker.tsx +4 -17
  571. package/src/components/image-grid.tsx +1 -6
  572. package/src/components/inline-edit-field.tsx +1 -5
  573. package/src/components/inline-entity-combobox.tsx +6 -21
  574. package/src/components/input.tsx +14 -2
  575. package/src/components/jump-calendar.tsx +2 -6
  576. package/src/components/legal-labels.ts +1 -2
  577. package/src/components/legal-page.tsx +18 -7
  578. package/src/components/legal.tsx +14 -5
  579. package/src/components/lightbox.tsx +1 -3
  580. package/src/components/line-items.tsx +7 -15
  581. package/src/components/list.tsx +29 -25
  582. package/src/components/measured-grid.tsx +8 -30
  583. package/src/components/menu-item.tsx +1 -3
  584. package/src/components/mini-calendar.tsx +129 -159
  585. package/src/components/money-field.tsx +4 -2
  586. package/src/components/month-picker.tsx +14 -21
  587. package/src/components/multi-entity-combobox.tsx +6 -26
  588. package/src/components/multi-select.tsx +5 -9
  589. package/src/components/nav-pills.tsx +10 -2
  590. package/src/components/number-field.tsx +18 -15
  591. package/src/components/number-input.tsx +3 -19
  592. package/src/components/numpad-sheet.tsx +9 -13
  593. package/src/components/one-time-code-input.tsx +6 -11
  594. package/src/components/page-contents.tsx +2 -9
  595. package/src/components/page-header.tsx +5 -10
  596. package/src/components/password-strength-labels.ts +1 -2
  597. package/src/components/password-strength.tsx +6 -9
  598. package/src/components/phone-input.tsx +2 -13
  599. package/src/components/picker-sheet.tsx +2 -5
  600. package/src/components/pie-chart.tsx +6 -12
  601. package/src/components/popover.tsx +2 -1
  602. package/src/components/progress-bar.tsx +16 -25
  603. package/src/components/qr-code.tsx +2 -9
  604. package/src/components/row-actions.tsx +9 -1
  605. package/src/components/search-field.tsx +4 -5
  606. package/src/components/select.tsx +2 -10
  607. package/src/components/separator.tsx +1 -5
  608. package/src/components/series-chart-axes.ts +5 -5
  609. package/src/components/series-chart-budget.ts +1 -4
  610. package/src/components/series-chart-ticks.ts +1 -4
  611. package/src/components/series-chart.tsx +43 -83
  612. package/src/components/settings-fields.tsx +20 -15
  613. package/src/components/share-card.tsx +6 -14
  614. package/src/components/sign-chip.tsx +16 -16
  615. package/src/components/signature-pad.tsx +21 -13
  616. package/src/components/signed-amount.tsx +6 -14
  617. package/src/components/skeleton.tsx +2 -13
  618. package/src/components/slider.tsx +9 -20
  619. package/src/components/sparkline.tsx +2 -13
  620. package/src/components/stat-tile.tsx +13 -24
  621. package/src/components/swatch-picker.tsx +8 -3
  622. package/src/components/swipeable-row.tsx +2 -11
  623. package/src/components/table-skeleton.tsx +4 -1
  624. package/src/components/table.tsx +12 -8
  625. package/src/components/tabs.tsx +24 -39
  626. package/src/components/text-link.tsx +6 -6
  627. package/src/components/text.tsx +1 -2
  628. package/src/components/tile-radio.tsx +6 -19
  629. package/src/components/time-input.tsx +4 -5
  630. package/src/components/toast.tsx +3 -12
  631. package/src/components/toggle-group.tsx +9 -9
  632. package/src/components/toggle-legend.tsx +4 -16
  633. package/src/components/tooltip.tsx +9 -48
  634. package/src/components/translation-review-editor.tsx +4 -4
  635. package/src/components/translation-review-parts.tsx +7 -1
  636. package/src/components/translation-review.tsx +15 -16
  637. package/src/components/tree-view.tsx +17 -20
  638. package/src/components/treemap.tsx +59 -9
  639. package/src/components/trigger-aria.ts +1 -4
  640. package/src/components/use-table-state.ts +16 -17
  641. package/src/components/user-avatar.tsx +4 -21
  642. package/src/demo/demo-start.tsx +8 -4
  643. package/src/feedback/feedback-attachment-labels.ts +2 -1
  644. package/src/feedback/feedback-attachment.tsx +16 -29
  645. package/src/feedback/feedback-capture.ts +3 -1
  646. package/src/feedback/feedback-comment-thread.tsx +9 -6
  647. package/src/feedback/feedback-context.tsx +1 -4
  648. package/src/feedback/feedback-dialog.tsx +3 -4
  649. package/src/feedback/feedback-inbox.tsx +3 -9
  650. package/src/feedback/feedback-public-list.tsx +7 -1
  651. package/src/feedback/feedback-record.ts +6 -14
  652. package/src/feedback/feedback-replies.tsx +10 -5
  653. package/src/feedback/feedback-row-detail.tsx +2 -5
  654. package/src/feedback/feedback-status-undo.ts +1 -4
  655. package/src/feedback/feedback-submit-dialog.tsx +4 -4
  656. package/src/feedback/feedback-table.tsx +12 -8
  657. package/src/feedback/feedback-thread.tsx +4 -16
  658. package/src/feedback/feedback-vocabulary.ts +72 -82
  659. package/src/feedback/feedback-vote-button.tsx +9 -8
  660. package/src/hooks/use-anchored-rect.ts +1 -4
  661. package/src/hooks/use-document-title.ts +3 -1
  662. package/src/hooks/use-file-drop.ts +1 -3
  663. package/src/hooks/use-file-picker-labels.ts +1 -2
  664. package/src/hooks/use-file-picker.tsx +1 -5
  665. package/src/hooks/use-focus-trap.ts +1 -2
  666. package/src/hooks/use-overlay-history.ts +10 -5
  667. package/src/hooks/use-row-swipe.ts +1 -6
  668. package/src/i18n/defaults.ts +1 -4
  669. package/src/i18n/german.ts +33 -49
  670. package/src/i18n/kit-labels.tsx +5 -20
  671. package/src/i18n/languages.ts +2 -8
  672. package/src/i18n/locales/en.ts +11 -31
  673. package/src/i18n/locales/es.ts +35 -49
  674. package/src/i18n/locales/fr.ts +34 -51
  675. package/src/i18n/locales/hu.ts +26 -37
  676. package/src/i18n/locales/it.ts +35 -52
  677. package/src/i18n/locales/zh.ts +14 -32
  678. package/src/i18n/plurals.ts +4 -1
  679. package/src/i18n/review.ts +18 -7
  680. package/src/i18n/shared-labels.ts +1 -2
  681. package/src/index.ts +106 -32
  682. package/src/landing/access.ts +2 -7
  683. package/src/landing/landing-sections.tsx +14 -15
  684. package/src/landing/page-seo.ts +1 -3
  685. package/src/lib/calc.ts +4 -1
  686. package/src/lib/clipboard-minus.ts +4 -1
  687. package/src/lib/dates.ts +2 -10
  688. package/src/lib/decimal-marks.ts +1 -3
  689. package/src/lib/device-settings.ts +2 -1
  690. package/src/lib/direction.ts +1 -3
  691. package/src/lib/iban.ts +89 -9
  692. package/src/lib/logger.ts +1 -5
  693. package/src/lib/person-name.ts +1 -3
  694. package/src/lib/phone.ts +5 -8
  695. package/src/lib/qr-encode.ts +32 -8
  696. package/src/lib/session-refresh.ts +5 -6
  697. package/src/lib/table-text.ts +24 -6
  698. package/src/lib/text-match.ts +15 -3
  699. package/src/lib/translation-review.ts +1 -3
  700. package/src/notifications/notification-inbox.tsx +17 -4
  701. package/src/notifications/notification-parts.tsx +1 -2
  702. package/src/notifications/notification-types-setting.tsx +19 -18
  703. package/src/notifications/notifications-labels.ts +1 -2
  704. package/src/notifications/push-device-setting.tsx +7 -1
  705. package/src/notifications/push-devices-setting.tsx +7 -3
  706. package/src/notifications/push-worker.ts +10 -2
  707. package/src/notifications/quiet-hours-setting.tsx +4 -1
  708. package/src/notifications/use-push-device.ts +4 -1
  709. package/src/offline/pwa-update-prompt.tsx +7 -1
  710. package/src/offline/query-persistence.ts +9 -6
  711. package/src/offline.ts +6 -1
  712. package/src/rhf/fields.tsx +50 -19
  713. package/src/rhf/form-core.tsx +2 -6
  714. package/src/rhf/line-items.tsx +5 -7
  715. package/src/rhf/use-rhf-wizard-step.ts +3 -12
  716. package/src/search/command-palette.tsx +15 -23
  717. package/src/search/global-search.tsx +38 -8
  718. package/src/search/search-index.ts +5 -1
  719. package/src/settings/device-reset-setting.tsx +5 -8
  720. package/src/settings/settings-heading.tsx +3 -1
  721. package/src/settings/settings-layout.tsx +6 -13
  722. package/src/settings/use-settings-route.ts +4 -3
  723. package/src/shell/app-shell.tsx +48 -24
  724. package/src/shell/auth-layout.tsx +1 -6
  725. package/src/shell/dev-menu.tsx +12 -6
  726. package/src/shell/option-switcher-menu.tsx +1 -3
  727. package/src/shell/sync-status-indicator.tsx +14 -12
  728. package/src/shell/top-bar-parts-labels.ts +1 -3
  729. package/src/shell/topbar-action-menu.tsx +9 -8
  730. package/src/shell/topbar-controls.tsx +5 -19
  731. package/src/shell/tour-menu.tsx +9 -1
  732. package/src/sync/db.ts +5 -1
  733. package/src/sync/engine.ts +44 -12
  734. package/src/sync.ts +16 -2
  735. package/src/testing/css-variables.ts +1 -2
  736. package/src/testing/index.ts +1 -6
  737. package/src/testing/react.ts +1 -2
  738. package/src/testing/viewport.ts +9 -9
  739. package/src/theme/contrast-tokens.ts +13 -2
  740. package/src/theme/palette-derive.ts +24 -50
  741. package/src/theme/palette-presets.ts +0 -1
  742. package/src/theme/palette-store.ts +1 -4
  743. package/src/theme/text-size.ts +1 -1
  744. package/src/theme/theme-store.ts +2 -6
  745. package/src/tour/tour-catalogue.tsx +4 -2
  746. package/src/tour/tour-dock.ts +5 -1
  747. package/src/tour/tour-engine.ts +2 -6
  748. package/src/tour/tour.tsx +28 -12
  749. package/src/tour/use-tour-progress.ts +8 -2
  750. package/src/tour/use-tour-url-sync.ts +3 -1
  751. package/src/vite-env.d.ts +1 -4
  752. package/src/wizard/stepper-nav.tsx +10 -35
  753. package/src/wizard/types.ts +1 -4
  754. package/src/wizard/use-wizard.ts +28 -43
  755. package/src/wizard/validation.ts +1 -5
  756. package/src/wizard/wizard-context.tsx +2 -6
  757. package/src/wizard/wizard-step.tsx +1 -8
  758. package/src/wizard/wizard-summary.tsx +2 -6
  759. package/tokens.css +393 -152
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/session-refresh.ts"],"sourcesContent":["/**\n * Renewing a session when the access token runs out: the client half of\n * docs/auth-harmonization.md §11 (round 0.34 C7, KS U6), lifted from keksdose's\n * `refreshOnce` (Kurvenschmiede's is the same, line for line) and corrected where the\n * three apps' reviews found it wrong. It ends kastlan's sign-out over a network blip (B3).\n *\n * THE KIT OWNS THE RULE, THE APP OWNS THE CALL (§11.2, decision 1). The kit decides when\n * to refresh, who waits, what a failure means, when the session is over and whether a\n * renewal may still be stored. The app keeps its endpoint, its token storage, its\n * sign-out and where it navigates, and hands them in as {@link SessionRefreshOptions}.\n *\n * - **One flight per tab** (decision 2): every 401 that arrives while a refresh runs\n * waits for it, and so does `session.refresh()` (kastlan's boot).\n * - **Definitive** (decision 3): the device holds no refresh token (`refresh` resolves\n * `null`), the refresh answers 401 or 403, or the request replayed with the fresh\n * token gets a 401 again. Only then does the app sign out (`onEnded`), and only while\n * that session is still the app's.\n * - **Transient** (decision 4): everything else. The session stays: nothing is signed\n * out, stored or redirected, and the kit shows nothing. The request rejects with its\n * OWN 401, marked ({@link isTransientRefreshFailure}), so the app's message can say\n * \"can't reach the server\" instead of \"not signed in\".\n * - **Retries only where waiting helps** (decision 5, KS 7): no answer, the kit's own\n * timeout, 408, 429 and 5xx get up to three attempts, 1 s and then 3 s apart, each cut\n * off after 15 s; none while the browser reports itself offline. Any other answer, and\n * anything that is not an HTTP error, ends the flight at the first attempt.\n * - **A stale session is never written back** (§11.7, ka 3, KS 3, KS 4): every request\n * is stamped with `currentToken()` when it goes out, and every flight notes it when it\n * starts. A 401 to a request sent with an older token replays it with the app's token\n * now, without a refresh; a flight whose session changed while it ran stores nothing\n * and ends nothing. The access token is the session's identity because every change\n * the apps make replaces it — a refresh, another tab, a company switch, a password\n * change, a sign-in, a demo start, a sign-out.\n *\n * Framework-free like `server-wake.ts`: {@link attachSessionRefresh} takes the app's\n * axios instance as an ARGUMENT, typed structurally, so the kit never imports axios.\n */\n\nimport type { AxiosLikeInstance, ServerWakeAxiosConfig } from \"./server-wake\";\nimport { httpStatusOf } from \"../auth/auth-errors\";\n\n/** What the app's `refresh` resolves: the new access token, plus whatever its `store`\n * needs (its refresh token, the user). */\nexport interface SessionRenewal {\n /** The new access token; the waiting requests are replayed with it. */\n token: string;\n /**\n * `false`: store the renewal, but replay nothing — each waiting request rejects with\n * its 401, unmarked. kastlan's refresh can land in another company (§11.5, ka 3): a\n * waiting write, such as the handover's `POST /sync`, must not be replayed into it.\n */\n replay?: false;\n}\n\n/** What the app hands {@link createSessionRefresh} (§11.4). */\nexport interface SessionRefreshOptions<R extends SessionRenewal> {\n /**\n * The app's own `POST /auth/refresh`, on a BARE client — never the instance the kit is\n * attached to, so the refresh cannot re-enter the interceptor. It **writes nothing**:\n * the kit hands the answer to `store`, and only while the session is unchanged.\n *\n * Resolves the answer as a renewal, or `null` when the device holds no refresh token.\n * Throws on failure, and the kit classifies the throw: a 401 or 403 is definitive; no\n * answer (an axios error without a `response`), the kit's own timeout, 408, 429 and\n * 5xx are transient and retried; any other answer, and anything that is not an HTTP\n * error (a bug in this function), is transient and not retried. The status is read\n * from `err.response.status` (axios), `err.status` or `err.statusCode`.\n *\n * `signal` aborts when the attempt runs past `timeoutMs`; pass it to the request.\n */\n refresh: (signal: AbortSignal) => Promise<R | null>;\n /** Writes the renewal: the tokens and the user (a missing refresh token keeps the\n * stored one). Called only while the session the flight renews is still the app's,\n * and before the waiting requests are replayed — so it writes the token SYNCHRONOUSLY\n * where `currentToken` reads it: the replay goes through the app's own request\n * interceptor again, and is stamped then. A throw is the app's bug: the waiting\n * requests and `session.refresh()` reject with it. */\n store: (renewal: R) => void;\n /** The access token the app sends NOW, read where its request interceptor reads it;\n * `null` when there is none. */\n currentToken: () => string | null;\n /** Whether the session is a demo: a demo's 401 ends it, with no refresh tried\n * (landing-demo §5.5). */\n isDemo: () => boolean;\n /**\n * The session is over: drop the tokens and the user, then navigate — `/demo/ended` for\n * a demo, else the sign-in with the page it came from (auth §5.2). Called once per\n * session, however many requests found out (KS 8), and never by `session.refresh()`.\n */\n onEnded: (ended: { demo: boolean }) => void;\n /** Whether a URL is a signed-out step, whose 401 judges the form and never the\n * session. Replaces the default list, {@link isSignedOutStep}. */\n isSignedOutStep?: (url: string) => boolean;\n /** Attempts for a refresh that got no answer, timed out, or got a 408, 429 or 5xx.\n * Default 3. */\n attempts?: number;\n /** The waits before the second and later attempts; the last one repeats. Default\n * `[1000, 3000]`. */\n backoffMs?: readonly number[];\n /** Each attempt is cut off after this, and its `signal` aborted. Default 15 000. */\n timeoutMs?: number;\n}\n\n/** What `session.refresh()` resolves (§11.4), by `result`:\n *\n * | `result` | When | What the kit has done |\n * |---|---|---|\n * | `\"renewed\"` | a renewal while the session was unchanged | `store(renewal)` |\n * | `\"ended\"` | definitive | nothing; `onEnded` only for requests that waited on the same flight |\n * | `\"transient\"` | transient | nothing |\n * | `\"changed\"` | the session changed while it ran | nothing; read the app's own state |\n */\nexport type SessionRefreshOutcome<R extends SessionRenewal = SessionRenewal> =\n | { result: \"renewed\"; renewal: R }\n | { result: \"ended\" }\n | { result: \"transient\" }\n | { result: \"changed\" };\n\n/** The flight {@link createSessionRefresh} makes; {@link attachSessionRefresh} hooks it\n * to an axios instance. */\nexport interface SessionRefresh<R extends SessionRenewal = SessionRenewal> {\n /**\n * The same flight, for a caller outside the interceptor — kastlan's boot. Joins a\n * running flight, or starts one. Never calls `onEnded`: the caller decides what an\n * `\"ended\"` means for it.\n */\n refresh(): Promise<SessionRefreshOutcome<R>>;\n}\n\n// ── The signed-out steps ──────────────────────────────────────────────────────\n\n/**\n * Every `/auth/` call made without a session, the union of the three apps' lists\n * (§11.3): signing in (with its `2fa` and `set-password` steps, and a passkey's), up,\n * into a demo, a password reset, the verification link, the invitation check, the email\n * change's confirmation link, and the refresh itself. NOT `resend-verification` (KS 1):\n * in keksdose and Kurvenschmiede it needs a session; in kastlan it never answers 401.\n */\nconst SIGNED_OUT_STEPS = [\n \"login\",\n \"passkey/login\",\n \"register\",\n \"demo-session\",\n \"password-reset\",\n \"verify-email\",\n \"invitations/check\",\n \"me/email/confirm\",\n \"refresh\",\n] as const;\n\n/**\n * Whether a request's URL is a signed-out step — the kit's default list (§11.3), exported\n * for an app's tests and for an app's own `isSignedOutStep` that adds to it.\n *\n * **Whole steps only** (KS 2): the part of the path after its `auth/` segment, without\n * the query string, is the entry itself or starts with the entry and a `/`. So\n * `login/2fa` is `login`'s, but `register` never catches `/auth/passkey/register/begin`\n * (adding a passkey, which needs a session), `invitations/check` never\n * `/auth/invitations/accept`, and `me/email/confirm` never `/auth/me/email`. Relative and\n * absolute URLs alike; a URL with no `auth` segment is no step.\n */\nexport function isSignedOutStep(url: string): boolean {\n const path = url.replace(/[?#].*$/s, \"\").replace(/^([a-z][a-z\\d+.-]*:)?\\/\\/[^/]*/i, \"\");\n const segments = path.split(\"/\");\n const at = segments.indexOf(\"auth\");\n if (at < 0) return false;\n const step = segments.slice(at + 1).join(\"/\");\n return SIGNED_OUT_STEPS.some((entry) => step === entry || step.startsWith(`${entry}/`));\n}\n\n// ── The marker ────────────────────────────────────────────────────────────────\n\n/** On the request's own axios error, after a transient failure (decision 8). A\n * `Symbol.for` key: shared by every copy of the kit in a page, and left out of\n * `JSON.stringify`, so a log that serialises the error doesn't print it (kk 2). */\nconst TRANSIENT = Symbol.for(\"@eifi1/ui-kit:session-refresh.transient\");\n\n/**\n * Whether a request was refused because the refresh behind it failed TRANSIENTLY —\n * offline, a timeout, a 5xx — and not because the session is over (decision 8). The\n * error is the request's own 401, `err.response?.status` and every check an app already\n * has keep working; this reads the mark the kit put on it, so the app's message can say\n * \"can't reach the server\" instead of \"not signed in\". Read it FIRST: keksdose's sync\n * chip, kastlan's handover sync and Kurvenschmiede's `apiErrorMessage` count it as\n * offline (§11.5).\n *\n * Not the refresh's own error: its config carries the refresh token in its body, into any\n * log or crash report that keeps the error.\n */\nexport function isTransientRefreshFailure(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[TRANSIENT] === true;\n}\n\n// ── The flight ────────────────────────────────────────────────────────────────\n\n/** A flight's result, as the interceptor needs it: `\"ended\"` keeps the session it ended. */\ntype Flight<R extends SessionRenewal> =\n | { result: \"renewed\"; renewal: R }\n | { result: \"ended\"; token: string | null }\n | { result: \"transient\" }\n | { result: \"changed\" };\n\n/** What one attempt came to. */\ntype Attempt<R> = { renewal: R } | \"definitive\" | \"retry\" | \"transient\";\n\n/** What {@link attachSessionRefresh} needs of a session. Kept off the public interface:\n * only what {@link createSessionRefresh} made can be attached. */\ninterface Engine {\n token(): string | null;\n isDemo(): boolean;\n isSignedOutStep(url: string): boolean;\n join(): Promise<Flight<SessionRenewal>>;\n end(token: string | null, demo: boolean): void;\n}\n\nconst engines = new WeakMap<SessionRefresh<SessionRenewal>, Engine>();\n\n/** The kit's own timeout, told apart from anything the app's `refresh` throws. */\nconst TIMED_OUT = Symbol(\"timed out\");\n\nfunction isOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/** A refresh's throw, classified (§11.4). The status is read where `isRateLimited` reads\n * it — `httpStatusOf`, one probe for axios, ofetch and Node errors (DUP-11). */\nfunction classify(error: unknown): \"definitive\" | \"retry\" | \"transient\" {\n if (error === TIMED_OUT) return \"retry\";\n if (typeof error !== \"object\" || error === null) return \"transient\";\n const status = httpStatusOf(error);\n if (status === undefined) {\n // No answer: axios marks its own errors, and one without a response never reached a\n // server (offline, DNS, CORS, its own timeout). Anything else is a bug in `refresh`.\n return (error as { isAxiosError?: unknown }).isAxiosError === true ? \"retry\" : \"transient\";\n }\n if (status === 401 || status === 403) return \"definitive\";\n if (status === 408 || status === 429 || status >= 500) return \"retry\";\n return \"transient\";\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Make the flight: `const session = createSessionRefresh({ refresh, store, currentToken,\n * isDemo, onEnded })`, then {@link attachSessionRefresh}`(api, session)`. One per tab.\n */\nexport function createSessionRefresh<R extends SessionRenewal>(options: SessionRefreshOptions<R>): SessionRefresh<R> {\n const { attempts = 3, backoffMs = [1000, 3000], timeoutMs = 15_000 } = options;\n // An empty string is no token: the stamp and the flight compare tokens, and \"\" against\n // `null` must not read as a change of session.\n const token = () => options.currentToken() || null;\n\n /** One call of the app's `refresh`, cut off after `timeoutMs` even if it ignores the\n * signal. */\n const attempt = async (): Promise<Attempt<R>> => {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(TIMED_OUT);\n controller.abort();\n }, timeoutMs);\n });\n try {\n // Through `then`, so a `refresh` that throws before it returns a promise is\n // classified like one that rejects.\n const renewal = await Promise.race([Promise.resolve().then(() => options.refresh(controller.signal)), timeout]);\n return renewal ? { renewal } : \"definitive\";\n } catch (error) {\n return classify(error);\n } finally {\n clearTimeout(timer);\n }\n };\n\n const run = async (): Promise<Flight<R>> => {\n // The session this flight renews (§11.3 step 5).\n const noted = token();\n const changed = () => token() !== noted;\n let outcome = await attempt();\n for (let made = 1; outcome === \"retry\"; made += 1) {\n // No further attempt while the browser says it is offline, nor for a session that\n // is no longer the app's: whatever the answer, it would be \"changed\".\n if (made >= attempts || isOffline() || changed()) break;\n await sleep(backoffMs[made - 1] ?? backoffMs[backoffMs.length - 1] ?? 0);\n if (isOffline() || changed()) break;\n outcome = await attempt();\n }\n // A late answer never writes the old session back over a sign-out, a demo start or a\n // password change, and the old session's refusal never signs anyone out (KS 3).\n if (changed()) return { result: \"changed\" };\n if (outcome === \"definitive\") return { result: \"ended\", token: noted };\n if (outcome === \"retry\" || outcome === \"transient\") return { result: \"transient\" };\n options.store(outcome.renewal);\n return { result: \"renewed\", renewal: outcome.renewal };\n };\n\n let flight: Promise<Flight<R>> | null = null;\n const join = () => {\n // Cleared before any waiter resumes (`finally` settles first), so a waiter that\n // needs another flight starts a new one.\n flight ??= run().finally(() => {\n flight = null;\n });\n return flight;\n };\n\n /** The session `onEnded` was last called for: once per session (KS 8). */\n let ended: { token: string | null } | undefined;\n\n const session: SessionRefresh<R> = {\n async refresh() {\n const outcome = await join();\n return outcome.result === \"ended\" ? { result: \"ended\" } : outcome;\n },\n };\n engines.set(session, {\n token,\n isDemo: () => options.isDemo(),\n isSignedOutStep: options.isSignedOutStep ?? isSignedOutStep,\n join,\n end(endedToken, demo) {\n if (ended && ended.token === endedToken) return;\n ended = { token: endedToken };\n options.onEnded({ demo });\n },\n });\n return session;\n}\n\n// ── axios ─────────────────────────────────────────────────────────────────────\n\n/** The config fields the kit reads and writes — what axios's request config has. */\ninterface SessionRefreshAxiosConfig extends ServerWakeAxiosConfig {\n /** axios's `AxiosHeaders` (written through its `set`), or a plain record. */\n headers?: unknown;\n}\n\n/** An axios instance, structurally: {@link AxiosLikeInstance}, plus `request(config)` for\n * the replay. `axios.create()`'s result fits it as is. `NoInfer`, because axios's\n * `request` takes the WIDER `AxiosRequestConfig`: inferred from there, the config type\n * no longer fits the interceptors, which hand out `InternalAxiosRequestConfig`. */\ninterface SessionRefreshInstance<C extends SessionRefreshAxiosConfig, R extends { config: C }>\n extends AxiosLikeInstance<C, R> {\n request(config: NoInfer<C>): Promise<unknown>;\n}\n\n/** The keys the kit keeps on a request's config, as `attachServerWake` keeps\n * `_serverWake`: never a header. Plain string keys holding primitives, because axios\n * copies the config on a replay (`mergeConfig`) and a symbol key would be dropped. */\nconst STAMP = \"_sessionStamp\";\nconst REFRESHED = \"_sessionRefreshed\";\nconst RESTAMPED = \"_sessionRestamped\";\ntype Marked = {\n /** `currentToken()` when the request went out. */\n [STAMP]?: string | null;\n /** Replayed after a refresh: a 401 now is definitive (decision 3). */\n [REFRESHED]?: boolean;\n /** Replayed because it was sent with an older token: once for this reason. */\n [RESTAMPED]?: boolean;\n};\n\n/** `Authorization: Bearer <token>` on a config about to be replayed. The app's own\n * request interceptor runs again on the replay and writes the same, from the same\n * source. */\nfunction authorize(config: SessionRefreshAxiosConfig, token: string): void {\n const value = `Bearer ${token}`;\n const headers = config.headers;\n if (typeof headers !== \"object\" || headers === null) {\n config.headers = { Authorization: value };\n } else if (typeof (headers as { set?: unknown }).set === \"function\") {\n (headers as { set(name: string, value: string): unknown }).set(\"Authorization\", value);\n } else {\n (headers as Record<string, unknown>).Authorization = value;\n }\n}\n\n/**\n * Hook a session to an axios instance: `attachSessionRefresh(api, session)`. Adds a\n * request interceptor (the stamp) and a response interceptor (the 401), and returns a\n * function that ejects both.\n *\n * Attach it LAST (§11.3, kk 4): after `attachServerWake`, which asks to be first, and\n * after the app's own response interceptors (logging, a watchdog of its own). axios runs\n * response interceptors in the order they were added, and each of those must see the 401\n * settle before the refresh is awaited. The request side's order does not matter.\n *\n * On a 401, in this order (§11.3):\n *\n * 1. a signed-out step → reject, nothing else;\n * 2. sent with an older token → replayed with the app's token now, with no refresh, once\n * for this reason; with no token now, reject;\n * 3. a demo → `onEnded({ demo: true })`, reject;\n * 4. already replayed after a refresh → definitive: `onEnded({ demo: false })`, reject;\n * 5. otherwise it joins the flight, or starts it. A renewal replays it once with the\n * renewal's token (`replay: false`: rejects, unmarked); definitive ends the session;\n * transient rejects, marked; a session that changed meanwhile sends it through step\n * 2 again.\n *\n * Every rejection is the request's OWN error. Any other status passes through untouched.\n */\nexport function attachSessionRefresh<C extends SessionRefreshAxiosConfig, R extends { config: C }>(\n instance: SessionRefreshInstance<C, R>,\n session: SessionRefresh<SessionRenewal>,\n): () => void {\n const engine = engines.get(session);\n if (!engine) throw new TypeError(\"attachSessionRefresh takes the session createSessionRefresh made\");\n\n const onUnauthorized = async (error: object, config: C & Marked): Promise<unknown> => {\n if (engine.isSignedOutStep(config.url ?? \"\")) throw error;\n // A config the kit never stamped (sent before it was attached) counts as current.\n const stamp = config[STAMP] === undefined ? engine.token() : config[STAMP];\n const replay = (token: string) => {\n authorize(config, token);\n return instance.request(config);\n };\n for (;;) {\n const now = engine.token();\n // 2. The session it was sent for is gone, and whatever ended it has already done\n // what follows (ka 3, KS 3, KS 4).\n if (stamp !== now) {\n if (now === null || config[RESTAMPED]) throw error;\n config[RESTAMPED] = true;\n return replay(now);\n }\n // 3. A demo has nothing to refresh: its token lives as long as its account\n // (landing-demo §5.5).\n if (engine.isDemo()) {\n engine.end(now, true);\n throw error;\n }\n // 4. A replay for an older token doesn't count here: the app's current token may\n // simply have expired too, which needs a refresh, not a sign-out.\n if (config[REFRESHED]) {\n engine.end(now, false);\n throw error;\n }\n // 5. The flight.\n const flight = await engine.join();\n if (flight.result === \"changed\") continue;\n if (flight.result === \"ended\") {\n engine.end(flight.token, false);\n throw error;\n }\n if (flight.result === \"transient\") {\n (error as Record<symbol, unknown>)[TRANSIENT] = true;\n throw error;\n }\n if (flight.renewal.replay === false) throw error;\n config[REFRESHED] = true;\n return replay(flight.renewal.token);\n }\n };\n\n const request = instance.interceptors.request.use(\n (config) => {\n (config as C & Marked)[STAMP] = engine.token();\n return config;\n },\n (error) => Promise.reject(error),\n );\n const response = instance.interceptors.response.use(\n (res) => res,\n (error) => {\n const failed = error as { config?: C & Marked; response?: { status?: unknown } } | null;\n if (failed?.response?.status !== 401 || !failed.config) return Promise.reject(error);\n return onUnauthorized(failed, failed.config);\n },\n );\n return () => {\n instance.interceptors.request.eject(request);\n instance.interceptors.response.eject(response);\n };\n}\n"],"mappings":";AAsCA,SAAS,oBAAoB;AAmG7B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AQ,OAAO,MAAM;AAAA,IAC7C;AAAA,EACF;AACA,SAAO,MAAM;AACX,aAAS,aAAa,QAAQ,MAAM,OAAO;AAC3C,aAAS,aAAa,SAAS,MAAM,QAAQ;AAAA,EAC/C;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/lib/session-refresh.ts"],"sourcesContent":["/**\n * Renewing a session when the access token runs out: the client half of\n * docs/auth-harmonization.md §11 (round 0.34 C7, KS U6), lifted from keksdose's\n * `refreshOnce` (Kurvenschmiede's is the same, line for line) and corrected where the\n * three apps' reviews found it wrong. It ends kastlan's sign-out over a network blip (B3).\n *\n * THE KIT OWNS THE RULE, THE APP OWNS THE CALL (§11.2, decision 1). The kit decides when\n * to refresh, who waits, what a failure means, when the session is over and whether a\n * renewal may still be stored. The app keeps its endpoint, its token storage, its\n * sign-out and where it navigates, and hands them in as {@link SessionRefreshOptions}.\n *\n * - **One flight per tab** (decision 2): every 401 that arrives while a refresh runs\n * waits for it, and so does `session.refresh()` (kastlan's boot).\n * - **Definitive** (decision 3): the device holds no refresh token (`refresh` resolves\n * `null`), the refresh answers 401 or 403, or the request replayed with the fresh\n * token gets a 401 again. Only then does the app sign out (`onEnded`), and only while\n * that session is still the app's.\n * - **Transient** (decision 4): everything else. The session stays: nothing is signed\n * out, stored or redirected, and the kit shows nothing. The request rejects with its\n * OWN 401, marked ({@link isTransientRefreshFailure}), so the app's message can say\n * \"can't reach the server\" instead of \"not signed in\".\n * - **Retries only where waiting helps** (decision 5, KS 7): no answer, the kit's own\n * timeout, 408, 429 and 5xx get up to three attempts, 1 s and then 3 s apart, each cut\n * off after 15 s; none while the browser reports itself offline. Any other answer, and\n * anything that is not an HTTP error, ends the flight at the first attempt.\n * - **A stale session is never written back** (§11.7, ka 3, KS 3, KS 4): every request\n * is stamped with `currentToken()` when it goes out, and every flight notes it when it\n * starts. A 401 to a request sent with an older token replays it with the app's token\n * now, without a refresh; a flight whose session changed while it ran stores nothing\n * and ends nothing. The access token is the session's identity because every change\n * the apps make replaces it — a refresh, another tab, a company switch, a password\n * change, a sign-in, a demo start, a sign-out.\n *\n * Framework-free like `server-wake.ts`: {@link attachSessionRefresh} takes the app's\n * axios instance as an ARGUMENT, typed structurally, so the kit never imports axios.\n */\n\nimport type { AxiosLikeInstance, ServerWakeAxiosConfig } from \"./server-wake\";\nimport { httpStatusOf } from \"../auth/auth-errors\";\n\n/** What the app's `refresh` resolves: the new access token, plus whatever its `store`\n * needs (its refresh token, the user). */\nexport interface SessionRenewal {\n /** The new access token; the waiting requests are replayed with it. */\n token: string;\n /**\n * `false`: store the renewal, but replay nothing — each waiting request rejects with\n * its 401, unmarked. kastlan's refresh can land in another company (§11.5, ka 3): a\n * waiting write, such as the handover's `POST /sync`, must not be replayed into it.\n */\n replay?: false;\n}\n\n/** What the app hands {@link createSessionRefresh} (§11.4). */\nexport interface SessionRefreshOptions<R extends SessionRenewal> {\n /**\n * The app's own `POST /auth/refresh`, on a BARE client — never the instance the kit is\n * attached to, so the refresh cannot re-enter the interceptor. It **writes nothing**:\n * the kit hands the answer to `store`, and only while the session is unchanged.\n *\n * Resolves the answer as a renewal, or `null` when the device holds no refresh token.\n * Throws on failure, and the kit classifies the throw: a 401 or 403 is definitive; no\n * answer (an axios error without a `response`), the kit's own timeout, 408, 429 and\n * 5xx are transient and retried; any other answer, and anything that is not an HTTP\n * error (a bug in this function), is transient and not retried. The status is read\n * from `err.response.status` (axios), `err.status` or `err.statusCode`.\n *\n * `signal` aborts when the attempt runs past `timeoutMs`; pass it to the request.\n */\n refresh: (signal: AbortSignal) => Promise<R | null>;\n /** Writes the renewal: the tokens and the user (a missing refresh token keeps the\n * stored one). Called only while the session the flight renews is still the app's,\n * and before the waiting requests are replayed — so it writes the token SYNCHRONOUSLY\n * where `currentToken` reads it: the replay goes through the app's own request\n * interceptor again, and is stamped then. A throw is the app's bug: the waiting\n * requests and `session.refresh()` reject with it. */\n store: (renewal: R) => void;\n /** The access token the app sends NOW, read where its request interceptor reads it;\n * `null` when there is none. */\n currentToken: () => string | null;\n /** Whether the session is a demo: a demo's 401 ends it, with no refresh tried\n * (landing-demo §5.5). */\n isDemo: () => boolean;\n /**\n * The session is over: drop the tokens and the user, then navigate — `/demo/ended` for\n * a demo, else the sign-in with the page it came from (auth §5.2). Called once per\n * session, however many requests found out (KS 8), and never by `session.refresh()`.\n */\n onEnded: (ended: { demo: boolean }) => void;\n /** Whether a URL is a signed-out step, whose 401 judges the form and never the\n * session. Replaces the default list, {@link isSignedOutStep}. */\n isSignedOutStep?: (url: string) => boolean;\n /** Attempts for a refresh that got no answer, timed out, or got a 408, 429 or 5xx.\n * Default 3. */\n attempts?: number;\n /** The waits before the second and later attempts; the last one repeats. Default\n * `[1000, 3000]`. */\n backoffMs?: readonly number[];\n /** Each attempt is cut off after this, and its `signal` aborted. Default 15 000. */\n timeoutMs?: number;\n}\n\n/** What `session.refresh()` resolves (§11.4), by `result`:\n *\n * | `result` | When | What the kit has done |\n * |---|---|---|\n * | `\"renewed\"` | a renewal while the session was unchanged | `store(renewal)` |\n * | `\"ended\"` | definitive | nothing; `onEnded` only for requests that waited on the same flight |\n * | `\"transient\"` | transient | nothing |\n * | `\"changed\"` | the session changed while it ran | nothing; read the app's own state |\n */\nexport type SessionRefreshOutcome<R extends SessionRenewal = SessionRenewal> =\n { result: \"renewed\"; renewal: R } | { result: \"ended\" } | { result: \"transient\" } | { result: \"changed\" };\n\n/** The flight {@link createSessionRefresh} makes; {@link attachSessionRefresh} hooks it\n * to an axios instance. */\nexport interface SessionRefresh<R extends SessionRenewal = SessionRenewal> {\n /**\n * The same flight, for a caller outside the interceptor — kastlan's boot. Joins a\n * running flight, or starts one. Never calls `onEnded`: the caller decides what an\n * `\"ended\"` means for it.\n */\n refresh(): Promise<SessionRefreshOutcome<R>>;\n}\n\n// ── The signed-out steps ──────────────────────────────────────────────────────\n\n/**\n * Every `/auth/` call made without a session, the union of the three apps' lists\n * (§11.3): signing in (with its `2fa` and `set-password` steps, and a passkey's), up,\n * into a demo, a password reset, the verification link, the invitation check, the email\n * change's confirmation link, and the refresh itself. NOT `resend-verification` (KS 1):\n * in keksdose and Kurvenschmiede it needs a session; in kastlan it never answers 401.\n */\nconst SIGNED_OUT_STEPS = [\n \"login\",\n \"passkey/login\",\n \"register\",\n \"demo-session\",\n \"password-reset\",\n \"verify-email\",\n \"invitations/check\",\n \"me/email/confirm\",\n \"refresh\",\n] as const;\n\n/**\n * Whether a request's URL is a signed-out step — the kit's default list (§11.3), exported\n * for an app's tests and for an app's own `isSignedOutStep` that adds to it.\n *\n * **Whole steps only** (KS 2): the part of the path after its `auth/` segment, without\n * the query string, is the entry itself or starts with the entry and a `/`. So\n * `login/2fa` is `login`'s, but `register` never catches `/auth/passkey/register/begin`\n * (adding a passkey, which needs a session), `invitations/check` never\n * `/auth/invitations/accept`, and `me/email/confirm` never `/auth/me/email`. Relative and\n * absolute URLs alike; a URL with no `auth` segment is no step.\n */\nexport function isSignedOutStep(url: string): boolean {\n const path = url.replace(/[?#].*$/s, \"\").replace(/^([a-z][a-z\\d+.-]*:)?\\/\\/[^/]*/i, \"\");\n const segments = path.split(\"/\");\n const at = segments.indexOf(\"auth\");\n if (at < 0) return false;\n const step = segments.slice(at + 1).join(\"/\");\n return SIGNED_OUT_STEPS.some((entry) => step === entry || step.startsWith(`${entry}/`));\n}\n\n// ── The marker ────────────────────────────────────────────────────────────────\n\n/** On the request's own axios error, after a transient failure (decision 8). A\n * `Symbol.for` key: shared by every copy of the kit in a page, and left out of\n * `JSON.stringify`, so a log that serialises the error doesn't print it (kk 2). */\nconst TRANSIENT = Symbol.for(\"@eifi1/ui-kit:session-refresh.transient\");\n\n/**\n * Whether a request was refused because the refresh behind it failed TRANSIENTLY —\n * offline, a timeout, a 5xx — and not because the session is over (decision 8). The\n * error is the request's own 401, `err.response?.status` and every check an app already\n * has keep working; this reads the mark the kit put on it, so the app's message can say\n * \"can't reach the server\" instead of \"not signed in\". Read it FIRST: keksdose's sync\n * chip, kastlan's handover sync and Kurvenschmiede's `apiErrorMessage` count it as\n * offline (§11.5).\n *\n * Not the refresh's own error: its config carries the refresh token in its body, into any\n * log or crash report that keeps the error.\n */\nexport function isTransientRefreshFailure(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[TRANSIENT] === true;\n}\n\n// ── The flight ────────────────────────────────────────────────────────────────\n\n/** A flight's result, as the interceptor needs it: `\"ended\"` keeps the session it ended. */\ntype Flight<R extends SessionRenewal> =\n | { result: \"renewed\"; renewal: R }\n | { result: \"ended\"; token: string | null }\n | { result: \"transient\" }\n | { result: \"changed\" };\n\n/** What one attempt came to. */\ntype Attempt<R> = { renewal: R } | \"definitive\" | \"retry\" | \"transient\";\n\n/** What {@link attachSessionRefresh} needs of a session. Kept off the public interface:\n * only what {@link createSessionRefresh} made can be attached. */\ninterface Engine {\n token(): string | null;\n isDemo(): boolean;\n isSignedOutStep(url: string): boolean;\n join(): Promise<Flight<SessionRenewal>>;\n end(token: string | null, demo: boolean): void;\n}\n\nconst engines = new WeakMap<SessionRefresh<SessionRenewal>, Engine>();\n\n/** The kit's own timeout, told apart from anything the app's `refresh` throws. */\nconst TIMED_OUT = Symbol(\"timed out\");\n\nfunction isOffline(): boolean {\n return typeof navigator !== \"undefined\" && navigator.onLine === false;\n}\n\n/** A refresh's throw, classified (§11.4). The status is read where `isRateLimited` reads\n * it — `httpStatusOf`, one probe for axios, ofetch and Node errors (DUP-11). */\nfunction classify(error: unknown): \"definitive\" | \"retry\" | \"transient\" {\n if (error === TIMED_OUT) return \"retry\";\n if (typeof error !== \"object\" || error === null) return \"transient\";\n const status = httpStatusOf(error);\n if (status === undefined) {\n // No answer: axios marks its own errors, and one without a response never reached a\n // server (offline, DNS, CORS, its own timeout). Anything else is a bug in `refresh`.\n return (error as { isAxiosError?: unknown }).isAxiosError === true ? \"retry\" : \"transient\";\n }\n if (status === 401 || status === 403) return \"definitive\";\n if (status === 408 || status === 429 || status >= 500) return \"retry\";\n return \"transient\";\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Make the flight: `const session = createSessionRefresh({ refresh, store, currentToken,\n * isDemo, onEnded })`, then {@link attachSessionRefresh}`(api, session)`. One per tab.\n */\nexport function createSessionRefresh<R extends SessionRenewal>(options: SessionRefreshOptions<R>): SessionRefresh<R> {\n const { attempts = 3, backoffMs = [1000, 3000], timeoutMs = 15_000 } = options;\n // An empty string is no token: the stamp and the flight compare tokens, and \"\" against\n // `null` must not read as a change of session.\n const token = () => options.currentToken() || null;\n\n /** One call of the app's `refresh`, cut off after `timeoutMs` even if it ignores the\n * signal. */\n const attempt = async (): Promise<Attempt<R>> => {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(TIMED_OUT);\n controller.abort();\n }, timeoutMs);\n });\n try {\n // Through `then`, so a `refresh` that throws before it returns a promise is\n // classified like one that rejects.\n const renewal = await Promise.race([Promise.resolve().then(() => options.refresh(controller.signal)), timeout]);\n return renewal ? { renewal } : \"definitive\";\n } catch (error) {\n return classify(error);\n } finally {\n clearTimeout(timer);\n }\n };\n\n const run = async (): Promise<Flight<R>> => {\n // The session this flight renews (§11.3 step 5).\n const noted = token();\n const changed = () => token() !== noted;\n let outcome = await attempt();\n for (let made = 1; outcome === \"retry\"; made += 1) {\n // No further attempt while the browser says it is offline, nor for a session that\n // is no longer the app's: whatever the answer, it would be \"changed\".\n if (made >= attempts || isOffline() || changed()) break;\n await sleep(backoffMs[made - 1] ?? backoffMs[backoffMs.length - 1] ?? 0);\n if (isOffline() || changed()) break;\n outcome = await attempt();\n }\n // A late answer never writes the old session back over a sign-out, a demo start or a\n // password change, and the old session's refusal never signs anyone out (KS 3).\n if (changed()) return { result: \"changed\" };\n if (outcome === \"definitive\") return { result: \"ended\", token: noted };\n if (outcome === \"retry\" || outcome === \"transient\") return { result: \"transient\" };\n options.store(outcome.renewal);\n return { result: \"renewed\", renewal: outcome.renewal };\n };\n\n let flight: Promise<Flight<R>> | null = null;\n const join = () => {\n // Cleared before any waiter resumes (`finally` settles first), so a waiter that\n // needs another flight starts a new one.\n flight ??= run().finally(() => {\n flight = null;\n });\n return flight;\n };\n\n /** The session `onEnded` was last called for: once per session (KS 8). */\n let ended: { token: string | null } | undefined;\n\n const session: SessionRefresh<R> = {\n async refresh() {\n const outcome = await join();\n return outcome.result === \"ended\" ? { result: \"ended\" } : outcome;\n },\n };\n engines.set(session, {\n token,\n isDemo: () => options.isDemo(),\n isSignedOutStep: options.isSignedOutStep ?? isSignedOutStep,\n join,\n end(endedToken, demo) {\n if (ended && ended.token === endedToken) return;\n ended = { token: endedToken };\n options.onEnded({ demo });\n },\n });\n return session;\n}\n\n// ── axios ─────────────────────────────────────────────────────────────────────\n\n/** The config fields the kit reads and writes — what axios's request config has. */\ninterface SessionRefreshAxiosConfig extends ServerWakeAxiosConfig {\n /** axios's `AxiosHeaders` (written through its `set`), or a plain record. */\n headers?: unknown;\n}\n\n/** An axios instance, structurally: {@link AxiosLikeInstance}, plus `request(config)` for\n * the replay. `axios.create()`'s result fits it as is. `NoInfer`, because axios's\n * `request` takes the WIDER `AxiosRequestConfig`: inferred from there, the config type\n * no longer fits the interceptors, which hand out `InternalAxiosRequestConfig`. */\ninterface SessionRefreshInstance<\n C extends SessionRefreshAxiosConfig,\n R extends { config: C },\n> extends AxiosLikeInstance<C, R> {\n request(config: NoInfer<C>): Promise<unknown>;\n}\n\n/** The keys the kit keeps on a request's config, as `attachServerWake` keeps\n * `_serverWake`: never a header. Plain string keys holding primitives, because axios\n * copies the config on a replay (`mergeConfig`) and a symbol key would be dropped. */\nconst STAMP = \"_sessionStamp\";\nconst REFRESHED = \"_sessionRefreshed\";\nconst RESTAMPED = \"_sessionRestamped\";\ntype Marked = {\n /** `currentToken()` when the request went out. */\n [STAMP]?: string | null;\n /** Replayed after a refresh: a 401 now is definitive (decision 3). */\n [REFRESHED]?: boolean;\n /** Replayed because it was sent with an older token: once for this reason. */\n [RESTAMPED]?: boolean;\n};\n\n/** `Authorization: Bearer <token>` on a config about to be replayed. The app's own\n * request interceptor runs again on the replay and writes the same, from the same\n * source. */\nfunction authorize(config: SessionRefreshAxiosConfig, token: string): void {\n const value = `Bearer ${token}`;\n const headers = config.headers;\n if (typeof headers !== \"object\" || headers === null) {\n config.headers = { Authorization: value };\n } else if (typeof (headers as { set?: unknown }).set === \"function\") {\n (headers as { set(name: string, value: string): unknown }).set(\"Authorization\", value);\n } else {\n (headers as Record<string, unknown>).Authorization = value;\n }\n}\n\n/**\n * Hook a session to an axios instance: `attachSessionRefresh(api, session)`. Adds a\n * request interceptor (the stamp) and a response interceptor (the 401), and returns a\n * function that ejects both.\n *\n * Attach it LAST (§11.3, kk 4): after `attachServerWake`, which asks to be first, and\n * after the app's own response interceptors (logging, a watchdog of its own). axios runs\n * response interceptors in the order they were added, and each of those must see the 401\n * settle before the refresh is awaited. The request side's order does not matter.\n *\n * On a 401, in this order (§11.3):\n *\n * 1. a signed-out step → reject, nothing else;\n * 2. sent with an older token → replayed with the app's token now, with no refresh, once\n * for this reason; with no token now, reject;\n * 3. a demo → `onEnded({ demo: true })`, reject;\n * 4. already replayed after a refresh → definitive: `onEnded({ demo: false })`, reject;\n * 5. otherwise it joins the flight, or starts it. A renewal replays it once with the\n * renewal's token (`replay: false`: rejects, unmarked); definitive ends the session;\n * transient rejects, marked; a session that changed meanwhile sends it through step\n * 2 again.\n *\n * Every rejection is the request's OWN error. Any other status passes through untouched.\n */\nexport function attachSessionRefresh<C extends SessionRefreshAxiosConfig, R extends { config: C }>(\n instance: SessionRefreshInstance<C, R>,\n session: SessionRefresh<SessionRenewal>,\n): () => void {\n const engine = engines.get(session);\n if (!engine) throw new TypeError(\"attachSessionRefresh takes the session createSessionRefresh made\");\n\n const onUnauthorized = async (error: object, config: C & Marked): Promise<unknown> => {\n if (engine.isSignedOutStep(config.url ?? \"\")) throw error;\n // A config the kit never stamped (sent before it was attached) counts as current.\n const stamp = config[STAMP] === undefined ? engine.token() : config[STAMP];\n const replay = (token: string) => {\n authorize(config, token);\n return instance.request(config);\n };\n for (;;) {\n const now = engine.token();\n // 2. The session it was sent for is gone, and whatever ended it has already done\n // what follows (ka 3, KS 3, KS 4).\n if (stamp !== now) {\n if (now === null || config[RESTAMPED]) throw error;\n config[RESTAMPED] = true;\n return replay(now);\n }\n // 3. A demo has nothing to refresh: its token lives as long as its account\n // (landing-demo §5.5).\n if (engine.isDemo()) {\n engine.end(now, true);\n throw error;\n }\n // 4. A replay for an older token doesn't count here: the app's current token may\n // simply have expired too, which needs a refresh, not a sign-out.\n if (config[REFRESHED]) {\n engine.end(now, false);\n throw error;\n }\n // 5. The flight.\n const flight = await engine.join();\n if (flight.result === \"changed\") continue;\n if (flight.result === \"ended\") {\n engine.end(flight.token, false);\n throw error;\n }\n if (flight.result === \"transient\") {\n (error as Record<symbol, unknown>)[TRANSIENT] = true;\n throw error;\n }\n if (flight.renewal.replay === false) throw error;\n config[REFRESHED] = true;\n return replay(flight.renewal.token);\n }\n };\n\n const request = instance.interceptors.request.use(\n (config) => {\n (config as C & Marked)[STAMP] = engine.token();\n return config;\n },\n (error) => Promise.reject(error),\n );\n const response = instance.interceptors.response.use(\n (res) => res,\n (error) => {\n const failed = error as { config?: C & Marked; response?: { status?: unknown } } | null;\n if (failed?.response?.status !== 401 || !failed.config) return Promise.reject(error);\n return onUnauthorized(failed, failed.config);\n },\n );\n return () => {\n instance.interceptors.request.eject(request);\n instance.interceptors.response.eject(response);\n };\n}\n"],"mappings":";AAsCA,SAAS,oBAAoB;AAgG7B,MAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAaO,SAAS,gBAAgB,KAAsB;AACpD,QAAM,OAAO,IAAI,QAAQ,YAAY,EAAE,EAAE,QAAQ,mCAAmC,EAAE;AACtF,QAAM,WAAW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AAS,EAAG,OAAM;AAC7C,eAAO,SAAS,IAAI;AACpB,eAAO,OAAO,GAAG;AAAA,MACnB;AAGA,UAAI,OAAO,OAAO,GAAG;AACnB,eAAO,IAAI,KAAK,IAAI;AACpB,cAAM;AAAA,MACR;AAGA,UAAI,OAAO,SAAS,GAAG;AACrB,eAAO,IAAI,KAAK,KAAK;AACrB,cAAM;AAAA,MACR;AAEA,YAAM,SAAS,MAAM,OAAO,KAAK;AACjC,UAAI,OAAO,WAAW,UAAW;AACjC,UAAI,OAAO,WAAW,SAAS;AAC7B,eAAO,IAAI,OAAO,OAAO,KAAK;AAC9B,cAAM;AAAA,MACR;AACA,UAAI,OAAO,WAAW,aAAa;AACjC,QAAC,MAAkC,SAAS,IAAI;AAChD,cAAM;AAAA,MACR;AACA,UAAI,OAAO,QAAQ,WAAW,MAAO,OAAM;AAC3C,aAAO,SAAS,IAAI;AACpB,aAAO,OAAO,OAAO,QAAQ,KAAK;AAAA,IACpC;AAAA,EACF;AAEA,QAAM,UAAU,SAAS,aAAa,QAAQ;AAAA,IAC5C,CAAC,WAAW;AACV,MAAC,OAAsB,KAAK,IAAI,OAAO,MAAM;AAC7C,aAAO;AAAA,IACT;AAAA,IACA,CAAC,UAAU,QAAQ,OAAO,KAAK;AAAA,EACjC;AACA,QAAM,WAAW,SAAS,aAAa,SAAS;AAAA,IAC9C,CAAC,QAAQ;AAAA,IACT,CAAC,UAAU;AACT,YAAM,SAAS;AACf,UAAI,QAAQ,UAAU,WAAW,OAAO,CAAC,OAAO,OAAQ,QAAO,QAAQ,OAAO,KAAK;AACnF,aAAO,eAAe,QAAQ,OAAO,MAAM;AAAA,IAC7C;AAAA,EACF;AACA,SAAO,MAAM;AACX,aAAS,aAAa,QAAQ,MAAM,OAAO;AAC3C,aAAS,aAAa,SAAS,MAAM,QAAQ;AAAA,EAC/C;AACF;","names":[]}
@@ -75,7 +75,15 @@ const point = (field) => field.replace(",", ".");
75
75
  function parseTextTable(text, options = {}) {
76
76
  const content = textLines(text);
77
77
  if (!content.length) {
78
- return { header: null, rows: [], lines: [], width: 0, separator: options.separator ?? ",", decimalComma: false, unread: [] };
78
+ return {
79
+ header: null,
80
+ rows: [],
81
+ lines: [],
82
+ width: 0,
83
+ separator: options.separator ?? ",",
84
+ decimalComma: false,
85
+ unread: []
86
+ };
79
87
  }
80
88
  const separator = options.separator ?? votedSeparator(content);
81
89
  const decimalComma = options.decimalComma ?? (separator !== "," && DECIMAL_COMMA.test(content.map((entry) => entry.line).join("\n")));
@@ -90,7 +98,10 @@ function parseTextTable(text, options = {}) {
90
98
  const unread = split.slice(0, first).map(({ entry }) => entry);
91
99
  const body = split.slice(first);
92
100
  const fitting = body.filter(({ cells }) => cells.length === width);
93
- const header = options.header ?? looksLikeHeader(fitting[0].cells, fitting.slice(1, 21).map(({ cells }) => cells));
101
+ const header = options.header ?? looksLikeHeader(
102
+ fitting[0].cells,
103
+ fitting.slice(1, 21).map(({ cells }) => cells)
104
+ );
94
105
  const rows = [];
95
106
  const lines = [];
96
107
  body.forEach(({ cells, entry }, index) => {
@@ -133,7 +144,8 @@ function votedSeparator(lines) {
133
144
  }
134
145
  const withoutQuoted = (line) => line.replace(/"(?:[^"]|"")*"/g, '""');
135
146
  function cellsOf(line, separator) {
136
- if (separator === " ") return line.split(/\s+/).filter((field) => field !== "").map(unquote);
147
+ if (separator === " ")
148
+ return line.split(/\s+/).filter((field) => field !== "").map(unquote);
137
149
  const cells = [];
138
150
  let cell = "";
139
151
  let quoted = false;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/table-text.ts"],"sourcesContent":["/**\n * One lexer for \"paste the table out of a spreadsheet\", and the three rules for the\n * comma. `@eifi1/ui-kit/table-text` — pure functions over strings, no React.\n *\n * Moved here from Lenkbank (`shared/lib/parse-table.ts`), where three screens took a\n * table off somebody's clipboard — a measured-table grid, the text view beside it, and\n * a page that reads a recorder's setpoint/actual files — and each had grown its own\n * reader. They disagreed, and not in the harmless way: a whitespace-separated German\n * export was read as six columns of nonsense by two of them and as nothing at all by\n * the third, with no message either way. The lexing is one problem (lines, a\n * separator, fields, a header, numbers) and it is solved once here, so the next app\n * that imports a CSV does not write the comma rules wrong a second time.\n *\n * **What is genuinely different between callers is where the decision about the\n * comma is taken**, and that is a parameter rather than a constant. A comma is the\n * decimal mark in every German export and the column separator in every English CSV,\n * and no single rule serves both without regressing one of them. So the rules are\n * named instead of one being picked:\n *\n * * **`\"whole-text\"`** — the *file* door. A recorder writes one file in one\n * convention, so the separator and the decimal mark are decided once, from the\n * whole text, and stated back to the reader (`decimalComma`) where they can see\n * what was assumed. Deciding once is what lets one damaged line be *counted*\n * rather than re-guessed into a different convention than the lines around it.\n * * **`\"per-line\"`** — the *paste* door. What arrives on a clipboard is a few rows\n * out of a spreadsheet, sometimes one row, sometimes a line somebody typed. There\n * is no file to be consistent with, and a line must not change meaning because of\n * another line somewhere else in the box — so each line is read on its own\n * evidence.\n * * **unconditional** — one cell (`cellNumber` / `isCellNumber`). A single cell has\n * no columns in it, so a comma in one cannot be separating anything and is always\n * a decimal mark. That is not a table rule at all, which is why it is a pair of\n * one-liners beside the others rather than an option on them.\n *\n * What this deliberately does not do:\n *\n * * **Thousands separators.** `1.234,5` and `1,234.5` are both a number with two\n * marks in it, and telling the grouping mark from the decimal mark needs a rule\n * about digit runs that would then have to be right for a three-digit integer\n * too. A field carrying one is reported as a line that could not be read, with\n * its line number, which is something a reader can act on. Guessing is not.\n * * **Empty cells.** An empty field is dropped rather than held open as a hole, so a\n * row with a dropped channel in the middle of it shifts left. Keeping the hole\n * would mean reading `1;2;3;` — a trailing separator, which every spreadsheet\n * writes — as a four-column row. It is a known gap, not an oversight.\n * * **Quoted fields.** No `\"a;b\"` escaping. These are numbers; the only text in them\n * is the header line, and a header field with a separator in it costs a column\n * name, not a measurement.\n *\n * Both of those are the NUMERIC lexer's limits. A table whose cells are text — a bank\n * export, read for a column mapper — needs both, and {@link parseTextTable} (0.23) is\n * that door: empty cells held in place, quoted cells, and the same separator and comma\n * rules underneath.\n */\n\n/** A digit, a comma, a digit — a comma that can only be a decimal mark or a\n * grouping mark, never a separator with a number on each side of it. `1, 2`\n * deliberately does not match: a comma followed by a space is how a human\n * writes a list, and reading it as a decimal mark would turn a hand-typed\n * `1, 2, 3` into one number. */\nconst DECIMAL_COMMA = /\\d,\\d/;\n\n/** What separates the columns of one line. A regular expression only for the\n * whitespace case, because a run of spaces is one separator. */\ntype Separator = string | RegExp;\n\n/** Where the decision about the comma is taken. See the module docstring: the\n * file door decides once for the whole text, the paste door decides per line. */\nexport type DecimalRule = \"per-line\" | \"whole-text\";\n\nexport interface ParseTableOptions {\n decimal: DecimalRule;\n /**\n * How many columns the caller already knows the table has. A grid with fixed\n * columns knows its width before a number arrives: anything past it is sliced\n * off — an export with a trailing timestamp column is not an error worth\n * refusing — and a line with fewer is reported. Omitted where the width is the\n * file's own answer.\n */\n columns?: number;\n /**\n * How many leading lines that are not rows of numbers may be a header.\n * Default 1, the name row. {@link parseRows} passes 2, because a bench export\n * writes the units on a second line under the names.\n */\n headerLines?: number;\n}\n\nexport interface ParsedTable {\n rows: number[][];\n /** The first header line's fields — the column *names*. A units line under it\n * is absorbed and not returned: what a column is measured in is the caller's to\n * say (its column definitions), and a second list of strings here would be a\n * second answer to that. */\n header: string[] | null;\n /** Whether a comma was read as a decimal mark. Under `\"per-line\"` this is true\n * if any line was read that way, and it exists for the reader: a guess\n * nobody can see is a guess nobody can correct. */\n decimalComma: boolean;\n /** Line numbers — 1-based, counted in the text as it was handed over, blank\n * lines included — that held something which is not a row of numbers. A list\n * rather than a count, because one door names the first one and the other\n * counts them. */\n skipped: number[];\n}\n\n/**\n * The columns of one line, as text, with the decimal mark normalised to a point.\n *\n * Text rather than numbers because a grid holds cells as strings: a pasted\n * field that is not a number belongs in the cell it landed in, marked, where the\n * person who pasted it can see which column went wrong. Dropping it here would\n * shift every column after it and lose the evidence.\n */\nexport function splitRow(line: string): string[] {\n const separator = separatorOf(line);\n const decimalComma = separator !== \",\";\n return fieldsOf(line, separator).map((field) => (decimalComma ? point(field) : field));\n}\n\n/**\n * A pasted table, or the lines of it that are not one.\n *\n * The lexer both doors are built on. It reads lines, drops blanks and `#`\n * banners, decides what separates the columns, takes the header off the top and\n * converts what is left.\n */\nexport function parseTable(text: string, options: ParseTableOptions): ParsedTable {\n const headerLimit = options.headerLines ?? 1;\n const lines = contentLines(text);\n if (!lines.length) return { rows: [], header: null, decimalComma: false, skipped: [] };\n const fixed = options.decimal === \"whole-text\" ? wholeTextRule(lines) : null;\n\n let header: string[] | null = null;\n let headerCount = 0;\n const rows: number[][] = [];\n const skipped: number[] = [];\n let sawDecimalComma = false;\n\n for (const { line, number } of lines) {\n const separator = fixed ? fixed.separator : separatorOf(line);\n const decimalComma = fixed ? fixed.decimalComma : separator !== \",\";\n const fields = fieldsOf(line, separator);\n const numbers = fields.map((field) => Number(decimalComma ? point(field) : field));\n const readable = fields.length > 0 && numbers.every(Number.isFinite);\n\n if (!readable) {\n // A header is only a header at the top, and only before any data: a stray\n // word further down is a broken row, and dropping it silently would lose a\n // measurement without saying so.\n if (rows.length === 0 && headerCount < headerLimit) {\n header ??= fields;\n headerCount += 1;\n continue;\n }\n skipped.push(number);\n continue;\n }\n if (options.columns !== undefined && fields.length < options.columns) {\n skipped.push(number);\n continue;\n }\n if (decimalComma && DECIMAL_COMMA.test(line)) sawDecimalComma = true;\n rows.push(options.columns === undefined ? numbers : numbers.slice(0, options.columns));\n }\n\n return {\n rows,\n header,\n decimalComma: fixed ? fixed.decimalComma : sawDecimalComma,\n skipped,\n };\n}\n\n/**\n * The paste door: a fixed number of columns, and the line that stopped it.\n *\n * Read per line, with up to two header lines (names, then units). It answers with a\n * line number rather than with what it managed to read, because half a pasted\n * sweep saved as a measurement is worse than a refused paste — and because a\n * table that comes back **empty** is the one answer a reader cannot act on: it\n * looks exactly like a paste that did not happen. So text that has content and\n * produced no row at all is an error naming its first unreadable line, never\n * `{ rows: [] }`.\n */\nexport function parseRows(text: string, columns: number): { rows: number[][] } | { error: number } {\n const lines = contentLines(text);\n if (!lines.length) return { rows: [] };\n const parsed = parseTable(text, { decimal: \"per-line\", columns, headerLines: 2 });\n if (parsed.skipped.length) return { error: parsed.skipped[0] };\n if (!parsed.rows.length) return { error: lines[0].number };\n return { rows: parsed.rows };\n}\n\n/** One cell as a number. Unconditional: a cell has no columns in it, so a comma\n * in one is a decimal mark and nothing else. */\nexport const cellNumber = (cell: string) => Number(cell.replace(\",\", \".\"));\n\n/** Whether one cell holds a number yet. An empty cell is not one — it is a hole\n * in the measurement, which is a different thing from a zero. */\nexport const isCellNumber = (cell: string) =>\n cell.trim() !== \"\" && !Number.isNaN(cellNumber(cell));\n\n/**\n * The one separator and the one decimal mark a whole file is read with.\n *\n * The separator is taken from the line most likely to be data — the second,\n * where there is one, because the first is usually the names.\n *\n * A comma between two digits is then a decimal mark whenever something else is\n * already separating the columns: there is nothing else it could be. The rule\n * this replaces also demanded that no decimal POINT appear anywhere in the file,\n * which read a semicolon-separated export with one column written by a different\n * tool — an entirely ordinary thing for a bench to produce — as a table with no\n * rows in it, and said nothing.\n */\nfunction wholeTextRule(lines: { line: string }[]): { separator: Separator; decimalComma: boolean } {\n const separator = separatorOf(lines[lines.length > 1 ? 1 : 0].line);\n const body = lines.map((entry) => entry.line).join(\"\\n\");\n return { separator, decimalComma: separator !== \",\" && DECIMAL_COMMA.test(body) };\n}\n\n/** Lines with something on them, numbered as they stand in the original text so\n * a message can point at one. `#` banners are a recorder's, not a measurement. */\nfunction contentLines(text: string): { line: string; number: number }[] {\n return text\n .split(/\\r?\\n/)\n .map((line, index) => ({ line: line.trim(), number: index + 1 }))\n .filter(({ line }) => line !== \"\" && !line.startsWith(\"#\"));\n}\n\n/**\n * What separates this line's columns.\n *\n * In order of trust, not of count: a semicolon-separated line with decimal\n * commas has more commas than semicolons, and a tab-separated one may have both.\n * Whichever of tab and semicolon appears wins outright, because neither is ever\n * anything but a separator.\n *\n * The comma is the one that has to be argued about. A line that has whitespace\n * between its fields *and* a comma between two digits has already said what\n * separates it — so the comma is a decimal mark, and the whitespace separates.\n * That is a German export printed or dumped from MATLAB (`0,5 1,25 2,75`), and\n * reading its commas as separators produced six columns from three: each number\n * split into a pair of small integers, accepted as a row, and saved as a\n * measurement with nothing on screen to say so. A comma with a space after it is\n * not that shape (`DECIMAL_COMMA` does not match `1, 2`), so a hand-typed list\n * still separates on the comma.\n */\nfunction separatorOf(line: string): Separator {\n if (line.includes(\"\\t\")) return \"\\t\";\n if (line.includes(\";\")) return \";\";\n if (line.includes(\",\")) return /\\s/.test(line) && DECIMAL_COMMA.test(line) ? /\\s+/ : \",\";\n return /\\s+/;\n}\n\n/** One line into trimmed, non-empty fields, as they were written. The header is\n * returned out of these, so a column called `Weg,X` keeps its name even where\n * the numbers under it are being read with a decimal comma. */\nfunction fieldsOf(line: string, separator: Separator): string[] {\n return line\n .split(separator)\n .map((field) => field.trim())\n .filter((field) => field !== \"\");\n}\n\n/** The decimal mark this language of `Number` understands. One comma, because a\n * field with two of them is a grouped number and this module does not read\n * those — it reports the line instead. */\nconst point = (field: string) => field.replace(\",\", \".\");\n\n// ── A table of text ────────────────────────────────────────────────────────────\n\n/**\n * What separates the columns of a {@link TextTable}, named. `\" \"` is a run of\n * whitespace — one separator however many spaces or tabs it is made of — as in a\n * printed or MATLAB-dumped table.\n */\nexport type TableSeparator = \"\\t\" | \";\" | \",\" | \" \";\n\n/** One line of the text as it was handed over: its 1-based number (blank lines\n * counted, so a reader can count to it in the box they pasted into) and its text,\n * trimmed. */\nexport interface TableLine {\n line: number;\n text: string;\n}\n\nexport interface ParseTextTableOptions {\n /** The separator, decided by the caller — a \"separated by\" override, a format\n * the app already knows. Default: detected (see {@link parseTextTable}). */\n separator?: TableSeparator;\n /** Whether a comma between two digits is a decimal mark. Default: the\n * `\"whole-text\"` rule, decided once for the file. */\n decimalComma?: boolean;\n /** Whether the table's first line names its columns. Default: detected — a\n * word over a column of values (\"Amount\" over `-12,50`) is a header. */\n header?: boolean;\n}\n\n/**\n * A table read as text: every cell a string, as written.\n *\n * The *file* door's decisions, for a table that is not only numbers. Everything a\n * reader has to know to trust it is in the answer — the separator and the decimal\n * mark that were assumed, and the lines that were not read, with their number and\n * their text — because a guess nobody can see is a guess nobody can correct.\n */\nexport interface TextTable {\n /** The first line's cells, when it names the columns; `null` when it is data. */\n header: string[] | null;\n /** Each read row, `width` cells long. An empty cell is `\"\"`, kept in its place. */\n rows: string[][];\n /** Where each row came from — row-aligned with `rows`. */\n lines: TableLine[];\n /** How many columns the table has. */\n width: number;\n separator: TableSeparator;\n /** Whether a comma is this table's decimal mark — the convention its numbers are\n * written in, to read them with {@link tableNumber} and to say back to the reader. */\n decimalComma: boolean;\n /** Lines that are not a row of this table: a title above it, a total under it, a\n * row with a cell too many or too few. */\n unread: TableLine[];\n}\n\n/**\n * A pasted or dropped table, read as text — the lexer's file door for a table whose\n * cells are not all numbers (a bank export: a date, a payee, an amount), and the\n * parse under {@link ColumnMapper}.\n *\n * Moved under the same roof as {@link parseTable} because it has the same three\n * questions — what separates the columns, what the comma is, whether the first\n * line is a header — and answering them a second time somewhere else is how the\n * three readers this module replaced came to disagree. Kurvenschmiede's columns\n * input and keksdose's bank-file import both read a table whose columns the reader\n * then assigns, and both state what was assumed; this is that reading, once.\n *\n * Where it differs from {@link parseTable}, and why:\n *\n * * **Cells stay text.** Which cell is a number is the caller's question (its\n * column roles), so nothing here converts. {@link tableNumber} reads one in the\n * table's own convention.\n * * **An empty cell keeps its place.** A bank row with no memo has `;;` in it, and\n * dropping that field — which the numeric lexer does — would move the amount into\n * the memo's column. A trailing separator that ends most lines (`1;2;3;`, which\n * spreadsheets write) is a line ending, not a column.\n * * **Quoted cells.** `\"Example Ltd; branch 2\"` is one cell, and `\"\"` inside quotes\n * is a quote. Text has separators in it where numbers never do. A quoted cell that\n * runs over a line break is not joined — the line then has the wrong number of\n * cells and is reported.\n * * **The width is the file's.** The column count most lines share. A line with\n * another count is reported in `unread` rather than padded or cut: a row with a\n * cell too many is a row whose columns have slid, and reading it would put a payee\n * in the amount.\n * * **The separator is voted on**, over the first lines, rather than taken from the\n * second: an export that opens with a title block (a bank's account name and\n * period over the table) would otherwise be read with the title's separator.\n * * **The header is detected by its words.** The numeric lexer's rule — \"a line\n * that is not numbers\" — cannot work where the rows are text too. A first line is\n * a header when one of its cells is a word and every cell under it, as far as the\n * first rows go, is a value (digits and the marks numbers and dates are written\n * with): \"Amount\" over `-12,50`, \"Date\" over `01.02.2026`. A table of words only\n * is read without one; `options.header` says otherwise.\n *\n * Blank lines and `#` banners are skipped, as by the numeric lexer.\n */\nexport function parseTextTable(text: string, options: ParseTextTableOptions = {}): TextTable {\n const content = textLines(text);\n if (!content.length) {\n return { header: null, rows: [], lines: [], width: 0, separator: options.separator ?? \",\", decimalComma: false, unread: [] };\n }\n const separator = options.separator ?? votedSeparator(content);\n const decimalComma =\n options.decimalComma ?? (separator !== \",\" && DECIMAL_COMMA.test(content.map((entry) => entry.line).join(\"\\n\")));\n\n // A trailing separator is a line ending only where it is the file's habit: in a\n // file where most lines end in one. Elsewhere it closes an empty last cell.\n const trailing =\n separator !== \" \" && content.filter(({ line }) => line.endsWith(separator)).length * 2 > content.length;\n const split = content.map(({ line, number }) => {\n const cells = cellsOf(line, separator);\n if (trailing && line.endsWith(separator) && cells[cells.length - 1] === \"\") cells.pop();\n return { cells, entry: { line: number, text: line } };\n });\n\n const width = commonWidth(split.map(({ cells }) => cells.length));\n const first = split.findIndex(({ cells }) => cells.length === width);\n const unread: TableLine[] = split.slice(0, first).map(({ entry }) => entry);\n const body = split.slice(first);\n const fitting = body.filter(({ cells }) => cells.length === width);\n const header = options.header ?? looksLikeHeader(fitting[0].cells, fitting.slice(1, 21).map(({ cells }) => cells));\n\n const rows: string[][] = [];\n const lines: TableLine[] = [];\n body.forEach(({ cells, entry }, index) => {\n if (index === 0 && header) return;\n if (cells.length !== width) {\n unread.push(entry);\n return;\n }\n rows.push(cells);\n lines.push(entry);\n });\n\n return { header: header ? body[0].cells : null, rows, lines, width, separator, decimalComma, unread };\n}\n\n/**\n * One cell of a {@link TextTable} as a number, read in the table's convention.\n *\n * Not {@link cellNumber}, which reads every comma as a decimal mark — right for a\n * cell typed on its own, wrong for a cell of a file written with decimal points,\n * where `1,234` is a grouped thousand and reading it as 1.234 would be off by a\n * factor of a thousand without a word. Here a comma is a decimal mark only in a\n * table whose convention it is, and a cell with both marks is `NaN` either way: the\n * lexer does not read grouped numbers, it reports them. An empty cell is `NaN` too —\n * a hole in the table, not a zero.\n */\nexport function tableNumber(cell: string, decimalComma: boolean): number {\n const trimmed = cell.trim();\n if (trimmed === \"\") return Number.NaN;\n return Number(decimalComma ? point(trimmed) : trimmed);\n}\n\nconst SEPARATOR_TRUST: readonly TableSeparator[] = [\"\\t\", \";\", \",\", \" \"];\n\n/** {@link contentLines} for a table of text: spaces come off the ends, but a TAB\n * stays — in a tab-separated export a leading tab is an empty first cell, and\n * trimming it would slide the whole row one column to the left. */\nfunction textLines(text: string): { line: string; number: number }[] {\n return text\n .split(/\\r?\\n/)\n .map((line, index) => ({ line: line.replace(/^ +| +$/g, \"\"), number: index + 1 }))\n .filter(({ line }) => line.trim() !== \"\" && !line.trimStart().startsWith(\"#\"));\n}\n\n/** The separator most of the first lines are written with — a title block above the\n * table loses the vote to the table under it. A tie goes to the more trusted one. */\nfunction votedSeparator(lines: { line: string }[]): TableSeparator {\n const votes = new Map<TableSeparator, number>();\n for (const { line } of lines.slice(0, 50)) {\n const found = separatorOf(withoutQuoted(line));\n const named: TableSeparator = typeof found === \"string\" ? (found as TableSeparator) : \" \";\n votes.set(named, (votes.get(named) ?? 0) + 1);\n }\n let best: TableSeparator = SEPARATOR_TRUST[0];\n let bestCount = -1;\n for (const candidate of SEPARATOR_TRUST) {\n const count = votes.get(candidate) ?? 0;\n if (count > bestCount) {\n best = candidate;\n bestCount = count;\n }\n }\n return best;\n}\n\n/** A line with its quoted parts emptied, so a separator inside quotes does not vote. */\nconst withoutQuoted = (line: string) => line.replace(/\"(?:[^\"]|\"\")*\"/g, '\"\"');\n\n/**\n * One line into cells: trimmed, quotes taken off, empty cells kept in their place.\n * A run of whitespace is one separator and makes no empty cells.\n */\nfunction cellsOf(line: string, separator: TableSeparator): string[] {\n if (separator === \" \") return line.split(/\\s+/).filter((field) => field !== \"\").map(unquote);\n const cells: string[] = [];\n let cell = \"\";\n let quoted = false;\n let started = false;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index];\n if (quoted) {\n if (char === '\"' && line[index + 1] === '\"') {\n cell += '\"';\n index += 1;\n } else if (char === '\"') {\n quoted = false;\n } else {\n cell += char;\n }\n } else if (char === separator) {\n cells.push(cell.trim());\n cell = \"\";\n started = false;\n } else if (char === '\"' && !started) {\n quoted = true;\n started = true;\n cell = \"\";\n } else {\n if (char.trim() !== \"\") started = true;\n cell += char;\n }\n }\n cells.push(cell.trim());\n return cells;\n}\n\n/** A whitespace-separated field with its quotes off. */\nfunction unquote(field: string): string {\n return field.length >= 2 && field.startsWith('\"') && field.endsWith('\"') ? field.slice(1, -1).replace(/\"\"/g, '\"') : field;\n}\n\n/** The column count most lines share; a tie goes to the wider table. */\nfunction commonWidth(counts: number[]): number {\n const tally = new Map<number, number>();\n for (const count of counts) tally.set(count, (tally.get(count) ?? 0) + 1);\n let width = 0;\n let best = 0;\n for (const [count, times] of tally) {\n if (times > best || (times === best && count > width)) {\n width = count;\n best = times;\n }\n }\n return width;\n}\n\n/** A cell with a letter in it — a name, not a value. */\nconst isWord = (cell: string) => /\\p{L}/u.test(cell);\n/** A cell made of digits and the marks numbers, dates and times are written with. */\nconst isValue = (cell: string) => /\\d/.test(cell) && !isWord(cell);\n\n/**\n * Whether a first line names the columns under it. A word over a column of values\n * says so; with no rows to compare against, a line of words alone does.\n */\nfunction looksLikeHeader(first: string[], below: string[][]): boolean {\n if (!below.length) return first.some((cell) => cell !== \"\") && first.every((cell) => cell === \"\" || isWord(cell));\n return first.some((cell, column) => {\n if (!isWord(cell)) return false;\n const values = below.map((row) => row[column]).filter((value) => value !== \"\");\n return values.length > 0 && values.every(isValue);\n });\n}\n"],"mappings":";AA4DA,MAAM,gBAAgB;AAsDf,SAAS,SAAS,MAAwB;AAC/C,QAAM,YAAY,YAAY,IAAI;AAClC,QAAM,eAAe,cAAc;AACnC,SAAO,SAAS,MAAM,SAAS,EAAE,IAAI,CAAC,UAAW,eAAe,MAAM,KAAK,IAAI,KAAM;AACvF;AASO,SAAS,WAAW,MAAc,SAAyC;AAChF,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,QAAQ,aAAa,IAAI;AAC/B,MAAI,CAAC,MAAM,OAAQ,QAAO,EAAE,MAAM,CAAC,GAAG,QAAQ,MAAM,cAAc,OAAO,SAAS,CAAC,EAAE;AACrF,QAAM,QAAQ,QAAQ,YAAY,eAAe,cAAc,KAAK,IAAI;AAExE,MAAI,SAA0B;AAC9B,MAAI,cAAc;AAClB,QAAM,OAAmB,CAAC;AAC1B,QAAM,UAAoB,CAAC;AAC3B,MAAI,kBAAkB;AAEtB,aAAW,EAAE,MAAM,OAAO,KAAK,OAAO;AACpC,UAAM,YAAY,QAAQ,MAAM,YAAY,YAAY,IAAI;AAC5D,UAAM,eAAe,QAAQ,MAAM,eAAe,cAAc;AAChE,UAAM,SAAS,SAAS,MAAM,SAAS;AACvC,UAAM,UAAU,OAAO,IAAI,CAAC,UAAU,OAAO,eAAe,MAAM,KAAK,IAAI,KAAK,CAAC;AACjF,UAAM,WAAW,OAAO,SAAS,KAAK,QAAQ,MAAM,OAAO,QAAQ;AAEnE,QAAI,CAAC,UAAU;AAIb,UAAI,KAAK,WAAW,KAAK,cAAc,aAAa;AAClD,mBAAW;AACX,uBAAe;AACf;AAAA,MACF;AACA,cAAQ,KAAK,MAAM;AACnB;AAAA,IACF;AACA,QAAI,QAAQ,YAAY,UAAa,OAAO,SAAS,QAAQ,SAAS;AACpE,cAAQ,KAAK,MAAM;AACnB;AAAA,IACF;AACA,QAAI,gBAAgB,cAAc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C7E,WAAO,OAAO,SAAS,KAAK,OAAO,MAAM,OAAO;AAAA,EAClD,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/lib/table-text.ts"],"sourcesContent":["/**\n * One lexer for \"paste the table out of a spreadsheet\", and the three rules for the\n * comma. `@eifi1/ui-kit/table-text` — pure functions over strings, no React.\n *\n * Moved here from Lenkbank (`shared/lib/parse-table.ts`), where three screens took a\n * table off somebody's clipboard — a measured-table grid, the text view beside it, and\n * a page that reads a recorder's setpoint/actual files — and each had grown its own\n * reader. They disagreed, and not in the harmless way: a whitespace-separated German\n * export was read as six columns of nonsense by two of them and as nothing at all by\n * the third, with no message either way. The lexing is one problem (lines, a\n * separator, fields, a header, numbers) and it is solved once here, so the next app\n * that imports a CSV does not write the comma rules wrong a second time.\n *\n * **What is genuinely different between callers is where the decision about the\n * comma is taken**, and that is a parameter rather than a constant. A comma is the\n * decimal mark in every German export and the column separator in every English CSV,\n * and no single rule serves both without regressing one of them. So the rules are\n * named instead of one being picked:\n *\n * * **`\"whole-text\"`** — the *file* door. A recorder writes one file in one\n * convention, so the separator and the decimal mark are decided once, from the\n * whole text, and stated back to the reader (`decimalComma`) where they can see\n * what was assumed. Deciding once is what lets one damaged line be *counted*\n * rather than re-guessed into a different convention than the lines around it.\n * * **`\"per-line\"`** — the *paste* door. What arrives on a clipboard is a few rows\n * out of a spreadsheet, sometimes one row, sometimes a line somebody typed. There\n * is no file to be consistent with, and a line must not change meaning because of\n * another line somewhere else in the box — so each line is read on its own\n * evidence.\n * * **unconditional** — one cell (`cellNumber` / `isCellNumber`). A single cell has\n * no columns in it, so a comma in one cannot be separating anything and is always\n * a decimal mark. That is not a table rule at all, which is why it is a pair of\n * one-liners beside the others rather than an option on them.\n *\n * What this deliberately does not do:\n *\n * * **Thousands separators.** `1.234,5` and `1,234.5` are both a number with two\n * marks in it, and telling the grouping mark from the decimal mark needs a rule\n * about digit runs that would then have to be right for a three-digit integer\n * too. A field carrying one is reported as a line that could not be read, with\n * its line number, which is something a reader can act on. Guessing is not.\n * * **Empty cells.** An empty field is dropped rather than held open as a hole, so a\n * row with a dropped channel in the middle of it shifts left. Keeping the hole\n * would mean reading `1;2;3;` — a trailing separator, which every spreadsheet\n * writes — as a four-column row. It is a known gap, not an oversight.\n * * **Quoted fields.** No `\"a;b\"` escaping. These are numbers; the only text in them\n * is the header line, and a header field with a separator in it costs a column\n * name, not a measurement.\n *\n * Both of those are the NUMERIC lexer's limits. A table whose cells are text — a bank\n * export, read for a column mapper — needs both, and {@link parseTextTable} (0.23) is\n * that door: empty cells held in place, quoted cells, and the same separator and comma\n * rules underneath.\n */\n\n/** A digit, a comma, a digit — a comma that can only be a decimal mark or a\n * grouping mark, never a separator with a number on each side of it. `1, 2`\n * deliberately does not match: a comma followed by a space is how a human\n * writes a list, and reading it as a decimal mark would turn a hand-typed\n * `1, 2, 3` into one number. */\nconst DECIMAL_COMMA = /\\d,\\d/;\n\n/** What separates the columns of one line. A regular expression only for the\n * whitespace case, because a run of spaces is one separator. */\ntype Separator = string | RegExp;\n\n/** Where the decision about the comma is taken. See the module docstring: the\n * file door decides once for the whole text, the paste door decides per line. */\nexport type DecimalRule = \"per-line\" | \"whole-text\";\n\nexport interface ParseTableOptions {\n decimal: DecimalRule;\n /**\n * How many columns the caller already knows the table has. A grid with fixed\n * columns knows its width before a number arrives: anything past it is sliced\n * off — an export with a trailing timestamp column is not an error worth\n * refusing — and a line with fewer is reported. Omitted where the width is the\n * file's own answer.\n */\n columns?: number;\n /**\n * How many leading lines that are not rows of numbers may be a header.\n * Default 1, the name row. {@link parseRows} passes 2, because a bench export\n * writes the units on a second line under the names.\n */\n headerLines?: number;\n}\n\nexport interface ParsedTable {\n rows: number[][];\n /** The first header line's fields — the column *names*. A units line under it\n * is absorbed and not returned: what a column is measured in is the caller's to\n * say (its column definitions), and a second list of strings here would be a\n * second answer to that. */\n header: string[] | null;\n /** Whether a comma was read as a decimal mark. Under `\"per-line\"` this is true\n * if any line was read that way, and it exists for the reader: a guess\n * nobody can see is a guess nobody can correct. */\n decimalComma: boolean;\n /** Line numbers — 1-based, counted in the text as it was handed over, blank\n * lines included — that held something which is not a row of numbers. A list\n * rather than a count, because one door names the first one and the other\n * counts them. */\n skipped: number[];\n}\n\n/**\n * The columns of one line, as text, with the decimal mark normalised to a point.\n *\n * Text rather than numbers because a grid holds cells as strings: a pasted\n * field that is not a number belongs in the cell it landed in, marked, where the\n * person who pasted it can see which column went wrong. Dropping it here would\n * shift every column after it and lose the evidence.\n */\nexport function splitRow(line: string): string[] {\n const separator = separatorOf(line);\n const decimalComma = separator !== \",\";\n return fieldsOf(line, separator).map((field) => (decimalComma ? point(field) : field));\n}\n\n/**\n * A pasted table, or the lines of it that are not one.\n *\n * The lexer both doors are built on. It reads lines, drops blanks and `#`\n * banners, decides what separates the columns, takes the header off the top and\n * converts what is left.\n */\nexport function parseTable(text: string, options: ParseTableOptions): ParsedTable {\n const headerLimit = options.headerLines ?? 1;\n const lines = contentLines(text);\n if (!lines.length) return { rows: [], header: null, decimalComma: false, skipped: [] };\n const fixed = options.decimal === \"whole-text\" ? wholeTextRule(lines) : null;\n\n let header: string[] | null = null;\n let headerCount = 0;\n const rows: number[][] = [];\n const skipped: number[] = [];\n let sawDecimalComma = false;\n\n for (const { line, number } of lines) {\n const separator = fixed ? fixed.separator : separatorOf(line);\n const decimalComma = fixed ? fixed.decimalComma : separator !== \",\";\n const fields = fieldsOf(line, separator);\n const numbers = fields.map((field) => Number(decimalComma ? point(field) : field));\n const readable = fields.length > 0 && numbers.every(Number.isFinite);\n\n if (!readable) {\n // A header is only a header at the top, and only before any data: a stray\n // word further down is a broken row, and dropping it silently would lose a\n // measurement without saying so.\n if (rows.length === 0 && headerCount < headerLimit) {\n header ??= fields;\n headerCount += 1;\n continue;\n }\n skipped.push(number);\n continue;\n }\n if (options.columns !== undefined && fields.length < options.columns) {\n skipped.push(number);\n continue;\n }\n if (decimalComma && DECIMAL_COMMA.test(line)) sawDecimalComma = true;\n rows.push(options.columns === undefined ? numbers : numbers.slice(0, options.columns));\n }\n\n return {\n rows,\n header,\n decimalComma: fixed ? fixed.decimalComma : sawDecimalComma,\n skipped,\n };\n}\n\n/**\n * The paste door: a fixed number of columns, and the line that stopped it.\n *\n * Read per line, with up to two header lines (names, then units). It answers with a\n * line number rather than with what it managed to read, because half a pasted\n * sweep saved as a measurement is worse than a refused paste — and because a\n * table that comes back **empty** is the one answer a reader cannot act on: it\n * looks exactly like a paste that did not happen. So text that has content and\n * produced no row at all is an error naming its first unreadable line, never\n * `{ rows: [] }`.\n */\nexport function parseRows(text: string, columns: number): { rows: number[][] } | { error: number } {\n const lines = contentLines(text);\n if (!lines.length) return { rows: [] };\n const parsed = parseTable(text, { decimal: \"per-line\", columns, headerLines: 2 });\n if (parsed.skipped.length) return { error: parsed.skipped[0] };\n if (!parsed.rows.length) return { error: lines[0].number };\n return { rows: parsed.rows };\n}\n\n/** One cell as a number. Unconditional: a cell has no columns in it, so a comma\n * in one is a decimal mark and nothing else. */\nexport const cellNumber = (cell: string) => Number(cell.replace(\",\", \".\"));\n\n/** Whether one cell holds a number yet. An empty cell is not one — it is a hole\n * in the measurement, which is a different thing from a zero. */\nexport const isCellNumber = (cell: string) => cell.trim() !== \"\" && !Number.isNaN(cellNumber(cell));\n\n/**\n * The one separator and the one decimal mark a whole file is read with.\n *\n * The separator is taken from the line most likely to be data — the second,\n * where there is one, because the first is usually the names.\n *\n * A comma between two digits is then a decimal mark whenever something else is\n * already separating the columns: there is nothing else it could be. The rule\n * this replaces also demanded that no decimal POINT appear anywhere in the file,\n * which read a semicolon-separated export with one column written by a different\n * tool — an entirely ordinary thing for a bench to produce — as a table with no\n * rows in it, and said nothing.\n */\nfunction wholeTextRule(lines: { line: string }[]): { separator: Separator; decimalComma: boolean } {\n const separator = separatorOf(lines[lines.length > 1 ? 1 : 0].line);\n const body = lines.map((entry) => entry.line).join(\"\\n\");\n return { separator, decimalComma: separator !== \",\" && DECIMAL_COMMA.test(body) };\n}\n\n/** Lines with something on them, numbered as they stand in the original text so\n * a message can point at one. `#` banners are a recorder's, not a measurement. */\nfunction contentLines(text: string): { line: string; number: number }[] {\n return text\n .split(/\\r?\\n/)\n .map((line, index) => ({ line: line.trim(), number: index + 1 }))\n .filter(({ line }) => line !== \"\" && !line.startsWith(\"#\"));\n}\n\n/**\n * What separates this line's columns.\n *\n * In order of trust, not of count: a semicolon-separated line with decimal\n * commas has more commas than semicolons, and a tab-separated one may have both.\n * Whichever of tab and semicolon appears wins outright, because neither is ever\n * anything but a separator.\n *\n * The comma is the one that has to be argued about. A line that has whitespace\n * between its fields *and* a comma between two digits has already said what\n * separates it — so the comma is a decimal mark, and the whitespace separates.\n * That is a German export printed or dumped from MATLAB (`0,5 1,25 2,75`), and\n * reading its commas as separators produced six columns from three: each number\n * split into a pair of small integers, accepted as a row, and saved as a\n * measurement with nothing on screen to say so. A comma with a space after it is\n * not that shape (`DECIMAL_COMMA` does not match `1, 2`), so a hand-typed list\n * still separates on the comma.\n */\nfunction separatorOf(line: string): Separator {\n if (line.includes(\"\\t\")) return \"\\t\";\n if (line.includes(\";\")) return \";\";\n if (line.includes(\",\")) return /\\s/.test(line) && DECIMAL_COMMA.test(line) ? /\\s+/ : \",\";\n return /\\s+/;\n}\n\n/** One line into trimmed, non-empty fields, as they were written. The header is\n * returned out of these, so a column called `Weg,X` keeps its name even where\n * the numbers under it are being read with a decimal comma. */\nfunction fieldsOf(line: string, separator: Separator): string[] {\n return line\n .split(separator)\n .map((field) => field.trim())\n .filter((field) => field !== \"\");\n}\n\n/** The decimal mark this language of `Number` understands. One comma, because a\n * field with two of them is a grouped number and this module does not read\n * those — it reports the line instead. */\nconst point = (field: string) => field.replace(\",\", \".\");\n\n// ── A table of text ────────────────────────────────────────────────────────────\n\n/**\n * What separates the columns of a {@link TextTable}, named. `\" \"` is a run of\n * whitespace — one separator however many spaces or tabs it is made of — as in a\n * printed or MATLAB-dumped table.\n */\nexport type TableSeparator = \"\\t\" | \";\" | \",\" | \" \";\n\n/** One line of the text as it was handed over: its 1-based number (blank lines\n * counted, so a reader can count to it in the box they pasted into) and its text,\n * trimmed. */\nexport interface TableLine {\n line: number;\n text: string;\n}\n\nexport interface ParseTextTableOptions {\n /** The separator, decided by the caller — a \"separated by\" override, a format\n * the app already knows. Default: detected (see {@link parseTextTable}). */\n separator?: TableSeparator;\n /** Whether a comma between two digits is a decimal mark. Default: the\n * `\"whole-text\"` rule, decided once for the file. */\n decimalComma?: boolean;\n /** Whether the table's first line names its columns. Default: detected — a\n * word over a column of values (\"Amount\" over `-12,50`) is a header. */\n header?: boolean;\n}\n\n/**\n * A table read as text: every cell a string, as written.\n *\n * The *file* door's decisions, for a table that is not only numbers. Everything a\n * reader has to know to trust it is in the answer — the separator and the decimal\n * mark that were assumed, and the lines that were not read, with their number and\n * their text — because a guess nobody can see is a guess nobody can correct.\n */\nexport interface TextTable {\n /** The first line's cells, when it names the columns; `null` when it is data. */\n header: string[] | null;\n /** Each read row, `width` cells long. An empty cell is `\"\"`, kept in its place. */\n rows: string[][];\n /** Where each row came from — row-aligned with `rows`. */\n lines: TableLine[];\n /** How many columns the table has. */\n width: number;\n separator: TableSeparator;\n /** Whether a comma is this table's decimal mark — the convention its numbers are\n * written in, to read them with {@link tableNumber} and to say back to the reader. */\n decimalComma: boolean;\n /** Lines that are not a row of this table: a title above it, a total under it, a\n * row with a cell too many or too few. */\n unread: TableLine[];\n}\n\n/**\n * A pasted or dropped table, read as text — the lexer's file door for a table whose\n * cells are not all numbers (a bank export: a date, a payee, an amount), and the\n * parse under {@link ColumnMapper}.\n *\n * Moved under the same roof as {@link parseTable} because it has the same three\n * questions — what separates the columns, what the comma is, whether the first\n * line is a header — and answering them a second time somewhere else is how the\n * three readers this module replaced came to disagree. Kurvenschmiede's columns\n * input and keksdose's bank-file import both read a table whose columns the reader\n * then assigns, and both state what was assumed; this is that reading, once.\n *\n * Where it differs from {@link parseTable}, and why:\n *\n * * **Cells stay text.** Which cell is a number is the caller's question (its\n * column roles), so nothing here converts. {@link tableNumber} reads one in the\n * table's own convention.\n * * **An empty cell keeps its place.** A bank row with no memo has `;;` in it, and\n * dropping that field — which the numeric lexer does — would move the amount into\n * the memo's column. A trailing separator that ends most lines (`1;2;3;`, which\n * spreadsheets write) is a line ending, not a column.\n * * **Quoted cells.** `\"Example Ltd; branch 2\"` is one cell, and `\"\"` inside quotes\n * is a quote. Text has separators in it where numbers never do. A quoted cell that\n * runs over a line break is not joined — the line then has the wrong number of\n * cells and is reported.\n * * **The width is the file's.** The column count most lines share. A line with\n * another count is reported in `unread` rather than padded or cut: a row with a\n * cell too many is a row whose columns have slid, and reading it would put a payee\n * in the amount.\n * * **The separator is voted on**, over the first lines, rather than taken from the\n * second: an export that opens with a title block (a bank's account name and\n * period over the table) would otherwise be read with the title's separator.\n * * **The header is detected by its words.** The numeric lexer's rule — \"a line\n * that is not numbers\" — cannot work where the rows are text too. A first line is\n * a header when one of its cells is a word and every cell under it, as far as the\n * first rows go, is a value (digits and the marks numbers and dates are written\n * with): \"Amount\" over `-12,50`, \"Date\" over `01.02.2026`. A table of words only\n * is read without one; `options.header` says otherwise.\n *\n * Blank lines and `#` banners are skipped, as by the numeric lexer.\n */\nexport function parseTextTable(text: string, options: ParseTextTableOptions = {}): TextTable {\n const content = textLines(text);\n if (!content.length) {\n return {\n header: null,\n rows: [],\n lines: [],\n width: 0,\n separator: options.separator ?? \",\",\n decimalComma: false,\n unread: [],\n };\n }\n const separator = options.separator ?? votedSeparator(content);\n const decimalComma =\n options.decimalComma ?? (separator !== \",\" && DECIMAL_COMMA.test(content.map((entry) => entry.line).join(\"\\n\")));\n\n // A trailing separator is a line ending only where it is the file's habit: in a\n // file where most lines end in one. Elsewhere it closes an empty last cell.\n const trailing =\n separator !== \" \" && content.filter(({ line }) => line.endsWith(separator)).length * 2 > content.length;\n const split = content.map(({ line, number }) => {\n const cells = cellsOf(line, separator);\n if (trailing && line.endsWith(separator) && cells[cells.length - 1] === \"\") cells.pop();\n return { cells, entry: { line: number, text: line } };\n });\n\n const width = commonWidth(split.map(({ cells }) => cells.length));\n const first = split.findIndex(({ cells }) => cells.length === width);\n const unread: TableLine[] = split.slice(0, first).map(({ entry }) => entry);\n const body = split.slice(first);\n const fitting = body.filter(({ cells }) => cells.length === width);\n const header =\n options.header ??\n looksLikeHeader(\n fitting[0].cells,\n fitting.slice(1, 21).map(({ cells }) => cells),\n );\n\n const rows: string[][] = [];\n const lines: TableLine[] = [];\n body.forEach(({ cells, entry }, index) => {\n if (index === 0 && header) return;\n if (cells.length !== width) {\n unread.push(entry);\n return;\n }\n rows.push(cells);\n lines.push(entry);\n });\n\n return { header: header ? body[0].cells : null, rows, lines, width, separator, decimalComma, unread };\n}\n\n/**\n * One cell of a {@link TextTable} as a number, read in the table's convention.\n *\n * Not {@link cellNumber}, which reads every comma as a decimal mark — right for a\n * cell typed on its own, wrong for a cell of a file written with decimal points,\n * where `1,234` is a grouped thousand and reading it as 1.234 would be off by a\n * factor of a thousand without a word. Here a comma is a decimal mark only in a\n * table whose convention it is, and a cell with both marks is `NaN` either way: the\n * lexer does not read grouped numbers, it reports them. An empty cell is `NaN` too —\n * a hole in the table, not a zero.\n */\nexport function tableNumber(cell: string, decimalComma: boolean): number {\n const trimmed = cell.trim();\n if (trimmed === \"\") return Number.NaN;\n return Number(decimalComma ? point(trimmed) : trimmed);\n}\n\nconst SEPARATOR_TRUST: readonly TableSeparator[] = [\"\\t\", \";\", \",\", \" \"];\n\n/** {@link contentLines} for a table of text: spaces come off the ends, but a TAB\n * stays — in a tab-separated export a leading tab is an empty first cell, and\n * trimming it would slide the whole row one column to the left. */\nfunction textLines(text: string): { line: string; number: number }[] {\n return text\n .split(/\\r?\\n/)\n .map((line, index) => ({ line: line.replace(/^ +| +$/g, \"\"), number: index + 1 }))\n .filter(({ line }) => line.trim() !== \"\" && !line.trimStart().startsWith(\"#\"));\n}\n\n/** The separator most of the first lines are written with — a title block above the\n * table loses the vote to the table under it. A tie goes to the more trusted one. */\nfunction votedSeparator(lines: { line: string }[]): TableSeparator {\n const votes = new Map<TableSeparator, number>();\n for (const { line } of lines.slice(0, 50)) {\n const found = separatorOf(withoutQuoted(line));\n const named: TableSeparator = typeof found === \"string\" ? (found as TableSeparator) : \" \";\n votes.set(named, (votes.get(named) ?? 0) + 1);\n }\n let best: TableSeparator = SEPARATOR_TRUST[0];\n let bestCount = -1;\n for (const candidate of SEPARATOR_TRUST) {\n const count = votes.get(candidate) ?? 0;\n if (count > bestCount) {\n best = candidate;\n bestCount = count;\n }\n }\n return best;\n}\n\n/** A line with its quoted parts emptied, so a separator inside quotes does not vote. */\nconst withoutQuoted = (line: string) => line.replace(/\"(?:[^\"]|\"\")*\"/g, '\"\"');\n\n/**\n * One line into cells: trimmed, quotes taken off, empty cells kept in their place.\n * A run of whitespace is one separator and makes no empty cells.\n */\nfunction cellsOf(line: string, separator: TableSeparator): string[] {\n if (separator === \" \")\n return line\n .split(/\\s+/)\n .filter((field) => field !== \"\")\n .map(unquote);\n const cells: string[] = [];\n let cell = \"\";\n let quoted = false;\n let started = false;\n for (let index = 0; index < line.length; index += 1) {\n const char = line[index];\n if (quoted) {\n if (char === '\"' && line[index + 1] === '\"') {\n cell += '\"';\n index += 1;\n } else if (char === '\"') {\n quoted = false;\n } else {\n cell += char;\n }\n } else if (char === separator) {\n cells.push(cell.trim());\n cell = \"\";\n started = false;\n } else if (char === '\"' && !started) {\n quoted = true;\n started = true;\n cell = \"\";\n } else {\n if (char.trim() !== \"\") started = true;\n cell += char;\n }\n }\n cells.push(cell.trim());\n return cells;\n}\n\n/** A whitespace-separated field with its quotes off. */\nfunction unquote(field: string): string {\n return field.length >= 2 && field.startsWith('\"') && field.endsWith('\"')\n ? field.slice(1, -1).replace(/\"\"/g, '\"')\n : field;\n}\n\n/** The column count most lines share; a tie goes to the wider table. */\nfunction commonWidth(counts: number[]): number {\n const tally = new Map<number, number>();\n for (const count of counts) tally.set(count, (tally.get(count) ?? 0) + 1);\n let width = 0;\n let best = 0;\n for (const [count, times] of tally) {\n if (times > best || (times === best && count > width)) {\n width = count;\n best = times;\n }\n }\n return width;\n}\n\n/** A cell with a letter in it — a name, not a value. */\nconst isWord = (cell: string) => /\\p{L}/u.test(cell);\n/** A cell made of digits and the marks numbers, dates and times are written with. */\nconst isValue = (cell: string) => /\\d/.test(cell) && !isWord(cell);\n\n/**\n * Whether a first line names the columns under it. A word over a column of values\n * says so; with no rows to compare against, a line of words alone does.\n */\nfunction looksLikeHeader(first: string[], below: string[][]): boolean {\n if (!below.length) return first.some((cell) => cell !== \"\") && first.every((cell) => cell === \"\" || isWord(cell));\n return first.some((cell, column) => {\n if (!isWord(cell)) return false;\n const values = below.map((row) => row[column]).filter((value) => value !== \"\");\n return values.length > 0 && values.every(isValue);\n });\n}\n"],"mappings":";AA4DA,MAAM,gBAAgB;AAsDf,SAAS,SAAS,MAAwB;AAC/C,QAAM,YAAY,YAAY,IAAI;AAClC,QAAM,eAAe,cAAc;AACnC,SAAO,SAAS,MAAM,SAAS,EAAE,IAAI,CAAC,UAAW,eAAe,MAAM,KAAK,IAAI,KAAM;AACvF;AASO,SAAS,WAAW,MAAc,SAAyC;AAChF,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,QAAQ,aAAa,IAAI;AAC/B,MAAI,CAAC,MAAM,OAAQ,QAAO,EAAE,MAAM,CAAC,GAAG,QAAQ,MAAM,cAAc,OAAO,SAAS,CAAC,EAAE;AACrF,QAAM,QAAQ,QAAQ,YAAY,eAAe,cAAc,KAAK,IAAI;AAExE,MAAI,SAA0B;AAC9B,MAAI,cAAc;AAClB,QAAM,OAAmB,CAAC;AAC1B,QAAM,UAAoB,CAAC;AAC3B,MAAI,kBAAkB;AAEtB,aAAW,EAAE,MAAM,OAAO,KAAK,OAAO;AACpC,UAAM,YAAY,QAAQ,MAAM,YAAY,YAAY,IAAI;AAC5D,UAAM,eAAe,QAAQ,MAAM,eAAe,cAAc;AAChE,UAAM,SAAS,SAAS,MAAM,SAAS;AACv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CAAC,SAAiB,SAAS,KAAK,IAAI;AAEnD,MAAM,UAAU,CAAC,SAAiB,KAAK,KAAK,IAAI,KAAK,CAAC,OAAO,IAAI;AAMjE,SAAS,gBAAgB,OAAiB,OAA4B;AACpE,MAAI,CAAC,MAAM,OAAQ,QAAO,MAAM,KAAK,CAAC,SAAS,SAAS,EAAE,KAAK,MAAM,MAAM,CAAC,SAAS,SAAS,MAAM,OAAO,IAAI,CAAC;AAChH,SAAO,MAAM,KAAK,CAAC,MAAM,WAAW;AAClC,QAAI,CAAC,OAAO,IAAI,EAAG,QAAO;AAC1B,UAAM,SAAS,MAAM,IAAI,CAAC,QAAQ,IAAI,MAAM,CAAC,EAAE,OAAO,CAAC,UAAU,UAAU,EAAE;AAC7E,WAAO,OAAO,SAAS,KAAK,OAAO,MAAM,OAAO;AAAA,EAClD,CAAC;AACH;","names":[]}
@@ -33,6 +33,10 @@ export declare function searchWords(query: string, locale?: string): string[];
33
33
  * was a substring. No words match everything.
34
34
  *
35
35
  * `words` from {@link searchWords}; `texts` as they are (folded here), `undefined` skipped.
36
+ *
37
+ * Exported since 0.51.5 for an app's own async source: a picker shows `loadOptions`'
38
+ * rows as they come, so a source that narrows on the client filters with this, the same
39
+ * rule the kit applies to `options` (keksdose's shop picker past its first hundred shops).
36
40
  */
37
41
  export declare function matchesSearch(words: readonly string[], texts: readonly (string | undefined)[], locale?: string): boolean;
38
42
  /** {@link rankMatch}'s answer: lower is better, `-1` is no match. */
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/text-match.ts"],"sourcesContent":["/**\n * How typing into a kit list matches its rows — one rule for every list (DUP-5, refactor\n * audit 2026-10).\n *\n * There were six. \"zurich\" found Zürich in CountrySelect and the command palette and in no\n * EntityCombobox, Combobox, MultiSelect or DataTable text filter, where keksdose's\n * Swiss-German payees and categories and kastlan's eighteen entity pickers live; \"İ\"\n * folded by the locale in GroupedPicker and nowhere in the combobox family. The folding\n * only ever widens a match, so moving every list onto it took nothing away.\n */\n\n/**\n * A text as search compares it: the locale's lower case, accents off, ß spelt \"ss\" —\n * \"Zürich\" and \"ZURICH\" both read \"zurich\", \"Straße\" reads \"strasse\". Punctuation and\n * symbols stay: a currency is found by its \"€\", and \"c++\" is not the empty query.\n *\n * Lower-cased by the locale FIRST, then decomposed: the Turkish \"İ\" lower-cases to \"i\"\n * and the dotted capital's mark is then dropped like any other, so \"istanbul\" finds\n * \"İSTANBUL\" in every locale, while \"I\" folds to the dotless \"ı\" in Turkish alone.\n * `locale` left out is the runtime's default; a malformed tag folds as if left out.\n */\nexport function foldForSearch(text: string, locale?: string): string {\n let lower: string;\n try {\n lower = text.toLocaleLowerCase(locale);\n } catch {\n lower = text.toLocaleLowerCase();\n }\n return lower.normalize(\"NFD\").replace(/\\p{M}+/gu, \"\").replace(/ß/g, \"ss\");\n}\n\n/**\n * A picker's query as its words, each folded (0.51.4, keksdose's /prices shop picker):\n * \"Migros Zürich\" → `[\"migros\", \"zurich\"]`. An empty or blank query has no words.\n */\nexport function searchWords(query: string, locale?: string): string[] {\n return foldForSearch(query, locale).split(/\\s+/).filter((word) => word !== \"\");\n}\n\n/**\n * Whether a row matches a picker's query: EVERY word appears in at least one of the row's\n * texts — \"migros 8004\" finds a row named \"Migros · 8004 Zürich\", and a row whose chain is\n * its group and whose place is its label (pass both). Until 0.51.4 the whole query had to\n * be ONE substring of one text, so two words found nothing unless they stood side by side\n * in that order. One word matches exactly as before, and so does the old query when it\n * was a substring. No words match everything.\n *\n * `words` from {@link searchWords}; `texts` as they are (folded here), `undefined` skipped.\n */\nexport function matchesSearch(\n words: readonly string[],\n texts: readonly (string | undefined)[],\n locale?: string,\n): boolean {\n if (words.length === 0) return true;\n // One haystack per row; a word holds no whitespace, so it cannot match across the\n // newline between two texts.\n const hay = texts.filter((t): t is string => t !== undefined).map((t) => foldForSearch(t, locale)).join(\"\\n\");\n return words.every((word) => hay.includes(word));\n}\n\n/** {@link rankMatch}'s answer: lower is better, `-1` is no match. */\nexport type MatchRank = -1 | 0 | 1 | 2;\n\n/**\n * How well `label` answers `query` — CountrySelect's ranking, for every list that orders\n * its hits:\n *\n * - `0`: the query IS the row — its `code` (\"ch\" means Switzerland before it means Chad)\n * or the whole label;\n * - `1`: the label starts with it;\n * - `2`: the label contains it;\n * - `-1`: no match.\n *\n * Both sides are folded here ({@link foldForSearch}, by `locale`), so pass them as typed\n * and as shown. An empty query matches every row alike (`0`). Sort by the rank with a\n * stable sort, and rows of one rank keep the order they came in.\n */\nexport function rankMatch(\n label: string,\n query: string,\n { code, locale }: { code?: string; locale?: string } = {},\n): MatchRank {\n const q = foldForSearch(query.trim(), locale);\n if (!q) return 0;\n const text = foldForSearch(label, locale);\n if (text === q || (code !== undefined && foldForSearch(code, locale) === q)) return 0;\n if (text.startsWith(q)) return 1;\n return text.includes(q) ? 2 : -1;\n}\n"],"mappings":";AAqBO,SAAS,cAAc,MAAc,QAAyB;AACnE,MAAI;AACJ,MAAI;AACF,YAAQ,KAAK,kBAAkB,MAAM;AAAA,EACvC,QAAQ;AACN,YAAQ,KAAK,kBAAkB;AAAA,EACjC;AACA,SAAO,MAAM,UAAU,KAAK,EAAE,QAAQ,YAAY,EAAE,EAAE,QAAQ,MAAM,IAAI;AAC1E;AAMO,SAAS,YAAY,OAAe,QAA2B;AACpE,SAAO,cAAc,OAAO,MAAM,EAAE,MAAM,KAAK,EAAE,OAAO,CAAC,SAAS,SAAS,EAAE;AAC/E;AAYO,SAAS,cACd,OACA,OACA,QACS;AACT,MAAI,MAAM,WAAW,EAAG,QAAO;AAG/B,QAAM,MAAM,MAAM,OAAO,CAAC,MAAmB,MAAM,MAAS,EAAE,IAAI,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,EAAE,KAAK,IAAI;AAC5G,SAAO,MAAM,MAAM,CAAC,SAAS,IAAI,SAAS,IAAI,CAAC;AACjD;AAmBO,SAAS,UACd,OACA,OACA,EAAE,MAAM,OAAO,IAAwC,CAAC,GAC7C;AACX,QAAM,IAAI,cAAc,MAAM,KAAK,GAAG,MAAM;AAC5C,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,OAAO,cAAc,OAAO,MAAM;AACxC,MAAI,SAAS,KAAM,SAAS,UAAa,cAAc,MAAM,MAAM,MAAM,EAAI,QAAO;AACpF,MAAI,KAAK,WAAW,CAAC,EAAG,QAAO;AAC/B,SAAO,KAAK,SAAS,CAAC,IAAI,IAAI;AAChC;","names":[]}
1
+ {"version":3,"sources":["../../src/lib/text-match.ts"],"sourcesContent":["/**\n * How typing into a kit list matches its rows — one rule for every list (DUP-5, refactor\n * audit 2026-10).\n *\n * There were six. \"zurich\" found Zürich in CountrySelect and the command palette and in no\n * EntityCombobox, Combobox, MultiSelect or DataTable text filter, where keksdose's\n * Swiss-German payees and categories and kastlan's eighteen entity pickers live; \"İ\"\n * folded by the locale in GroupedPicker and nowhere in the combobox family. The folding\n * only ever widens a match, so moving every list onto it took nothing away.\n */\n\n/**\n * A text as search compares it: the locale's lower case, accents off, ß spelt \"ss\" —\n * \"Zürich\" and \"ZURICH\" both read \"zurich\", \"Straße\" reads \"strasse\". Punctuation and\n * symbols stay: a currency is found by its \"€\", and \"c++\" is not the empty query.\n *\n * Lower-cased by the locale FIRST, then decomposed: the Turkish \"İ\" lower-cases to \"i\"\n * and the dotted capital's mark is then dropped like any other, so \"istanbul\" finds\n * \"İSTANBUL\" in every locale, while \"I\" folds to the dotless \"ı\" in Turkish alone.\n * `locale` left out is the runtime's default; a malformed tag folds as if left out.\n */\nexport function foldForSearch(text: string, locale?: string): string {\n let lower: string;\n try {\n lower = text.toLocaleLowerCase(locale);\n } catch {\n lower = text.toLocaleLowerCase();\n }\n return lower\n .normalize(\"NFD\")\n .replace(/\\p{M}+/gu, \"\")\n .replace(/ß/g, \"ss\");\n}\n\n/**\n * A picker's query as its words, each folded (0.51.4, keksdose's /prices shop picker):\n * \"Migros Zürich\" → `[\"migros\", \"zurich\"]`. An empty or blank query has no words.\n */\nexport function searchWords(query: string, locale?: string): string[] {\n return foldForSearch(query, locale)\n .split(/\\s+/)\n .filter((word) => word !== \"\");\n}\n\n/**\n * Whether a row matches a picker's query: EVERY word appears in at least one of the row's\n * texts — \"migros 8004\" finds a row named \"Migros · 8004 Zürich\", and a row whose chain is\n * its group and whose place is its label (pass both). Until 0.51.4 the whole query had to\n * be ONE substring of one text, so two words found nothing unless they stood side by side\n * in that order. One word matches exactly as before, and so does the old query when it\n * was a substring. No words match everything.\n *\n * `words` from {@link searchWords}; `texts` as they are (folded here), `undefined` skipped.\n *\n * Exported since 0.51.5 for an app's own async source: a picker shows `loadOptions`'\n * rows as they come, so a source that narrows on the client filters with this, the same\n * rule the kit applies to `options` (keksdose's shop picker past its first hundred shops).\n */\nexport function matchesSearch(\n words: readonly string[],\n texts: readonly (string | undefined)[],\n locale?: string,\n): boolean {\n if (words.length === 0) return true;\n // One haystack per row; a word holds no whitespace, so it cannot match across the\n // newline between two texts.\n const hay = texts\n .filter((t): t is string => t !== undefined)\n .map((t) => foldForSearch(t, locale))\n .join(\"\\n\");\n return words.every((word) => hay.includes(word));\n}\n\n/** {@link rankMatch}'s answer: lower is better, `-1` is no match. */\nexport type MatchRank = -1 | 0 | 1 | 2;\n\n/**\n * How well `label` answers `query` — CountrySelect's ranking, for every list that orders\n * its hits:\n *\n * - `0`: the query IS the row — its `code` (\"ch\" means Switzerland before it means Chad)\n * or the whole label;\n * - `1`: the label starts with it;\n * - `2`: the label contains it;\n * - `-1`: no match.\n *\n * Both sides are folded here ({@link foldForSearch}, by `locale`), so pass them as typed\n * and as shown. An empty query matches every row alike (`0`). Sort by the rank with a\n * stable sort, and rows of one rank keep the order they came in.\n */\nexport function rankMatch(\n label: string,\n query: string,\n { code, locale }: { code?: string; locale?: string } = {},\n): MatchRank {\n const q = foldForSearch(query.trim(), locale);\n if (!q) return 0;\n const text = foldForSearch(label, locale);\n if (text === q || (code !== undefined && foldForSearch(code, locale) === q)) return 0;\n if (text.startsWith(q)) return 1;\n return text.includes(q) ? 2 : -1;\n}\n"],"mappings":";AAqBO,SAAS,cAAc,MAAc,QAAyB;AACnE,MAAI;AACJ,MAAI;AACF,YAAQ,KAAK,kBAAkB,MAAM;AAAA,EACvC,QAAQ;AACN,YAAQ,KAAK,kBAAkB;AAAA,EACjC;AACA,SAAO,MACJ,UAAU,KAAK,EACf,QAAQ,YAAY,EAAE,EACtB,QAAQ,MAAM,IAAI;AACvB;AAMO,SAAS,YAAY,OAAe,QAA2B;AACpE,SAAO,cAAc,OAAO,MAAM,EAC/B,MAAM,KAAK,EACX,OAAO,CAAC,SAAS,SAAS,EAAE;AACjC;AAgBO,SAAS,cACd,OACA,OACA,QACS;AACT,MAAI,MAAM,WAAW,EAAG,QAAO;AAG/B,QAAM,MAAM,MACT,OAAO,CAAC,MAAmB,MAAM,MAAS,EAC1C,IAAI,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,EACnC,KAAK,IAAI;AACZ,SAAO,MAAM,MAAM,CAAC,SAAS,IAAI,SAAS,IAAI,CAAC;AACjD;AAmBO,SAAS,UACd,OACA,OACA,EAAE,MAAM,OAAO,IAAwC,CAAC,GAC7C;AACX,QAAM,IAAI,cAAc,MAAM,KAAK,GAAG,MAAM;AAC5C,MAAI,CAAC,EAAG,QAAO;AACf,QAAM,OAAO,cAAc,OAAO,MAAM;AACxC,MAAI,SAAS,KAAM,SAAS,UAAa,cAAc,MAAM,MAAM,MAAM,EAAI,QAAO;AACpF,MAAI,KAAK,WAAW,CAAC,EAAG,QAAO;AAC/B,SAAO,KAAK,SAAS,CAAC,IAAI,IAAI;AAChC;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/translation-review.ts"],"sourcesContent":["/**\n * The pure half of an app's translation review (H1 in docs/i18n-harmonization.md): from\n * the strings the app ships and the verdicts its server stores to one row per (locale,\n * key) with a status — keksdose's `features/translations/translation-catalogue.ts` and\n * kastlan's copy of it, which had grown apart by a fifth status and a second kind of key.\n *\n * WHY THE STRINGS ARE THE CATALOGUE. Nothing on the server lists which strings exist: a\n * verdict only says what somebody thought of one. So the rows are built from what the app\n * ships — its locale bundles, kastlan's document texts, the kit's own words\n * (`kitLabelStrings`) — and the review can never offer a string users do not see. A\n * verdict is stored WITH the wording it was given on, and a string that changed since is\n * noticed by comparing the two: `changed`, read it again, whatever the verdict was.\n *\n * WHAT STAYS IN THE APP. Which locale is read against which (keksdose: everything against\n * English, English against de-CH; kastlan: against German, German against English), where\n * the strings come from, who may review what (the locales and areas its server answers\n * with), and every request. The kit takes those as input and never derives them.\n *\n * camelCase, like the rest of the kit. The contract's wire shape is snake_case\n * (`reference_text`, `reviewer_name`, `reviewed_at`); {@link fromApiReview} and\n * {@link toApiWrite} are the two lines each app would otherwise write — both apps speak\n * the same contract, so the mapping is written once, here.\n */\n\nimport { foldForSearch } from \"./text-match\";\n\n// ── Shapes ──────────────────────────────────────────────────────────────────────\n\nexport type TranslationVerdict = \"APPROVED\" | \"NEEDS_CHANGE\";\n\n/** One stored verdict: what a reviewer said about one string in one locale. */\nexport interface TranslationReview {\n locale: string;\n key: string;\n /** The wording that was judged — compared with today's to notice a change. Empty for\n * a string the locale lacked (a suggested translation for a `missing` row). */\n text: string;\n /** The reference wording at the time. `null` from a server that did not store it. */\n referenceText: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n /** The reviewer's wording — or, for a missing string, the translation to add. */\n suggestion: string | null;\n /** `null` once the reviewer's account has been erased. */\n reviewerName: string | null;\n /** ISO timestamp. */\n reviewedAt: string;\n}\n\n/** What a save sends: the verdict plus the wording it is given on. */\nexport interface TranslationReviewWrite {\n locale: string;\n key: string;\n text: string;\n referenceText: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n suggestion: string | null;\n}\n\n/** What a reset sends: back to \"unreviewed\". */\nexport interface TranslationReviewKey {\n locale: string;\n key: string;\n}\n\n/**\n * Where a string stands, in the order a reviewer works through them: what is not there\n * at all, what nobody has read, what changed after it was read, what was sent back, and\n * what is done. `missing` never occurs for an app whose locales have every key\n * (keksdose); kastlan's French lacks 172 screen texts.\n */\nexport type ReviewStatus = \"missing\" | \"unreviewed\" | \"changed\" | \"needs_change\" | \"approved\";\n\nexport const REVIEW_STATUSES: readonly ReviewStatus[] = [\n \"missing\",\n \"unreviewed\",\n \"changed\",\n \"needs_change\",\n \"approved\",\n];\n\nexport interface TranslationRow {\n /** `${locale}|${key}` — unique across every locale on a page. A bar, not a colon:\n * kastlan's keys contain colons (`common:actions.save`). */\n id: string;\n key: string;\n /** The key's group: `budget` for `budget.rta`, `common` for `common:actions.save`,\n * `kit` for the kit's own words. See {@link keyNamespace}. */\n namespace: string;\n /** Where the string comes from, in the app's own words — kastlan's `screen` and\n * `documents`, keksdose's one source. `\"\"` when the app does not say. */\n source: string;\n locale: string;\n /** The wording users see today; empty when the locale lacks the string. */\n text: string;\n /** The same key in the reference locale. */\n reference: string;\n status: ReviewStatus;\n review: TranslationReview | null;\n /** The interpolations and tags differ from the reference's — `{{count}}` dropped, a\n * `<1>` link lost, a `{date}` renamed. A machine can check that much, so it does,\n * before a person reads. Never set on a missing string: it has nothing to lose. */\n placeholderMismatch: boolean;\n}\n\n// ── The wire contract ───────────────────────────────────────────────────────────\n\n/** A verdict as `GET /translations/reviews` returns it (H1's shared contract). Typed\n * structurally, so an app's generated OpenAPI type fits without a cast. */\nexport interface ApiTranslationReview {\n locale: string;\n key: string;\n text: string;\n reference_text: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n suggestion: string | null;\n reviewer_name: string | null;\n /** server-kit 0.10: the name's two parts (`reviewer_name` is them in the reader's order). */\n reviewer_first_name?: string | null;\n reviewer_last_name?: string | null;\n reviewed_at: string;\n}\n\n/** `GET /translations/reviews` (server-kit `TranslationReviewsResponse`): the locales and\n * areas the caller may review (`areas` null: every area; `[\"kit\"]` for a review token)\n * and every stored verdict in them. Typed structurally, as {@link ApiTranslationReview}. */\nexport interface ApiTranslationReviewsResponse {\n locales: string[];\n areas?: string[] | null;\n reviews: ApiTranslationReview[];\n}\n\n/** One item of `PUT /translations/reviews`. */\nexport interface ApiTranslationReviewWrite {\n locale: string;\n key: string;\n text: string;\n reference_text: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n suggestion: string | null;\n}\n\n/** A verdict from the server, in the kit's spelling. */\nexport function fromApiReview(review: ApiTranslationReview): TranslationReview {\n return {\n locale: review.locale,\n key: review.key,\n text: review.text,\n referenceText: review.reference_text,\n verdict: review.verdict,\n note: review.note,\n suggestion: review.suggestion,\n reviewerName: review.reviewer_name,\n reviewedAt: review.reviewed_at,\n };\n}\n\n/** A save, in the server's spelling. `TranslationReviewKey` needs no mapping — it is\n * `{ locale, key }` on both sides. */\nexport function toApiWrite(write: TranslationReviewWrite): ApiTranslationReviewWrite {\n return {\n locale: write.locale,\n key: write.key,\n text: write.text,\n reference_text: write.referenceText,\n verdict: write.verdict,\n note: write.note,\n suggestion: write.suggestion,\n };\n}\n\n// ── Strings ─────────────────────────────────────────────────────────────────────\n\n/**\n * A nested bundle as `key → string`, in the bundle's own order. Non-string leaves are\n * skipped rather than stringified into something nobody wrote.\n *\n * `prefix` is put in front of every key AS IS, so it names the separator too:\n * `flattenStrings(bundle)` is keksdose's `budget.rta`, `flattenStrings(tree, \"common:\")`\n * kastlan's `common:actions.save`, and `flattenStrings(kitLabelStrings(labels), \"kit.\")`\n * the kit's own words as `kit.combobox.resultCount(3)` — already flat, so only the prefix\n * is added.\n */\nexport function flattenStrings(tree: Readonly<Record<string, unknown>>, prefix = \"\"): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(tree)) {\n const path = `${prefix}${key}`;\n if (typeof value === \"string\") out[path] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n Object.assign(out, flattenStrings(value as Record<string, unknown>, `${path}.`));\n }\n }\n return out;\n}\n\n/**\n * The key's group, for the namespace filter: the part before a colon when there is one\n * (kastlan's `common:actions.save` → `common`, `doc_text.invoice:due` →\n * `doc_text.invoice`), else the first dotted segment (keksdose's `budget.rta` →\n * `budget`, the kit's `kit.combobox.resultCount(3)` → `kit`). Only the part before a\n * sample's `(` is looked at, so a colon inside one cannot move the split.\n */\nexport function keyNamespace(key: string): string {\n const head = key.split(\"(\", 1)[0];\n const colon = head.indexOf(\":\");\n return colon >= 0 ? head.slice(0, colon) : head.split(\".\", 1)[0];\n}\n\n// i18next `{{x}}` (formatting options ignored: `{{x, number}}` is `{{x}}`); a Python\n// format field `{x}` / `{0}` / `{amount:.2f}` (kastlan's document texts), but not a\n// LaTeX argument (`\\textbf{x}` — a letter or backslash right before the brace); a\n// numbered or named tag (`<1>`, `<strong>`), not prose in angle brackets (\"<deleted\n// user>\"); and a nested `$t(key)`. `{{x}}` is tried first at its position and consumed\n// whole, so it is never counted a second time as `{x}`.\nconst PLACEHOLDER_RE =\n /\\{\\{\\s*([^}\\s,]+)[^}]*\\}\\}|(?<![\\\\A-Za-z])\\{([a-z_][a-z0-9_]*|\\d+)(?:[!:][^{}]*)?\\}|<\\/?(\\d+|[a-z][a-z0-9]*)\\s*\\/?>|\\$t\\(([^)]+)\\)/g;\n\n/** The placeholders in a string, as a sorted multiset: `{{count}}`, `{date}`, `<1>`,\n * `$t(common.save)`. */\nexport function placeholderTokens(text: string): string[] {\n const found: string[] = [];\n for (const m of text.matchAll(PLACEHOLDER_RE)) {\n if (m[1]) found.push(`{{${m[1]}}}`);\n // `{ref:retention}` (ui-kit 0.28's legal cross-reference) keeps its target: a\n // translation that points at another section changed what the sentence says. Every\n // other `{x:spec}` is a format spec, which a translation may change.\n else if (m[2]) found.push(m[2] === \"ref\" ? m[0] : `{${m[2]}}`);\n else if (m[3]) found.push(`<${m[3]}>`);\n else if (m[4]) found.push(`$t(${m[4]})`);\n }\n return found.sort();\n}\n\n/** Whether `text` has other placeholders than `reference` — dropped, renamed or added.\n * Moving one is fine: a translation reorders a sentence. */\nexport function placeholderMismatch(text: string, reference: string): boolean {\n const a = placeholderTokens(text);\n const b = placeholderTokens(reference);\n return a.length !== b.length || a.some((p, i) => p !== b[i]);\n}\n\n// ── Status ──────────────────────────────────────────────────────────────────────\n\n/**\n * A verdict counts only for the wording it was given on. If the string or its reference\n * changed since, it is `changed` — read it again — whatever the verdict was. A string the\n * locale lacks is `missing` until somebody suggests its translation (stored as\n * NEEDS_CHANGE on the empty text, so it reads `needs_change`, and `changed` once a\n * developer adds the string).\n */\nexport function reviewStatus(\n review: TranslationReview | null | undefined,\n text: string,\n reference: string,\n): ReviewStatus {\n if (!review) return text === \"\" && reference !== \"\" ? \"missing\" : \"unreviewed\";\n if (review.text !== text) return \"changed\";\n if (review.referenceText != null && review.referenceText !== reference) return \"changed\";\n return review.verdict === \"APPROVED\" ? \"approved\" : \"needs_change\";\n}\n\n/**\n * Whether `key` lies in `area`: the key IS the area, or sits under it — `legal.terms`\n * and kastlan's `legal:terms` are in `legal`, `legalese.title` is not.\n *\n * 0.28: the kit's own words of that area too — `kit.legal.sections.terms.law.body(…)`\n * is in `legal`. All three apps list the kit's labels under `kit.`\n * (`flattenStrings(kitLabelStrings(labels), \"kit.\")`), and since 0.28 the kit writes\n * the shared legal sections, so a lawyer with a `[\"legal\"]` grant who was not shown\n * `kit.legal.*` would not see half of the Privacy Policy — and the server would refuse\n * the verdicts (docs/legal-harmonization.md §7.5). server-kit's `in_areas` and the apps'\n * copies of it apply the same rule.\n */\nexport function keyInArea(key: string, area: string): boolean {\n return (\n key === area || key.startsWith(`${area}.`) || key.startsWith(`${area}:`) || key.startsWith(`kit.${area}.`)\n );\n}\n\n/**\n * The area of `areas` that `key` lies in ({@link keyInArea}), or `undefined` — the\n * translation page's grouping by the same rule the filter and the server use, so\n * `kit.legal.sections.privacy.rights.lead` is grouped under `legal` with the app's own\n * legal texts instead of under `kit.legal`:\n *\n * const namespaceOf = (key: string) => reviewAreaOf(key, [\"legal\"]) ?? ownNamespaceOf(key);\n *\n * Where two areas both hold the key (`legal` and `legal.privacy`), the longer — the more\n * specific — wins, whatever their order. `inArea` is the app's own rule, as for\n * {@link keyInAreas}.\n */\nexport function reviewAreaOf(\n key: string,\n areas: readonly string[],\n inArea: (key: string, area: string) => boolean = keyInArea,\n): string | undefined {\n let found: string | undefined;\n for (const area of areas) {\n if (inArea(key, area) && (found === undefined || area.length > found.length)) found = area;\n }\n return found;\n}\n\n/**\n * Whether `key` lies in one of `areas` — the scope a reviewer may be limited to\n * (keksdose: `[\"legal\"]`, a lawyer who judges the Imprint, the Privacy Policy and the\n * Terms and sees nothing else). `null`/`undefined` is every area. The server applies the\n * same rule and refuses verdicts outside; this decides only what is listed.\n */\nexport function keyInAreas(\n key: string,\n areas: readonly string[] | null | undefined,\n inArea: (key: string, area: string) => boolean = keyInArea,\n): boolean {\n return !areas || areas.some((area) => inArea(key, area));\n}\n\nexport interface TranslationRowsInput {\n locale: string;\n /** The locale's strings, `key → text` ({@link flattenStrings}). */\n strings: Readonly<Record<string, string>>;\n /** The reference locale's strings — whichever locale THIS app reads `locale` against. */\n reference: Readonly<Record<string, string>>;\n /** The verdicts: this locale's by key, or the whole list as the server sent it (other\n * locales' verdicts are skipped). */\n reviews?: ReadonlyMap<string, TranslationReview> | readonly TranslationReview[];\n /** Default {@link keyNamespace}. */\n namespaceOf?: (key: string) => string;\n /** The row's source, an app-defined word (kastlan: `doc_text.` keys are `documents`,\n * the rest `screen`). Default: none (`\"\"`). */\n sourceOf?: (key: string) => string;\n /** Keep only keys inside these areas ({@link keyInAreas}); `null` keeps every key. */\n areas?: readonly string[] | null;\n /** Default {@link keyInArea}. */\n inArea?: (key: string, area: string) => boolean;\n}\n\n/**\n * Every key of one locale, with its status: the reference's keys first, in its order, so\n * rows read the way the app's authors wrote them; a key only this locale has is appended\n * rather than dropped (a parity test should forbid it, but the page should not lie if one\n * slips through).\n */\nexport function translationRows({\n locale,\n strings,\n reference,\n reviews,\n namespaceOf: groupOf = keyNamespace,\n sourceOf,\n areas,\n inArea,\n}: TranslationRowsInput): TranslationRow[] {\n const byKey = new Map<string, TranslationReview>();\n if (reviews instanceof Map) {\n for (const [key, review] of reviews) byKey.set(key, review);\n } else if (reviews) {\n for (const review of reviews as readonly TranslationReview[]) {\n if (review.locale === locale) byKey.set(review.key, review);\n }\n }\n const keys = Object.keys(reference);\n for (const key of Object.keys(strings)) if (!(key in reference)) keys.push(key);\n return keys\n .filter((key) => keyInAreas(key, areas, inArea))\n .map((key) => {\n const text = strings[key] ?? \"\";\n const ref = reference[key] ?? \"\";\n const review = byKey.get(key) ?? null;\n return {\n id: `${locale}|${key}`,\n key,\n namespace: groupOf(key),\n source: sourceOf?.(key) ?? \"\",\n locale,\n text,\n reference: ref,\n status: reviewStatus(review, text, ref),\n review,\n placeholderMismatch: text !== \"\" && placeholderMismatch(text, ref),\n };\n });\n}\n\n/** How many rows stand where, and how many there are. */\nexport type TranslationSummary = Record<ReviewStatus, number> & { total: number };\n\nexport function summariseRows(rows: readonly TranslationRow[]): TranslationSummary {\n const summary: TranslationSummary = {\n missing: 0,\n unreviewed: 0,\n changed: 0,\n needs_change: 0,\n approved: 0,\n total: rows.length,\n };\n for (const row of rows) summary[row.status] += 1;\n return summary;\n}\n\n// ── Filtering ───────────────────────────────────────────────────────────────────\n\n/** The panel's filters. `\"all\"` switches one off. */\nexport interface TranslationReviewFilter {\n status: ReviewStatus | \"all\";\n source: string;\n namespace: string;\n /** Searched in the key, the text and the reference, folded as every kit list's search\n * is (`foldForSearch`): no case, no accents — \"uberweisung\" finds \"Überweisung\". */\n query: string;\n placeholdersOnly: boolean;\n}\n\nexport const DEFAULT_TRANSLATION_REVIEW_FILTER: TranslationReviewFilter = {\n status: \"all\",\n source: \"all\",\n namespace: \"all\",\n query: \"\",\n placeholdersOnly: false,\n};\n\nexport function filterTranslationRows(\n rows: readonly TranslationRow[],\n filter: Partial<TranslationReviewFilter>,\n): TranslationRow[] {\n const f = { ...DEFAULT_TRANSLATION_REVIEW_FILTER, ...filter };\n // Folded as every kit list's search is (DUP-5, refactor audit 2026-10).\n const q = foldForSearch(f.query.trim());\n return rows.filter(\n (row) =>\n (f.status === \"all\" || row.status === f.status) &&\n (f.source === \"all\" || row.source === f.source) &&\n (f.namespace === \"all\" || row.namespace === f.namespace) &&\n (!f.placeholdersOnly || row.placeholderMismatch) &&\n (!q || [row.key, row.text, row.reference].some((s) => foldForSearch(s).includes(q))),\n );\n}\n\n// ── Grouping ────────────────────────────────────────────────────────────────────\n\n/** One group of rows — an area, a source — and how they stand. */\nexport interface TranslationRowGroup {\n key: string;\n rows: TranslationRow[];\n summary: TranslationSummary;\n}\n\n/**\n * Rows in groups, each group where its first row is — the reference's order, so the areas\n * read the way the app's authors wrote the bundle — and each group's rows in their own\n * order. keksdose live #377: a reviewer on a phone works area by area (\"the budget\n * strings, then the legal ones\"), and a flat list of 3859 rows is not a way to see\n * where an area stands.\n *\n * `groupOf` names a row's group: `(row) => row.namespace` for the areas,\n * `(row) => row.source` for kastlan's screen texts and documents.\n */\nexport function groupTranslationRows(\n rows: readonly TranslationRow[],\n groupOf: (row: TranslationRow) => string,\n): TranslationRowGroup[] {\n const byKey = new Map<string, TranslationRow[]>();\n for (const row of rows) {\n const key = groupOf(row);\n const list = byKey.get(key);\n if (list) list.push(row);\n else byKey.set(key, [row]);\n }\n return [...byKey].map(([key, list]) => ({ key, rows: list, summary: summariseRows(list) }));\n}\n\n/**\n * The rows a group's \"Approve the unreviewed\" takes: the ones nobody has given a verdict\n * and that have a text. Not `changed` — a string that moved since it was judged asks to\n * be READ again, which a bulk action is the opposite of — and not `missing`, which has\n * nothing to approve.\n */\nexport function unreviewedRows(rows: readonly TranslationRow[]): TranslationRow[] {\n return rows.filter((row) => row.status === \"unreviewed\" && row.text !== \"\");\n}\n\n// ── Writing ─────────────────────────────────────────────────────────────────────\n\n/** What gets stored for a verdict: the wording it was given on, so a later change of the\n * string (or of its reference) shows up as `changed`. */\nexport function reviewWrite(\n row: TranslationRow,\n verdict: TranslationVerdict,\n note: string | null = null,\n suggestion: string | null = null,\n): TranslationReviewWrite {\n return {\n locale: row.locale,\n key: row.key,\n text: row.text,\n referenceText: row.reference,\n verdict,\n note,\n suggestion,\n };\n}\n\n/** What takes a set of verdicts back: see {@link reviewUndo}. */\nexport interface TranslationReviewUndo {\n /** The verdicts the rows had before, to store again — each on the wording it was\n * given on, so a row that was `changed` reads `changed` again. */\n writes: TranslationReviewWrite[];\n /** The rows that had no verdict before: back to unreviewed. */\n clears: TranslationReviewKey[];\n}\n\n/**\n * How to take back what was just said about `rows` — the rows AS THEY WERE before the\n * write, with the verdicts they carried then. The panel's Undo toast (0.25, keksdose live\n * #377) runs it: a swipe on a phone approves in one movement, and a movement can be a\n * mistake.\n *\n * A row that had a verdict gets it stored again (its note, its suggestion, the wording it\n * was judged on); one that had none is cleared. The server stamps the restored verdict\n * with the person undoing and the time, as it stamps every write — the contract has no\n * way to write a verdict in somebody else's name, and should not.\n */\nexport function reviewUndo(rows: readonly TranslationRow[]): TranslationReviewUndo {\n const writes: TranslationReviewWrite[] = [];\n const clears: TranslationReviewKey[] = [];\n for (const row of rows) {\n const before = row.review;\n if (!before) {\n clears.push({ locale: row.locale, key: row.key });\n continue;\n }\n writes.push({\n locale: row.locale,\n key: row.key,\n text: before.text,\n referenceText: before.referenceText,\n verdict: before.verdict,\n note: before.note,\n suggestion: before.suggestion,\n });\n }\n return { writes, clears };\n}\n\n/** The app's cached verdict list with `written` in place of what was said before — a\n * save answers with the rows it wrote, so a page patches its copy instead of\n * downloading every verdict again after each click. Any spelling with `locale` and\n * `key` (the API's or the kit's). */\nexport function mergeReviews<T extends TranslationReviewKey>(prev: readonly T[], written: readonly T[]): T[] {\n const id = (r: TranslationReviewKey) => `${r.locale}|${r.key}`;\n const replaced = new Set(written.map(id));\n return [...prev.filter((r) => !replaced.has(id(r))), ...written];\n}\n\n/** The cached list without the verdicts on `cleared`. */\nexport function dropReviews<T extends TranslationReviewKey>(\n prev: readonly T[],\n cleared: readonly TranslationReviewKey[],\n): T[] {\n const gone = new Set(cleared.map((r) => `${r.locale}|${r.key}`));\n return prev.filter((r) => !gone.has(`${r.locale}|${r.key}`));\n}\n\n// ── Swipe bindings ──────────────────────────────────────────────────────────────\n\n/**\n * What a phone card's swipe can be bound to in `TranslationReviewPanel`'s `swipe`\n * (keksdose — Marcel's live #377 rework, 2026-10-03: *\"Add the swipe options to be shown\n * also to the settings /settings#interaction area where the other swipe options are\n * defined\"*). keksdose lets the user bind every list's swipes there — per side, a primary\n * action at the first threshold and a secondary one at a longer drag — and lists each\n * surface's ids in its `SWIPE_ACTIONS`; this is the translation list's, in the order a\n * settings page offers them.\n *\n * - `approve` — the string is right as it stands. With the panel's Undo toast.\n * - `edit` — open the editor with the cursor in the wording: \"Needs a change\" (or\n * \"Suggest translation\" on a missing string). Writes nothing; the editor does.\n * - `clear` — take the verdict back: unreviewed again. With the Undo toast, which stores\n * the verdict again.\n *\n * THERE IS NO SEPARATE \"needs a change\". The editor has no verdict to preselect: Approve\n * and \"Needs a change\" stand side by side in it, and \"Needs a change\" takes a note or a\n * different wording — a verdict without either tells whoever fixes the string nothing, so\n * a swipe never sends one blind (0.25). The one honest thing a \"needs a change\" swipe can\n * do is therefore open the editor with the cursor in the wording — which is `edit`, and\n * `edit` already says \"Needs a change\" on the card. A second id doing the same would arm\n * a second threshold that does what the first already did: the duplicate keksdose's\n * `resolveSwipePlan` drops for exactly that reason.\n */\nexport const TRANSLATION_REVIEW_SWIPE_ACTIONS = [\"approve\", \"edit\", \"clear\"] as const;\n\n/** One of {@link TRANSLATION_REVIEW_SWIPE_ACTIONS}. */\nexport type TranslationReviewSwipeAction = (typeof TRANSLATION_REVIEW_SWIPE_ACTIONS)[number];\n\n/**\n * Which swipe does what on a phone card — `TranslationReviewPanel`'s `swipe`. Each side is\n * an ordered ladder, exactly as `SwipeableRow` and DataTable's `mobileSwipeActions` model\n * one: index 0 commits at the first threshold, index 1 at the longer drag (and so on — the\n * thresholds spread evenly over the card's width). A side left out, or empty, does not\n * swipe.\n *\n * LOGICAL SIDES: `end` is a drag toward the reading end of the line — right in a\n * left-to-right page, left in a right-to-left one — and `start` the other way, so one\n * binding holds in both directions. An app whose settings store physical sides (keksdose's\n * `right`/`left`) hands `right` as `end` for a left-to-right page.\n */\nexport interface TranslationReviewSwipeBinding {\n /** A drag toward the reading START, nearest threshold first. */\n start?: readonly TranslationReviewSwipeAction[];\n /** A drag toward the reading END, nearest threshold first. */\n end?: readonly TranslationReviewSwipeAction[];\n}\n\n/** What `swipe={true}` means — 0.25's fixed mapping: approve toward the end, open the\n * editor (\"Needs a change\") toward the start. A settings page's \"reset\" goes back here. */\nexport const DEFAULT_TRANSLATION_REVIEW_SWIPE: TranslationReviewSwipeBinding = Object.freeze({\n start: Object.freeze([\"edit\"] as const),\n end: Object.freeze([\"approve\"] as const),\n});\n\n/** The ladders one row actually offers, from a {@link TranslationReviewSwipeBinding}. */\nexport interface TranslationReviewSwipePlan {\n start: TranslationReviewSwipeAction[];\n end: TranslationReviewSwipeAction[];\n}\n\n/**\n * The binding resolved against one row — keksdose's `resolveSwipePlan`, for this list.\n * An id the row cannot offer DROPS OUT and the ladder closes up behind it, so the second\n * stage becomes the first rather than the side going dead behind an unreachable first\n * stage (or arming a threshold that does nothing):\n *\n * - `approve`: not on a missing string (nothing to approve) or an approved one (it would\n * say it again) — the rows that have no approve button either;\n * - `clear`: not without `canClear` (the app passed no `onClear`), and not on a row with\n * no verdict to take back (unreviewed; missing with no suggestion);\n * - `edit`: on every row;\n * - an id named twice on one side: the second time (a longer drag to the same effect);\n * - an id this version does not know (a binding stored by another version, an app's own\n * \"none\" slot): dropped like one that does not apply.\n *\n * Only what the ROW decides. Whether the panel may write at all — `readOnly`, no\n * `onSave`, a write lock, the row's own write still out — is the panel's, and then no\n * side swipes.\n */\nexport function translationReviewSwipePlan(\n binding: TranslationReviewSwipeBinding,\n row: TranslationRow,\n { canClear = false }: { canClear?: boolean } = {},\n): TranslationReviewSwipePlan {\n const offers = (id: TranslationReviewSwipeAction): boolean => {\n switch (id) {\n case \"approve\":\n return row.text !== \"\" && row.status !== \"approved\";\n case \"edit\":\n return true;\n case \"clear\":\n return canClear && row.review !== null;\n default:\n return false;\n }\n };\n const side = (ids: readonly TranslationReviewSwipeAction[] | undefined): TranslationReviewSwipeAction[] => {\n const out: TranslationReviewSwipeAction[] = [];\n for (const id of ids ?? []) {\n if (!out.includes(id) && offers(id)) out.push(id);\n }\n return out;\n };\n return { start: side(binding.start), end: side(binding.end) };\n}\n\n// ── Export ──────────────────────────────────────────────────────────────────────\n\n/**\n * One entry of the \"Export corrections\" file — enough for a developer to apply the change\n * to the bundle without opening the page. snake_case `reviewed_at` on purpose: this is a\n * FILE, the one keksdose and kastlan already write, beside an API spelled that way.\n */\nexport interface TranslationCorrection {\n locale: string;\n key: string;\n status: ReviewStatus;\n current: string;\n reference: string;\n suggestion: string | null;\n note: string | null;\n reviewer: string | null;\n reviewed_at: string | null;\n}\n\n/** The rows sent back (verdict NEEDS_CHANGE — a suggested translation for a missing\n * string included), as the export file lists them. */\nexport function translationCorrections(rows: readonly TranslationRow[]): TranslationCorrection[] {\n return rows\n .filter((row) => row.review?.verdict === \"NEEDS_CHANGE\")\n .map((row) => ({\n locale: row.locale,\n key: row.key,\n status: row.status,\n current: row.text,\n reference: row.reference,\n suggestion: row.review?.suggestion ?? null,\n note: row.review?.note ?? null,\n reviewer: row.review?.reviewerName ?? null,\n reviewed_at: row.review?.reviewedAt ?? null,\n }));\n}\n"],"mappings":";AAwBA,SAAS,qBAAqB;AAkDvB,MAAM,kBAA2C;AAAA,EACtD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAkEO,SAAS,cAAc,QAAiD;AAC7E,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,KAAK,OAAO;AAAA,IACZ,MAAM,OAAO;AAAA,IACb,eAAe,OAAO;AAAA,IACtB,SAAS,OAAO;AAAA,IAChB,MAAM,OAAO;AAAA,IACb,YAAY,OAAO;AAAA,IACnB,cAAc,OAAO;AAAA,IACrB,YAAY,OAAO;AAAA,EACrB;AACF;AAIO,SAAS,WAAW,OAA0D;AACnF,S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AAY,IAAI,WAAW;AAAA,MACpC;AACE,eAAO;AAAA,IACX;AAAA,EACF;AACA,QAAM,OAAO,CAAC,QAA6F;AACzG,UAAM,MAAsC,CAAC;AAC7C,eAAW,MAAM,OAAO,CAAC,GAAG;AAC1B,UAAI,CAAC,IAAI,SAAS,EAAE,KAAK,OAAO,EAAE,EAAG,KAAI,KAAK,EAAE;AAAA,IAClD;AACA,WAAO;AAAA,EACT;AACA,SAAO,EAAE,OAAO,KAAK,QAAQ,KAAK,GAAG,KAAK,KAAK,QAAQ,GAAG,EAAE;AAC9D;AAuBO,SAAS,uBAAuB,MAA0D;AAC/F,SAAO,KACJ,OAAO,CAAC,QAAQ,IAAI,QAAQ,YAAY,cAAc,EACtD,IAAI,CAAC,SAAS;AAAA,IACb,QAAQ,IAAI;AAAA,IACZ,KAAK,IAAI;AAAA,IACT,QAAQ,IAAI;AAAA,IACZ,SAAS,IAAI;AAAA,IACb,WAAW,IAAI;AAAA,IACf,YAAY,IAAI,QAAQ,cAAc;AAAA,IACtC,MAAM,IAAI,QAAQ,QAAQ;AAAA,IAC1B,UAAU,IAAI,QAAQ,gBAAgB;AAAA,IACtC,aAAa,IAAI,QAAQ,cAAc;AAAA,EACzC,EAAE;AACN;","names":[]}
1
+ {"version":3,"sources":["../../src/lib/translation-review.ts"],"sourcesContent":["/**\n * The pure half of an app's translation review (H1 in docs/i18n-harmonization.md): from\n * the strings the app ships and the verdicts its server stores to one row per (locale,\n * key) with a status — keksdose's `features/translations/translation-catalogue.ts` and\n * kastlan's copy of it, which had grown apart by a fifth status and a second kind of key.\n *\n * WHY THE STRINGS ARE THE CATALOGUE. Nothing on the server lists which strings exist: a\n * verdict only says what somebody thought of one. So the rows are built from what the app\n * ships — its locale bundles, kastlan's document texts, the kit's own words\n * (`kitLabelStrings`) — and the review can never offer a string users do not see. A\n * verdict is stored WITH the wording it was given on, and a string that changed since is\n * noticed by comparing the two: `changed`, read it again, whatever the verdict was.\n *\n * WHAT STAYS IN THE APP. Which locale is read against which (keksdose: everything against\n * English, English against de-CH; kastlan: against German, German against English), where\n * the strings come from, who may review what (the locales and areas its server answers\n * with), and every request. The kit takes those as input and never derives them.\n *\n * camelCase, like the rest of the kit. The contract's wire shape is snake_case\n * (`reference_text`, `reviewer_name`, `reviewed_at`); {@link fromApiReview} and\n * {@link toApiWrite} are the two lines each app would otherwise write — both apps speak\n * the same contract, so the mapping is written once, here.\n */\n\nimport { foldForSearch } from \"./text-match\";\n\n// ── Shapes ──────────────────────────────────────────────────────────────────────\n\nexport type TranslationVerdict = \"APPROVED\" | \"NEEDS_CHANGE\";\n\n/** One stored verdict: what a reviewer said about one string in one locale. */\nexport interface TranslationReview {\n locale: string;\n key: string;\n /** The wording that was judged — compared with today's to notice a change. Empty for\n * a string the locale lacked (a suggested translation for a `missing` row). */\n text: string;\n /** The reference wording at the time. `null` from a server that did not store it. */\n referenceText: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n /** The reviewer's wording — or, for a missing string, the translation to add. */\n suggestion: string | null;\n /** `null` once the reviewer's account has been erased. */\n reviewerName: string | null;\n /** ISO timestamp. */\n reviewedAt: string;\n}\n\n/** What a save sends: the verdict plus the wording it is given on. */\nexport interface TranslationReviewWrite {\n locale: string;\n key: string;\n text: string;\n referenceText: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n suggestion: string | null;\n}\n\n/** What a reset sends: back to \"unreviewed\". */\nexport interface TranslationReviewKey {\n locale: string;\n key: string;\n}\n\n/**\n * Where a string stands, in the order a reviewer works through them: what is not there\n * at all, what nobody has read, what changed after it was read, what was sent back, and\n * what is done. `missing` never occurs for an app whose locales have every key\n * (keksdose); kastlan's French lacks 172 screen texts.\n */\nexport type ReviewStatus = \"missing\" | \"unreviewed\" | \"changed\" | \"needs_change\" | \"approved\";\n\nexport const REVIEW_STATUSES: readonly ReviewStatus[] = [\n \"missing\",\n \"unreviewed\",\n \"changed\",\n \"needs_change\",\n \"approved\",\n];\n\nexport interface TranslationRow {\n /** `${locale}|${key}` — unique across every locale on a page. A bar, not a colon:\n * kastlan's keys contain colons (`common:actions.save`). */\n id: string;\n key: string;\n /** The key's group: `budget` for `budget.rta`, `common` for `common:actions.save`,\n * `kit` for the kit's own words. See {@link keyNamespace}. */\n namespace: string;\n /** Where the string comes from, in the app's own words — kastlan's `screen` and\n * `documents`, keksdose's one source. `\"\"` when the app does not say. */\n source: string;\n locale: string;\n /** The wording users see today; empty when the locale lacks the string. */\n text: string;\n /** The same key in the reference locale. */\n reference: string;\n status: ReviewStatus;\n review: TranslationReview | null;\n /** The interpolations and tags differ from the reference's — `{{count}}` dropped, a\n * `<1>` link lost, a `{date}` renamed. A machine can check that much, so it does,\n * before a person reads. Never set on a missing string: it has nothing to lose. */\n placeholderMismatch: boolean;\n}\n\n// ── The wire contract ───────────────────────────────────────────────────────────\n\n/** A verdict as `GET /translations/reviews` returns it (H1's shared contract). Typed\n * structurally, so an app's generated OpenAPI type fits without a cast. */\nexport interface ApiTranslationReview {\n locale: string;\n key: string;\n text: string;\n reference_text: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n suggestion: string | null;\n reviewer_name: string | null;\n /** server-kit 0.10: the name's two parts (`reviewer_name` is them in the reader's order). */\n reviewer_first_name?: string | null;\n reviewer_last_name?: string | null;\n reviewed_at: string;\n}\n\n/** `GET /translations/reviews` (server-kit `TranslationReviewsResponse`): the locales and\n * areas the caller may review (`areas` null: every area; `[\"kit\"]` for a review token)\n * and every stored verdict in them. Typed structurally, as {@link ApiTranslationReview}. */\nexport interface ApiTranslationReviewsResponse {\n locales: string[];\n areas?: string[] | null;\n reviews: ApiTranslationReview[];\n}\n\n/** One item of `PUT /translations/reviews`. */\nexport interface ApiTranslationReviewWrite {\n locale: string;\n key: string;\n text: string;\n reference_text: string | null;\n verdict: TranslationVerdict;\n note: string | null;\n suggestion: string | null;\n}\n\n/** A verdict from the server, in the kit's spelling. */\nexport function fromApiReview(review: ApiTranslationReview): TranslationReview {\n return {\n locale: review.locale,\n key: review.key,\n text: review.text,\n referenceText: review.reference_text,\n verdict: review.verdict,\n note: review.note,\n suggestion: review.suggestion,\n reviewerName: review.reviewer_name,\n reviewedAt: review.reviewed_at,\n };\n}\n\n/** A save, in the server's spelling. `TranslationReviewKey` needs no mapping — it is\n * `{ locale, key }` on both sides. */\nexport function toApiWrite(write: TranslationReviewWrite): ApiTranslationReviewWrite {\n return {\n locale: write.locale,\n key: write.key,\n text: write.text,\n reference_text: write.referenceText,\n verdict: write.verdict,\n note: write.note,\n suggestion: write.suggestion,\n };\n}\n\n// ── Strings ─────────────────────────────────────────────────────────────────────\n\n/**\n * A nested bundle as `key → string`, in the bundle's own order. Non-string leaves are\n * skipped rather than stringified into something nobody wrote.\n *\n * `prefix` is put in front of every key AS IS, so it names the separator too:\n * `flattenStrings(bundle)` is keksdose's `budget.rta`, `flattenStrings(tree, \"common:\")`\n * kastlan's `common:actions.save`, and `flattenStrings(kitLabelStrings(labels), \"kit.\")`\n * the kit's own words as `kit.combobox.resultCount(3)` — already flat, so only the prefix\n * is added.\n */\nexport function flattenStrings(tree: Readonly<Record<string, unknown>>, prefix = \"\"): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(tree)) {\n const path = `${prefix}${key}`;\n if (typeof value === \"string\") out[path] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) {\n Object.assign(out, flattenStrings(value as Record<string, unknown>, `${path}.`));\n }\n }\n return out;\n}\n\n/**\n * The key's group, for the namespace filter: the part before a colon when there is one\n * (kastlan's `common:actions.save` → `common`, `doc_text.invoice:due` →\n * `doc_text.invoice`), else the first dotted segment (keksdose's `budget.rta` →\n * `budget`, the kit's `kit.combobox.resultCount(3)` → `kit`). Only the part before a\n * sample's `(` is looked at, so a colon inside one cannot move the split.\n */\nexport function keyNamespace(key: string): string {\n const head = key.split(\"(\", 1)[0];\n const colon = head.indexOf(\":\");\n return colon >= 0 ? head.slice(0, colon) : head.split(\".\", 1)[0];\n}\n\n// i18next `{{x}}` (formatting options ignored: `{{x, number}}` is `{{x}}`); a Python\n// format field `{x}` / `{0}` / `{amount:.2f}` (kastlan's document texts), but not a\n// LaTeX argument (`\\textbf{x}` — a letter or backslash right before the brace); a\n// numbered or named tag (`<1>`, `<strong>`), not prose in angle brackets (\"<deleted\n// user>\"); and a nested `$t(key)`. `{{x}}` is tried first at its position and consumed\n// whole, so it is never counted a second time as `{x}`.\nconst PLACEHOLDER_RE =\n /\\{\\{\\s*([^}\\s,]+)[^}]*\\}\\}|(?<![\\\\A-Za-z])\\{([a-z_][a-z0-9_]*|\\d+)(?:[!:][^{}]*)?\\}|<\\/?(\\d+|[a-z][a-z0-9]*)\\s*\\/?>|\\$t\\(([^)]+)\\)/g;\n\n/** The placeholders in a string, as a sorted multiset: `{{count}}`, `{date}`, `<1>`,\n * `$t(common.save)`. */\nexport function placeholderTokens(text: string): string[] {\n const found: string[] = [];\n for (const m of text.matchAll(PLACEHOLDER_RE)) {\n if (m[1]) found.push(`{{${m[1]}}}`);\n // `{ref:retention}` (ui-kit 0.28's legal cross-reference) keeps its target: a\n // translation that points at another section changed what the sentence says. Every\n // other `{x:spec}` is a format spec, which a translation may change.\n else if (m[2]) found.push(m[2] === \"ref\" ? m[0] : `{${m[2]}}`);\n else if (m[3]) found.push(`<${m[3]}>`);\n else if (m[4]) found.push(`$t(${m[4]})`);\n }\n return found.sort();\n}\n\n/** Whether `text` has other placeholders than `reference` — dropped, renamed or added.\n * Moving one is fine: a translation reorders a sentence. */\nexport function placeholderMismatch(text: string, reference: string): boolean {\n const a = placeholderTokens(text);\n const b = placeholderTokens(reference);\n return a.length !== b.length || a.some((p, i) => p !== b[i]);\n}\n\n// ── Status ──────────────────────────────────────────────────────────────────────\n\n/**\n * A verdict counts only for the wording it was given on. If the string or its reference\n * changed since, it is `changed` — read it again — whatever the verdict was. A string the\n * locale lacks is `missing` until somebody suggests its translation (stored as\n * NEEDS_CHANGE on the empty text, so it reads `needs_change`, and `changed` once a\n * developer adds the string).\n */\nexport function reviewStatus(\n review: TranslationReview | null | undefined,\n text: string,\n reference: string,\n): ReviewStatus {\n if (!review) return text === \"\" && reference !== \"\" ? \"missing\" : \"unreviewed\";\n if (review.text !== text) return \"changed\";\n if (review.referenceText != null && review.referenceText !== reference) return \"changed\";\n return review.verdict === \"APPROVED\" ? \"approved\" : \"needs_change\";\n}\n\n/**\n * Whether `key` lies in `area`: the key IS the area, or sits under it — `legal.terms`\n * and kastlan's `legal:terms` are in `legal`, `legalese.title` is not.\n *\n * 0.28: the kit's own words of that area too — `kit.legal.sections.terms.law.body(…)`\n * is in `legal`. All three apps list the kit's labels under `kit.`\n * (`flattenStrings(kitLabelStrings(labels), \"kit.\")`), and since 0.28 the kit writes\n * the shared legal sections, so a lawyer with a `[\"legal\"]` grant who was not shown\n * `kit.legal.*` would not see half of the Privacy Policy — and the server would refuse\n * the verdicts (docs/legal-harmonization.md §7.5). server-kit's `in_areas` and the apps'\n * copies of it apply the same rule.\n */\nexport function keyInArea(key: string, area: string): boolean {\n return key === area || key.startsWith(`${area}.`) || key.startsWith(`${area}:`) || key.startsWith(`kit.${area}.`);\n}\n\n/**\n * The area of `areas` that `key` lies in ({@link keyInArea}), or `undefined` — the\n * translation page's grouping by the same rule the filter and the server use, so\n * `kit.legal.sections.privacy.rights.lead` is grouped under `legal` with the app's own\n * legal texts instead of under `kit.legal`:\n *\n * const namespaceOf = (key: string) => reviewAreaOf(key, [\"legal\"]) ?? ownNamespaceOf(key);\n *\n * Where two areas both hold the key (`legal` and `legal.privacy`), the longer — the more\n * specific — wins, whatever their order. `inArea` is the app's own rule, as for\n * {@link keyInAreas}.\n */\nexport function reviewAreaOf(\n key: string,\n areas: readonly string[],\n inArea: (key: string, area: string) => boolean = keyInArea,\n): string | undefined {\n let found: string | undefined;\n for (const area of areas) {\n if (inArea(key, area) && (found === undefined || area.length > found.length)) found = area;\n }\n return found;\n}\n\n/**\n * Whether `key` lies in one of `areas` — the scope a reviewer may be limited to\n * (keksdose: `[\"legal\"]`, a lawyer who judges the Imprint, the Privacy Policy and the\n * Terms and sees nothing else). `null`/`undefined` is every area. The server applies the\n * same rule and refuses verdicts outside; this decides only what is listed.\n */\nexport function keyInAreas(\n key: string,\n areas: readonly string[] | null | undefined,\n inArea: (key: string, area: string) => boolean = keyInArea,\n): boolean {\n return !areas || areas.some((area) => inArea(key, area));\n}\n\nexport interface TranslationRowsInput {\n locale: string;\n /** The locale's strings, `key → text` ({@link flattenStrings}). */\n strings: Readonly<Record<string, string>>;\n /** The reference locale's strings — whichever locale THIS app reads `locale` against. */\n reference: Readonly<Record<string, string>>;\n /** The verdicts: this locale's by key, or the whole list as the server sent it (other\n * locales' verdicts are skipped). */\n reviews?: ReadonlyMap<string, TranslationReview> | readonly TranslationReview[];\n /** Default {@link keyNamespace}. */\n namespaceOf?: (key: string) => string;\n /** The row's source, an app-defined word (kastlan: `doc_text.` keys are `documents`,\n * the rest `screen`). Default: none (`\"\"`). */\n sourceOf?: (key: string) => string;\n /** Keep only keys inside these areas ({@link keyInAreas}); `null` keeps every key. */\n areas?: readonly string[] | null;\n /** Default {@link keyInArea}. */\n inArea?: (key: string, area: string) => boolean;\n}\n\n/**\n * Every key of one locale, with its status: the reference's keys first, in its order, so\n * rows read the way the app's authors wrote them; a key only this locale has is appended\n * rather than dropped (a parity test should forbid it, but the page should not lie if one\n * slips through).\n */\nexport function translationRows({\n locale,\n strings,\n reference,\n reviews,\n namespaceOf: groupOf = keyNamespace,\n sourceOf,\n areas,\n inArea,\n}: TranslationRowsInput): TranslationRow[] {\n const byKey = new Map<string, TranslationReview>();\n if (reviews instanceof Map) {\n for (const [key, review] of reviews) byKey.set(key, review);\n } else if (reviews) {\n for (const review of reviews as readonly TranslationReview[]) {\n if (review.locale === locale) byKey.set(review.key, review);\n }\n }\n const keys = Object.keys(reference);\n for (const key of Object.keys(strings)) if (!(key in reference)) keys.push(key);\n return keys\n .filter((key) => keyInAreas(key, areas, inArea))\n .map((key) => {\n const text = strings[key] ?? \"\";\n const ref = reference[key] ?? \"\";\n const review = byKey.get(key) ?? null;\n return {\n id: `${locale}|${key}`,\n key,\n namespace: groupOf(key),\n source: sourceOf?.(key) ?? \"\",\n locale,\n text,\n reference: ref,\n status: reviewStatus(review, text, ref),\n review,\n placeholderMismatch: text !== \"\" && placeholderMismatch(text, ref),\n };\n });\n}\n\n/** How many rows stand where, and how many there are. */\nexport type TranslationSummary = Record<ReviewStatus, number> & { total: number };\n\nexport function summariseRows(rows: readonly TranslationRow[]): TranslationSummary {\n const summary: TranslationSummary = {\n missing: 0,\n unreviewed: 0,\n changed: 0,\n needs_change: 0,\n approved: 0,\n total: rows.length,\n };\n for (const row of rows) summary[row.status] += 1;\n return summary;\n}\n\n// ── Filtering ───────────────────────────────────────────────────────────────────\n\n/** The panel's filters. `\"all\"` switches one off. */\nexport interface TranslationReviewFilter {\n status: ReviewStatus | \"all\";\n source: string;\n namespace: string;\n /** Searched in the key, the text and the reference, folded as every kit list's search\n * is (`foldForSearch`): no case, no accents — \"uberweisung\" finds \"Überweisung\". */\n query: string;\n placeholdersOnly: boolean;\n}\n\nexport const DEFAULT_TRANSLATION_REVIEW_FILTER: TranslationReviewFilter = {\n status: \"all\",\n source: \"all\",\n namespace: \"all\",\n query: \"\",\n placeholdersOnly: false,\n};\n\nexport function filterTranslationRows(\n rows: readonly TranslationRow[],\n filter: Partial<TranslationReviewFilter>,\n): TranslationRow[] {\n const f = { ...DEFAULT_TRANSLATION_REVIEW_FILTER, ...filter };\n // Folded as every kit list's search is (DUP-5, refactor audit 2026-10).\n const q = foldForSearch(f.query.trim());\n return rows.filter(\n (row) =>\n (f.status === \"all\" || row.status === f.status) &&\n (f.source === \"all\" || row.source === f.source) &&\n (f.namespace === \"all\" || row.namespace === f.namespace) &&\n (!f.placeholdersOnly || row.placeholderMismatch) &&\n (!q || [row.key, row.text, row.reference].some((s) => foldForSearch(s).includes(q))),\n );\n}\n\n// ── Grouping ────────────────────────────────────────────────────────────────────\n\n/** One group of rows — an area, a source — and how they stand. */\nexport interface TranslationRowGroup {\n key: string;\n rows: TranslationRow[];\n summary: TranslationSummary;\n}\n\n/**\n * Rows in groups, each group where its first row is — the reference's order, so the areas\n * read the way the app's authors wrote the bundle — and each group's rows in their own\n * order. keksdose live #377: a reviewer on a phone works area by area (\"the budget\n * strings, then the legal ones\"), and a flat list of 3859 rows is not a way to see\n * where an area stands.\n *\n * `groupOf` names a row's group: `(row) => row.namespace` for the areas,\n * `(row) => row.source` for kastlan's screen texts and documents.\n */\nexport function groupTranslationRows(\n rows: readonly TranslationRow[],\n groupOf: (row: TranslationRow) => string,\n): TranslationRowGroup[] {\n const byKey = new Map<string, TranslationRow[]>();\n for (const row of rows) {\n const key = groupOf(row);\n const list = byKey.get(key);\n if (list) list.push(row);\n else byKey.set(key, [row]);\n }\n return [...byKey].map(([key, list]) => ({ key, rows: list, summary: summariseRows(list) }));\n}\n\n/**\n * The rows a group's \"Approve the unreviewed\" takes: the ones nobody has given a verdict\n * and that have a text. Not `changed` — a string that moved since it was judged asks to\n * be READ again, which a bulk action is the opposite of — and not `missing`, which has\n * nothing to approve.\n */\nexport function unreviewedRows(rows: readonly TranslationRow[]): TranslationRow[] {\n return rows.filter((row) => row.status === \"unreviewed\" && row.text !== \"\");\n}\n\n// ── Writing ─────────────────────────────────────────────────────────────────────\n\n/** What gets stored for a verdict: the wording it was given on, so a later change of the\n * string (or of its reference) shows up as `changed`. */\nexport function reviewWrite(\n row: TranslationRow,\n verdict: TranslationVerdict,\n note: string | null = null,\n suggestion: string | null = null,\n): TranslationReviewWrite {\n return {\n locale: row.locale,\n key: row.key,\n text: row.text,\n referenceText: row.reference,\n verdict,\n note,\n suggestion,\n };\n}\n\n/** What takes a set of verdicts back: see {@link reviewUndo}. */\nexport interface TranslationReviewUndo {\n /** The verdicts the rows had before, to store again — each on the wording it was\n * given on, so a row that was `changed` reads `changed` again. */\n writes: TranslationReviewWrite[];\n /** The rows that had no verdict before: back to unreviewed. */\n clears: TranslationReviewKey[];\n}\n\n/**\n * How to take back what was just said about `rows` — the rows AS THEY WERE before the\n * write, with the verdicts they carried then. The panel's Undo toast (0.25, keksdose live\n * #377) runs it: a swipe on a phone approves in one movement, and a movement can be a\n * mistake.\n *\n * A row that had a verdict gets it stored again (its note, its suggestion, the wording it\n * was judged on); one that had none is cleared. The server stamps the restored verdict\n * with the person undoing and the time, as it stamps every write — the contract has no\n * way to write a verdict in somebody else's name, and should not.\n */\nexport function reviewUndo(rows: readonly TranslationRow[]): TranslationReviewUndo {\n const writes: TranslationReviewWrite[] = [];\n const clears: TranslationReviewKey[] = [];\n for (const row of rows) {\n const before = row.review;\n if (!before) {\n clears.push({ locale: row.locale, key: row.key });\n continue;\n }\n writes.push({\n locale: row.locale,\n key: row.key,\n text: before.text,\n referenceText: before.referenceText,\n verdict: before.verdict,\n note: before.note,\n suggestion: before.suggestion,\n });\n }\n return { writes, clears };\n}\n\n/** The app's cached verdict list with `written` in place of what was said before — a\n * save answers with the rows it wrote, so a page patches its copy instead of\n * downloading every verdict again after each click. Any spelling with `locale` and\n * `key` (the API's or the kit's). */\nexport function mergeReviews<T extends TranslationReviewKey>(prev: readonly T[], written: readonly T[]): T[] {\n const id = (r: TranslationReviewKey) => `${r.locale}|${r.key}`;\n const replaced = new Set(written.map(id));\n return [...prev.filter((r) => !replaced.has(id(r))), ...written];\n}\n\n/** The cached list without the verdicts on `cleared`. */\nexport function dropReviews<T extends TranslationReviewKey>(\n prev: readonly T[],\n cleared: readonly TranslationReviewKey[],\n): T[] {\n const gone = new Set(cleared.map((r) => `${r.locale}|${r.key}`));\n return prev.filter((r) => !gone.has(`${r.locale}|${r.key}`));\n}\n\n// ── Swipe bindings ──────────────────────────────────────────────────────────────\n\n/**\n * What a phone card's swipe can be bound to in `TranslationReviewPanel`'s `swipe`\n * (keksdose — Marcel's live #377 rework, 2026-10-03: *\"Add the swipe options to be shown\n * also to the settings /settings#interaction area where the other swipe options are\n * defined\"*). keksdose lets the user bind every list's swipes there — per side, a primary\n * action at the first threshold and a secondary one at a longer drag — and lists each\n * surface's ids in its `SWIPE_ACTIONS`; this is the translation list's, in the order a\n * settings page offers them.\n *\n * - `approve` — the string is right as it stands. With the panel's Undo toast.\n * - `edit` — open the editor with the cursor in the wording: \"Needs a change\" (or\n * \"Suggest translation\" on a missing string). Writes nothing; the editor does.\n * - `clear` — take the verdict back: unreviewed again. With the Undo toast, which stores\n * the verdict again.\n *\n * THERE IS NO SEPARATE \"needs a change\". The editor has no verdict to preselect: Approve\n * and \"Needs a change\" stand side by side in it, and \"Needs a change\" takes a note or a\n * different wording — a verdict without either tells whoever fixes the string nothing, so\n * a swipe never sends one blind (0.25). The one honest thing a \"needs a change\" swipe can\n * do is therefore open the editor with the cursor in the wording — which is `edit`, and\n * `edit` already says \"Needs a change\" on the card. A second id doing the same would arm\n * a second threshold that does what the first already did: the duplicate keksdose's\n * `resolveSwipePlan` drops for exactly that reason.\n */\nexport const TRANSLATION_REVIEW_SWIPE_ACTIONS = [\"approve\", \"edit\", \"clear\"] as const;\n\n/** One of {@link TRANSLATION_REVIEW_SWIPE_ACTIONS}. */\nexport type TranslationReviewSwipeAction = (typeof TRANSLATION_REVIEW_SWIPE_ACTIONS)[number];\n\n/**\n * Which swipe does what on a phone card — `TranslationReviewPanel`'s `swipe`. Each side is\n * an ordered ladder, exactly as `SwipeableRow` and DataTable's `mobileSwipeActions` model\n * one: index 0 commits at the first threshold, index 1 at the longer drag (and so on — the\n * thresholds spread evenly over the card's width). A side left out, or empty, does not\n * swipe.\n *\n * LOGICAL SIDES: `end` is a drag toward the reading end of the line — right in a\n * left-to-right page, left in a right-to-left one — and `start` the other way, so one\n * binding holds in both directions. An app whose settings store physical sides (keksdose's\n * `right`/`left`) hands `right` as `end` for a left-to-right page.\n */\nexport interface TranslationReviewSwipeBinding {\n /** A drag toward the reading START, nearest threshold first. */\n start?: readonly TranslationReviewSwipeAction[];\n /** A drag toward the reading END, nearest threshold first. */\n end?: readonly TranslationReviewSwipeAction[];\n}\n\n/** What `swipe={true}` means — 0.25's fixed mapping: approve toward the end, open the\n * editor (\"Needs a change\") toward the start. A settings page's \"reset\" goes back here. */\nexport const DEFAULT_TRANSLATION_REVIEW_SWIPE: TranslationReviewSwipeBinding = Object.freeze({\n start: Object.freeze([\"edit\"] as const),\n end: Object.freeze([\"approve\"] as const),\n});\n\n/** The ladders one row actually offers, from a {@link TranslationReviewSwipeBinding}. */\nexport interface TranslationReviewSwipePlan {\n start: TranslationReviewSwipeAction[];\n end: TranslationReviewSwipeAction[];\n}\n\n/**\n * The binding resolved against one row — keksdose's `resolveSwipePlan`, for this list.\n * An id the row cannot offer DROPS OUT and the ladder closes up behind it, so the second\n * stage becomes the first rather than the side going dead behind an unreachable first\n * stage (or arming a threshold that does nothing):\n *\n * - `approve`: not on a missing string (nothing to approve) or an approved one (it would\n * say it again) — the rows that have no approve button either;\n * - `clear`: not without `canClear` (the app passed no `onClear`), and not on a row with\n * no verdict to take back (unreviewed; missing with no suggestion);\n * - `edit`: on every row;\n * - an id named twice on one side: the second time (a longer drag to the same effect);\n * - an id this version does not know (a binding stored by another version, an app's own\n * \"none\" slot): dropped like one that does not apply.\n *\n * Only what the ROW decides. Whether the panel may write at all — `readOnly`, no\n * `onSave`, a write lock, the row's own write still out — is the panel's, and then no\n * side swipes.\n */\nexport function translationReviewSwipePlan(\n binding: TranslationReviewSwipeBinding,\n row: TranslationRow,\n { canClear = false }: { canClear?: boolean } = {},\n): TranslationReviewSwipePlan {\n const offers = (id: TranslationReviewSwipeAction): boolean => {\n switch (id) {\n case \"approve\":\n return row.text !== \"\" && row.status !== \"approved\";\n case \"edit\":\n return true;\n case \"clear\":\n return canClear && row.review !== null;\n default:\n return false;\n }\n };\n const side = (ids: readonly TranslationReviewSwipeAction[] | undefined): TranslationReviewSwipeAction[] => {\n const out: TranslationReviewSwipeAction[] = [];\n for (const id of ids ?? []) {\n if (!out.includes(id) && offers(id)) out.push(id);\n }\n return out;\n };\n return { start: side(binding.start), end: side(binding.end) };\n}\n\n// ── Export ──────────────────────────────────────────────────────────────────────\n\n/**\n * One entry of the \"Export corrections\" file — enough for a developer to apply the change\n * to the bundle without opening the page. snake_case `reviewed_at` on purpose: this is a\n * FILE, the one keksdose and kastlan already write, beside an API spelled that way.\n */\nexport interface TranslationCorrection {\n locale: string;\n key: string;\n status: ReviewStatus;\n current: string;\n reference: string;\n suggestion: string | null;\n note: string | null;\n reviewer: string | null;\n reviewed_at: string | null;\n}\n\n/** The rows sent back (verdict NEEDS_CHANGE — a suggested translation for a missing\n * string included), as the export file lists them. */\nexport function translationCorrections(rows: readonly TranslationRow[]): TranslationCorrection[] {\n return rows\n .filter((row) => row.review?.verdict === \"NEEDS_CHANGE\")\n .map((row) => ({\n locale: row.locale,\n key: row.key,\n status: row.status,\n current: row.text,\n reference: row.reference,\n suggestion: row.review?.suggestion ?? null,\n note: row.review?.note ?? null,\n reviewer: row.review?.reviewerName ?? null,\n reviewed_at: row.review?.reviewedAt ?? null,\n }));\n}\n"],"mappings":";AAwBA,SAAS,qBAAqB;AAkDvB,MAAM,kBAA2C;AAAA,EACtD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAkEO,SAAS,cAAc,QAAiD;AAC7E,SAAO;AAAA,IACL,QAAQ,OAAO;AAAA,IACf,KAAK,OAAO;AAAA,IACZ,MAAM,OAAO;AAAA,IACb,eAAe,OAAO;AAAA,IACtB,SAAS,OAAO;AAAA,IAChB,MAAM,OAAO;AAAA,IACb,YAAY,OAAO;AAAA,IACnB,cAAc,OAAO;AAAA,IACrB,YAAY,OAAO;AAAA,EACrB;AACF;AAIO,SAAS,WAAW,OAA0D;AACnF,SAAO;AAAA,IACL,QAAQ,MAAM;AAAA,IACd,KAAK,MAAM;AAAA,IACX,MAAM,MAAM;AAAA,IACZ,gBAAgB,MAAM;AAAA,IACtB,SAAS,MAAM;AAAA,IACf,MAAM,MAAM;AAAA,IACZ,YAAY,MAAM;AAAA,EACpB;AACF;AAcO,SAAS,eAAe,MAAyC,S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