@toolbox-web/grid 3.9.1 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/all.js +1 -1
  2. package/all.js.map +1 -1
  3. package/custom-elements.json +2 -2
  4. package/index.js +1 -1
  5. package/index.js.map +1 -1
  6. package/lib/core/grid.d.ts +8 -4
  7. package/lib/core/plugin/base-plugin.d.ts +7 -0
  8. package/lib/core/types.d.ts +8 -3
  9. package/lib/features/clipboard.js.map +1 -1
  10. package/lib/features/column-virtualization.js.map +1 -1
  11. package/lib/features/context-menu.js.map +1 -1
  12. package/lib/features/editing.js.map +1 -1
  13. package/lib/features/export.js.map +1 -1
  14. package/lib/features/filtering.js.map +1 -1
  15. package/lib/features/grouping-columns.js.map +1 -1
  16. package/lib/features/grouping-rows.js.map +1 -1
  17. package/lib/features/master-detail.js.map +1 -1
  18. package/lib/features/multi-sort.js.map +1 -1
  19. package/lib/features/pinned-columns.js.map +1 -1
  20. package/lib/features/pinned-rows.js.map +1 -1
  21. package/lib/features/pivot.js.map +1 -1
  22. package/lib/features/print.js.map +1 -1
  23. package/lib/features/registry.js +1 -1
  24. package/lib/features/registry.js.map +1 -1
  25. package/lib/features/reorder-columns.js.map +1 -1
  26. package/lib/features/responsive.js.map +1 -1
  27. package/lib/features/row-drag-drop.js.map +1 -1
  28. package/lib/features/selection.js.map +1 -1
  29. package/lib/features/server-side.js.map +1 -1
  30. package/lib/features/shell.js.map +1 -1
  31. package/lib/features/sticky-rows.js.map +1 -1
  32. package/lib/features/tooltip.js.map +1 -1
  33. package/lib/features/tree.js.map +1 -1
  34. package/lib/features/undo-redo.js.map +1 -1
  35. package/lib/features/visibility.js.map +1 -1
  36. package/lib/plugins/clipboard/index.js.map +1 -1
  37. package/lib/plugins/column-virtualization/index.js.map +1 -1
  38. package/lib/plugins/context-menu/context-menu-plugin.d.ts +9 -4
  39. package/lib/plugins/context-menu/index.js +1 -1
  40. package/lib/plugins/context-menu/index.js.map +1 -1
  41. package/lib/plugins/context-menu/types.d.ts +8 -4
  42. package/lib/plugins/editing/editors.d.ts +15 -0
  43. package/lib/plugins/editing/index.js +1 -1
  44. package/lib/plugins/editing/index.js.map +1 -1
  45. package/lib/plugins/editing/internal/dirty-tracking-manager.d.ts +2 -1
  46. package/lib/plugins/editing/types.d.ts +5 -1
  47. package/lib/plugins/export/index.js +1 -1
  48. package/lib/plugins/export/index.js.map +1 -1
  49. package/lib/plugins/filtering/filter-model.d.ts +22 -2
  50. package/lib/plugins/filtering/filter-panel-default.d.ts +15 -1
  51. package/lib/plugins/filtering/filtering-plugin.d.ts +5 -2
  52. package/lib/plugins/filtering/index.d.ts +1 -1
  53. package/lib/plugins/filtering/index.js +1 -1
  54. package/lib/plugins/filtering/index.js.map +1 -1
  55. package/lib/plugins/filtering/types.d.ts +58 -3
  56. package/lib/plugins/grouping-columns/index.js.map +1 -1
  57. package/lib/plugins/grouping-rows/grouping-rows-plugin.d.ts +7 -14
  58. package/lib/plugins/grouping-rows/grouping-rows.d.ts +48 -0
  59. package/lib/plugins/grouping-rows/index.d.ts +1 -1
  60. package/lib/plugins/grouping-rows/index.js +1 -1
  61. package/lib/plugins/grouping-rows/index.js.map +1 -1
  62. package/lib/plugins/grouping-rows/types.d.ts +21 -0
  63. package/lib/plugins/hierarchy/index.js.map +1 -1
  64. package/lib/plugins/master-detail/index.d.ts +1 -1
  65. package/lib/plugins/master-detail/index.js +1 -1
  66. package/lib/plugins/master-detail/index.js.map +1 -1
  67. package/lib/plugins/master-detail/master-detail-plugin.d.ts +28 -6
  68. package/lib/plugins/master-detail/master-detail.d.ts +0 -8
  69. package/lib/plugins/master-detail/types.d.ts +25 -1
  70. package/lib/plugins/multi-sort/index.js +1 -1
  71. package/lib/plugins/multi-sort/index.js.map +1 -1
  72. package/lib/plugins/pinned-columns/index.js.map +1 -1
  73. package/lib/plugins/pinned-rows/index.js.map +1 -1
  74. package/lib/plugins/pivot/index.js +1 -1
  75. package/lib/plugins/pivot/index.js.map +1 -1
  76. package/lib/plugins/pivot/pivot-plugin.d.ts +2 -0
  77. package/lib/plugins/pivot/types.d.ts +2 -0
  78. package/lib/plugins/print/index.js.map +1 -1
  79. package/lib/plugins/reorder-columns/index.js.map +1 -1
  80. package/lib/plugins/responsive/index.js.map +1 -1
  81. package/lib/plugins/row-drag-drop/index.js.map +1 -1
  82. package/lib/plugins/selection/index.js +1 -1
  83. package/lib/plugins/selection/index.js.map +1 -1
  84. package/lib/plugins/selection/selection-plugin.d.ts +8 -1
  85. package/lib/plugins/server-side/datasource-types.d.ts +28 -0
  86. package/lib/plugins/server-side/datasource.d.ts +7 -0
  87. package/lib/plugins/server-side/index.js +1 -1
  88. package/lib/plugins/server-side/index.js.map +1 -1
  89. package/lib/plugins/server-side/server-side-plugin.d.ts +61 -8
  90. package/lib/plugins/server-side/types.d.ts +9 -1
  91. package/lib/plugins/shared/form-field-target.d.ts +10 -0
  92. package/lib/plugins/shared/format-value.d.ts +12 -0
  93. package/lib/plugins/shell/index.js.map +1 -1
  94. package/lib/plugins/sticky-rows/index.js.map +1 -1
  95. package/lib/plugins/tooltip/index.js.map +1 -1
  96. package/lib/plugins/tree/index.js +1 -1
  97. package/lib/plugins/tree/index.js.map +1 -1
  98. package/lib/plugins/tree/tree-plugin.d.ts +5 -11
  99. package/lib/plugins/tree/types.d.ts +22 -6
  100. package/lib/plugins/undo-redo/history.d.ts +2 -1
  101. package/lib/plugins/undo-redo/index.js +1 -1
  102. package/lib/plugins/undo-redo/index.js.map +1 -1
  103. package/lib/plugins/undo-redo/types.d.ts +13 -1
  104. package/lib/plugins/undo-redo/undo-redo-plugin.d.ts +15 -2
  105. package/lib/plugins/visibility/index.js.map +1 -1
  106. package/package.json +1 -1
  107. package/umd/grid.all.umd.js +1 -1
  108. package/umd/grid.all.umd.js.map +1 -1
  109. package/umd/grid.umd.js +1 -1
  110. package/umd/grid.umd.js.map +1 -1
  111. package/umd/plugins/clipboard.umd.js.map +1 -1
  112. package/umd/plugins/column-virtualization.umd.js.map +1 -1
  113. package/umd/plugins/context-menu.umd.js +1 -1
  114. package/umd/plugins/context-menu.umd.js.map +1 -1
  115. package/umd/plugins/editing.umd.js +1 -1
  116. package/umd/plugins/editing.umd.js.map +1 -1
  117. package/umd/plugins/export.umd.js +1 -1
  118. package/umd/plugins/export.umd.js.map +1 -1
  119. package/umd/plugins/filtering.umd.js +1 -1
  120. package/umd/plugins/filtering.umd.js.map +1 -1
  121. package/umd/plugins/grouping-columns.umd.js.map +1 -1
  122. package/umd/plugins/grouping-rows.umd.js +1 -1
  123. package/umd/plugins/grouping-rows.umd.js.map +1 -1
  124. package/umd/plugins/hierarchy.umd.js.map +1 -1
  125. package/umd/plugins/master-detail.umd.js +1 -1
  126. package/umd/plugins/master-detail.umd.js.map +1 -1
  127. package/umd/plugins/multi-sort.umd.js +1 -1
  128. package/umd/plugins/multi-sort.umd.js.map +1 -1
  129. package/umd/plugins/pinned-columns.umd.js.map +1 -1
  130. package/umd/plugins/pinned-rows.umd.js.map +1 -1
  131. package/umd/plugins/pivot.umd.js +1 -1
  132. package/umd/plugins/pivot.umd.js.map +1 -1
  133. package/umd/plugins/print.umd.js.map +1 -1
  134. package/umd/plugins/reorder-columns.umd.js.map +1 -1
  135. package/umd/plugins/responsive.umd.js.map +1 -1
  136. package/umd/plugins/row-drag-drop.umd.js.map +1 -1
  137. package/umd/plugins/selection.umd.js +1 -1
  138. package/umd/plugins/selection.umd.js.map +1 -1
  139. package/umd/plugins/server-side.umd.js +1 -1
  140. package/umd/plugins/server-side.umd.js.map +1 -1
  141. package/umd/plugins/shell.umd.js.map +1 -1
  142. package/umd/plugins/sticky-rows.umd.js.map +1 -1
  143. package/umd/plugins/tooltip.umd.js.map +1 -1
  144. package/umd/plugins/tree.umd.js +1 -1
  145. package/umd/plugins/tree.umd.js.map +1 -1
  146. package/umd/plugins/undo-redo.umd.js +1 -1
  147. package/umd/plugins/undo-redo.umd.js.map +1 -1
  148. package/umd/plugins/visibility.umd.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../../../../libs/grid/src/lib/plugins/server-side/placeholder.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../../libs/grid/src/lib/core/internal/loading.ts","../../../../../../libs/grid/src/lib/core/internal/row-teardown.ts","../../../../../../libs/grid/src/lib/plugins/shared/loading-placeholder.ts","../../../../../../libs/grid/src/lib/plugins/server-side/datasource.ts","../../../../../../libs/grid/src/lib/plugins/server-side/server-side-plugin.ts"],"sourcesContent":["/**\n * ServerSide loading placeholders — the synthetic rows that stand in for nodes\n * whose block has not arrived yet.\n */\nimport type { LoadingPlaceholderRow } from './types';\n\n/**\n * Create the placeholder for node `index`. `__rowCacheKey` keys the variable-height\n * cache so a consumer `getRowId` is never consulted for a placeholder.\n */\nexport function createLoadingPlaceholder(index: number): LoadingPlaceholderRow {\n return { __loading: true, __index: index, __rowCacheKey: `__loading:${index}` } as LoadingPlaceholderRow;\n}\n\n/**\n * Type guard for ServerSide loading placeholders.\n *\n * With the default `placeholderRendering: 'loading-row'` the grid renders placeholders\n * itself, so column renderers, value accessors, `format` and `rowClass` are never called\n * for them while rendering. Use this guard where placeholders still reach your code: with\n * `placeholderRendering: 'columns'` (including a Responsive `cardRenderer`), in a\n * `sortComparator` or `gridConfig.sortHandler` under `sortMode: 'local'`, in Export\n * `mode: 'formatted'` / `processCell` and Clipboard copy (which call `format`), or when\n * reading `grid.rows` directly.\n *\n * @example\n * ```ts\n * import { isLoadingPlaceholder } from '@toolbox-web/grid/plugins/server-side';\n *\n * const loaded = grid.rows.filter((row) => !isLoadingPlaceholder(row));\n * ```\n * @since 3.9.1\n */\nexport function isLoadingPlaceholder(row: unknown): row is LoadingPlaceholderRow {\n return (\n row != null &&\n typeof row === 'object' &&\n (row as { __loading?: unknown }).__loading === true &&\n typeof (row as { __index?: unknown }).__index === 'number'\n );\n}\n","/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, alias collapse)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n * 140–149 DataSource / ServerSide\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","// Centralized template expression evaluation & sanitization utilities.\n// Responsible for safely interpolating {{ }} expressions while blocking\n// access to dangerous globals / reflective capabilities.\nimport type { CompiledViewFunction, EvalContext } from '../types';\n\n// #region Constants\nconst EXPR_RE = /{{\\s*([^}]+)\\s*}}/g;\nconst EMPTY_SENTINEL = '__DG_EMPTY__';\nconst SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/;\n\n// Forbidden identifiers built at runtime to avoid static analysis scanners\n// from flagging string literals (e.g. socket.dev \"network access\" / \"uses eval\").\n// Stored as reversed, pipe-delimited tokens — reversed back when constructing the regex.\nconst _F =\n '__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles'\n .split('|')\n .map((s) => s.split('').reverse().join(''));\nconst FORBIDDEN = new RegExp(`__(proto|defineGetter|defineSetter)|${_F.slice(3).join('|')}|this\\\\b`);\n// #endregion\n\n// #region HTML Sanitization\n\n/**\n * Escape a plain text string for safe insertion into HTML.\n * Converts special HTML characters to their entity equivalents.\n *\n * @param text - Plain text string to escape\n * @returns HTML-safe string\n */\nexport function escapeHtml(text: string): string {\n if (!text || typeof text !== 'string') return '';\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Tags that are considered dangerous and will be completely removed.\n * These can execute scripts, load external resources, or manipulate the page.\n */\nconst DANGEROUS_TAGS = new Set(\n 'script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math'.split(\n '|',\n ),\n);\n\n/**\n * Attributes that are considered dangerous - event handlers and data loading.\n */\nconst DANGEROUS_ATTR_PATTERN = /^on\\w+$/i;\n\n/**\n * Attributes that can contain URLs which might be javascript: or data: URIs.\n */\nconst URL_ATTRS = new Set('href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset'.split('|'));\n\n/**\n * Protocol patterns that are dangerous in URLs.\n */\nconst DANGEROUS_URL_PROTOCOL = /^\\s*(javascript|vbscript|data|blob):/i;\n\n/**\n * Sanitize an HTML string by removing dangerous tags and attributes.\n *\n * Prefer {@link setSanitizedHTML} wherever the result is destined for an\n * element: this function has to re-serialize the sanitized tree back to a\n * string, and the caller's `innerHTML =` then re-parses it. That\n * parse→serialize→parse round trip is the classic mutation-XSS vector, and it\n * costs a second parse. Use this overload only when a string is genuinely\n * required (e.g. the value is stored, compared, or handed to another API).\n *\n * @param html - Raw HTML string to sanitize\n * @returns Sanitized HTML string safe for innerHTML\n */\nexport function sanitizeHTML(html: string): string {\n if (!html || typeof html !== 'string') return '';\n\n // Fast path: if no HTML tags at all, return as-is (already safe)\n if (html.indexOf('<') === -1) return html;\n\n const template = document.createElement('template');\n template.innerHTML = html;\n\n sanitizeNode(template.content);\n\n return template.innerHTML;\n}\n\n/**\n * Parse and sanitize an HTML string into a detached {@link DocumentFragment}.\n *\n * This is the primitive {@link setSanitizedHTML} builds on, exposed for callers\n * that need to inspect or relocate the nodes before insertion.\n *\n * @param html - Raw HTML string to sanitize\n * @returns Fragment containing the sanitized nodes (empty for falsy input)\n */\nexport function sanitizeToFragment(html: string): DocumentFragment {\n const template = document.createElement('template');\n if (html && typeof html === 'string') {\n template.innerHTML = html;\n sanitizeNode(template.content);\n }\n return template.content;\n}\n\n/**\n * Replace an element's children with the sanitized parse of `html`.\n *\n * **This is the canonical sink for user-supplied markup** — cell/header/group\n * renderer string returns, `gridConfig.icons.*`, light-DOM tool panel fallback\n * content, and any new extension point that turns a user string into markup.\n * `textContent` is wrong here (it renders SVG icon strings as literal text) and\n * raw `innerHTML` is wrong (it is an XSS sink).\n *\n * Nodes are moved from the parse fragment rather than re-serialized, so the\n * sanitized tree is exactly what lands in the document.\n *\n * @param el - Element whose children are replaced\n * @param html - Raw HTML string to sanitize and insert\n */\nexport function setSanitizedHTML(el: Element, html: string): void {\n if (!html || typeof html !== 'string') {\n el.replaceChildren();\n return;\n }\n // Nothing for the parser to do: no markup and no entities to decode.\n if (html.indexOf('<') === -1 && html.indexOf('&') === -1) {\n el.textContent = html;\n return;\n }\n el.replaceChildren(sanitizeToFragment(html));\n}\n\n/**\n * Recursively sanitize a DOM node tree.\n */\nfunction sanitizeNode(root: DocumentFragment | Element): void {\n const toRemove: Element[] = [];\n\n // Use querySelectorAll to find all elements, then filter\n const elements = root.querySelectorAll('*');\n\n for (const el of elements) {\n const tagName = el.tagName.toLowerCase();\n\n // Check if tag is dangerous\n if (DANGEROUS_TAGS.has(tagName)) {\n toRemove.push(el);\n continue;\n }\n\n // SVG elements need special handling - they can contain script-like behavior\n if (tagName === 'svg' || el.namespaceURI === 'http://www.w3.org/2000/svg') {\n // Remove entire SVG if it has any suspicious attributes\n const hasDangerousContent = Array.from(el.attributes).some(\n (attr) => DANGEROUS_ATTR_PATTERN.test(attr.name) || attr.name === 'href' || attr.name === 'xlink:href',\n );\n if (hasDangerousContent) {\n toRemove.push(el);\n continue;\n }\n }\n\n // Check and remove dangerous attributes\n const attrsToRemove: string[] = [];\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n\n // Event handlers (onclick, onerror, onload, etc.)\n if (DANGEROUS_ATTR_PATTERN.test(attrName)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // `is=` upgrades a plain tag into a registered customized built-in, so it\n // can smuggle behaviour past the tag-name check above.\n if (attrName === 'is') {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // URL attributes with dangerous protocols\n if (URL_ATTRS.has(attrName) && DANGEROUS_URL_PROTOCOL.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // style attribute can contain expressions (IE) or url() with javascript:\n if (attrName === 'style' && /expression\\s*\\(|javascript:|behavior\\s*:/i.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n }\n\n attrsToRemove.forEach((name) => el.removeAttribute(name));\n }\n\n // Remove dangerous elements (do this after iteration to avoid modifying during traversal)\n toRemove.forEach((el) => el.remove());\n}\n\n// #endregion\n\n// #region Template Evaluation\n\n// #region Safe Expression Evaluator\n// A minimal recursive-descent evaluator for the token set allowed by SAFE_EXPR.\n// Replaces `new Function()` to avoid dynamic code execution warnings from\n// static analysis tools (socket.dev, npm audit) while maintaining identical\n// functionality for expressions that pass the allowlist guards.\n//\n// Supported grammar (matching SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/):\n// ternary → logicalOr ('?' ternary ':' ternary)?\n// logicalOr → logicalAnd ('||' logicalAnd)*\n// logicalAnd → equality ('&&' equality)*\n// equality → comparison (('==' | '!=' | '===' | '!==') comparison)*\n// comparison → additive (('<' | '>' | '<=' | '>=') additive)*\n// additive → multiplicative (('+' | '-') multiplicative)*\n// multiplicative → unary (('*' | '/' | '%') unary)*\n// unary → '!' unary | primary\n// primary → NUMBER | STRING | IDENT ('.' IDENT)? | '(' ternary ')'\n\ntype Token =\n { type: 'num'; v: number } | { type: 'str'; v: string } | { type: 'id'; v: string } | { type: 'op'; v: string };\n\nfunction tokenize(expr: string): Token[] | null {\n const tokens: Token[] = [];\n let i = 0;\n while (i < expr.length) {\n const ch = expr[i];\n if (ch === ' ') {\n i++;\n continue;\n }\n\n // Numbers\n if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < expr.length && expr[i + 1] >= '0' && expr[i + 1] <= '9')) {\n const start = i;\n while (i < expr.length && ((expr[i] >= '0' && expr[i] <= '9') || expr[i] === '.')) i++;\n tokens.push({ type: 'num', v: Number(expr.slice(start, i)) });\n continue;\n }\n\n // String literals (single-quoted only, per SAFE_EXPR)\n if (ch === \"'\") {\n let s = '';\n i++; // skip opening quote\n while (i < expr.length && expr[i] !== \"'\") s += expr[i++];\n if (i >= expr.length) return null; // unterminated\n i++; // skip closing quote\n tokens.push({ type: 'str', v: s });\n continue;\n }\n\n // Identifiers (value, row, row.field)\n if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$') {\n const start = i;\n while (i < expr.length && /[\\w$.]/.test(expr[i])) i++;\n tokens.push({ type: 'id', v: expr.slice(start, i) });\n continue;\n }\n\n // Multi-char operators\n if (i + 2 < expr.length) {\n const tri = expr.slice(i, i + 3);\n if (tri === '===' || tri === '!==') {\n tokens.push({ type: 'op', v: tri });\n i += 3;\n continue;\n }\n }\n if (i + 1 < expr.length) {\n const bi = expr.slice(i, i + 2);\n if (bi === '==' || bi === '!=' || bi === '<=' || bi === '>=' || bi === '&&' || bi === '||') {\n tokens.push({ type: 'op', v: bi });\n i += 2;\n continue;\n }\n }\n\n // Single-char operators\n if ('+-*/%<>!?:(),'.includes(ch)) {\n tokens.push({ type: 'op', v: ch });\n i++;\n continue;\n }\n\n return null; // unexpected character\n }\n return tokens;\n}\n\nfunction safeEval(expr: string, ctx: EvalContext): unknown {\n const toks = tokenize(expr);\n if (!toks) return undefined;\n const tokens: Token[] = toks;\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function advance(): Token {\n return tokens[pos++];\n }\n function match(type: string, val?: string): boolean {\n const t = peek();\n if (!t) return false;\n if (t.type !== type) return false;\n if (val !== undefined && t.v !== val) return false;\n return true;\n }\n\n function resolveId(name: string): unknown {\n if (name === 'value') return ctx.value;\n if (name.startsWith('row.')) {\n const key = name.slice(4);\n return ctx.row ? ctx.row[key] : undefined;\n }\n if (name.startsWith('typeDefault.')) {\n const key = name.slice('typeDefault.'.length);\n return ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n }\n // bare 'row' reference\n if (name === 'row') return ctx.row;\n if (name === 'typeDefault') return ctx.typeDefault;\n return undefined;\n }\n\n function parseTernary(): unknown {\n const result = parseLogicalOr();\n if (match('op', '?')) {\n advance(); // consume '?'\n const consequent = parseTernary();\n if (!match('op', ':')) return undefined;\n advance(); // consume ':'\n const alternate = parseTernary();\n return result ? consequent : alternate;\n }\n return result;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (match('op', '||')) {\n advance();\n left = left || parseLogicalAnd();\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (match('op', '&&')) {\n advance();\n left = left && parseEquality();\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '===') {\n advance();\n left = left === parseComparison();\n } else if (t.v === '!==') {\n advance();\n left = left !== parseComparison();\n } else if (t.v === '==') {\n advance();\n left = left == parseComparison();\n } else if (t.v === '!=') {\n advance();\n left = left != parseComparison();\n } else break;\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '<') {\n advance();\n left = (left as number) < (parseAdditive() as number);\n } else if (t.v === '>') {\n advance();\n left = (left as number) > (parseAdditive() as number);\n } else if (t.v === '<=') {\n advance();\n left = (left as number) <= (parseAdditive() as number);\n } else if (t.v === '>=') {\n advance();\n left = (left as number) >= (parseAdditive() as number);\n } else break;\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '+') {\n advance();\n left = (left as number) + (parseMultiplicative() as number);\n } else if (t.v === '-') {\n advance();\n left = (left as number) - (parseMultiplicative() as number);\n } else break;\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '*') {\n advance();\n left = (left as number) * (parseUnary() as number);\n } else if (t.v === '/') {\n advance();\n left = (left as number) / (parseUnary() as number);\n } else if (t.v === '%') {\n advance();\n left = (left as number) % (parseUnary() as number);\n } else break;\n }\n return left;\n }\n\n function parseUnary(): unknown {\n if (match('op', '!')) {\n advance();\n return !parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'num') {\n advance();\n return t.v;\n }\n if (t.type === 'str') {\n advance();\n return t.v;\n }\n if (t.type === 'id') {\n advance();\n return resolveId(t.v as string);\n }\n if (t.type === 'op' && t.v === '(') {\n advance(); // consume '('\n const result = parseTernary();\n if (match('op', ')')) advance(); // consume ')'\n return result;\n }\n // Unary minus for negative numbers\n if (t.type === 'op' && t.v === '-') {\n advance();\n return -(parsePrimary() as number);\n }\n return undefined;\n }\n\n const result = parseTernary();\n // Ensure all tokens were consumed\n if (pos < tokens.length) return undefined;\n return result;\n}\n// #endregion\n\nexport function evalTemplateString(raw: string, ctx: EvalContext): string {\n if (!raw || raw.indexOf('{{') === -1) return raw; // fast path (no expressions)\n const parts: { expr: string; result: string }[] = [];\n const evaluated = raw.replace(EXPR_RE, (_m, expr) => {\n const res = evalSingle(expr, ctx);\n parts.push({ expr: expr.trim(), result: res });\n // The template markup is author-controlled; the interpolated data is not.\n // Escaping here stops row data from injecting elements or breaking out of\n // an attribute (sanitizeHTML downstream only strips *dangerous* markup).\n return res === EMPTY_SENTINEL ? res : escapeHtml(res);\n });\n const finalStr = postProcess(evaluated);\n // If every part evaluated to EMPTY_SENTINEL we treat this as intentionally blank.\n // If any expression was blocked due to forbidden token (EMPTY_SENTINEL) we *still* only output ''\n // but do not escalate to BLOCKED_SENTINEL unless the original contained explicit forbidden tokens.\n const allEmpty = parts.length && parts.every((p) => p.result === '' || p.result === EMPTY_SENTINEL);\n const hadForbidden = REFLECTIVE_RE.test(raw);\n if (hadForbidden || allEmpty) return '';\n return finalStr;\n}\n\nfunction evalSingle(expr: string, ctx: EvalContext): string {\n expr = (expr || '').trim();\n if (!expr) return EMPTY_SENTINEL;\n if (REFLECTIVE_RE.test(expr)) return EMPTY_SENTINEL;\n if (expr === 'value') return ctx.value == null ? EMPTY_SENTINEL : String(ctx.value);\n if (expr.startsWith('row.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice(4);\n const v = ctx.row ? ctx.row[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.startsWith('typeDefault.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice('typeDefault.'.length);\n const v = ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.length > 80) return EMPTY_SENTINEL;\n if (!SAFE_EXPR.test(expr) || FORBIDDEN.test(expr)) return EMPTY_SENTINEL;\n const dotChain = expr.match(/\\./g);\n if (dotChain && dotChain.length > 1) return EMPTY_SENTINEL;\n try {\n const out = safeEval(expr, ctx);\n const str = out == null ? '' : String(out);\n if (REFLECTIVE_RE.test(str)) return EMPTY_SENTINEL;\n return str || EMPTY_SENTINEL;\n } catch {\n return EMPTY_SENTINEL;\n }\n}\n// #endregion\n\n// #region Cell Scrubbing\n/** Pattern matching reflective/introspective APIs that must be stripped from output. */\nconst REFLECTIVE_RE = /Reflect|Proxy|ownKeys/;\n\nfunction postProcess(s: string): string {\n if (!s) return s;\n return s.replace(new RegExp(EMPTY_SENTINEL, 'g'), '').replace(/Reflect\\.[^<>{}\\s]+|\\bProxy\\b|ownKeys\\([^)]*\\)/g, '');\n}\n\nexport function finalCellScrub(cell: HTMLElement): void {\n if (!REFLECTIVE_RE.test(cell.textContent || '')) return;\n // First pass: clear only text nodes containing forbidden tokens\n for (const n of cell.childNodes) {\n if (n.nodeType === Node.TEXT_NODE && REFLECTIVE_RE.test(n.textContent || '')) n.textContent = '';\n }\n // If forbidden tokens persist in element nodes, nuke everything\n if (REFLECTIVE_RE.test(cell.textContent || '')) {\n cell.textContent = '';\n }\n}\n// #endregion\n\n// #region Template Compilation\nexport function compileTemplate(raw: string) {\n if (REFLECTIVE_RE.test(raw)) {\n const fn = (() => '') as CompiledViewFunction;\n fn.__blocked = true;\n return fn;\n }\n const fn = ((ctx: EvalContext) => evalTemplateString(raw, ctx)) as CompiledViewFunction;\n fn.__blocked = false;\n return fn;\n}\n// #endregion\n","/**\n * Loading State Module\n *\n * Handles loading overlays, row loading, and cell loading states.\n * Provides DOM manipulation helpers for loading indicators.\n *\n * @module internal/loading\n */\n\nimport type { FrameworkAdapter, GridConfig, LoadingContext, RowElementInternal } from '../types';\nimport { setSanitizedHTML } from './sanitize';\n\n/**\n * Create the default spinner element.\n * @param size - 'large' for grid overlay, 'small' for row/cell\n */\nexport function createDefaultSpinner(size: 'large' | 'small'): HTMLElement {\n const spinner = document.createElement('div');\n spinner.className = `tbw-spinner tbw-spinner--${size}`;\n spinner.setAttribute('role', 'progressbar');\n spinner.setAttribute('aria-label', 'Loading');\n return spinner;\n}\n\n/**\n * Create loading content using custom renderer or default spinner.\n *\n * Strings returned by a custom renderer are passed through `setSanitizedHTML()`\n * — mirroring the cell, header and empty-state render paths — so a message\n * interpolating server data (e.g. `Loading ${dataset.name}…`) is not an XSS\n * sink.\n *\n * @param size - 'large' for grid overlay, 'small' for row/cell\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingContent(size: 'large' | 'small', renderer?: GridConfig['loadingRenderer']): HTMLElement {\n if (renderer) {\n const context: LoadingContext = { size };\n const result = renderer(context);\n if (typeof result === 'string') {\n const wrapper = document.createElement('div');\n setSanitizedHTML(wrapper, result);\n return wrapper;\n }\n return result;\n }\n\n return createDefaultSpinner(size);\n}\n\n/**\n * Create or update the loading overlay element.\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingOverlay(renderer?: GridConfig['loadingRenderer']): HTMLElement {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-loading-overlay';\n overlay.setAttribute('role', 'status');\n overlay.setAttribute('aria-live', 'polite');\n overlay.appendChild(createLoadingContent('large', renderer));\n return overlay;\n}\n\n/**\n * Show the loading overlay on the grid root element.\n * @param gridRoot - The .tbw-grid-root element\n * @param overlayEl - The overlay element (will be cached by caller)\n */\nexport function showLoadingOverlay(gridRoot: Element, overlayEl: HTMLElement): void {\n gridRoot.appendChild(overlayEl);\n}\n\n/**\n * Hide the loading overlay.\n * @param overlayEl - The overlay element to remove\n */\nexport function hideLoadingOverlay(overlayEl: HTMLElement | undefined): void {\n overlayEl?.remove();\n}\n\n/** Remove a cell's owned loading overlay and release adapter-managed content. */\nexport function removeCellLoadingOverlay(cellEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!cellEl.firstElementChild) return;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Move a cell's owned loading overlay in front of the cell while its content is rewritten,\n * so the still-active loader survives adapter release and content replacement. The caller\n * appends it back. The overlay stays connected because React prunes detached portal containers.\n */\nexport function parkCellLoadingOverlay(cellEl: HTMLElement): HTMLElement | null {\n if (!cellEl.firstElementChild) return null;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return null;\n const parent = cellEl.parentElement;\n if (parent) parent.insertBefore(overlay, cellEl);\n else overlay.remove();\n return overlay;\n}\n\n/** Remove a row's owned loading overlay and release adapter-managed content. */\nexport function removeRowLoadingOverlay(rowEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!rowEl.firstElementChild) return;\n const overlay = rowEl.querySelector<HTMLElement>(':scope > .tbw-row-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Update a row element's loading state.\n * Uses real DOM elements instead of ::before/::after pseudo-elements\n * because the selection plugin already uses ::after on rows for border styling.\n * @param rowEl - The row element\n * @param loading - Whether the row is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * in place of the default spinner. Only invoked when the overlay is created.\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setRowLoadingState(\n rowEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n rowEl.classList.add('tbw-row-loading');\n rowEl.setAttribute('aria-busy', 'true');\n\n // Create overlay + spinner DOM elements if not already present.\n // Direct children only — a nested grid's row overlay must not be mistaken for this row's.\n if (!rowEl.querySelector(':scope > .tbw-row-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-row-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n\n if (renderer) {\n overlay.appendChild(createLoadingContent('small', renderer));\n } else {\n const spinner = document.createElement('div');\n spinner.className = 'tbw-row-loading-spinner';\n overlay.appendChild(spinner);\n }\n\n rowEl.appendChild(overlay);\n }\n } else {\n rowEl.classList.remove('tbw-row-loading');\n rowEl.removeAttribute('aria-busy');\n\n // Remove overlay + spinner DOM elements\n removeRowLoadingOverlay(rowEl, adapter);\n }\n}\n\n/**\n * Update a cell element's loading state.\n * @param cellEl - The cell element\n * @param loading - Whether the cell is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setCellLoadingState(\n cellEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n cellEl.classList.add('tbw-cell-loading');\n cellEl.setAttribute('aria-busy', 'true');\n\n // Breadcrumb so the render hot path can skip the per-cell scan on the\n // overwhelming majority of rows. Conservative: only ever set here, so it can\n // read stale-true after the last loading cell clears (costs one extra scan).\n const rowEl = cellEl.parentElement as RowElementInternal | null;\n if (rowEl) rowEl.__hasCellLoading = true;\n\n if (renderer) {\n cellEl.classList.add('tbw-cell-loading-custom');\n if (!cellEl.querySelector(':scope > .tbw-cell-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-cell-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n overlay.appendChild(createLoadingContent('small', renderer));\n cellEl.appendChild(overlay);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading-custom');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading');\n cellEl.classList.remove('tbw-cell-loading-custom');\n cellEl.removeAttribute('aria-busy');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n}\n","/**\n * Row teardown shared by the core render path and plugin-rendered rows\n * (loading placeholders), so framework-adapter cleanup has one implementation.\n */\nimport type { GridHost } from '../types';\nimport { removeCellLoadingOverlay, removeRowLoadingOverlay } from './loading';\n\n/**\n * Release a pooled row's adapter-owned content — its row loader, cell loaders, then\n * cell views — before the row is discarded. Callers own the `beginBatch`/`endBatch`\n * bracket so a multi-row teardown collapses into one deferred commit (#330).\n */\nexport function releasePooledRow(adapter: GridHost['__frameworkAdapter'], rowEl: HTMLElement): void {\n if (!adapter?.releaseCell && !adapter?.unmount) return;\n removeRowLoadingOverlay(rowEl, adapter);\n const cells = rowEl.children;\n for (let c = 0; c < cells.length; c++) {\n const cell = cells[c] as HTMLElement;\n removeCellLoadingOverlay(cell, adapter);\n if (cell.firstElementChild) adapter.releaseCell?.(cell);\n }\n}\n\n/**\n * Wipe a pooled row's cells ahead of a full rebuild.\n *\n * Framework views are released BEFORE the DOM is wiped — without this,\n * Angular EmbeddedViewRefs / React roots / Vue apps created by renderers and\n * editor factories stay alive in the adapter's tracking arrays after their DOM\n * is destroyed, leaking memory on every recycle. Wrapped in `beginBatch`/`endBatch`\n * because `innerHTML = ''` detaches every cell as a group, letting adapters defer\n * per-cell sync commits to a single render once detachment completes (#330).\n */\nexport function clearRowForRebuild(grid: Pick<GridHost, '__frameworkAdapter'> & HTMLElement, rowEl: HTMLElement): void {\n // Clear loading state before rebuild — grid re-applies it after render for\n // actually-loading rows. Prevents a stale tbw-row-loading class from\n // persisting when pool elements are recycled.\n rowEl.classList.remove('tbw-row-loading');\n rowEl.removeAttribute('aria-busy');\n\n const adapter = grid.__frameworkAdapter;\n if (!adapter?.releaseCell && !adapter?.unmount) {\n rowEl.innerHTML = '';\n return;\n }\n adapter.beginBatch?.(grid);\n try {\n removeRowLoadingOverlay(rowEl, adapter);\n const children = rowEl.children;\n for (let i = children.length - 1; i >= 0; i--) {\n const cell = children[i] as HTMLElement;\n removeCellLoadingOverlay(cell, adapter);\n adapter.releaseCell?.(cell);\n }\n rowEl.innerHTML = '';\n } finally {\n adapter.endBatch?.(grid);\n }\n}\n","/**\n * Loading placeholder rows shared by plugins that synthesize them (ServerSide\n * blocks in flight, GroupingRows groups being fetched). Inlined into each\n * plugin bundle that imports it — core never calls it.\n */\nimport { setRowLoadingState } from '../../core/internal/loading';\nimport { clearRowForRebuild } from '../../core/internal/row-teardown';\nimport type { GridHost, RowElementInternal } from '../../core/types';\n\n/**\n * Marker class on placeholder rows. Lets layout plugins (Responsive card mode)\n * tell a placeholder apart from a data row — `tbw-row-loading` is not enough,\n * because `grid.setRowLoading()` puts that on real rows too.\n */\nexport const PLACEHOLDER_ROW_CLASS = 'placeholder-row';\n\n/**\n * Render a placeholder as one full-width cell in the core row-loading state, so\n * no column renderer runs for a row that holds no data.\n *\n * Call from a plugin `renderRow` hook and return `true`. The previous cells are\n * released through the framework adapter first (a pooled element may have held\n * React portals / Vue teleports / Angular views for a loaded row). The row is\n * flagged `__isCustomRow`, which forces a full rebuild once real data replaces\n * the placeholder; that rebuild also clears the loading state.\n *\n * Height: the row occupies exactly what virtualization reserves for it — the\n * height a plugin reports through `getRowHeight()` (e.g. a Responsive card), else\n * the default row height. Any inline height a recycled element carried (a\n * Responsive card height, a per-row `--tbw-row-height`) is dropped.\n */\nexport function renderLoadingPlaceholderRow(grid: GridHost, rowEl: HTMLElement, row: unknown, rowIndex: number): void {\n const el = rowEl as RowElementInternal;\n syncPlaceholderHeight(grid, el, row, rowIndex);\n // Same placeholder, still intact: nothing else to do (renders run every scroll frame).\n if (el.__rowDataRef === row && el.__isCustomRow && el.classList.contains('tbw-row-loading')) return;\n\n clearRowForRebuild(grid, el);\n el.className = `data-grid-row ${PLACEHOLDER_ROW_CLASS}`;\n el.__isCustomRow = true;\n const cell = document.createElement('div');\n cell.className = 'cell';\n cell.style.gridColumn = '1 / -1';\n cell.setAttribute('role', 'gridcell');\n cell.textContent = '\\u00A0'; // keeps the row at its normal height\n el.appendChild(cell);\n setRowLoadingState(el, true, grid.effectiveConfig?.loadingRenderer);\n}\n\n/** Match the row's DOM height to the slot virtualization reserves for it. Writes only on change. */\nfunction syncPlaceholderHeight(grid: GridHost, el: HTMLElement, row: unknown, rowIndex: number): void {\n const { style } = el;\n if (style.getPropertyValue('--tbw-row-height')) style.removeProperty('--tbw-row-height');\n const pluginHeight = grid._getPluginRowHeight?.(row, rowIndex);\n const height = pluginHeight !== undefined && pluginHeight > 0 ? `${pluginHeight}px` : '';\n if (style.height !== height) style.height = height;\n}\n","import type { GetRowsParams, GetRowsResult, ServerSideDataSource, Subscribable } from './datasource-types';\n\nexport function getBlockNumber(nodeIndex: number, blockSize: number): number {\n return Math.floor(nodeIndex / blockSize);\n}\n\nexport function getBlockRange(blockNumber: number, blockSize: number): { start: number; end: number } {\n return {\n start: blockNumber * blockSize,\n end: (blockNumber + 1) * blockSize,\n };\n}\n\nexport function getRequiredBlocks(startNode: number, endNode: number, blockSize: number): number[] {\n const startBlock = getBlockNumber(startNode, blockSize);\n const endBlock = getBlockNumber(endNode - 1, blockSize);\n\n const blocks: number[] = [];\n for (let i = startBlock; i <= endBlock; i++) {\n blocks.push(i);\n }\n return blocks;\n}\n\nfunction isSubscribable<T>(value: unknown): value is Subscribable<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { subscribe?: unknown }).subscribe === 'function' &&\n // Promises don't have `.subscribe`, but defensively rule them out.\n typeof (value as { then?: unknown }).then !== 'function'\n );\n}\n\nfunction makeAbortError(): DOMException {\n return new DOMException('Aborted', 'AbortError');\n}\n\n/**\n * Bridge a `Promise | Subscribable` getRows return value into a single\n * `Promise<GetRowsResult>`. For Subscribables, abort triggers `unsubscribe()`\n * so the underlying request (e.g. Angular `HttpClient` XHR) is cancelled.\n * Promise sources should pass `signal` to `fetch` themselves — we still reject\n * on abort either way so the plugin's abort path is consistent.\n */\nexport function toResultPromise<T>(source: Promise<T> | Subscribable<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(makeAbortError());\n }\n if (!isSubscribable<T>(source)) {\n // Promise path: reject on abort so the plugin's catch sees a consistent\n // signal even if the underlying fetch ignored params.signal.\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(makeAbortError());\n signal.addEventListener('abort', onAbort, { once: true });\n Promise.resolve(source).then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n }\n // Subscribable path: subscribe once, settle on next/error/complete, and\n // unsubscribe on abort — that's what cancels HttpClient's XHR.\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n const subscription = source.subscribe({\n next: (value) => {\n if (settled) return;\n settled = true;\n resolve(value);\n subscription.unsubscribe();\n },\n error: (err) => {\n if (settled) return;\n settled = true;\n reject(err);\n },\n complete: () => {\n if (settled) return;\n settled = true;\n reject(new Error('getRows observable completed without emitting a value'));\n },\n });\n if (settled) return; // synchronous emit\n const onAbort = () => {\n if (settled) return;\n settled = true;\n subscription.unsubscribe();\n reject(makeAbortError());\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport function loadBlock(\n dataSource: ServerSideDataSource,\n blockNumber: number,\n blockSize: number,\n params: Partial<GetRowsParams>,\n signal: AbortSignal,\n): Promise<GetRowsResult> {\n const range = getBlockRange(blockNumber, blockSize);\n\n const result = dataSource.getRows({\n startNode: range.start,\n endNode: range.end,\n pageSize: range.end - range.start,\n sortModel: params.sortModel,\n filterModel: params.filterModel,\n signal,\n });\n return toResultPromise(result, signal);\n}\n\nexport function getRowFromCache(\n nodeIndex: number,\n blockSize: number,\n loadedBlocks: Map<number, unknown[]>,\n): unknown | undefined {\n const blockNumber = getBlockNumber(nodeIndex, blockSize);\n const block = loadedBlocks.get(blockNumber);\n if (!block) return undefined;\n\n const indexInBlock = nodeIndex % blockSize;\n return block[indexInBlock];\n}\n\nexport function isBlockLoaded(blockNumber: number, loadedBlocks: Map<number, unknown[]>): boolean {\n return loadedBlocks.has(blockNumber);\n}\n\nexport function isBlockLoading(blockNumber: number, loadingBlocks: Set<number>): boolean {\n return loadingBlocks.has(blockNumber);\n}\n\n/**\n * Build a default {@link ServerSideDataSource} that fetches the whole dataset\n * from a URL once and serves it in blocks from memory. Powers the declarative\n * `<tbw-grid data-src=\"...\">` shorthand (issue #273) so a zero-JS HTML page can\n * render server-fetched rows.\n *\n * The endpoint may return either a plain array of rows (`[...]`) or an envelope\n * (`{ rows, totalNodeCount }`). The fetch runs at most once on success — the\n * resolved dataset is cached and sliced per `getRows` block — so a static JSON\n * file works out of the box. A failed (or aborted) fetch is not cached, so a\n * later block request retries instead of leaving the grid permanently empty.\n * For true server-side pagination (per-block fetches, remote sort/filter),\n * provide a `dataSource` in the plugin config instead.\n *\n * @param url Absolute or relative URL. The fetch runs at most once on success,\n * so only the first `getRows()` call's `signal` is passed to `fetch()`;\n * later calls resolve from the cached dataset and don't re-fetch.\n * @internal\n */\nexport function createUrlDataSource(url: string): ServerSideDataSource {\n let datasetPromise: Promise<{ rows: unknown[]; total: number }> | null = null;\n\n const loadDataset = (signal: AbortSignal): Promise<{ rows: unknown[]; total: number }> => {\n if (!datasetPromise) {\n datasetPromise = fetch(url, { signal })\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch \"${url}\": ${response.status} ${response.statusText}`);\n }\n const data: unknown = await response.json();\n if (Array.isArray(data)) {\n return { rows: data, total: data.length };\n }\n const envelope = (data ?? {}) as { rows?: unknown[]; totalNodeCount?: number };\n const rows = Array.isArray(envelope.rows) ? envelope.rows : [];\n const total = typeof envelope.totalNodeCount === 'number' ? envelope.totalNodeCount : rows.length;\n return { rows, total };\n })\n .catch((err) => {\n // Don't cache failures/aborts — the plugin aborts in-flight block\n // requests on sort/filter/refresh, and caching the rejected promise\n // would poison every later block load. Null it so the next request\n // re-fetches.\n datasetPromise = null;\n throw err;\n });\n }\n return datasetPromise;\n };\n\n return {\n async getRows({ startNode, endNode, signal }: GetRowsParams): Promise<GetRowsResult> {\n const { rows, total } = await loadDataset(signal);\n return { rows: rows.slice(startNode, endNode), totalNodeCount: total };\n },\n };\n}\n","/**\n * Server-Side Data Plugin (Class-based)\n *\n * Central data orchestrator for the grid. Owns fetch + cache + row-model management.\n * Structural plugins (Tree, GroupingRows) claim data via events; core grid uses it\n * as flat rows when unclaimed.\n */\n\nimport {\n DATASOURCE_CHILD_FETCH_ERROR,\n DATASOURCE_FETCH_ERROR,\n DATASOURCE_NO_CHILD_HANDLER,\n DATASOURCE_THROTTLED,\n debugDiagnostic,\n errorDiagnostic,\n warnDiagnostic,\n} from '../../core/internal/diagnostics';\nimport { builtInSort } from '../../core/internal/sorting';\nimport { renderLoadingPlaceholderRow } from '../shared/loading-placeholder';\nimport { BaseGridPlugin, ScrollEvent, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { createUrlDataSource, getBlockNumber, getRequiredBlocks, getRowFromCache, loadBlock } from './datasource';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n DataSourceLoadingDetail,\n FetchChildrenQuery,\n GetRowsParams,\n GetRowsResult,\n ServerSideDataSource,\n ViewportMappingQuery,\n ViewportMappingResponse,\n} from './datasource-types';\nimport { createLoadingPlaceholder, isLoadingPlaceholder } from './placeholder';\nimport type { ServerSideConfig } from './types';\n\n/** Scroll debounce delay in ms */\nconst SCROLL_DEBOUNCE_MS = 100;\n\n/**\n * Server-Side Data Plugin for tbw-grid\n *\n * Central data orchestrator for the grid. Manages fetch, cache, and row-model for\n * server-side data loading. Structural plugins (Tree, GroupingRows) can claim data\n * via events; the core grid uses it as flat rows when unclaimed.\n *\n * ## Installation\n *\n * ```ts\n * import { ServerSidePlugin } from '@toolbox-web/grid/plugins/server-side';\n * ```\n *\n * ## DataSource Interface\n *\n * ```ts\n * interface ServerSideDataSource {\n * getRows(params: GetRowsParams): Promise<GetRowsResult>;\n * getChildRows?(params: GetChildRowsParams): Promise<GetChildRowsResult>;\n * }\n * ```\n *\n * @example Basic Server-Side Loading\n * ```ts\n * import '@toolbox-web/grid';\n * import '@toolbox-web/grid/features/server-side';\n *\n * grid.gridConfig = {\n * columns: [...],\n * features: {\n * serverSide: {\n * pageSize: 50,\n * dataSource: {\n * async getRows(params) {\n * const response = await fetch(\n * `/api/data?start=${params.startNode}&end=${params.endNode}`\n * );\n * const data = await response.json();\n * return { rows: data.rows, totalNodeCount: data.total };\n * },\n * },\n * },\n * },\n * };\n * ```\n *\n * @see {@link ServerSideConfig} for configuration options\n * @see {@link ServerSideDataSource} for data source interface\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class ServerSidePlugin extends BaseGridPlugin<ServerSideConfig> {\n /**\n * Plugin manifest declaring capabilities, hooks, events, and queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n hookPriority: {\n processRows: -10, // Run before structural plugins (Tree, GroupingRows)\n renderRow: -10, // Claim placeholders before row renderers (e.g. Responsive cardRenderer) see them\n },\n incompatibleWith: [\n {\n name: 'pivot',\n reason:\n 'PivotPlugin requires the full dataset to compute aggregations. ' +\n 'ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side.',\n },\n ],\n events: [\n { type: 'datasource:data', description: 'Root data page/block loaded' },\n { type: 'datasource:children', description: 'Child data loaded for a parent context' },\n { type: 'datasource:loading', description: 'Loading state changed' },\n { type: 'datasource:error', description: 'Fetch operation failed' },\n ],\n queries: [\n { type: 'datasource:fetch-children', description: 'Request child rows for a parent context' },\n { type: 'datasource:is-active', description: 'Check if ServerSide plugin has an active data source' },\n ],\n };\n\n /** @internal */\n readonly name = 'serverSide';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ServerSideConfig> {\n return {\n maxConcurrentRequests: 2,\n };\n }\n\n // #region Internal State\n private dataSource: ServerSideDataSource | null = null;\n private totalNodeCount = 0;\n private infiniteScrollMode = false;\n private loadedBlocks = new Map<number, unknown[]>();\n private loadingBlocks = new Set<number>();\n /**\n * Per-block AbortControllers for in-flight requests. Aborted when a block\n * is superseded (sort/filter change, refresh, purgeCache, detach) so data\n * sources that honor `params.signal` (e.g. `fetch`, RxJS via `fromObservable`)\n * can cancel the underlying network call.\n */\n private blockControllers = new Map<number, AbortController>();\n private lastRequestId = 0;\n private scrollDebounceTimer?: ReturnType<typeof setTimeout>;\n /**\n * One-shot flag set when a block lands; consumed in `afterRender()` to re-check\n * required blocks against the viewport produced by the render that the new data\n * triggered (a synchronous check would see the pre-render virtual window).\n */\n private pendingViewportCheck = false;\n /** Persistent node array with stable placeholder references to avoid unnecessary DOM rebuilds. */\n private managedNodes: unknown[] = [];\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Invalidate cache and refetch on sort/filter changes — gated by sortMode/filterMode.\n // 'local' (opt-in): keep cache; sort/filter the loaded rows in place via a re-render.\n // See getEnrichmentParams() — local-mode state is also omitted from block fetch params\n // so scroll-triggered loadRequiredBlocks() doesn't leak local state to the backend.\n this.on('sort-change', () => {\n if (this.config.sortMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n this.on('filter-change', () => {\n if (this.config.filterMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n\n // Auto-initialize from config when dataSource is provided declaratively\n if (this.config.dataSource) {\n this.setDataSource(this.config.dataSource);\n return;\n }\n\n // Declarative `data-src` shorthand (issue #273): when no JS dataSource is\n // configured, read the host's `data-src` attribute and fetch the whole\n // dataset from that URL. Enables a zero-JS HTML page to render\n // server-fetched rows. A JS `dataSource` config always takes precedence.\n const src = this.gridElement?.getAttribute('data-src');\n if (src) {\n this.setDataSource(createUrlDataSource(src));\n }\n }\n\n /** @internal */\n override detach(): void {\n this.dataSource = null;\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.abortAllBlocks();\n this.managedNodes = [];\n this.lastRequestId = 0;\n this.pendingViewportCheck = false;\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n this.scrollDebounceTimer = undefined;\n }\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Abort all in-flight block requests. Called when the plugin tears down,\n * the data source is replaced, the cache is purged, or the sort/filter\n * model changes (the previously loaded block coordinates no longer apply).\n */\n private abortAllBlocks(): void {\n for (const controller of this.blockControllers.values()) {\n controller.abort();\n }\n this.blockControllers.clear();\n }\n\n /**\n * Build enrichment params by querying sort/filter models from loaded plugins.\n *\n * When `sortMode === 'local'` the `sortModel` is omitted so scroll-triggered\n * block fetches don't ask the backend for an ordering it isn't applying.\n * Same for `filterMode === 'local'` and `filterModel`.\n */\n private getEnrichmentParams(): Partial<GetRowsParams> {\n const sortLocal = this.config.sortMode === 'local';\n const filterLocal = this.config.filterMode === 'local';\n const sortResults = sortLocal\n ? undefined\n : (this.grid?.query?.('sort:get-model', null) as\n Array<{ field: string; direction: 'asc' | 'desc' }>[] | undefined);\n const filterResults = filterLocal\n ? undefined\n : (this.grid?.query?.('filter:get-model', null) as Record<string, unknown>[] | undefined);\n\n // Fallback to core single-column sort state when no plugin answers the\n // 'sort:get-model' query (e.g. MultiSortPlugin not loaded). Translate the\n // numeric direction (1/-1) to the public 'asc'/'desc' string form.\n let sortModel = sortResults?.[0];\n const host = this.grid;\n if (!sortLocal && !sortModel && host?._sortState) {\n const { field, direction } = host._sortState;\n sortModel = [{ field, direction: direction === 1 ? 'asc' : 'desc' }];\n }\n\n return {\n sortModel,\n filterModel: filterResults?.[0],\n };\n }\n\n /**\n * Translate visible viewport indices to node-space indices via structural plugins.\n * Falls back to 1:1 mapping (flat data) when no structural plugin responds.\n */\n private getViewportMapping(viewportStart: number, viewportEnd: number): ViewportMappingResponse {\n const query: ViewportMappingQuery = { viewportStart, viewportEnd };\n const results = this.grid?.query?.('datasource:viewport-mapping', query) as ViewportMappingResponse[] | undefined;\n\n // Structural plugin responded — use its mapping\n if (results?.[0]) return results[0];\n\n // No structural plugin → 1:1 mapping (flat data)\n return {\n startNode: viewportStart,\n endNode: viewportEnd,\n totalLoadedNodes: this.totalNodeCount,\n };\n }\n\n /**\n * Handle sort or filter model changes.\n * Purge cache and refetch current viewport with new enrichment params.\n */\n private onModelChange(): void {\n if (!this.dataSource) return;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.requestRender();\n // Eagerly fetch the current viewport with the new enrichment params.\n // Without this, the table stays blank until the user scrolls (no other\n // path triggers a fetch — processRows just rebuilds from cached blocks).\n this.loadRequiredBlocks();\n }\n\n /**\n * Apply server response metadata: resolve totalNodeCount and infinite scroll mode.\n * When `lastNode` is provided, it takes priority and finalizes the total.\n * When `totalNodeCount` is -1, switch to infinite scroll (growing array).\n * When a block returns fewer rows than blockSize, detect end-of-data.\n */\n private applyServerResult(result: GetRowsResult, blockNum: number, blockSize: number): void {\n if (result.lastNode !== undefined) {\n // Server declared the exact end\n this.totalNodeCount = result.lastNode + 1;\n this.infiniteScrollMode = false;\n } else if (result.totalNodeCount === -1) {\n this.infiniteScrollMode = true;\n } else {\n this.totalNodeCount = result.totalNodeCount;\n this.infiniteScrollMode = false;\n }\n\n // Auto-detect end of data: short block means server has no more rows\n if (this.infiniteScrollMode && result.rows.length < blockSize) {\n this.totalNodeCount = blockNum * blockSize + result.rows.length;\n this.infiniteScrollMode = false;\n }\n }\n\n /**\n * Estimate the row count for infinite scroll mode.\n * Returns loaded rows + one extra block of placeholders to trigger next fetch.\n */\n private getInfiniteScrollEstimate(blockSize: number): number {\n let maxLoadedEnd = 0;\n for (const [block, rows] of this.loadedBlocks) {\n const end = block * blockSize + rows.length;\n if (end > maxLoadedEnd) maxLoadedEnd = end;\n }\n return maxLoadedEnd + blockSize;\n }\n\n /**\n * Check current viewport and load any missing blocks.\n */\n private loadRequiredBlocks(): void {\n if (!this.dataSource) return;\n\n const { _virtualization } = this.grid;\n const blockSize = this.config.pageSize ?? 100;\n\n // Translate viewport to node space via structural plugins\n const viewport = this.getViewportMapping(_virtualization.start, _virtualization.end);\n\n // Expand the viewport by loadThreshold in both directions to prefetch\n // blocks the user is about to scroll into. The end is clamped to\n // totalNodeCount when known so we don't request blocks past the end of\n // data — but `totalNodeCount = 0` means \"not yet loaded\" (e.g. just after\n // purgeCache or before the first fetch resolves), in which case we leave\n // it unclamped so the initial block can be fetched.\n const threshold = Math.max(0, this.config.loadThreshold ?? 0);\n const expandedStart = Math.max(0, viewport.startNode - threshold);\n const knownTotal = this.totalNodeCount > 0 ? this.totalNodeCount : Infinity;\n const expandedEnd = Math.min(knownTotal, viewport.endNode + threshold);\n if (expandedEnd <= expandedStart) return;\n\n // Determine which blocks are needed for current viewport (in node space)\n const requiredBlocks = getRequiredBlocks(expandedStart, expandedEnd, blockSize);\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n // Load missing blocks\n for (const blockNum of requiredBlocks) {\n if (this.loadedBlocks.has(blockNum) || this.loadingBlocks.has(blockNum)) {\n continue;\n }\n\n // Check concurrent request limit\n if (this.loadingBlocks.size >= (this.config.maxConcurrentRequests ?? 2)) {\n debugDiagnostic(DATASOURCE_THROTTLED, 'Concurrent request limit reached, deferring block load', gridId);\n break;\n }\n\n this.loadingBlocks.add(blockNum);\n const controller = new AbortController();\n this.blockControllers.set(blockNum, controller);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(this.dataSource, blockNum, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.blockControllers.delete(blockNum);\n // Drop results from a request that was superseded after the await\n // resolved (data source ignored the abort signal). Without this guard\n // a stale block would land in the cache after a sort/filter change.\n if (controller.signal.aborted) {\n this.loadingBlocks.delete(blockNum);\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n this.loadedBlocks.set(blockNum, result.rows);\n // Capture pre-update length so we can detect whether processRows must\n // re-run to grow the managedNodes array (e.g. after onModelChange reset).\n const previousManagedLength = this.managedNodes.length;\n this.applyServerResult(result, blockNum, blockSize);\n this.loadingBlocks.delete(blockNum);\n\n // Update managed nodes in place for this block (avoids full processRows rebuild)\n const start = blockNum * blockSize;\n for (let i = 0; i < result.rows.length; i++) {\n if (start + i < this.managedNodes.length) {\n this.managedNodes[start + i] = result.rows[i];\n }\n }\n\n // Broadcast data event with claimed flag\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: start,\n endNode: start + result.rows.length,\n claimed: false,\n };\n this.broadcast('datasource:data', detail);\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n\n // If managedNodes still hasn't been sized for the (possibly newly known)\n // totalNodeCount — typically because onModelChange() reset it to 0 right\n // before this fetch — we MUST run processRows to grow the array. The\n // in-place writes above are no-ops in that case (length is 0).\n // Without this, sort/filter changes leave the grid permanently blank\n // until something else triggers a ROWS phase.\n // A structural plugin (Tree, GroupingRows) that claimed the data derives\n // its own row model from `managedNodes`. The in-place element swap above\n // is invisible to that derived model — it still references the discarded\n // placeholder objects — so processRows MUST re-run for it to re-derive.\n const needsRowModelRebuild =\n previousManagedLength === 0 ||\n detail.claimed ||\n this.managedNodes.length < (Number.isFinite(this.totalNodeCount) ? this.totalNodeCount : 0);\n\n if (needsRowModelRebuild) {\n // Scheduled render: re-check against its viewport in afterRender().\n this.pendingViewportCheck = true;\n this.requestRender();\n } else {\n // Re-render visible rows without force geometry recalculation.\n // requestVirtualRefresh() skips spacer height writes that cause oscillation\n // with the scheduler's afterRender microtask. Node count hasn't changed —\n // only cached data replaced placeholders — so geometry is stable.\n this.requestVirtualRefresh();\n }\n\n // Re-check now in case the user scrolled while the block was in flight\n // (requestVirtualRefresh() is synchronous, so the window is current).\n this.loadRequiredBlocks();\n })\n .catch((error: unknown) => {\n this.blockControllers.delete(blockNum);\n this.loadingBlocks.delete(blockNum);\n // A superseded request may surface as either an AbortError or as a\n // user-thrown error after the data source detected the abort —\n // suppress diagnostics in both cases. Real failures still surface.\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n });\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processRows(rows: readonly unknown[]): unknown[] {\n if (!this.dataSource) return [...rows];\n\n const blockSize = this.config.pageSize ?? 100;\n\n // Guard against invalid totalNodeCount (e.g. undefined from a malformed datasource response).\n // In infinite scroll mode, estimate the total from loaded data + one extra block.\n const nodeCount = this.infiniteScrollMode\n ? this.getInfiniteScrollEstimate(blockSize)\n : Number.isFinite(this.totalNodeCount) && this.totalNodeCount >= 0\n ? this.totalNodeCount\n : 0;\n\n // Grow array with stable placeholder objects (created once, reused across renders)\n while (this.managedNodes.length < nodeCount) {\n this.managedNodes.push(createLoadingPlaceholder(this.managedNodes.length));\n }\n // Shrink if total decreased\n this.managedNodes.length = nodeCount;\n\n // Replace placeholders with cached data (stable refs for unchanged entries)\n for (let i = 0; i < nodeCount; i++) {\n const cached = getRowFromCache(i, blockSize, this.loadedBlocks);\n if (cached) {\n this.managedNodes[i] = cached;\n }\n }\n\n // Local-mode sort: when sortMode === 'local' the plugin owns ordering of\n // the loaded rows itself (core sort ran on the input but we discarded it\n // by returning managedNodes). Apply the current core sort state on top of\n // managedNodes so the user sees in-place sorting without a refetch.\n // Note: any plugin sort that runs after us (priority > -10, e.g. multi-sort)\n // will further re-sort our output, which is the intended chain.\n const host = this.grid;\n if (this.config.sortMode === 'local' && host?._sortState) {\n const columns = (host._columns ?? []) as ColumnConfig[];\n // Honor user's gridConfig.sortHandler when provided — same resolution\n // as core's reapplyCoreSort/applySort. processRows is synchronous, so\n // async handlers cannot be awaited here: keep the current managedNodes\n // order for this pass and swallow any rejection so it doesn't surface\n // as an unhandled promise rejection. The next core sort cycle (or the\n // next block load) will re-invoke this path with up-to-date state.\n const handler = host.effectiveConfig?.sortHandler ?? builtInSort;\n const result = handler(this.managedNodes, host._sortState, columns);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n void (result as Promise<unknown[]>).catch(() => undefined);\n return this.managedNodes;\n }\n return result as unknown[];\n }\n\n return this.managedNodes;\n }\n\n /** @internal */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean {\n if (!isLoadingPlaceholder(row) || this.config.placeholderRendering === 'columns') return false;\n renderLoadingPlaceholderRow(this.grid, rowEl, row, rowIndex);\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.pendingViewportCheck) return;\n this.pendingViewportCheck = false;\n this.loadRequiredBlocks();\n }\n\n /** @internal */\n override onScroll(_event: ScrollEvent): void {\n if (!this.dataSource) return;\n\n // Immediate check for blocks\n this.loadRequiredBlocks();\n\n // Debounce: when scrolling stops, do a final check with fresh viewport\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n }\n this.scrollDebounceTimer = setTimeout(() => {\n this.loadRequiredBlocks();\n }, SCROLL_DEBOUNCE_MS);\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n switch (query.type) {\n case 'datasource:is-active':\n return this.dataSource != null;\n\n case 'datasource:fetch-children': {\n const { context } = query.context as FetchChildrenQuery;\n this.fetchChildren(context);\n return undefined;\n }\n }\n return undefined;\n }\n // #endregion\n\n // #region Child Data Fetching\n\n /**\n * Fetch child rows via the datasource and broadcast the result.\n */\n private fetchChildren(context: { source: string; [key: string]: unknown }): void {\n if (!this.dataSource) return;\n\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n if (!this.dataSource.getChildRows) {\n warnDiagnostic(\n DATASOURCE_NO_CHILD_HANDLER,\n `Plugin \"${context.source}\" requested child rows but getChildRows() is not implemented on the dataSource`,\n gridId,\n );\n return;\n }\n\n const enrichment = this.getEnrichmentParams();\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true, context });\n\n this.dataSource\n .getChildRows({ context, sortModel: enrichment.sortModel, filterModel: enrichment.filterModel })\n .then((result) => {\n const detail: DataSourceChildrenDetail = {\n rows: result.rows,\n context,\n claimed: false,\n };\n this.broadcast('datasource:children', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n })\n .catch((error: unknown) => {\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_CHILD_FETCH_ERROR, `getChildRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err, context });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Set the data source for server-side loading.\n * @param dataSource - Data source implementing the getRows method (and optionally getChildRows)\n */\n setDataSource(dataSource: ServerSideDataSource): void {\n this.abortAllBlocks();\n this.dataSource = dataSource;\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.pendingViewportCheck = false;\n\n // Load first block with enrichment params\n const blockSize = this.config.pageSize ?? 100;\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n const controller = new AbortController();\n this.blockControllers.set(0, controller);\n this.loadingBlocks.add(0);\n\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(dataSource, 0, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.blockControllers.delete(0);\n this.loadingBlocks.delete(0);\n if (controller.signal.aborted) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n return;\n }\n this.loadedBlocks.set(0, result.rows);\n this.applyServerResult(result, 0, blockSize);\n\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: 0,\n endNode: result.rows.length,\n claimed: false,\n };\n this.broadcast('datasource:data', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n // Fill the rest of the viewport (plus loadThreshold) once block 0 has\n // rendered — see afterRender(). Checking here would use the empty\n // pre-data virtual window and request nothing.\n this.pendingViewportCheck = true;\n this.requestRender();\n })\n .catch((error: unknown) => {\n this.blockControllers.delete(0);\n this.loadingBlocks.delete(0);\n if (controller.signal.aborted) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n });\n }\n\n /**\n * Refresh all data from the server.\n * Purges cache and refetches from block 0.\n */\n refresh(): void {\n if (!this.dataSource) return;\n const ds = this.dataSource;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n // Re-trigger load via setDataSource which handles enrichment and broadcasting\n this.setDataSource(ds);\n }\n\n /**\n * Clear all cached data without refreshing.\n */\n purgeCache(): void {\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.managedNodes = [];\n // Drop a deferred viewport fill so the purge doesn't refetch on the next render.\n this.pendingViewportCheck = false;\n }\n\n /**\n * Get the total node count from the server.\n */\n getTotalNodeCount(): number {\n return this.totalNodeCount;\n }\n\n /**\n * Check if a specific node is loaded in the cache.\n * @param nodeIndex - Node index to check\n */\n isNodeLoaded(nodeIndex: number): boolean {\n const blockSize = this.config.pageSize ?? 100;\n const blockNum = getBlockNumber(nodeIndex, blockSize);\n return this.loadedBlocks.has(blockNum);\n }\n\n /**\n * Get the number of loaded cache blocks.\n */\n getLoadedBlockCount(): number {\n return this.loadedBlocks.size;\n }\n // #endregion\n}\n"],"mappings":"oEAUA,SAAgB,EAAyB,GACvC,MAAO,CAAE,WAAW,EAAM,QAAS,EAAO,cAAe,aAAa,IACxE,CAqBA,SAAgB,EAAqB,GACnC,OACS,MAAP,GACe,iBAAR,IACwC,IAA9C,EAAgC,WACiB,iBAA1C,EAA8B,OAE1C,CCwIA,IAAa,EAAyB,SAgFtC,SAAgB,EAAiB,EAAsB,EAAiB,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tB,KAAK,oBAAqB,EAE1B,KAAK,cAAc,EACrB,CAKA,UAAA,GACE,KAAK,iBACL,KAAK,aAAa,QAClB,KAAK,aAAe,GAEpB,KAAK,sBAAuB,CAC9B,CAKA,iBAAA,GACE,OAAO,KAAK,cACd,CAMA,YAAA,CAAa,GACX,MACM,EAAW,EAAe,EADd,KAAK,OAAO,UAAY,KAE1C,OAAO,KAAK,aAAa,IAAI,EAC/B,CAKA,mBAAA,GACE,OAAO,KAAK,aAAa,IAC3B"}
