@toclocoinc/lattice-grid 1.86.4 → 1.86.5

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 (306) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +1 -1
  3. package/angular/package.json +1 -1
  4. package/docs/API.html +4 -4
  5. package/docs/api/adapters.html +1 -1
  6. package/docs/api/ai.html +1 -1
  7. package/docs/api/alarms.html +1 -1
  8. package/docs/api/calendar.html +1 -1
  9. package/docs/api/charts.html +1 -1
  10. package/docs/api/dashboard.html +1 -1
  11. package/docs/api/data-router.html +1 -1
  12. package/docs/api/deckgl.html +1 -1
  13. package/docs/api/gantt.html +1 -1
  14. package/docs/api/geometry.html +1 -1
  15. package/docs/api/grid.html +2 -2
  16. package/docs/api/index.html +1 -1
  17. package/docs/api/kanban.html +1 -1
  18. package/docs/api/kpi.html +1 -1
  19. package/docs/api/layout.html +1 -1
  20. package/docs/api/leaflet.html +1 -1
  21. package/docs/api/list.html +1 -1
  22. package/docs/api/mapview.html +1 -1
  23. package/docs/api/mock-socket.html +1 -1
  24. package/docs/api/presets.html +1 -1
  25. package/docs/api/tabs.html +1 -1
  26. package/docs/api/types.html +1 -1
  27. package/docs/api-detail.html +4 -4
  28. package/docs/warnings.json +1 -1
  29. package/lattice-grid.d.ts +1 -1
  30. package/lattice-grid.esm.min.js +3 -3
  31. package/lattice-grid.min.cjs +3 -3
  32. package/lattice-grid.min.css +1 -1
  33. package/lattice-grid.min.js +3 -3
  34. package/modules/ai.d.ts +1 -1
  35. package/modules/ai.esm.min.js +2 -2
  36. package/modules/ai.min.cjs +2 -2
  37. package/modules/ai.min.js +2 -2
  38. package/modules/alarms.d.ts +1 -1
  39. package/modules/alarms.esm.min.js +2 -2
  40. package/modules/alarms.min.cjs +2 -2
  41. package/modules/alarms.min.js +2 -2
  42. package/modules/angular.d.ts +1 -1
  43. package/modules/angular.esm.min.js +2 -2
  44. package/modules/angular.min.cjs +2 -2
  45. package/modules/angular.min.js +2 -2
  46. package/modules/calendar.d.ts +1 -1
  47. package/modules/calendar.esm.min.js +2 -2
  48. package/modules/calendar.min.cjs +2 -2
  49. package/modules/calendar.min.js +2 -2
  50. package/modules/chart-alluvial.d.ts +1 -1
  51. package/modules/chart-alluvial.esm.min.js +1 -1
  52. package/modules/chart-alluvial.min.cjs +1 -1
  53. package/modules/chart-alluvial.min.js +1 -1
  54. package/modules/chart-arc.d.ts +1 -1
  55. package/modules/chart-arc.esm.min.js +1 -1
  56. package/modules/chart-arc.min.cjs +1 -1
  57. package/modules/chart-arc.min.js +1 -1
  58. package/modules/chart-barrace.d.ts +1 -1
  59. package/modules/chart-barrace.esm.min.js +1 -1
  60. package/modules/chart-barrace.min.cjs +1 -1
  61. package/modules/chart-barrace.min.js +1 -1
  62. package/modules/chart-bubblemap.d.ts +1 -1
  63. package/modules/chart-bubblemap.esm.min.js +1 -1
  64. package/modules/chart-bubblemap.min.cjs +1 -1
  65. package/modules/chart-bubblemap.min.js +1 -1
  66. package/modules/chart-bump.d.ts +1 -1
  67. package/modules/chart-bump.esm.min.js +1 -1
  68. package/modules/chart-bump.min.cjs +1 -1
  69. package/modules/chart-bump.min.js +1 -1
  70. package/modules/chart-calendar.d.ts +1 -1
  71. package/modules/chart-calendar.esm.min.js +1 -1
  72. package/modules/chart-calendar.min.cjs +1 -1
  73. package/modules/chart-calendar.min.js +1 -1
  74. package/modules/chart-choropleth.d.ts +1 -1
  75. package/modules/chart-choropleth.esm.min.js +1 -1
  76. package/modules/chart-choropleth.min.cjs +1 -1
  77. package/modules/chart-choropleth.min.js +1 -1
  78. package/modules/chart-decomposition.d.ts +1 -1
  79. package/modules/chart-decomposition.esm.min.js +1 -1
  80. package/modules/chart-decomposition.min.cjs +1 -1
  81. package/modules/chart-decomposition.min.js +1 -1
  82. package/modules/chart-diverging.d.ts +1 -1
  83. package/modules/chart-diverging.esm.min.js +1 -1
  84. package/modules/chart-diverging.min.cjs +1 -1
  85. package/modules/chart-diverging.min.js +1 -1
  86. package/modules/chart-dumbbell.d.ts +1 -1
  87. package/modules/chart-dumbbell.esm.min.js +1 -1
  88. package/modules/chart-dumbbell.min.cjs +1 -1
  89. package/modules/chart-dumbbell.min.js +1 -1
  90. package/modules/chart-fan.d.ts +1 -1
  91. package/modules/chart-fan.esm.min.js +1 -1
  92. package/modules/chart-fan.min.cjs +1 -1
  93. package/modules/chart-fan.min.js +1 -1
  94. package/modules/chart-forcetree.d.ts +1 -1
  95. package/modules/chart-forcetree.esm.min.js +2 -2
  96. package/modules/chart-forcetree.esm.min.js.map +2 -2
  97. package/modules/chart-forcetree.min.cjs +2 -2
  98. package/modules/chart-forcetree.min.js +2 -2
  99. package/modules/chart-forcetree.min.js.map +2 -2
  100. package/modules/chart-hexbin.d.ts +1 -1
  101. package/modules/chart-hexbin.esm.min.js +2 -2
  102. package/modules/chart-hexbin.esm.min.js.map +1 -1
  103. package/modules/chart-hexbin.min.cjs +2 -2
  104. package/modules/chart-hexbin.min.js +2 -2
  105. package/modules/chart-hexbin.min.js.map +1 -1
  106. package/modules/chart-hexmap.d.ts +1 -1
  107. package/modules/chart-hexmap.esm.min.js +1 -1
  108. package/modules/chart-hexmap.min.cjs +1 -1
  109. package/modules/chart-hexmap.min.js +1 -1
  110. package/modules/chart-icicle.d.ts +1 -1
  111. package/modules/chart-icicle.esm.min.js +1 -1
  112. package/modules/chart-icicle.min.cjs +1 -1
  113. package/modules/chart-icicle.min.js +1 -1
  114. package/modules/chart-markermap.d.ts +1 -1
  115. package/modules/chart-markermap.esm.min.js +1 -1
  116. package/modules/chart-markermap.min.cjs +1 -1
  117. package/modules/chart-markermap.min.js +1 -1
  118. package/modules/chart-motion.d.ts +1 -1
  119. package/modules/chart-motion.esm.min.js +1 -1
  120. package/modules/chart-motion.min.cjs +1 -1
  121. package/modules/chart-motion.min.js +1 -1
  122. package/modules/chart-pack.d.ts +1 -1
  123. package/modules/chart-pack.esm.min.js +1 -1
  124. package/modules/chart-pack.min.cjs +1 -1
  125. package/modules/chart-pack.min.js +1 -1
  126. package/modules/chart-parallel.d.ts +1 -1
  127. package/modules/chart-parallel.esm.min.js +1 -1
  128. package/modules/chart-parallel.min.cjs +1 -1
  129. package/modules/chart-parallel.min.js +1 -1
  130. package/modules/chart-pictorial.d.ts +1 -1
  131. package/modules/chart-pictorial.esm.min.js +1 -1
  132. package/modules/chart-pictorial.min.cjs +1 -1
  133. package/modules/chart-pictorial.min.js +1 -1
  134. package/modules/chart-polararea.d.ts +1 -1
  135. package/modules/chart-polararea.esm.min.js +1 -1
  136. package/modules/chart-polararea.min.cjs +1 -1
  137. package/modules/chart-polararea.min.js +1 -1
  138. package/modules/chart-polarscatter.d.ts +1 -1
  139. package/modules/chart-polarscatter.esm.min.js +1 -1
  140. package/modules/chart-polarscatter.min.cjs +1 -1
  141. package/modules/chart-polarscatter.min.js +1 -1
  142. package/modules/chart-pyramid.d.ts +1 -1
  143. package/modules/chart-pyramid.esm.min.js +1 -1
  144. package/modules/chart-pyramid.min.cjs +1 -1
  145. package/modules/chart-pyramid.min.js +1 -1
  146. package/modules/chart-radialbar.d.ts +1 -1
  147. package/modules/chart-radialbar.esm.min.js +1 -1
  148. package/modules/chart-radialbar.min.cjs +1 -1
  149. package/modules/chart-radialbar.min.js +1 -1
  150. package/modules/chart-ridgeline.d.ts +1 -1
  151. package/modules/chart-ridgeline.esm.min.js +1 -1
  152. package/modules/chart-ridgeline.min.cjs +1 -1
  153. package/modules/chart-ridgeline.min.js +1 -1
  154. package/modules/chart-roc.d.ts +1 -1
  155. package/modules/chart-roc.esm.min.js +1 -1
  156. package/modules/chart-roc.min.cjs +1 -1
  157. package/modules/chart-roc.min.js +1 -1
  158. package/modules/chart-serpentine.d.ts +1 -1
  159. package/modules/chart-serpentine.esm.min.js +1 -1
  160. package/modules/chart-serpentine.min.cjs +1 -1
  161. package/modules/chart-serpentine.min.js +1 -1
  162. package/modules/chart-slope.d.ts +1 -1
  163. package/modules/chart-slope.esm.min.js +1 -1
  164. package/modules/chart-slope.min.cjs +1 -1
  165. package/modules/chart-slope.min.js +1 -1
  166. package/modules/chart-spiral.d.ts +1 -1
  167. package/modules/chart-spiral.esm.min.js +1 -1
  168. package/modules/chart-spiral.min.cjs +1 -1
  169. package/modules/chart-spiral.min.js +1 -1
  170. package/modules/chart-splom.d.ts +1 -1
  171. package/modules/chart-splom.esm.min.js +1 -1
  172. package/modules/chart-splom.min.cjs +1 -1
  173. package/modules/chart-splom.min.js +1 -1
  174. package/modules/chart-tree.d.ts +1 -1
  175. package/modules/chart-tree.esm.min.js +2 -2
  176. package/modules/chart-tree.esm.min.js.map +2 -2
  177. package/modules/chart-tree.min.cjs +2 -2
  178. package/modules/chart-tree.min.js +2 -2
  179. package/modules/chart-tree.min.js.map +2 -2
  180. package/modules/chart-venn.d.ts +1 -1
  181. package/modules/chart-venn.esm.min.js +1 -1
  182. package/modules/chart-venn.min.cjs +1 -1
  183. package/modules/chart-venn.min.js +1 -1
  184. package/modules/chart-voronoi.d.ts +1 -1
  185. package/modules/chart-voronoi.esm.min.js +1 -1
  186. package/modules/chart-voronoi.min.cjs +1 -1
  187. package/modules/chart-voronoi.min.js +1 -1
  188. package/modules/chart-waffle.d.ts +1 -1
  189. package/modules/chart-waffle.esm.min.js +1 -1
  190. package/modules/chart-waffle.min.cjs +1 -1
  191. package/modules/chart-waffle.min.js +1 -1
  192. package/modules/chart-wordcloud.d.ts +1 -1
  193. package/modules/chart-wordcloud.esm.min.js +1 -1
  194. package/modules/chart-wordcloud.min.cjs +1 -1
  195. package/modules/chart-wordcloud.min.js +1 -1
  196. package/modules/charts.d.ts +1 -1
  197. package/modules/charts.esm.min.js +235 -235
  198. package/modules/charts.esm.min.js.map +2 -2
  199. package/modules/charts.min.cjs +235 -235
  200. package/modules/charts.min.js +235 -235
  201. package/modules/charts.min.js.map +2 -2
  202. package/modules/dashboard.d.ts +1 -1
  203. package/modules/dashboard.esm.min.js +2 -2
  204. package/modules/dashboard.min.cjs +2 -2
  205. package/modules/dashboard.min.js +2 -2
  206. package/modules/data-router.d.ts +1 -1
  207. package/modules/data-router.esm.min.js +2 -2
  208. package/modules/data-router.min.cjs +2 -2
  209. package/modules/data-router.min.js +2 -2
  210. package/modules/deckgl.d.ts +1 -1
  211. package/modules/deckgl.esm.min.js +2 -2
  212. package/modules/deckgl.min.cjs +2 -2
  213. package/modules/deckgl.min.js +2 -2
  214. package/modules/devtools.d.ts +1 -1
  215. package/modules/devtools.esm.min.js +1 -1
  216. package/modules/devtools.min.cjs +1 -1
  217. package/modules/devtools.min.js +1 -1
  218. package/modules/dhtmlx-compat.d.ts +1 -1
  219. package/modules/dhtmlx-compat.esm.min.js +2 -2
  220. package/modules/dhtmlx-compat.min.cjs +2 -2
  221. package/modules/dhtmlx-compat.min.js +2 -2
  222. package/modules/gantt.d.ts +1 -1
  223. package/modules/gantt.esm.min.js +2 -2
  224. package/modules/gantt.min.cjs +2 -2
  225. package/modules/gantt.min.js +2 -2
  226. package/modules/geo-europe-nuts.d.ts +1 -1
  227. package/modules/geo-europe-nuts.esm.min.js +1 -1
  228. package/modules/geo-europe-nuts.min.cjs +1 -1
  229. package/modules/geo-europe-nuts.min.js +1 -1
  230. package/modules/geo-uk.d.ts +1 -1
  231. package/modules/geo-uk.esm.min.js +1 -1
  232. package/modules/geo-uk.min.cjs +1 -1
  233. package/modules/geo-uk.min.js +1 -1
  234. package/modules/geo-us-states.d.ts +1 -1
  235. package/modules/geo-us-states.esm.min.js +1 -1
  236. package/modules/geo-us-states.min.cjs +1 -1
  237. package/modules/geo-us-states.min.js +1 -1
  238. package/modules/geo-world-110m.d.ts +1 -1
  239. package/modules/geo-world-110m.esm.min.js +1 -1
  240. package/modules/geo-world-110m.min.cjs +1 -1
  241. package/modules/geo-world-110m.min.js +1 -1
  242. package/modules/geo-world-50m.d.ts +1 -1
  243. package/modules/geo-world-50m.esm.min.js +1 -1
  244. package/modules/geo-world-50m.min.cjs +1 -1
  245. package/modules/geo-world-50m.min.js +1 -1
  246. package/modules/geometry.d.ts +1 -1
  247. package/modules/geometry.esm.min.js +2 -2
  248. package/modules/geometry.min.cjs +2 -2
  249. package/modules/geometry.min.js +2 -2
  250. package/modules/htmx.d.ts +1 -1
  251. package/modules/htmx.esm.min.js +3 -3
  252. package/modules/htmx.min.cjs +3 -3
  253. package/modules/htmx.min.js +3 -3
  254. package/modules/kanban.d.ts +1 -1
  255. package/modules/kanban.esm.min.js +2 -2
  256. package/modules/kanban.min.cjs +2 -2
  257. package/modules/kanban.min.js +2 -2
  258. package/modules/kpi.d.ts +1 -1
  259. package/modules/kpi.esm.min.js +2 -2
  260. package/modules/kpi.min.cjs +2 -2
  261. package/modules/kpi.min.js +2 -2
  262. package/modules/layout.d.ts +1 -1
  263. package/modules/layout.esm.min.js +2 -2
  264. package/modules/layout.min.cjs +2 -2
  265. package/modules/layout.min.js +2 -2
  266. package/modules/leaflet.d.ts +1 -1
  267. package/modules/leaflet.esm.min.js +2 -2
  268. package/modules/leaflet.min.cjs +2 -2
  269. package/modules/leaflet.min.js +2 -2
  270. package/modules/list.d.ts +1 -1
  271. package/modules/list.esm.min.js +2 -2
  272. package/modules/list.min.cjs +2 -2
  273. package/modules/list.min.js +2 -2
  274. package/modules/mapview.d.ts +1 -1
  275. package/modules/mapview.esm.min.js +2 -2
  276. package/modules/mapview.min.cjs +2 -2
  277. package/modules/mapview.min.js +2 -2
  278. package/modules/mock-socket.d.ts +1 -1
  279. package/modules/mock-socket.esm.min.js +1 -1
  280. package/modules/mock-socket.min.cjs +1 -1
  281. package/modules/mock-socket.min.js +1 -1
  282. package/modules/presets.d.ts +1 -1
  283. package/modules/presets.esm.min.js +2 -2
  284. package/modules/presets.min.cjs +2 -2
  285. package/modules/presets.min.js +2 -2
  286. package/modules/react.d.ts +1 -1
  287. package/modules/react.esm.min.js +2 -2
  288. package/modules/react.min.cjs +2 -2
  289. package/modules/react.min.js +2 -2
  290. package/modules/svelte.d.ts +1 -1
  291. package/modules/svelte.esm.min.js +2 -2
  292. package/modules/svelte.min.cjs +2 -2
  293. package/modules/svelte.min.js +2 -2
  294. package/modules/tabs.d.ts +1 -1
  295. package/modules/tabs.esm.min.js +2 -2
  296. package/modules/tabs.min.cjs +2 -2
  297. package/modules/tabs.min.js +2 -2
  298. package/modules/vue.d.ts +1 -1
  299. package/modules/vue.esm.min.js +2 -2
  300. package/modules/vue.min.cjs +2 -2
  301. package/modules/vue.min.js +2 -2
  302. package/modules/webcomponent.d.ts +1 -1
  303. package/modules/webcomponent.esm.min.js +3 -3
  304. package/modules/webcomponent.min.cjs +3 -3
  305. package/modules/webcomponent.min.js +3 -3
  306. package/package.json +1 -1
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * Lattice Grid 1.86.4, data-router module
2
+ * Lattice Grid 1.86.5, data-router module
3
3
  * Copyright (c) 2026 TOCLOCO Inc. All rights reserved.
4
4
  * https://latticegrid.dev
5
5
  */
6
- var Kn=Object.create(null),qn=Object.create(null);function pt(y,Oe){Kn[y]=Oe}function zn(y){var Oe=qn[y];if(Oe)return Oe;var de=Object.create(null);qn[y]=de;var A=Kn[y];if(!A)throw new Error("[lattice] missing module: "+y);return A(de,zn),de}pt("packages/core/src/internal/util.js",function(y,Oe){"use strict";Object.defineProperty(y,"VERSION",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"reportedWarnings",{enumerable:!0,get:function(){return x}}),Object.defineProperty(y,"warnOnce",{enumerable:!0,get:function(){return te}}),Object.defineProperty(y,"infoOnce",{enumerable:!0,get:function(){return z}}),Object.defineProperty(y,"resetWarnings",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(y,"fail",{enumerable:!0,get:function(){return $}}),Object.defineProperty(y,"invariant",{enumerable:!0,get:function(){return X}}),Object.defineProperty(y,"DEV",{enumerable:!0,get:function(){return P}}),Object.defineProperty(y,"isObject",{enumerable:!0,get:function(){return R}}),Object.defineProperty(y,"isFunction",{enumerable:!0,get:function(){return E}}),Object.defineProperty(y,"isNil",{enumerable:!0,get:function(){return N}}),Object.defineProperty(y,"isBlank",{enumerable:!0,get:function(){return H}}),Object.defineProperty(y,"isCtor",{enumerable:!0,get:function(){return q}}),Object.defineProperty(y,"pathGetter",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(y,"pathSetter",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(y,"getPath",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(y,"setPath",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(y,"humanise",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(y,"escapeHtml",{enumerable:!0,get:function(){return ht}}),Object.defineProperty(y,"titleCase",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(y,"expand",{enumerable:!0,get:function(){return h}}),Object.defineProperty(y,"toArray",{enumerable:!0,get:function(){return p}}),Object.defineProperty(y,"merge",{enumerable:!0,get:function(){return m}}),Object.defineProperty(y,"mergeRow",{enumerable:!0,get:function(){return S}}),Object.defineProperty(y,"Lru",{enumerable:!0,get:function(){return W}}),Object.defineProperty(y,"collator",{enumerable:!0,get:function(){return Be}}),Object.defineProperty(y,"defaultCompare",{enumerable:!0,get:function(){return nt}}),Object.defineProperty(y,"now",{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(y,"nextFrame",{enumerable:!0,get:function(){return a}}),Object.defineProperty(y,"cancelFrame",{enumerable:!0,get:function(){return g}}),Object.defineProperty(y,"frameBatched",{enumerable:!0,get:function(){return M}}),Object.defineProperty(y,"settleDebounce",{enumerable:!0,get:function(){return G}}),Object.defineProperty(y,"whenIdle",{enumerable:!0,get:function(){return O}}),Object.defineProperty(y,"uid",{enumerable:!0,get:function(){return Y}});const de="1.86.4";async function A(){return de}const se="1.86.4",pe=new Set,re=2e3;function ke(l){if(pe.add(l),pe.size>re){const u=pe.values().next().value;u!==void 0&&pe.delete(u)}}const D=[],J=500;function le(l,u,b){D.push({key:l,level:u,message:b.map(I=>typeof I=="string"?I:C(I)).join(" "),at:Date.now()}),D.length>J&&D.shift()}function C(l){if(l instanceof Error)return l.message;try{return JSON.stringify(l)}catch{return String(l)}}function x(){return D.map(l=>({...l}))}function _(l){if(l.length===0||typeof l[0]!="string")return l;const u=l[0].replace(/^\[lattice\]\s*/,"");return u===l[0]?l:[u,...l.slice(1)]}function te(l,...u){if(pe.has(l))return;ke(l);const b=_(u);le(l,"warn",b),console.warn("[lattice]",...b)}function z(l,...u){if(pe.has(l))return;ke(l);const b=_(u);le(l,"info",b),console.info("[lattice]",...b)}function ne(){pe.clear(),D.length=0}function $(l,u){const b=new Error(`[lattice] ${l}`);throw u!==void 0&&(b.cause=u),b}function X(l,u){l||$(u)}const P=(()=>{try{return!(typeof process<"u"&&process.env&&process.env.NODE_ENV==="production")}catch{return!0}})();function R(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)}function E(l){return typeof l=="function"}function N(l){return l==null}function H(l){return l==null||l===""}function q(l){return typeof l!="function"?!1:/^class[\s{]/.test(Function.prototype.toString.call(l))?!0:!!(l.prototype&&Object.getOwnPropertyNames(l.prototype).length>1)}const K=new Map;function ae(l){let u=K.get(l);if(u)return u;if(!l.includes("."))u=b=>b?.[l];else{const b=l.split("."),I=b.length;u=ve=>{let ie=ve;for(let he=0;he<I;he++){if(ie==null)return;ie=ie[b[he]]}return ie}}return K.set(l,u),u}const We=new Map;function Le(l){let u=We.get(l);if(u)return u;if(!l.includes("."))u=(b,I)=>{b!=null&&(b[l]=I)};else{const b=l.split("."),I=b.length-1;u=(ve,ie)=>{let he=ve;for(let ge=0;ge<I;ge++){if(he==null)return;const qe=b[ge];he[qe]==null&&(he[qe]={}),he=he[qe]}he!=null&&(he[b[I]]=ie)}}return We.set(l,u),u}function Ae(l,u){return ae(u)(l)}function ue(l,u,b){Le(u)(l,b)}function oe(l){return l?(l.includes(".")?l.slice(l.lastIndexOf(".")+1):l).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/^./,b=>b.toUpperCase()):""}const Ce={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function ht(l){const u=l==null?"":String(l);return/[&<>"']/.test(u)?u.replace(/[&<>"']/g,b=>Ce[b]):u}function xe(l){return String(l).replace(/\w\S*/g,u=>u[0].toUpperCase()+u.slice(1).toLowerCase())}function h(l,u,b){if(l!==void 0)return l===!0?{enabled:!0,...b}:l===!1?{enabled:!1}:R(l)?l:{[u]:l,enabled:!0}}function p(l){return l==null?[]:Array.isArray(l)?l:[l]}const c=Object.freeze(new Set(["__proto__","constructor","prototype"]));function m(l,u){if(!R(l))return R(u)?{...u}:u;if(!R(u))return u===void 0?l:u;const b={...l};for(const I of Object.keys(u)){if(c.has(I))continue;const ve=u[I];ve!==void 0&&(b[I]=R(ve)&&R(b[I])?m(b[I],ve):ve)}return b}function S(l,u){if(!R(l)||!R(u)||l===u)return u;const b=Object.create(Object.getPrototypeOf(l));return Object.assign(b,l,u),b}class W{#e;#t=new Map;#n;constructor(u=256,b=null){this.#e=u,this.#n=b}get size(){return this.#t.size}get max(){return this.#e}set max(u){this.#e=u,this.#r()}has(u){return this.#t.has(u)}get(u){const b=this.#t;if(!b.has(u))return;const I=b.get(u);return b.delete(u),b.set(u,I),I}peek(u){return this.#t.get(u)}set(u,b){const I=this.#t;return I.has(u)&&I.delete(u),I.set(u,b),this.#r(),b}delete(u){const b=this.#t.get(u);return this.#t.delete(u)&&this.#n&&this.#n(b,u),b}clear(){if(this.#n)for(const[u,b]of this.#t)this.#n(b,u);this.#t.clear()}keys(){return this.#t.keys()}values(){return this.#t.values()}#r(){const u=this.#t;for(;u.size>this.#e;){const b=u.keys().next().value,I=u.get(b);u.delete(b),this.#n&&this.#n(I,b)}}}const U=new Map;function Be(l,u){const b=`${l||""}|${u?JSON.stringify(u):""}`;let I=U.get(b);return I||(I=new Intl.Collator(l||void 0,{numeric:!0,sensitivity:"variant",...u}),U.set(b,I)),I}function nt(l,u){if(l===u)return 0;if(l==null)return 1;if(u==null)return-1;if(typeof l=="number"&&typeof u=="number")return Number.isNaN(l)?Number.isNaN(u)?0:1:Number.isNaN(u)||l<u?-1:l>u?1:0;const b=String(l),I=String(u);return b<I?-1:b>I?1:0}function Fe(){return typeof performance<"u"&&performance.now?performance.now():Date.now()}const Ze=typeof requestAnimationFrame=="function";function a(l){return Ze?requestAnimationFrame(l):setTimeout(()=>l(Fe()),16)}function g(l){l!=null&&(Ze?cancelAnimationFrame(l):clearTimeout(l))}function M(l){let u=null,b=null;const I=()=>{u=null;const ie=b;b=null,l(...ie||[])},ve=(...ie)=>{b=ie,u===null&&(u=a(I))};return ve.cancel=()=>{g(u),u=null,b=null},ve.flush=()=>{u!==null&&(g(u),I())},ve}function G(l,u){let b=null,I=null;const ve=()=>{if(b=null,I===null)return;const ge=I;I=null,l(...ge),ie()},ie=()=>{b=setTimeout(ve,u),typeof b?.unref=="function"&&b.unref()},he=(...ge)=>{b===null?(l(...ge),ie()):(I=ge,clearTimeout(b),ie())};return he.flush=()=>{if(b!==null&&clearTimeout(b),b=null,I===null)return;const ge=I;I=null,l(...ge)},he.cancel=()=>{b!==null&&clearTimeout(b),b=null,I=null},he.pending=()=>b!==null||I!==null,he}function O(l,u=50){return typeof requestIdleCallback=="function"?requestIdleCallback(l,{timeout:u}):setTimeout(()=>l({timeRemaining:()=>0,didTimeout:!0}),1)}let Q=0;function Y(l="l"){return`${l}${(++Q).toString(36)}`}}),pt("packages/core/src/source/filterwire.js",function(y,Oe){"use strict";Object.defineProperty(y,"HOST_FILTER_WARN_ID",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"WHERE_PAGE_RELATIVE_WARN_ID",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(y,"warnWherePageRelative",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"warnHostFilterNotApplied",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(y,"WHERE_NOT_APPLIED_WARN_ID",{enumerable:!0,get:function(){return D}}),Object.defineProperty(y,"warnWhereNotApplied",{enumerable:!0,get:function(){return J}}),Object.defineProperty(y,"WHERE_OVER_THRESHOLD_WARN_ID",{enumerable:!0,get:function(){return le}}),Object.defineProperty(y,"warnWhereOverThreshold",{enumerable:!0,get:function(){return C}}),Object.defineProperty(y,"RELATIVE_TOKENS",{enumerable:!0,get:function(){return P}}),Object.defineProperty(y,"parseRelativeToken",{enumerable:!0,get:function(){return R}}),Object.defineProperty(y,"resolveRelativeRange",{enumerable:!0,get:function(){return E}}),Object.defineProperty(y,"relativeTokenOf",{enumerable:!0,get:function(){return N}}),Object.defineProperty(y,"relativeTokenHelp",{enumerable:!0,get:function(){return H}}),Object.defineProperty(y,"isResolvableRelative",{enumerable:!0,get:function(){return q}}),Object.defineProperty(y,"resolveRelativeCondition",{enumerable:!0,get:function(){return K}}),Object.defineProperty(y,"isGroup",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(y,"forEachCondition",{enumerable:!0,get:function(){return We}}),Object.defineProperty(y,"mapConditions",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(y,"normaliseFilterSet",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(y,"buildFilterSet",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(y,"wireFilters",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(y,"querySignature",{enumerable:!0,get:function(){return ht}});const A=Oe("packages/core/src/internal/util.js").warnOnce,se="source.remote.hostFilter",pe="source.where.pageRelative";function re(p,c){!Array.isArray(p)||!p.length||A(pe,`filters.where (${p.join(", ")}) runs over the rows the ${c} source fetched,`,"not the whole dataset: match counts and totals are page-relative.","Give the predicate a { condition } twin so the engine can narrow the fetch itself.")}function ke(p){const c=(p||{}).config;!c||!c.hostFilter||A(se,"config.hostFilter is not sent to a server-delegated source (paged/remote) and is not applied:","filtering only the fetched window would give wrong counts and totals.","Express the filter as a FilterSet condition, or send it through config.context.")}const D="source.where.notApplied";function J(p,c){A(`${D}:${p}`,`filters.where("${p}") is registered but the ${c} source holds only its fetched window`,"and cannot run the predicate over it: the predicate is not applied there, and rows it would","exclude stay on screen.","Give it a { condition } twin so the engine can narrow the fetch itself — that is the","supported route for a paged or remote source.")}const le="source.where.overThreshold";function C(p,c,m,S){!Array.isArray(p)||!p.length||A(`${le}:${c}`,`filters.where (${p.join(", ")}) is not applied to the ${c} pushdown source:`,m===null?"the adapter reports no row total, so the size of the matching set is unknown.":`its matching set is ${m.toLocaleString()} rows, at or past the whereRowLimit of ${S.toLocaleString()}.`,"Running the predicate needs every matching row fetched and held here, which is the whole","download a pushdown source exists to avoid, so it is refused and the rows the predicate","would exclude stay on screen.","Give the predicate a { condition } twin so the engine narrows the fetch itself — that is the","route that works at any size — or raise `whereRowLimit` on the source config if you want the","download.")}const x=new Map;function _(p){let c=x.get(p);return c||(c=new Intl.DateTimeFormat("en-US",{timeZone:p,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),x.set(p,c)),c}function te(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function z(p,c){const m=_(c).formatToParts(new Date(p)),S={y:1970,m:1,d:1,h:0,mi:0,s:0};for(const W of m)W.type==="year"?S.y=+W.value:W.type==="month"?S.m=+W.value:W.type==="day"?S.d=+W.value:W.type==="hour"?S.h=+W.value%24:W.type==="minute"?S.mi=+W.value:W.type==="second"&&(S.s=+W.value);return S}function ne(p,c){const m=z(p,c);return Date.UTC(m.y,m.m-1,m.d,m.h,m.mi,m.s)-Math.floor(p/1e3)*1e3}function $(p,c,m,S){const W=Date.UTC(p,c-1,m),U=W-ne(W,S);return W-ne(U,S)}function X(p,c,m){const S=new Date(Date.UTC(p.y,p.m-1,p.d+c));return $(S.getUTCFullYear(),S.getUTCMonth()+1,S.getUTCDate(),m)}const P=Object.freeze(["today","yesterday","lastNDays","thisWeek","thisMonth","thisQuarter","thisYear","quarterToDate","yearToDate"]);function R(p,c){if(typeof p!="string")return null;const m=p.trim().toLowerCase().replace(/[\s_-]+/g,""),S=/^last(\d*|n)days?$/.exec(m);if(S){const W=S[1]==="n"?"":S[1],U=Number(W||c);return!Number.isFinite(U)||U<=0?null:{kind:"lastNDays",n:Math.floor(U)}}switch(m){case"today":return{kind:"today",n:0};case"yesterday":return{kind:"yesterday",n:0};case"thisweek":return{kind:"thisWeek",n:0};case"thismonth":return{kind:"thisMonth",n:0};case"thisquarter":return{kind:"thisQuarter",n:0};case"thisyear":return{kind:"thisYear",n:0};case"quartertodate":case"qtd":return{kind:"quarterToDate",n:0};case"yeartodate":case"ytd":return{kind:"yearToDate",n:0};default:return null}}function E(p,c={}){const m=R(p,c.n);if(!m)return null;const S=c.tz||te(),W=c.now instanceof Date?c.now.getTime():typeof c.now=="number"?c.now:Date.now(),U=z(W,S),Be=$(U.y,U.m,U.d,S),nt=X(U,1,S);let Fe=Be,Ze=nt;switch(m.kind){case"today":break;case"yesterday":Fe=X(U,-1,S),Ze=Be;break;case"lastNDays":Ze=c.includeToday?nt:Be,Fe=X(U,c.includeToday?-(m.n-1):-m.n,S);break;case"thisWeek":{const a=Number.isFinite(c.weekStartsOn)?Number(c.weekStartsOn):1,M=(new Date(Date.UTC(U.y,U.m-1,U.d)).getUTCDay()-a+7)%7;Fe=X(U,-M,S),Ze=X(U,-M+7,S);break}case"thisMonth":Fe=$(U.y,U.m,1,S),Ze=$(U.m===12?U.y+1:U.y,U.m===12?1:U.m+1,1,S);break;case"thisQuarter":case"quarterToDate":{const a=Math.floor((U.m-1)/3)*3+1;Fe=$(U.y,a,1,S),Ze=m.kind==="quarterToDate"?nt:a===10?$(U.y+1,1,1,S):$(U.y,a+3,1,S);break}case"thisYear":case"yearToDate":Fe=$(U.y,1,1,S),Ze=m.kind==="yearToDate"?nt:$(U.y+1,1,1,S);break;default:return null}return{from:new Date(Fe).toISOString(),to:new Date(Ze).toISOString(),bounds:"[)",tz:S,relative:m.kind==="lastNDays"?`last${m.n}Days`:m.kind,n:m.n}}function N(p){if(!p||typeof p!="object")return null;const c=p.value;if(c&&typeof c=="object"&&!Array.isArray(c)&&"relative"in c)return{token:String(c.relative),n:typeof c.n=="number"?c.n:void 0};if(p.op==="relative"&&typeof p.value=="string")return{token:p.value,n:void 0};const m=p.meta;return m&&typeof m.relative=="string"&&p.value===void 0?{token:m.relative,n:typeof m.n=="number"?m.n:void 0}:null}function H(){return`Known tokens: ${P.filter(c=>c!=="lastNDays").join(", ")}. "lastNDays" needs a count: pass "last7Days", or the value object { relative: 'lastNDays', n: 7 }.`}function q(p){const c=N(p);return c?R(c.token,c.n)!==null:!1}function K(p,c={}){const m=N(p);if(!m)return p;const S=E(m.token,{...c,n:m.n});return S?{...p,type:p.type||"date",op:"between",value:[S.from,S.to],bounds:p.bounds||S.bounds,meta:{...p.meta||{},relative:S.relative,tz:S.tz}}:(A(`source.relative.${m.token}`,`unknown relative date token "${m.token}"; sending the condition unresolved.`,H()),p)}function ae(p){return!!p&&typeof p=="object"&&Array.isArray(p.conditions)}function We(p,c){if(p){if(ae(p)){for(const m of p.conditions)We(m,c);return}c(p)}}function Le(p,c){if(!p)return null;if(!ae(p))return c(p);const m=p;let S=!1;const W=[];for(const U of m.conditions){const Be=Le(U,c);Be!==U&&(S=!0),Be&&W.push(Be)}return!S&&W.length===m.conditions.length?p:W.length?{...m,conditions:W}:null}function Ae(p){if(!p)return null;if(!ae(p))return p;const c=p,m=[];for(const S of c.conditions){const W=Ae(S);W&&m.push(W)}return m.length?{op:c.op,conditions:m}:null}function ue(p){const c=Ae(p);return c?ae(c)&&c.op==="and"?c:{op:"and",conditions:[c]}:null}function oe(p){const c=(p||[]).filter(Boolean);return c.length?{op:"and",conditions:c}:null}function Ce(p,c={}){const m=Le(p,S=>K(S,c));return ue(m)}function ht(p){const c=xe(p.filters??null);return JSON.stringify([c,p.sort??null,p.quick??"",p.groupBy??null,p.pivotBy??null,h(p.context)])}function xe(p){if(!p)return null;if(ae(p)){const S=p;return{op:S.op,conditions:S.conditions.map(xe)}}const c=p,m=c.meta&&typeof c.meta.relative=="string"?c.meta.relative:N(c)?.token;return{col:c.col,op:c.op,bounds:c.bounds??null,caseSensitive:c.caseSensitive??!1,value:m?`rel:${m}`:c.value??null}}function h(p){if(p==null)return null;try{return JSON.parse(JSON.stringify(p))}catch{return A("source.context.unserialisable","config.context is not JSON-serialisable; cache keys ignore it."),"[unserialisable]"}}}),pt("packages/core/src/source/aggregates.js",function(y,Oe){"use strict";Object.defineProperty(y,"STAT_PUSHDOWN",{enumerable:!0,get:function(){return de}}),Object.defineProperty(y,"pushableAggregates",{enumerable:!0,get:function(){return A}}),Object.defineProperty(y,"fillAggregateSql",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"resolveAggregatesConfig",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(y,"routeAggregate",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"resolveAggregatePlan",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(y,"groupKeysPushable",{enumerable:!0,get:function(){return J}}),Object.defineProperty(y,"pushdownDocRows",{enumerable:!0,get:function(){return le}});const de=Object.freeze({sum:{pushable:!0,class:"identical",sql:"sum(%c)"},avg:{pushable:!0,class:"identical",sql:"avg(%c)"},min:{pushable:!0,class:"identical",sql:"min(%c)"},max:{pushable:!0,class:"identical",sql:"max(%c)"},count:{pushable:!0,class:"identical",sql:"count(*)"},countValues:{pushable:!0,class:"identical",sql:"count(%c)",blankAware:!0},range:{pushable:!0,class:"identical",sql:"(max(%c) - min(%c))"},variance:{pushable:!0,class:"identical",sql:"var_samp(%c)"},varianceP:{pushable:!0,class:"identical",sql:"var_pop(%c)"},stddev:{pushable:!0,class:"identical",sql:"stddev_samp(%c)"},stddevP:{pushable:!0,class:"identical",sql:"stddev_pop(%c)"},sumSquares:{pushable:!0,class:"identical",sql:"sum(%c * %c)"},median:{pushable:!0,class:"identical",sql:"median(%c)"},p25:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.25)"},p75:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.75)"},p90:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.9)"},p95:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.95)"},p99:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.99)"},iqr:{pushable:!0,class:"identical",sql:"(quantile_cont(%c, 0.75) - quantile_cont(%c, 0.25))"},mad:{pushable:!0,class:"identical",sql:"mad(%c)"},distinct:{pushable:!0,class:"identical",sql:"count(DISTINCT %c)",blankAware:!0},skewness:{pushable:!0,class:"identical",sql:"skewness(%c)"},kurtosis:{pushable:!0,class:"identical",sql:"kurtosis(%c)"},geomean:{pushable:!0,class:"identical",sql:"exp(avg(ln(%c)))"},harmean:{pushable:!0,class:"identical",sql:"(count(%c) / sum(1.0 / %c))"},entropy:{pushable:!0,class:"identical",sql:"entropy(%c)",blankAware:!0},correlation:{pushable:!0,class:"identical",sql:"corr(%w, %c)",twoColumn:!0},hhi:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL ELSE list_sum(list_transform(map_values(histogram(%c)), lambda v: (v::DOUBLE/count(%c))*(v::DOUBLE/count(%c)))) END"},evenness:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL WHEN count(DISTINCT %c)<2 THEN 1.0 ELSE entropy(%c)/log2(count(DISTINCT %c)) END"},top3Share:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL ELSE list_sum(list_slice(list_sort(map_values(histogram(%c)),'DESC'),1,3))::DOUBLE/count(%c) END"},top10Share:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL ELSE list_sum(list_slice(list_sort(map_values(histogram(%c)),'DESC'),1,10))::DOUBLE/count(%c) END"},gini:{pushable:!0,class:"identical",sql:"CASE WHEN list_min(list(%c) FILTER (WHERE isfinite(%c)))<0 THEN NULL WHEN len(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN NULL WHEN list_sum(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN 0 ELSE 2.0*list_sum(list_transform(list_sort(list(%c) FILTER (WHERE isfinite(%c))), lambda v, i: i*v))/(len(list(%c) FILTER (WHERE isfinite(%c)))*list_sum(list(%c) FILTER (WHERE isfinite(%c))))-(len(list(%c) FILTER (WHERE isfinite(%c)))+1.0)/len(list(%c) FILTER (WHERE isfinite(%c))) END"},trimmedMean:{pushable:!0,class:"identical",sql:"CASE WHEN len(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN NULL ELSE list_avg(list_slice(list_sort(list(%c) FILTER (WHERE isfinite(%c))), floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT+1, len(list(%c) FILTER (WHERE isfinite(%c)))-floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT)) END"},winsorizedMean:{pushable:!0,class:"identical",sql:"CASE WHEN len(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN NULL ELSE list_avg(list_transform(list_sort(list(%c) FILTER (WHERE isfinite(%c))), lambda v: least(list_sort(list(%c) FILTER (WHERE isfinite(%c)))[len(list(%c) FILTER (WHERE isfinite(%c)))-floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT], greatest(list_sort(list(%c) FILTER (WHERE isfinite(%c)))[floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT+1], v)))) END"},robustOutliers:{pushable:!0,class:"identical",sql:"(SELECT CASE WHEN len(d.a)=0 THEN NULL WHEN d.mad=0 THEN NULL ELSE len(list_filter(d.a, lambda v: abs(0.6745*(v-d.med)/d.mad)>3.5)) END FROM (SELECT xs AS a, list_median(xs) AS med, list_median(list_transform(xs, lambda w: abs(w-list_median(xs)))) AS mad FROM (SELECT list(%c) FILTER (WHERE isfinite(%c)) AS xs)) d)"},jarqueBera:{pushable:!0,class:"identical",sql:"CASE WHEN len(list(%c) FILTER (WHERE isfinite(%c)))<8 THEN NULL WHEN list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),2)))=0 THEN NULL ELSE (len(list(%c) FILTER (WHERE isfinite(%c)))/6.0)*(power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),3)))/power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),2))),1.5),2)+power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),4)))/power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),2))),2)-3,2)/4.0) END"},weightedAvg:{pushable:!0,class:"identical",twoColumn:!0,sql:"sum(%c*%w) FILTER (WHERE isfinite(%c) AND isfinite(%w))/nullif(sum(%w) FILTER (WHERE isfinite(%c) AND isfinite(%w)),0)"},mode:{pushable:!0,class:"may-differ",sql:"mode(%c)",note:"DuckDB returns a modal value even for an all-distinct column; the grid returns null. Tie-breaking can also differ, and on a text column an empty string counts as a value. Under pushdown you will see a value."},weightedQuantile:{pushable:!1,class:"fallback",note:"No SQL equivalent for the grid's weighted-quantile midpoint convention; always computed client-side (needs a full-dataset pull for a correct figure over a remote source)."}});function A(){const C=new Set;for(const[x,_]of Object.entries(de))_.pushable&&C.add(x);return C}function se(C,x,_){let te=C.split("%c").join(x);return _!==void 0&&(te=te.split("%w").join(_)),te}function pe(C){const x=C||{},_=x.default==="engine"||x.default==="engine-if-identical"?x.default:"client",te={};if(x.overrides&&typeof x.overrides=="object")for(const[z,ne]of Object.entries(x.overrides))(ne==="engine"||ne==="client")&&(te[z]=ne);return{default:_,overrides:te}}function re(C,x){const _=de[C];if(!_||!_.pushable)return"client";const te=x.overrides[C];return te==="engine"||te==="client"?te:x.default==="client"?"client":x.default==="engine-if-identical"?_.class==="identical"?"engine":"client":"engine"}function ke(C,x){const _=pe(x),te=[],z=[];for(const ne of C||[]){const $=de[ne.fn],X=re(ne.fn,_),P={id:ne.id,col:ne.col,fn:ne.fn,class:$?$.class:"fallback"};ne.weight!==void 0&&(P.weight=ne.weight),ne.params!==void 0&&(P.params=ne.params),X==="engine"?te.push(P):(P.reason=$&&!$.pushable?$.note||"the engine cannot express this stat":"client by config",z.push(P))}return{engine:te,client:z,config:_}}const D=/^[A-Za-z_][A-Za-z0-9_$]*$/;function J(C,x=[]){return(C||[]).every(te=>{if(typeof te=="string")return D.test(te);if(!te||typeof te!="object")return!1;const z=te;return Array.isArray(x)&&x.includes(z.bucket)&&typeof z.col=="string"&&D.test(z.col)&&typeof z.size=="number"&&Number.isFinite(z.size)&&z.size>0})}function le(){return Object.entries(de).map(([C,x])=>({stat:C,class:x.class,sql:x.sql?se(x.sql,"col",x.twoColumn?"weight":void 0):"",note:x.note||(x.class==="identical"?"Pushes to DuckDB with the same result.":"")}))}}),pt("packages/core/src/source/abort.js",function(y,Oe){"use strict";Object.defineProperty(y,"SupersededError",{enumerable:!0,get:function(){return de}}),Object.defineProperty(y,"RequestToken",{enumerable:!0,get:function(){return A}}),Object.defineProperty(y,"AbortScope",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"createAbortScope",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(y,"isAbortError",{enumerable:!0,get:function(){return re}});class de extends Error{constructor(D,J="superseded"){super(`[lattice] request ${D?`"${D}" `:""}${J}`),this.name="SupersededError",this.superseded=!0,this.key=D}}class A{#e;constructor(D,J,le,C){this.#e=D,this.key=J,this.controller=le,this.signal=le.signal,this.seq=C}get current(){return!this.signal.aborted&&this.#e.tokenFor(this.key)===this}settle(){this.#e.settle(this)}abort(D){this.signal.aborted||this.controller.abort(new de(this.key,D)),this.#e.settle(this)}}class se{#e=new Map;#t=0;begin(D="",J="superseded"){const le=this.#e.get(D);le&&!le.signal.aborted&&le.controller.abort(new de(D,J));const C=new A(this,D,new AbortController,++this.#t);return this.#e.set(D,C),C}tokenFor(D){return this.#e.get(D)}pending(D=""){const J=this.#e.get(D);return!!J&&!J.signal.aborted}get size(){return this.#e.size}settle(D){this.#e.get(D.key)===D&&this.#e.delete(D.key)}abort(D="",J="superseded"){const le=this.#e.get(D);le&&le.abort(J)}abortAll(D="superseded"){for(const J of[...this.#e.values()])J.abort(D);this.#e.clear()}}function pe(){return new se}function re(ke){if(!ke||typeof ke!="object")return!1;const D=ke;return D.superseded===!0||D.name==="AbortError"||D.name==="SupersededError"}}),pt("packages/core/src/source/pushdown.js",function(y,Oe){"use strict";Object.defineProperty(y,"FOREGROUND_WAIT_MS",{enumerable:!0,get:function(){return $}}),Object.defineProperty(y,"NO_CAPABILITIES",{enumerable:!0,get:function(){return P}}),Object.defineProperty(y,"resolveMutate",{enumerable:!0,get:function(){return R}}),Object.defineProperty(y,"capabilitiesOf",{enumerable:!0,get:function(){return H}}),Object.defineProperty(y,"splitFilters",{enumerable:!0,get:function(){return K}}),Object.defineProperty(y,"LEAF_COUNT_ID",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(y,"PIVOT_UNSUPPORTED",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(y,"GROUP_UNSUPPORTED",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(y,"UNGROUPED_LEVEL",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(y,"planQuery",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(y,"applyResidual",{enumerable:!0,get:function(){return c}}),Object.defineProperty(y,"DEFAULT_WHERE_ROW_LIMIT",{enumerable:!0,get:function(){return U}}),Object.defineProperty(y,"createPushdownSource",{enumerable:!0,get:function(){return Ze}});const de=Oe("packages/core/src/internal/util.js"),A=de.defaultCompare,se=de.isFunction,pe=de.toArray,re=de.warnOnce,ke=Oe("packages/core/src/source/filterwire.js"),D=ke.isGroup,J=ke.warnWherePageRelative,le=ke.warnWhereOverThreshold,C=Oe("packages/core/src/source/aggregates.js"),x=C.resolveAggregatePlan,_=C.groupKeysPushable,te=C.STAT_PUSHDOWN,ne=Oe("packages/core/src/source/abort.js").SupersededError,$=1e3;function X(a){const g=a&&a.signal;if(!g||!g.aborted)return;const M=g.reason;throw M instanceof Error?M:new ne("","superseded before it was sent")}const P=Object.freeze({filter:!1,operators:Object.freeze([]),sort:!1,quick:!1,range:!1,total:!1,group:!1,pivot:!1,mutate:!1});function R(a){if(!a||typeof a!="object")return!1;const g=a.returning==="row"||a.returning==="key"?a.returning:"none";return{append:a.append===!0,update:a.update===!0,delete:a.delete===!0,returning:g}}function E(a,g){if(!a||typeof g!="string")return;if(!g.includes("."))return a[g];let M=a;for(const G of g.split(".")){if(M===null||typeof M!="object")return;M=M[G]}return M}function N(a){if(a===!0)return!0;if(!a||typeof a!="object")return!1;const g=a;return g.enabled===!1?!1:g.enabled===!0||se(g.commit)}function H(a){const g={...P,...a||{}};return g.operators=new Set(g.operators||[]),g.mutate=R(g.mutate),g}function q(a,g){return!a||!a.op||!g.operators.size?!1:g.operators.has(a.op)}function K(a,g){if(!a)return{pushed:null,residual:null};if(!g.filter)return{pushed:null,residual:a};if(g.filter==="term"){if(D(a)){const Q=a.conditions||[];if(String(a.op)!=="and")return{pushed:null,residual:a};const Y=Q.findIndex(u=>!D(u)&&q(u,g));if(Y<0)return{pushed:null,residual:a};const l=Q.filter((u,b)=>b!==Y);return{pushed:Q[Y],residual:l.length?{op:"and",conditions:l}:null}}return q(a,g)?{pushed:a,residual:null}:{pushed:null,residual:a}}if(!D(a))return q(a,g)?{pushed:a,residual:null}:{pushed:null,residual:a};if(String(a.op)!=="and")return(a.conditions||[]).every(Y=>D(Y)?K(Y,g).residual===null:q(Y,g))?{pushed:a,residual:null}:{pushed:null,residual:a};const M=[],G=[];for(const Q of a.conditions||[]){if(D(Q)){if(g.filter==="flat"){G.push(Q);continue}const Y=K(Q,g);Y.pushed&&M.push(Y.pushed),Y.residual&&G.push(Y.residual);continue}(q(Q,g)?M:G).push(Q)}const O=Q=>Q.length===0?null:Q.length===1?Q[0]:{op:"and",conditions:Q};return{pushed:O(M),residual:O(G)}}const ae="__lattice_leaves";function We(a){return a.aggregates?a.aggregates instanceof Set?a.aggregates:new Set(pe(a.aggregates)):new Set}function Le(a){const g=We(a);return g.size?g.has("count")?a.filter!=="tree"||!a.operators||!a.operators.has("eq")?"the adapter does not declare the `group` capability, and cannot narrow a group's rows by its key (that needs a `tree` filter with the `eq` operator)":"":"the adapter does not declare the `group` capability, and its declared aggregates have no `count` to give each group its row count":"the adapter does not declare the `group` capability"}function Ae(a,g,M,G,O,Q,Y){const l=Array.isArray(a.groupBy)?a.groupBy:[],u=Array.isArray(a.groupPath)?a.groupPath:[],b=Array.isArray(a.groupValues)?a.groupValues:null;if(!g.group){const I=Le(g);if(I)return I}return _(l)?M.residual?"the filter did not fully push, so the engine would group a superset of the matching rows":G?O?Q?"a host `where` predicate can only run in the browser, over rows the engine grouped":Y?"fullDataset holds the whole matching set, so the grid groups it itself":!b||b.length!==u.length?"the request carries no typed `groupValues` for its group path, and the string `groupPath` cannot be compared against a typed column":"":"a quick search did not push, so the engine would group unsearched rows":"the sort did not push, so the engine would order the groups differently":"a grouping key is not a plain column the engine can name in a GROUP BY"}const ue="pushdown:pivot-unsupported",oe="pushdown:group-unsupported",Ce=Symbol("lattice.remote.ungroupedLevel");function ht(a,g,M,G,O,Q){const Y=Array.isArray(a.pivotBy)?a.pivotBy:[],l=Array.isArray(a.groupBy)?a.groupBy:[],u=Array.isArray(a.groupPath)?a.groupPath:[],b=Array.isArray(a.groupValues)?a.groupValues:null;return g.pivot?_(Y)?l.length&&!_(l)?"a grouping key is not a plain column the engine can name in a GROUP BY":M.residual?"the filter did not fully push, so the engine would pivot a superset of the matching rows":G?O?Q?"a host `where` predicate can only run in the browser, over rows the engine pivoted":!b||b.length!==u.length?"the request carries no typed `groupValues` for its group path, and the string `groupPath` cannot be compared against a typed column":"":"a quick search did not push, so the engine would pivot unsearched rows":"the sort did not push, so the engine would order the rows differently":"a pivot column is not a plain column the engine can name in a GROUP BY":"the adapter does not declare the `pivot` capability"}function xe(a,g,M=!1){const G=K(a.filters||null,g),O=[];G.residual&&O.push("filter");const Q=a.sort||[],Y=Q.length===0||g.sort==="multi"&&Q.length>=1||g.sort==="single"&&Q.length===1;!Y&&Q.length&&O.push("sort");const l=a.quick?String(a.quick):"",u=!l||!!g.quick;u||O.push("quick");const b=a.where&&a.where.active?a.where:null;b&&O.push("where");const I={filters:G.residual,sort:Y?null:Q,quick:u?"":l,where:b},ve=!!M,ie=Array.isArray(a.groupBy)&&a.groupBy.length>0,he=ie?Ae(a,g,G,Y,u,b,ve):"",ge=a.pivotMode!==!1&&Array.isArray(a.pivotBy)&&a.pivotBy.length>0,qe=ge?ht(a,g,G,Y,u,b):"",Te=ge&&qe==="";ge&&!Te&&O.push("pivot");const ze=ge?Te&&ie:ie&&he==="";ie&&!ge&&!ze&&O.push("group");const $e=(ze||Te)&&Array.isArray(a.groupValues)?a.groupValues.length:0,ut=ze||ge?!1:ve||!!(I.filters||I.sort||I.quick||I.where)||!g.range;return{pushed:{...a,filters:G.pushed,sort:Y?Q:[],quick:u?l:"",range:ut?null:a.range},residual:I,needsAll:ut,unpushed:O,full:ve,grouped:ze,groupLevel:$e,groupReason:ge?"":he,pivoted:Te,pivotReason:qe}}function h(a){const g=Array.isArray(a.totals)?a.totals:[],M=a.totalFns&&typeof a.totalFns=="object"?a.totalFns:{},G=[],O=[];for(const Q of g){const Y=String(Q),l=typeof M[Y]=="string"?M[Y]:null,u=l?te[l]:null;l?!u||!u.pushable||!u.sql?O.push({id:Y,fn:l,class:u?u.class:"fallback",reason:u&&u.note?u.note:`the pushdown map cannot express "${l}"`}):u.twoColumn?O.push({id:Y,fn:l,class:u.class,reason:`"${l}" reduces two columns, and a grouped request carries no weight column`}):G.push({id:Y,col:Y,fn:l,class:u.class}):O.push({id:Y,fn:null,class:"fallback",reason:"the column totals with a host function, so there is no named statistic to push"})}return{engine:G,client:O}}const p=Object.freeze({items:a=>a==null?[]:Array.isArray(a)?a:[a]});function c(a,g,M){if(!g)return a;let G=a;if(g.filters&&se(M.evaluateFilters)){const O=G,Q={count:G.length,handle:u=>({id:u,get:b=>E(O[b],u)}),itemwise:u=>O.some(b=>Array.isArray(E(b,u)))?p:null},Y=M.evaluateFilters(g.filters,Q),l=[];for(let u=0;u<G.length;u++)Y[u]&&l.push(G[u]);G=l}if(g.where&&g.where.active&&(g.whole||J(g.where.names,"pushdown"),G=G.filter(O=>g.where.passes(O))),g.quick){const O=g.quick.toLowerCase();G=G.filter(Q=>{if(!Q||typeof Q!="object")return!1;for(const Y of Object.values(Q))if(Y!=null&&String(Y).toLowerCase().includes(O))return!0;return!1})}if(g.sort&&g.sort.length&&se(M.sortMulti)){const O=[...new Set(g.sort.map(u=>u.col))],Q=G,Y=O.map(u=>({id:u,get:b=>E(Q[b],u)})),l=M.sortMulti(Y,g.sort.map(u=>({col:u.col,dir:u.dir})),Uint32Array.from({length:G.length},(u,b)=>b),{});G=Array.from(l,u=>Q[u])}return G}function m(a){return JSON.stringify({filters:a.filters||null,sort:a.sort||[],quick:a.quick||"",groupBy:a.groupBy||[],groupPath:a.groupPath||[],context:a.context??null})}function S(a){if(!a||typeof a!="object")return 16;let g="";try{g=JSON.stringify(a)}catch{return 200}return g.length*2+64}function W(a){const g=a||{};return{enabled:!!g.enabled,maxRows:Number.isFinite(g.maxRows)?g.maxRows:1e6,maxBytesEstimate:Number.isFinite(g.maxBytesEstimate)?g.maxBytesEstimate:512*1024*1024}}const U=5e4;function Be(a){return Number.isFinite(a)&&a>=0?a:U}function nt(a){return!!a&&se(a.then)}async function Fe(a){if(!a||a.total!==void 0||!nt(a.pendingTotal))return a;const g=await a.pendingTotal,{pendingTotal:M,...G}=a;return typeof g=="number"?{...G,total:g}:G}function Ze(a={}){const g=a.adapter;if(!g||!se(g.execute))return re("source.pushdown.adapter","createPushdownSource needs an `adapter` with an `execute(query)` function."),{...a,mode:"remote",fetch:async()=>({rows:[],total:0})};const M=H(g.capabilities),G=g.capabilities&&Object.getOwnPropertyDescriptor(g.capabilities,"operators");G&&se(G.get)&&Object.defineProperty(M,"operators",{enumerable:!0,configurable:!0,get:()=>new Set(g.capabilities.operators||[]),set:()=>{}});const O=g.name||"adapter";let Q=null;const Y=()=>se(g.ready)?(Q||(Q=Promise.resolve(g.ready()).then(()=>{Object.assign(M,H(g.capabilities))},F=>{throw Q=null,F})),Q):null,l=W(a.fullDataset),u=!!a.allowPartialResults,b=Be(a.whereRowLimit);let I=null;const ve=a.aggregates;let ie=null,he=null,ge=null,qe=null,Te=null,ze,$e=null,ut=0,ct=null;const it=()=>!l.enabled||!ie?null:(ct!==ie.key&&(ut++,ct=ie.key),{rows:ie.rows,version:ut}),Et=async F=>{const L=F.where&&F.where.active?F.where:null;if(!L)return{request:F,probe:null};const{where:Z,...V}=F,T=xe(V,M,l.enabled);if(T.needsAll)return{request:F,probe:null};const me=m(T.pushed);let we=null;return(!I||I.key!==me)&&(M.total?(X(F),we=await Fe(await g.execute(T.pushed,F)),I={key:me,size:we&&typeof we.total=="number"?we.total:null}):I={key:me,size:null}),I.size!==null&&I.size<b?{request:F,probe:null}:(le(L.names,O,I.size,b),{request:V,probe:we})},jt=async(F,L)=>{$e=null;const Z=h(F.pushed);ge={engine:Z.engine,client:Z.client,groupBy:F.pushed.groupBy},Z.client.length&&re(`source.pushdown.group.totals.${O}.${Z.client.map(me=>me.id).join(".")}`,`the ${O} adapter cannot compute the group subtotal for ${Z.client.map(me=>`"${me.id}" (${me.reason})`).join(", ")}, so those group rows carry no value for that column. A figure computed over anything other than the group would be wrong, so none is shown; \`lastPlan().aggregates.client\` names them.`);const V=await g.executeGroupLevel(F.pushed,Z.engine,L)||{};let T=V.rows||[];return!M.range&&L.range&&(T=T.slice(L.range.start,L.range.end)),rt(V),V.total===void 0?{rows:T}:{rows:T,total:V.total}},st=new Map,Yt=64,wt=async(F,L)=>{$e=null;const Z=F.pushed,V=Z.groupBy,T=Array.isArray(Z.groupValues)?Z.groupValues:[],me=T.length,we=[...Z.filters?[Z.filters]:[],...V.slice(0,me).map((ee,Ge)=>({col:ee,op:"eq",value:T[Ge]===void 0?null:T[Ge],caseSensitive:!0}))],be=we.length===0?null:we.length===1?we[0]:{op:"and",conditions:we},He=L.range?L.range.start:0;if(me>=V.length){const ee={...Z,filters:be,groupBy:[],groupPath:[],groupValues:[],totals:[],totalFns:{}},Ge=await Fe(await g.execute(ee,L))||{};let et=Ge.rows||[];return!M.range&&L.range&&(et=et.slice(L.range.start,L.range.end)),typeof Ge.total=="number"?{rows:et,total:Ge.total}:{rows:et}}const Re=V[me],ce=h(Z),Ue=We(M),tt=ce.engine.filter(ee=>Ue.has(ee.fn)),De=[...ce.engine.filter(ee=>!Ue.has(ee.fn)).map(ee=>({id:ee.id,fn:ee.fn,class:ee.class,reason:`the ${O} adapter does not compute "${ee.fn}"`})),...ce.client];ge={engine:tt,client:De,groupBy:V},De.length&&re(`source.pushdown.group.totals.${O}.${De.map(ee=>ee.id).join(".")}`,`the ${O} adapter cannot compute the group subtotal for ${De.map(ee=>`"${ee.id}" (${ee.reason})`).join(", ")}, so those group rows carry no value for that column. A figure computed over anything other than the group would be wrong, so none is shown; \`lastPlan().aggregates.client\` names them.`);const fe=[...tt.map(ee=>({id:ee.id,col:ee.col,fn:ee.fn})),{id:ae,col:Re,fn:"count"}],Ee={...Z,filters:be,range:null},Me=JSON.stringify([m(Ee),T,Re,fe]);let je=He>0?st.get(Me):void 0;if(!je){for(je=Promise.resolve(g.executeGroupedAggregates(Ee,[Re],fe)),st.delete(Me),st.set(Me,je);st.size>Yt;)st.delete(st.keys().next().value);je.catch(()=>{st.get(Me)===je&&st.delete(Me)})}const vt=await je||[];X(L);const $t=ee=>{const Ge={};for(const et of tt)Ge[et.id]=ee?ee[et.id]:void 0;return Ge},at=(Z.sort||[]).find(ee=>ee&&ee.col===Re),Ne=at&&at.dir==="desc"?-1:1,ot=vt.filter(ee=>ee&&ee.level===1).map(ee=>({[Re]:ee.keys[0]===void 0?null:ee.keys[0],leafCount:Number(ee.values&&ee.values[ae])||0,totals:$t(ee.values)})).sort((ee,Ge)=>Ne*A(ee[Re],Ge[Re]));if(me===0){const ee=vt.find(et=>et&&et.level===0),Ge=ee?Number(ee.values&&ee.values[ae]):NaN;rt({matchCount:Number.isFinite(Ge)?Ge:ot.reduce((et,Xt)=>et+Xt.leafCount,0),...ee?{grand:$t(ee.values)}:{}})}const Dt=L.range?L.range.end:ot.length;return{rows:ot.slice(He,Dt),total:ot.length}},rt=F=>{typeof F.matchCount=="number"&&(qe=F.matchCount,Te=F.grand?{totals:F.grand,leafCount:F.matchCount}:null,ze===void 0&&se(g.unfilteredCount)&&(ze=null,Promise.resolve(g.unfilteredCount()).then(L=>{ze=typeof L=="number"?L:null}).catch(L=>{re(`source.pushdown.group.unfiltered.${O}`,`the ${O} adapter could not count the unfiltered set (${L&&L.message?L.message:L}), so "N of M" falls back to the display count for its denominator.`)})))},gt=async(F,L)=>{$e=null;const Z=h(F.pushed);ge={engine:Z.engine,client:Z.client,groupBy:F.pushed.groupBy,pivotBy:F.pushed.pivotBy},Z.client.length&&re(`source.pushdown.pivot.totals.${O}.${Z.client.map(be=>be.id).join(".")}`,`the ${O} adapter cannot compute the pivot cells for ${Z.client.map(be=>`"${be.id}" (${be.reason})`).join(", ")}, so those cells are empty. A figure computed over anything other than the cell would be wrong, so none is shown; \`lastPlan().aggregates.client\` names them.`);const V=await g.executePivotLevel(F.pushed,Z.engine,L)||{};let T=V.rows||[];!M.range&&L.range&&(T=T.slice(L.range.start,L.range.end)),rt(V);const me=V.pivot&&typeof V.pivot=="object"?V.pivot:{},we={cells:Array.isArray(me.cells)?me.cells:[],...Array.isArray(me.axis)?{axis:me.axis}:{}};return V.total===void 0?{rows:T,pivot:we}:{rows:T,total:V.total,pivot:we}},At=F=>{re(`source.pushdown.pivot.${O}.${F}`,`pushdown:pivot-unsupported: the ${O} adapter cannot pivot this query because ${F}, so no rows are fetched rather than every leaf row being pulled into the browser to pivot there. \`lastPlan().pivotReason\` says the same.`);const L=new Error(`[lattice] ${ue}: the ${O} adapter cannot pivot this query because ${F}, so no rows are fetched rather than every leaf row being pulled into the browser to pivot there. \`lastPlan().pivotReason\` says the same.`);throw L.code=ue,L.reason=F,L},Qt=(F,L)=>{const Z={key:L,state:"pending",value:null};return $e=Z,F.then(V=>($e===Z&&($e={key:L,state:"settled",value:typeof V=="number"?V:null}),V),V=>{throw $e===Z&&($e={key:L,state:"failed",value:null}),V})};let _e=0,Je=[];const Xe=()=>_e===0?null:new Promise(F=>{const L=setTimeout(F,$);Je.push(()=>{clearTimeout(L),F()})}),Ye=async F=>{const L=Y();L&&await L;const V=F&&F.pivotMode!==!1&&Array.isArray(F.pivotBy)&&F.pivotBy.length>0?{request:F,probe:null}:await Et(F);X(F);let T=xe(V.request,M,l.enabled);if(M.group&&T.grouped&&!T.pivoted&&!se(g.executeGroupLevel)&&(re(`source.pushdown.group.method.${O}`,`the ${O} adapter declares the \`group\` capability but has no \`executeGroupLevel(query, aggregates, request)\`, so grouping is not pushed and the grid stays ungrouped unless it holds the whole matching set. Implement the method or drop the capability.`),T=xe(V.request,{...M,group:!1,aggregates:null},l.enabled)),T.pivoted&&!se(g.executePivotLevel)&&(T=xe(V.request,{...M,pivot:!1},l.enabled),T.pivotReason="the adapter declares the `pivot` capability but has no `executePivotLevel(query, aggregates, request)`"),T.grouped&&!T.pivoted&&!M.group&&!se(g.executeGroupedAggregates)&&(re(`source.pushdown.group.aggregates.method.${O}`,`the ${O} adapter declares \`aggregates\` but has no \`executeGroupedAggregates(query, groupBy, aggregates)\`, so the grouped view cannot be built from grouped aggregates and the grid stays ungrouped unless it holds the whole matching set. Implement the method, or declare \`group\` and implement \`executeGroupLevel\`.`),T=xe(V.request,{...M,aggregates:null},l.enabled)),he=T,T.pivoted)return gt(T,F);if(T.pivotReason&&At(T.pivotReason),T.grouped)return M.group?jt(T,F):wt(T,F);const we=!!T.groupReason&&!T.full;we?re(`source.pushdown.group-unsupported.${O}.${T.groupReason}`,`pushdown:group-unsupported: the ${O} adapter was not asked to group this query because ${T.groupReason}, so the grid stays ungrouped rather than building group rows, counts and subtotals from a window of leaf rows. \`lastPlan().groupReason\` says the same.`):T.groupReason&&re(`source.pushdown.group.${O}.${T.groupReason}`,`the ${O} adapter was not asked to group this query because ${T.groupReason}. The engine returns rows and the grouping is the grid's to do, which needs every matching row in the browser — correct where the grid holds them, and wrong-looking where it holds a window. \`lastPlan().unpushed\` names it.`);const be=fe=>we?{...fe,[Ce]:!0}:fe;if(!T.needsAll){const fe=V.probe||await g.execute(T.pushed,F),Ee=fe.rows||[];return nt(fe.pendingTotal)&&fe.total===void 0?be({rows:Ee,pendingTotal:Qt(fe.pendingTotal,m(T.pushed))}):($e=null,!M.total&&fe.total===void 0?be({rows:Ee}):be({rows:Ee,total:fe.total??Ee.length}))}T.unpushed.length&&re(`source.pushdown.residual.${O}.${T.unpushed.join(".")}`,`the ${O} adapter cannot push ${T.unpushed.join(" or ")}, so every matching row is fetched and the rest is applied in the browser. Correct, and slower than it needs to be: widening the adapter is the fix.`);const He=m(T.pushed);if(!ie||ie.key!==He){const fe=await Fe(await g.execute(T.pushed,F));$e=null;const Ee=fe.rows||[];if(T.full){const Me=typeof fe.total=="number"?Math.max(fe.total,Ee.length):Ee.length;if(Me>l.maxRows)throw new Error(`[lattice] fullDataset refused: the ${O} adapter's matching set is ${Me.toLocaleString()} rows, past the configured maxRows of ${l.maxRows.toLocaleString()}. The whole set cannot be held client-side, so it is refused rather than truncated — a fraction shown as the whole would make every total and statistic silently wrong. Narrow the filter or raise maxRows.`);const je=Ee.length*S(Ee[0]);if(je>l.maxBytesEstimate)throw new Error(`[lattice] fullDataset refused: the ${O} adapter's matching set is an estimated ${Math.round(je/(1024*1024)).toLocaleString()} MB across ${Ee.length.toLocaleString()} rows, past the configured maxBytesEstimate of ${Math.round(l.maxBytesEstimate/(1024*1024)).toLocaleString()} MB. The whole set cannot be held client-side, so it is refused rather than truncated. Narrow the filter or raise maxBytesEstimate.`)}if(typeof fe.total=="number"&&Ee.length<fe.total){const Me=!!(T.residual.filters||T.residual.quick||T.residual.sort&&T.residual.sort.length);if(Me&&!u)throw new Error(`[lattice] the ${O} adapter returned ${Ee.length} of ${fe.total} matching rows when asked for the whole result, and the query has residual ${T.unpushed.join(" and ")||"work"} to finish in the browser. Filtering or sorting a fraction of the result would return wrong rows, so the result is refused. Fix the adapter to follow the engine's own paging before returning, hold the data in memory, or set \`allowPartialResults: true\` on the source config to accept this knowingly.`);Me?re(`source.pushdown.partial.residual.${O}`,`the ${O} adapter returned ${Ee.length} of ${fe.total} matching rows when asked for the whole result, and residual work will run over that fraction. allowPartialResults is set, so the result is used as-is — it may be wrong. The adapter must follow the engine's own paging to be correct.`):re(`source.pushdown.partial.${O}`,`the ${O} adapter returned ${Ee.length} of ${fe.total} matching rows when asked for the whole result. The adapter must follow the engine's own paging before returning.`)}ie={key:He,rows:Ee,total:typeof fe.total=="number"?fe.total:null}}let Re=T;if(T.residual.where){const fe=ie.total??ie.rows.length;if(fe>=b){le(T.residual.where.names,O,fe,b);const{where:Ee,...Me}=V.request;Re=xe(Me,M,l.enabled),he=Re}}const ce=ie.total!==null&&ie.rows.length>=ie.total,Ue=c(ie.rows,{...Re.residual,whole:ce},a.compute||{}),tt=F.range?F.range.start:0,De=F.range?F.range.end:Ue.length;return be({rows:Ue.slice(tt,De),total:Ue.length})},kt=async(F,L)=>{const Z=Xe();Z&&await Z;const V=Y();V&&await V;const T=xe(F,M,l.enabled);he=T;const me=x(L,ve),we=Array.isArray(F.groupBy)?F.groupBy:[],be=we.length>0,He=!T.residual.filters&&!T.residual.quick,Re=!be||_(we,M.buckets);let ce=me.engine,Ue=me.client;if(M.aggregates&&ce.length){const Ee=M.aggregates instanceof Set?M.aggregates:new Set(pe(M.aggregates)),Me=ce.filter(je=>!Ee.has(je.fn));Me.length&&(ce=ce.filter(je=>Ee.has(je.fn)),Ue=[...Me.map(je=>({...je,reason:`the ${O} adapter does not compute "${je.fn}"`})),...Ue])}const tt=Ee=>{Ue=[...ce.map(Me=>({...Me,reason:Ee})),...Ue],ce=[]};ce.length&&!He?tt(T.residual.quick&&!T.residual.filters?"a quick search the adapter cannot push forces all-client (no mixed provenance)":"residual filter forces all-client (no mixed provenance)"):ce.length&&!Re&&tt("a grouping key the engine cannot form forces all-client (no mixed provenance)");let De={},fe;return ce.length&&(se(be?g.executeGroupedAggregates:g.executeAggregates)?be?fe=await g.executeGroupedAggregates(T.pushed,we,ce)||[]:De=await g.executeAggregates(T.pushed,ce)||{}:(re(`source.pushdown.aggregates.${O}${be?".grouped":""}`,`the ${O} adapter cannot compute ${be?"grouped ":""}aggregates, so every requested statistic is computed client-side. Correct, and slower than it needs to be.`),tt(`adapter cannot compute ${be?"grouped ":""}aggregates`))),ge={engine:ce,client:Ue,...be?{groupBy:we}:{}},{values:De,engine:ce,client:Ue,...fe!==void 0?{groups:fe}:{}}},Pt=async F=>{_e++;try{return await Ye(F)}finally{if(_e--,_e===0&&Je.length){const L=Je;Je=[];for(const Z of L)Z()}}},lt=N(a.edit),ft=a.edit&&typeof a.edit=="object"&&se(a.edit.commit);let mt=a.edit;if(lt&&!ft)if(M.mutate&&M.mutate.update){const F=L=>{if(!M.mutate||!M.mutate.update)throw new Error(`[lattice] the ${O} adapter cannot update rows (mutate.update is not declared), so this edit cannot be persisted. The cell is reverted rather than left looking saved.`);const Z={kind:"update",key:String(L.key),patch:{[L.colId]:L.value}};return g.mutate(Z,L.request||{})};mt={...a.edit===!0?{}:a.edit,commit:F}}else re(`source.pushdown.readonly.${O}`,`edit is enabled but the ${O} adapter declares mutate: ${M.mutate?"without update":"false"} (read-only by declaration), so no commit is synthesised and the grid stays read-only. Declare \`mutate: { update: true }\` on the adapter to allow cell edits.`);const Ft=lt&&M.mutate&&(M.mutate.append||M.mutate.delete)?{append:M.mutate.append===!0,remove:M.mutate.delete===!0,returning:M.mutate.returning,mutate:(F,L)=>g.mutate(F,L||{})}:null,Ve=async F=>{const L=Y();L&&await L;const{range:Z,signal:V,export:T,...me}=F||{},we={...me,groupBy:[],groupPath:[],groupValues:[],pivotBy:[],pivotMode:!1,totals:[]};return{plan:xe(we,M,l.enabled),signal:V}};async function*Se(F,L={}){const{plan:Z,signal:V}=await Ve(F),T=Math.max(1,Math.floor(Number(L.pageSize))||5e3),me={signal:V,stream:!0};if(!Z.needsAll)for(let He=0;;He+=T){X(me);const Re=await g.execute({...Z.pushed,range:{start:He,end:He+T}},me);Re&&nt(Re.pendingTotal)&&Re.pendingTotal.then(null,()=>{});const ce=Re&&Re.rows||[];if(ce.length&&(yield ce),ce.length<T)return}X(me);const we=await Fe(await g.execute({...Z.pushed,range:void 0},me)),be=c(we&&we.rows||[],{...Z.residual,whole:!0},a.compute||{});for(let He=0;He<be.length;He+=T)yield be.slice(He,He+T)}return{...a,edit:mt,rowMutate:Ft,mode:"remote",fetch:Pt,foregroundIdle:Xe,aggregate:kt,countMatching:async F=>{const{plan:L,signal:Z}=await Ve(F);if(!L.needsAll&&M.total){X({signal:Z});const T=await Fe(await g.execute({...L.pushed,range:{start:0,end:0}},{signal:Z}));if(T&&typeof T.total=="number")return T.total}let V=0;for await(const T of Se(F))V+=T.length;return V},streamMatching:Se,lastPlan:()=>he?{...he,...ge?{aggregates:ge}:{},...$e?{total:{deferred:!0,state:$e.state,value:$e.value}}:{}}:null,fullFrame:it,counts:()=>({match:qe,total:ze??null,pending:!!$e&&$e.state==="pending"}),grandTotals:()=>Te}}}),pt("packages/core/src/model/rowkey.js",function(y,Oe){"use strict";Object.defineProperty(y,"KEY_DEPENDENT_FEATURES",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(y,"compositeKey",{enumerable:!0,get:function(){return le}}),Object.defineProperty(y,"createRowKey",{enumerable:!0,get:function(){return C}}),Object.defineProperty(y,"warnMissingKeys",{enumerable:!0,get:function(){return te}}),Object.defineProperty(y,"groupPathKey",{enumerable:!0,get:function(){return z}}),Object.defineProperty(y,"splitPathKey",{enumerable:!0,get:function(){return ne}});const de=Oe("packages/core/src/internal/util.js"),A=de.warnOnce,se=de.pathGetter,pe=de.isFunction,re=de.isBlank,ke=["changes (rows.apply / rows.queue)","streaming dedupe","selection persistence","remote reload","cell comments"],D="";function J($){if($===null)return"\0n";if($===void 0)return"\0u";const X=typeof $;if(X==="string")return $;if(X==="number"||X==="bigint"||X==="boolean")return String($);if($ instanceof Date)return`\0d${$.getTime()}`;try{return`\0o${JSON.stringify($)}`}catch{return"\0o?"}}function le($){if($.length===1)return J($[0]);let X="";for(let P=0;P<$.length;P++)P&&(X+=D),X+=J($[P]);return X}function C($,X={}){const P=X.warn!==!1;if(pe($)){const R=$;return{stable:!0,fields:[],disabled:[],key(E,N){try{const H=R(E);return Array.isArray(H)?le(H):J(H)}catch(H){return A("rowKey.throw","rowKey function threw; falling back to index identity for the affected rows.",H),`#${N??-1}`}},keyEmpty(E){try{const N=R(E);return Array.isArray(N)?N.length===0||N.some(re):re(N)}catch{return!1}},missingFields(){return[]}}}if(Array.isArray($)&&$.length>0){const R=$.filter(H=>typeof H=="string"),E=R.map(H=>se(H)),N=E.length;return{stable:!0,fields:R,disabled:[],key(H){const q=new Array(N);for(let K=0;K<N;K++)q[K]=E[K](H);return le(q)},keyEmpty(H){for(let q=0;q<N;q++)if(re(E[q](H)))return!0;return!1},missingFields(H){const q=[];for(let K=0;K<N;K++)re(E[K](H))&&q.push(R[K]);return q}}}if(typeof $=="string"&&$.length>0){const R=se($);return{stable:!0,fields:[$],disabled:[],key(E){return J(R(E))},keyEmpty(E){return re(R(E))},missingFields(E){return re(R(E))?[$]:[]}}}return P&&A("rowKey.missing",`no rowKey configured, so rows are identified by object identity. This disables: ${ke.join(", ")}. Set rowKey to a field name, an array of field names, or a function.`),{stable:!1,fields:[],disabled:ke.slice(),key(R,E){if(R===null||typeof R!="object")return`#${E??0}:${String(R)}`;let N=x.get(R);return N===void 0&&(N=`#${_++}`,x.set(R,N)),N}}}const x=new WeakMap;let _=0;function te($,X){if(!$||$.stable===!1||!pe($.keyEmpty)||!Array.isArray(X)||X.length===0)return;let P=0,R=null,E;for(let K=0;K<X.length;K++){const ae=X[K];$.keyEmpty(ae)&&(P++,R===null&&(R=pe($.missingFields)?$.missingFields(ae):[],E=ae))}if(P===0)return;const N=$.fields.length?$.fields.join(","):"(function)",H=R&&R.length?R.join(", "):$.fields.length?$.fields.join(", "):"the rowKey function",q=E!==null&&typeof E=="object"?Object.keys(E).join(", ")||"(no fields)":String(E);A(`rowKey.emptyValue:${N}`,`rowKey ${H} is missing on ${P} of ${X.length} rows; the first such row has: ${q}. Rows without a key value collapse onto one key, so selection, edits and rows.apply updates land on whichever row now shares it. Set rowKey to a field present on every row, or fix the source data.`)}function z($){return le($)}function ne($){return $.split(D)}}),pt("packages/modules/data-router/devtools.js",function(y,Oe){"use strict";Object.defineProperty(y,"mountRouterDevtools",{enumerable:!0,get:function(){return J}}),Object.defineProperty(y,"default",{enumerable:!0,get:function(){return le}});const A=Oe("packages/core/src/internal/util.js").warnOnce,se="lat-router-devtools";function pe(C,x,_){const te=C.createElement(x);return te.textContent=_==null?"—":String(_),te}function re(C){return Number.isFinite(C)?`${Math.round(C*10)/10}/s`:"—"}function ke(C,x,_,te){const z=C.createElement("section");z.className=`${se}-section`;const ne=C.createElement("h4");ne.textContent=x,z.appendChild(ne);const $=C.createElement("table"),X=C.createElement("tr");for(const P of _)X.appendChild(pe(C,"th",P));$.appendChild(X);for(const P of te){const R=C.createElement("tr");for(const E of P)R.appendChild(pe(C,"td",E));$.appendChild(R)}return z.appendChild($),z}function D(C,x,_){x.textContent="";const te=ke(C,"Router",["metric","value"],[["throughput",re(_.throughput)],["unrouted",_.unrouted],["dropped (duplicate)",_.dropped],["buffer depth",_.buffered],["lag (deltas behind)",_.lag]]);x.appendChild(te),x.appendChild(ke(C,"Routes",["#","label","kind","rows","shown","rows/sec"],_.routes.map(z=>[z.index,z.label,z.kind,z.rows,z.shown,re(z.throughput)]))),_.sources.length&&x.appendChild(ke(C,"Sources",["id","rows","ingested","rows/sec"],_.sources.map(z=>[z.id,z.rows,z.ingested,re(z.throughput)])))}function J(C,x,_={}){const te=x&&x.ownerDocument||(typeof document<"u"?document:null);if(!C||typeof C.metrics!="function"||typeof C.on!="function"||!x||!te)return A("data-router:devtools-target","router.mountDevtools(el) needs a router with metrics()/on() and a DOM element to render into; the panel was not mounted."),{destroy(){},refresh(){}};const z=te.createElement("div");z.className=se,x.appendChild(z);const ne=()=>D(te,z,C.metrics());ne();const $=C.on("metrics",()=>ne());return{refresh:ne,destroy(){$(),z.parentNode&&z.parentNode.removeChild(z)}}}const le=J}),pt("packages/core/src/format/date.js",function(y,Oe){"use strict";Object.defineProperty(y,"scanPattern",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"toDate",{enumerable:!0,get:function(){return D}}),Object.defineProperty(y,"compilePattern",{enumerable:!0,get:function(){return C}}),Object.defineProperty(y,"compileDate",{enumerable:!0,get:function(){return _}}),Object.defineProperty(y,"toIsoDate",{enumerable:!0,get:function(){return te}}),Object.defineProperty(y,"toIsoDateTime",{enumerable:!0,get:function(){return z}}),Object.defineProperty(y,"compareIso",{enumerable:!0,get:function(){return X}});const de=Oe("packages/core/src/internal/util.js"),A=de.isNil,se=de.warnOnce,pe=["yyyy","yy","MMMM","MMM","MM","M","dd","d","EEEE","EEE","HH","H","hh","h","mm","m","ss","s","SSS","a"];function re(P){const R=[];let E=0,N="";const H=()=>{N&&(R.push({token:null,text:N}),N="")};for(;E<P.length;){const q=P[E];if(q==="'"){if(P[E+1]==="'"){N+="'",E+=2;continue}const ae=P.indexOf("'",E+1);if(ae===-1){N+=P.slice(E+1),E=P.length;continue}N+=P.slice(E+1,ae),E=ae+1;continue}const K=pe.find(ae=>P.startsWith(ae,E));if(K){H(),R.push({token:K,text:K}),E+=K.length;continue}/[A-Za-z]/.test(q)&&se(`date.pattern.token:${q}`,`the date pattern "${P}" contains '${q}', which is not a supported token, so it is rendered as text. Quote it as a literal to silence this. Supported: ${pe.join(" ")}.`),N+=q,E+=1}return H(),R}const ke=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?)?$/;function D(P){if(A(P)||P==="")return null;if(P instanceof Date)return Number.isNaN(P.getTime())?null:P;if(typeof P=="number")return Number.isNaN(P)?null:new Date(P);if(typeof P=="string"){const R=ke.exec(P.trim());if(R){const[,N,H,q,K="0",ae="0",We="0"]=R;return new Date(+N,+H-1,+q,+K,+ae,+We)}const E=new Date(P);return Number.isNaN(E.getTime())?null:E}return null}function J(P,R){return String(P).padStart(R,"0")}function le(P){if(!P)return N=>({year:N.getFullYear(),month:N.getMonth()+1,day:N.getDate(),hour:N.getHours(),minute:N.getMinutes(),second:N.getSeconds(),ms:N.getMilliseconds(),weekday:N.getDay()});const R=new Intl.DateTimeFormat("en-US",{timeZone:P,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,weekday:"short"}),E={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};return N=>{const H={year:0,month:1,day:1,hour:0,minute:0,second:0,ms:N.getMilliseconds(),weekday:0};for(const q of R.formatToParts(N))switch(q.type){case"year":H.year=Number(q.value);break;case"month":H.month=Number(q.value);break;case"day":H.day=Number(q.value);break;case"hour":H.hour=Number(q.value)%24;break;case"minute":H.minute=Number(q.value);break;case"second":H.second=Number(q.value);break;case"weekday":H.weekday=E[q.value]??0;break;default:break}return H}}function C(P,R,E){const N=re(P),H=le(E),q=new Set(N.filter(Ae=>Ae.token).map(Ae=>Ae.token)),K=q.has("MMM")?new Intl.DateTimeFormat(R,{month:"short",timeZone:E}):null,ae=q.has("MMMM")?new Intl.DateTimeFormat(R,{month:"long",timeZone:E}):null,We=q.has("EEE")?new Intl.DateTimeFormat(R,{weekday:"short",timeZone:E}):null,Le=q.has("EEEE")?new Intl.DateTimeFormat(R,{weekday:"long",timeZone:E}):null;return Ae=>{const ue=H(Ae);let oe="";for(const Ce of N){if(!Ce.token){oe+=Ce.text;continue}switch(Ce.token){case"yyyy":oe+=J(ue.year,4);break;case"yy":oe+=J(ue.year%100,2);break;case"MMMM":oe+=ae.format(Ae);break;case"MMM":oe+=K.format(Ae);break;case"MM":oe+=J(ue.month,2);break;case"M":oe+=String(ue.month);break;case"dd":oe+=J(ue.day,2);break;case"d":oe+=String(ue.day);break;case"EEEE":oe+=Le.format(Ae);break;case"EEE":oe+=We.format(Ae);break;case"HH":oe+=J(ue.hour,2);break;case"H":oe+=String(ue.hour);break;case"hh":oe+=J(ue.hour%12===0?12:ue.hour%12,2);break;case"h":oe+=String(ue.hour%12===0?12:ue.hour%12);break;case"mm":oe+=J(ue.minute,2);break;case"m":oe+=String(ue.minute);break;case"ss":oe+=J(ue.second,2);break;case"s":oe+=String(ue.second);break;case"SSS":oe+=J(ue.ms,3);break;case"a":oe+=ue.hour<12?"AM":"PM";break;default:oe+=Ce.text;break}}return oe}}const x=[["year",365*24*36e5],["month",720*36e5],["week",168*36e5],["day",24*36e5],["hour",36e5],["minute",6e4],["second",1e3]];function _(P,R){const E=P||{},N=E.locale||R||void 0,H=E.nullDisplay??"",q=E.timeZone;let K;if(E.pattern)K=C(E.pattern,N,q);else if(E.dateStyle||E.timeStyle){const ue={timeZone:q};E.dateStyle&&(ue.dateStyle=E.dateStyle),E.timeStyle&&(ue.timeStyle=E.timeStyle);const oe=new Intl.DateTimeFormat(N,ue);K=Ce=>oe.format(Ce)}else{const ue=new Intl.DateTimeFormat(N,{dateStyle:"medium",timeZone:q});K=oe=>ue.format(oe)}const ae=E.relative?new Intl.RelativeTimeFormat(N,{numeric:"auto"}):null,Le=(typeof E.relative=="object"&&E.relative?E.relative.threshold??7:7)*24*36e5,Ae=(ue,oe)=>{const Ce=D(ue);if(!Ce)return H;if(ae){const ht=oe&&typeof oe.now=="number"?oe.now:Date.now(),xe=Ce.getTime()-ht;if(Math.abs(xe)<Le){for(const[h,p]of x)if(Math.abs(xe)>=p||h==="second")return ae.format(Math.round(xe/p),h)}}return K(Ce)};return Ae.spec=E,Ae}function te(P){if(A(P)||P==="")return null;if(typeof P=="string"){const N=/^(\d{4}-\d{2}-\d{2})/.exec(P.trim());if(N)return N[1];const H=D(P);return H?te(H):null}const R=D(P);if(!R)return null;const E=N=>String(N).padStart(2,"0");return`${R.getFullYear()}-${E(R.getMonth()+1)}-${E(R.getDate())}`}function z(P,R){if(A(P)||P==="")return null;if(typeof P=="string"){const N=P.trim();if(ne.test(N)){const K=D(N);return K?$(K,R):null}const H=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?/.exec(N);if(H){const[,K,ae,We,Le]=H;return`${K}T${ae}:${We}${Le&&Le!=="00"?`:${Le}`:""}`}if(/^\d{4}-\d{2}-\d{2}$/.test(N))return`${N}T00:00`;const q=D(N);return q?z(q):null}const E=D(P);return E?$(E,R):null}const ne=/(?:Z|[+-]\d{2}:?\d{2})$/i;function $(P,R){const E=K=>String(K).padStart(2,"0");if(R)try{const K=new Intl.DateTimeFormat("en-CA",{timeZone:R,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(P).reduce((Le,Ae)=>(Ae.type!=="literal"&&(Le[Ae.type]=Ae.value),Le),{}),ae=K.hour==="24"?"00":K.hour,We=Number(K.second);return`${K.year}-${K.month}-${K.day}T${ae}:${K.minute}`+(We?`:${K.second}`:"")}catch{}const N=`${P.getFullYear()}-${E(P.getMonth()+1)}-${E(P.getDate())}`,H=P.getSeconds(),q=`${E(P.getHours())}:${E(P.getMinutes())}${H?`:${E(H)}`:""}`;return`${N}T${q}`}function X(P,R){const E=A(P)||P===""?null:String(P),N=A(R)||R===""?null:String(R);return E===null?N===null?0:1:N===null||E<N?-1:E>N?1:0}}),pt("packages/core/src/format/boolean.js",function(y,Oe){"use strict";Object.defineProperty(y,"toTriState",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"compileBoolean",{enumerable:!0,get:function(){return ke}});const A=Oe("packages/core/src/internal/util.js").isNil,se={true:"☑",false:"☐",null:""},pe={true:"◉",false:"◯",null:""};function re(D){if(A(D)||D==="")return null;if(typeof D=="boolean")return D;if(typeof D=="number")return D!==0;const J=String(D).trim().toLowerCase();return J==="true"||J==="yes"||J==="y"||J==="1"?!0:J==="false"||J==="no"||J==="n"||J==="0"?!1:null}function ke(D,J){const le=D||{},C=le.display||"text",x=le.trueLabel??"Yes",_=le.falseLabel??"No",te=le.nullLabel??"";let z=x,ne=_;const $=te;C==="checkbox"?(z=se.true,ne=se.false):C==="switch"?(z=pe.true,ne=pe.false):C==="icon"&&(z=le.trueIcon??x,ne=le.falseIcon??_);const X=P=>{const R=re(P);return R===null?$:R?z:ne};return X.display=C,X.labels={true:x,false:_,null:te},X.locale=J,X.spec=le,X}}),pt("packages/modules/data-router/index.js",function(y,Oe){"use strict";Object.defineProperty(y,"createDataRouter",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(y,"default",{enumerable:!0,get:function(){return xe}});const A=Oe("packages/core/src/internal/util.js").warnOnce,se=Oe("packages/core/src/source/pushdown.js"),pe=se.planQuery,re=se.capabilitiesOf,D=Oe("packages/core/src/model/rowkey.js").compositeKey,le=Oe("packages/modules/data-router/devtools.js").mountRouterDevtools,C=Oe("packages/core/src/format/date.js"),x=C.toIsoDate,_=C.scanPattern,z=Oe("packages/core/src/format/boolean.js").toTriState;function ne(h,p){return typeof h=="function"?h:typeof h=="string"?c=>c[h]:p}function $(h,p){if(!h||typeof h!="object"||typeof p!="string")return;if(!p.includes("."))return h[p];let c=h;for(const m of p.split(".")){if(!c||typeof c!="object")return;c=c[m]}return c}function X(h,p){const c=p.split(".");if(c.length===1){delete h[p];return}let m=h;for(let S=0;S<c.length-1;S+=1)if(m=m[c[S]],!m||typeof m!="object")return;delete m[c[c.length-1]]}function P(h){return Array.isArray(h)?"array":h===null?"null":typeof h}function R(h,p){if(h===void 0||typeof h=="string"&&h.length>0)return h;if(typeof h=="function")return c=>{const m=h(c);if(typeof m=="string"||typeof m=="number"&&Number.isFinite(m))return m;throw new Error(`lattice-data-router: rowKey function must return a string or number; got ${P(m)}.`)};throw new Error(`lattice-data-router: rowKey must be a property name or a function; composite keys are not supported on ${p}.`)}function E(h){if(typeof h=="function")return h;if(h&&typeof h=="object"&&typeof h.key=="string"){const p=h.dir==="desc"?-1:1,{key:c}=h;return(m,S)=>{const W=m?m[c]:void 0,U=S?S[c]:void 0;return W<U?-1*p:W>U?1*p:0}}return null}function N(h){if(!h||typeof h!="object")return null;let p=0;Number.isFinite(h.minInterval)&&h.minInterval>0?p=Number(h.minInterval):Number.isFinite(h.maxHz)&&h.maxHz>0&&(p=1e3/Number(h.maxHz));const c=Number.isFinite(h.sample)&&h.sample>1?Math.floor(Number(h.sample)):1,m=Number.isFinite(h.maxLag)&&h.maxLag>=0?Math.floor(Number(h.maxLag)):null;return p===0&&c===1&&m===null?null:{minInterval:p,sample:c,maxLag:m}}let H=0;function q(){return H+=1,`r${H}`}function K(h){const c=(Array.isArray(h)?h:[h]).map(m=>({name:typeof m=="string"?m:null,get:ne(m,()=>{})}));return m=>{const S={},W=[];for(const U of c){const Be=U.get(m);W.push(Be),U.name&&(S[U.name]=Be)}return{key:D(W),fields:S}}}function ae(h,p){if(typeof h=="function")return h(p);if(h&&typeof h=="object"){const{op:c,field:m}=h;if(c==="count")return p.length;const S=m!=null?p.map(W=>Number(W[m])).filter(W=>Number.isFinite(W)):[];if(c==="sum")return S.reduce((W,U)=>W+U,0);if(c==="avg")return S.length?S.reduce((W,U)=>W+U,0)/S.length:0;if(c==="min")return S.length?Math.min(...S):void 0;if(c==="max")return S.length?Math.max(...S):void 0}}function We(h){return h&&typeof h=="object"&&typeof h.from=="string"&&typeof h.to=="string"?{from:h.to,to:h.from}:(A("data-router:mutual-fn","relate({ mutual: true }) with a function relation cannot be inverted; the same predicate is applied in both directions. Use a { from, to } key map for a mutual edge."),h)}function Le(h,p){return h?p?{op:"and",conditions:[h,p]}:h:p||null}const Ae=Object.freeze(["eq","ne","lt","lte","gt","gte","between","notBetween","in","notIn","contains","notContains","startsWith","endsWith","blank","notBlank"]);function ue(h,p){const c=p?p[h.col]:void 0,m=h.value,S=W=>h.caseSensitive?String(W):String(W).toLowerCase();switch(h.op){case"eq":return c===m;case"ne":return c!==m;case"lt":return c<m;case"lte":return c<=m;case"gt":return c>m;case"gte":return c>=m;case"between":return Array.isArray(m)&&c>=m[0]&&c<=m[1];case"notBetween":return!(Array.isArray(m)&&c>=m[0]&&c<=m[1]);case"in":return Array.isArray(m)&&m.includes(c);case"notIn":return!(Array.isArray(m)&&m.includes(c));case"contains":return c!=null&&S(c).includes(S(m));case"notContains":return c==null||!S(c).includes(S(m));case"startsWith":return c!=null&&S(c).startsWith(S(m));case"endsWith":return c!=null&&S(c).endsWith(S(m));case"blank":return c==null||c==="";case"notBlank":return!(c==null||c==="");default:throw new Error(`[lattice] query() cannot evaluate the residual filter operator "${String(h.op)}" on column "${String(h.col)}" client-side, so the query is refused rather than returning rows the filter excludes. Push it down to an adapter that implements it, or use an operator this router evaluates: ${Ae.join(", ")}.`)}}function oe(h,p){return h?Array.isArray(h.conditions)?h.op==="or"?h.conditions.some(c=>oe(c,p)):h.op==="not"?!h.conditions.every(c=>oe(c,p)):h.conditions.every(c=>oe(c,p)):ue(h,p):!0}function Ce(h={}){const p=ne(h.key,()=>{}),c=ne(R(h.rowKey,"routes"),e=>e.rowKey),m=typeof h.key=="string"?h.key:null,S=!!h.overlap,W=typeof h.onUnrouted=="function"?h.onUnrouted:null,U=Number.isFinite(h.selectionDebounce)?Number(h.selectionDebounce):16,Be=typeof h.onWrite=="function"?h.onWrite:null,nt=typeof h.onConflict=="function"?h.onConflict:null,Fe=h.seq!=null?ne(h.seq,()=>{}):null,Ze=Fe?h.dedupe!==!1:!1,a=c;let g=null;typeof h.batch=="number"?g=h.batch:h.batch&&Number.isFinite(h.batch.intervalMs)&&(g=Number(h.batch.intervalMs));const M=g!==null||!!h.coalesce,G=new Map;let O,Q=0;const Y=[];let l=null;const u=h.time!=null?ne(h.time,()=>{}):null,b=typeof h.now=="function"?h.now:Date.now,I=1e4;let ve=!1,ie=null,he=null,ge="time",qe=new Map;const Te=[];let ze=0,$e,ut,ct=!1,it=null,Et=[],jt=0,st=0,Yt="time",wt=!1,rt=null,gt=null;const At=e=>{if(e&&Number.isFinite(e.seq))return e.seq;if(Fe&&e&&e.row){const t=Fe(e.row);return Number.isFinite(t)?t:void 0}},Qt=e=>{if(e&&Number.isFinite(e.t))return e.t;if(u&&e&&e.row){const t=u(e.row);if(Number.isFinite(t))return t}return b()},_e=[];let Je=null;const Xe=[],Ye=[],kt=new Map,Pt=new Set;let lt=null,ft=0;const mt=new Map,Ft=new Set,Ve=typeof h.rowKey=="string"?h.rowKey:"rowKey",Se=new Map;let Zt=0;const F=new Set,L=[],Z=new Map,V=(e,t)=>{Z.set(e,(Z.get(e)||0)+t)};let T=0;const me=new Map,we=new Map;let be=null;const He=Number.isFinite(h.metricsInterval)?Number(h.metricsInterval):1e3;let Re=0,ce=null,Ue="lattice-router",tt=250,De=null,fe=null,Ee=!1,Me=!1,je=null,vt=!1,$t=null;const at=[],Ne=()=>Je?[..._e,Je]:_e,ot=e=>Ne().find(t=>t.grid===e)||null,Dt=e=>{const t=[];for(const n of _e)if(n.match(e)&&(t.push(n),!S))break;return t.length?t:Je?[Je]:[]},ee=e=>e.hasPartValue?e.partValue:e.label!=null?e.label:e.grid,Ge=e=>{for(const t of Ne())if(t.grid===e)return t;for(const t of Ne())if(t.hasPartValue&&t.partValue===e||t.label!=null&&t.label===e)return t;return null},et=(e,t)=>{if(t.add.length||t.update.length||t.remove.length){const n=e.sink(t);Xt(e,n)}return{added:t.add.length,updated:t.update.length,removed:t.remove.length}},Xt=(e,t)=>{const n=t?.rejected;if(!Array.isArray(n)||!n.length)return;const r=n.filter(i=>i&&i.operation==="remove");if(!r.length)return;const o=e.label||`route ${e.routeId}`;A(`data-router:remove-rejected:${e.routeId}`,`route "${o}" asked its target to remove ${r.length} row(s) the target does not have (for example ${JSON.stringify(String(r[0].id))}). The rows are still on screen. This is a key mismatch: the key the route derives for a row is not the key the grid derives for it. Check that the route's \`rowKey\` names the same value as the grid's.`)},Vn=(e,t)=>{for(const n of Xe)if(n.to===e.grid&&n.predicate&&!n.predicate(t))return!1;if(e.graphPreds){for(const n of e.graphPreds)if(!n(t))return!1}return!0},yt=e=>{const t=[];for(const s of e.partition.values())e.filter&&!e.filter(s)||Vn(e,s)&&t.push(s);if(F.size){const s=new Map;for(const w of t)for(const j of Object.keys(w))F.has(j)&&w[j]!==void 0&&!s.has(j)&&s.set(j,!0);const f=e.spreadFields||(e.spreadFields=new Map),d=[],k=[];for(const w of s.keys())f.has(w)||d.push(w);for(const w of f.keys())s.has(w)||k.push(w);d.length||k.length?(e.spreadFields=s,Wn("fields:changed",{route:ee(e),added:d,removed:k})):e.spreadFields=s}let n;if(e.rollup){const s=new Map;for(const d of t){const{key:k,fields:w}=e.rollup.group(d);let j=s.get(k);j||(j={key:k,fields:w,rows:[]},s.set(k,j)),j.rows.push(d)}let f=[];for(const d of s.values()){const k={...d.fields};for(const[w,j]of e.rollup.specs)k[w]=ae(j,d.rows);f.push({gkey:d.key,row:k})}e.sort&&f.sort((d,k)=>e.sort(d.row,k.row)),e.transform&&(f=f.map(d=>({gkey:d.gkey,row:e.transform(d.row)}))),n=new Map(f.map(d=>[d.gkey,d.row]))}else{let s=t;e.sort&&(s=s.slice().sort(e.sort)),n=new Map;for(const f of s)n.set(D([e.keyOf(f)]),e.transform?e.transform(f):f)}const r=[],o=[],i=[];for(const[s,f]of n)e.keys.has(s)?ht(e.keys.get(s),f)||o.push(f):r.push(f);for(const s of e.keys.keys())n.has(s)||i.push(s);return e.keys=n,et(e,{add:r,update:o,remove:i})},Bt=e=>{e.bpTimer&&(clearTimeout(e.bpTimer),e.bpTimer=null),yt(e),e.bpPending=0,e.bpLastFlush=b()},Gn=(e,t)=>{if(e.bpTimer)return;const n=e.bp.minInterval>0?Math.max(e.bp.minInterval-(t-e.bpLastFlush),0):0;e.bpTimer=setTimeout(()=>{e.bpTimer=null,Bt(e)},n),e.bpTimer&&typeof e.bpTimer.unref=="function"&&e.bpTimer.unref()},_n=(e,t)=>{if(!e.bp){yt(e);return}e.bpPending+=t,e.bpCoalesced+=t;const n=e.bp;if(n.maxLag!=null&&e.bpPending<=n.maxLag&&!e.bpTimer){Bt(e);return}const r=b(),o=r-e.bpLastFlush>=n.minInterval,i=e.bpPending>=n.sample;if(o&&i){Bt(e);return}Gn(e,r)},Jn=e=>{e.bpTimer&&(clearTimeout(e.bpTimer),e.bpTimer=null),e.bpPending=0,e.bpLastFlush=b()},en=(e,t)=>{if(typeof e=="function"){const n=e(t);return typeof n=="function"?n:null}if(e&&typeof e=="object"){const n=e.from,r=e.to,o=new Set(t.map(i=>i&&i[n]));return i=>o.has(i&&i[r])}return null},tn=e=>{const t=ot(e),n=e&&e.selection,r=n&&typeof n.keys=="function"?n.keys():[];return!r.length||!t?[]:r.map(o=>t.partition.get(String(o))).filter(o=>o!==void 0)},Yn=e=>{const t=e&&e.selection;if(!t||typeof t.predicate!="function")return null;const n=t.predicate();if(!n||n.all!==!0)return null;const r=typeof t.count=="function"?t.count():Promise.resolve(null);return{predicate:n,count:r}},Mt=e=>{const t=Yn(e.from);if(t){if(typeof e.relation=="function"&&e.relation.length>=2){const r=e.relation(tn(e.from),t);e.predicate=typeof r=="function"?r:null}else A("data-router:link-predicate-unsupported","link()/relate() source grid has every row matching a filter selected on a source that holds only the rows it has loaded. The relation does not declare it accepts a predicate selection — a function taking (selected, { predicate, count }) as its second parameter — so the link cannot build a target-row predicate from a truncated key list and imposes no constraint."),e.predicate=null;return}const n=tn(e.from);e.predicate=n.length?en(e.relation,n):null},Lt=()=>{const e=new Set;for(const t of Ye)e.add(t.from),e.add(t.to);return e},Ot=()=>{for(const i of Ne())i.graphPreds=null;if(!Ye.length)return;const e=Lt(),t=new Map;for(const i of e){const s=tn(i);s.length&&t.set(i,s)}const n=new Map(t);let r=!0,o=(e.size+1)*2;for(;r&&o-- >0;){r=!1;for(const i of e){if(t.has(i))continue;const s=Ye.filter(j=>j.to===i&&n.has(j.from));if(!s.length)continue;const f=ot(i);if(!f)continue;const d=s.map(j=>en(j.rel,n.get(j.from))).filter(Boolean),k=[];for(const j of f.partition.values())d.every(B=>B(j))&&k.push(j);const w=n.get(i);if(!w||w.length!==k.length)n.set(i,k),r=!0;else{const j=new Set(w);k.some(B=>!j.has(B))&&(n.set(i,k),r=!0)}}}for(const i of Ye){if(!n.has(i.from))continue;const s=en(i.rel,n.get(i.from));if(!s)continue;const f=ot(i.to);f&&(f.graphPreds||(f.graphPreds=[])).push(s)}},wn=e=>{const t=kt.get(e);if(t){t.count+=1;return}const n=e&&typeof e.on=="function"?e.on("selection:changed",()=>Qn(e)):()=>{};kt.set(e,{off:n,count:1})},nn=()=>{lt&&(clearTimeout(lt),lt=null);const e=Pt;if(!e.size)return;const t=new Set;for(const n of Xe)e.has(n.from)&&(Mt(n),t.add(n.to));if(Pt.clear(),Ye.length){Ot();for(const n of Lt())t.add(n)}for(const n of t){const r=ot(n);r&&yt(r)}},Qn=e=>{if(Pt.add(e),U<=0){nn();return}lt||(lt=setTimeout(nn,U))},kn=e=>{const t=kt.get(e);t&&(t.count-=1,t.count<=0&&(t.off(),kt.delete(e)))},Zn=e=>typeof e=="function"?t=>e(t):e&&e.rows&&typeof e.rows.apply=="function"?t=>e.rows.apply(t):(A("data-router:bad-target","attach/subscribe target has no rows.apply and is not a function; its slice goes nowhere. Pass a grid or a handler(change) function."),()=>{}),rn=(e,t,n)=>({grid:e,routeId:q(),sink:Zn(e),match:t,keyOf:ne(R(n.rowKey,"routes"),c),partition:new Map,keys:new Map,transform:typeof n.transform=="function"?n.transform:null,filter:typeof n.filter=="function"?n.filter:null,sort:E(n.sort),rollup:n.rollup&&n.rollup.groupBy!=null?{group:K(n.rollup.groupBy),specs:Object.entries(n.rollup.aggregate||{})}:null,where:n.where&&typeof n.where=="object"?n.where:null,graphPreds:null,onWrite:typeof n.onWrite=="function"?n.onWrite:null,onConflict:typeof n.onConflict=="function"?n.onConflict:null,writable:n.writable===!0,readonly:!!(n.rollup&&n.rollup.groupBy!=null||typeof n.transform=="function"),label:typeof n.label=="string"?n.label:null,metricRows:0,bp:N(n.backpressure),bpPending:0,bpTimer:null,bpLastFlush:-1/0,bpCoalesced:0}),vn=e=>{if(!S){for(const t of _e)if(t.hasPartValue&&t.partValue===e){A(`data-router:overlap:${String(e)}`,`Data Router: value ${JSON.stringify(e)} already routes to another viewer; with overlap:false only the first receives rows. Pass createDataRouter({ overlap: true }) to fan one value to several viewers.`);return}}},Sn=(e,t)=>`${String(e)}${String(t)}`,Xn=e=>{const t=e&&e.row;if(!t)return null;const n=t.data&&typeof t.data=="object"?t.data:t;return n?{...n}:null},Ht=(e,t)=>{const n=e.grid;if(!n||!n.edit||typeof n.edit.setCells!="function")return;const r=Sn(t.key,t.colId);Ft.add(r);try{n.edit.setCells([{key:t.key,colId:t.colId,value:t.before}],"cell")}finally{Ft.delete(r)}V("writeReverted",1)},En=e=>{e&&Qe.apply([{op:"upsert",row:e}])},jn=(e,t,n)=>{const r=n&&typeof n=="object"?n:null,o=r&&r.conflict!==void 0?r.conflict:null;if(o){const i=e.onConflict||nt;if(i)try{i(t,{serverRow:o})}catch{}V("writeConflicted",1),En(r&&r.row?r.row:t.row);return}if(n===!1||r&&r.ok===!1){V("writeRejected",1),Ht(e,t);return}V("writeAccepted",1),En(r&&r.row?r.row:t.row)},er=e=>{const t=String(e);for(const n of Se.values())if(n.live.has(t))return n.handle;return null},tr=(e,t)=>{if(!t||t.key===void 0||t.colId===void 0||Ft.has(Sn(t.key,t.colId)))return;const n=Xn(t),r={key:String(t.key),colId:String(t.colId),value:t.value,before:t.oldValue,row:n};if(V("writeRouted",1),e.readonly){A("data-router:readonly-write","an edit on a derived (rollup/transform) route is read-only and was reverted; a derived row cannot be inverted to a source row. Make the source route writable instead."),Ht(e,r);return}const o=e.onWrite||Be;if(!o){A("data-router:no-onwrite","a route attached with { writable: true } has no onWrite handler (per-route or router-global); the edit was left in place but not persisted. Pass onWrite to route the write.");return}let i;try{i=o(r,{route:e.grid,source:er(r.key)})}catch{Ht(e,r),V("writeRejected",1);return}i&&typeof i.then=="function"?i.then(s=>jn(e,r,s),()=>{Ht(e,r),V("writeRejected",1)}):jn(e,r,i)},nr=e=>{const t=e.grid;if(!t||typeof t.on!="function"||!t.edit||typeof t.edit.setCells!="function"){A("data-router:writable-target","attach({ writable: true }) needs a grid exposing grid.on and grid.edit.setCells; write-back is off for this route.");return}if(mt.has(t))return;const n=t.on("cell:changed",r=>tr(e,r));mt.set(t,typeof n=="function"?n:()=>{})},rr=e=>{const t=[];for(const n of e.partition.values())e.filter&&!e.filter(n)||t.push(n);return t},Kt=e=>{const t=rr(e);if(e.kind==="monitor"){let r;try{r=e.evaluate(t)}catch{r=void 0}e.handler(r,t);return}let n;try{n=e.condition(t)}catch{n=!1}if(n){if(!e.armed)return;e.debounceMs>0?(e.pending={signal:n,rows:t},e.timer||(e.timer=setTimeout(()=>{e.timer=null;const r=e.pending;e.pending=null,r&&(e.armed=!1,e.handler(r.signal,r.rows))},e.debounceMs))):(e.armed=!1,e.handler(n,t))}else e.armed=!0,e.timer&&(clearTimeout(e.timer),e.timer=null),e.pending=null},on=(e,t)=>{e.partition=new Map;for(const n of t)e.match(n)&&e.partition.set(String(e.keyOf(n)),n)},or=(e,t)=>{for(const n of t){const r=n&&n.row;if(!r)continue;const o=String(e.keyOf(r));if(n.op==="delete"){e.partition.delete(o);continue}e.match(r)?e.partition.set(o,r):e.partition.delete(o)}},Ct=()=>{const e=new Map;for(const t of Ne())for(const n of t.partition.values())e.set(String(a(n)),n);return[...e.values()]},Pn=()=>{qe=new Map;for(const e of Ne())for(const t of e.partition.values())qe.set(String(a(t)),t);Te.length=0,ze=0,$e=O,ut=void 0},On=()=>{const e=Te.shift();e&&(e.op==="del"?qe.delete(e.key):qe.set(e.key,e.row),$e=e.seq,ut=e.t)},ir=()=>{if(ie!=null)for(;Te.length>ie;)On();if(he!=null&&Te.length){const e=Te[Te.length-1].t;for(;Te.length>1&&e-Te[0].t>he;)On()}},sr=e=>{!e||!e.row||Te.push({pos:ze++,seq:At(e),t:Qt(e),op:e.op==="delete"?"del":"set",key:String(a(e.row)),row:e.row})},sn=(e,t)=>t==="seq"?e.seq:e.t,qt=(e,t)=>{const n=new Map(qe);for(const r of Te){const o=sn(r,t);if(e!==void 0&&o!==void 0&&o>e)break;r.op==="del"?n.delete(r.key):n.set(r.key,r.row)}return n},zt=e=>{const t=new Map(Ne().map(n=>[n,[]]));for(const n of e)for(const r of Dt(n))t.get(r).push(n);for(const n of Ne())n.partition=new Map(t.get(n).map(r=>[String(n.keyOf(r)),r]));for(const n of Xe)Mt(n);Ot();for(const n of Ne())yt(n)},ln=e=>ve?!0:(A("data-router:no-buffer",`${e}() needs a buffered window; call router.buffer({ window, max }) first to record one.`),!1),Ut=()=>{if(rt&&(clearTimeout(rt),rt=null),wt=!1,Et=[],jt=0,gt){const e=gt;gt=null,e()}},lr=()=>{if(Et=[],jt=0,gt){const e=gt;gt=null,e()}},ar=()=>{rt=null;const e=Et[jt++];e.op==="del"?it.delete(e.key):it.set(e.key,e.row),zt([...it.values()]),Re=e.pos+1,an()};function an(){if(!wt){if(jt>=Et.length){lr();return}rt=setTimeout(ar,st)}}function Vt(e){if(je)try{je.postMessage(e)}catch{}}function Tn(){return{t:"snapshot",rows:Ct(),seq:O,checkpoint:Object.fromEntries(G)}}function ur(e){const t=e&&e.data;if(!(!t||typeof t!="object")){if(t.t==="hello"){Ct().length&&Vt(Tn());return}vt=!0;try{t.t==="delta"?Qe.apply(t.deltas||[]):t.t==="snapshot"&&(Qe.load(t.rows||[]),t.checkpoint&&Qe.seenThrough(t.checkpoint))}finally{vt=!1}}}function cr(e,t){e.partition=new Map(t.map(n=>[String(e.keyOf(n)),n]))}function fr(e,t){const n=t.filter(o=>!o.isDefault),r=t.find(o=>o.isDefault)||null;for(const o of t)o.partition=new Map;for(const o of e){const i=[];for(const f of n)if(f.match(o)&&(i.push(f),!S))break;const s=i.length?i:r?[r]:[];if(!s.length){ft+=1,W&&W(o);continue}for(const f of s)f.partition.set(String(f.keyOf(o)),o)}}const dr=(e,t)=>{if(typeof t=="function")return r=>t(r);let n=null;return t===!0?n=String(e):typeof t=="string"&&(n=t),n==null?null:(r,o=Ve)=>`${n}:${r[o]}`},Rn=(e,t)=>{const n={...e.map?e.map(t):t};if(e.fields&&vr(e,n),e.ns){const r=pr(e,n),o=e.ns(n,r||Ve);r&&(n[r]=o),n[Ve]=o}return n},pr=(e,t)=>{if(typeof h.rowKey!="function")return null;if(e.keyProp!==void 0)return e.keyProp;const n=new Set;try{h.rowKey(new Proxy(t,{get(r,o,i){return typeof o=="string"&&n.add(o),Reflect.get(r,o,i)}}))}catch{}return e.keyProp=n.size===1?[...n][0]:null,e.keyProp===null&&A(`data-router:function-key-namespace:${e.id}`,`addSource("${e.id}") sets \`key\` but the rowKey function does not read exactly one row property, so its ids cannot be namespaced and rows from different feeds sharing an id will replace one another. Use a property-name rowKey, or give each feed ids that are already distinct.`),e.keyProp},Nn=(e,t)=>{const n=[];for(const r of t||[]){if(!r||!r.row)continue;const o=Rn(e,r.row),i=String(o[Ve]);r.op==="delete"?e.live.delete(i):e.live.set(i,o),n.push({...r,row:o})}return e.ingested+=n.length,V(`source:${e.id}`,n.length),n},An=e=>({get id(){return e.id},get size(){return e.live.size},load(t){const n=(t||[]).map(i=>Rn(e,i)),r=new Map(n.map(i=>[String(i[Ve]),i])),o=[];for(const[i,s]of e.live)r.has(i)||o.push({op:"delete",row:s});for(const i of n)o.push({op:"upsert",row:i});return e.live=r,e.ingested+=n.length,V(`source:${e.id}`,n.length),xt(e,o,i=>Qe.apply(i)),this},apply(t){return xt(e,Nn(e,t),n=>Qe.apply(n)),this},push(t){return xt(e,Nn(e,Array.isArray(t)?t:[t]),n=>Qe.push(n)),this},remove(){const t=[];for(const n of e.live.values())t.push({op:"delete",row:n});return e.live.clear(),Se.delete(e.id),t.length&&Qe.apply(t),Qe}}),Gt=new Set(["text","number","integer","boolean","date","json"]),Fn=(e,t=".")=>{if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string")return null;let n=e.trim();if(n===""||/\d\s*[*/^]\s*[\d.(]/.test(n)||(n=n.replace(/[\s\u00a0\u202f\u2009']/g,""),t===","?n=n.split(".").join("").replace(",","."):n=n.split(",").join(""),n=n.replace(/[^0-9eE+\-.]/g,""),n===""||n==="-"||n==="+"||n==="."||n==="-."||n==="+."))return null;const r=Number(n);return Number.isFinite(r)?r:null},hr=e=>{if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}},gr=(e,t,n)=>{A(`router:coerce-failed:${e.id}:${t.name}`,`source "${e.id}" field "${t.name}": could not coerce ${hr(n)} to ${t.type}; the value is stored as null.`)},mr=(e,t)=>{if(typeof t=="string")return Gt.has(t)?{name:e,type:t,format:null,decimal:null,trueSet:null,falseSet:null,nulls:null}:(A("data-router:field-type",`addSource field "${e}" names an unknown type "${t}" (expected ${[...Gt].join(", ")}); the field passes through uncoerced.`),null);if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.type==null?null:String(t.type);return n!=null&&!Gt.has(n)?(A("data-router:field-type",`addSource field "${e}" names an unknown type "${n}" (expected ${[...Gt].join(", ")}); the field passes through uncoerced.`),null):{name:e,type:n,format:typeof t.format=="string"?t.format:null,decimal:t.decimal===","||t.decimal==="."?t.decimal:null,trueSet:Array.isArray(t.true)&&t.true.length?new Set(t.true.map(String)):null,falseSet:Array.isArray(t.false)&&t.false.length?new Set(t.false.map(String)):null,nulls:Array.isArray(t.nulls)&&t.nulls.length?new Set(t.nulls.map(String)):null}}return A("data-router:field-spec",`addSource field "${e}" has an unusable fields declaration (a type string or an options object); the field passes through uncoerced.`),null},yr=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=[];for(const[n,r]of Object.entries(e)){const o=mr(n,r);o&&t.push(o)}return t.length?t:null},br=(e,t)=>{if(e==null)return null;const n=String(e).trim();if(n==="")return null;const r={yyyy:"(\\d{4})",yy:"(\\d{2})",MM:"(\\d{1,2})",M:"(\\d{1,2})",dd:"(\\d{1,2})",d:"(\\d{1,2})",HH:"(\\d{1,2})",mm:"(\\d{1,2})",ss:"(\\d{1,2})"},o=w=>w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");let i="^";const s=[];for(const w of _(t))if(w.token&&r[w.token])i+=r[w.token],s.push(w.token);else{if(w.token)return null;i+=o(w.text)}i+="$";const f=new RegExp(i).exec(n);if(!f)return null;const d={year:0,month:1,day:1,hour:0,minute:0,second:0};for(let w=0;w<s.length;w+=1){const j=Number(f[w+1]);if(Number.isNaN(j))return null;const B=s[w];B==="yyyy"?d.year=j:B==="yy"?d.year=2e3+j:B==="MM"||B==="M"?d.month=j:B==="dd"||B==="d"?d.day=j:B==="HH"?d.hour=j:B==="mm"?d.minute=j:B==="ss"&&(d.second=j)}const k=new Date(d.year,d.month-1,d.day,d.hour,d.minute,d.second);return Number.isNaN(k.getTime())?null:x(k)},wr=(e,t)=>{switch(e.type){case"text":return{ok:!0,value:typeof t=="string"?t:String(t)};case"number":{const n=Fn(t,e.decimal===","?",":".");return n==null?{ok:!1}:{ok:!0,value:n}}case"integer":{const n=Fn(t,e.decimal===","?",":".");return n==null||!Number.isInteger(n)?{ok:!1}:{ok:!0,value:n}}case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(e.trueSet||e.falseSet){const r=String(t);return e.trueSet&&e.trueSet.has(r)?{ok:!0,value:!0}:e.falseSet&&e.falseSet.has(r)?{ok:!0,value:!1}:{ok:!1}}const n=z(t);return n==null?{ok:!1}:{ok:!0,value:n}}case"date":{const n=e.format||"iso";if(n==="epoch-s"){const o=Number(t),i=o*1e3;if(!Number.isFinite(o)||!Number.isFinite(i))return{ok:!1};const s=x(new Date(i));return s==null?{ok:!1}:{ok:!0,value:s}}if(n==="epoch-ms"){const o=Number(t);if(!Number.isFinite(o))return{ok:!1};const i=x(new Date(o));return i==null?{ok:!1}:{ok:!0,value:i}}if(n==="iso"){const o=x(t);return o==null?{ok:!1}:{ok:!0,value:o}}const r=br(t,n);return r==null?{ok:!1}:{ok:!0,value:r}}case"json":{if(typeof t!="string")return{ok:!0,value:t};try{return{ok:!0,value:JSON.parse(t)}}catch{return{ok:!1}}}default:return{ok:!0,value:t}}},kr=(e,t,n)=>{const r=n[t.name];if(r==null||typeof r=="number"&&Number.isNaN(r)){n[t.name]=null;return}if(t.nulls&&t.nulls.has(String(r))){n[t.name]=null;return}if(t.type==null)return;if(t.type!=="text"&&typeof r=="string"&&r.trim()===""){n[t.name]=null;return}const o=wr(t,r);if(!o.ok){gr(e,t,r),n[t.name]=null;return}n[t.name]=o.value},vr=(e,t)=>{for(const n of e.fields)kr(e,n,t)},Tt=e=>e==null?null:String(e),un=(e,t)=>{if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!un(e[n],t[n]))return!1;return!0}if(e&&t&&typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!un(e[o],t[o]))return!1;return!0}return!1},cn=(e,t)=>{if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!un(e[o],t[o]))return!1;return!0},Sr=Object.freeze(["count","sum","avg","min","max","distinctCount","first","last"]),Er=Object.freeze(["sum","avg","min","max","distinctCount","first","last"]),jr=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=[];for(const[n,r]of Object.entries(e)){if(!r||typeof r!="object"||typeof r.fn!="string"){A("data-router:join-aggregate-bad-spec",`join aggregate "${n}" is not a { fn, field? } reducer; the aggregate is skipped.`);continue}if(!Sr.includes(r.fn)){A("data-router:join-aggregate-bad-fn",`join aggregate "${n}" uses fn "${r.fn}", which is not count|sum|avg|min|max|distinctCount|first|last; the aggregate is skipped.`);continue}const o=typeof r.field=="string"&&r.field?r.field:null;if(Er.includes(r.fn)&&!o){A("data-router:join-aggregate-no-field",`join aggregate "${n}" (${r.fn}) needs a field; the aggregate is skipped.`);continue}const i=r.fn==="first"||r.fn==="last"?typeof r.orderBy=="string"&&r.orderBy?r.orderBy:o:null;t.push([n,{fn:r.fn,field:o,orderBy:i}])}return t.length?t:null},fn=(e,t)=>{if(!(!e||typeof e!="object"))return t in e||A(`data-router:collect-select-field:${t}`,`a collect join's \`select\` names "${t}", which the collected rows do not have; it is collected as undefined.`),e[t]},Pr=(e,t)=>{if(!e||typeof e!="object")return null;const n=e.from!=null?String(e.from):null;if(!n)return A("data-router:join-no-from","join needs a `from` (the lookup source id); ignoring the join."),null;const r=e.many===!0||e.spread!=null;let o=e.localKey!=null?e.localKey:e.on;o==null&&r&&(o=Ve);let i;if(typeof o=="function")i=o;else if(typeof o=="string")i=v=>v[o];else return A("data-router:join-no-localkey","join needs a `localKey` (a field name or fn); ignoring the join."),null;const s=e.foreignKey!=null?e.foreignKey:e.fromKey;let f,d;if(typeof s=="function")f=s,d=s;else if(typeof s=="string")f=v=>v[s],d=s;else if(typeof o=="string")f=v=>v[o],d=o;else return A("data-router:join-no-foreignkey","join with a fn `localKey` needs an explicit string/fn `foreignKey`; ignoring the join."),null;if(r){if(e.spread!=null){const Pe=e.spread&&typeof e.spread=="object"?e.spread:{},Ke=Pe.name,dt=Pe.value;let Wt,yn;if(typeof Ke=="function")Wt=Ke;else if(typeof Ke=="string"&&Ke.length)Wt=bt=>bt[Ke];else return A("data-router:spread-no-name","a spread join needs a `name` (the attribute-name field or fn); ignoring the join."),null;if(typeof dt=="function")yn=dt;else if(typeof dt=="string"&&dt.length)yn=bt=>bt[dt];else return A("data-router:spread-no-value","a spread join needs a `value` (the attribute-value field or fn); ignoring the join."),null;const zr=typeof Pe.prefix=="string"?Pe.prefix:"";let bn=null;const Jt=Pe.include;if(typeof Jt=="function")bn=Jt;else if(Array.isArray(Jt)){const bt=new Set(Jt.map(It=>String(It)));bn=It=>bt.has(It)}const Hn=new Map;if(Pe.type&&typeof Pe.type=="object"&&!Array.isArray(Pe.type))for(const[bt,It]of Object.entries(Pe.type))Ir.includes(It)&&Hn.set(bt,It);return{many:!0,spread:!0,from:n,localKey:i,foreignKeyFn:f,ffKey:d,nameFn:Wt,valueFn:yn,prefix:zr,includeFn:bn,typeOf:bt=>Hn.get(bt),keyIndex:new Map,lastFk:new Map,owner:t,probe:null,spreadPrev:new Map}}let v=e.missing;if(v!=="hold"&&v!=="passthrough"&&v!=="null"&&(v!=null&&A("data-router:join-bad-missing",`join.missing "${v}" is not hold|passthrough|null; using "passthrough".`),v="passthrough"),e.aggregate!=null){const Pe=jr(e.aggregate);if(!Pe)return A("data-router:join-aggregate-invalid","a join aggregate must be a non-empty object of named reducers; ignoring the join."),null;const Ke=typeof e.where=="function"?e.where:null;return{many:!0,aggregate:Pe,whereFn:Ke,from:n,localKey:i,foreignKeyFn:f,ffKey:d,missing:v,keyIndex:new Map,lastFk:new Map,owner:t,probe:null}}if(typeof e.as!="string"||!e.as)return A("data-router:join-no-as","a collect join (many: true) needs an `as` (the field to put the collected array into); ignoring the join."),null;let ye=null;const Ie=e.select!=null?e.select:e.fields;typeof Ie=="function"?ye=Ie:typeof Ie=="string"&&Ie?ye=Pe=>fn(Pe,Ie):Array.isArray(Ie)&&Ie.length?ye=Pe=>{const Ke={};for(const dt of Ie)Ke[String(dt)]=fn(Pe,String(dt));return Ke}:Ie&&typeof Ie=="object"&&!Array.isArray(Ie)&&Object.keys(Ie).length&&(ye=Pe=>{const Ke={};for(const[dt,Wt]of Object.entries(Ie))Ke[String(Wt)]=fn(Pe,dt);return Ke}),ye||(ye=Pe=>Pe);const Rt=e.distinct===!0,Nt=e.sort===!0?!0:typeof e.sort=="function"?e.sort:!1,St=e.onParentDelete==="cascade"||e.onParentDelete==="orphan"?e.onParentDelete:"keep";return{many:!0,from:n,localKey:i,foreignKeyFn:f,ffKey:d,as:e.as,selectFn:ye,distinct:Rt,sort:Nt,missing:v,onParentDelete:St,keyIndex:new Map,lastFk:new Map,owner:t,probe:null}}let k=null;const w=[],j=e.fields!=null?e.fields:e.select;if(typeof j=="function")k=j;else if(Array.isArray(j))for(const v of j)w.push([String(v),String(v)]);else if(j&&typeof j=="object")for(const[v,ye]of Object.entries(j))w.push([v,String(ye)]);else A("data-router:join-no-fields","join has no `fields`/`select`; rows pass through unenriched.");let B=e.missing;return B!=="hold"&&B!=="passthrough"&&B!=="null"&&(B!=null&&A("data-router:join-bad-missing",`join.missing "${B}" is not hold|passthrough|null; using "passthrough".`),B="passthrough"),{many:!1,from:n,localKey:i,foreignKeyFn:f,ffKey:d,pairs:w,selectFn:k,missing:B,keyIndex:new Map,lastFk:new Map,owner:t,probe:null}},Or=(e,t)=>{const n=new Set,r=[e];for(;r.length;){const o=r.pop();if(o===t)return!0;if(n.has(o))continue;n.add(o);const i=Se.get(o);if(i)for(const s of i.joins)r.push(s.from)}return!1},$n=(e,t)=>{if(e==null)return[];const n=[];for(const o of Array.isArray(e)?e:[e]){const i=Pr(o,t);i&&n.push(i)}const r=[];for(const o of n){if(o.from===t.id||Or(o.from,t.id)){A("router:join-cycle",`join from "${t.id}" to "${o.from}" would close a join cycle; the join is refused.`);continue}r.push(o)}return r},Tr=(e,t)=>{const n=new Set;let r=Se.get(e);for(;r&&r.unnestParentId!=null&&!n.has(r.id);){if(n.add(r.id),r.unnestParentId===t)return!0;r=Se.get(r.unnestParentId)}return!1},Rr=(e,t)=>{if(!e||typeof e!="object")return null;const n=typeof e.path=="string"&&e.path?e.path:null;if(!n)return A("data-router:unnest-no-path","an unnest needs a `path` (the dotted array field on the row); ignoring the unnest."),null;const r=typeof e.as=="string"&&e.as?e.as:null;if(!r)return A("data-router:unnest-no-as","an unnest needs an `as` (the child row type); ignoring the unnest."),null;if(r===t.id||Tr(t.id,r))return A("router:unnest-cycle",`unnest "${t.id}" → "${r}" would close an unnest cycle; the unnest is refused.`),null;const o=typeof e.parentKey=="string"&&e.parentKey?e.parentKey:`${t.id}Id`,i=e.keep===!0;let s;if(typeof e.key=="function")s=e.key;else if(typeof e.key=="string"&&e.key){const k=e.key;s=w=>w[k]}else s=null;let f=Se.get(r);if(!f){f={id:r,map:null,fields:null,ns:null,live:new Map,out:new Map,ingested:0,joins:[],unnests:[],unnestParentId:t.id},f.handle=An(f),Se.set(r,f),f.joins=$n(e.join,f),f.unnests=Dn(e.unnest,f);for(const k of f.joins)Se.has(k.from)&&_t(Se.get(k.from),k);for(const k of Se.values())if(k!==f)for(const w of k.joins)w.from===r&&w.probe==null&&_t(f,w)}const d=e.onParentDelete==="orphan"||e.onParentDelete==="keep"?e.onParentDelete:"cascade";return{path:n,as:r,keyFn:s,parentKeyField:o,keep:i,owner:t,child:f,onParentDelete:d,prevChildren:new Map}},Dn=(e,t)=>{if(e==null)return[];const n=[];for(const r of Array.isArray(e)?e:[e]){const o=Rr(r,t);o&&n.push(o)}return n},Nr=(e,t)=>{const n=[];let r=0;for(const o of t||[]){if(!o||!o.row)continue;const i=String(o.row[Ve]),s=e.prevChildren.get(i)||new Map;if(o.op==="delete"){for(const[w,j]of s)if(e.onParentDelete==="orphan"){if(j.__orphan===!0)continue;const B={...j,__orphan:!0};e.child.live.set(w,B),n.push({op:"upsert",row:B}),r+=1}else e.onParentDelete==="keep"||(e.child.live.delete(w),n.push({op:"delete",row:j}));e.prevChildren.delete(i);continue}const f=$(o.row,e.path),d=Array.isArray(f)?f:[],k=new Map;for(let w=0;w<d.length;w+=1){const j=d[w],B=e.keyFn?e.keyFn(j,o.row,w):null,v=B==null?`${i}:${w}`:String(B);k.has(v)&&A("router:unnest-duplicate-key",`the unnest "${e.as}" produced the child key "${v}" more than once for one parent; the later child (source order) wins.`);const ye={...j&&typeof j=="object"?j:{}};ye[e.parentKeyField]=o.row[Ve],ye[Ve]=v,m&&(ye[m]=e.as);const Ie=e.child.live.get(v);Ie&&Ie.__orphan===!0&&(ye.__orphan=void 0),k.set(v,ye)}for(const[w,j]of s)k.has(w)||(e.child.live.delete(w),n.push({op:"delete",row:j}));for(const[w,j]of k){const B=s.get(w);B===void 0?(e.child.live.set(w,j),n.push({op:"upsert",row:j})):cn(B,j)||(e.child.live.set(w,j),n.push({op:"upsert",row:j}))}e.prevChildren.set(i,k)}return r>0&&A("router:orphaned-rows",`${r} child row(s) were orphaned when their parent was deleted; they are kept and marked __orphan: true (onParentDelete: 'orphan').`),n},Mn=(e,t,n)=>{const r={...t};if(e.selectFn){const o=e.selectFn(n,t);return o&&typeof o=="object"&&Object.assign(r,o),r}for(const[o,i]of e.pairs)r[i]=n?n[o]:null;return r},Ar=(e,t)=>{if(t==null||!e.probe)return null;const n=e.probe.index.get(t);if(!n||!n.size)return null;const r=Se.get(e.from);if(!r)return null;let o;for(o of n);return r.out&&r.out.get(o)||null},Fr=(e,t,n)=>{const r=Se.get(e.from),o=[];if(n!=null&&r&&e.probe){const s=e.probe.index.get(n);if(s)for(const f of s){const d=r.out?r.out.get(f):void 0;d!==void 0&&o.push(e.selectFn(d,t))}}if(e.missing==="hold"&&o.length===0)return{hold:!0};if(e.missing==="null"&&o.length===0)return{hold:!1,value:null};let i=o;if(e.distinct){const s=new Map,f=[];for(const d of i){const k=typeof d=="object"&&d!==null?JSON.stringify(d):`${typeof d}:${String(d)}`;s.has(k)||(s.set(k,!0),f.push(d))}i=f}return e.sort&&(i=i.slice().sort(e.sort===!0?In:e.sort)),{hold:!1,value:i}},In=(e,t)=>{if(e===t)return 0;if(e==null)return-1;if(t==null)return 1;if(typeof e=="number"&&typeof t=="number")return e-t;const n=String(e),r=String(t);return n<r?-1:n>r?1:0},$r=(e,t)=>{const{fn:n,field:r,orderBy:o}=e;if(n==="count")return t.length;if(n==="first"||n==="last"){if(!t.length)return null;let s=t[0];for(let f=1;f<t.length;f+=1){const d=In(t[f][o],s[o]);(n==="first"&&d<0||n==="last"&&d>0)&&(s=t[f])}return r?s[r]:s}if(n==="distinctCount"){if(!t.length)return null;const s=new Set;for(const f of t)s.add(f[r]);return s.size}const i=r?t.map(s=>Number(s[r])).filter(s=>Number.isFinite(s)):[];return n==="sum"?i.reduce((s,f)=>s+f,0):n==="avg"?i.length?i.reduce((s,f)=>s+f,0)/i.length:null:n==="min"?i.length?Math.min(...i):null:n==="max"&&i.length?Math.max(...i):null},Dr=(e,t)=>e.map(([n,r])=>[n,$r(r,t)]),Mr=(e,t)=>{const n=Se.get(e.from),r=[];let o=!1;if(t!=null&&n&&e.probe){const i=e.probe.index.get(t);if(i)for(const s of i){const f=n.out?n.out.get(s):void 0;f!==void 0&&(o=!0,(!e.whereFn||e.whereFn(f))&&r.push(f))}}return e.missing==="hold"&&!o?{hold:!0}:{hold:!1,values:Dr(e.aggregate,r)}},Ir=Object.freeze(["number","date","boolean","text"]);function Lr(e,t){if(e==null)return e;if(t==="number"){if(typeof e=="number")return e;const n=Number(e);return Number.isFinite(n)?n:e}if(t==="date"){if(e instanceof Date)return e;const n=new Date(e);return Number.isNaN(n.getTime())?e:n}if(t==="boolean"){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no"||n==="")return!1}return!!e}return t==="text"?String(e):e}const Cr=(e,t)=>{const n=Se.get(e.from),r=new Map;if(t!=null&&n&&e.probe){const o=e.probe.index.get(t);if(o)for(const i of o){const s=n.out?n.out.get(i):void 0;if(s===void 0)continue;const f=e.nameFn(s);if(f==null)continue;const d=String(f);if(e.includeFn&&!e.includeFn(d,s))continue;const k=e.prefix+d;r.has(k)&&A("router:spread-duplicate",`a spread join wrote the field "${k}" more than once for one parent; the last attribute row (source order) wins.`),r.set(k,Lr(e.valueFn(s),e.typeOf?e.typeOf(d):void 0))}}return r},dn=(e,t,n)=>{const r=e.lastFk.get(t);if(r!==void 0&&r!==n){const i=e.keyIndex.get(r);i&&(i.delete(t),i.size||e.keyIndex.delete(r))}if(n==null){e.lastFk.set(t,null);return}let o=e.keyIndex.get(n);o||(o=new Set,e.keyIndex.set(n,o)),o.add(t),e.lastFk.set(t,n)},pn=(e,t,n)=>{const r=e.joins.indexOf(n);for(let o=r+1;o<e.joins.length;o+=1){const i=e.joins[o];dn(i,t,null),i.lastFk.delete(t)}},Ln=(e,t,n)=>{let r={...t};if(e.unnests&&e.unnests.length)for(const o of e.unnests)o.keep||X(r,o.path);for(const o of e.joins){const i=Tt(o.localKey(r));if(dn(o,n,i),o.spread){const s=Cr(o,i),f=o.spreadPrev.get(n)||new Set,d=new Set;for(const[k,w]of s){if(Object.prototype.hasOwnProperty.call(t,k)){A("router:spread-collision",`a spread join skipped the field "${k}" because the parent row already carries it; a spread field never overwrites a base parent field.`),d.add(k);continue}r[k]=w,F.add(k),d.add(k)}for(const k of f)d.has(k)||(r[k]=void 0);o.spreadPrev.set(n,d)}else if(o.many)if(o.aggregate){const s=Mr(o,i);if(s.hold)return pn(e,n,o),{emit:!1,row:t};for(const[f,d]of s.values)r[f]=d}else{const s=Fr(o,r,i);if(s.hold)return pn(e,n,o),{emit:!1,row:t};r[o.as]=s.value}else{const s=Ar(o,i);if(s)r=Mn(o,r,s);else{if(o.missing==="hold")return pn(e,n,o),{emit:!1,row:t};o.missing==="null"&&(r=Mn(o,r,null))}}}return{emit:!0,row:r}},_t=(e,t)=>{e.probes||(e.probes=new Map);let n=e.probes.get(t.ffKey);if(!n){n={fn:t.foreignKeyFn,index:new Map,prev:new Map,specs:new Set},e.probes.set(t.ffKey,n);for(const[r,o]of e.live){const i=Tt(n.fn(o));if(i==null)continue;let s=n.index.get(i);s||(s=new Set,n.index.set(i,s)),s.add(r),n.prev.set(r,i)}}n.specs.add(t),t.probe=n},Cn=(e,t,n)=>{const r=e.live.get(t);if(!r)return;const o=e.out.get(t),i=Ln(e,r,t);let s=!1;i.emit?(e.out.set(t,i.row),(o===void 0||!cn(o,i.row))&&(n.push({op:"upsert",row:i.row}),s=!0)):(e.out.delete(t),o!==void 0&&(n.push({op:"delete",row:o}),s=!0)),s&&xn(e,new Set([t]),n)},xn=(e,t,n)=>{if(!(!e.probes||!e.probes.size))for(const r of e.probes.values()){const o=new Set;for(const i of t){const s=e.live.get(i),f=s?Tt(r.fn(s)):null;f!=null&&o.add(f)}if(o.size)for(const i of r.specs)for(const s of o){const f=i.keyIndex.get(s);if(f)for(const d of[...f])Cn(i.owner,d,n)}}},xt=(e,t,n)=>{if(e.unnests&&e.unnests.length)for(const f of e.unnests){const d=Nr(f,t);d.length&&xt(f.child,d,n)}{const f=[],d=[];for(const k of t)!k||!k.row||(k.op==="delete"?f.push(k.row):d.push(k.row));if(f.length||d.length){const k=[];for(const v of e.joins)if(v.many&&!v.aggregate&&!v.spread&&(v.onParentDelete==="cascade"||v.onParentDelete==="orphan")){const ye=Se.get(v.from);k.push({childSource:ye,pkFn:v.localKey,fkFn:v.foreignKeyFn,index:v.probe?v.probe.index:null,mode:v.onParentDelete,writeBack:!1})}for(const v of L)v.parentId===e.id&&k.push({childSource:Se.get(v.childId),pkFn:v.pkFn,fkFn:v.fkFn,index:v.probe?v.probe.index:null,mode:v.onParentDelete,writeBack:v.writeBack});const w=new Map;let j=0;const B=v=>{let ye=w.get(v.id);return ye||(ye={source:v,deltas:[],writeBack:[]},w.set(v.id,ye)),ye};for(const v of k)if(!(!v.childSource||!v.index)){for(const ye of f){const Ie=Tt(v.pkFn(ye));if(Ie==null)continue;const Rt=v.index.get(Ie);if(!Rt)continue;const Nt=B(v.childSource);for(const St of[...Rt]){const Pe=v.childSource.live.get(St);if(Pe){if(v.mode==="cascade")v.childSource.live.delete(St),Nt.deltas.push({op:"delete",row:Pe}),v.writeBack&&Nt.writeBack.push(Pe);else if(Pe.__orphan!==!0){const Ke={...Pe,__orphan:!0};v.childSource.live.set(St,Ke),Nt.deltas.push({op:"upsert",row:Ke}),j+=1}}}}if(v.mode==="orphan")for(const ye of d){const Ie=Tt(v.pkFn(ye));if(Ie==null)continue;const Rt=v.index.get(Ie);if(!Rt)continue;const Nt=B(v.childSource);for(const St of[...Rt]){const Pe=v.childSource.live.get(St);if(!Pe||Pe.__orphan!==!0)continue;const Ke={...Pe,__orphan:void 0};v.childSource.live.set(St,Ke),Nt.deltas.push({op:"upsert",row:Ke})}}}j>0&&A("router:orphaned-rows",`${j} child row(s) were orphaned when their parent was deleted; they are kept and marked __orphan: true (onParentDelete: 'orphan').`);for(const v of w.values())if(v.deltas.length&&xt(v.source,v.deltas,n),v.writeBack.length&&Be)for(const ye of v.writeBack)try{Be({op:"delete",key:String(ye[Ve]),row:ye},{route:null,source:v.source.handle})}catch{}}}const r=new Map;if(e.probes&&e.probes.size)for(const f of e.probes.values()){const d=new Set;for(const k of t){const w=String(k.row[Ve]);if(k.op==="delete"){const v=f.prev.get(w);if(v!=null){const ye=f.index.get(v);ye&&(ye.delete(w),ye.size||f.index.delete(v)),d.add(v)}f.prev.delete(w);continue}const j=Tt(f.fn(k.row)),B=f.prev.get(w);if(B!=null&&B!==j){const v=f.index.get(B);v&&(v.delete(w),v.size||f.index.delete(B)),d.add(B)}if(j!=null){let v=f.index.get(j);v||(v=new Set,f.index.set(j,v)),v.add(w),d.add(j)}f.prev.set(w,j)}d.size&&r.set(f,d)}const o=[],i=new Set;for(const f of t){const d=String(f.row[Ve]);if(f.op==="delete"){for(const B of e.joins)dn(B,d,null),B.lastFk.delete(d),B.spread&&B.spreadPrev.delete(d);const j=e.out.get(d);e.out.delete(d),j!==void 0&&(o.push(f),i.add(d));continue}const k=e.out.get(d),w=Ln(e,f.row,d);w.emit?(e.out.set(d,w.row),(k===void 0||!cn(k,w.row))&&(o.push({...f,row:w.row}),i.add(d))):(e.out.delete(d),k!==void 0&&(o.push({op:"delete",row:k}),i.add(d)))}n(o);const s=[];if(r.size)for(const[f,d]of r)for(const k of f.specs)for(const w of d){const j=k.keyIndex.get(w);if(j)for(const B of[...j])Cn(k.owner,B,s)}i.size&&xn(e,i,s),s.length&&Qe.apply(s)},hn=(e,t,n)=>{const r=me.get(e);if(me.set(e,{cur:t,t:n}),!r)return 0;const o=(n-r.t)/1e3;return o<=0?0:(t-r.cur)/o},xr=()=>{if(!ve)return 0;let e=0;for(const t of Te)t.pos>=Re&&(e+=1);return e},Wn=(e,t)=>{const n=we.get(e);if(n)for(const r of n)try{r(t)}catch{}},Wr=()=>{be||He<=0||(be=setInterval(()=>Wn("metrics",Qe.metrics()),He),be&&typeof be.unref=="function"&&be.unref())},Bn=()=>{be&&(clearInterval(be),be=null)},Br=e=>{const t=e.indexedDB||(typeof indexedDB<"u"?indexedDB:null);if(!t)return null;const n=typeof e.dbName=="string"?e.dbName:"lattice-router",r=typeof e.storeName=="string"?e.storeName:"snapshots";let o=null;const i=()=>o||(o=new Promise((s,f)=>{let d;try{d=t.open(n,1)}catch(k){f(k);return}d.onupgradeneeded=()=>{const k=d.result;k.objectStoreNames.contains(r)||k.createObjectStore(r)},d.onsuccess=()=>s(d.result),d.onerror=()=>f(d.error)}),o);return{set(s,f){return i().then(d=>new Promise((k,w)=>{const j=d.transaction(r,"readwrite");j.objectStore(r).put(f,s),j.oncomplete=()=>k(),j.onerror=()=>w(j.error),j.onabort=()=>w(j.error)}))},get(s){return i().then(f=>new Promise((d,k)=>{const j=f.transaction(r,"readonly").objectStore(r).get(s);j.onsuccess=()=>d(j.result),j.onerror=()=>k(j.error)}))},close(){o&&o.then(s=>{try{s.close()}catch{}},()=>{})}}},Hr=()=>ve?[...qt(void 0,ge).values()]:Ct(),Kr=()=>({v:1,world:Hr(),maxSeq:O,checkpoint:Object.fromEntries(G),buffer:ve?{on:!0,max:ie,window:he,domain:ge,pos:ze,baseSeq:$e,baseT:ut,base:[...qe.entries()],log:Te.map(e=>({pos:e.pos,seq:e.seq,t:e.t,op:e.op,key:e.key,row:e.row}))}:{on:!1}}),qr=e=>{if(!e||typeof e!="object")return!1;Me=!0;try{Qe.load(Array.isArray(e.world)?e.world:[])}finally{Me=!1}e.checkpoint&&Qe.seenThrough(e.checkpoint),Number.isFinite(e.maxSeq)&&(O===void 0||e.maxSeq>O)&&(O=e.maxSeq);const t=e.buffer;if(t&&t.on){ve=!0,ie=Number.isFinite(t.max)?t.max:null,he=Number.isFinite(t.window)?t.window:null,ge=t.domain==="seq"||t.domain==="time"?t.domain:Fe?"seq":"time",qe=new Map(Array.isArray(t.base)?t.base:[]),Te.length=0;for(const n of Array.isArray(t.log)?t.log:[])Te.push({...n});ze=Number.isFinite(t.pos)?t.pos:Te.length,$e=t.baseSeq,ut=t.baseT,Re=ze}return!0},gn=()=>{if(!ce)return Promise.resolve();const e=Kr(),t=Promise.resolve().then(()=>ce.set(Ue,e)).catch(()=>{});return fe=t,t.then(()=>{fe===t&&(fe=null)})},mn=()=>{if(!(!Ee||!ce||Me)){if(tt<=0){gn();return}De||(De=setTimeout(()=>{De=null,gn()},tt),De&&typeof De.unref=="function"&&De.unref())}},Qe={attach(e,t,n={}){const r=typeof t!="function",o=r?s=>p(s)===t:t;r&&vn(t);const i=rn(e,o,n);return r&&(i.hasPartValue=!0,i.partValue=t),_e.push(i),i.writable&&nr(i),this},attachDefault(e,t={}){return Je=rn(e,()=>!1,t),Je.isDefault=!0,this},subscribe(e,t,n={}){const r=typeof e!="function",o=r?s=>p(s)===e:e;r&&vn(e);const i=rn(t,o,n);return r&&(i.hasPartValue=!0,i.partValue=e),_e.push(i),this},alert(e,t,n,r={}){const i={match:typeof e=="function"?e:s=>p(s)===e,keyOf:ne(R(r.rowKey,"alerts"),c),filter:typeof r.filter=="function"?r.filter:null,condition:typeof t=="function"?t:()=>!1,handler:typeof n=="function"?n:()=>{},debounceMs:Number.isFinite(r.debounce)?Number(r.debounce):0,armed:!0,timer:null,pending:null,partition:new Map};return at.push(i),on(i,Ct()),Kt(i),this},monitor(e,t,n,r={}){const i={kind:"monitor",match:typeof e=="function"?e:s=>p(s)===e,keyOf:ne(R(r.rowKey,"alerts"),c),filter:typeof r.filter=="function"?r.filter:null,evaluate:typeof t=="function"?t:()=>{},handler:typeof n=="function"?n:()=>{},armed:!0,timer:null,pending:null,partition:new Map};return at.push(i),on(i,Ct()),Kt(i),()=>{const s=at.indexOf(i);s>=0&&at.splice(s,1),i.timer&&(clearTimeout(i.timer),i.timer=null),i.partition.clear()}},configure(e={}){const t=n=>({rowKey:n.rowKey,transform:n.transform,filter:n.filter,sort:n.sort,rollup:n.rollup,debounce:n.debounce,where:n.where,writable:n.writable,onWrite:n.onWrite,onConflict:n.onConflict,backpressure:n.backpressure,label:n.label});for(const n of e.routes||[])if(n){if(n.default!==void 0){this.attachDefault(n.default,t(n));continue}if(n.alert!==void 0){this.alert(n.when,n.condition,n.alert,t(n));continue}if(n.subscribe!==void 0){this.subscribe(n.when,n.subscribe,t(n));continue}this.attach(n.grid,n.when,t(n))}for(const n of e.links||[])n&&n.from&&n.to&&this.link(n.from,n.to,n.on!==void 0?n.on:n.relation);return e.relate&&this.relate(e.relate),e.buffer&&this.buffer(e.buffer),this},link(e,t,n){const r={from:e,to:t,relation:n,predicate:null};Xe.push(r),wn(e),Mt(r);const o=ot(t);return o&&yt(o),this},relate(e){for(const t of e||[]){if(!t||!t.from||!t.to)continue;const n=t.on!==void 0?t.on:t.relation!==void 0?t.relation:t.rel;Ye.push({from:t.from,to:t.to,rel:n}),t.mutual&&Ye.push({from:t.to,to:t.from,rel:We(n)})}for(const t of Lt())wn(t);Ot();for(const t of Lt()){const n=ot(t);n&&yt(n)}return this},flush(){return nn(),this},detach(e){const t=new Set;for(let o=Xe.length-1;o>=0;o--){const i=Xe[o];(i.from===e||i.to===e)&&(i.to!==e&&t.add(i.to),kn(i.from),Xe.splice(o,1))}let n=!1;for(let o=Ye.length-1;o>=0;o--)(Ye[o].from===e||Ye[o].to===e)&&(kn(Ye[o].from),Ye.splice(o,1),n=!0);for(let o=_e.length-1;o>=0;o--)_e[o].grid===e&&_e.splice(o,1);Je&&Je.grid===e&&(Je=null),Pt.delete(e);const r=mt.get(e);if(r&&(r(),mt.delete(e)),n){Ot();for(const o of Lt())t.add(o)}for(const o of t){const i=ot(o);i&&yt(i)}return this},load(e){ft=0;const t=new Map(Ne().map(r=>[r,[]]));for(const r of e||[]){const o=Dt(r);if(!o.length){ft+=1,W&&W(r);continue}for(const i of o)t.get(i).push(r)}for(const r of Ne()){const o=t.get(r);r.partition=new Map(o.map(i=>[String(r.keyOf(i)),i])),r.metricRows+=o.length,T+=o.length}if(Fe)for(const r of e||[]){const o=Fe(r);if(!Number.isFinite(o))continue;const i=String(a(r)),s=G.get(i);(s===void 0||o>s)&&G.set(i,o),(O===void 0||o>O)&&(O=o)}for(const r of Xe)Mt(r);Ot();for(const r of at)on(r,e||[]),Kt(r);for(const r of Ne())r.bp&&Jn(r);const n=Ne().map(r=>yt(r));return ve&&Pn(),Re=ze,je&&!vt&&Vt(Tn()),mn(),n},apply(e){let t=(e||[]).filter(o=>o&&o.row);if(Ze){t=t.map((i,s)=>[i,s]).sort((i,s)=>{const f=At(i[0]),d=At(s[0]);return f===void 0||d===void 0?i[1]-s[1]:f-d||i[1]-s[1]}).map(i=>i[0]);const o=[];for(const i of t){const s=At(i);if(s!==void 0){const f=String(a(i.row)),d=G.get(f);if(d!==void 0&&s<=d){Q+=1;continue}G.set(f,s),(O===void 0||s>O)&&(O=s)}o.push(i)}t=o}if(je&&!vt&&t.length&&Vt({t:"delta",deltas:t.map(o=>({op:o.op,row:o.row,seq:o.seq}))}),ve){for(const o of t)sr(o);ir()}for(const o of at)or(o,t),Kt(o);if(ct){mn();return}const n=new Map(Ne().map(o=>[o,new Map]));for(const o of t){const i=o&&o.row;if(!i)continue;if(o.op==="delete"){let f=!1;for(const d of Ne()){const k=String(d.keyOf(i));(d.partition.has(k)||n.get(d).has(k))&&(n.get(d).set(k,{op:"del"}),f=!0)}!f&&!Dt(i).length&&(ft+=1,W&&W(o));continue}const s=Dt(i);if(!s.length){ft+=1,W&&W(o);continue}for(const f of Ne()){if(s.includes(f))continue;const d=String(f.keyOf(i));(f.partition.has(d)||n.get(f).get(d)?.op==="set")&&n.get(f).set(d,{op:"del"})}for(const f of s)n.get(f).set(String(f.keyOf(i)),{op:"set",row:i})}const r=new Map;for(const o of Ne()){let i=0;const s=n.get(o).size;for(const[f,d]of n.get(o)){if(d.op==="del"){o.partition.delete(f);continue}o.partition.set(f,d.row),i+=1}o.metricRows+=i,T+=i,r.set(o,s)}for(const o of Xe)Mt(o);Ot();for(const o of Ne())_n(o,r.get(o)||0);Re=ze,mn()},push(e){const t=Array.isArray(e)?e:[e];if(!M)return this.apply(t),this;for(const n of t)Y.push(n);return g!==null&&(g<=0?this.flushStream():l||(l=setTimeout(()=>this.flushStream(),g))),this},flushStream(){if(l&&(clearTimeout(l),l=null),!Y.length)return this;const e=Y.splice(0,Y.length);return this.apply(e),this},flushBackpressure(){for(const e of Ne())e.bp&&(e.bpTimer||e.bpPending>0)&&Bt(e);return this},addSource(e,t){let n,r;e&&typeof e=="object"?(r=e,n=r.id!=null?String(r.id):`source${++Zt}`):(n=e!=null?String(e):`source${++Zt}`,r=t||{});const o=Se.get(n);if(o)return A("data-router:duplicate-source",`addSource("${n}") was already registered; returning the existing source handle. Use a distinct id per feed.`),o.handle;const i={id:n,map:typeof r.map=="function"?r.map:null,fields:yr(r.fields),ns:dr(n,r.key),live:new Map,out:new Map,ingested:0,joins:[],unnests:[]};i.handle=An(i),i.joins=$n(r.join,i),Se.set(n,i);for(const s of i.joins)Se.has(s.from)&&_t(Se.get(s.from),s);for(const s of Se.values())if(s!==i)for(const f of s.joins)f.from===n&&f.probe==null&&_t(i,f);return i.unnests=Dn(r.unnest,i),i.handle},removeSource(e){const t=e&&typeof e=="object"&&e.id!==void 0?String(e.id):String(e),n=Se.get(t);return n&&n.handle.remove(),this},sources(){return[...Se.keys()]},relateRows(e={}){const t=w=>w&&typeof w=="object"&&w.id!==void 0?String(w.id):String(w),n=t(e.child),r=t(e.parent),o=Se.get(n),i=Se.get(r);if(!o||!i)return A("data-router:relaterows-missing-source","relateRows needs both `child` and `parent` to be registered source ids (or the handles addSource returned); the rule was ignored."),this;let s,f;if(typeof e.foreignKey=="function")s=e.foreignKey,f=`fn:${s.toString()}`;else if(typeof e.foreignKey=="string"&&e.foreignKey)s=w=>w[e.foreignKey],f=e.foreignKey;else return A("data-router:relaterows-no-foreignkey","relateRows needs a `foreignKey` (the child field holding the parent key); the rule was ignored."),this;const d=e.onParentDelete==="cascade"||e.onParentDelete==="orphan"?e.onParentDelete:null;if(!d)return this;o.probes||(o.probes=new Map);let k=o.probes.get(f);if(!k){k={fn:s,index:new Map,prev:new Map,specs:new Set},o.probes.set(f,k);for(const[w,j]of o.live){const B=Tt(k.fn(j));if(B==null)continue;let v=k.index.get(B);v||(v=new Set,k.index.set(B,v)),v.add(w),k.prev.set(w,B)}}return L.push({parentId:r,childId:n,fkFn:s,pkFn:w=>w[Ve],onParentDelete:d,writeBack:e.writeBack===!0,probe:k}),this},fieldsOf(e){const t=Ge(e);return!t||!t.spreadFields?[]:[...t.spreadFields.keys()]},metrics(){const e=b(),t=Ne().map((r,o)=>({index:o,label:r.label||(r.isDefault?"default":null),kind:typeof r.grid=="function"?"view":"grid",rows:r.partition.size,shown:r.keys.size,routed:r.metricRows,throughput:hn(`route:${o}`,r.metricRows,e),backpressure:r.bp?{pending:r.bpPending,coalesced:r.bpCoalesced}:null})),n=[...Se.values()].map(r=>({id:r.id,rows:r.live.size,ingested:r.ingested,throughput:hn(`source:${r.id}`,r.ingested,e)}));return{routes:t,sources:n,unrouted:ft,dropped:Q,buffered:Te.length,lag:xr(),throughput:hn("total",T,e)}},on(e,t){if(typeof t!="function")return()=>{};let n=we.get(e);return n||(n=new Set,we.set(e,n)),n.add(t),e==="metrics"&&Wr(),()=>{n.delete(t),e==="metrics"&&n.size===0&&Bn()}},mountDevtools(e,t={}){return le(this,e,t)},get unrouted(){return ft},get dropped(){return Q},lastSeq(){return O},checkpoint(){return new Map(G)},seenThrough(e){const t=e instanceof Map?e.entries():Object.entries(e||{});for(const[n,r]of t){const o=Number(r);if(!Number.isFinite(o))continue;const i=G.get(String(n));(i===void 0||o>i)&&G.set(String(n),o),(O===void 0||o>O)&&(O=o)}return this},persist(e={}){if(Ee=!0,typeof e.key=="string"&&(Ue=e.key),Number.isFinite(e.debounce)&&(tt=Number(e.debounce)),e.storage&&typeof e.storage.get=="function"&&typeof e.storage.set=="function")ce=e.storage;else{let t=null;try{t=Br(e)}catch{t=null}t?ce=t:(ce=null,A("data-router:no-indexeddb","router.persist() found no usable IndexedDB (a non-browser runtime, private mode, or blocked storage); the router runs in-memory with no durable resume. Pass { storage } to use another backend."))}return this},async restore(){if(!ce)return!1;let e;try{e=await ce.get(Ue)}catch{return!1}return e==null?!1:qr(e)},async flushPersist(){return De&&(clearTimeout(De),De=null),await gn(),fe&&await fe,this},get persisting(){return Ee&&!!ce},buffer(e={}){return ve=!0,Number.isFinite(e.max)?ie=Number(e.max):"max"in e&&e.max==null&&(ie=null),Number.isFinite(e.window)?he=Number(e.window):"window"in e&&e.window==null&&(he=null),ie==null&&he==null&&(ie=I,A("data-router:buffer-default-cap",`buffer() called with no window or max; applying a default cap of ${I} deltas so the buffer stays bounded. Pass { window } or { max } to size it.`)),ge=Fe?"seq":"time",Pn(),this},scrubTo(e,t={}){if(!ln("scrubTo"))return this;Ut(),ct=!0;const n=t.by||ge;it=qt(e,n),zt([...it.values()]),Re=0;for(const r of Te){const o=sn(r,n);if(e!==void 0&&o!==void 0&&o>e)break;Re=r.pos+1}return this},replay(e,t,n={}){if(!ln("replay"))return Promise.resolve();Ut(),ct=!0;const r=n.by||ge;return Yt=r,st=Number.isFinite(n.speed)?Number(n.speed):0,it=qt(e,r),zt([...it.values()]),Et=Te.filter(o=>{const i=sn(o,r);return i!==void 0&&i>e&&i<=t}).slice().sort((o,i)=>o.pos-i.pos),jt=0,wt=!1,new Promise(o=>{gt=o,an()})},pause(){return wt=!0,rt&&(clearTimeout(rt),rt=null),this},resume(){return wt?(wt=!1,an(),this):this},live(){return ln("live")?(Ut(),ct=!1,it=null,zt([...qt(void 0,ge).values()]),Re=ze,this):this},get traveling(){return ct},get buffered(){return Te.length},broadcast(e={}){if(typeof BroadcastChannel!="function")return A("data-router:no-broadcastchannel","router.broadcast() needs the BroadcastChannel API, which this runtime does not provide; cross-tab mirroring is off."),this;const t=e&&typeof e.channel=="string"?e.channel:"";return t?(je&&(je.close(),je=null),je=new BroadcastChannel(t),je.onmessage=ur,Vt({t:"hello"}),this):(A("data-router:broadcast-channel","router.broadcast({ channel }) needs a string channel name; nothing was mirrored."),this)},get broadcasting(){return!!je},async query(e,t={}){if(!e||typeof e.execute!="function")return A("data-router:bad-query-source","router.query(adapter) needs an adapter with an execute(query) function (a DFQL/DuckDB adapter or a pushdown source); nothing was fetched."),this;const n=re(e.capabilities),r=t||{},o=r.filters||null,i=[];ft=0;const s=Ne().filter(d=>d.where),f=Ne().filter(d=>!d.where);for(const d of s){const k=Le(o,d.where),w=pe({...r,filters:k},n);let B=((await e.execute(w.pushed,r)).rows||[]).slice();w.residual&&w.residual.filters&&(B=B.filter(v=>oe(w.residual.filters,v))),B=B.filter(v=>d.match(v)),cr(d,B),i.push({route:d.grid,pushedFilter:!!(w.pushed&&w.pushed.filters),residual:w.unpushed.slice()})}if(f.length){const d=pe(r,n);let w=((await e.execute(d.pushed,r)).rows||[]).slice();d.residual&&d.residual.filters&&(w=w.filter(j=>oe(d.residual.filters,j))),fr(w,f),i.push({base:!0,pushedFilter:!!(d.pushed&&d.pushed.filters),residual:d.unpushed.slice()})}$t=i;for(const d of Xe)Mt(d);Ot();for(const d of Ne())yt(d);return this},lastQueryPlan(){return $t?$t.map(e=>({...e})):null},destroy(){if(lt&&(clearTimeout(lt),lt=null),l&&(clearTimeout(l),l=null),De&&(clearTimeout(De),De=null),ce&&typeof ce.close=="function")try{ce.close()}catch{}Ee=!1,ce=null,je&&(je.close(),je=null),vt=!1,Ut(),ve=!1,ct=!1,it=null,Te.length=0,qe.clear();for(const e of kt.values())e.off();kt.clear();for(const e of mt.values())e();mt.clear(),Ft.clear(),Se.clear(),Bn(),we.clear(),me.clear();for(const e of at)e.timer&&(clearTimeout(e.timer),e.timer=null);at.length=0;for(const e of Ne())e.bpTimer&&(clearTimeout(e.bpTimer),e.bpTimer=null);Xe.length=0,Ye.length=0,Pt.clear(),Y.length=0,G.clear(),_e.length=0,Je=null}};return h.config&&Qe.configure(h.config),Qe}function ht(h,p){if(h===p)return!0;if(!h||!p)return!1;const c=Object.keys(h),m=Object.keys(p);if(c.length!==m.length)return!1;for(const S of c)if(h[S]!==p[S])return!1;return!0}const xe=Ce});const Un=zn("packages/modules/data-router/index.js"),Ur=Un.createDataRouter;var Vr=Un.default;export{Ur as createDataRouter,Vr as default};
6
+ var Kn=Object.create(null),qn=Object.create(null);function pt(y,Oe){Kn[y]=Oe}function zn(y){var Oe=qn[y];if(Oe)return Oe;var de=Object.create(null);qn[y]=de;var A=Kn[y];if(!A)throw new Error("[lattice] missing module: "+y);return A(de,zn),de}pt("packages/core/src/internal/util.js",function(y,Oe){"use strict";Object.defineProperty(y,"VERSION",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"reportedWarnings",{enumerable:!0,get:function(){return x}}),Object.defineProperty(y,"warnOnce",{enumerable:!0,get:function(){return te}}),Object.defineProperty(y,"infoOnce",{enumerable:!0,get:function(){return z}}),Object.defineProperty(y,"resetWarnings",{enumerable:!0,get:function(){return ne}}),Object.defineProperty(y,"fail",{enumerable:!0,get:function(){return $}}),Object.defineProperty(y,"invariant",{enumerable:!0,get:function(){return X}}),Object.defineProperty(y,"DEV",{enumerable:!0,get:function(){return P}}),Object.defineProperty(y,"isObject",{enumerable:!0,get:function(){return R}}),Object.defineProperty(y,"isFunction",{enumerable:!0,get:function(){return E}}),Object.defineProperty(y,"isNil",{enumerable:!0,get:function(){return N}}),Object.defineProperty(y,"isBlank",{enumerable:!0,get:function(){return H}}),Object.defineProperty(y,"isCtor",{enumerable:!0,get:function(){return q}}),Object.defineProperty(y,"pathGetter",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(y,"pathSetter",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(y,"getPath",{enumerable:!0,get:function(){return Ae}}),Object.defineProperty(y,"setPath",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(y,"humanise",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(y,"escapeHtml",{enumerable:!0,get:function(){return ht}}),Object.defineProperty(y,"titleCase",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(y,"expand",{enumerable:!0,get:function(){return h}}),Object.defineProperty(y,"toArray",{enumerable:!0,get:function(){return p}}),Object.defineProperty(y,"merge",{enumerable:!0,get:function(){return m}}),Object.defineProperty(y,"mergeRow",{enumerable:!0,get:function(){return S}}),Object.defineProperty(y,"Lru",{enumerable:!0,get:function(){return W}}),Object.defineProperty(y,"collator",{enumerable:!0,get:function(){return Be}}),Object.defineProperty(y,"defaultCompare",{enumerable:!0,get:function(){return nt}}),Object.defineProperty(y,"now",{enumerable:!0,get:function(){return Fe}}),Object.defineProperty(y,"nextFrame",{enumerable:!0,get:function(){return a}}),Object.defineProperty(y,"cancelFrame",{enumerable:!0,get:function(){return g}}),Object.defineProperty(y,"frameBatched",{enumerable:!0,get:function(){return M}}),Object.defineProperty(y,"settleDebounce",{enumerable:!0,get:function(){return G}}),Object.defineProperty(y,"whenIdle",{enumerable:!0,get:function(){return O}}),Object.defineProperty(y,"uid",{enumerable:!0,get:function(){return Y}});const de="1.86.5";async function A(){return de}const se="1.86.5",pe=new Set,re=2e3;function ke(l){if(pe.add(l),pe.size>re){const u=pe.values().next().value;u!==void 0&&pe.delete(u)}}const D=[],J=500;function le(l,u,b){D.push({key:l,level:u,message:b.map(I=>typeof I=="string"?I:C(I)).join(" "),at:Date.now()}),D.length>J&&D.shift()}function C(l){if(l instanceof Error)return l.message;try{return JSON.stringify(l)}catch{return String(l)}}function x(){return D.map(l=>({...l}))}function _(l){if(l.length===0||typeof l[0]!="string")return l;const u=l[0].replace(/^\[lattice\]\s*/,"");return u===l[0]?l:[u,...l.slice(1)]}function te(l,...u){if(pe.has(l))return;ke(l);const b=_(u);le(l,"warn",b),console.warn("[lattice]",...b)}function z(l,...u){if(pe.has(l))return;ke(l);const b=_(u);le(l,"info",b),console.info("[lattice]",...b)}function ne(){pe.clear(),D.length=0}function $(l,u){const b=new Error(`[lattice] ${l}`);throw u!==void 0&&(b.cause=u),b}function X(l,u){l||$(u)}const P=(()=>{try{return!(typeof process<"u"&&process.env&&process.env.NODE_ENV==="production")}catch{return!0}})();function R(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)}function E(l){return typeof l=="function"}function N(l){return l==null}function H(l){return l==null||l===""}function q(l){return typeof l!="function"?!1:/^class[\s{]/.test(Function.prototype.toString.call(l))?!0:!!(l.prototype&&Object.getOwnPropertyNames(l.prototype).length>1)}const K=new Map;function ae(l){let u=K.get(l);if(u)return u;if(!l.includes("."))u=b=>b?.[l];else{const b=l.split("."),I=b.length;u=ve=>{let ie=ve;for(let he=0;he<I;he++){if(ie==null)return;ie=ie[b[he]]}return ie}}return K.set(l,u),u}const We=new Map;function Le(l){let u=We.get(l);if(u)return u;if(!l.includes("."))u=(b,I)=>{b!=null&&(b[l]=I)};else{const b=l.split("."),I=b.length-1;u=(ve,ie)=>{let he=ve;for(let ge=0;ge<I;ge++){if(he==null)return;const qe=b[ge];he[qe]==null&&(he[qe]={}),he=he[qe]}he!=null&&(he[b[I]]=ie)}}return We.set(l,u),u}function Ae(l,u){return ae(u)(l)}function ue(l,u,b){Le(u)(l,b)}function oe(l){return l?(l.includes(".")?l.slice(l.lastIndexOf(".")+1):l).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/\s+/g," ").trim().replace(/^./,b=>b.toUpperCase()):""}const Ce={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function ht(l){const u=l==null?"":String(l);return/[&<>"']/.test(u)?u.replace(/[&<>"']/g,b=>Ce[b]):u}function xe(l){return String(l).replace(/\w\S*/g,u=>u[0].toUpperCase()+u.slice(1).toLowerCase())}function h(l,u,b){if(l!==void 0)return l===!0?{enabled:!0,...b}:l===!1?{enabled:!1}:R(l)?l:{[u]:l,enabled:!0}}function p(l){return l==null?[]:Array.isArray(l)?l:[l]}const c=Object.freeze(new Set(["__proto__","constructor","prototype"]));function m(l,u){if(!R(l))return R(u)?{...u}:u;if(!R(u))return u===void 0?l:u;const b={...l};for(const I of Object.keys(u)){if(c.has(I))continue;const ve=u[I];ve!==void 0&&(b[I]=R(ve)&&R(b[I])?m(b[I],ve):ve)}return b}function S(l,u){if(!R(l)||!R(u)||l===u)return u;const b=Object.create(Object.getPrototypeOf(l));return Object.assign(b,l,u),b}class W{#e;#t=new Map;#n;constructor(u=256,b=null){this.#e=u,this.#n=b}get size(){return this.#t.size}get max(){return this.#e}set max(u){this.#e=u,this.#r()}has(u){return this.#t.has(u)}get(u){const b=this.#t;if(!b.has(u))return;const I=b.get(u);return b.delete(u),b.set(u,I),I}peek(u){return this.#t.get(u)}set(u,b){const I=this.#t;return I.has(u)&&I.delete(u),I.set(u,b),this.#r(),b}delete(u){const b=this.#t.get(u);return this.#t.delete(u)&&this.#n&&this.#n(b,u),b}clear(){if(this.#n)for(const[u,b]of this.#t)this.#n(b,u);this.#t.clear()}keys(){return this.#t.keys()}values(){return this.#t.values()}#r(){const u=this.#t;for(;u.size>this.#e;){const b=u.keys().next().value,I=u.get(b);u.delete(b),this.#n&&this.#n(I,b)}}}const U=new Map;function Be(l,u){const b=`${l||""}|${u?JSON.stringify(u):""}`;let I=U.get(b);return I||(I=new Intl.Collator(l||void 0,{numeric:!0,sensitivity:"variant",...u}),U.set(b,I)),I}function nt(l,u){if(l===u)return 0;if(l==null)return 1;if(u==null)return-1;if(typeof l=="number"&&typeof u=="number")return Number.isNaN(l)?Number.isNaN(u)?0:1:Number.isNaN(u)||l<u?-1:l>u?1:0;const b=String(l),I=String(u);return b<I?-1:b>I?1:0}function Fe(){return typeof performance<"u"&&performance.now?performance.now():Date.now()}const Ze=typeof requestAnimationFrame=="function";function a(l){return Ze?requestAnimationFrame(l):setTimeout(()=>l(Fe()),16)}function g(l){l!=null&&(Ze?cancelAnimationFrame(l):clearTimeout(l))}function M(l){let u=null,b=null;const I=()=>{u=null;const ie=b;b=null,l(...ie||[])},ve=(...ie)=>{b=ie,u===null&&(u=a(I))};return ve.cancel=()=>{g(u),u=null,b=null},ve.flush=()=>{u!==null&&(g(u),I())},ve}function G(l,u){let b=null,I=null;const ve=()=>{if(b=null,I===null)return;const ge=I;I=null,l(...ge),ie()},ie=()=>{b=setTimeout(ve,u),typeof b?.unref=="function"&&b.unref()},he=(...ge)=>{b===null?(l(...ge),ie()):(I=ge,clearTimeout(b),ie())};return he.flush=()=>{if(b!==null&&clearTimeout(b),b=null,I===null)return;const ge=I;I=null,l(...ge)},he.cancel=()=>{b!==null&&clearTimeout(b),b=null,I=null},he.pending=()=>b!==null||I!==null,he}function O(l,u=50){return typeof requestIdleCallback=="function"?requestIdleCallback(l,{timeout:u}):setTimeout(()=>l({timeRemaining:()=>0,didTimeout:!0}),1)}let Q=0;function Y(l="l"){return`${l}${(++Q).toString(36)}`}}),pt("packages/core/src/source/filterwire.js",function(y,Oe){"use strict";Object.defineProperty(y,"HOST_FILTER_WARN_ID",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"WHERE_PAGE_RELATIVE_WARN_ID",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(y,"warnWherePageRelative",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"warnHostFilterNotApplied",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(y,"WHERE_NOT_APPLIED_WARN_ID",{enumerable:!0,get:function(){return D}}),Object.defineProperty(y,"warnWhereNotApplied",{enumerable:!0,get:function(){return J}}),Object.defineProperty(y,"WHERE_OVER_THRESHOLD_WARN_ID",{enumerable:!0,get:function(){return le}}),Object.defineProperty(y,"warnWhereOverThreshold",{enumerable:!0,get:function(){return C}}),Object.defineProperty(y,"RELATIVE_TOKENS",{enumerable:!0,get:function(){return P}}),Object.defineProperty(y,"parseRelativeToken",{enumerable:!0,get:function(){return R}}),Object.defineProperty(y,"resolveRelativeRange",{enumerable:!0,get:function(){return E}}),Object.defineProperty(y,"relativeTokenOf",{enumerable:!0,get:function(){return N}}),Object.defineProperty(y,"relativeTokenHelp",{enumerable:!0,get:function(){return H}}),Object.defineProperty(y,"isResolvableRelative",{enumerable:!0,get:function(){return q}}),Object.defineProperty(y,"resolveRelativeCondition",{enumerable:!0,get:function(){return K}}),Object.defineProperty(y,"isGroup",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(y,"forEachCondition",{enumerable:!0,get:function(){return We}}),Object.defineProperty(y,"mapConditions",{enumerable:!0,get:function(){return Le}}),Object.defineProperty(y,"normaliseFilterSet",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(y,"buildFilterSet",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(y,"wireFilters",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(y,"querySignature",{enumerable:!0,get:function(){return ht}});const A=Oe("packages/core/src/internal/util.js").warnOnce,se="source.remote.hostFilter",pe="source.where.pageRelative";function re(p,c){!Array.isArray(p)||!p.length||A(pe,`filters.where (${p.join(", ")}) runs over the rows the ${c} source fetched,`,"not the whole dataset: match counts and totals are page-relative.","Give the predicate a { condition } twin so the engine can narrow the fetch itself.")}function ke(p){const c=(p||{}).config;!c||!c.hostFilter||A(se,"config.hostFilter is not sent to a server-delegated source (paged/remote) and is not applied:","filtering only the fetched window would give wrong counts and totals.","Express the filter as a FilterSet condition, or send it through config.context.")}const D="source.where.notApplied";function J(p,c){A(`${D}:${p}`,`filters.where("${p}") is registered but the ${c} source holds only its fetched window`,"and cannot run the predicate over it: the predicate is not applied there, and rows it would","exclude stay on screen.","Give it a { condition } twin so the engine can narrow the fetch itself — that is the","supported route for a paged or remote source.")}const le="source.where.overThreshold";function C(p,c,m,S){!Array.isArray(p)||!p.length||A(`${le}:${c}`,`filters.where (${p.join(", ")}) is not applied to the ${c} pushdown source:`,m===null?"the adapter reports no row total, so the size of the matching set is unknown.":`its matching set is ${m.toLocaleString()} rows, at or past the whereRowLimit of ${S.toLocaleString()}.`,"Running the predicate needs every matching row fetched and held here, which is the whole","download a pushdown source exists to avoid, so it is refused and the rows the predicate","would exclude stay on screen.","Give the predicate a { condition } twin so the engine narrows the fetch itself — that is the","route that works at any size — or raise `whereRowLimit` on the source config if you want the","download.")}const x=new Map;function _(p){let c=x.get(p);return c||(c=new Intl.DateTimeFormat("en-US",{timeZone:p,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),x.set(p,c)),c}function te(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function z(p,c){const m=_(c).formatToParts(new Date(p)),S={y:1970,m:1,d:1,h:0,mi:0,s:0};for(const W of m)W.type==="year"?S.y=+W.value:W.type==="month"?S.m=+W.value:W.type==="day"?S.d=+W.value:W.type==="hour"?S.h=+W.value%24:W.type==="minute"?S.mi=+W.value:W.type==="second"&&(S.s=+W.value);return S}function ne(p,c){const m=z(p,c);return Date.UTC(m.y,m.m-1,m.d,m.h,m.mi,m.s)-Math.floor(p/1e3)*1e3}function $(p,c,m,S){const W=Date.UTC(p,c-1,m),U=W-ne(W,S);return W-ne(U,S)}function X(p,c,m){const S=new Date(Date.UTC(p.y,p.m-1,p.d+c));return $(S.getUTCFullYear(),S.getUTCMonth()+1,S.getUTCDate(),m)}const P=Object.freeze(["today","yesterday","lastNDays","thisWeek","thisMonth","thisQuarter","thisYear","quarterToDate","yearToDate"]);function R(p,c){if(typeof p!="string")return null;const m=p.trim().toLowerCase().replace(/[\s_-]+/g,""),S=/^last(\d*|n)days?$/.exec(m);if(S){const W=S[1]==="n"?"":S[1],U=Number(W||c);return!Number.isFinite(U)||U<=0?null:{kind:"lastNDays",n:Math.floor(U)}}switch(m){case"today":return{kind:"today",n:0};case"yesterday":return{kind:"yesterday",n:0};case"thisweek":return{kind:"thisWeek",n:0};case"thismonth":return{kind:"thisMonth",n:0};case"thisquarter":return{kind:"thisQuarter",n:0};case"thisyear":return{kind:"thisYear",n:0};case"quartertodate":case"qtd":return{kind:"quarterToDate",n:0};case"yeartodate":case"ytd":return{kind:"yearToDate",n:0};default:return null}}function E(p,c={}){const m=R(p,c.n);if(!m)return null;const S=c.tz||te(),W=c.now instanceof Date?c.now.getTime():typeof c.now=="number"?c.now:Date.now(),U=z(W,S),Be=$(U.y,U.m,U.d,S),nt=X(U,1,S);let Fe=Be,Ze=nt;switch(m.kind){case"today":break;case"yesterday":Fe=X(U,-1,S),Ze=Be;break;case"lastNDays":Ze=c.includeToday?nt:Be,Fe=X(U,c.includeToday?-(m.n-1):-m.n,S);break;case"thisWeek":{const a=Number.isFinite(c.weekStartsOn)?Number(c.weekStartsOn):1,M=(new Date(Date.UTC(U.y,U.m-1,U.d)).getUTCDay()-a+7)%7;Fe=X(U,-M,S),Ze=X(U,-M+7,S);break}case"thisMonth":Fe=$(U.y,U.m,1,S),Ze=$(U.m===12?U.y+1:U.y,U.m===12?1:U.m+1,1,S);break;case"thisQuarter":case"quarterToDate":{const a=Math.floor((U.m-1)/3)*3+1;Fe=$(U.y,a,1,S),Ze=m.kind==="quarterToDate"?nt:a===10?$(U.y+1,1,1,S):$(U.y,a+3,1,S);break}case"thisYear":case"yearToDate":Fe=$(U.y,1,1,S),Ze=m.kind==="yearToDate"?nt:$(U.y+1,1,1,S);break;default:return null}return{from:new Date(Fe).toISOString(),to:new Date(Ze).toISOString(),bounds:"[)",tz:S,relative:m.kind==="lastNDays"?`last${m.n}Days`:m.kind,n:m.n}}function N(p){if(!p||typeof p!="object")return null;const c=p.value;if(c&&typeof c=="object"&&!Array.isArray(c)&&"relative"in c)return{token:String(c.relative),n:typeof c.n=="number"?c.n:void 0};if(p.op==="relative"&&typeof p.value=="string")return{token:p.value,n:void 0};const m=p.meta;return m&&typeof m.relative=="string"&&p.value===void 0?{token:m.relative,n:typeof m.n=="number"?m.n:void 0}:null}function H(){return`Known tokens: ${P.filter(c=>c!=="lastNDays").join(", ")}. "lastNDays" needs a count: pass "last7Days", or the value object { relative: 'lastNDays', n: 7 }.`}function q(p){const c=N(p);return c?R(c.token,c.n)!==null:!1}function K(p,c={}){const m=N(p);if(!m)return p;const S=E(m.token,{...c,n:m.n});return S?{...p,type:p.type||"date",op:"between",value:[S.from,S.to],bounds:p.bounds||S.bounds,meta:{...p.meta||{},relative:S.relative,tz:S.tz}}:(A(`source.relative.${m.token}`,`unknown relative date token "${m.token}"; sending the condition unresolved.`,H()),p)}function ae(p){return!!p&&typeof p=="object"&&Array.isArray(p.conditions)}function We(p,c){if(p){if(ae(p)){for(const m of p.conditions)We(m,c);return}c(p)}}function Le(p,c){if(!p)return null;if(!ae(p))return c(p);const m=p;let S=!1;const W=[];for(const U of m.conditions){const Be=Le(U,c);Be!==U&&(S=!0),Be&&W.push(Be)}return!S&&W.length===m.conditions.length?p:W.length?{...m,conditions:W}:null}function Ae(p){if(!p)return null;if(!ae(p))return p;const c=p,m=[];for(const S of c.conditions){const W=Ae(S);W&&m.push(W)}return m.length?{op:c.op,conditions:m}:null}function ue(p){const c=Ae(p);return c?ae(c)&&c.op==="and"?c:{op:"and",conditions:[c]}:null}function oe(p){const c=(p||[]).filter(Boolean);return c.length?{op:"and",conditions:c}:null}function Ce(p,c={}){const m=Le(p,S=>K(S,c));return ue(m)}function ht(p){const c=xe(p.filters??null);return JSON.stringify([c,p.sort??null,p.quick??"",p.groupBy??null,p.pivotBy??null,h(p.context)])}function xe(p){if(!p)return null;if(ae(p)){const S=p;return{op:S.op,conditions:S.conditions.map(xe)}}const c=p,m=c.meta&&typeof c.meta.relative=="string"?c.meta.relative:N(c)?.token;return{col:c.col,op:c.op,bounds:c.bounds??null,caseSensitive:c.caseSensitive??!1,value:m?`rel:${m}`:c.value??null}}function h(p){if(p==null)return null;try{return JSON.parse(JSON.stringify(p))}catch{return A("source.context.unserialisable","config.context is not JSON-serialisable; cache keys ignore it."),"[unserialisable]"}}}),pt("packages/core/src/source/aggregates.js",function(y,Oe){"use strict";Object.defineProperty(y,"STAT_PUSHDOWN",{enumerable:!0,get:function(){return de}}),Object.defineProperty(y,"pushableAggregates",{enumerable:!0,get:function(){return A}}),Object.defineProperty(y,"fillAggregateSql",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"resolveAggregatesConfig",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(y,"routeAggregate",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"resolveAggregatePlan",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(y,"groupKeysPushable",{enumerable:!0,get:function(){return J}}),Object.defineProperty(y,"pushdownDocRows",{enumerable:!0,get:function(){return le}});const de=Object.freeze({sum:{pushable:!0,class:"identical",sql:"sum(%c)"},avg:{pushable:!0,class:"identical",sql:"avg(%c)"},min:{pushable:!0,class:"identical",sql:"min(%c)"},max:{pushable:!0,class:"identical",sql:"max(%c)"},count:{pushable:!0,class:"identical",sql:"count(*)"},countValues:{pushable:!0,class:"identical",sql:"count(%c)",blankAware:!0},range:{pushable:!0,class:"identical",sql:"(max(%c) - min(%c))"},variance:{pushable:!0,class:"identical",sql:"var_samp(%c)"},varianceP:{pushable:!0,class:"identical",sql:"var_pop(%c)"},stddev:{pushable:!0,class:"identical",sql:"stddev_samp(%c)"},stddevP:{pushable:!0,class:"identical",sql:"stddev_pop(%c)"},sumSquares:{pushable:!0,class:"identical",sql:"sum(%c * %c)"},median:{pushable:!0,class:"identical",sql:"median(%c)"},p25:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.25)"},p75:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.75)"},p90:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.9)"},p95:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.95)"},p99:{pushable:!0,class:"identical",sql:"quantile_cont(%c, 0.99)"},iqr:{pushable:!0,class:"identical",sql:"(quantile_cont(%c, 0.75) - quantile_cont(%c, 0.25))"},mad:{pushable:!0,class:"identical",sql:"mad(%c)"},distinct:{pushable:!0,class:"identical",sql:"count(DISTINCT %c)",blankAware:!0},skewness:{pushable:!0,class:"identical",sql:"skewness(%c)"},kurtosis:{pushable:!0,class:"identical",sql:"kurtosis(%c)"},geomean:{pushable:!0,class:"identical",sql:"exp(avg(ln(%c)))"},harmean:{pushable:!0,class:"identical",sql:"(count(%c) / sum(1.0 / %c))"},entropy:{pushable:!0,class:"identical",sql:"entropy(%c)",blankAware:!0},correlation:{pushable:!0,class:"identical",sql:"corr(%w, %c)",twoColumn:!0},hhi:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL ELSE list_sum(list_transform(map_values(histogram(%c)), lambda v: (v::DOUBLE/count(%c))*(v::DOUBLE/count(%c)))) END"},evenness:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL WHEN count(DISTINCT %c)<2 THEN 1.0 ELSE entropy(%c)/log2(count(DISTINCT %c)) END"},top3Share:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL ELSE list_sum(list_slice(list_sort(map_values(histogram(%c)),'DESC'),1,3))::DOUBLE/count(%c) END"},top10Share:{pushable:!0,class:"identical",blankAware:!0,sql:"CASE WHEN count(%c)=0 THEN NULL ELSE list_sum(list_slice(list_sort(map_values(histogram(%c)),'DESC'),1,10))::DOUBLE/count(%c) END"},gini:{pushable:!0,class:"identical",sql:"CASE WHEN list_min(list(%c) FILTER (WHERE isfinite(%c)))<0 THEN NULL WHEN len(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN NULL WHEN list_sum(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN 0 ELSE 2.0*list_sum(list_transform(list_sort(list(%c) FILTER (WHERE isfinite(%c))), lambda v, i: i*v))/(len(list(%c) FILTER (WHERE isfinite(%c)))*list_sum(list(%c) FILTER (WHERE isfinite(%c))))-(len(list(%c) FILTER (WHERE isfinite(%c)))+1.0)/len(list(%c) FILTER (WHERE isfinite(%c))) END"},trimmedMean:{pushable:!0,class:"identical",sql:"CASE WHEN len(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN NULL ELSE list_avg(list_slice(list_sort(list(%c) FILTER (WHERE isfinite(%c))), floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT+1, len(list(%c) FILTER (WHERE isfinite(%c)))-floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT)) END"},winsorizedMean:{pushable:!0,class:"identical",sql:"CASE WHEN len(list(%c) FILTER (WHERE isfinite(%c)))=0 THEN NULL ELSE list_avg(list_transform(list_sort(list(%c) FILTER (WHERE isfinite(%c))), lambda v: least(list_sort(list(%c) FILTER (WHERE isfinite(%c)))[len(list(%c) FILTER (WHERE isfinite(%c)))-floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT], greatest(list_sort(list(%c) FILTER (WHERE isfinite(%c)))[floor(len(list(%c) FILTER (WHERE isfinite(%c)))*0.1)::BIGINT+1], v)))) END"},robustOutliers:{pushable:!0,class:"identical",sql:"(SELECT CASE WHEN len(d.a)=0 THEN NULL WHEN d.mad=0 THEN NULL ELSE len(list_filter(d.a, lambda v: abs(0.6745*(v-d.med)/d.mad)>3.5)) END FROM (SELECT xs AS a, list_median(xs) AS med, list_median(list_transform(xs, lambda w: abs(w-list_median(xs)))) AS mad FROM (SELECT list(%c) FILTER (WHERE isfinite(%c)) AS xs)) d)"},jarqueBera:{pushable:!0,class:"identical",sql:"CASE WHEN len(list(%c) FILTER (WHERE isfinite(%c)))<8 THEN NULL WHEN list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),2)))=0 THEN NULL ELSE (len(list(%c) FILTER (WHERE isfinite(%c)))/6.0)*(power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),3)))/power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),2))),1.5),2)+power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),4)))/power(list_avg(list_transform(list(%c) FILTER (WHERE isfinite(%c)), lambda v: power(v-list_avg(list(%c) FILTER (WHERE isfinite(%c))),2))),2)-3,2)/4.0) END"},weightedAvg:{pushable:!0,class:"identical",twoColumn:!0,sql:"sum(%c*%w) FILTER (WHERE isfinite(%c) AND isfinite(%w))/nullif(sum(%w) FILTER (WHERE isfinite(%c) AND isfinite(%w)),0)"},mode:{pushable:!0,class:"may-differ",sql:"mode(%c)",note:"DuckDB returns a modal value even for an all-distinct column; the grid returns null. Tie-breaking can also differ, and on a text column an empty string counts as a value. Under pushdown you will see a value."},weightedQuantile:{pushable:!1,class:"fallback",note:"No SQL equivalent for the grid's weighted-quantile midpoint convention; always computed client-side (needs a full-dataset pull for a correct figure over a remote source)."}});function A(){const C=new Set;for(const[x,_]of Object.entries(de))_.pushable&&C.add(x);return C}function se(C,x,_){let te=C.split("%c").join(x);return _!==void 0&&(te=te.split("%w").join(_)),te}function pe(C){const x=C||{},_=x.default==="engine"||x.default==="engine-if-identical"?x.default:"client",te={};if(x.overrides&&typeof x.overrides=="object")for(const[z,ne]of Object.entries(x.overrides))(ne==="engine"||ne==="client")&&(te[z]=ne);return{default:_,overrides:te}}function re(C,x){const _=de[C];if(!_||!_.pushable)return"client";const te=x.overrides[C];return te==="engine"||te==="client"?te:x.default==="client"?"client":x.default==="engine-if-identical"?_.class==="identical"?"engine":"client":"engine"}function ke(C,x){const _=pe(x),te=[],z=[];for(const ne of C||[]){const $=de[ne.fn],X=re(ne.fn,_),P={id:ne.id,col:ne.col,fn:ne.fn,class:$?$.class:"fallback"};ne.weight!==void 0&&(P.weight=ne.weight),ne.params!==void 0&&(P.params=ne.params),X==="engine"?te.push(P):(P.reason=$&&!$.pushable?$.note||"the engine cannot express this stat":"client by config",z.push(P))}return{engine:te,client:z,config:_}}const D=/^[A-Za-z_][A-Za-z0-9_$]*$/;function J(C,x=[]){return(C||[]).every(te=>{if(typeof te=="string")return D.test(te);if(!te||typeof te!="object")return!1;const z=te;return Array.isArray(x)&&x.includes(z.bucket)&&typeof z.col=="string"&&D.test(z.col)&&typeof z.size=="number"&&Number.isFinite(z.size)&&z.size>0})}function le(){return Object.entries(de).map(([C,x])=>({stat:C,class:x.class,sql:x.sql?se(x.sql,"col",x.twoColumn?"weight":void 0):"",note:x.note||(x.class==="identical"?"Pushes to DuckDB with the same result.":"")}))}}),pt("packages/core/src/source/abort.js",function(y,Oe){"use strict";Object.defineProperty(y,"SupersededError",{enumerable:!0,get:function(){return de}}),Object.defineProperty(y,"RequestToken",{enumerable:!0,get:function(){return A}}),Object.defineProperty(y,"AbortScope",{enumerable:!0,get:function(){return se}}),Object.defineProperty(y,"createAbortScope",{enumerable:!0,get:function(){return pe}}),Object.defineProperty(y,"isAbortError",{enumerable:!0,get:function(){return re}});class de extends Error{constructor(D,J="superseded"){super(`[lattice] request ${D?`"${D}" `:""}${J}`),this.name="SupersededError",this.superseded=!0,this.key=D}}class A{#e;constructor(D,J,le,C){this.#e=D,this.key=J,this.controller=le,this.signal=le.signal,this.seq=C}get current(){return!this.signal.aborted&&this.#e.tokenFor(this.key)===this}settle(){this.#e.settle(this)}abort(D){this.signal.aborted||this.controller.abort(new de(this.key,D)),this.#e.settle(this)}}class se{#e=new Map;#t=0;begin(D="",J="superseded"){const le=this.#e.get(D);le&&!le.signal.aborted&&le.controller.abort(new de(D,J));const C=new A(this,D,new AbortController,++this.#t);return this.#e.set(D,C),C}tokenFor(D){return this.#e.get(D)}pending(D=""){const J=this.#e.get(D);return!!J&&!J.signal.aborted}get size(){return this.#e.size}settle(D){this.#e.get(D.key)===D&&this.#e.delete(D.key)}abort(D="",J="superseded"){const le=this.#e.get(D);le&&le.abort(J)}abortAll(D="superseded"){for(const J of[...this.#e.values()])J.abort(D);this.#e.clear()}}function pe(){return new se}function re(ke){if(!ke||typeof ke!="object")return!1;const D=ke;return D.superseded===!0||D.name==="AbortError"||D.name==="SupersededError"}}),pt("packages/core/src/source/pushdown.js",function(y,Oe){"use strict";Object.defineProperty(y,"FOREGROUND_WAIT_MS",{enumerable:!0,get:function(){return $}}),Object.defineProperty(y,"NO_CAPABILITIES",{enumerable:!0,get:function(){return P}}),Object.defineProperty(y,"resolveMutate",{enumerable:!0,get:function(){return R}}),Object.defineProperty(y,"capabilitiesOf",{enumerable:!0,get:function(){return H}}),Object.defineProperty(y,"splitFilters",{enumerable:!0,get:function(){return K}}),Object.defineProperty(y,"LEAF_COUNT_ID",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(y,"PIVOT_UNSUPPORTED",{enumerable:!0,get:function(){return ue}}),Object.defineProperty(y,"GROUP_UNSUPPORTED",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(y,"UNGROUPED_LEVEL",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(y,"planQuery",{enumerable:!0,get:function(){return xe}}),Object.defineProperty(y,"applyResidual",{enumerable:!0,get:function(){return c}}),Object.defineProperty(y,"DEFAULT_WHERE_ROW_LIMIT",{enumerable:!0,get:function(){return U}}),Object.defineProperty(y,"createPushdownSource",{enumerable:!0,get:function(){return Ze}});const de=Oe("packages/core/src/internal/util.js"),A=de.defaultCompare,se=de.isFunction,pe=de.toArray,re=de.warnOnce,ke=Oe("packages/core/src/source/filterwire.js"),D=ke.isGroup,J=ke.warnWherePageRelative,le=ke.warnWhereOverThreshold,C=Oe("packages/core/src/source/aggregates.js"),x=C.resolveAggregatePlan,_=C.groupKeysPushable,te=C.STAT_PUSHDOWN,ne=Oe("packages/core/src/source/abort.js").SupersededError,$=1e3;function X(a){const g=a&&a.signal;if(!g||!g.aborted)return;const M=g.reason;throw M instanceof Error?M:new ne("","superseded before it was sent")}const P=Object.freeze({filter:!1,operators:Object.freeze([]),sort:!1,quick:!1,range:!1,total:!1,group:!1,pivot:!1,mutate:!1});function R(a){if(!a||typeof a!="object")return!1;const g=a.returning==="row"||a.returning==="key"?a.returning:"none";return{append:a.append===!0,update:a.update===!0,delete:a.delete===!0,returning:g}}function E(a,g){if(!a||typeof g!="string")return;if(!g.includes("."))return a[g];let M=a;for(const G of g.split(".")){if(M===null||typeof M!="object")return;M=M[G]}return M}function N(a){if(a===!0)return!0;if(!a||typeof a!="object")return!1;const g=a;return g.enabled===!1?!1:g.enabled===!0||se(g.commit)}function H(a){const g={...P,...a||{}};return g.operators=new Set(g.operators||[]),g.mutate=R(g.mutate),g}function q(a,g){return!a||!a.op||!g.operators.size?!1:g.operators.has(a.op)}function K(a,g){if(!a)return{pushed:null,residual:null};if(!g.filter)return{pushed:null,residual:a};if(g.filter==="term"){if(D(a)){const Q=a.conditions||[];if(String(a.op)!=="and")return{pushed:null,residual:a};const Y=Q.findIndex(u=>!D(u)&&q(u,g));if(Y<0)return{pushed:null,residual:a};const l=Q.filter((u,b)=>b!==Y);return{pushed:Q[Y],residual:l.length?{op:"and",conditions:l}:null}}return q(a,g)?{pushed:a,residual:null}:{pushed:null,residual:a}}if(!D(a))return q(a,g)?{pushed:a,residual:null}:{pushed:null,residual:a};if(String(a.op)!=="and")return(a.conditions||[]).every(Y=>D(Y)?K(Y,g).residual===null:q(Y,g))?{pushed:a,residual:null}:{pushed:null,residual:a};const M=[],G=[];for(const Q of a.conditions||[]){if(D(Q)){if(g.filter==="flat"){G.push(Q);continue}const Y=K(Q,g);Y.pushed&&M.push(Y.pushed),Y.residual&&G.push(Y.residual);continue}(q(Q,g)?M:G).push(Q)}const O=Q=>Q.length===0?null:Q.length===1?Q[0]:{op:"and",conditions:Q};return{pushed:O(M),residual:O(G)}}const ae="__lattice_leaves";function We(a){return a.aggregates?a.aggregates instanceof Set?a.aggregates:new Set(pe(a.aggregates)):new Set}function Le(a){const g=We(a);return g.size?g.has("count")?a.filter!=="tree"||!a.operators||!a.operators.has("eq")?"the adapter does not declare the `group` capability, and cannot narrow a group's rows by its key (that needs a `tree` filter with the `eq` operator)":"":"the adapter does not declare the `group` capability, and its declared aggregates have no `count` to give each group its row count":"the adapter does not declare the `group` capability"}function Ae(a,g,M,G,O,Q,Y){const l=Array.isArray(a.groupBy)?a.groupBy:[],u=Array.isArray(a.groupPath)?a.groupPath:[],b=Array.isArray(a.groupValues)?a.groupValues:null;if(!g.group){const I=Le(g);if(I)return I}return _(l)?M.residual?"the filter did not fully push, so the engine would group a superset of the matching rows":G?O?Q?"a host `where` predicate can only run in the browser, over rows the engine grouped":Y?"fullDataset holds the whole matching set, so the grid groups it itself":!b||b.length!==u.length?"the request carries no typed `groupValues` for its group path, and the string `groupPath` cannot be compared against a typed column":"":"a quick search did not push, so the engine would group unsearched rows":"the sort did not push, so the engine would order the groups differently":"a grouping key is not a plain column the engine can name in a GROUP BY"}const ue="pushdown:pivot-unsupported",oe="pushdown:group-unsupported",Ce=Symbol("lattice.remote.ungroupedLevel");function ht(a,g,M,G,O,Q){const Y=Array.isArray(a.pivotBy)?a.pivotBy:[],l=Array.isArray(a.groupBy)?a.groupBy:[],u=Array.isArray(a.groupPath)?a.groupPath:[],b=Array.isArray(a.groupValues)?a.groupValues:null;return g.pivot?_(Y)?l.length&&!_(l)?"a grouping key is not a plain column the engine can name in a GROUP BY":M.residual?"the filter did not fully push, so the engine would pivot a superset of the matching rows":G?O?Q?"a host `where` predicate can only run in the browser, over rows the engine pivoted":!b||b.length!==u.length?"the request carries no typed `groupValues` for its group path, and the string `groupPath` cannot be compared against a typed column":"":"a quick search did not push, so the engine would pivot unsearched rows":"the sort did not push, so the engine would order the rows differently":"a pivot column is not a plain column the engine can name in a GROUP BY":"the adapter does not declare the `pivot` capability"}function xe(a,g,M=!1){const G=K(a.filters||null,g),O=[];G.residual&&O.push("filter");const Q=a.sort||[],Y=Q.length===0||g.sort==="multi"&&Q.length>=1||g.sort==="single"&&Q.length===1;!Y&&Q.length&&O.push("sort");const l=a.quick?String(a.quick):"",u=!l||!!g.quick;u||O.push("quick");const b=a.where&&a.where.active?a.where:null;b&&O.push("where");const I={filters:G.residual,sort:Y?null:Q,quick:u?"":l,where:b},ve=!!M,ie=Array.isArray(a.groupBy)&&a.groupBy.length>0,he=ie?Ae(a,g,G,Y,u,b,ve):"",ge=a.pivotMode!==!1&&Array.isArray(a.pivotBy)&&a.pivotBy.length>0,qe=ge?ht(a,g,G,Y,u,b):"",Te=ge&&qe==="";ge&&!Te&&O.push("pivot");const ze=ge?Te&&ie:ie&&he==="";ie&&!ge&&!ze&&O.push("group");const $e=(ze||Te)&&Array.isArray(a.groupValues)?a.groupValues.length:0,ut=ze||ge?!1:ve||!!(I.filters||I.sort||I.quick||I.where)||!g.range;return{pushed:{...a,filters:G.pushed,sort:Y?Q:[],quick:u?l:"",range:ut?null:a.range},residual:I,needsAll:ut,unpushed:O,full:ve,grouped:ze,groupLevel:$e,groupReason:ge?"":he,pivoted:Te,pivotReason:qe}}function h(a){const g=Array.isArray(a.totals)?a.totals:[],M=a.totalFns&&typeof a.totalFns=="object"?a.totalFns:{},G=[],O=[];for(const Q of g){const Y=String(Q),l=typeof M[Y]=="string"?M[Y]:null,u=l?te[l]:null;l?!u||!u.pushable||!u.sql?O.push({id:Y,fn:l,class:u?u.class:"fallback",reason:u&&u.note?u.note:`the pushdown map cannot express "${l}"`}):u.twoColumn?O.push({id:Y,fn:l,class:u.class,reason:`"${l}" reduces two columns, and a grouped request carries no weight column`}):G.push({id:Y,col:Y,fn:l,class:u.class}):O.push({id:Y,fn:null,class:"fallback",reason:"the column totals with a host function, so there is no named statistic to push"})}return{engine:G,client:O}}const p=Object.freeze({items:a=>a==null?[]:Array.isArray(a)?a:[a]});function c(a,g,M){if(!g)return a;let G=a;if(g.filters&&se(M.evaluateFilters)){const O=G,Q={count:G.length,handle:u=>({id:u,get:b=>E(O[b],u)}),itemwise:u=>O.some(b=>Array.isArray(E(b,u)))?p:null},Y=M.evaluateFilters(g.filters,Q),l=[];for(let u=0;u<G.length;u++)Y[u]&&l.push(G[u]);G=l}if(g.where&&g.where.active&&(g.whole||J(g.where.names,"pushdown"),G=G.filter(O=>g.where.passes(O))),g.quick){const O=g.quick.toLowerCase();G=G.filter(Q=>{if(!Q||typeof Q!="object")return!1;for(const Y of Object.values(Q))if(Y!=null&&String(Y).toLowerCase().includes(O))return!0;return!1})}if(g.sort&&g.sort.length&&se(M.sortMulti)){const O=[...new Set(g.sort.map(u=>u.col))],Q=G,Y=O.map(u=>({id:u,get:b=>E(Q[b],u)})),l=M.sortMulti(Y,g.sort.map(u=>({col:u.col,dir:u.dir})),Uint32Array.from({length:G.length},(u,b)=>b),{});G=Array.from(l,u=>Q[u])}return G}function m(a){return JSON.stringify({filters:a.filters||null,sort:a.sort||[],quick:a.quick||"",groupBy:a.groupBy||[],groupPath:a.groupPath||[],context:a.context??null})}function S(a){if(!a||typeof a!="object")return 16;let g="";try{g=JSON.stringify(a)}catch{return 200}return g.length*2+64}function W(a){const g=a||{};return{enabled:!!g.enabled,maxRows:Number.isFinite(g.maxRows)?g.maxRows:1e6,maxBytesEstimate:Number.isFinite(g.maxBytesEstimate)?g.maxBytesEstimate:512*1024*1024}}const U=5e4;function Be(a){return Number.isFinite(a)&&a>=0?a:U}function nt(a){return!!a&&se(a.then)}async function Fe(a){if(!a||a.total!==void 0||!nt(a.pendingTotal))return a;const g=await a.pendingTotal,{pendingTotal:M,...G}=a;return typeof g=="number"?{...G,total:g}:G}function Ze(a={}){const g=a.adapter;if(!g||!se(g.execute))return re("source.pushdown.adapter","createPushdownSource needs an `adapter` with an `execute(query)` function."),{...a,mode:"remote",fetch:async()=>({rows:[],total:0})};const M=H(g.capabilities),G=g.capabilities&&Object.getOwnPropertyDescriptor(g.capabilities,"operators");G&&se(G.get)&&Object.defineProperty(M,"operators",{enumerable:!0,configurable:!0,get:()=>new Set(g.capabilities.operators||[]),set:()=>{}});const O=g.name||"adapter";let Q=null;const Y=()=>se(g.ready)?(Q||(Q=Promise.resolve(g.ready()).then(()=>{Object.assign(M,H(g.capabilities))},F=>{throw Q=null,F})),Q):null,l=W(a.fullDataset),u=!!a.allowPartialResults,b=Be(a.whereRowLimit);let I=null;const ve=a.aggregates;let ie=null,he=null,ge=null,qe=null,Te=null,ze,$e=null,ut=0,ct=null;const it=()=>!l.enabled||!ie?null:(ct!==ie.key&&(ut++,ct=ie.key),{rows:ie.rows,version:ut}),Et=async F=>{const L=F.where&&F.where.active?F.where:null;if(!L)return{request:F,probe:null};const{where:Z,...V}=F,T=xe(V,M,l.enabled);if(T.needsAll)return{request:F,probe:null};const me=m(T.pushed);let we=null;return(!I||I.key!==me)&&(M.total?(X(F),we=await Fe(await g.execute(T.pushed,F)),I={key:me,size:we&&typeof we.total=="number"?we.total:null}):I={key:me,size:null}),I.size!==null&&I.size<b?{request:F,probe:null}:(le(L.names,O,I.size,b),{request:V,probe:we})},jt=async(F,L)=>{$e=null;const Z=h(F.pushed);ge={engine:Z.engine,client:Z.client,groupBy:F.pushed.groupBy},Z.client.length&&re(`source.pushdown.group.totals.${O}.${Z.client.map(me=>me.id).join(".")}`,`the ${O} adapter cannot compute the group subtotal for ${Z.client.map(me=>`"${me.id}" (${me.reason})`).join(", ")}, so those group rows carry no value for that column. A figure computed over anything other than the group would be wrong, so none is shown; \`lastPlan().aggregates.client\` names them.`);const V=await g.executeGroupLevel(F.pushed,Z.engine,L)||{};let T=V.rows||[];return!M.range&&L.range&&(T=T.slice(L.range.start,L.range.end)),rt(V),V.total===void 0?{rows:T}:{rows:T,total:V.total}},st=new Map,Yt=64,wt=async(F,L)=>{$e=null;const Z=F.pushed,V=Z.groupBy,T=Array.isArray(Z.groupValues)?Z.groupValues:[],me=T.length,we=[...Z.filters?[Z.filters]:[],...V.slice(0,me).map((ee,Ge)=>({col:ee,op:"eq",value:T[Ge]===void 0?null:T[Ge],caseSensitive:!0}))],be=we.length===0?null:we.length===1?we[0]:{op:"and",conditions:we},He=L.range?L.range.start:0;if(me>=V.length){const ee={...Z,filters:be,groupBy:[],groupPath:[],groupValues:[],totals:[],totalFns:{}},Ge=await Fe(await g.execute(ee,L))||{};let et=Ge.rows||[];return!M.range&&L.range&&(et=et.slice(L.range.start,L.range.end)),typeof Ge.total=="number"?{rows:et,total:Ge.total}:{rows:et}}const Re=V[me],ce=h(Z),Ue=We(M),tt=ce.engine.filter(ee=>Ue.has(ee.fn)),De=[...ce.engine.filter(ee=>!Ue.has(ee.fn)).map(ee=>({id:ee.id,fn:ee.fn,class:ee.class,reason:`the ${O} adapter does not compute "${ee.fn}"`})),...ce.client];ge={engine:tt,client:De,groupBy:V},De.length&&re(`source.pushdown.group.totals.${O}.${De.map(ee=>ee.id).join(".")}`,`the ${O} adapter cannot compute the group subtotal for ${De.map(ee=>`"${ee.id}" (${ee.reason})`).join(", ")}, so those group rows carry no value for that column. A figure computed over anything other than the group would be wrong, so none is shown; \`lastPlan().aggregates.client\` names them.`);const fe=[...tt.map(ee=>({id:ee.id,col:ee.col,fn:ee.fn})),{id:ae,col:Re,fn:"count"}],Ee={...Z,filters:be,range:null},Me=JSON.stringify([m(Ee),T,Re,fe]);let je=He>0?st.get(Me):void 0;if(!je){for(je=Promise.resolve(g.executeGroupedAggregates(Ee,[Re],fe)),st.delete(Me),st.set(Me,je);st.size>Yt;)st.delete(st.keys().next().value);je.catch(()=>{st.get(Me)===je&&st.delete(Me)})}const vt=await je||[];X(L);const $t=ee=>{const Ge={};for(const et of tt)Ge[et.id]=ee?ee[et.id]:void 0;return Ge},at=(Z.sort||[]).find(ee=>ee&&ee.col===Re),Ne=at&&at.dir==="desc"?-1:1,ot=vt.filter(ee=>ee&&ee.level===1).map(ee=>({[Re]:ee.keys[0]===void 0?null:ee.keys[0],leafCount:Number(ee.values&&ee.values[ae])||0,totals:$t(ee.values)})).sort((ee,Ge)=>Ne*A(ee[Re],Ge[Re]));if(me===0){const ee=vt.find(et=>et&&et.level===0),Ge=ee?Number(ee.values&&ee.values[ae]):NaN;rt({matchCount:Number.isFinite(Ge)?Ge:ot.reduce((et,Xt)=>et+Xt.leafCount,0),...ee?{grand:$t(ee.values)}:{}})}const Dt=L.range?L.range.end:ot.length;return{rows:ot.slice(He,Dt),total:ot.length}},rt=F=>{typeof F.matchCount=="number"&&(qe=F.matchCount,Te=F.grand?{totals:F.grand,leafCount:F.matchCount}:null,ze===void 0&&se(g.unfilteredCount)&&(ze=null,Promise.resolve(g.unfilteredCount()).then(L=>{ze=typeof L=="number"?L:null}).catch(L=>{re(`source.pushdown.group.unfiltered.${O}`,`the ${O} adapter could not count the unfiltered set (${L&&L.message?L.message:L}), so "N of M" falls back to the display count for its denominator.`)})))},gt=async(F,L)=>{$e=null;const Z=h(F.pushed);ge={engine:Z.engine,client:Z.client,groupBy:F.pushed.groupBy,pivotBy:F.pushed.pivotBy},Z.client.length&&re(`source.pushdown.pivot.totals.${O}.${Z.client.map(be=>be.id).join(".")}`,`the ${O} adapter cannot compute the pivot cells for ${Z.client.map(be=>`"${be.id}" (${be.reason})`).join(", ")}, so those cells are empty. A figure computed over anything other than the cell would be wrong, so none is shown; \`lastPlan().aggregates.client\` names them.`);const V=await g.executePivotLevel(F.pushed,Z.engine,L)||{};let T=V.rows||[];!M.range&&L.range&&(T=T.slice(L.range.start,L.range.end)),rt(V);const me=V.pivot&&typeof V.pivot=="object"?V.pivot:{},we={cells:Array.isArray(me.cells)?me.cells:[],...Array.isArray(me.axis)?{axis:me.axis}:{}};return V.total===void 0?{rows:T,pivot:we}:{rows:T,total:V.total,pivot:we}},At=F=>{re(`source.pushdown.pivot.${O}.${F}`,`pushdown:pivot-unsupported: the ${O} adapter cannot pivot this query because ${F}, so no rows are fetched rather than every leaf row being pulled into the browser to pivot there. \`lastPlan().pivotReason\` says the same.`);const L=new Error(`[lattice] ${ue}: the ${O} adapter cannot pivot this query because ${F}, so no rows are fetched rather than every leaf row being pulled into the browser to pivot there. \`lastPlan().pivotReason\` says the same.`);throw L.code=ue,L.reason=F,L},Qt=(F,L)=>{const Z={key:L,state:"pending",value:null};return $e=Z,F.then(V=>($e===Z&&($e={key:L,state:"settled",value:typeof V=="number"?V:null}),V),V=>{throw $e===Z&&($e={key:L,state:"failed",value:null}),V})};let _e=0,Je=[];const Xe=()=>_e===0?null:new Promise(F=>{const L=setTimeout(F,$);Je.push(()=>{clearTimeout(L),F()})}),Ye=async F=>{const L=Y();L&&await L;const V=F&&F.pivotMode!==!1&&Array.isArray(F.pivotBy)&&F.pivotBy.length>0?{request:F,probe:null}:await Et(F);X(F);let T=xe(V.request,M,l.enabled);if(M.group&&T.grouped&&!T.pivoted&&!se(g.executeGroupLevel)&&(re(`source.pushdown.group.method.${O}`,`the ${O} adapter declares the \`group\` capability but has no \`executeGroupLevel(query, aggregates, request)\`, so grouping is not pushed and the grid stays ungrouped unless it holds the whole matching set. Implement the method or drop the capability.`),T=xe(V.request,{...M,group:!1,aggregates:null},l.enabled)),T.pivoted&&!se(g.executePivotLevel)&&(T=xe(V.request,{...M,pivot:!1},l.enabled),T.pivotReason="the adapter declares the `pivot` capability but has no `executePivotLevel(query, aggregates, request)`"),T.grouped&&!T.pivoted&&!M.group&&!se(g.executeGroupedAggregates)&&(re(`source.pushdown.group.aggregates.method.${O}`,`the ${O} adapter declares \`aggregates\` but has no \`executeGroupedAggregates(query, groupBy, aggregates)\`, so the grouped view cannot be built from grouped aggregates and the grid stays ungrouped unless it holds the whole matching set. Implement the method, or declare \`group\` and implement \`executeGroupLevel\`.`),T=xe(V.request,{...M,aggregates:null},l.enabled)),he=T,T.pivoted)return gt(T,F);if(T.pivotReason&&At(T.pivotReason),T.grouped)return M.group?jt(T,F):wt(T,F);const we=!!T.groupReason&&!T.full;we?re(`source.pushdown.group-unsupported.${O}.${T.groupReason}`,`pushdown:group-unsupported: the ${O} adapter was not asked to group this query because ${T.groupReason}, so the grid stays ungrouped rather than building group rows, counts and subtotals from a window of leaf rows. \`lastPlan().groupReason\` says the same.`):T.groupReason&&re(`source.pushdown.group.${O}.${T.groupReason}`,`the ${O} adapter was not asked to group this query because ${T.groupReason}. The engine returns rows and the grouping is the grid's to do, which needs every matching row in the browser — correct where the grid holds them, and wrong-looking where it holds a window. \`lastPlan().unpushed\` names it.`);const be=fe=>we?{...fe,[Ce]:!0}:fe;if(!T.needsAll){const fe=V.probe||await g.execute(T.pushed,F),Ee=fe.rows||[];return nt(fe.pendingTotal)&&fe.total===void 0?be({rows:Ee,pendingTotal:Qt(fe.pendingTotal,m(T.pushed))}):($e=null,!M.total&&fe.total===void 0?be({rows:Ee}):be({rows:Ee,total:fe.total??Ee.length}))}T.unpushed.length&&re(`source.pushdown.residual.${O}.${T.unpushed.join(".")}`,`the ${O} adapter cannot push ${T.unpushed.join(" or ")}, so every matching row is fetched and the rest is applied in the browser. Correct, and slower than it needs to be: widening the adapter is the fix.`);const He=m(T.pushed);if(!ie||ie.key!==He){const fe=await Fe(await g.execute(T.pushed,F));$e=null;const Ee=fe.rows||[];if(T.full){const Me=typeof fe.total=="number"?Math.max(fe.total,Ee.length):Ee.length;if(Me>l.maxRows)throw new Error(`[lattice] fullDataset refused: the ${O} adapter's matching set is ${Me.toLocaleString()} rows, past the configured maxRows of ${l.maxRows.toLocaleString()}. The whole set cannot be held client-side, so it is refused rather than truncated — a fraction shown as the whole would make every total and statistic silently wrong. Narrow the filter or raise maxRows.`);const je=Ee.length*S(Ee[0]);if(je>l.maxBytesEstimate)throw new Error(`[lattice] fullDataset refused: the ${O} adapter's matching set is an estimated ${Math.round(je/(1024*1024)).toLocaleString()} MB across ${Ee.length.toLocaleString()} rows, past the configured maxBytesEstimate of ${Math.round(l.maxBytesEstimate/(1024*1024)).toLocaleString()} MB. The whole set cannot be held client-side, so it is refused rather than truncated. Narrow the filter or raise maxBytesEstimate.`)}if(typeof fe.total=="number"&&Ee.length<fe.total){const Me=!!(T.residual.filters||T.residual.quick||T.residual.sort&&T.residual.sort.length);if(Me&&!u)throw new Error(`[lattice] the ${O} adapter returned ${Ee.length} of ${fe.total} matching rows when asked for the whole result, and the query has residual ${T.unpushed.join(" and ")||"work"} to finish in the browser. Filtering or sorting a fraction of the result would return wrong rows, so the result is refused. Fix the adapter to follow the engine's own paging before returning, hold the data in memory, or set \`allowPartialResults: true\` on the source config to accept this knowingly.`);Me?re(`source.pushdown.partial.residual.${O}`,`the ${O} adapter returned ${Ee.length} of ${fe.total} matching rows when asked for the whole result, and residual work will run over that fraction. allowPartialResults is set, so the result is used as-is — it may be wrong. The adapter must follow the engine's own paging to be correct.`):re(`source.pushdown.partial.${O}`,`the ${O} adapter returned ${Ee.length} of ${fe.total} matching rows when asked for the whole result. The adapter must follow the engine's own paging before returning.`)}ie={key:He,rows:Ee,total:typeof fe.total=="number"?fe.total:null}}let Re=T;if(T.residual.where){const fe=ie.total??ie.rows.length;if(fe>=b){le(T.residual.where.names,O,fe,b);const{where:Ee,...Me}=V.request;Re=xe(Me,M,l.enabled),he=Re}}const ce=ie.total!==null&&ie.rows.length>=ie.total,Ue=c(ie.rows,{...Re.residual,whole:ce},a.compute||{}),tt=F.range?F.range.start:0,De=F.range?F.range.end:Ue.length;return be({rows:Ue.slice(tt,De),total:Ue.length})},kt=async(F,L)=>{const Z=Xe();Z&&await Z;const V=Y();V&&await V;const T=xe(F,M,l.enabled);he=T;const me=x(L,ve),we=Array.isArray(F.groupBy)?F.groupBy:[],be=we.length>0,He=!T.residual.filters&&!T.residual.quick,Re=!be||_(we,M.buckets);let ce=me.engine,Ue=me.client;if(M.aggregates&&ce.length){const Ee=M.aggregates instanceof Set?M.aggregates:new Set(pe(M.aggregates)),Me=ce.filter(je=>!Ee.has(je.fn));Me.length&&(ce=ce.filter(je=>Ee.has(je.fn)),Ue=[...Me.map(je=>({...je,reason:`the ${O} adapter does not compute "${je.fn}"`})),...Ue])}const tt=Ee=>{Ue=[...ce.map(Me=>({...Me,reason:Ee})),...Ue],ce=[]};ce.length&&!He?tt(T.residual.quick&&!T.residual.filters?"a quick search the adapter cannot push forces all-client (no mixed provenance)":"residual filter forces all-client (no mixed provenance)"):ce.length&&!Re&&tt("a grouping key the engine cannot form forces all-client (no mixed provenance)");let De={},fe;return ce.length&&(se(be?g.executeGroupedAggregates:g.executeAggregates)?be?fe=await g.executeGroupedAggregates(T.pushed,we,ce)||[]:De=await g.executeAggregates(T.pushed,ce)||{}:(re(`source.pushdown.aggregates.${O}${be?".grouped":""}`,`the ${O} adapter cannot compute ${be?"grouped ":""}aggregates, so every requested statistic is computed client-side. Correct, and slower than it needs to be.`),tt(`adapter cannot compute ${be?"grouped ":""}aggregates`))),ge={engine:ce,client:Ue,...be?{groupBy:we}:{}},{values:De,engine:ce,client:Ue,...fe!==void 0?{groups:fe}:{}}},Pt=async F=>{_e++;try{return await Ye(F)}finally{if(_e--,_e===0&&Je.length){const L=Je;Je=[];for(const Z of L)Z()}}},lt=N(a.edit),ft=a.edit&&typeof a.edit=="object"&&se(a.edit.commit);let mt=a.edit;if(lt&&!ft)if(M.mutate&&M.mutate.update){const F=L=>{if(!M.mutate||!M.mutate.update)throw new Error(`[lattice] the ${O} adapter cannot update rows (mutate.update is not declared), so this edit cannot be persisted. The cell is reverted rather than left looking saved.`);const Z={kind:"update",key:String(L.key),patch:{[L.colId]:L.value}};return g.mutate(Z,L.request||{})};mt={...a.edit===!0?{}:a.edit,commit:F}}else re(`source.pushdown.readonly.${O}`,`edit is enabled but the ${O} adapter declares mutate: ${M.mutate?"without update":"false"} (read-only by declaration), so no commit is synthesised and the grid stays read-only. Declare \`mutate: { update: true }\` on the adapter to allow cell edits.`);const Ft=lt&&M.mutate&&(M.mutate.append||M.mutate.delete)?{append:M.mutate.append===!0,remove:M.mutate.delete===!0,returning:M.mutate.returning,mutate:(F,L)=>g.mutate(F,L||{})}:null,Ve=async F=>{const L=Y();L&&await L;const{range:Z,signal:V,export:T,...me}=F||{},we={...me,groupBy:[],groupPath:[],groupValues:[],pivotBy:[],pivotMode:!1,totals:[]};return{plan:xe(we,M,l.enabled),signal:V}};async function*Se(F,L={}){const{plan:Z,signal:V}=await Ve(F),T=Math.max(1,Math.floor(Number(L.pageSize))||5e3),me={signal:V,stream:!0};if(!Z.needsAll)for(let He=0;;He+=T){X(me);const Re=await g.execute({...Z.pushed,range:{start:He,end:He+T}},me);Re&&nt(Re.pendingTotal)&&Re.pendingTotal.then(null,()=>{});const ce=Re&&Re.rows||[];if(ce.length&&(yield ce),ce.length<T)return}X(me);const we=await Fe(await g.execute({...Z.pushed,range:void 0},me)),be=c(we&&we.rows||[],{...Z.residual,whole:!0},a.compute||{});for(let He=0;He<be.length;He+=T)yield be.slice(He,He+T)}return{...a,edit:mt,rowMutate:Ft,mode:"remote",fetch:Pt,foregroundIdle:Xe,aggregate:kt,countMatching:async F=>{const{plan:L,signal:Z}=await Ve(F);if(!L.needsAll&&M.total){X({signal:Z});const T=await Fe(await g.execute({...L.pushed,range:{start:0,end:0}},{signal:Z}));if(T&&typeof T.total=="number")return T.total}let V=0;for await(const T of Se(F))V+=T.length;return V},streamMatching:Se,lastPlan:()=>he?{...he,...ge?{aggregates:ge}:{},...$e?{total:{deferred:!0,state:$e.state,value:$e.value}}:{}}:null,fullFrame:it,counts:()=>({match:qe,total:ze??null,pending:!!$e&&$e.state==="pending"}),grandTotals:()=>Te}}}),pt("packages/core/src/model/rowkey.js",function(y,Oe){"use strict";Object.defineProperty(y,"KEY_DEPENDENT_FEATURES",{enumerable:!0,get:function(){return ke}}),Object.defineProperty(y,"compositeKey",{enumerable:!0,get:function(){return le}}),Object.defineProperty(y,"createRowKey",{enumerable:!0,get:function(){return C}}),Object.defineProperty(y,"warnMissingKeys",{enumerable:!0,get:function(){return te}}),Object.defineProperty(y,"groupPathKey",{enumerable:!0,get:function(){return z}}),Object.defineProperty(y,"splitPathKey",{enumerable:!0,get:function(){return ne}});const de=Oe("packages/core/src/internal/util.js"),A=de.warnOnce,se=de.pathGetter,pe=de.isFunction,re=de.isBlank,ke=["changes (rows.apply / rows.queue)","streaming dedupe","selection persistence","remote reload","cell comments"],D="";function J($){if($===null)return"\0n";if($===void 0)return"\0u";const X=typeof $;if(X==="string")return $;if(X==="number"||X==="bigint"||X==="boolean")return String($);if($ instanceof Date)return`\0d${$.getTime()}`;try{return`\0o${JSON.stringify($)}`}catch{return"\0o?"}}function le($){if($.length===1)return J($[0]);let X="";for(let P=0;P<$.length;P++)P&&(X+=D),X+=J($[P]);return X}function C($,X={}){const P=X.warn!==!1;if(pe($)){const R=$;return{stable:!0,fields:[],disabled:[],key(E,N){try{const H=R(E);return Array.isArray(H)?le(H):J(H)}catch(H){return A("rowKey.throw","rowKey function threw; falling back to index identity for the affected rows.",H),`#${N??-1}`}},keyEmpty(E){try{const N=R(E);return Array.isArray(N)?N.length===0||N.some(re):re(N)}catch{return!1}},missingFields(){return[]}}}if(Array.isArray($)&&$.length>0){const R=$.filter(H=>typeof H=="string"),E=R.map(H=>se(H)),N=E.length;return{stable:!0,fields:R,disabled:[],key(H){const q=new Array(N);for(let K=0;K<N;K++)q[K]=E[K](H);return le(q)},keyEmpty(H){for(let q=0;q<N;q++)if(re(E[q](H)))return!0;return!1},missingFields(H){const q=[];for(let K=0;K<N;K++)re(E[K](H))&&q.push(R[K]);return q}}}if(typeof $=="string"&&$.length>0){const R=se($);return{stable:!0,fields:[$],disabled:[],key(E){return J(R(E))},keyEmpty(E){return re(R(E))},missingFields(E){return re(R(E))?[$]:[]}}}return P&&A("rowKey.missing",`no rowKey configured, so rows are identified by object identity. This disables: ${ke.join(", ")}. Set rowKey to a field name, an array of field names, or a function.`),{stable:!1,fields:[],disabled:ke.slice(),key(R,E){if(R===null||typeof R!="object")return`#${E??0}:${String(R)}`;let N=x.get(R);return N===void 0&&(N=`#${_++}`,x.set(R,N)),N}}}const x=new WeakMap;let _=0;function te($,X){if(!$||$.stable===!1||!pe($.keyEmpty)||!Array.isArray(X)||X.length===0)return;let P=0,R=null,E;for(let K=0;K<X.length;K++){const ae=X[K];$.keyEmpty(ae)&&(P++,R===null&&(R=pe($.missingFields)?$.missingFields(ae):[],E=ae))}if(P===0)return;const N=$.fields.length?$.fields.join(","):"(function)",H=R&&R.length?R.join(", "):$.fields.length?$.fields.join(", "):"the rowKey function",q=E!==null&&typeof E=="object"?Object.keys(E).join(", ")||"(no fields)":String(E);A(`rowKey.emptyValue:${N}`,`rowKey ${H} is missing on ${P} of ${X.length} rows; the first such row has: ${q}. Rows without a key value collapse onto one key, so selection, edits and rows.apply updates land on whichever row now shares it. Set rowKey to a field present on every row, or fix the source data.`)}function z($){return le($)}function ne($){return $.split(D)}}),pt("packages/modules/data-router/devtools.js",function(y,Oe){"use strict";Object.defineProperty(y,"mountRouterDevtools",{enumerable:!0,get:function(){return J}}),Object.defineProperty(y,"default",{enumerable:!0,get:function(){return le}});const A=Oe("packages/core/src/internal/util.js").warnOnce,se="lat-router-devtools";function pe(C,x,_){const te=C.createElement(x);return te.textContent=_==null?"—":String(_),te}function re(C){return Number.isFinite(C)?`${Math.round(C*10)/10}/s`:"—"}function ke(C,x,_,te){const z=C.createElement("section");z.className=`${se}-section`;const ne=C.createElement("h4");ne.textContent=x,z.appendChild(ne);const $=C.createElement("table"),X=C.createElement("tr");for(const P of _)X.appendChild(pe(C,"th",P));$.appendChild(X);for(const P of te){const R=C.createElement("tr");for(const E of P)R.appendChild(pe(C,"td",E));$.appendChild(R)}return z.appendChild($),z}function D(C,x,_){x.textContent="";const te=ke(C,"Router",["metric","value"],[["throughput",re(_.throughput)],["unrouted",_.unrouted],["dropped (duplicate)",_.dropped],["buffer depth",_.buffered],["lag (deltas behind)",_.lag]]);x.appendChild(te),x.appendChild(ke(C,"Routes",["#","label","kind","rows","shown","rows/sec"],_.routes.map(z=>[z.index,z.label,z.kind,z.rows,z.shown,re(z.throughput)]))),_.sources.length&&x.appendChild(ke(C,"Sources",["id","rows","ingested","rows/sec"],_.sources.map(z=>[z.id,z.rows,z.ingested,re(z.throughput)])))}function J(C,x,_={}){const te=x&&x.ownerDocument||(typeof document<"u"?document:null);if(!C||typeof C.metrics!="function"||typeof C.on!="function"||!x||!te)return A("data-router:devtools-target","router.mountDevtools(el) needs a router with metrics()/on() and a DOM element to render into; the panel was not mounted."),{destroy(){},refresh(){}};const z=te.createElement("div");z.className=se,x.appendChild(z);const ne=()=>D(te,z,C.metrics());ne();const $=C.on("metrics",()=>ne());return{refresh:ne,destroy(){$(),z.parentNode&&z.parentNode.removeChild(z)}}}const le=J}),pt("packages/core/src/format/date.js",function(y,Oe){"use strict";Object.defineProperty(y,"scanPattern",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"toDate",{enumerable:!0,get:function(){return D}}),Object.defineProperty(y,"compilePattern",{enumerable:!0,get:function(){return C}}),Object.defineProperty(y,"compileDate",{enumerable:!0,get:function(){return _}}),Object.defineProperty(y,"toIsoDate",{enumerable:!0,get:function(){return te}}),Object.defineProperty(y,"toIsoDateTime",{enumerable:!0,get:function(){return z}}),Object.defineProperty(y,"compareIso",{enumerable:!0,get:function(){return X}});const de=Oe("packages/core/src/internal/util.js"),A=de.isNil,se=de.warnOnce,pe=["yyyy","yy","MMMM","MMM","MM","M","dd","d","EEEE","EEE","HH","H","hh","h","mm","m","ss","s","SSS","a"];function re(P){const R=[];let E=0,N="";const H=()=>{N&&(R.push({token:null,text:N}),N="")};for(;E<P.length;){const q=P[E];if(q==="'"){if(P[E+1]==="'"){N+="'",E+=2;continue}const ae=P.indexOf("'",E+1);if(ae===-1){N+=P.slice(E+1),E=P.length;continue}N+=P.slice(E+1,ae),E=ae+1;continue}const K=pe.find(ae=>P.startsWith(ae,E));if(K){H(),R.push({token:K,text:K}),E+=K.length;continue}/[A-Za-z]/.test(q)&&se(`date.pattern.token:${q}`,`the date pattern "${P}" contains '${q}', which is not a supported token, so it is rendered as text. Quote it as a literal to silence this. Supported: ${pe.join(" ")}.`),N+=q,E+=1}return H(),R}const ke=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?)?$/;function D(P){if(A(P)||P==="")return null;if(P instanceof Date)return Number.isNaN(P.getTime())?null:P;if(typeof P=="number")return Number.isNaN(P)?null:new Date(P);if(typeof P=="string"){const R=ke.exec(P.trim());if(R){const[,N,H,q,K="0",ae="0",We="0"]=R;return new Date(+N,+H-1,+q,+K,+ae,+We)}const E=new Date(P);return Number.isNaN(E.getTime())?null:E}return null}function J(P,R){return String(P).padStart(R,"0")}function le(P){if(!P)return N=>({year:N.getFullYear(),month:N.getMonth()+1,day:N.getDate(),hour:N.getHours(),minute:N.getMinutes(),second:N.getSeconds(),ms:N.getMilliseconds(),weekday:N.getDay()});const R=new Intl.DateTimeFormat("en-US",{timeZone:P,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,weekday:"short"}),E={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};return N=>{const H={year:0,month:1,day:1,hour:0,minute:0,second:0,ms:N.getMilliseconds(),weekday:0};for(const q of R.formatToParts(N))switch(q.type){case"year":H.year=Number(q.value);break;case"month":H.month=Number(q.value);break;case"day":H.day=Number(q.value);break;case"hour":H.hour=Number(q.value)%24;break;case"minute":H.minute=Number(q.value);break;case"second":H.second=Number(q.value);break;case"weekday":H.weekday=E[q.value]??0;break;default:break}return H}}function C(P,R,E){const N=re(P),H=le(E),q=new Set(N.filter(Ae=>Ae.token).map(Ae=>Ae.token)),K=q.has("MMM")?new Intl.DateTimeFormat(R,{month:"short",timeZone:E}):null,ae=q.has("MMMM")?new Intl.DateTimeFormat(R,{month:"long",timeZone:E}):null,We=q.has("EEE")?new Intl.DateTimeFormat(R,{weekday:"short",timeZone:E}):null,Le=q.has("EEEE")?new Intl.DateTimeFormat(R,{weekday:"long",timeZone:E}):null;return Ae=>{const ue=H(Ae);let oe="";for(const Ce of N){if(!Ce.token){oe+=Ce.text;continue}switch(Ce.token){case"yyyy":oe+=J(ue.year,4);break;case"yy":oe+=J(ue.year%100,2);break;case"MMMM":oe+=ae.format(Ae);break;case"MMM":oe+=K.format(Ae);break;case"MM":oe+=J(ue.month,2);break;case"M":oe+=String(ue.month);break;case"dd":oe+=J(ue.day,2);break;case"d":oe+=String(ue.day);break;case"EEEE":oe+=Le.format(Ae);break;case"EEE":oe+=We.format(Ae);break;case"HH":oe+=J(ue.hour,2);break;case"H":oe+=String(ue.hour);break;case"hh":oe+=J(ue.hour%12===0?12:ue.hour%12,2);break;case"h":oe+=String(ue.hour%12===0?12:ue.hour%12);break;case"mm":oe+=J(ue.minute,2);break;case"m":oe+=String(ue.minute);break;case"ss":oe+=J(ue.second,2);break;case"s":oe+=String(ue.second);break;case"SSS":oe+=J(ue.ms,3);break;case"a":oe+=ue.hour<12?"AM":"PM";break;default:oe+=Ce.text;break}}return oe}}const x=[["year",365*24*36e5],["month",720*36e5],["week",168*36e5],["day",24*36e5],["hour",36e5],["minute",6e4],["second",1e3]];function _(P,R){const E=P||{},N=E.locale||R||void 0,H=E.nullDisplay??"",q=E.timeZone;let K;if(E.pattern)K=C(E.pattern,N,q);else if(E.dateStyle||E.timeStyle){const ue={timeZone:q};E.dateStyle&&(ue.dateStyle=E.dateStyle),E.timeStyle&&(ue.timeStyle=E.timeStyle);const oe=new Intl.DateTimeFormat(N,ue);K=Ce=>oe.format(Ce)}else{const ue=new Intl.DateTimeFormat(N,{dateStyle:"medium",timeZone:q});K=oe=>ue.format(oe)}const ae=E.relative?new Intl.RelativeTimeFormat(N,{numeric:"auto"}):null,Le=(typeof E.relative=="object"&&E.relative?E.relative.threshold??7:7)*24*36e5,Ae=(ue,oe)=>{const Ce=D(ue);if(!Ce)return H;if(ae){const ht=oe&&typeof oe.now=="number"?oe.now:Date.now(),xe=Ce.getTime()-ht;if(Math.abs(xe)<Le){for(const[h,p]of x)if(Math.abs(xe)>=p||h==="second")return ae.format(Math.round(xe/p),h)}}return K(Ce)};return Ae.spec=E,Ae}function te(P){if(A(P)||P==="")return null;if(typeof P=="string"){const N=/^(\d{4}-\d{2}-\d{2})/.exec(P.trim());if(N)return N[1];const H=D(P);return H?te(H):null}const R=D(P);if(!R)return null;const E=N=>String(N).padStart(2,"0");return`${R.getFullYear()}-${E(R.getMonth()+1)}-${E(R.getDate())}`}function z(P,R){if(A(P)||P==="")return null;if(typeof P=="string"){const N=P.trim();if(ne.test(N)){const K=D(N);return K?$(K,R):null}const H=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?/.exec(N);if(H){const[,K,ae,We,Le]=H;return`${K}T${ae}:${We}${Le&&Le!=="00"?`:${Le}`:""}`}if(/^\d{4}-\d{2}-\d{2}$/.test(N))return`${N}T00:00`;const q=D(N);return q?z(q):null}const E=D(P);return E?$(E,R):null}const ne=/(?:Z|[+-]\d{2}:?\d{2})$/i;function $(P,R){const E=K=>String(K).padStart(2,"0");if(R)try{const K=new Intl.DateTimeFormat("en-CA",{timeZone:R,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(P).reduce((Le,Ae)=>(Ae.type!=="literal"&&(Le[Ae.type]=Ae.value),Le),{}),ae=K.hour==="24"?"00":K.hour,We=Number(K.second);return`${K.year}-${K.month}-${K.day}T${ae}:${K.minute}`+(We?`:${K.second}`:"")}catch{}const N=`${P.getFullYear()}-${E(P.getMonth()+1)}-${E(P.getDate())}`,H=P.getSeconds(),q=`${E(P.getHours())}:${E(P.getMinutes())}${H?`:${E(H)}`:""}`;return`${N}T${q}`}function X(P,R){const E=A(P)||P===""?null:String(P),N=A(R)||R===""?null:String(R);return E===null?N===null?0:1:N===null||E<N?-1:E>N?1:0}}),pt("packages/core/src/format/boolean.js",function(y,Oe){"use strict";Object.defineProperty(y,"toTriState",{enumerable:!0,get:function(){return re}}),Object.defineProperty(y,"compileBoolean",{enumerable:!0,get:function(){return ke}});const A=Oe("packages/core/src/internal/util.js").isNil,se={true:"☑",false:"☐",null:""},pe={true:"◉",false:"◯",null:""};function re(D){if(A(D)||D==="")return null;if(typeof D=="boolean")return D;if(typeof D=="number")return D!==0;const J=String(D).trim().toLowerCase();return J==="true"||J==="yes"||J==="y"||J==="1"?!0:J==="false"||J==="no"||J==="n"||J==="0"?!1:null}function ke(D,J){const le=D||{},C=le.display||"text",x=le.trueLabel??"Yes",_=le.falseLabel??"No",te=le.nullLabel??"";let z=x,ne=_;const $=te;C==="checkbox"?(z=se.true,ne=se.false):C==="switch"?(z=pe.true,ne=pe.false):C==="icon"&&(z=le.trueIcon??x,ne=le.falseIcon??_);const X=P=>{const R=re(P);return R===null?$:R?z:ne};return X.display=C,X.labels={true:x,false:_,null:te},X.locale=J,X.spec=le,X}}),pt("packages/modules/data-router/index.js",function(y,Oe){"use strict";Object.defineProperty(y,"createDataRouter",{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(y,"default",{enumerable:!0,get:function(){return xe}});const A=Oe("packages/core/src/internal/util.js").warnOnce,se=Oe("packages/core/src/source/pushdown.js"),pe=se.planQuery,re=se.capabilitiesOf,D=Oe("packages/core/src/model/rowkey.js").compositeKey,le=Oe("packages/modules/data-router/devtools.js").mountRouterDevtools,C=Oe("packages/core/src/format/date.js"),x=C.toIsoDate,_=C.scanPattern,z=Oe("packages/core/src/format/boolean.js").toTriState;function ne(h,p){return typeof h=="function"?h:typeof h=="string"?c=>c[h]:p}function $(h,p){if(!h||typeof h!="object"||typeof p!="string")return;if(!p.includes("."))return h[p];let c=h;for(const m of p.split(".")){if(!c||typeof c!="object")return;c=c[m]}return c}function X(h,p){const c=p.split(".");if(c.length===1){delete h[p];return}let m=h;for(let S=0;S<c.length-1;S+=1)if(m=m[c[S]],!m||typeof m!="object")return;delete m[c[c.length-1]]}function P(h){return Array.isArray(h)?"array":h===null?"null":typeof h}function R(h,p){if(h===void 0||typeof h=="string"&&h.length>0)return h;if(typeof h=="function")return c=>{const m=h(c);if(typeof m=="string"||typeof m=="number"&&Number.isFinite(m))return m;throw new Error(`lattice-data-router: rowKey function must return a string or number; got ${P(m)}.`)};throw new Error(`lattice-data-router: rowKey must be a property name or a function; composite keys are not supported on ${p}.`)}function E(h){if(typeof h=="function")return h;if(h&&typeof h=="object"&&typeof h.key=="string"){const p=h.dir==="desc"?-1:1,{key:c}=h;return(m,S)=>{const W=m?m[c]:void 0,U=S?S[c]:void 0;return W<U?-1*p:W>U?1*p:0}}return null}function N(h){if(!h||typeof h!="object")return null;let p=0;Number.isFinite(h.minInterval)&&h.minInterval>0?p=Number(h.minInterval):Number.isFinite(h.maxHz)&&h.maxHz>0&&(p=1e3/Number(h.maxHz));const c=Number.isFinite(h.sample)&&h.sample>1?Math.floor(Number(h.sample)):1,m=Number.isFinite(h.maxLag)&&h.maxLag>=0?Math.floor(Number(h.maxLag)):null;return p===0&&c===1&&m===null?null:{minInterval:p,sample:c,maxLag:m}}let H=0;function q(){return H+=1,`r${H}`}function K(h){const c=(Array.isArray(h)?h:[h]).map(m=>({name:typeof m=="string"?m:null,get:ne(m,()=>{})}));return m=>{const S={},W=[];for(const U of c){const Be=U.get(m);W.push(Be),U.name&&(S[U.name]=Be)}return{key:D(W),fields:S}}}function ae(h,p){if(typeof h=="function")return h(p);if(h&&typeof h=="object"){const{op:c,field:m}=h;if(c==="count")return p.length;const S=m!=null?p.map(W=>Number(W[m])).filter(W=>Number.isFinite(W)):[];if(c==="sum")return S.reduce((W,U)=>W+U,0);if(c==="avg")return S.length?S.reduce((W,U)=>W+U,0)/S.length:0;if(c==="min")return S.length?Math.min(...S):void 0;if(c==="max")return S.length?Math.max(...S):void 0}}function We(h){return h&&typeof h=="object"&&typeof h.from=="string"&&typeof h.to=="string"?{from:h.to,to:h.from}:(A("data-router:mutual-fn","relate({ mutual: true }) with a function relation cannot be inverted; the same predicate is applied in both directions. Use a { from, to } key map for a mutual edge."),h)}function Le(h,p){return h?p?{op:"and",conditions:[h,p]}:h:p||null}const Ae=Object.freeze(["eq","ne","lt","lte","gt","gte","between","notBetween","in","notIn","contains","notContains","startsWith","endsWith","blank","notBlank"]);function ue(h,p){const c=p?p[h.col]:void 0,m=h.value,S=W=>h.caseSensitive?String(W):String(W).toLowerCase();switch(h.op){case"eq":return c===m;case"ne":return c!==m;case"lt":return c<m;case"lte":return c<=m;case"gt":return c>m;case"gte":return c>=m;case"between":return Array.isArray(m)&&c>=m[0]&&c<=m[1];case"notBetween":return!(Array.isArray(m)&&c>=m[0]&&c<=m[1]);case"in":return Array.isArray(m)&&m.includes(c);case"notIn":return!(Array.isArray(m)&&m.includes(c));case"contains":return c!=null&&S(c).includes(S(m));case"notContains":return c==null||!S(c).includes(S(m));case"startsWith":return c!=null&&S(c).startsWith(S(m));case"endsWith":return c!=null&&S(c).endsWith(S(m));case"blank":return c==null||c==="";case"notBlank":return!(c==null||c==="");default:throw new Error(`[lattice] query() cannot evaluate the residual filter operator "${String(h.op)}" on column "${String(h.col)}" client-side, so the query is refused rather than returning rows the filter excludes. Push it down to an adapter that implements it, or use an operator this router evaluates: ${Ae.join(", ")}.`)}}function oe(h,p){return h?Array.isArray(h.conditions)?h.op==="or"?h.conditions.some(c=>oe(c,p)):h.op==="not"?!h.conditions.every(c=>oe(c,p)):h.conditions.every(c=>oe(c,p)):ue(h,p):!0}function Ce(h={}){const p=ne(h.key,()=>{}),c=ne(R(h.rowKey,"routes"),e=>e.rowKey),m=typeof h.key=="string"?h.key:null,S=!!h.overlap,W=typeof h.onUnrouted=="function"?h.onUnrouted:null,U=Number.isFinite(h.selectionDebounce)?Number(h.selectionDebounce):16,Be=typeof h.onWrite=="function"?h.onWrite:null,nt=typeof h.onConflict=="function"?h.onConflict:null,Fe=h.seq!=null?ne(h.seq,()=>{}):null,Ze=Fe?h.dedupe!==!1:!1,a=c;let g=null;typeof h.batch=="number"?g=h.batch:h.batch&&Number.isFinite(h.batch.intervalMs)&&(g=Number(h.batch.intervalMs));const M=g!==null||!!h.coalesce,G=new Map;let O,Q=0;const Y=[];let l=null;const u=h.time!=null?ne(h.time,()=>{}):null,b=typeof h.now=="function"?h.now:Date.now,I=1e4;let ve=!1,ie=null,he=null,ge="time",qe=new Map;const Te=[];let ze=0,$e,ut,ct=!1,it=null,Et=[],jt=0,st=0,Yt="time",wt=!1,rt=null,gt=null;const At=e=>{if(e&&Number.isFinite(e.seq))return e.seq;if(Fe&&e&&e.row){const t=Fe(e.row);return Number.isFinite(t)?t:void 0}},Qt=e=>{if(e&&Number.isFinite(e.t))return e.t;if(u&&e&&e.row){const t=u(e.row);if(Number.isFinite(t))return t}return b()},_e=[];let Je=null;const Xe=[],Ye=[],kt=new Map,Pt=new Set;let lt=null,ft=0;const mt=new Map,Ft=new Set,Ve=typeof h.rowKey=="string"?h.rowKey:"rowKey",Se=new Map;let Zt=0;const F=new Set,L=[],Z=new Map,V=(e,t)=>{Z.set(e,(Z.get(e)||0)+t)};let T=0;const me=new Map,we=new Map;let be=null;const He=Number.isFinite(h.metricsInterval)?Number(h.metricsInterval):1e3;let Re=0,ce=null,Ue="lattice-router",tt=250,De=null,fe=null,Ee=!1,Me=!1,je=null,vt=!1,$t=null;const at=[],Ne=()=>Je?[..._e,Je]:_e,ot=e=>Ne().find(t=>t.grid===e)||null,Dt=e=>{const t=[];for(const n of _e)if(n.match(e)&&(t.push(n),!S))break;return t.length?t:Je?[Je]:[]},ee=e=>e.hasPartValue?e.partValue:e.label!=null?e.label:e.grid,Ge=e=>{for(const t of Ne())if(t.grid===e)return t;for(const t of Ne())if(t.hasPartValue&&t.partValue===e||t.label!=null&&t.label===e)return t;return null},et=(e,t)=>{if(t.add.length||t.update.length||t.remove.length){const n=e.sink(t);Xt(e,n)}return{added:t.add.length,updated:t.update.length,removed:t.remove.length}},Xt=(e,t)=>{const n=t?.rejected;if(!Array.isArray(n)||!n.length)return;const r=n.filter(i=>i&&i.operation==="remove");if(!r.length)return;const o=e.label||`route ${e.routeId}`;A(`data-router:remove-rejected:${e.routeId}`,`route "${o}" asked its target to remove ${r.length} row(s) the target does not have (for example ${JSON.stringify(String(r[0].id))}). The rows are still on screen. This is a key mismatch: the key the route derives for a row is not the key the grid derives for it. Check that the route's \`rowKey\` names the same value as the grid's.`)},Vn=(e,t)=>{for(const n of Xe)if(n.to===e.grid&&n.predicate&&!n.predicate(t))return!1;if(e.graphPreds){for(const n of e.graphPreds)if(!n(t))return!1}return!0},yt=e=>{const t=[];for(const s of e.partition.values())e.filter&&!e.filter(s)||Vn(e,s)&&t.push(s);if(F.size){const s=new Map;for(const w of t)for(const j of Object.keys(w))F.has(j)&&w[j]!==void 0&&!s.has(j)&&s.set(j,!0);const f=e.spreadFields||(e.spreadFields=new Map),d=[],k=[];for(const w of s.keys())f.has(w)||d.push(w);for(const w of f.keys())s.has(w)||k.push(w);d.length||k.length?(e.spreadFields=s,Wn("fields:changed",{route:ee(e),added:d,removed:k})):e.spreadFields=s}let n;if(e.rollup){const s=new Map;for(const d of t){const{key:k,fields:w}=e.rollup.group(d);let j=s.get(k);j||(j={key:k,fields:w,rows:[]},s.set(k,j)),j.rows.push(d)}let f=[];for(const d of s.values()){const k={...d.fields};for(const[w,j]of e.rollup.specs)k[w]=ae(j,d.rows);f.push({gkey:d.key,row:k})}e.sort&&f.sort((d,k)=>e.sort(d.row,k.row)),e.transform&&(f=f.map(d=>({gkey:d.gkey,row:e.transform(d.row)}))),n=new Map(f.map(d=>[d.gkey,d.row]))}else{let s=t;e.sort&&(s=s.slice().sort(e.sort)),n=new Map;for(const f of s)n.set(D([e.keyOf(f)]),e.transform?e.transform(f):f)}const r=[],o=[],i=[];for(const[s,f]of n)e.keys.has(s)?ht(e.keys.get(s),f)||o.push(f):r.push(f);for(const s of e.keys.keys())n.has(s)||i.push(s);return e.keys=n,et(e,{add:r,update:o,remove:i})},Bt=e=>{e.bpTimer&&(clearTimeout(e.bpTimer),e.bpTimer=null),yt(e),e.bpPending=0,e.bpLastFlush=b()},Gn=(e,t)=>{if(e.bpTimer)return;const n=e.bp.minInterval>0?Math.max(e.bp.minInterval-(t-e.bpLastFlush),0):0;e.bpTimer=setTimeout(()=>{e.bpTimer=null,Bt(e)},n),e.bpTimer&&typeof e.bpTimer.unref=="function"&&e.bpTimer.unref()},_n=(e,t)=>{if(!e.bp){yt(e);return}e.bpPending+=t,e.bpCoalesced+=t;const n=e.bp;if(n.maxLag!=null&&e.bpPending<=n.maxLag&&!e.bpTimer){Bt(e);return}const r=b(),o=r-e.bpLastFlush>=n.minInterval,i=e.bpPending>=n.sample;if(o&&i){Bt(e);return}Gn(e,r)},Jn=e=>{e.bpTimer&&(clearTimeout(e.bpTimer),e.bpTimer=null),e.bpPending=0,e.bpLastFlush=b()},en=(e,t)=>{if(typeof e=="function"){const n=e(t);return typeof n=="function"?n:null}if(e&&typeof e=="object"){const n=e.from,r=e.to,o=new Set(t.map(i=>i&&i[n]));return i=>o.has(i&&i[r])}return null},tn=e=>{const t=ot(e),n=e&&e.selection,r=n&&typeof n.keys=="function"?n.keys():[];return!r.length||!t?[]:r.map(o=>t.partition.get(String(o))).filter(o=>o!==void 0)},Yn=e=>{const t=e&&e.selection;if(!t||typeof t.predicate!="function")return null;const n=t.predicate();if(!n||n.all!==!0)return null;const r=typeof t.count=="function"?t.count():Promise.resolve(null);return{predicate:n,count:r}},Mt=e=>{const t=Yn(e.from);if(t){if(typeof e.relation=="function"&&e.relation.length>=2){const r=e.relation(tn(e.from),t);e.predicate=typeof r=="function"?r:null}else A("data-router:link-predicate-unsupported","link()/relate() source grid has every row matching a filter selected on a source that holds only the rows it has loaded. The relation does not declare it accepts a predicate selection — a function taking (selected, { predicate, count }) as its second parameter — so the link cannot build a target-row predicate from a truncated key list and imposes no constraint."),e.predicate=null;return}const n=tn(e.from);e.predicate=n.length?en(e.relation,n):null},Lt=()=>{const e=new Set;for(const t of Ye)e.add(t.from),e.add(t.to);return e},Ot=()=>{for(const i of Ne())i.graphPreds=null;if(!Ye.length)return;const e=Lt(),t=new Map;for(const i of e){const s=tn(i);s.length&&t.set(i,s)}const n=new Map(t);let r=!0,o=(e.size+1)*2;for(;r&&o-- >0;){r=!1;for(const i of e){if(t.has(i))continue;const s=Ye.filter(j=>j.to===i&&n.has(j.from));if(!s.length)continue;const f=ot(i);if(!f)continue;const d=s.map(j=>en(j.rel,n.get(j.from))).filter(Boolean),k=[];for(const j of f.partition.values())d.every(B=>B(j))&&k.push(j);const w=n.get(i);if(!w||w.length!==k.length)n.set(i,k),r=!0;else{const j=new Set(w);k.some(B=>!j.has(B))&&(n.set(i,k),r=!0)}}}for(const i of Ye){if(!n.has(i.from))continue;const s=en(i.rel,n.get(i.from));if(!s)continue;const f=ot(i.to);f&&(f.graphPreds||(f.graphPreds=[])).push(s)}},wn=e=>{const t=kt.get(e);if(t){t.count+=1;return}const n=e&&typeof e.on=="function"?e.on("selection:changed",()=>Qn(e)):()=>{};kt.set(e,{off:n,count:1})},nn=()=>{lt&&(clearTimeout(lt),lt=null);const e=Pt;if(!e.size)return;const t=new Set;for(const n of Xe)e.has(n.from)&&(Mt(n),t.add(n.to));if(Pt.clear(),Ye.length){Ot();for(const n of Lt())t.add(n)}for(const n of t){const r=ot(n);r&&yt(r)}},Qn=e=>{if(Pt.add(e),U<=0){nn();return}lt||(lt=setTimeout(nn,U))},kn=e=>{const t=kt.get(e);t&&(t.count-=1,t.count<=0&&(t.off(),kt.delete(e)))},Zn=e=>typeof e=="function"?t=>e(t):e&&e.rows&&typeof e.rows.apply=="function"?t=>e.rows.apply(t):(A("data-router:bad-target","attach/subscribe target has no rows.apply and is not a function; its slice goes nowhere. Pass a grid or a handler(change) function."),()=>{}),rn=(e,t,n)=>({grid:e,routeId:q(),sink:Zn(e),match:t,keyOf:ne(R(n.rowKey,"routes"),c),partition:new Map,keys:new Map,transform:typeof n.transform=="function"?n.transform:null,filter:typeof n.filter=="function"?n.filter:null,sort:E(n.sort),rollup:n.rollup&&n.rollup.groupBy!=null?{group:K(n.rollup.groupBy),specs:Object.entries(n.rollup.aggregate||{})}:null,where:n.where&&typeof n.where=="object"?n.where:null,graphPreds:null,onWrite:typeof n.onWrite=="function"?n.onWrite:null,onConflict:typeof n.onConflict=="function"?n.onConflict:null,writable:n.writable===!0,readonly:!!(n.rollup&&n.rollup.groupBy!=null||typeof n.transform=="function"),label:typeof n.label=="string"?n.label:null,metricRows:0,bp:N(n.backpressure),bpPending:0,bpTimer:null,bpLastFlush:-1/0,bpCoalesced:0}),vn=e=>{if(!S){for(const t of _e)if(t.hasPartValue&&t.partValue===e){A(`data-router:overlap:${String(e)}`,`Data Router: value ${JSON.stringify(e)} already routes to another viewer; with overlap:false only the first receives rows. Pass createDataRouter({ overlap: true }) to fan one value to several viewers.`);return}}},Sn=(e,t)=>`${String(e)}${String(t)}`,Xn=e=>{const t=e&&e.row;if(!t)return null;const n=t.data&&typeof t.data=="object"?t.data:t;return n?{...n}:null},Ht=(e,t)=>{const n=e.grid;if(!n||!n.edit||typeof n.edit.setCells!="function")return;const r=Sn(t.key,t.colId);Ft.add(r);try{n.edit.setCells([{key:t.key,colId:t.colId,value:t.before}],"cell")}finally{Ft.delete(r)}V("writeReverted",1)},En=e=>{e&&Qe.apply([{op:"upsert",row:e}])},jn=(e,t,n)=>{const r=n&&typeof n=="object"?n:null,o=r&&r.conflict!==void 0?r.conflict:null;if(o){const i=e.onConflict||nt;if(i)try{i(t,{serverRow:o})}catch{}V("writeConflicted",1),En(r&&r.row?r.row:t.row);return}if(n===!1||r&&r.ok===!1){V("writeRejected",1),Ht(e,t);return}V("writeAccepted",1),En(r&&r.row?r.row:t.row)},er=e=>{const t=String(e);for(const n of Se.values())if(n.live.has(t))return n.handle;return null},tr=(e,t)=>{if(!t||t.key===void 0||t.colId===void 0||Ft.has(Sn(t.key,t.colId)))return;const n=Xn(t),r={key:String(t.key),colId:String(t.colId),value:t.value,before:t.oldValue,row:n};if(V("writeRouted",1),e.readonly){A("data-router:readonly-write","an edit on a derived (rollup/transform) route is read-only and was reverted; a derived row cannot be inverted to a source row. Make the source route writable instead."),Ht(e,r);return}const o=e.onWrite||Be;if(!o){A("data-router:no-onwrite","a route attached with { writable: true } has no onWrite handler (per-route or router-global); the edit was left in place but not persisted. Pass onWrite to route the write.");return}let i;try{i=o(r,{route:e.grid,source:er(r.key)})}catch{Ht(e,r),V("writeRejected",1);return}i&&typeof i.then=="function"?i.then(s=>jn(e,r,s),()=>{Ht(e,r),V("writeRejected",1)}):jn(e,r,i)},nr=e=>{const t=e.grid;if(!t||typeof t.on!="function"||!t.edit||typeof t.edit.setCells!="function"){A("data-router:writable-target","attach({ writable: true }) needs a grid exposing grid.on and grid.edit.setCells; write-back is off for this route.");return}if(mt.has(t))return;const n=t.on("cell:changed",r=>tr(e,r));mt.set(t,typeof n=="function"?n:()=>{})},rr=e=>{const t=[];for(const n of e.partition.values())e.filter&&!e.filter(n)||t.push(n);return t},Kt=e=>{const t=rr(e);if(e.kind==="monitor"){let r;try{r=e.evaluate(t)}catch{r=void 0}e.handler(r,t);return}let n;try{n=e.condition(t)}catch{n=!1}if(n){if(!e.armed)return;e.debounceMs>0?(e.pending={signal:n,rows:t},e.timer||(e.timer=setTimeout(()=>{e.timer=null;const r=e.pending;e.pending=null,r&&(e.armed=!1,e.handler(r.signal,r.rows))},e.debounceMs))):(e.armed=!1,e.handler(n,t))}else e.armed=!0,e.timer&&(clearTimeout(e.timer),e.timer=null),e.pending=null},on=(e,t)=>{e.partition=new Map;for(const n of t)e.match(n)&&e.partition.set(String(e.keyOf(n)),n)},or=(e,t)=>{for(const n of t){const r=n&&n.row;if(!r)continue;const o=String(e.keyOf(r));if(n.op==="delete"){e.partition.delete(o);continue}e.match(r)?e.partition.set(o,r):e.partition.delete(o)}},Ct=()=>{const e=new Map;for(const t of Ne())for(const n of t.partition.values())e.set(String(a(n)),n);return[...e.values()]},Pn=()=>{qe=new Map;for(const e of Ne())for(const t of e.partition.values())qe.set(String(a(t)),t);Te.length=0,ze=0,$e=O,ut=void 0},On=()=>{const e=Te.shift();e&&(e.op==="del"?qe.delete(e.key):qe.set(e.key,e.row),$e=e.seq,ut=e.t)},ir=()=>{if(ie!=null)for(;Te.length>ie;)On();if(he!=null&&Te.length){const e=Te[Te.length-1].t;for(;Te.length>1&&e-Te[0].t>he;)On()}},sr=e=>{!e||!e.row||Te.push({pos:ze++,seq:At(e),t:Qt(e),op:e.op==="delete"?"del":"set",key:String(a(e.row)),row:e.row})},sn=(e,t)=>t==="seq"?e.seq:e.t,qt=(e,t)=>{const n=new Map(qe);for(const r of Te){const o=sn(r,t);if(e!==void 0&&o!==void 0&&o>e)break;r.op==="del"?n.delete(r.key):n.set(r.key,r.row)}return n},zt=e=>{const t=new Map(Ne().map(n=>[n,[]]));for(const n of e)for(const r of Dt(n))t.get(r).push(n);for(const n of Ne())n.partition=new Map(t.get(n).map(r=>[String(n.keyOf(r)),r]));for(const n of Xe)Mt(n);Ot();for(const n of Ne())yt(n)},ln=e=>ve?!0:(A("data-router:no-buffer",`${e}() needs a buffered window; call router.buffer({ window, max }) first to record one.`),!1),Ut=()=>{if(rt&&(clearTimeout(rt),rt=null),wt=!1,Et=[],jt=0,gt){const e=gt;gt=null,e()}},lr=()=>{if(Et=[],jt=0,gt){const e=gt;gt=null,e()}},ar=()=>{rt=null;const e=Et[jt++];e.op==="del"?it.delete(e.key):it.set(e.key,e.row),zt([...it.values()]),Re=e.pos+1,an()};function an(){if(!wt){if(jt>=Et.length){lr();return}rt=setTimeout(ar,st)}}function Vt(e){if(je)try{je.postMessage(e)}catch{}}function Tn(){return{t:"snapshot",rows:Ct(),seq:O,checkpoint:Object.fromEntries(G)}}function ur(e){const t=e&&e.data;if(!(!t||typeof t!="object")){if(t.t==="hello"){Ct().length&&Vt(Tn());return}vt=!0;try{t.t==="delta"?Qe.apply(t.deltas||[]):t.t==="snapshot"&&(Qe.load(t.rows||[]),t.checkpoint&&Qe.seenThrough(t.checkpoint))}finally{vt=!1}}}function cr(e,t){e.partition=new Map(t.map(n=>[String(e.keyOf(n)),n]))}function fr(e,t){const n=t.filter(o=>!o.isDefault),r=t.find(o=>o.isDefault)||null;for(const o of t)o.partition=new Map;for(const o of e){const i=[];for(const f of n)if(f.match(o)&&(i.push(f),!S))break;const s=i.length?i:r?[r]:[];if(!s.length){ft+=1,W&&W(o);continue}for(const f of s)f.partition.set(String(f.keyOf(o)),o)}}const dr=(e,t)=>{if(typeof t=="function")return r=>t(r);let n=null;return t===!0?n=String(e):typeof t=="string"&&(n=t),n==null?null:(r,o=Ve)=>`${n}:${r[o]}`},Rn=(e,t)=>{const n={...e.map?e.map(t):t};if(e.fields&&vr(e,n),e.ns){const r=pr(e,n),o=e.ns(n,r||Ve);r&&(n[r]=o),n[Ve]=o}return n},pr=(e,t)=>{if(typeof h.rowKey!="function")return null;if(e.keyProp!==void 0)return e.keyProp;const n=new Set;try{h.rowKey(new Proxy(t,{get(r,o,i){return typeof o=="string"&&n.add(o),Reflect.get(r,o,i)}}))}catch{}return e.keyProp=n.size===1?[...n][0]:null,e.keyProp===null&&A(`data-router:function-key-namespace:${e.id}`,`addSource("${e.id}") sets \`key\` but the rowKey function does not read exactly one row property, so its ids cannot be namespaced and rows from different feeds sharing an id will replace one another. Use a property-name rowKey, or give each feed ids that are already distinct.`),e.keyProp},Nn=(e,t)=>{const n=[];for(const r of t||[]){if(!r||!r.row)continue;const o=Rn(e,r.row),i=String(o[Ve]);r.op==="delete"?e.live.delete(i):e.live.set(i,o),n.push({...r,row:o})}return e.ingested+=n.length,V(`source:${e.id}`,n.length),n},An=e=>({get id(){return e.id},get size(){return e.live.size},load(t){const n=(t||[]).map(i=>Rn(e,i)),r=new Map(n.map(i=>[String(i[Ve]),i])),o=[];for(const[i,s]of e.live)r.has(i)||o.push({op:"delete",row:s});for(const i of n)o.push({op:"upsert",row:i});return e.live=r,e.ingested+=n.length,V(`source:${e.id}`,n.length),xt(e,o,i=>Qe.apply(i)),this},apply(t){return xt(e,Nn(e,t),n=>Qe.apply(n)),this},push(t){return xt(e,Nn(e,Array.isArray(t)?t:[t]),n=>Qe.push(n)),this},remove(){const t=[];for(const n of e.live.values())t.push({op:"delete",row:n});return e.live.clear(),Se.delete(e.id),t.length&&Qe.apply(t),Qe}}),Gt=new Set(["text","number","integer","boolean","date","json"]),Fn=(e,t=".")=>{if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e!="string")return null;let n=e.trim();if(n===""||/\d\s*[*/^]\s*[\d.(]/.test(n)||(n=n.replace(/[\s\u00a0\u202f\u2009']/g,""),t===","?n=n.split(".").join("").replace(",","."):n=n.split(",").join(""),n=n.replace(/[^0-9eE+\-.]/g,""),n===""||n==="-"||n==="+"||n==="."||n==="-."||n==="+."))return null;const r=Number(n);return Number.isFinite(r)?r:null},hr=e=>{if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}},gr=(e,t,n)=>{A(`router:coerce-failed:${e.id}:${t.name}`,`source "${e.id}" field "${t.name}": could not coerce ${hr(n)} to ${t.type}; the value is stored as null.`)},mr=(e,t)=>{if(typeof t=="string")return Gt.has(t)?{name:e,type:t,format:null,decimal:null,trueSet:null,falseSet:null,nulls:null}:(A("data-router:field-type",`addSource field "${e}" names an unknown type "${t}" (expected ${[...Gt].join(", ")}); the field passes through uncoerced.`),null);if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.type==null?null:String(t.type);return n!=null&&!Gt.has(n)?(A("data-router:field-type",`addSource field "${e}" names an unknown type "${n}" (expected ${[...Gt].join(", ")}); the field passes through uncoerced.`),null):{name:e,type:n,format:typeof t.format=="string"?t.format:null,decimal:t.decimal===","||t.decimal==="."?t.decimal:null,trueSet:Array.isArray(t.true)&&t.true.length?new Set(t.true.map(String)):null,falseSet:Array.isArray(t.false)&&t.false.length?new Set(t.false.map(String)):null,nulls:Array.isArray(t.nulls)&&t.nulls.length?new Set(t.nulls.map(String)):null}}return A("data-router:field-spec",`addSource field "${e}" has an unusable fields declaration (a type string or an options object); the field passes through uncoerced.`),null},yr=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=[];for(const[n,r]of Object.entries(e)){const o=mr(n,r);o&&t.push(o)}return t.length?t:null},br=(e,t)=>{if(e==null)return null;const n=String(e).trim();if(n==="")return null;const r={yyyy:"(\\d{4})",yy:"(\\d{2})",MM:"(\\d{1,2})",M:"(\\d{1,2})",dd:"(\\d{1,2})",d:"(\\d{1,2})",HH:"(\\d{1,2})",mm:"(\\d{1,2})",ss:"(\\d{1,2})"},o=w=>w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");let i="^";const s=[];for(const w of _(t))if(w.token&&r[w.token])i+=r[w.token],s.push(w.token);else{if(w.token)return null;i+=o(w.text)}i+="$";const f=new RegExp(i).exec(n);if(!f)return null;const d={year:0,month:1,day:1,hour:0,minute:0,second:0};for(let w=0;w<s.length;w+=1){const j=Number(f[w+1]);if(Number.isNaN(j))return null;const B=s[w];B==="yyyy"?d.year=j:B==="yy"?d.year=2e3+j:B==="MM"||B==="M"?d.month=j:B==="dd"||B==="d"?d.day=j:B==="HH"?d.hour=j:B==="mm"?d.minute=j:B==="ss"&&(d.second=j)}const k=new Date(d.year,d.month-1,d.day,d.hour,d.minute,d.second);return Number.isNaN(k.getTime())?null:x(k)},wr=(e,t)=>{switch(e.type){case"text":return{ok:!0,value:typeof t=="string"?t:String(t)};case"number":{const n=Fn(t,e.decimal===","?",":".");return n==null?{ok:!1}:{ok:!0,value:n}}case"integer":{const n=Fn(t,e.decimal===","?",":".");return n==null||!Number.isInteger(n)?{ok:!1}:{ok:!0,value:n}}case"boolean":{if(typeof t=="boolean")return{ok:!0,value:t};if(e.trueSet||e.falseSet){const r=String(t);return e.trueSet&&e.trueSet.has(r)?{ok:!0,value:!0}:e.falseSet&&e.falseSet.has(r)?{ok:!0,value:!1}:{ok:!1}}const n=z(t);return n==null?{ok:!1}:{ok:!0,value:n}}case"date":{const n=e.format||"iso";if(n==="epoch-s"){const o=Number(t),i=o*1e3;if(!Number.isFinite(o)||!Number.isFinite(i))return{ok:!1};const s=x(new Date(i));return s==null?{ok:!1}:{ok:!0,value:s}}if(n==="epoch-ms"){const o=Number(t);if(!Number.isFinite(o))return{ok:!1};const i=x(new Date(o));return i==null?{ok:!1}:{ok:!0,value:i}}if(n==="iso"){const o=x(t);return o==null?{ok:!1}:{ok:!0,value:o}}const r=br(t,n);return r==null?{ok:!1}:{ok:!0,value:r}}case"json":{if(typeof t!="string")return{ok:!0,value:t};try{return{ok:!0,value:JSON.parse(t)}}catch{return{ok:!1}}}default:return{ok:!0,value:t}}},kr=(e,t,n)=>{const r=n[t.name];if(r==null||typeof r=="number"&&Number.isNaN(r)){n[t.name]=null;return}if(t.nulls&&t.nulls.has(String(r))){n[t.name]=null;return}if(t.type==null)return;if(t.type!=="text"&&typeof r=="string"&&r.trim()===""){n[t.name]=null;return}const o=wr(t,r);if(!o.ok){gr(e,t,r),n[t.name]=null;return}n[t.name]=o.value},vr=(e,t)=>{for(const n of e.fields)kr(e,n,t)},Tt=e=>e==null?null:String(e),un=(e,t)=>{if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!un(e[n],t[n]))return!1;return!0}if(e&&t&&typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!un(e[o],t[o]))return!1;return!0}return!1},cn=(e,t)=>{if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n)if(!un(e[o],t[o]))return!1;return!0},Sr=Object.freeze(["count","sum","avg","min","max","distinctCount","first","last"]),Er=Object.freeze(["sum","avg","min","max","distinctCount","first","last"]),jr=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=[];for(const[n,r]of Object.entries(e)){if(!r||typeof r!="object"||typeof r.fn!="string"){A("data-router:join-aggregate-bad-spec",`join aggregate "${n}" is not a { fn, field? } reducer; the aggregate is skipped.`);continue}if(!Sr.includes(r.fn)){A("data-router:join-aggregate-bad-fn",`join aggregate "${n}" uses fn "${r.fn}", which is not count|sum|avg|min|max|distinctCount|first|last; the aggregate is skipped.`);continue}const o=typeof r.field=="string"&&r.field?r.field:null;if(Er.includes(r.fn)&&!o){A("data-router:join-aggregate-no-field",`join aggregate "${n}" (${r.fn}) needs a field; the aggregate is skipped.`);continue}const i=r.fn==="first"||r.fn==="last"?typeof r.orderBy=="string"&&r.orderBy?r.orderBy:o:null;t.push([n,{fn:r.fn,field:o,orderBy:i}])}return t.length?t:null},fn=(e,t)=>{if(!(!e||typeof e!="object"))return t in e||A(`data-router:collect-select-field:${t}`,`a collect join's \`select\` names "${t}", which the collected rows do not have; it is collected as undefined.`),e[t]},Pr=(e,t)=>{if(!e||typeof e!="object")return null;const n=e.from!=null?String(e.from):null;if(!n)return A("data-router:join-no-from","join needs a `from` (the lookup source id); ignoring the join."),null;const r=e.many===!0||e.spread!=null;let o=e.localKey!=null?e.localKey:e.on;o==null&&r&&(o=Ve);let i;if(typeof o=="function")i=o;else if(typeof o=="string")i=v=>v[o];else return A("data-router:join-no-localkey","join needs a `localKey` (a field name or fn); ignoring the join."),null;const s=e.foreignKey!=null?e.foreignKey:e.fromKey;let f,d;if(typeof s=="function")f=s,d=s;else if(typeof s=="string")f=v=>v[s],d=s;else if(typeof o=="string")f=v=>v[o],d=o;else return A("data-router:join-no-foreignkey","join with a fn `localKey` needs an explicit string/fn `foreignKey`; ignoring the join."),null;if(r){if(e.spread!=null){const Pe=e.spread&&typeof e.spread=="object"?e.spread:{},Ke=Pe.name,dt=Pe.value;let Wt,yn;if(typeof Ke=="function")Wt=Ke;else if(typeof Ke=="string"&&Ke.length)Wt=bt=>bt[Ke];else return A("data-router:spread-no-name","a spread join needs a `name` (the attribute-name field or fn); ignoring the join."),null;if(typeof dt=="function")yn=dt;else if(typeof dt=="string"&&dt.length)yn=bt=>bt[dt];else return A("data-router:spread-no-value","a spread join needs a `value` (the attribute-value field or fn); ignoring the join."),null;const zr=typeof Pe.prefix=="string"?Pe.prefix:"";let bn=null;const Jt=Pe.include;if(typeof Jt=="function")bn=Jt;else if(Array.isArray(Jt)){const bt=new Set(Jt.map(It=>String(It)));bn=It=>bt.has(It)}const Hn=new Map;if(Pe.type&&typeof Pe.type=="object"&&!Array.isArray(Pe.type))for(const[bt,It]of Object.entries(Pe.type))Ir.includes(It)&&Hn.set(bt,It);return{many:!0,spread:!0,from:n,localKey:i,foreignKeyFn:f,ffKey:d,nameFn:Wt,valueFn:yn,prefix:zr,includeFn:bn,typeOf:bt=>Hn.get(bt),keyIndex:new Map,lastFk:new Map,owner:t,probe:null,spreadPrev:new Map}}let v=e.missing;if(v!=="hold"&&v!=="passthrough"&&v!=="null"&&(v!=null&&A("data-router:join-bad-missing",`join.missing "${v}" is not hold|passthrough|null; using "passthrough".`),v="passthrough"),e.aggregate!=null){const Pe=jr(e.aggregate);if(!Pe)return A("data-router:join-aggregate-invalid","a join aggregate must be a non-empty object of named reducers; ignoring the join."),null;const Ke=typeof e.where=="function"?e.where:null;return{many:!0,aggregate:Pe,whereFn:Ke,from:n,localKey:i,foreignKeyFn:f,ffKey:d,missing:v,keyIndex:new Map,lastFk:new Map,owner:t,probe:null}}if(typeof e.as!="string"||!e.as)return A("data-router:join-no-as","a collect join (many: true) needs an `as` (the field to put the collected array into); ignoring the join."),null;let ye=null;const Ie=e.select!=null?e.select:e.fields;typeof Ie=="function"?ye=Ie:typeof Ie=="string"&&Ie?ye=Pe=>fn(Pe,Ie):Array.isArray(Ie)&&Ie.length?ye=Pe=>{const Ke={};for(const dt of Ie)Ke[String(dt)]=fn(Pe,String(dt));return Ke}:Ie&&typeof Ie=="object"&&!Array.isArray(Ie)&&Object.keys(Ie).length&&(ye=Pe=>{const Ke={};for(const[dt,Wt]of Object.entries(Ie))Ke[String(Wt)]=fn(Pe,dt);return Ke}),ye||(ye=Pe=>Pe);const Rt=e.distinct===!0,Nt=e.sort===!0?!0:typeof e.sort=="function"?e.sort:!1,St=e.onParentDelete==="cascade"||e.onParentDelete==="orphan"?e.onParentDelete:"keep";return{many:!0,from:n,localKey:i,foreignKeyFn:f,ffKey:d,as:e.as,selectFn:ye,distinct:Rt,sort:Nt,missing:v,onParentDelete:St,keyIndex:new Map,lastFk:new Map,owner:t,probe:null}}let k=null;const w=[],j=e.fields!=null?e.fields:e.select;if(typeof j=="function")k=j;else if(Array.isArray(j))for(const v of j)w.push([String(v),String(v)]);else if(j&&typeof j=="object")for(const[v,ye]of Object.entries(j))w.push([v,String(ye)]);else A("data-router:join-no-fields","join has no `fields`/`select`; rows pass through unenriched.");let B=e.missing;return B!=="hold"&&B!=="passthrough"&&B!=="null"&&(B!=null&&A("data-router:join-bad-missing",`join.missing "${B}" is not hold|passthrough|null; using "passthrough".`),B="passthrough"),{many:!1,from:n,localKey:i,foreignKeyFn:f,ffKey:d,pairs:w,selectFn:k,missing:B,keyIndex:new Map,lastFk:new Map,owner:t,probe:null}},Or=(e,t)=>{const n=new Set,r=[e];for(;r.length;){const o=r.pop();if(o===t)return!0;if(n.has(o))continue;n.add(o);const i=Se.get(o);if(i)for(const s of i.joins)r.push(s.from)}return!1},$n=(e,t)=>{if(e==null)return[];const n=[];for(const o of Array.isArray(e)?e:[e]){const i=Pr(o,t);i&&n.push(i)}const r=[];for(const o of n){if(o.from===t.id||Or(o.from,t.id)){A("router:join-cycle",`join from "${t.id}" to "${o.from}" would close a join cycle; the join is refused.`);continue}r.push(o)}return r},Tr=(e,t)=>{const n=new Set;let r=Se.get(e);for(;r&&r.unnestParentId!=null&&!n.has(r.id);){if(n.add(r.id),r.unnestParentId===t)return!0;r=Se.get(r.unnestParentId)}return!1},Rr=(e,t)=>{if(!e||typeof e!="object")return null;const n=typeof e.path=="string"&&e.path?e.path:null;if(!n)return A("data-router:unnest-no-path","an unnest needs a `path` (the dotted array field on the row); ignoring the unnest."),null;const r=typeof e.as=="string"&&e.as?e.as:null;if(!r)return A("data-router:unnest-no-as","an unnest needs an `as` (the child row type); ignoring the unnest."),null;if(r===t.id||Tr(t.id,r))return A("router:unnest-cycle",`unnest "${t.id}" → "${r}" would close an unnest cycle; the unnest is refused.`),null;const o=typeof e.parentKey=="string"&&e.parentKey?e.parentKey:`${t.id}Id`,i=e.keep===!0;let s;if(typeof e.key=="function")s=e.key;else if(typeof e.key=="string"&&e.key){const k=e.key;s=w=>w[k]}else s=null;let f=Se.get(r);if(!f){f={id:r,map:null,fields:null,ns:null,live:new Map,out:new Map,ingested:0,joins:[],unnests:[],unnestParentId:t.id},f.handle=An(f),Se.set(r,f),f.joins=$n(e.join,f),f.unnests=Dn(e.unnest,f);for(const k of f.joins)Se.has(k.from)&&_t(Se.get(k.from),k);for(const k of Se.values())if(k!==f)for(const w of k.joins)w.from===r&&w.probe==null&&_t(f,w)}const d=e.onParentDelete==="orphan"||e.onParentDelete==="keep"?e.onParentDelete:"cascade";return{path:n,as:r,keyFn:s,parentKeyField:o,keep:i,owner:t,child:f,onParentDelete:d,prevChildren:new Map}},Dn=(e,t)=>{if(e==null)return[];const n=[];for(const r of Array.isArray(e)?e:[e]){const o=Rr(r,t);o&&n.push(o)}return n},Nr=(e,t)=>{const n=[];let r=0;for(const o of t||[]){if(!o||!o.row)continue;const i=String(o.row[Ve]),s=e.prevChildren.get(i)||new Map;if(o.op==="delete"){for(const[w,j]of s)if(e.onParentDelete==="orphan"){if(j.__orphan===!0)continue;const B={...j,__orphan:!0};e.child.live.set(w,B),n.push({op:"upsert",row:B}),r+=1}else e.onParentDelete==="keep"||(e.child.live.delete(w),n.push({op:"delete",row:j}));e.prevChildren.delete(i);continue}const f=$(o.row,e.path),d=Array.isArray(f)?f:[],k=new Map;for(let w=0;w<d.length;w+=1){const j=d[w],B=e.keyFn?e.keyFn(j,o.row,w):null,v=B==null?`${i}:${w}`:String(B);k.has(v)&&A("router:unnest-duplicate-key",`the unnest "${e.as}" produced the child key "${v}" more than once for one parent; the later child (source order) wins.`);const ye={...j&&typeof j=="object"?j:{}};ye[e.parentKeyField]=o.row[Ve],ye[Ve]=v,m&&(ye[m]=e.as);const Ie=e.child.live.get(v);Ie&&Ie.__orphan===!0&&(ye.__orphan=void 0),k.set(v,ye)}for(const[w,j]of s)k.has(w)||(e.child.live.delete(w),n.push({op:"delete",row:j}));for(const[w,j]of k){const B=s.get(w);B===void 0?(e.child.live.set(w,j),n.push({op:"upsert",row:j})):cn(B,j)||(e.child.live.set(w,j),n.push({op:"upsert",row:j}))}e.prevChildren.set(i,k)}return r>0&&A("router:orphaned-rows",`${r} child row(s) were orphaned when their parent was deleted; they are kept and marked __orphan: true (onParentDelete: 'orphan').`),n},Mn=(e,t,n)=>{const r={...t};if(e.selectFn){const o=e.selectFn(n,t);return o&&typeof o=="object"&&Object.assign(r,o),r}for(const[o,i]of e.pairs)r[i]=n?n[o]:null;return r},Ar=(e,t)=>{if(t==null||!e.probe)return null;const n=e.probe.index.get(t);if(!n||!n.size)return null;const r=Se.get(e.from);if(!r)return null;let o;for(o of n);return r.out&&r.out.get(o)||null},Fr=(e,t,n)=>{const r=Se.get(e.from),o=[];if(n!=null&&r&&e.probe){const s=e.probe.index.get(n);if(s)for(const f of s){const d=r.out?r.out.get(f):void 0;d!==void 0&&o.push(e.selectFn(d,t))}}if(e.missing==="hold"&&o.length===0)return{hold:!0};if(e.missing==="null"&&o.length===0)return{hold:!1,value:null};let i=o;if(e.distinct){const s=new Map,f=[];for(const d of i){const k=typeof d=="object"&&d!==null?JSON.stringify(d):`${typeof d}:${String(d)}`;s.has(k)||(s.set(k,!0),f.push(d))}i=f}return e.sort&&(i=i.slice().sort(e.sort===!0?In:e.sort)),{hold:!1,value:i}},In=(e,t)=>{if(e===t)return 0;if(e==null)return-1;if(t==null)return 1;if(typeof e=="number"&&typeof t=="number")return e-t;const n=String(e),r=String(t);return n<r?-1:n>r?1:0},$r=(e,t)=>{const{fn:n,field:r,orderBy:o}=e;if(n==="count")return t.length;if(n==="first"||n==="last"){if(!t.length)return null;let s=t[0];for(let f=1;f<t.length;f+=1){const d=In(t[f][o],s[o]);(n==="first"&&d<0||n==="last"&&d>0)&&(s=t[f])}return r?s[r]:s}if(n==="distinctCount"){if(!t.length)return null;const s=new Set;for(const f of t)s.add(f[r]);return s.size}const i=r?t.map(s=>Number(s[r])).filter(s=>Number.isFinite(s)):[];return n==="sum"?i.reduce((s,f)=>s+f,0):n==="avg"?i.length?i.reduce((s,f)=>s+f,0)/i.length:null:n==="min"?i.length?Math.min(...i):null:n==="max"&&i.length?Math.max(...i):null},Dr=(e,t)=>e.map(([n,r])=>[n,$r(r,t)]),Mr=(e,t)=>{const n=Se.get(e.from),r=[];let o=!1;if(t!=null&&n&&e.probe){const i=e.probe.index.get(t);if(i)for(const s of i){const f=n.out?n.out.get(s):void 0;f!==void 0&&(o=!0,(!e.whereFn||e.whereFn(f))&&r.push(f))}}return e.missing==="hold"&&!o?{hold:!0}:{hold:!1,values:Dr(e.aggregate,r)}},Ir=Object.freeze(["number","date","boolean","text"]);function Lr(e,t){if(e==null)return e;if(t==="number"){if(typeof e=="number")return e;const n=Number(e);return Number.isFinite(n)?n:e}if(t==="date"){if(e instanceof Date)return e;const n=new Date(e);return Number.isNaN(n.getTime())?e:n}if(t==="boolean"){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no"||n==="")return!1}return!!e}return t==="text"?String(e):e}const Cr=(e,t)=>{const n=Se.get(e.from),r=new Map;if(t!=null&&n&&e.probe){const o=e.probe.index.get(t);if(o)for(const i of o){const s=n.out?n.out.get(i):void 0;if(s===void 0)continue;const f=e.nameFn(s);if(f==null)continue;const d=String(f);if(e.includeFn&&!e.includeFn(d,s))continue;const k=e.prefix+d;r.has(k)&&A("router:spread-duplicate",`a spread join wrote the field "${k}" more than once for one parent; the last attribute row (source order) wins.`),r.set(k,Lr(e.valueFn(s),e.typeOf?e.typeOf(d):void 0))}}return r},dn=(e,t,n)=>{const r=e.lastFk.get(t);if(r!==void 0&&r!==n){const i=e.keyIndex.get(r);i&&(i.delete(t),i.size||e.keyIndex.delete(r))}if(n==null){e.lastFk.set(t,null);return}let o=e.keyIndex.get(n);o||(o=new Set,e.keyIndex.set(n,o)),o.add(t),e.lastFk.set(t,n)},pn=(e,t,n)=>{const r=e.joins.indexOf(n);for(let o=r+1;o<e.joins.length;o+=1){const i=e.joins[o];dn(i,t,null),i.lastFk.delete(t)}},Ln=(e,t,n)=>{let r={...t};if(e.unnests&&e.unnests.length)for(const o of e.unnests)o.keep||X(r,o.path);for(const o of e.joins){const i=Tt(o.localKey(r));if(dn(o,n,i),o.spread){const s=Cr(o,i),f=o.spreadPrev.get(n)||new Set,d=new Set;for(const[k,w]of s){if(Object.prototype.hasOwnProperty.call(t,k)){A("router:spread-collision",`a spread join skipped the field "${k}" because the parent row already carries it; a spread field never overwrites a base parent field.`),d.add(k);continue}r[k]=w,F.add(k),d.add(k)}for(const k of f)d.has(k)||(r[k]=void 0);o.spreadPrev.set(n,d)}else if(o.many)if(o.aggregate){const s=Mr(o,i);if(s.hold)return pn(e,n,o),{emit:!1,row:t};for(const[f,d]of s.values)r[f]=d}else{const s=Fr(o,r,i);if(s.hold)return pn(e,n,o),{emit:!1,row:t};r[o.as]=s.value}else{const s=Ar(o,i);if(s)r=Mn(o,r,s);else{if(o.missing==="hold")return pn(e,n,o),{emit:!1,row:t};o.missing==="null"&&(r=Mn(o,r,null))}}}return{emit:!0,row:r}},_t=(e,t)=>{e.probes||(e.probes=new Map);let n=e.probes.get(t.ffKey);if(!n){n={fn:t.foreignKeyFn,index:new Map,prev:new Map,specs:new Set},e.probes.set(t.ffKey,n);for(const[r,o]of e.live){const i=Tt(n.fn(o));if(i==null)continue;let s=n.index.get(i);s||(s=new Set,n.index.set(i,s)),s.add(r),n.prev.set(r,i)}}n.specs.add(t),t.probe=n},Cn=(e,t,n)=>{const r=e.live.get(t);if(!r)return;const o=e.out.get(t),i=Ln(e,r,t);let s=!1;i.emit?(e.out.set(t,i.row),(o===void 0||!cn(o,i.row))&&(n.push({op:"upsert",row:i.row}),s=!0)):(e.out.delete(t),o!==void 0&&(n.push({op:"delete",row:o}),s=!0)),s&&xn(e,new Set([t]),n)},xn=(e,t,n)=>{if(!(!e.probes||!e.probes.size))for(const r of e.probes.values()){const o=new Set;for(const i of t){const s=e.live.get(i),f=s?Tt(r.fn(s)):null;f!=null&&o.add(f)}if(o.size)for(const i of r.specs)for(const s of o){const f=i.keyIndex.get(s);if(f)for(const d of[...f])Cn(i.owner,d,n)}}},xt=(e,t,n)=>{if(e.unnests&&e.unnests.length)for(const f of e.unnests){const d=Nr(f,t);d.length&&xt(f.child,d,n)}{const f=[],d=[];for(const k of t)!k||!k.row||(k.op==="delete"?f.push(k.row):d.push(k.row));if(f.length||d.length){const k=[];for(const v of e.joins)if(v.many&&!v.aggregate&&!v.spread&&(v.onParentDelete==="cascade"||v.onParentDelete==="orphan")){const ye=Se.get(v.from);k.push({childSource:ye,pkFn:v.localKey,fkFn:v.foreignKeyFn,index:v.probe?v.probe.index:null,mode:v.onParentDelete,writeBack:!1})}for(const v of L)v.parentId===e.id&&k.push({childSource:Se.get(v.childId),pkFn:v.pkFn,fkFn:v.fkFn,index:v.probe?v.probe.index:null,mode:v.onParentDelete,writeBack:v.writeBack});const w=new Map;let j=0;const B=v=>{let ye=w.get(v.id);return ye||(ye={source:v,deltas:[],writeBack:[]},w.set(v.id,ye)),ye};for(const v of k)if(!(!v.childSource||!v.index)){for(const ye of f){const Ie=Tt(v.pkFn(ye));if(Ie==null)continue;const Rt=v.index.get(Ie);if(!Rt)continue;const Nt=B(v.childSource);for(const St of[...Rt]){const Pe=v.childSource.live.get(St);if(Pe){if(v.mode==="cascade")v.childSource.live.delete(St),Nt.deltas.push({op:"delete",row:Pe}),v.writeBack&&Nt.writeBack.push(Pe);else if(Pe.__orphan!==!0){const Ke={...Pe,__orphan:!0};v.childSource.live.set(St,Ke),Nt.deltas.push({op:"upsert",row:Ke}),j+=1}}}}if(v.mode==="orphan")for(const ye of d){const Ie=Tt(v.pkFn(ye));if(Ie==null)continue;const Rt=v.index.get(Ie);if(!Rt)continue;const Nt=B(v.childSource);for(const St of[...Rt]){const Pe=v.childSource.live.get(St);if(!Pe||Pe.__orphan!==!0)continue;const Ke={...Pe,__orphan:void 0};v.childSource.live.set(St,Ke),Nt.deltas.push({op:"upsert",row:Ke})}}}j>0&&A("router:orphaned-rows",`${j} child row(s) were orphaned when their parent was deleted; they are kept and marked __orphan: true (onParentDelete: 'orphan').`);for(const v of w.values())if(v.deltas.length&&xt(v.source,v.deltas,n),v.writeBack.length&&Be)for(const ye of v.writeBack)try{Be({op:"delete",key:String(ye[Ve]),row:ye},{route:null,source:v.source.handle})}catch{}}}const r=new Map;if(e.probes&&e.probes.size)for(const f of e.probes.values()){const d=new Set;for(const k of t){const w=String(k.row[Ve]);if(k.op==="delete"){const v=f.prev.get(w);if(v!=null){const ye=f.index.get(v);ye&&(ye.delete(w),ye.size||f.index.delete(v)),d.add(v)}f.prev.delete(w);continue}const j=Tt(f.fn(k.row)),B=f.prev.get(w);if(B!=null&&B!==j){const v=f.index.get(B);v&&(v.delete(w),v.size||f.index.delete(B)),d.add(B)}if(j!=null){let v=f.index.get(j);v||(v=new Set,f.index.set(j,v)),v.add(w),d.add(j)}f.prev.set(w,j)}d.size&&r.set(f,d)}const o=[],i=new Set;for(const f of t){const d=String(f.row[Ve]);if(f.op==="delete"){for(const B of e.joins)dn(B,d,null),B.lastFk.delete(d),B.spread&&B.spreadPrev.delete(d);const j=e.out.get(d);e.out.delete(d),j!==void 0&&(o.push(f),i.add(d));continue}const k=e.out.get(d),w=Ln(e,f.row,d);w.emit?(e.out.set(d,w.row),(k===void 0||!cn(k,w.row))&&(o.push({...f,row:w.row}),i.add(d))):(e.out.delete(d),k!==void 0&&(o.push({op:"delete",row:k}),i.add(d)))}n(o);const s=[];if(r.size)for(const[f,d]of r)for(const k of f.specs)for(const w of d){const j=k.keyIndex.get(w);if(j)for(const B of[...j])Cn(k.owner,B,s)}i.size&&xn(e,i,s),s.length&&Qe.apply(s)},hn=(e,t,n)=>{const r=me.get(e);if(me.set(e,{cur:t,t:n}),!r)return 0;const o=(n-r.t)/1e3;return o<=0?0:(t-r.cur)/o},xr=()=>{if(!ve)return 0;let e=0;for(const t of Te)t.pos>=Re&&(e+=1);return e},Wn=(e,t)=>{const n=we.get(e);if(n)for(const r of n)try{r(t)}catch{}},Wr=()=>{be||He<=0||(be=setInterval(()=>Wn("metrics",Qe.metrics()),He),be&&typeof be.unref=="function"&&be.unref())},Bn=()=>{be&&(clearInterval(be),be=null)},Br=e=>{const t=e.indexedDB||(typeof indexedDB<"u"?indexedDB:null);if(!t)return null;const n=typeof e.dbName=="string"?e.dbName:"lattice-router",r=typeof e.storeName=="string"?e.storeName:"snapshots";let o=null;const i=()=>o||(o=new Promise((s,f)=>{let d;try{d=t.open(n,1)}catch(k){f(k);return}d.onupgradeneeded=()=>{const k=d.result;k.objectStoreNames.contains(r)||k.createObjectStore(r)},d.onsuccess=()=>s(d.result),d.onerror=()=>f(d.error)}),o);return{set(s,f){return i().then(d=>new Promise((k,w)=>{const j=d.transaction(r,"readwrite");j.objectStore(r).put(f,s),j.oncomplete=()=>k(),j.onerror=()=>w(j.error),j.onabort=()=>w(j.error)}))},get(s){return i().then(f=>new Promise((d,k)=>{const j=f.transaction(r,"readonly").objectStore(r).get(s);j.onsuccess=()=>d(j.result),j.onerror=()=>k(j.error)}))},close(){o&&o.then(s=>{try{s.close()}catch{}},()=>{})}}},Hr=()=>ve?[...qt(void 0,ge).values()]:Ct(),Kr=()=>({v:1,world:Hr(),maxSeq:O,checkpoint:Object.fromEntries(G),buffer:ve?{on:!0,max:ie,window:he,domain:ge,pos:ze,baseSeq:$e,baseT:ut,base:[...qe.entries()],log:Te.map(e=>({pos:e.pos,seq:e.seq,t:e.t,op:e.op,key:e.key,row:e.row}))}:{on:!1}}),qr=e=>{if(!e||typeof e!="object")return!1;Me=!0;try{Qe.load(Array.isArray(e.world)?e.world:[])}finally{Me=!1}e.checkpoint&&Qe.seenThrough(e.checkpoint),Number.isFinite(e.maxSeq)&&(O===void 0||e.maxSeq>O)&&(O=e.maxSeq);const t=e.buffer;if(t&&t.on){ve=!0,ie=Number.isFinite(t.max)?t.max:null,he=Number.isFinite(t.window)?t.window:null,ge=t.domain==="seq"||t.domain==="time"?t.domain:Fe?"seq":"time",qe=new Map(Array.isArray(t.base)?t.base:[]),Te.length=0;for(const n of Array.isArray(t.log)?t.log:[])Te.push({...n});ze=Number.isFinite(t.pos)?t.pos:Te.length,$e=t.baseSeq,ut=t.baseT,Re=ze}return!0},gn=()=>{if(!ce)return Promise.resolve();const e=Kr(),t=Promise.resolve().then(()=>ce.set(Ue,e)).catch(()=>{});return fe=t,t.then(()=>{fe===t&&(fe=null)})},mn=()=>{if(!(!Ee||!ce||Me)){if(tt<=0){gn();return}De||(De=setTimeout(()=>{De=null,gn()},tt),De&&typeof De.unref=="function"&&De.unref())}},Qe={attach(e,t,n={}){const r=typeof t!="function",o=r?s=>p(s)===t:t;r&&vn(t);const i=rn(e,o,n);return r&&(i.hasPartValue=!0,i.partValue=t),_e.push(i),i.writable&&nr(i),this},attachDefault(e,t={}){return Je=rn(e,()=>!1,t),Je.isDefault=!0,this},subscribe(e,t,n={}){const r=typeof e!="function",o=r?s=>p(s)===e:e;r&&vn(e);const i=rn(t,o,n);return r&&(i.hasPartValue=!0,i.partValue=e),_e.push(i),this},alert(e,t,n,r={}){const i={match:typeof e=="function"?e:s=>p(s)===e,keyOf:ne(R(r.rowKey,"alerts"),c),filter:typeof r.filter=="function"?r.filter:null,condition:typeof t=="function"?t:()=>!1,handler:typeof n=="function"?n:()=>{},debounceMs:Number.isFinite(r.debounce)?Number(r.debounce):0,armed:!0,timer:null,pending:null,partition:new Map};return at.push(i),on(i,Ct()),Kt(i),this},monitor(e,t,n,r={}){const i={kind:"monitor",match:typeof e=="function"?e:s=>p(s)===e,keyOf:ne(R(r.rowKey,"alerts"),c),filter:typeof r.filter=="function"?r.filter:null,evaluate:typeof t=="function"?t:()=>{},handler:typeof n=="function"?n:()=>{},armed:!0,timer:null,pending:null,partition:new Map};return at.push(i),on(i,Ct()),Kt(i),()=>{const s=at.indexOf(i);s>=0&&at.splice(s,1),i.timer&&(clearTimeout(i.timer),i.timer=null),i.partition.clear()}},configure(e={}){const t=n=>({rowKey:n.rowKey,transform:n.transform,filter:n.filter,sort:n.sort,rollup:n.rollup,debounce:n.debounce,where:n.where,writable:n.writable,onWrite:n.onWrite,onConflict:n.onConflict,backpressure:n.backpressure,label:n.label});for(const n of e.routes||[])if(n){if(n.default!==void 0){this.attachDefault(n.default,t(n));continue}if(n.alert!==void 0){this.alert(n.when,n.condition,n.alert,t(n));continue}if(n.subscribe!==void 0){this.subscribe(n.when,n.subscribe,t(n));continue}this.attach(n.grid,n.when,t(n))}for(const n of e.links||[])n&&n.from&&n.to&&this.link(n.from,n.to,n.on!==void 0?n.on:n.relation);return e.relate&&this.relate(e.relate),e.buffer&&this.buffer(e.buffer),this},link(e,t,n){const r={from:e,to:t,relation:n,predicate:null};Xe.push(r),wn(e),Mt(r);const o=ot(t);return o&&yt(o),this},relate(e){for(const t of e||[]){if(!t||!t.from||!t.to)continue;const n=t.on!==void 0?t.on:t.relation!==void 0?t.relation:t.rel;Ye.push({from:t.from,to:t.to,rel:n}),t.mutual&&Ye.push({from:t.to,to:t.from,rel:We(n)})}for(const t of Lt())wn(t);Ot();for(const t of Lt()){const n=ot(t);n&&yt(n)}return this},flush(){return nn(),this},detach(e){const t=new Set;for(let o=Xe.length-1;o>=0;o--){const i=Xe[o];(i.from===e||i.to===e)&&(i.to!==e&&t.add(i.to),kn(i.from),Xe.splice(o,1))}let n=!1;for(let o=Ye.length-1;o>=0;o--)(Ye[o].from===e||Ye[o].to===e)&&(kn(Ye[o].from),Ye.splice(o,1),n=!0);for(let o=_e.length-1;o>=0;o--)_e[o].grid===e&&_e.splice(o,1);Je&&Je.grid===e&&(Je=null),Pt.delete(e);const r=mt.get(e);if(r&&(r(),mt.delete(e)),n){Ot();for(const o of Lt())t.add(o)}for(const o of t){const i=ot(o);i&&yt(i)}return this},load(e){ft=0;const t=new Map(Ne().map(r=>[r,[]]));for(const r of e||[]){const o=Dt(r);if(!o.length){ft+=1,W&&W(r);continue}for(const i of o)t.get(i).push(r)}for(const r of Ne()){const o=t.get(r);r.partition=new Map(o.map(i=>[String(r.keyOf(i)),i])),r.metricRows+=o.length,T+=o.length}if(Fe)for(const r of e||[]){const o=Fe(r);if(!Number.isFinite(o))continue;const i=String(a(r)),s=G.get(i);(s===void 0||o>s)&&G.set(i,o),(O===void 0||o>O)&&(O=o)}for(const r of Xe)Mt(r);Ot();for(const r of at)on(r,e||[]),Kt(r);for(const r of Ne())r.bp&&Jn(r);const n=Ne().map(r=>yt(r));return ve&&Pn(),Re=ze,je&&!vt&&Vt(Tn()),mn(),n},apply(e){let t=(e||[]).filter(o=>o&&o.row);if(Ze){t=t.map((i,s)=>[i,s]).sort((i,s)=>{const f=At(i[0]),d=At(s[0]);return f===void 0||d===void 0?i[1]-s[1]:f-d||i[1]-s[1]}).map(i=>i[0]);const o=[];for(const i of t){const s=At(i);if(s!==void 0){const f=String(a(i.row)),d=G.get(f);if(d!==void 0&&s<=d){Q+=1;continue}G.set(f,s),(O===void 0||s>O)&&(O=s)}o.push(i)}t=o}if(je&&!vt&&t.length&&Vt({t:"delta",deltas:t.map(o=>({op:o.op,row:o.row,seq:o.seq}))}),ve){for(const o of t)sr(o);ir()}for(const o of at)or(o,t),Kt(o);if(ct){mn();return}const n=new Map(Ne().map(o=>[o,new Map]));for(const o of t){const i=o&&o.row;if(!i)continue;if(o.op==="delete"){let f=!1;for(const d of Ne()){const k=String(d.keyOf(i));(d.partition.has(k)||n.get(d).has(k))&&(n.get(d).set(k,{op:"del"}),f=!0)}!f&&!Dt(i).length&&(ft+=1,W&&W(o));continue}const s=Dt(i);if(!s.length){ft+=1,W&&W(o);continue}for(const f of Ne()){if(s.includes(f))continue;const d=String(f.keyOf(i));(f.partition.has(d)||n.get(f).get(d)?.op==="set")&&n.get(f).set(d,{op:"del"})}for(const f of s)n.get(f).set(String(f.keyOf(i)),{op:"set",row:i})}const r=new Map;for(const o of Ne()){let i=0;const s=n.get(o).size;for(const[f,d]of n.get(o)){if(d.op==="del"){o.partition.delete(f);continue}o.partition.set(f,d.row),i+=1}o.metricRows+=i,T+=i,r.set(o,s)}for(const o of Xe)Mt(o);Ot();for(const o of Ne())_n(o,r.get(o)||0);Re=ze,mn()},push(e){const t=Array.isArray(e)?e:[e];if(!M)return this.apply(t),this;for(const n of t)Y.push(n);return g!==null&&(g<=0?this.flushStream():l||(l=setTimeout(()=>this.flushStream(),g))),this},flushStream(){if(l&&(clearTimeout(l),l=null),!Y.length)return this;const e=Y.splice(0,Y.length);return this.apply(e),this},flushBackpressure(){for(const e of Ne())e.bp&&(e.bpTimer||e.bpPending>0)&&Bt(e);return this},addSource(e,t){let n,r;e&&typeof e=="object"?(r=e,n=r.id!=null?String(r.id):`source${++Zt}`):(n=e!=null?String(e):`source${++Zt}`,r=t||{});const o=Se.get(n);if(o)return A("data-router:duplicate-source",`addSource("${n}") was already registered; returning the existing source handle. Use a distinct id per feed.`),o.handle;const i={id:n,map:typeof r.map=="function"?r.map:null,fields:yr(r.fields),ns:dr(n,r.key),live:new Map,out:new Map,ingested:0,joins:[],unnests:[]};i.handle=An(i),i.joins=$n(r.join,i),Se.set(n,i);for(const s of i.joins)Se.has(s.from)&&_t(Se.get(s.from),s);for(const s of Se.values())if(s!==i)for(const f of s.joins)f.from===n&&f.probe==null&&_t(i,f);return i.unnests=Dn(r.unnest,i),i.handle},removeSource(e){const t=e&&typeof e=="object"&&e.id!==void 0?String(e.id):String(e),n=Se.get(t);return n&&n.handle.remove(),this},sources(){return[...Se.keys()]},relateRows(e={}){const t=w=>w&&typeof w=="object"&&w.id!==void 0?String(w.id):String(w),n=t(e.child),r=t(e.parent),o=Se.get(n),i=Se.get(r);if(!o||!i)return A("data-router:relaterows-missing-source","relateRows needs both `child` and `parent` to be registered source ids (or the handles addSource returned); the rule was ignored."),this;let s,f;if(typeof e.foreignKey=="function")s=e.foreignKey,f=`fn:${s.toString()}`;else if(typeof e.foreignKey=="string"&&e.foreignKey)s=w=>w[e.foreignKey],f=e.foreignKey;else return A("data-router:relaterows-no-foreignkey","relateRows needs a `foreignKey` (the child field holding the parent key); the rule was ignored."),this;const d=e.onParentDelete==="cascade"||e.onParentDelete==="orphan"?e.onParentDelete:null;if(!d)return this;o.probes||(o.probes=new Map);let k=o.probes.get(f);if(!k){k={fn:s,index:new Map,prev:new Map,specs:new Set},o.probes.set(f,k);for(const[w,j]of o.live){const B=Tt(k.fn(j));if(B==null)continue;let v=k.index.get(B);v||(v=new Set,k.index.set(B,v)),v.add(w),k.prev.set(w,B)}}return L.push({parentId:r,childId:n,fkFn:s,pkFn:w=>w[Ve],onParentDelete:d,writeBack:e.writeBack===!0,probe:k}),this},fieldsOf(e){const t=Ge(e);return!t||!t.spreadFields?[]:[...t.spreadFields.keys()]},metrics(){const e=b(),t=Ne().map((r,o)=>({index:o,label:r.label||(r.isDefault?"default":null),kind:typeof r.grid=="function"?"view":"grid",rows:r.partition.size,shown:r.keys.size,routed:r.metricRows,throughput:hn(`route:${o}`,r.metricRows,e),backpressure:r.bp?{pending:r.bpPending,coalesced:r.bpCoalesced}:null})),n=[...Se.values()].map(r=>({id:r.id,rows:r.live.size,ingested:r.ingested,throughput:hn(`source:${r.id}`,r.ingested,e)}));return{routes:t,sources:n,unrouted:ft,dropped:Q,buffered:Te.length,lag:xr(),throughput:hn("total",T,e)}},on(e,t){if(typeof t!="function")return()=>{};let n=we.get(e);return n||(n=new Set,we.set(e,n)),n.add(t),e==="metrics"&&Wr(),()=>{n.delete(t),e==="metrics"&&n.size===0&&Bn()}},mountDevtools(e,t={}){return le(this,e,t)},get unrouted(){return ft},get dropped(){return Q},lastSeq(){return O},checkpoint(){return new Map(G)},seenThrough(e){const t=e instanceof Map?e.entries():Object.entries(e||{});for(const[n,r]of t){const o=Number(r);if(!Number.isFinite(o))continue;const i=G.get(String(n));(i===void 0||o>i)&&G.set(String(n),o),(O===void 0||o>O)&&(O=o)}return this},persist(e={}){if(Ee=!0,typeof e.key=="string"&&(Ue=e.key),Number.isFinite(e.debounce)&&(tt=Number(e.debounce)),e.storage&&typeof e.storage.get=="function"&&typeof e.storage.set=="function")ce=e.storage;else{let t=null;try{t=Br(e)}catch{t=null}t?ce=t:(ce=null,A("data-router:no-indexeddb","router.persist() found no usable IndexedDB (a non-browser runtime, private mode, or blocked storage); the router runs in-memory with no durable resume. Pass { storage } to use another backend."))}return this},async restore(){if(!ce)return!1;let e;try{e=await ce.get(Ue)}catch{return!1}return e==null?!1:qr(e)},async flushPersist(){return De&&(clearTimeout(De),De=null),await gn(),fe&&await fe,this},get persisting(){return Ee&&!!ce},buffer(e={}){return ve=!0,Number.isFinite(e.max)?ie=Number(e.max):"max"in e&&e.max==null&&(ie=null),Number.isFinite(e.window)?he=Number(e.window):"window"in e&&e.window==null&&(he=null),ie==null&&he==null&&(ie=I,A("data-router:buffer-default-cap",`buffer() called with no window or max; applying a default cap of ${I} deltas so the buffer stays bounded. Pass { window } or { max } to size it.`)),ge=Fe?"seq":"time",Pn(),this},scrubTo(e,t={}){if(!ln("scrubTo"))return this;Ut(),ct=!0;const n=t.by||ge;it=qt(e,n),zt([...it.values()]),Re=0;for(const r of Te){const o=sn(r,n);if(e!==void 0&&o!==void 0&&o>e)break;Re=r.pos+1}return this},replay(e,t,n={}){if(!ln("replay"))return Promise.resolve();Ut(),ct=!0;const r=n.by||ge;return Yt=r,st=Number.isFinite(n.speed)?Number(n.speed):0,it=qt(e,r),zt([...it.values()]),Et=Te.filter(o=>{const i=sn(o,r);return i!==void 0&&i>e&&i<=t}).slice().sort((o,i)=>o.pos-i.pos),jt=0,wt=!1,new Promise(o=>{gt=o,an()})},pause(){return wt=!0,rt&&(clearTimeout(rt),rt=null),this},resume(){return wt?(wt=!1,an(),this):this},live(){return ln("live")?(Ut(),ct=!1,it=null,zt([...qt(void 0,ge).values()]),Re=ze,this):this},get traveling(){return ct},get buffered(){return Te.length},broadcast(e={}){if(typeof BroadcastChannel!="function")return A("data-router:no-broadcastchannel","router.broadcast() needs the BroadcastChannel API, which this runtime does not provide; cross-tab mirroring is off."),this;const t=e&&typeof e.channel=="string"?e.channel:"";return t?(je&&(je.close(),je=null),je=new BroadcastChannel(t),je.onmessage=ur,Vt({t:"hello"}),this):(A("data-router:broadcast-channel","router.broadcast({ channel }) needs a string channel name; nothing was mirrored."),this)},get broadcasting(){return!!je},async query(e,t={}){if(!e||typeof e.execute!="function")return A("data-router:bad-query-source","router.query(adapter) needs an adapter with an execute(query) function (a DFQL/DuckDB adapter or a pushdown source); nothing was fetched."),this;const n=re(e.capabilities),r=t||{},o=r.filters||null,i=[];ft=0;const s=Ne().filter(d=>d.where),f=Ne().filter(d=>!d.where);for(const d of s){const k=Le(o,d.where),w=pe({...r,filters:k},n);let B=((await e.execute(w.pushed,r)).rows||[]).slice();w.residual&&w.residual.filters&&(B=B.filter(v=>oe(w.residual.filters,v))),B=B.filter(v=>d.match(v)),cr(d,B),i.push({route:d.grid,pushedFilter:!!(w.pushed&&w.pushed.filters),residual:w.unpushed.slice()})}if(f.length){const d=pe(r,n);let w=((await e.execute(d.pushed,r)).rows||[]).slice();d.residual&&d.residual.filters&&(w=w.filter(j=>oe(d.residual.filters,j))),fr(w,f),i.push({base:!0,pushedFilter:!!(d.pushed&&d.pushed.filters),residual:d.unpushed.slice()})}$t=i;for(const d of Xe)Mt(d);Ot();for(const d of Ne())yt(d);return this},lastQueryPlan(){return $t?$t.map(e=>({...e})):null},destroy(){if(lt&&(clearTimeout(lt),lt=null),l&&(clearTimeout(l),l=null),De&&(clearTimeout(De),De=null),ce&&typeof ce.close=="function")try{ce.close()}catch{}Ee=!1,ce=null,je&&(je.close(),je=null),vt=!1,Ut(),ve=!1,ct=!1,it=null,Te.length=0,qe.clear();for(const e of kt.values())e.off();kt.clear();for(const e of mt.values())e();mt.clear(),Ft.clear(),Se.clear(),Bn(),we.clear(),me.clear();for(const e of at)e.timer&&(clearTimeout(e.timer),e.timer=null);at.length=0;for(const e of Ne())e.bpTimer&&(clearTimeout(e.bpTimer),e.bpTimer=null);Xe.length=0,Ye.length=0,Pt.clear(),Y.length=0,G.clear(),_e.length=0,Je=null}};return h.config&&Qe.configure(h.config),Qe}function ht(h,p){if(h===p)return!0;if(!h||!p)return!1;const c=Object.keys(h),m=Object.keys(p);if(c.length!==m.length)return!1;for(const S of c)if(h[S]!==p[S])return!1;return!0}const xe=Ce});const Un=zn("packages/modules/data-router/index.js"),Ur=Un.createDataRouter;var Vr=Un.default;export{Ur as createDataRouter,Vr as default};
7
7
 
8
8
  //# sourceMappingURL=data-router.esm.min.js.map