1
+ {"version":3,"file":"index.js","names":["BaseGridPlugin","builtInSort","createLoadingPlaceholder","index","__loading","__index","__rowCacheKey","isLoadingPlaceholder","row","DATASOURCE_FETCH_ERROR","formatDiagnostic","code","message","gridId","pluginName","gridPrefix","toLowerCase","docsUrl","debugDiagnostic","console","debug","errorDiagnostic","error","_F","split","map","s","reverse","join","DANGEROUS_TAGS","RegExp","slice","Set","DANGEROUS_ATTR_PATTERN","URL_ATTRS","DANGEROUS_URL_PROTOCOL","sanitizeToFragment","html","template","document","createElement","innerHTML","root","toRemove","elements","querySelectorAll","el","tagName","has","push","namespaceURI","Array","from","attributes","some","attr","test","name","attrsToRemove","attrName","value","forEach","removeAttribute","remove","sanitizeNode","content","createLoadingContent","size","renderer","result","wrapper","indexOf","replaceChildren","textContent","spinner","className","setAttribute","createDefaultSpinner","removeCellLoadingOverlay","cellEl","adapter","firstElementChild","overlay","querySelector","unmount","removeRowLoadingOverlay","rowEl","renderLoadingPlaceholderRow","grid","rowIndex","style","getPropertyValue","removeProperty","pluginHeight","_getPluginRowHeight","height","syncPlaceholderHeight","__rowDataRef","__isCustomRow","classList","contains","__frameworkAdapter","releaseCell","beginBatch","children","i","length","cell","endBatch","clearRowForRebuild","gridColumn","appendChild","loading","add","setRowLoadingState","effectiveConfig","loadingRenderer","getBlockNumber","nodeIndex","blockSize","Math","floor","makeAbortError","DOMException","loadBlock","dataSource","blockNumber","params","signal","range","start","end","getBlockRange","getRows","startNode","endNode","pageSize","sortModel","filterModel","Promise","reject","source","aborted","subscribe","then","resolve","onAbort","addEventListener","once","v","removeEventListener","e","settled","subscription","next","unsubscribe","err","complete","Error","toResultPromise","getRowFromCache","loadedBlocks","block","get","urlDataSources","WeakSet","createUrlDataSource","url","datasetPromise","rows","total","fetch","async","response","ok","status","statusText","data","json","isArray","envelope","totalNodeCount","catch","loadDataset","isUrlDataSource","addRangeBlocks","blocks","knownTotal","max","to","min","startBlock","endBlock","getRequiredBlocks","ServerSidePlugin","static","modifiesRowStructure","hookPriority","processRows","renderRow","incompatibleWith","reason","events","type","description","queries","defaultConfig","maxConcurrentRequests","infiniteScrollMode","Map","loadingBlocks","blockControllers","childControllers","scrollDebounceTimer","pendingViewportCheck","managedNodes","generation","attach","super","this","on","sortMode","requestRender","onModelChange","filterMode","config","setDataSource","src","gridElement","getAttribute","detach","clear","abortAllBlocks","controller","abort","clearTimeout","values","releaseBlock","blockNum","delete","getEnrichmentParams","sortLocal","filterLocal","sortResults","query","filterResults","host","_sortState","field","direction","getRequiredBlockNumbers","viewportStart","viewportEnd","threshold","mapped","queryViewportMapping","displayDiffers","addPlaceholderBlocks","sort","a","b","Infinity","displayStart","displayEnd","last","ceil","loadRequiredBlocks","applyServerResult","lastNode","getInfiniteScrollEstimate","maxLoadedEnd","getNodeCount","Number","isFinite","_virtualization","loadThreshold","requiredBlocks","enrichment","AbortController","set","broadcast","previousManagedLength","detail","claimed","variableHeights","requestVirtualRefresh","String","nodeCount","cached","columns","_columns","sortHandler","placeholderRendering","afterRender","onScroll","_event","setTimeout","handleQuery","context","fetchChildren","requesterSignal","getChildRows","warn","warnDiagnostic","release","settle","request","refresh","ds","purgeCache","getTotalNodeCount","isNodeLoaded","getLoadedBlockCount"],"sources":["../../../../../../libs/grid/src/lib/plugins/server-side/placeholder.ts","../../../../../../libs/grid/src/lib/core/internal/diagnostics.ts","../../../../../../libs/grid/src/lib/core/internal/sanitize.ts","../../../../../../libs/grid/src/lib/core/internal/loading.ts","../../../../../../libs/grid/src/lib/core/internal/row-teardown.ts","../../../../../../libs/grid/src/lib/plugins/shared/loading-placeholder.ts","../../../../../../libs/grid/src/lib/plugins/server-side/datasource.ts","../../../../../../libs/grid/src/lib/plugins/server-side/server-side-plugin.ts"],"sourcesContent":["/**\n * ServerSide loading placeholders — the synthetic rows that stand in for nodes\n * whose block has not arrived yet.\n */\nimport type { LoadingPlaceholderRow } from './types';\n\n/**\n * Create the placeholder for node `index`. `__rowCacheKey` keys the variable-height\n * cache so a consumer `getRowId` is never consulted for a placeholder.\n */\nexport function createLoadingPlaceholder(index: number): LoadingPlaceholderRow {\n return { __loading: true, __index: index, __rowCacheKey: `__loading:${index}` } as LoadingPlaceholderRow;\n}\n\n/**\n * Type guard for ServerSide loading placeholders.\n *\n * With the default `placeholderRendering: 'loading-row'` the grid renders placeholders\n * itself, so column renderers, value accessors, `format` and `rowClass` are never called\n * for them while rendering. Use this guard where placeholders still reach your code: with\n * `placeholderRendering: 'columns'` (including a Responsive `cardRenderer`), in a\n * `sortComparator` or `gridConfig.sortHandler` under `sortMode: 'local'`, in Export\n * `mode: 'formatted'` / `processCell` and Clipboard copy (which call `format`), or when\n * reading `grid.rows` directly.\n *\n * @example\n * ```ts\n * import { isLoadingPlaceholder } from '@toolbox-web/grid/plugins/server-side';\n *\n * const loaded = grid.rows.filter((row) => !isLoadingPlaceholder(row));\n * ```\n * @since 3.9.1\n */\nexport function isLoadingPlaceholder(row: unknown): row is LoadingPlaceholderRow {\n return (\n row != null &&\n typeof row === 'object' &&\n (row as { __loading?: unknown }).__loading === true &&\n typeof (row as { __index?: unknown }).__index === 'number'\n );\n}\n","/**\n * Centralized diagnostic messages for @toolbox-web/grid.\n *\n * Every user-facing warning, error, or info message in the grid has a unique\n * diagnostic code (e.g. `TBW001`). Each code maps to a section on the online\n * troubleshooting page, giving developers a direct link to resolution steps.\n *\n * ## Usage\n *\n * ```ts\n * import { MISSING_BREAKPOINT, warnDiagnostic, throwDiagnostic } from './diagnostics';\n *\n * // Warn with a code\n * warnDiagnostic(MISSING_BREAKPOINT, 'Set a breakpoint...', gridId);\n *\n * // Throw with a code\n * throwDiagnostic(MISSING_ROW_ID, 'Configure getRowId...', gridId);\n * ```\n *\n * Plugins should prefer `this.warn(MISSING_BREAKPOINT, message)` via BaseGridPlugin\n * instead of importing this module directly.\n *\n * @internal\n */\n\n// #region Grid Prefix\n\n/**\n * Build the `[tbw-grid]` or `[tbw-grid#my-id]` log prefix.\n * Pass `pluginName` for a scoped prefix like `[tbw-grid:SelectionPlugin]`.\n */\nexport function gridPrefix(gridId?: string, pluginName?: string): string {\n const id = gridId ? `#${gridId}` : '';\n const plugin = pluginName ? `:${pluginName}` : '';\n return `[tbw-grid${id}${plugin}]`;\n}\n\n// #endregion\n\n// #region Diagnostic Codes\n\n/**\n * Diagnostic codes used across the grid library.\n *\n * Each code is an individual export so that unused codes are tree-shaken\n * from bundles that don't reference them (esbuild can't tree-shake\n * properties from a single object).\n *\n * Naming: TBW + 3-digit number.\n * Ranges:\n * 001–019 Configuration validation (missing plugins, bad config)\n * 020–029 Plugin lifecycle (dependencies, incompatibilities, alias collapse)\n * 030–039 Feature registry\n * 040–049 Row operations (row ID, row mutations)\n * 050–059 Column operations (width, template)\n * 060–069 Rendering (callbacks, formatters, external views)\n * 070–079 Shell (tool panels, header/toolbar content)\n * 080–089 Editing & editors\n * 090–099 Print\n * 100–109 Clipboard\n * 110–119 Plugin-specific (responsive, undo-redo, grouping-columns)\n * 120–129 Style injection\n * 130–139 Attribute parsing\n * 140–149 DataSource / ServerSide\n */\n\n// --- Config validation (001–019) ---\n/** Column uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN = 'TBW001' as const;\n/** Grid config uses a plugin-owned property but the plugin is not loaded. */\nexport const MISSING_PLUGIN_CONFIG = 'TBW002' as const;\n/** Plugin config rule violation (error severity). */\nexport const CONFIG_RULE_ERROR = 'TBW003' as const;\n/** Plugin config rule violation (warning severity). */\nexport const CONFIG_RULE_WARN = 'TBW004' as const;\n\n// --- Plugin lifecycle (020–029) ---\n/** Required plugin dependency is missing. */\nexport const MISSING_DEPENDENCY = 'TBW020' as const;\n/** Optional plugin dependency is missing. */\nexport const OPTIONAL_DEPENDENCY = 'TBW021' as const;\n/** Two loaded plugins are incompatible. */\nexport const INCOMPATIBLE_PLUGINS = 'TBW022' as const;\n/** Two plugin instances resolve to the same canonical name (alias collapse). */\nexport const PLUGIN_ALIAS_COLLAPSE = 'TBW023' as const;\n/** Error thrown inside a plugin event handler. */\nexport const PLUGIN_EVENT_ERROR = 'TBW024' as const;\n/** Conflicting config values found while merging alias-collapsed plugin instances. */\nexport const PLUGIN_ALIAS_CONFIG_CONFLICT = 'TBW025' as const;\n\n// --- Feature registry (030–039) ---\n/** Feature was re-registered (overwritten). */\nexport const FEATURE_REREGISTERED = 'TBW030' as const;\n/** Feature configured but not imported. */\nexport const FEATURE_NOT_IMPORTED = 'TBW031' as const;\n/** Feature depends on another feature that is not enabled. */\nexport const FEATURE_MISSING_DEP = 'TBW032' as const;\n\n// --- Row operations (040–049) ---\n/** Cannot determine row ID (no getRowId and no id property). */\nexport const MISSING_ROW_ID = 'TBW040' as const;\n/** Row with given ID not found. */\nexport const ROW_NOT_FOUND = 'TBW041' as const;\n\n// --- Column operations (050–059) ---\n/** Column has an invalid CSS width value. */\nexport const INVALID_COLUMN_WIDTH = 'TBW050' as const;\n\n// --- Rendering callbacks (060–069) ---\n/** rowClass callback threw an error. */\nexport const ROW_CLASS_ERROR = 'TBW060' as const;\n/** cellClass callback threw an error. */\nexport const CELL_CLASS_ERROR = 'TBW061' as const;\n/** Column format function threw an error. */\nexport const FORMAT_ERROR = 'TBW062' as const;\n/** External view mount() threw an error. */\nexport const VIEW_MOUNT_ERROR = 'TBW063' as const;\n/** External view event dispatch error. */\nexport const VIEW_DISPATCH_ERROR = 'TBW064' as const;\n\n// --- Shell (070–079) ---\n/** Tool panel missing required id. */\nexport const TOOL_PANEL_MISSING_ATTR = 'TBW070' as const;\n/** No tool panels registered. */\nexport const NO_TOOL_PANELS = 'TBW071' as const;\n/** Tool panel section not found. */\nexport const TOOL_PANEL_NOT_FOUND = 'TBW072' as const;\n/** Tool panel already registered. */\nexport const TOOL_PANEL_DUPLICATE = 'TBW073' as const;\n/** Header content already registered. */\nexport const HEADER_CONTENT_DUPLICATE = 'TBW074' as const;\n/** Toolbar content already registered. */\nexport const TOOLBAR_CONTENT_DUPLICATE = 'TBW075' as const;\n\n// --- Editing & editors (080–089) ---\n/** External editor mount() threw an error. */\nexport const EDITOR_MOUNT_ERROR = 'TBW080' as const;\n\n// --- Print (090–099) ---\n/** Print already in progress. */\nexport const PRINT_IN_PROGRESS = 'TBW090' as const;\n/** Grid not available for printing. */\nexport const PRINT_NO_GRID = 'TBW091' as const;\n/** Print operation failed. */\nexport const PRINT_FAILED = 'TBW092' as const;\n/** Multiple elements share the same grid ID (print isolation issue). */\nexport const PRINT_DUPLICATE_ID = 'TBW093' as const;\n\n// --- Clipboard (100–109) ---\n/** Clipboard API write failed. */\nexport const CLIPBOARD_FAILED = 'TBW100' as const;\n\n// --- Plugin-specific (110–119) ---\n/** ResponsivePlugin: no breakpoint configured. */\nexport const MISSING_BREAKPOINT = 'TBW110' as const;\n/** UndoRedoPlugin: transaction already in progress. */\nexport const TRANSACTION_IN_PROGRESS = 'TBW111' as const;\n/** UndoRedoPlugin: no transaction in progress. */\nexport const NO_TRANSACTION = 'TBW112' as const;\n/** GroupingColumnsPlugin: missing id or header on column group definition. */\nexport const COLUMN_GROUP_NO_ID = 'TBW113' as const;\n/** GroupingColumnsPlugin: conflicting columnGroups sources. */\nexport const COLUMN_GROUPS_CONFLICT = 'TBW114' as const;\n\n// --- Style injection (120–129) ---\n/** Failed to extract grid.css from document stylesheets. */\nexport const STYLE_EXTRACT_FAILED = 'TBW120' as const;\n/** Could not find grid.css in document.styleSheets. */\nexport const STYLE_NOT_FOUND = 'TBW121' as const;\n\n// --- Attribute parsing (130–139) ---\n/** Invalid JSON in an HTML attribute. */\nexport const INVALID_ATTRIBUTE_JSON = 'TBW130' as const;\n\n// --- DataSource / ServerSide (140–149) ---\n/** ServerSidePlugin: getRows() rejected. */\nexport const DATASOURCE_FETCH_ERROR = 'TBW140' as const;\n/** ServerSidePlugin: getChildRows() rejected. */\nexport const DATASOURCE_CHILD_FETCH_ERROR = 'TBW141' as const;\n/** ServerSidePlugin: getChildRows() not implemented but a plugin queried for children. */\nexport const DATASOURCE_NO_CHILD_HANDLER = 'TBW142' as const;\n/** ServerSidePlugin: concurrent request limit reached, request deferred. */\nexport const DATASOURCE_THROTTLED = 'TBW143' as const;\n\nexport type DiagnosticCode =\n | typeof MISSING_PLUGIN\n | typeof MISSING_PLUGIN_CONFIG\n | typeof CONFIG_RULE_ERROR\n | typeof CONFIG_RULE_WARN\n | typeof MISSING_DEPENDENCY\n | typeof OPTIONAL_DEPENDENCY\n | typeof INCOMPATIBLE_PLUGINS\n | typeof PLUGIN_ALIAS_COLLAPSE\n | typeof PLUGIN_EVENT_ERROR\n | typeof PLUGIN_ALIAS_CONFIG_CONFLICT\n | typeof FEATURE_REREGISTERED\n | typeof FEATURE_NOT_IMPORTED\n | typeof FEATURE_MISSING_DEP\n | typeof MISSING_ROW_ID\n | typeof ROW_NOT_FOUND\n | typeof INVALID_COLUMN_WIDTH\n | typeof ROW_CLASS_ERROR\n | typeof CELL_CLASS_ERROR\n | typeof FORMAT_ERROR\n | typeof VIEW_MOUNT_ERROR\n | typeof VIEW_DISPATCH_ERROR\n | typeof TOOL_PANEL_MISSING_ATTR\n | typeof NO_TOOL_PANELS\n | typeof TOOL_PANEL_NOT_FOUND\n | typeof TOOL_PANEL_DUPLICATE\n | typeof HEADER_CONTENT_DUPLICATE\n | typeof TOOLBAR_CONTENT_DUPLICATE\n | typeof EDITOR_MOUNT_ERROR\n | typeof PRINT_IN_PROGRESS\n | typeof PRINT_NO_GRID\n | typeof PRINT_FAILED\n | typeof PRINT_DUPLICATE_ID\n | typeof CLIPBOARD_FAILED\n | typeof MISSING_BREAKPOINT\n | typeof TRANSACTION_IN_PROGRESS\n | typeof NO_TRANSACTION\n | typeof COLUMN_GROUP_NO_ID\n | typeof COLUMN_GROUPS_CONFLICT\n | typeof STYLE_EXTRACT_FAILED\n | typeof STYLE_NOT_FOUND\n | typeof INVALID_ATTRIBUTE_JSON\n | typeof DATASOURCE_FETCH_ERROR\n | typeof DATASOURCE_CHILD_FETCH_ERROR\n | typeof DATASOURCE_NO_CHILD_HANDLER\n | typeof DATASOURCE_THROTTLED;\n\n// #endregion\n\n// #region Docs URL\n\nconst DOCS_BASE = 'https://toolboxjs.com/grid/errors';\n\n/** Build a direct link to the troubleshooting section for a code. */\nfunction docsUrl(code: DiagnosticCode): string {\n return `${DOCS_BASE}#${code.toLowerCase()}`;\n}\n\n// #endregion\n\n// #region Formatting\n\n/**\n * Format a diagnostic message with prefix, code, and docs link.\n *\n * Output format:\n * ```\n * [tbw-grid#my-id] TBW001: Your message here.\n *\n * → More info: https://toolboxjs.com/grid/errors#tbw001\n * ```\n */\nexport function formatDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): string {\n const prefix = gridPrefix(gridId, pluginName);\n return `${prefix} ${code}: ${message}\\n\\n → More info: ${docsUrl(code)}`;\n}\n\n// #endregion\n\n// #region Public API\n\n/**\n * Throw an error with a diagnostic code and docs link.\n * Use for configuration errors and API misuse that should halt execution.\n */\nexport function throwDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): never {\n throw new Error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a warning with a diagnostic code and docs link.\n * Use for recoverable issues the developer should fix.\n */\nexport function warnDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.warn(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log a debug message with a diagnostic code and docs link.\n * Use for optional/soft dependency notifications — visible only when\n * the browser DevTools \"Verbose\" log level is enabled.\n */\nexport function debugDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.debug(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n/**\n * Log an error with a diagnostic code and docs link.\n * Use for non-throwing errors (e.g., failed async operations).\n */\nexport function errorDiagnostic(code: DiagnosticCode, message: string, gridId?: string, pluginName?: string): void {\n console.error(formatDiagnostic(code, message, gridId, pluginName));\n}\n\n// #endregion\n","// Centralized template expression evaluation & sanitization utilities.\n// Responsible for safely interpolating {{ }} expressions while blocking\n// access to dangerous globals / reflective capabilities.\nimport type { CompiledViewFunction, EvalContext } from '../types';\n\n// #region Constants\nconst EXPR_RE = /{{\\s*([^}]+)\\s*}}/g;\nconst EMPTY_SENTINEL = '__DG_EMPTY__';\nconst SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/;\n\n// Forbidden identifiers built at runtime to avoid static analysis scanners\n// from flagging string literals (e.g. socket.dev \"network access\" / \"uses eval\").\n// Stored as reversed, pipe-delimited tokens — reversed back when constructing the regex.\nconst _F =\n '__otorp__|__retteGenifed__|__retteSenifed__|rotcurtsnoc|wodniw|sihTlabolg|labolg|ssecorp|noitcnuF|tropmi|lave|tcelfeR|yxorP|rorrE|stnemugra|tnemucod|noitacol|eikooc|egarotSlacol|egarotSnoisses|BDdexedni|hctef|tseuqeRpttHLMX|tekcoSbeW|rekroW|rekroWderahS|rekroWecivreS|renepo|tnerap|pot|semarf|fles'\n .split('|')\n .map((s) => s.split('').reverse().join(''));\nconst FORBIDDEN = new RegExp(`__(proto|defineGetter|defineSetter)|${_F.slice(3).join('|')}|this\\\\b`);\n// #endregion\n\n// #region HTML Sanitization\n\n/**\n * Escape a plain text string for safe insertion into HTML.\n * Converts special HTML characters to their entity equivalents.\n *\n * @param text - Plain text string to escape\n * @returns HTML-safe string\n */\nexport function escapeHtml(text: string): string {\n if (!text || typeof text !== 'string') return '';\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\n/**\n * Tags that are considered dangerous and will be completely removed.\n * These can execute scripts, load external resources, or manipulate the page.\n */\nconst DANGEROUS_TAGS = new Set(\n 'script|iframe|object|embed|form|input|button|textarea|select|link|meta|base|style|template|slot|portal|frame|frameset|applet|noscript|noembed|plaintext|xmp|listing|math'.split(\n '|',\n ),\n);\n\n/**\n * Attributes that are considered dangerous - event handlers and data loading.\n */\nconst DANGEROUS_ATTR_PATTERN = /^on\\w+$/i;\n\n/**\n * Attributes that can contain URLs which might be javascript: or data: URIs.\n */\nconst URL_ATTRS = new Set('href|src|action|formaction|data|srcdoc|xlink:href|poster|srcset'.split('|'));\n\n/**\n * Protocol patterns that are dangerous in URLs.\n */\nconst DANGEROUS_URL_PROTOCOL = /^\\s*(javascript|vbscript|data|blob):/i;\n\n/**\n * Sanitize an HTML string by removing dangerous tags and attributes.\n *\n * Prefer {@link setSanitizedHTML} wherever the result is destined for an\n * element: this function has to re-serialize the sanitized tree back to a\n * string, and the caller's `innerHTML =` then re-parses it. That\n * parse→serialize→parse round trip is the classic mutation-XSS vector, and it\n * costs a second parse. Use this overload only when a string is genuinely\n * required (e.g. the value is stored, compared, or handed to another API).\n *\n * @param html - Raw HTML string to sanitize\n * @returns Sanitized HTML string safe for innerHTML\n */\nexport function sanitizeHTML(html: string): string {\n if (!html || typeof html !== 'string') return '';\n\n // Fast path: if no HTML tags at all, return as-is (already safe)\n if (html.indexOf('<') === -1) return html;\n\n const template = document.createElement('template');\n template.innerHTML = html;\n\n sanitizeNode(template.content);\n\n return template.innerHTML;\n}\n\n/**\n * Parse and sanitize an HTML string into a detached {@link DocumentFragment}.\n *\n * This is the primitive {@link setSanitizedHTML} builds on, exposed for callers\n * that need to inspect or relocate the nodes before insertion.\n *\n * @param html - Raw HTML string to sanitize\n * @returns Fragment containing the sanitized nodes (empty for falsy input)\n */\nexport function sanitizeToFragment(html: string): DocumentFragment {\n const template = document.createElement('template');\n if (html && typeof html === 'string') {\n template.innerHTML = html;\n sanitizeNode(template.content);\n }\n return template.content;\n}\n\n/**\n * Replace an element's children with the sanitized parse of `html`.\n *\n * **This is the canonical sink for user-supplied markup** — cell/header/group\n * renderer string returns, `gridConfig.icons.*`, light-DOM tool panel fallback\n * content, and any new extension point that turns a user string into markup.\n * `textContent` is wrong here (it renders SVG icon strings as literal text) and\n * raw `innerHTML` is wrong (it is an XSS sink).\n *\n * Nodes are moved from the parse fragment rather than re-serialized, so the\n * sanitized tree is exactly what lands in the document.\n *\n * @param el - Element whose children are replaced\n * @param html - Raw HTML string to sanitize and insert\n */\nexport function setSanitizedHTML(el: Element, html: string): void {\n if (!html || typeof html !== 'string') {\n el.replaceChildren();\n return;\n }\n // Nothing for the parser to do: no markup and no entities to decode.\n if (html.indexOf('<') === -1 && html.indexOf('&') === -1) {\n el.textContent = html;\n return;\n }\n el.replaceChildren(sanitizeToFragment(html));\n}\n\n/**\n * Recursively sanitize a DOM node tree.\n */\nfunction sanitizeNode(root: DocumentFragment | Element): void {\n const toRemove: Element[] = [];\n\n // Use querySelectorAll to find all elements, then filter\n const elements = root.querySelectorAll('*');\n\n for (const el of elements) {\n const tagName = el.tagName.toLowerCase();\n\n // Check if tag is dangerous\n if (DANGEROUS_TAGS.has(tagName)) {\n toRemove.push(el);\n continue;\n }\n\n // SVG elements need special handling - they can contain script-like behavior\n if (tagName === 'svg' || el.namespaceURI === 'http://www.w3.org/2000/svg') {\n // Remove entire SVG if it has any suspicious attributes\n const hasDangerousContent = Array.from(el.attributes).some(\n (attr) => DANGEROUS_ATTR_PATTERN.test(attr.name) || attr.name === 'href' || attr.name === 'xlink:href',\n );\n if (hasDangerousContent) {\n toRemove.push(el);\n continue;\n }\n }\n\n // Check and remove dangerous attributes\n const attrsToRemove: string[] = [];\n for (const attr of el.attributes) {\n const attrName = attr.name.toLowerCase();\n\n // Event handlers (onclick, onerror, onload, etc.)\n if (DANGEROUS_ATTR_PATTERN.test(attrName)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // `is=` upgrades a plain tag into a registered customized built-in, so it\n // can smuggle behaviour past the tag-name check above.\n if (attrName === 'is') {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // URL attributes with dangerous protocols\n if (URL_ATTRS.has(attrName) && DANGEROUS_URL_PROTOCOL.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n\n // style attribute can contain expressions (IE) or url() with javascript:\n if (attrName === 'style' && /expression\\s*\\(|javascript:|behavior\\s*:/i.test(attr.value)) {\n attrsToRemove.push(attr.name);\n continue;\n }\n }\n\n attrsToRemove.forEach((name) => el.removeAttribute(name));\n }\n\n // Remove dangerous elements (do this after iteration to avoid modifying during traversal)\n toRemove.forEach((el) => el.remove());\n}\n\n// #endregion\n\n// #region Template Evaluation\n\n// #region Safe Expression Evaluator\n// A minimal recursive-descent evaluator for the token set allowed by SAFE_EXPR.\n// Replaces `new Function()` to avoid dynamic code execution warnings from\n// static analysis tools (socket.dev, npm audit) while maintaining identical\n// functionality for expressions that pass the allowlist guards.\n//\n// Supported grammar (matching SAFE_EXPR = /^[\\w$. '?+\\-*/%:()!<>=,&|]+$/):\n// ternary → logicalOr ('?' ternary ':' ternary)?\n// logicalOr → logicalAnd ('||' logicalAnd)*\n// logicalAnd → equality ('&&' equality)*\n// equality → comparison (('==' | '!=' | '===' | '!==') comparison)*\n// comparison → additive (('<' | '>' | '<=' | '>=') additive)*\n// additive → multiplicative (('+' | '-') multiplicative)*\n// multiplicative → unary (('*' | '/' | '%') unary)*\n// unary → '!' unary | primary\n// primary → NUMBER | STRING | IDENT ('.' IDENT)? | '(' ternary ')'\n\ntype Token =\n { type: 'num'; v: number } | { type: 'str'; v: string } | { type: 'id'; v: string } | { type: 'op'; v: string };\n\nfunction tokenize(expr: string): Token[] | null {\n const tokens: Token[] = [];\n let i = 0;\n while (i < expr.length) {\n const ch = expr[i];\n if (ch === ' ') {\n i++;\n continue;\n }\n\n // Numbers\n if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < expr.length && expr[i + 1] >= '0' && expr[i + 1] <= '9')) {\n const start = i;\n while (i < expr.length && ((expr[i] >= '0' && expr[i] <= '9') || expr[i] === '.')) i++;\n tokens.push({ type: 'num', v: Number(expr.slice(start, i)) });\n continue;\n }\n\n // String literals (single-quoted only, per SAFE_EXPR)\n if (ch === \"'\") {\n let s = '';\n i++; // skip opening quote\n while (i < expr.length && expr[i] !== \"'\") s += expr[i++];\n if (i >= expr.length) return null; // unterminated\n i++; // skip closing quote\n tokens.push({ type: 'str', v: s });\n continue;\n }\n\n // Identifiers (value, row, row.field)\n if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch === '_' || ch === '$') {\n const start = i;\n while (i < expr.length && /[\\w$.]/.test(expr[i])) i++;\n tokens.push({ type: 'id', v: expr.slice(start, i) });\n continue;\n }\n\n // Multi-char operators\n if (i + 2 < expr.length) {\n const tri = expr.slice(i, i + 3);\n if (tri === '===' || tri === '!==') {\n tokens.push({ type: 'op', v: tri });\n i += 3;\n continue;\n }\n }\n if (i + 1 < expr.length) {\n const bi = expr.slice(i, i + 2);\n if (bi === '==' || bi === '!=' || bi === '<=' || bi === '>=' || bi === '&&' || bi === '||') {\n tokens.push({ type: 'op', v: bi });\n i += 2;\n continue;\n }\n }\n\n // Single-char operators\n if ('+-*/%<>!?:(),'.includes(ch)) {\n tokens.push({ type: 'op', v: ch });\n i++;\n continue;\n }\n\n return null; // unexpected character\n }\n return tokens;\n}\n\nfunction safeEval(expr: string, ctx: EvalContext): unknown {\n const toks = tokenize(expr);\n if (!toks) return undefined;\n const tokens: Token[] = toks;\n let pos = 0;\n\n function peek(): Token | undefined {\n return tokens[pos];\n }\n function advance(): Token {\n return tokens[pos++];\n }\n function match(type: string, val?: string): boolean {\n const t = peek();\n if (!t) return false;\n if (t.type !== type) return false;\n if (val !== undefined && t.v !== val) return false;\n return true;\n }\n\n function resolveId(name: string): unknown {\n if (name === 'value') return ctx.value;\n if (name.startsWith('row.')) {\n const key = name.slice(4);\n return ctx.row ? ctx.row[key] : undefined;\n }\n if (name.startsWith('typeDefault.')) {\n const key = name.slice('typeDefault.'.length);\n return ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n }\n // bare 'row' reference\n if (name === 'row') return ctx.row;\n if (name === 'typeDefault') return ctx.typeDefault;\n return undefined;\n }\n\n function parseTernary(): unknown {\n const result = parseLogicalOr();\n if (match('op', '?')) {\n advance(); // consume '?'\n const consequent = parseTernary();\n if (!match('op', ':')) return undefined;\n advance(); // consume ':'\n const alternate = parseTernary();\n return result ? consequent : alternate;\n }\n return result;\n }\n\n function parseLogicalOr(): unknown {\n let left = parseLogicalAnd();\n while (match('op', '||')) {\n advance();\n left = left || parseLogicalAnd();\n }\n return left;\n }\n\n function parseLogicalAnd(): unknown {\n let left = parseEquality();\n while (match('op', '&&')) {\n advance();\n left = left && parseEquality();\n }\n return left;\n }\n\n function parseEquality(): unknown {\n let left = parseComparison();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '===') {\n advance();\n left = left === parseComparison();\n } else if (t.v === '!==') {\n advance();\n left = left !== parseComparison();\n } else if (t.v === '==') {\n advance();\n left = left == parseComparison();\n } else if (t.v === '!=') {\n advance();\n left = left != parseComparison();\n } else break;\n }\n return left;\n }\n\n function parseComparison(): unknown {\n let left = parseAdditive();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '<') {\n advance();\n left = (left as number) < (parseAdditive() as number);\n } else if (t.v === '>') {\n advance();\n left = (left as number) > (parseAdditive() as number);\n } else if (t.v === '<=') {\n advance();\n left = (left as number) <= (parseAdditive() as number);\n } else if (t.v === '>=') {\n advance();\n left = (left as number) >= (parseAdditive() as number);\n } else break;\n }\n return left;\n }\n\n function parseAdditive(): unknown {\n let left = parseMultiplicative();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '+') {\n advance();\n left = (left as number) + (parseMultiplicative() as number);\n } else if (t.v === '-') {\n advance();\n left = (left as number) - (parseMultiplicative() as number);\n } else break;\n }\n return left;\n }\n\n function parseMultiplicative(): unknown {\n let left = parseUnary();\n while (true) {\n const t = peek();\n if (!t || t.type !== 'op') break;\n if (t.v === '*') {\n advance();\n left = (left as number) * (parseUnary() as number);\n } else if (t.v === '/') {\n advance();\n left = (left as number) / (parseUnary() as number);\n } else if (t.v === '%') {\n advance();\n left = (left as number) % (parseUnary() as number);\n } else break;\n }\n return left;\n }\n\n function parseUnary(): unknown {\n if (match('op', '!')) {\n advance();\n return !parseUnary();\n }\n return parsePrimary();\n }\n\n function parsePrimary(): unknown {\n const t = peek();\n if (!t) return undefined;\n if (t.type === 'num') {\n advance();\n return t.v;\n }\n if (t.type === 'str') {\n advance();\n return t.v;\n }\n if (t.type === 'id') {\n advance();\n return resolveId(t.v as string);\n }\n if (t.type === 'op' && t.v === '(') {\n advance(); // consume '('\n const result = parseTernary();\n if (match('op', ')')) advance(); // consume ')'\n return result;\n }\n // Unary minus for negative numbers\n if (t.type === 'op' && t.v === '-') {\n advance();\n return -(parsePrimary() as number);\n }\n return undefined;\n }\n\n const result = parseTernary();\n // Ensure all tokens were consumed\n if (pos < tokens.length) return undefined;\n return result;\n}\n// #endregion\n\nexport function evalTemplateString(raw: string, ctx: EvalContext): string {\n if (!raw || raw.indexOf('{{') === -1) return raw; // fast path (no expressions)\n const parts: { expr: string; result: string }[] = [];\n const evaluated = raw.replace(EXPR_RE, (_m, expr) => {\n const res = evalSingle(expr, ctx);\n parts.push({ expr: expr.trim(), result: res });\n // The template markup is author-controlled; the interpolated data is not.\n // Escaping here stops row data from injecting elements or breaking out of\n // an attribute (sanitizeHTML downstream only strips *dangerous* markup).\n return res === EMPTY_SENTINEL ? res : escapeHtml(res);\n });\n const finalStr = postProcess(evaluated);\n // If every part evaluated to EMPTY_SENTINEL we treat this as intentionally blank.\n // If any expression was blocked due to forbidden token (EMPTY_SENTINEL) we *still* only output ''\n // but do not escalate to BLOCKED_SENTINEL unless the original contained explicit forbidden tokens.\n const allEmpty = parts.length && parts.every((p) => p.result === '' || p.result === EMPTY_SENTINEL);\n const hadForbidden = REFLECTIVE_RE.test(raw);\n if (hadForbidden || allEmpty) return '';\n return finalStr;\n}\n\nfunction evalSingle(expr: string, ctx: EvalContext): string {\n expr = (expr || '').trim();\n if (!expr) return EMPTY_SENTINEL;\n if (REFLECTIVE_RE.test(expr)) return EMPTY_SENTINEL;\n if (expr === 'value') return ctx.value == null ? EMPTY_SENTINEL : String(ctx.value);\n if (expr.startsWith('row.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice(4);\n const v = ctx.row ? ctx.row[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.startsWith('typeDefault.') && !/[()?]/.test(expr) && !expr.includes(':')) {\n const key = expr.slice('typeDefault.'.length);\n const v = ctx.typeDefault ? ctx.typeDefault[key] : undefined;\n return v == null ? EMPTY_SENTINEL : String(v);\n }\n if (expr.length > 80) return EMPTY_SENTINEL;\n if (!SAFE_EXPR.test(expr) || FORBIDDEN.test(expr)) return EMPTY_SENTINEL;\n const dotChain = expr.match(/\\./g);\n if (dotChain && dotChain.length > 1) return EMPTY_SENTINEL;\n try {\n const out = safeEval(expr, ctx);\n const str = out == null ? '' : String(out);\n if (REFLECTIVE_RE.test(str)) return EMPTY_SENTINEL;\n return str || EMPTY_SENTINEL;\n } catch {\n return EMPTY_SENTINEL;\n }\n}\n// #endregion\n\n// #region Cell Scrubbing\n/** Pattern matching reflective/introspective APIs that must be stripped from output. */\nconst REFLECTIVE_RE = /Reflect|Proxy|ownKeys/;\n\nfunction postProcess(s: string): string {\n if (!s) return s;\n return s.replace(new RegExp(EMPTY_SENTINEL, 'g'), '').replace(/Reflect\\.[^<>{}\\s]+|\\bProxy\\b|ownKeys\\([^)]*\\)/g, '');\n}\n\nexport function finalCellScrub(cell: HTMLElement): void {\n if (!REFLECTIVE_RE.test(cell.textContent || '')) return;\n // First pass: clear only text nodes containing forbidden tokens\n for (const n of cell.childNodes) {\n if (n.nodeType === Node.TEXT_NODE && REFLECTIVE_RE.test(n.textContent || '')) n.textContent = '';\n }\n // If forbidden tokens persist in element nodes, nuke everything\n if (REFLECTIVE_RE.test(cell.textContent || '')) {\n cell.textContent = '';\n }\n}\n// #endregion\n\n// #region Template Compilation\nexport function compileTemplate(raw: string) {\n if (REFLECTIVE_RE.test(raw)) {\n const fn = (() => '') as CompiledViewFunction;\n fn.__blocked = true;\n return fn;\n }\n const fn = ((ctx: EvalContext) => evalTemplateString(raw, ctx)) as CompiledViewFunction;\n fn.__blocked = false;\n return fn;\n}\n// #endregion\n","/**\n * Loading State Module\n *\n * Handles loading overlays, row loading, and cell loading states.\n * Provides DOM manipulation helpers for loading indicators.\n *\n * @module internal/loading\n */\n\nimport type { FrameworkAdapter, GridConfig, LoadingContext, RowElementInternal } from '../types';\nimport { setSanitizedHTML } from './sanitize';\n\n/**\n * Create the default spinner element.\n * @param size - 'large' for grid overlay, 'small' for row/cell\n */\nexport function createDefaultSpinner(size: 'large' | 'small'): HTMLElement {\n const spinner = document.createElement('div');\n spinner.className = `tbw-spinner tbw-spinner--${size}`;\n spinner.setAttribute('role', 'progressbar');\n spinner.setAttribute('aria-label', 'Loading');\n return spinner;\n}\n\n/**\n * Create loading content using custom renderer or default spinner.\n *\n * Strings returned by a custom renderer are passed through `setSanitizedHTML()`\n * — mirroring the cell, header and empty-state render paths — so a message\n * interpolating server data (e.g. `Loading ${dataset.name}…`) is not an XSS\n * sink.\n *\n * @param size - 'large' for grid overlay, 'small' for row/cell\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingContent(size: 'large' | 'small', renderer?: GridConfig['loadingRenderer']): HTMLElement {\n if (renderer) {\n const context: LoadingContext = { size };\n const result = renderer(context);\n if (typeof result === 'string') {\n const wrapper = document.createElement('div');\n setSanitizedHTML(wrapper, result);\n return wrapper;\n }\n return result;\n }\n\n return createDefaultSpinner(size);\n}\n\n/**\n * Create or update the loading overlay element.\n * @param renderer - Optional custom loading renderer from config\n */\nexport function createLoadingOverlay(renderer?: GridConfig['loadingRenderer']): HTMLElement {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-loading-overlay';\n overlay.setAttribute('role', 'status');\n overlay.setAttribute('aria-live', 'polite');\n overlay.appendChild(createLoadingContent('large', renderer));\n return overlay;\n}\n\n/**\n * Show the loading overlay on the grid root element.\n * @param gridRoot - The .tbw-grid-root element\n * @param overlayEl - The overlay element (will be cached by caller)\n */\nexport function showLoadingOverlay(gridRoot: Element, overlayEl: HTMLElement): void {\n gridRoot.appendChild(overlayEl);\n}\n\n/**\n * Hide the loading overlay.\n * @param overlayEl - The overlay element to remove\n */\nexport function hideLoadingOverlay(overlayEl: HTMLElement | undefined): void {\n overlayEl?.remove();\n}\n\n/** Remove a cell's owned loading overlay and release adapter-managed content. */\nexport function removeCellLoadingOverlay(cellEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!cellEl.firstElementChild) return;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Move a cell's owned loading overlay in front of the cell while its content is rewritten,\n * so the still-active loader survives adapter release and content replacement. The caller\n * appends it back. The overlay stays connected because React prunes detached portal containers.\n */\nexport function parkCellLoadingOverlay(cellEl: HTMLElement): HTMLElement | null {\n if (!cellEl.firstElementChild) return null;\n const overlay = cellEl.querySelector<HTMLElement>(':scope > .tbw-cell-loading-overlay');\n if (!overlay) return null;\n const parent = cellEl.parentElement;\n if (parent) parent.insertBefore(overlay, cellEl);\n else overlay.remove();\n return overlay;\n}\n\n/** Remove a row's owned loading overlay and release adapter-managed content. */\nexport function removeRowLoadingOverlay(rowEl: HTMLElement, adapter?: Pick<FrameworkAdapter, 'unmount'>): void {\n if (!rowEl.firstElementChild) return;\n const overlay = rowEl.querySelector<HTMLElement>(':scope > .tbw-row-loading-overlay');\n if (!overlay) return;\n adapter?.unmount?.(overlay);\n overlay.remove();\n}\n\n/**\n * Update a row element's loading state.\n * Uses real DOM elements instead of ::before/::after pseudo-elements\n * because the selection plugin already uses ::after on rows for border styling.\n * @param rowEl - The row element\n * @param loading - Whether the row is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * in place of the default spinner. Only invoked when the overlay is created.\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setRowLoadingState(\n rowEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n rowEl.classList.add('tbw-row-loading');\n rowEl.setAttribute('aria-busy', 'true');\n\n // Create overlay + spinner DOM elements if not already present.\n // Direct children only — a nested grid's row overlay must not be mistaken for this row's.\n if (!rowEl.querySelector(':scope > .tbw-row-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-row-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n\n if (renderer) {\n overlay.appendChild(createLoadingContent('small', renderer));\n } else {\n const spinner = document.createElement('div');\n spinner.className = 'tbw-row-loading-spinner';\n overlay.appendChild(spinner);\n }\n\n rowEl.appendChild(overlay);\n }\n } else {\n rowEl.classList.remove('tbw-row-loading');\n rowEl.removeAttribute('aria-busy');\n\n // Remove overlay + spinner DOM elements\n removeRowLoadingOverlay(rowEl, adapter);\n }\n}\n\n/**\n * Update a cell element's loading state.\n * @param cellEl - The cell element\n * @param loading - Whether the cell is loading\n * @param renderer - Optional `gridConfig.loadingRenderer`; called with `{ size: 'small' }`\n * @param adapter - Framework adapter used to release renderer-owned content on removal.\n */\nexport function setCellLoadingState(\n cellEl: HTMLElement,\n loading: boolean,\n renderer?: GridConfig['loadingRenderer'],\n adapter?: Pick<FrameworkAdapter, 'unmount'>,\n): void {\n if (loading) {\n cellEl.classList.add('tbw-cell-loading');\n cellEl.setAttribute('aria-busy', 'true');\n\n // Breadcrumb so the render hot path can skip the per-cell scan on the\n // overwhelming majority of rows. Conservative: only ever set here, so it can\n // read stale-true after the last loading cell clears (costs one extra scan).\n const rowEl = cellEl.parentElement as RowElementInternal | null;\n if (rowEl) rowEl.__hasCellLoading = true;\n\n if (renderer) {\n cellEl.classList.add('tbw-cell-loading-custom');\n if (!cellEl.querySelector(':scope > .tbw-cell-loading-overlay')) {\n const overlay = document.createElement('div');\n overlay.className = 'tbw-cell-loading-overlay';\n overlay.setAttribute('aria-hidden', 'true');\n overlay.appendChild(createLoadingContent('small', renderer));\n cellEl.appendChild(overlay);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading-custom');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n } else {\n cellEl.classList.remove('tbw-cell-loading');\n cellEl.classList.remove('tbw-cell-loading-custom');\n cellEl.removeAttribute('aria-busy');\n removeCellLoadingOverlay(cellEl, adapter);\n }\n}\n","/**\n * Row teardown shared by the core render path and plugin-rendered rows\n * (loading placeholders), so framework-adapter cleanup has one implementation.\n */\nimport type { GridHost } from '../types';\nimport { removeCellLoadingOverlay, removeRowLoadingOverlay } from './loading';\n\n/**\n * Release a pooled row's adapter-owned content — its row loader, cell loaders, then\n * cell views — before the row is discarded. Callers own the `beginBatch`/`endBatch`\n * bracket so a multi-row teardown collapses into one deferred commit (#330).\n */\nexport function releasePooledRow(adapter: GridHost['__frameworkAdapter'], rowEl: HTMLElement): void {\n if (!adapter?.releaseCell && !adapter?.unmount) return;\n removeRowLoadingOverlay(rowEl, adapter);\n const cells = rowEl.children;\n for (let c = 0; c < cells.length; c++) {\n const cell = cells[c] as HTMLElement;\n removeCellLoadingOverlay(cell, adapter);\n if (cell.firstElementChild) adapter.releaseCell?.(cell);\n }\n}\n\n/**\n * Wipe a pooled row's cells ahead of a full rebuild.\n *\n * Framework views are released BEFORE the DOM is wiped — without this,\n * Angular EmbeddedViewRefs / React roots / Vue apps created by renderers and\n * editor factories stay alive in the adapter's tracking arrays after their DOM\n * is destroyed, leaking memory on every recycle. Wrapped in `beginBatch`/`endBatch`\n * because `innerHTML = ''` detaches every cell as a group, letting adapters defer\n * per-cell sync commits to a single render once detachment completes (#330).\n */\nexport function clearRowForRebuild(grid: Pick<GridHost, '__frameworkAdapter'> & HTMLElement, rowEl: HTMLElement): void {\n // Clear loading state before rebuild — grid re-applies it after render for\n // actually-loading rows. Prevents a stale tbw-row-loading class from\n // persisting when pool elements are recycled.\n rowEl.classList.remove('tbw-row-loading');\n rowEl.removeAttribute('aria-busy');\n\n const adapter = grid.__frameworkAdapter;\n if (!adapter?.releaseCell && !adapter?.unmount) {\n rowEl.innerHTML = '';\n return;\n }\n adapter.beginBatch?.(grid);\n try {\n removeRowLoadingOverlay(rowEl, adapter);\n const children = rowEl.children;\n for (let i = children.length - 1; i >= 0; i--) {\n const cell = children[i] as HTMLElement;\n removeCellLoadingOverlay(cell, adapter);\n adapter.releaseCell?.(cell);\n }\n rowEl.innerHTML = '';\n } finally {\n adapter.endBatch?.(grid);\n }\n}\n","/**\n * Loading placeholder rows shared by plugins that synthesize them (ServerSide\n * blocks in flight, GroupingRows groups being fetched). Inlined into each\n * plugin bundle that imports it — core never calls it.\n */\nimport { setRowLoadingState } from '../../core/internal/loading';\nimport { clearRowForRebuild } from '../../core/internal/row-teardown';\nimport type { GridHost, RowElementInternal } from '../../core/types';\n\n/**\n * Marker class on placeholder rows. Lets layout plugins (Responsive card mode)\n * tell a placeholder apart from a data row — `tbw-row-loading` is not enough,\n * because `grid.setRowLoading()` puts that on real rows too.\n */\nexport const PLACEHOLDER_ROW_CLASS = 'placeholder-row';\n\n/**\n * Render a placeholder as one full-width cell in the core row-loading state, so\n * no column renderer runs for a row that holds no data.\n *\n * Call from a plugin `renderRow` hook and return `true`. The previous cells are\n * released through the framework adapter first (a pooled element may have held\n * React portals / Vue teleports / Angular views for a loaded row). The row is\n * flagged `__isCustomRow`, which forces a full rebuild once real data replaces\n * the placeholder; that rebuild also clears the loading state.\n *\n * Height: the row occupies exactly what virtualization reserves for it — the\n * height a plugin reports through `getRowHeight()` (e.g. a Responsive card), else\n * the default row height. Any inline height a recycled element carried (a\n * Responsive card height, a per-row `--tbw-row-height`) is dropped.\n */\nexport function renderLoadingPlaceholderRow(grid: GridHost, rowEl: HTMLElement, row: unknown, rowIndex: number): void {\n const el = rowEl as RowElementInternal;\n syncPlaceholderHeight(grid, el, row, rowIndex);\n // Same placeholder, still intact: nothing else to do (renders run every scroll frame).\n if (el.__rowDataRef === row && el.__isCustomRow && el.classList.contains('tbw-row-loading')) return;\n\n clearRowForRebuild(grid, el);\n el.className = `data-grid-row ${PLACEHOLDER_ROW_CLASS}`;\n el.__isCustomRow = true;\n const cell = document.createElement('div');\n cell.className = 'cell';\n cell.style.gridColumn = '1 / -1';\n cell.setAttribute('role', 'gridcell');\n cell.textContent = '\\u00A0'; // keeps the row at its normal height\n el.appendChild(cell);\n setRowLoadingState(el, true, grid.effectiveConfig?.loadingRenderer);\n}\n\n/** Match the row's DOM height to the slot virtualization reserves for it. Writes only on change. */\nfunction syncPlaceholderHeight(grid: GridHost, el: HTMLElement, row: unknown, rowIndex: number): void {\n const { style } = el;\n if (style.getPropertyValue('--tbw-row-height')) style.removeProperty('--tbw-row-height');\n const pluginHeight = grid._getPluginRowHeight?.(row, rowIndex);\n const height = pluginHeight !== undefined && pluginHeight > 0 ? `${pluginHeight}px` : '';\n if (style.height !== height) style.height = height;\n}\n","import type { GetRowsParams, GetRowsResult, ServerSideDataSource, Subscribable } from './datasource-types';\n\nexport function getBlockNumber(nodeIndex: number, blockSize: number): number {\n return Math.floor(nodeIndex / blockSize);\n}\n\nexport function getBlockRange(blockNumber: number, blockSize: number): { start: number; end: number } {\n return {\n start: blockNumber * blockSize,\n end: (blockNumber + 1) * blockSize,\n };\n}\n\nexport function getRequiredBlocks(startNode: number, endNode: number, blockSize: number): number[] {\n const startBlock = getBlockNumber(startNode, blockSize);\n const endBlock = getBlockNumber(endNode - 1, blockSize);\n\n const blocks: number[] = [];\n for (let i = startBlock; i <= endBlock; i++) {\n blocks.push(i);\n }\n return blocks;\n}\n\nfunction isSubscribable<T>(value: unknown): value is Subscribable<T> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { subscribe?: unknown }).subscribe === 'function' &&\n // Promises don't have `.subscribe`, but defensively rule them out.\n typeof (value as { then?: unknown }).then !== 'function'\n );\n}\n\nfunction makeAbortError(): DOMException {\n return new DOMException('Aborted', 'AbortError');\n}\n\n/**\n * Bridge a `Promise | Subscribable` getRows return value into a single\n * `Promise<GetRowsResult>`. For Subscribables, abort triggers `unsubscribe()`\n * so the underlying request (e.g. Angular `HttpClient` XHR) is cancelled.\n * Promise sources should pass `signal` to `fetch` themselves — we still reject\n * on abort either way so the plugin's abort path is consistent.\n */\nexport function toResultPromise<T>(source: Promise<T> | Subscribable<T>, signal: AbortSignal): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(makeAbortError());\n }\n if (!isSubscribable<T>(source)) {\n // Promise path: reject on abort so the plugin's catch sees a consistent\n // signal even if the underlying fetch ignored params.signal.\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(makeAbortError());\n signal.addEventListener('abort', onAbort, { once: true });\n Promise.resolve(source).then(\n (v) => {\n signal.removeEventListener('abort', onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener('abort', onAbort);\n reject(e);\n },\n );\n });\n }\n // Subscribable path: subscribe once, settle on next/error/complete, and\n // unsubscribe on abort — that's what cancels HttpClient's XHR.\n return new Promise<T>((resolve, reject) => {\n let settled = false;\n const subscription = source.subscribe({\n next: (value) => {\n if (settled) return;\n settled = true;\n resolve(value);\n subscription.unsubscribe();\n },\n error: (err) => {\n if (settled) return;\n settled = true;\n reject(err);\n },\n complete: () => {\n if (settled) return;\n settled = true;\n reject(new Error('getRows observable completed without emitting a value'));\n },\n });\n if (settled) return; // synchronous emit\n const onAbort = () => {\n if (settled) return;\n settled = true;\n subscription.unsubscribe();\n reject(makeAbortError());\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport function loadBlock(\n dataSource: ServerSideDataSource,\n blockNumber: number,\n blockSize: number,\n params: Partial<GetRowsParams>,\n signal: AbortSignal,\n): Promise<GetRowsResult> {\n const range = getBlockRange(blockNumber, blockSize);\n\n let result: Promise<GetRowsResult> | Subscribable<GetRowsResult>;\n try {\n result = dataSource.getRows({\n startNode: range.start,\n endNode: range.end,\n pageSize: range.end - range.start,\n sortModel: params.sortModel,\n filterModel: params.filterModel,\n signal,\n });\n } catch (error) {\n // A non-async getRows() can throw synchronously — surface it as a rejection\n // so the caller's .catch releases the block and broadcasts datasource:error.\n return Promise.reject(error);\n }\n return toResultPromise(result, signal);\n}\n\nexport function getRowFromCache(\n nodeIndex: number,\n blockSize: number,\n loadedBlocks: Map<number, unknown[]>,\n): unknown | undefined {\n const blockNumber = getBlockNumber(nodeIndex, blockSize);\n const block = loadedBlocks.get(blockNumber);\n if (!block) return undefined;\n\n const indexInBlock = nodeIndex % blockSize;\n return block[indexInBlock];\n}\n\nexport function isBlockLoaded(blockNumber: number, loadedBlocks: Map<number, unknown[]>): boolean {\n return loadedBlocks.has(blockNumber);\n}\n\nexport function isBlockLoading(blockNumber: number, loadingBlocks: Set<number>): boolean {\n return loadingBlocks.has(blockNumber);\n}\n\n/** Sources built by {@link createUrlDataSource}. */\nconst urlDataSources = new WeakSet<ServerSideDataSource>();\n\n/**\n * Build a default {@link ServerSideDataSource} that fetches the whole dataset\n * from a URL once and serves it in blocks from memory. Powers the declarative\n * `<tbw-grid data-src=\"...\">` shorthand (issue #273) so a zero-JS HTML page can\n * render server-fetched rows.\n *\n * The endpoint may return either a plain array of rows (`[...]`) or an envelope\n * (`{ rows, totalNodeCount }`). The fetch runs at most once on success — the\n * resolved dataset is cached and sliced per `getRows` block — so a static JSON\n * file works out of the box. A failed (or aborted) fetch is not cached, so a\n * later block request retries instead of leaving the grid permanently empty.\n * For true server-side pagination (per-block fetches, remote sort/filter),\n * provide a `dataSource` in the plugin config instead.\n *\n * @param url Absolute or relative URL. The fetch runs at most once on success,\n * so only the first `getRows()` call's `signal` is passed to `fetch()`;\n * later calls resolve from the cached dataset and don't re-fetch.\n * @internal\n */\nexport function createUrlDataSource(url: string): ServerSideDataSource {\n let datasetPromise: Promise<{ rows: unknown[]; total: number }> | null = null;\n\n const loadDataset = (signal: AbortSignal): Promise<{ rows: unknown[]; total: number }> => {\n if (!datasetPromise) {\n datasetPromise = fetch(url, { signal })\n .then(async (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch \"${url}\": ${response.status} ${response.statusText}`);\n }\n const data: unknown = await response.json();\n if (Array.isArray(data)) {\n return { rows: data, total: data.length };\n }\n const envelope = (data ?? {}) as { rows?: unknown[]; totalNodeCount?: number };\n const rows = Array.isArray(envelope.rows) ? envelope.rows : [];\n const total = typeof envelope.totalNodeCount === 'number' ? envelope.totalNodeCount : rows.length;\n return { rows, total };\n })\n .catch((err) => {\n // Don't cache failures/aborts — the plugin aborts in-flight block\n // requests on sort/filter/refresh, and caching the rejected promise\n // would poison every later block load. Null it so the next request\n // re-fetches.\n datasetPromise = null;\n throw err;\n });\n }\n return datasetPromise;\n };\n\n const source: ServerSideDataSource = {\n async getRows({ startNode, endNode, signal }: GetRowsParams): Promise<GetRowsResult> {\n const { rows, total } = await loadDataset(signal);\n return { rows: rows.slice(startNode, endNode), totalNodeCount: total };\n },\n };\n urlDataSources.add(source);\n return source;\n}\n\n/**\n * Whether `source` was built by {@link createUrlDataSource}. Such a source only\n * slices a cached dataset and ignores `sortModel` / `filterModel`, so the grid\n * must sort and filter its rows locally.\n * @internal\n */\nexport function isUrlDataSource(source: ServerSideDataSource | null): boolean {\n return source != null && urlDataSources.has(source);\n}\n","/**\n * Server-Side Data Plugin (Class-based)\n *\n * Central data orchestrator for the grid. Owns fetch + cache + row-model management.\n * Structural plugins (Tree, GroupingRows) claim data via events; core grid uses it\n * as flat rows when unclaimed.\n */\n\nimport {\n DATASOURCE_CHILD_FETCH_ERROR,\n DATASOURCE_FETCH_ERROR,\n DATASOURCE_NO_CHILD_HANDLER,\n DATASOURCE_THROTTLED,\n debugDiagnostic,\n errorDiagnostic,\n warnDiagnostic,\n} from '../../core/internal/diagnostics';\nimport { builtInSort } from '../../core/internal/sorting';\nimport { BaseGridPlugin, ScrollEvent, type PluginManifest, type PluginQuery } from '../../core/plugin/base-plugin';\nimport type { ColumnConfig } from '../../core/types';\nimport { renderLoadingPlaceholderRow } from '../shared/loading-placeholder';\nimport {\n createUrlDataSource,\n getBlockNumber,\n getRequiredBlocks,\n getRowFromCache,\n isUrlDataSource,\n loadBlock,\n} from './datasource';\nimport type {\n DataSourceChildrenDetail,\n DataSourceDataDetail,\n DataSourceErrorDetail,\n DataSourceLoadingDetail,\n FetchChildrenQuery,\n GetChildRowsResult,\n GetRowsParams,\n GetRowsResult,\n ServerSideDataSource,\n ViewportMappingQuery,\n ViewportMappingResponse,\n} from './datasource-types';\nimport { createLoadingPlaceholder, isLoadingPlaceholder } from './placeholder';\nimport type { ServerSideConfig } from './types';\n\n/** Scroll debounce delay in ms */\nconst SCROLL_DEBOUNCE_MS = 100;\n\n/** Add the blocks covering nodes `[start, end)`, clamped to `[0, knownTotal)`. */\nfunction addRangeBlocks(blocks: Set<number>, start: number, end: number, blockSize: number, knownTotal: number): void {\n const from = Math.max(0, start);\n const to = Math.min(knownTotal, end);\n if (to > from) for (const block of getRequiredBlocks(from, to, blockSize)) blocks.add(block);\n}\n\n/**\n * Server-Side Data Plugin for tbw-grid\n *\n * Central data orchestrator for the grid. Manages fetch, cache, and row-model for\n * server-side data loading. Structural plugins (Tree, GroupingRows) can claim data\n * via events; the core grid uses it as flat rows when unclaimed.\n *\n * ## Installation\n *\n * ```ts\n * import { ServerSidePlugin } from '@toolbox-web/grid/plugins/server-side';\n * ```\n *\n * ## DataSource Interface\n *\n * ```ts\n * interface ServerSideDataSource {\n * getRows(params: GetRowsParams): Promise<GetRowsResult>;\n * getChildRows?(params: GetChildRowsParams): Promise<GetChildRowsResult>;\n * }\n * ```\n *\n * @example Basic Server-Side Loading\n * ```ts\n * import '@toolbox-web/grid';\n * import '@toolbox-web/grid/features/server-side';\n *\n * grid.gridConfig = {\n * columns: [...],\n * features: {\n * serverSide: {\n * pageSize: 50,\n * dataSource: {\n * async getRows(params) {\n * const response = await fetch(\n * `/api/data?start=${params.startNode}&end=${params.endNode}`\n * );\n * const data = await response.json();\n * return { rows: data.rows, totalNodeCount: data.total };\n * },\n * },\n * },\n * },\n * };\n * ```\n *\n * @see {@link ServerSideConfig} for configuration options\n * @see {@link ServerSideDataSource} for data source interface\n *\n * @internal Extends BaseGridPlugin\n * @since 0.1.1\n */\nexport class ServerSidePlugin extends BaseGridPlugin<ServerSideConfig> {\n /**\n * Plugin manifest declaring capabilities, hooks, events, and queries.\n * @internal\n */\n static override readonly manifest: PluginManifest = {\n modifiesRowStructure: true,\n hookPriority: {\n processRows: -10, // Run before structural plugins (Tree, GroupingRows)\n renderRow: -10, // Claim placeholders before row renderers (e.g. Responsive cardRenderer) see them\n },\n incompatibleWith: [\n {\n name: 'pivot',\n reason:\n 'PivotPlugin requires the full dataset to compute aggregations. ' +\n 'ServerSidePlugin lazy-loads rows in blocks, so pivot aggregation cannot be performed client-side.',\n },\n ],\n events: [\n { type: 'datasource:data', description: 'Root data page/block loaded' },\n { type: 'datasource:children', description: 'Child data loaded for a parent context' },\n { type: 'datasource:loading', description: 'Loading state changed' },\n { type: 'datasource:error', description: 'Fetch operation failed' },\n ],\n queries: [\n { type: 'datasource:fetch-children', description: 'Request child rows for a parent context' },\n { type: 'datasource:is-active', description: 'Check if ServerSide plugin has an active data source' },\n {\n type: 'datasource:filter-mode',\n description: \"Who filters rows while a data source is active: 'server' (data source) or 'local' (grid)\",\n },\n {\n type: 'datasource:sort-mode',\n description: \"Who sorts rows while a data source is active: 'server' (data source) or 'local' (grid)\",\n },\n ],\n };\n\n /** @internal */\n readonly name = 'serverSide';\n\n /** @internal */\n protected override get defaultConfig(): Partial<ServerSideConfig> {\n return {\n maxConcurrentRequests: 2,\n };\n }\n\n // #region Internal State\n private dataSource: ServerSideDataSource | null = null;\n private totalNodeCount = 0;\n private infiniteScrollMode = false;\n private loadedBlocks = new Map<number, unknown[]>();\n private loadingBlocks = new Set<number>();\n /**\n * Per-block AbortControllers for in-flight requests. Aborted when a block\n * is superseded (sort/filter change, refresh, purgeCache, detach) so data\n * sources that honor `params.signal` (e.g. `fetch`, RxJS via `fromObservable`)\n * can cancel the underlying network call.\n */\n private blockControllers = new Map<number, AbortController>();\n /**\n * In-flight `getChildRows` requests. Aborted only on `detach()` or when the\n * requester's `FetchChildrenQuery.signal` fires — NOT on sort/filter/refresh:\n * cancellation is requester-owned (Tree, GroupingRows, MasterDetail each\n * abort their own stale loads). An abort broadcasts only `datasource:loading`\n * `false`, which no requester treats as a release, so an unrequested abort\n * would strand its loading state.\n */\n private childControllers = new Set<AbortController>();\n private scrollDebounceTimer?: ReturnType<typeof setTimeout>;\n /**\n * One-shot flag set when a block lands; consumed in `afterRender()` to re-check\n * required blocks against the viewport produced by the render that the new data\n * triggered (a synchronous check would see the pre-render virtual window).\n */\n private pendingViewportCheck = false;\n /** Persistent node array with stable placeholder references to avoid unnecessary DOM rebuilds. */\n private managedNodes: unknown[] = [];\n /**\n * Bumped whenever the block cache is discarded; stamped on `datasource:data` so\n * structural consumers (GroupingRows) can tell an appended block from a new dataset.\n */\n #generation = 0;\n // #endregion\n\n // #region Lifecycle\n\n /** @internal */\n override attach(grid: import('../../core/plugin/base-plugin').GridElement): void {\n super.attach(grid);\n\n // Invalidate cache and refetch on sort/filter changes — gated by sortMode/filterMode.\n // 'local' (opt-in): keep cache; sort/filter the loaded rows in place via a re-render.\n // See getEnrichmentParams() — local-mode state is also omitted from block fetch params\n // so scroll-triggered loadRequiredBlocks() doesn't leak local state to the backend.\n this.on('sort-change', () => {\n if (this.sortMode === 'local') {\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n this.on('filter-change', () => {\n if (this.filterMode === 'local') {\n // The filter can reject rows above unloaded placeholders, moving them into\n // view without a scroll — re-check the viewport after this render (#520).\n this.pendingViewportCheck = true;\n this.requestRender();\n } else {\n this.onModelChange();\n }\n });\n\n // Auto-initialize from config when dataSource is provided declaratively\n if (this.config.dataSource) {\n this.setDataSource(this.config.dataSource);\n return;\n }\n\n // Declarative `data-src` shorthand (issue #273): when no JS dataSource is\n // configured, read the host's `data-src` attribute and fetch the whole\n // dataset from that URL. Enables a zero-JS HTML page to render\n // server-fetched rows. A JS `dataSource` config always takes precedence.\n const src = this.gridElement?.getAttribute('data-src');\n if (src) {\n this.setDataSource(createUrlDataSource(src));\n }\n }\n\n /** @internal */\n override detach(): void {\n this.dataSource = null;\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.loadedBlocks.clear();\n this.#generation++;\n this.abortAllBlocks();\n for (const controller of this.childControllers) controller.abort();\n this.childControllers.clear();\n this.managedNodes = [];\n this.pendingViewportCheck = false;\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n this.scrollDebounceTimer = undefined;\n }\n }\n // #endregion\n\n // #region Private Methods\n\n /**\n * Abort all in-flight block requests and release their loading slots. Called\n * when the plugin tears down, the data source is replaced, the cache is purged,\n * or the sort/filter model changes (the previously loaded block coordinates no\n * longer apply).\n */\n private abortAllBlocks(): void {\n for (const controller of this.blockControllers.values()) {\n controller.abort();\n }\n this.blockControllers.clear();\n this.loadingBlocks.clear();\n }\n\n /**\n * Release `blockNum`'s in-flight slot when its request settles — but only if\n * `controller` still owns it. An aborted request settles a microtask after the\n * abort, by which time a superseding request (refresh, sort/filter change) may\n * have re-registered the same block; deleting that entry would orphan the new\n * request from `abortAllBlocks()` and let stale rows land in the cache.\n */\n private releaseBlock(blockNum: number, controller: AbortController): void {\n if (this.blockControllers.get(blockNum) !== controller) return;\n this.blockControllers.delete(blockNum);\n this.loadingBlocks.delete(blockNum);\n }\n\n /**\n * Effective sort/filter ownership. The `data-src` URL source only slices a cached\n * dataset and ignores `sortModel` / `filterModel`, so it is always `'local'` —\n * otherwise a sort or filter would refetch the unchanged rows and nobody would\n * apply it.\n */\n private get sortMode(): 'server' | 'local' {\n return isUrlDataSource(this.dataSource) ? 'local' : (this.config.sortMode ?? 'server');\n }\n\n private get filterMode(): 'server' | 'local' {\n return isUrlDataSource(this.dataSource) ? 'local' : (this.config.filterMode ?? 'server');\n }\n\n /**\n * Build enrichment params by querying sort/filter models from loaded plugins.\n *\n * When `sortMode === 'local'` the `sortModel` is omitted so scroll-triggered\n * block fetches don't ask the backend for an ordering it isn't applying.\n * Same for `filterMode === 'local'` and `filterModel`.\n */\n private getEnrichmentParams(): Partial<GetRowsParams> {\n const sortLocal = this.sortMode === 'local';\n const filterLocal = this.filterMode === 'local';\n const sortResults = sortLocal\n ? undefined\n : (this.grid?.query?.('sort:get-model', null) as\n Array<{ field: string; direction: 'asc' | 'desc' }>[] | undefined);\n const filterResults = filterLocal\n ? undefined\n : (this.grid?.query?.('filter:get-model', null) as Record<string, unknown>[] | undefined);\n\n // Fallback to core single-column sort state when no plugin answers the\n // 'sort:get-model' query (e.g. MultiSortPlugin not loaded). Translate the\n // numeric direction (1/-1) to the public 'asc'/'desc' string form.\n let sortModel = sortResults?.[0];\n const host = this.grid;\n if (!sortLocal && !sortModel && host?._sortState) {\n const { field, direction } = host._sortState;\n sortModel = [{ field, direction: direction === 1 ? 'asc' : 'desc' }];\n }\n\n return {\n sortModel,\n filterModel: filterResults?.[0],\n };\n }\n\n /**\n * Blocks (ascending) the viewport — expanded by `threshold` rows both ways to\n * prefetch — needs loaded. The viewport is translated through a structural\n * plugin's `datasource:viewport-mapping` when one responds, else 1:1 (flat data).\n *\n * When the displayed rows are not `managedNodes` itself, a later stage may have\n * dropped or reordered rows (local filter or sort), or a structural plugin\n * renumbered the rows it kept (Tree counts the remaining roots from zero). Then a\n * display index is no longer a node index, so the blocks of the placeholders on\n * screen are added: their `__index` is their node index, and loaded rows need no fetch.\n */\n private getRequiredBlockNumbers(\n viewportStart: number,\n viewportEnd: number,\n threshold: number,\n blockSize: number,\n ): number[] {\n // Blocks past the end of data are never requested (see `knownTotal`).\n const knownTotal = this.knownTotal;\n const blocks = new Set<number>();\n const mapped = this.queryViewportMapping(viewportStart, viewportEnd);\n const displayDiffers = this.displayDiffers;\n\n if (mapped || !displayDiffers) {\n const range = mapped ?? { startNode: viewportStart, endNode: viewportEnd };\n addRangeBlocks(blocks, range.startNode - threshold, range.endNode + threshold, blockSize, knownTotal);\n }\n if (displayDiffers) {\n this.addPlaceholderBlocks(blocks, viewportStart - threshold, viewportEnd + threshold, blockSize, knownTotal);\n }\n return [...blocks].sort((a, b) => a - b);\n }\n\n /**\n * `totalNodeCount`, or `Infinity` while it is unknown — `0` means \"not yet loaded\"\n * (just after purgeCache, or before the first fetch resolves), and block 0 must\n * still be fetchable then.\n */\n private get knownTotal(): number {\n return this.totalNodeCount > 0 ? this.totalNodeCount : Infinity;\n }\n\n /** Whether the displayed rows are not `managedNodes` itself, so display indices may not be node indices. */\n private get displayDiffers(): boolean {\n return this.rows !== this.managedNodes && this.managedNodes.length > 0;\n }\n\n /** A structural plugin's (Tree, GroupingRows) translation of the viewport to node space, if any. */\n private queryViewportMapping(viewportStart: number, viewportEnd: number): ViewportMappingResponse | undefined {\n const query: ViewportMappingQuery = { viewportStart, viewportEnd };\n const results = this.grid?.query?.('datasource:viewport-mapping', query) as ViewportMappingResponse[] | undefined;\n return results?.[0];\n }\n\n /** Add the block of every placeholder displayed in `[displayStart, displayEnd)` (may be fractional). */\n private addPlaceholderBlocks(\n blocks: Set<number>,\n displayStart: number,\n displayEnd: number,\n blockSize: number,\n knownTotal: number,\n ): void {\n const rows = this.rows;\n const last = Math.min(rows.length, Math.ceil(displayEnd));\n for (let i = Math.max(0, Math.floor(displayStart)); i < last; i++) {\n const row = rows[i];\n if (isLoadingPlaceholder(row) && row.__index < knownTotal) blocks.add(getBlockNumber(row.__index, blockSize));\n }\n }\n\n /**\n * Handle sort or filter model changes.\n * Purge cache and refetch current viewport with new enrichment params.\n */\n private onModelChange(): void {\n if (!this.dataSource) return;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.#generation++;\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.requestRender();\n // Eagerly fetch the current viewport with the new enrichment params.\n // Without this, the table stays blank until the user scrolls (no other\n // path triggers a fetch — processRows just rebuilds from cached blocks).\n this.loadRequiredBlocks();\n }\n\n /**\n * Apply server response metadata: resolve totalNodeCount and infinite scroll mode.\n * When `lastNode` is provided, it takes priority and finalizes the total.\n * When `totalNodeCount` is -1, switch to infinite scroll (growing array).\n * When a block returns fewer rows than blockSize, detect end-of-data.\n */\n private applyServerResult(result: GetRowsResult, blockNum: number, blockSize: number): void {\n if (result.lastNode !== undefined) {\n // Server declared the exact end\n this.totalNodeCount = result.lastNode + 1;\n this.infiniteScrollMode = false;\n } else if (result.totalNodeCount === -1) {\n this.infiniteScrollMode = true;\n } else {\n this.totalNodeCount = result.totalNodeCount;\n this.infiniteScrollMode = false;\n }\n\n // Auto-detect end of data: short block means server has no more rows\n if (this.infiniteScrollMode && result.rows.length < blockSize) {\n this.totalNodeCount = blockNum * blockSize + result.rows.length;\n this.infiniteScrollMode = false;\n }\n }\n\n /**\n * Estimate the row count for infinite scroll mode.\n * Returns loaded rows + one extra block of placeholders to trigger next fetch.\n */\n private getInfiniteScrollEstimate(blockSize: number): number {\n let maxLoadedEnd = 0;\n for (const [block, rows] of this.loadedBlocks) {\n const end = block * blockSize + rows.length;\n if (end > maxLoadedEnd) maxLoadedEnd = end;\n }\n return maxLoadedEnd + blockSize;\n }\n\n /**\n * Length `managedNodes` must have: the infinite-scroll estimate, else\n * `totalNodeCount` (guarded against an invalid value from a malformed\n * datasource response, e.g. `undefined`).\n */\n private getNodeCount(blockSize: number): number {\n if (this.infiniteScrollMode) return this.getInfiniteScrollEstimate(blockSize);\n return Number.isFinite(this.totalNodeCount) && this.totalNodeCount >= 0 ? this.totalNodeCount : 0;\n }\n\n /**\n * Check current viewport and load any missing blocks.\n */\n private loadRequiredBlocks(): void {\n if (!this.dataSource) return;\n\n const { _virtualization } = this.grid;\n const blockSize = this.config.pageSize ?? 100;\n\n // Blocks the viewport covers in node space, expanded by loadThreshold in both\n // directions to prefetch blocks the user is about to scroll into.\n const threshold = Math.max(0, this.config.loadThreshold ?? 0);\n const requiredBlocks = this.getRequiredBlockNumbers(\n _virtualization.start,\n _virtualization.end,\n threshold,\n blockSize,\n );\n if (requiredBlocks.length === 0) return;\n\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n // Load missing blocks\n for (const blockNum of requiredBlocks) {\n if (this.loadedBlocks.has(blockNum) || this.loadingBlocks.has(blockNum)) {\n continue;\n }\n\n // Check concurrent request limit\n if (this.loadingBlocks.size >= (this.config.maxConcurrentRequests ?? 2)) {\n debugDiagnostic(DATASOURCE_THROTTLED, 'Concurrent request limit reached, deferring block load', gridId);\n break;\n }\n\n this.loadingBlocks.add(blockNum);\n const controller = new AbortController();\n this.blockControllers.set(blockNum, controller);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(this.dataSource, blockNum, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.releaseBlock(blockNum, controller);\n // Drop results from a request that was superseded after the await\n // resolved (data source ignored the abort signal). Without this guard\n // a stale block would land in the cache after a sort/filter change.\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n this.loadedBlocks.set(blockNum, result.rows);\n // Capture pre-update length so we can detect whether processRows must\n // re-run to grow the managedNodes array (e.g. after onModelChange reset).\n const previousManagedLength = this.managedNodes.length;\n this.applyServerResult(result, blockNum, blockSize);\n\n // Update managed nodes in place for this block (avoids full processRows rebuild)\n const start = blockNum * blockSize;\n for (let i = 0; i < result.rows.length; i++) {\n if (start + i < this.managedNodes.length) {\n this.managedNodes[start + i] = result.rows[i];\n }\n }\n\n // Broadcast data event with claimed flag\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: start,\n endNode: start + result.rows.length,\n claimed: false,\n generation: this.#generation,\n };\n this.broadcast('datasource:data', detail);\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n\n // If managedNodes is not sized for the (possibly newly known) node count\n // — reset to 0 by onModelChange() right before this fetch, an infinite-\n // scroll estimate that grows by a block, or a short block that finalized\n // a smaller total — we MUST run processRows to resize the array. The\n // in-place writes above cannot grow or shrink it.\n // Without this, sort/filter changes leave the grid permanently blank\n // and infinite scroll stalls after the second block.\n // A structural plugin (Tree, GroupingRows) that claimed the data derives\n // its own row model from `managedNodes`. The in-place element swap above\n // is invisible to that derived model — it still references the discarded\n // placeholder objects — so processRows MUST re-run for it to re-derive.\n // The same holds when `_rows` is not `managedNodes` itself: a later\n // processRows stage (local sort, local filter, MultiSort) produced it\n // from the previous contents (#520).\n // With variable row heights the loaded rows can differ in height from the\n // placeholders they replace; only the ROWS → forced-refresh path rebuilds\n // the position cache and spacer (refreshVirtualWindow(false) does neither).\n const needsRowModelRebuild =\n previousManagedLength === 0 ||\n detail.claimed ||\n this.rows !== this.managedNodes ||\n this.managedNodes.length !== this.getNodeCount(blockSize) ||\n this.grid._virtualization?.variableHeights === true;\n\n if (needsRowModelRebuild) {\n // New identity so downstream processRows caches keyed on the input\n // reference (e.g. FilteringPlugin) see the loaded rows (#520).\n this.managedNodes = this.managedNodes.slice();\n // Scheduled render: re-check against its viewport in afterRender().\n this.pendingViewportCheck = true;\n this.requestRender();\n } else {\n // Re-render visible rows without force geometry recalculation.\n // requestVirtualRefresh() skips spacer height writes that cause oscillation\n // with the scheduler's afterRender microtask. Node count hasn't changed and\n // row heights are uniform — only cached data replaced placeholders — so\n // geometry is stable.\n this.requestVirtualRefresh();\n }\n\n // Re-check now in case the user scrolled while the block was in flight\n // (requestVirtualRefresh() is synchronous, so the window is current).\n this.loadRequiredBlocks();\n })\n .catch((error: unknown) => {\n this.releaseBlock(blockNum, controller);\n // A superseded request may surface as either an AbortError or as a\n // user-thrown error after the data source detected the abort —\n // suppress diagnostics in both cases. Real failures still surface.\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n });\n }\n }\n // #endregion\n\n // #region Hooks\n\n /** @internal */\n override processRows(rows: readonly unknown[]): unknown[] {\n if (!this.dataSource) return [...rows];\n\n const blockSize = this.config.pageSize ?? 100;\n const nodeCount = this.getNodeCount(blockSize);\n\n // Grow array with stable placeholder objects (created once, reused across renders)\n while (this.managedNodes.length < nodeCount) {\n this.managedNodes.push(createLoadingPlaceholder(this.managedNodes.length));\n }\n // Shrink if total decreased\n this.managedNodes.length = nodeCount;\n\n // Replace placeholders with cached data (stable refs for unchanged entries)\n for (let i = 0; i < nodeCount; i++) {\n const cached = getRowFromCache(i, blockSize, this.loadedBlocks);\n if (cached) {\n this.managedNodes[i] = cached;\n }\n }\n\n // Local-mode sort: when sortMode === 'local' the plugin owns ordering of\n // the loaded rows itself (core sort ran on the input but we discarded it\n // by returning managedNodes). Apply the current core sort state on top of\n // managedNodes so the user sees in-place sorting without a refetch.\n // Note: any plugin sort that runs after us (priority > -10, e.g. multi-sort)\n // will further re-sort our output, which is the intended chain.\n const host = this.grid;\n if (this.sortMode === 'local' && host?._sortState) {\n const columns = (host._columns ?? []) as ColumnConfig[];\n // Honor user's gridConfig.sortHandler when provided — same resolution\n // as core's reapplyCoreSort/applySort. processRows is synchronous, so\n // async handlers cannot be awaited here: keep the current managedNodes\n // order for this pass and swallow any rejection so it doesn't surface\n // as an unhandled promise rejection. The next core sort cycle (or the\n // next block load) will re-invoke this path with up-to-date state.\n const handler = host.effectiveConfig?.sortHandler ?? builtInSort;\n const result = handler(this.managedNodes, host._sortState, columns);\n if (result && typeof (result as Promise<unknown[]>).then === 'function') {\n void (result as Promise<unknown[]>).catch(() => undefined);\n return this.managedNodes;\n }\n return result as unknown[];\n }\n\n return this.managedNodes;\n }\n\n /** @internal */\n override renderRow(row: unknown, rowEl: HTMLElement, rowIndex: number): boolean {\n if (!isLoadingPlaceholder(row) || this.config.placeholderRendering === 'columns') return false;\n renderLoadingPlaceholderRow(this.grid, rowEl, row, rowIndex);\n return true;\n }\n\n /** @internal */\n override afterRender(): void {\n if (!this.pendingViewportCheck) return;\n this.pendingViewportCheck = false;\n this.loadRequiredBlocks();\n }\n\n /** @internal */\n override onScroll(_event: ScrollEvent): void {\n if (!this.dataSource) return;\n\n // Immediate check for blocks\n this.loadRequiredBlocks();\n\n // Debounce: when scrolling stops, do a final check with fresh viewport\n if (this.scrollDebounceTimer) {\n clearTimeout(this.scrollDebounceTimer);\n }\n this.scrollDebounceTimer = setTimeout(() => {\n this.loadRequiredBlocks();\n }, SCROLL_DEBOUNCE_MS);\n }\n\n /** @internal */\n override handleQuery(query: PluginQuery): unknown {\n switch (query.type) {\n case 'datasource:is-active':\n return this.dataSource != null;\n\n case 'datasource:filter-mode':\n return this.dataSource ? this.filterMode : undefined;\n\n case 'datasource:sort-mode':\n return this.dataSource ? this.sortMode : undefined;\n\n case 'datasource:fetch-children': {\n const { context, signal } = query.context as FetchChildrenQuery;\n this.fetchChildren(context, signal);\n return undefined;\n }\n }\n return undefined;\n }\n // #endregion\n\n // #region Child Data Fetching\n\n /**\n * Fetch child rows via the datasource and broadcast the result.\n * `requesterSignal` (from `FetchChildrenQuery.signal`) aborts the request;\n * an aborted request broadcasts only `datasource:loading` `false`.\n */\n private fetchChildren(context: { source: string; [key: string]: unknown }, requesterSignal?: AbortSignal): void {\n if (!this.dataSource) return;\n if (requesterSignal?.aborted) return;\n\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n\n if (!this.dataSource.getChildRows) {\n const message = `Plugin \"${context.source}\" requested child rows but getChildRows() is not implemented on the dataSource`;\n warnDiagnostic(DATASOURCE_NO_CHILD_HANDLER, message, gridId);\n // Settle the request: requesters hold a pending-load entry from the moment\n // they query, and only `datasource:children`/`error` releases it (#539).\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: new Error(message), context });\n return;\n }\n\n const enrichment = this.getEnrichmentParams();\n const controller = new AbortController();\n const abort = (): void => controller.abort();\n // Untrack on abort rather than on settlement — a getChildRows() that ignores\n // the signal may never settle, and its controller must not outlive cancellation.\n const release = (): void => {\n this.childControllers.delete(controller);\n requesterSignal?.removeEventListener('abort', abort);\n controller.signal.removeEventListener('abort', release);\n };\n controller.signal.addEventListener('abort', release, { once: true });\n requesterSignal?.addEventListener('abort', abort, { once: true });\n this.childControllers.add(controller);\n // Settle the request; `false` when it was aborted and its result must be dropped.\n const settle = (): boolean => {\n release();\n if (!controller.signal.aborted) return true;\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n return false;\n };\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true, context });\n\n let request: Promise<GetChildRowsResult>;\n try {\n request = this.dataSource.getChildRows({\n context,\n sortModel: enrichment.sortModel,\n filterModel: enrichment.filterModel,\n signal: controller.signal,\n });\n } catch (error) {\n // A non-async getChildRows() can throw synchronously — route it through .catch below.\n request = Promise.reject(error);\n }\n\n request\n .then((result) => {\n if (!settle()) return;\n const detail: DataSourceChildrenDetail = {\n rows: result.rows,\n context,\n claimed: false,\n };\n this.broadcast('datasource:children', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n })\n .catch((error: unknown) => {\n if (!settle()) return;\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_CHILD_FETCH_ERROR, `getChildRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err, context });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false, context });\n });\n }\n // #endregion\n\n // #region Public API\n\n /**\n * Set the data source for server-side loading.\n * @param dataSource - Data source implementing the getRows method (and optionally getChildRows)\n */\n setDataSource(dataSource: ServerSideDataSource): void {\n this.abortAllBlocks();\n this.dataSource = dataSource;\n this.loadedBlocks.clear();\n this.#generation++;\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n this.pendingViewportCheck = false;\n\n // Load first block with enrichment params\n const blockSize = this.config.pageSize ?? 100;\n const enrichment = this.getEnrichmentParams();\n const gridId = this.grid?.getAttribute?.('id') ?? undefined;\n const controller = new AbortController();\n this.blockControllers.set(0, controller);\n this.loadingBlocks.add(0);\n\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: true });\n\n loadBlock(dataSource, 0, blockSize, enrichment, controller.signal)\n .then((result) => {\n this.releaseBlock(0, controller);\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n this.loadedBlocks.set(0, result.rows);\n this.applyServerResult(result, 0, blockSize);\n\n const detail: DataSourceDataDetail = {\n rows: result.rows,\n totalNodeCount: result.totalNodeCount,\n startNode: 0,\n endNode: result.rows.length,\n claimed: false,\n generation: this.#generation,\n };\n this.broadcast('datasource:data', detail);\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n // Fill the rest of the viewport (plus loadThreshold) once block 0 has\n // rendered — see afterRender(). Checking here would use the empty\n // pre-data virtual window and request nothing.\n this.pendingViewportCheck = true;\n // processRows grows managedNodes in place; a new identity invalidates\n // input-ref caches (a local filter rendered while block 0 was pending).\n this.managedNodes = this.managedNodes.slice();\n this.requestRender();\n })\n .catch((error: unknown) => {\n this.releaseBlock(0, controller);\n if (controller.signal.aborted) {\n if (this.loadingBlocks.size === 0) {\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n }\n return;\n }\n const err = error instanceof Error ? error : new Error(String(error));\n errorDiagnostic(DATASOURCE_FETCH_ERROR, `getRows() failed: ${err.message}`, gridId);\n this.broadcast<DataSourceErrorDetail>('datasource:error', { error: err });\n this.broadcast<DataSourceLoadingDetail>('datasource:loading', { loading: false });\n });\n }\n\n /**\n * Refresh all data from the server.\n * Purges cache and refetches from block 0.\n */\n refresh(): void {\n if (!this.dataSource) return;\n const ds = this.dataSource;\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.loadingBlocks.clear();\n this.managedNodes = [];\n this.totalNodeCount = 0;\n this.infiniteScrollMode = false;\n // Re-trigger load via setDataSource which handles enrichment and broadcasting\n this.setDataSource(ds);\n }\n\n /**\n * Clear all cached data without refreshing.\n */\n purgeCache(): void {\n this.abortAllBlocks();\n this.loadedBlocks.clear();\n this.#generation++;\n this.managedNodes = [];\n // Drop a deferred viewport fill so the purge doesn't refetch on the next render.\n this.pendingViewportCheck = false;\n }\n\n /**\n * Get the total node count from the server.\n */\n getTotalNodeCount(): number {\n return this.totalNodeCount;\n }\n\n /**\n * Check if a specific node is loaded in the cache.\n * @param nodeIndex - Node index to check\n */\n isNodeLoaded(nodeIndex: number): boolean {\n const blockSize = this.config.pageSize ?? 100;\n const blockNum = getBlockNumber(nodeIndex, blockSize);\n return this.loadedBlocks.has(blockNum);\n }\n\n /**\n * Get the number of loaded cache blocks.\n */\n getLoadedBlockCount(): number {\n return this.loadedBlocks.size;\n }\n // #endregion\n}\n"],"mappings":"yB,2CAUA,SAAgBE,EAAyBC,GACvC,MAAO,CAAEC,WAAW,EAAMC,QAASF,EAAOG,cAAe,aAAaH,IACxE,CAqBA,SAAgBI,EAAqBC,GACnC,OACS,MAAPA,GACe,iBAARA,IACwC,IAA9CA,EAAgCJ,WACiB,iBAA1CI,EAA8BH,OAE1C,CCwIA,IAAaI,EAAy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