@katlux/toolkit 0.1.1-alpha.129 → 0.1.1-alpha.130

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 (90) hide show
  1. package/bin/add-ai-reference.mjs +85 -46
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/components/KButton/KButton.global.d.vue.ts +2 -2
  4. package/dist/runtime/components/KButton/KButton.global.vue.d.ts +2 -2
  5. package/dist/runtime/components/KButton/KButton.logic.d.ts +1 -1
  6. package/dist/runtime/components/KCheckbox/KCheckbox.global.d.vue.ts +1 -1
  7. package/dist/runtime/components/KCheckbox/KCheckbox.global.vue.d.ts +1 -1
  8. package/dist/runtime/components/KCombobox/KCombobox.global.d.vue.ts +1 -1
  9. package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +1 -1
  10. package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +1 -1
  11. package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +1 -1
  12. package/dist/runtime/components/KHourPicker/KHourPicker.global.d.vue.ts +1 -1
  13. package/dist/runtime/components/KHourPicker/KHourPicker.global.vue.d.ts +1 -1
  14. package/dist/runtime/components/KRangeSlider/KRangeSlider.global.d.vue.ts +1 -1
  15. package/dist/runtime/components/KRangeSlider/KRangeSlider.global.vue.d.ts +1 -1
  16. package/dist/runtime/components/KSlider/KSlider.global.d.vue.ts +1 -1
  17. package/dist/runtime/components/KSlider/KSlider.global.vue.d.ts +1 -1
  18. package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +1 -1
  19. package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +1 -1
  20. package/dist/skills/KATLUX_INDEX.md +40 -0
  21. package/dist/skills/katlux-components/SKILL.md +106 -0
  22. package/dist/skills/katlux-components/components/KAccordion.md +27 -0
  23. package/dist/skills/katlux-components/components/KAlert.md +22 -0
  24. package/dist/skills/katlux-components/components/KAreaChart.md +19 -0
  25. package/dist/skills/katlux-components/components/KBarChart.md +20 -0
  26. package/dist/skills/katlux-components/components/KBulkActions.md +19 -0
  27. package/dist/skills/katlux-components/components/KButton.md +12 -0
  28. package/dist/skills/katlux-components/components/KCalendar.md +17 -0
  29. package/dist/skills/katlux-components/components/KCheckbox.md +15 -0
  30. package/dist/skills/katlux-components/components/KCombobox.md +41 -0
  31. package/dist/skills/katlux-components/components/KCompositeInput.md +67 -0
  32. package/dist/skills/katlux-components/components/KContextMenu.md +20 -0
  33. package/dist/skills/katlux-components/components/KDataIterator.md +35 -0
  34. package/dist/skills/katlux-components/components/KDatatable.md +55 -0
  35. package/dist/skills/katlux-components/components/KDatePicker.md +26 -0
  36. package/dist/skills/katlux-components/components/KDropdown.md +18 -0
  37. package/dist/skills/katlux-components/components/KGantt.md +28 -0
  38. package/dist/skills/katlux-components/components/KGrid.md +17 -0
  39. package/dist/skills/katlux-components/components/KHeatMap.md +32 -0
  40. package/dist/skills/katlux-components/components/KHourSelect.md +11 -0
  41. package/dist/skills/katlux-components/components/KIcon.md +5 -0
  42. package/dist/skills/katlux-components/components/KLayout.md +34 -0
  43. package/dist/skills/katlux-components/components/KLineChart.md +18 -0
  44. package/dist/skills/katlux-components/components/KLoader.md +7 -0
  45. package/dist/skills/katlux-components/components/KMaskTextbox.md +12 -0
  46. package/dist/skills/katlux-components/components/KModal.md +22 -0
  47. package/dist/skills/katlux-components/components/KPagination.md +22 -0
  48. package/dist/skills/katlux-components/components/KPanel.md +18 -0
  49. package/dist/skills/katlux-components/components/KPieChart.md +14 -0
  50. package/dist/skills/katlux-components/components/KProductList.md +42 -0
  51. package/dist/skills/katlux-components/components/KScatterChart.md +20 -0
  52. package/dist/skills/katlux-components/components/KSlider.md +28 -0
  53. package/dist/skills/katlux-components/components/KTabs.md +31 -0
  54. package/dist/skills/katlux-components/components/KTextbox.md +15 -0
  55. package/dist/skills/katlux-components/components/KToast.md +14 -0
  56. package/dist/skills/katlux-components/components/KTooltip.md +13 -0
  57. package/dist/skills/katlux-components/components/KTree.md +45 -0
  58. package/dist/skills/katlux-components/components/KTreePicker.md +35 -0
  59. package/dist/skills/katlux-components/components/KTreeView.md +30 -0
  60. package/dist/skills/katlux-components/components/MultiTabs.md +20 -0
  61. package/dist/skills/katlux-components/components/calendar-customization.md +6 -0
  62. package/dist/skills/katlux-components/components/datatable-customization.md +14 -0
  63. package/dist/skills/katlux-components/components/directives.md +11 -0
  64. package/dist/skills/katlux-components/components/form-validation.md +125 -0
  65. package/dist/skills/katlux-components/components/tree-customization.md +9 -0
  66. package/dist/skills/katlux-components/components/useToast.md +27 -0
  67. package/dist/skills/katlux-components/components/validation-directives.md +6 -0
  68. package/dist/skills/katlux-config/SKILL.md +156 -0
  69. package/dist/skills/katlux-presets/SKILL.md +356 -0
  70. package/dist/skills/katlux-providers/SKILL.md +64 -0
  71. package/dist/skills/katlux-providers/providers/ADataProvider.md +59 -0
  72. package/dist/skills/katlux-providers/providers/CAPIFlatClientDataProvider.md +28 -0
  73. package/dist/skills/katlux-providers/providers/CAPIFlatServerDataProvider.md +20 -0
  74. package/dist/skills/katlux-providers/providers/CFlatClientDataProvider.md +11 -0
  75. package/dist/skills/katlux-providers/providers/CFlatServerDataProvider.md +58 -0
  76. package/dist/skills/katlux-providers/providers/CTreeClientDataProvider.md +14 -0
  77. package/dist/skills/katlux-providers/providers/CTreeServerDataProvider.md +5 -0
  78. package/dist/skills/katlux-providers/providers/KatluxIndexedDB.md +10 -0
  79. package/dist/skills/katlux-providers/providers/RequestProvider.md +49 -0
  80. package/dist/skills/katlux-providers/providers/RequestQueue.md +52 -0
  81. package/dist/skills/katlux-providers/providers/api-protocol.md +40 -0
  82. package/dist/skills/katlux-providers/providers/caching.md +170 -0
  83. package/dist/skills/katlux-providers/providers/composables.md +107 -0
  84. package/dist/skills/katlux-providers/providers/encryption.md +151 -0
  85. package/dist/skills/katlux-providers/providers/react-integration.md +45 -0
  86. package/dist/skills/katlux-providers/providers/testing-isolation.md +6 -0
  87. package/dist/skills/katlux-providers/providers/types.md +27 -0
  88. package/dist/skills/katlux-providers/providers/useDataProvider.md +51 -0
  89. package/dist/skills/katlux-tokens/SKILL.md +133 -0
  90. package/package.json +2 -2
@@ -0,0 +1,20 @@
1
+ ### `CAPIFlatServerDataProvider` / `CAPITreeServerDataProvider`
2
+ Handle full API integration with automatic query generation. Pagination, filtering, and sorting are executed on the server via query parameters.
3
+
4
+ - **`setAPIUrl(url: string)`**: Sets the endpoint and triggers initial load.
5
+ - **`apiUrl`**: `Ref<string>` - The active API endpoint.
6
+
7
+ | Provider Option | Type | Description |
8
+ | --- | --- | --- |
9
+ | `cacheStrategy` | `ECacheStrategy`| Persistence engine for this provider |
10
+ | `cacheLifetime` | `number` | Expiration in milliseconds |
11
+ | `refreshOnMutation`| `boolean` | Reload data after `delete`/`update` (Default: true) |
12
+
13
+ - **Methods**:
14
+ | Method | Params | Description |
15
+ | --- | --- | --- |
16
+ | `refresh(hardRefresh?)`| `boolean` | Manual trigger for reload. Cache will only be overridden if `hardRefresh` parameter is true. |
17
+ | `loadPageData(opts)` | `{ disableCache?: boolean }` | Core logic for data retrieval |
18
+ | `create(item)` | `any` | Async POST request to creation endpoint |
19
+ | `update(item)` | `any` | Async PUT request to update endpoint |
20
+ | `delete(items)` | `any[]` | Async batch deletion via endpoint |
@@ -0,0 +1,11 @@
1
+ ### `CFlatClientDataProvider`
2
+ Manages local arrays with client-side logic, extending `AEncryptedClientProvider`.
3
+ - **`setData(data: any[]): Promise<void> | void`**: Ingests dataset into provider. When encryption is enabled, eagerly encrypts designated `fields` before storing in `allData`. Plaintext never persists in `allData`. Pre-encrypted envelopes (`__encrypted: true`) pass through unchanged (idempotent). Zero overhead synchronous fast-path when encryption is disabled.
4
+ - **`setDataChunked(data: any[], options?: ISetDataChunkedOptions): Promise<void>`**: Ingests massive datasets in batches, yielding to the event loop between chunks to keep the browser UI responsive (`chunkSize`, `onProgress`, `yieldStrategy`).
5
+ - **`setEncryption(options)` / `clearEncryption()`**: Dynamically updates, rotates, or wipes cryptographic keys and cached ciphers at runtime.
6
+ - **`allData`**: `Ref<any[]>` - The complete source dataset (holds ciphertext for encrypted fields in JS memory).
7
+ - **`pageData`**: `Ref<any[]>` - Active visible page slice (lazily decrypted into plaintext on active page render). Only `pageSize` rows are plaintext in JS memory.
8
+ - **`rowMap`**: `readonly TRow[]` - Reference map array maintaining the active filtered & sorted row references. When a page is requested, a portion of this array is served directly in $O(1)$ without re-evaluating filters or sorts.
9
+ - **`updateMap()`**: Explicitly forces recalculation of the `rowMap` if items inside `allData` were modified in-place.
10
+ - **`setFilter(filter: IDataFilter | null, immediate: boolean = false)`**: Applies a structured filter. When `encryption.searchIndex: true`, performs exact match (`==`, `!=`) and substring search (`in`) on encrypted fields using HMAC-SHA256 blind index tokens and trigram sets via `CSearchIndex`. Resets to page 1.
11
+ - **`filter`**: `Ref<IDataFilter | null>` - The currently active filter configuration.
@@ -0,0 +1,58 @@
1
+ ### `CFlatServerDataProvider`
2
+ Handler-based server-side flat data provider that delegates pagination, filtering, and sorting to a custom async handler function.
3
+ - **Purpose**: Use when API requests require custom logic, GraphQL queries, non-standard endpoints, or multi-source data aggregation where standard REST URL conventions don't apply.
4
+ - **Constructor Options (`IDataProviderOptions`)**:
5
+ | Option | Type | Default | Description |
6
+ | --- | --- | --- | --- |
7
+ | `pageSize` | `number` | `10` | Default items per page |
8
+ | `currentPage` | `number` | `1` | Initial page number (1-based) |
9
+ | `filter` | `IDataFilter \| null` | `null` | Initial filter structure |
10
+ | `sortList` | `IDataSort[]` | `[]` | Initial sorting rules |
11
+ | `SSR` | `boolean` | `false` | Enable Nuxt SSR hydration via `getAsyncData` |
12
+ | `urlPageParam` | `string` | `''` | Optional URL query parameter for page syncing |
13
+ | `deduplicate` | `boolean` | `true` | Prevent duplicate concurrent fetches |
14
+
15
+ - **Reactive Properties**:
16
+ | Property | Type | Description |
17
+ | --- | --- | --- |
18
+ | `pageData` | `Ref<any[]>` | Current page slice of records |
19
+ | `rowCount` | `Ref<number>` | Total matching record count returned by the handler |
20
+ | `loading` | `Ref<boolean>` | Reactive fetching indicator |
21
+ | `currentPage` | `Ref<number>` | Current page index (triggers reload when modified) |
22
+ | `pageSize` | `Ref<number>` | Page size (triggers reload when modified) |
23
+ | `contextKey` | `Ref<string>` | Stable key used for Nuxt SSR hydration caching |
24
+
25
+ - **Methods**:
26
+ | Method | Parameters | Description |
27
+ | --- | --- | --- |
28
+ | `setContextKey(key)` | `string` | Sets a stable unique key for Nuxt SSR hydration |
29
+ | `setPageDataHandler(handler)` | `TPageDataHandler` | Sets the async fetching function and triggers initial load |
30
+ | `loadPageData(opts?)` | `{ disableCache?: boolean }` | Triggers the registered handler |
31
+ | `refresh(hardRefresh?)` | `boolean` | Re-runs the handler; overrides cache if `hardRefresh = true` |
32
+ | `setFilter(filter)` | `IDataFilter \| null` | Updates active filter criteria and resets to page 1 |
33
+ | `setSortList(sorts)` | `IDataSort[]` | Updates sort order and resets to page 1 |
34
+
35
+ - **Example Usage**:
36
+ ```ts
37
+ import { CFlatServerDataProvider } from '@katlux/providers'
38
+
39
+ const userProvider = new CFlatServerDataProvider({
40
+ pageSize: 15,
41
+ currentPage: 1,
42
+ SSR: true
43
+ })
44
+
45
+ // Set unique context key for SSR hydration
46
+ userProvider.setContextKey('admin-user-list')
47
+
48
+ // Register custom async fetcher
49
+ await userProvider.setPageDataHandler(async (currentPage, pageSize, filter, sortList) => {
50
+ const data = await $fetch('/api/users', {
51
+ params: { page: currentPage, limit: pageSize, filter, sort: sortList }
52
+ })
53
+ return {
54
+ rows: data.items,
55
+ rowCount: data.total
56
+ }
57
+ })
58
+ ```
@@ -0,0 +1,14 @@
1
+ ### `CTreeClientDataProvider`
2
+ Builds and manages reactive trees from flat arrays, extending `CFlatClientDataProvider`.
3
+ - **`setData(data: any[]): Promise<void> | void`**: Ingests hierarchical items. Encrypts sensitive fields eagerly while preserving structural keys (`idKey`, `parentKey`) in plaintext.
4
+ - **`setDataChunked(data: any[], options?)`**: Non-blocking chunked ingestion for large trees.
5
+ - **Constructor Options (`ITreeDataProviderOptions`)**:
6
+ | Option | Type | Default | Description |
7
+ | --- | --- | --- | --- |
8
+ | `idKey` | `string` | `'id'` | Unique identifier field |
9
+ | `parentKey` | `string` | `'parentId'`| Parent reference field |
10
+ | `expandedByDefault`| `boolean` | `false` | Initial node state |
11
+ | `paginateBy` | `string` | `'all'` | `'all'` (flat) or `'root'` (hierarchical) |
12
+ | `encryption` | `IProviderEncryptionOptions` | `undefined` | AES-GCM or custom cipher encryption configuration |
13
+ - **`setFilter(filter: IDataFilter | null)`**: Applies a structured filter across tree nodes client-side. When `searchIndex: true`, matches on encrypted fields using blind index search and automatically expands parent ancestors of matching child nodes. Resets to page 1.
14
+ - **`filter`**: `Ref<IDataFilter | null>` - The currently active filter configuration.
@@ -0,0 +1,5 @@
1
+ ### `CTreeServerDataProvider`
2
+ Hierarchical equivalent of `CFlatServerDataProvider`.
3
+ - **Purpose**: Tree-based server-side data provider delegating hierarchical data retrieval to a custom async handler function.
4
+ - **Tree Persistence**: Automatically syncs `expandedNodes` with the server via the handler.
5
+ - **Handler Signature**: `(page, size, filter, sort, treeParams) => Promise<IDataResult>`
@@ -0,0 +1,10 @@
1
+ ### `KatluxIndexedDB`
2
+ Centralized IndexedDB singleton (`DB_NAME = 'KatluxDB'`, `DB_VERSION = 3`) that manages shared object stores (`cache`, `queue`, `dead_letter`). Prevents IndexedDB database versioning conflicts across Katlux modules.
3
+
4
+ - **Static Methods**:
5
+ | Method | Params | Description |
6
+ | --- | --- | --- |
7
+ | `open()` | None | Opens or retrieves the shared IDBDatabase connection |
8
+ | `getStore(name, mode)`| `'cache'\|'queue'\|'dead_letter', 'readonly'\|'readwrite'` | Returns an IDBObjectStore for reading or writing |
9
+ | `clearStore(name)` | `'cache'\|'queue'\|'dead_letter'` | Clears all records in the specified object store |
10
+ | `close()` | None | Closes the open database connection |
@@ -0,0 +1,49 @@
1
+ ### `RequestProvider`
2
+ The core engine for all HTTP communication, supporting deduplication, tag-based registry auto-refreshes, offline mutation queuing, and caching.
3
+ - **Methods**:
4
+ | Method | Params | Description |
5
+ | --- | --- | --- |
6
+ | `registerRequest<T>(url, opts)` | `string, IRequestOptions` | Executes a request with deduplication, offline enqueuing (for mutations with `queue: true`), or tag-based registry notifications |
7
+ | `setCacheProvider(provider)` | `ACacheProvider \| ECacheStrategy` | Configures global caching strategy |
8
+ | `setCacheLifetime(ms)` | `number` | Sets default global expiration (milliseconds) |
9
+ | `setDeduplicate(bool)` | `boolean` | Toggle request deduplication |
10
+ | `onDataReceived(cb)` | `(data: any, generation?: number) => void` | Registers a callback triggered when data is successfully received (passes request generation if available) |
11
+ | `refresh(hardRefresh)` | `boolean` | Re-runs the last request. Cache will only be overridden if `hardRefresh` parameter is true. |
12
+
13
+ - **Constructor**: `new RequestProvider(provider?, lifetime?, deduplicate?, tags?)`
14
+ - `provider`: `ACacheProvider | ECacheStrategy` — optional default cache backend
15
+ - `lifetime`: `number` — optional default cache lifetime in ms
16
+ - `deduplicate`: `boolean` — optional deduplication toggle (default `true`)
17
+ - `tags`: `string[]` — optional tag array for subscription to `RequestProviderRegistry`
18
+
19
+ - **`IRequestOptions` Properties**:
20
+ | Property | Type | Description |
21
+ | --- | --- | --- |
22
+ | `method` | `string` | HTTP method (`'GET'`, `'POST'`, `'PUT'`, `'DELETE'`, `'PATCH'`. Default: `'GET'`) |
23
+ | `body` | `any` | Request body data |
24
+ | `query` | `Record<string, any>` | URL query parameters |
25
+ | `headers` | `Record<string, string>` | Custom HTTP headers |
26
+ | `cacheStrategy` | `ECacheStrategy` | Override global strategy for this request |
27
+ | `lifetime` | `number` | Override global expiration for this request |
28
+ | `key` | `string` | Custom unique key for caching/deduplication |
29
+ | `cacheKey` | `string` | Namespace/context key for shared cache storage |
30
+ | `deduplicate` | `boolean` | Override global deduplication setting |
31
+ | `disableCache` | `boolean` | Explicitly override cache for this request |
32
+ | `tags` | `string[]` | Associated tags for invalidation / auto-refresh upon mutation |
33
+ | `queue` | `boolean` | When true (for non-GET requests), enqueues the mutation into `RequestQueue` instead of dispatching immediately |
34
+ | `label` | `string` | Human-readable description for queued mutation display in UI |
35
+ | `nuxtApp` | `any` | Nuxt app instance — enables SSR cookie forwarding via h3 |
36
+ | `_generation` | `number` | Internal request generation counter to discard stale responses |
37
+
38
+ ### `RequestProviderRegistry`
39
+ Framework-agnostic static registry mapping active `RequestProvider` instances to tag arrays. When mutations complete (or offline queues flush), `RequestProviderRegistry` automatically triggers `refresh(true)` on all matching registered GET providers.
40
+
41
+ - **Static Methods**:
42
+ | Method | Params | Description |
43
+ | --- | --- | --- |
44
+ | `register(provider, tags)` | `RequestProvider, string[]` | Subscribes a provider instance to the specified tags |
45
+ | `unregister(provider)` | `RequestProvider` | Removes a provider instance from the registry |
46
+ | `notifyMutation(tags)` | `string[]` | Refreshes all GET providers registered under any of the specified tags (deduplicated) |
47
+ | `refreshByTag(tag)` | `string` | Refreshes all GET providers registered under the given tag |
48
+ | `getEntries()` | None | Returns all active `{ provider, tags }` registry entries |
49
+ | `clear()` | None | Clears all registered providers |
@@ -0,0 +1,52 @@
1
+ ### `RequestQueue` (Offline PWA Queue)
2
+ Static persistent queue manager for queuing mutations offline and flushing them when connectivity is restored.
3
+
4
+ - **Storage Options (`EQueueStorage`)**: `IndexedDB` (default, stored under `KatluxDB`), `LocalStorage`, `Memory`. Automatically falls back if a backend is unavailable.
5
+ - **Native State**:
6
+ - `RequestQueue.queue`: `IQueuedOperation[]` — Pure native array of pending queued mutations.
7
+ - `RequestQueue.deadLetterQueue`: `IDeadLetterItem[]` — Pure native array of permanently failed operations (4xx/5xx errors).
8
+ - `RequestQueue.isFlushing`: `boolean` — Boolean flag indicating active flush state.
9
+ - `RequestQueue.subscribe(listener: () => void): () => void` — Observer subscription hook.
10
+ - **Vue 3 Integration (`useRequestQueue` composable from `@katlux/toolkit`)**:
11
+ ```typescript
12
+ import { useRequestQueue } from '#toolkit/composables/useRequestQueue'
13
+
14
+ const {
15
+ queue, // Ref<IQueuedOperation[]>
16
+ deadLetterQueue, // Ref<IDeadLetterItem[]>
17
+ isFlushing, // Ref<boolean>
18
+ enqueue,
19
+ flushAll,
20
+ flushOne,
21
+ retryOne,
22
+ discard,
23
+ init,
24
+ setStorageBackend
25
+ } = useRequestQueue()
26
+ ```
27
+ - **Flushing Behavior**:
28
+ - Processed in **FIFO order** (first in, first out).
29
+ - **Stop-on-first-error**: Execution halts immediately if an item fails to preserve queue dependency integrity.
30
+ - **Dead-letter handling**: Server errors (4xx/5xx) move the failed operation to `deadLetterQueue` with `failedAt`, `lastError`, and `httpStatus`.
31
+ - **Dead-letter capacity guard**: When `deadLetterQueue` reaches `MAX_DEAD_LETTER_SIZE`, subsequent additions halt to prevent silent data loss, emitting to `onError` without unhandled promise rejections.
32
+ - **Network errors**: If fetch fails due to connectivity (no HTTP response), the item remains in `queue` for subsequent retry.
33
+ - **Partial refresh**: Successfully processed item tags trigger `RequestProviderRegistry.notifyMutation()` immediately.
34
+ - **Static Methods**:
35
+ | Method | Params | Description |
36
+ | --- | --- | --- |
37
+ | `init()` | None | Initializes queue storage backend and loads persisted state |
38
+ | `setStorageBackend(type)` | `EQueueStorage` | Sets storage backend (`IndexedDB`, `LocalStorage`, `Memory`) |
39
+ | `enqueue(item)` | `IQueuedOperationInput` | Adds a mutation item to the queue |
40
+ | `flushAll(options?)` | `{ tag?: string }` | Flushes queued operations in FIFO order |
41
+ | `flushOne(id)` | `string` | Dispatches a specific queued item by ID |
42
+ | `retryOne(id)` | `string` | Moves a dead-letter item back to the FRONT of the pending queue |
43
+ | `discard(id)` | `string` | Permanently removes an item from `queue` or `deadLetterQueue` |
44
+ | `reorder(ids)` | `string[]` | Reorders pending operations by ID array |
45
+ | `setMaxPayloadSize(bytes)` | `number` | Sets maximum allowed mutation payload size (default: 5MB) |
46
+ | `setMaxQueueSize(limit)` | `number` | Sets maximum pending queue capacity with FIFO eviction (default: 500) |
47
+ | `setMaxDeadLetterSize(limit)` | `number` | Sets maximum dead-letter queue capacity before halting (default: 200) |
48
+ | `onDeadLetter(cb)` | `(item, err) => void` | Event listener fired when an item enters dead-letter |
49
+ | `onFlushComplete(cb)` | `(succeededTags) => void` | Event listener fired when a flush finishes with successes |
50
+ | `onNetworkError(cb)` | `(err) => void` | Event listener fired when a flush halts due to offline network error |
51
+ | `onError(cb)` | `(err) => void` | Event listener fired on fatal queue or capacity errors |
52
+ | `onQueueFatalError(cb)` | `(err) => void` | Alias for `onError` |
@@ -0,0 +1,40 @@
1
+ ## 3.8. API Communication Protocol (Server-Side)
2
+ When using `CAPIFlatServerDataProvider` or `CAPITreeServerDataProvider`, the requested URL will include the following query string parameters.
3
+
4
+ ### Standard Parameters (Flat & Tree)
5
+ | Parameter | Type | Description |
6
+ | --- | --- | --- |
7
+ | `pageNumber` | `number` | Current 1-based page index |
8
+ | `pageSize` | `number` | Items per page (0 = no pagination) |
9
+ | `filter` | `JSON` | Serialized `IDataFilter` object |
10
+ | `sortList` | `JSON` | Serialized `IDataSort[]` array |
11
+
12
+ ### Tree-Specific Parameters
13
+ | Parameter | Type | Description |
14
+ | --- | --- | --- |
15
+ | `expandedNodes` | `JSON` | Stringified array of expanded node IDs |
16
+ | `parentKey` | `string` | Field key for ancestor reference |
17
+ | `idKey` | `string` | Field key for unique identifier |
18
+ | `paginateBy` | `string` | `'all'` or `'root'` |
19
+ | `expandedByDefault`| `boolean` | Initial expansion state |
20
+
21
+ ### Filter JSON Structure Example
22
+ ```json
23
+ {
24
+ "operator": "in",
25
+ "field": { "product_name": "mont" },
26
+ "active": true
27
+ }
28
+ ```
29
+
30
+ ### Complex Filter (OR) Example
31
+ ```json
32
+ {
33
+ "operator": "or",
34
+ "field": [
35
+ { "operator": "==", "field": { "status": "active" }, "active": true },
36
+ { "operator": "==", "field": { "priority": "high" }, "active": true }
37
+ ],
38
+ "active": true
39
+ }
40
+ ```
@@ -0,0 +1,170 @@
1
+ ### `CacheProvider` (Interface: `ACacheProvider`)
2
+ Standard interface for persistence strategies. **Note**: `ACacheProvider` is an abstract class and cannot be instantiated with `new`.
3
+
4
+ - **`CacheProviderFactory`**: The primary way to obtain a cache provider instance. Unused cache drivers are dynamically loaded and tree-shaken from initial application bundles.
5
+ - `CacheProviderFactory.getProvider(strategy: ECacheStrategy | string): Promise<ACacheProvider | null>`: Asynchronously loads and returns the singleton instance for the specified strategy.
6
+ - `CacheProviderFactory.getProviderSync(strategy: ECacheStrategy | string): ACacheProvider | undefined`: Synchronously returns the singleton instance if already loaded.
7
+ - `CacheProviderFactory.registerDriver(strategy: string, loaderOrClass)`: Registers a custom cache strategy driver or pre-loaded class.
8
+ - `CacheProviderFactory.clearInstances()`: Clears the singleton cache.
9
+ - **Direct Access**: Individual providers (e.g., `CMemoryCache`, `CLocalStorageCache`) can also be accessed via their static `getInstance()` method.
10
+
11
+ > [!NOTE]
12
+ > All `CacheProvider` methods are asynchronous and return a **Promise**. This is required to support non-blocking storage engines like **IndexedDB**.
13
+
14
+ - **Supported Strategies & Execution Scopes**:
15
+ - **Server-Side Caches (Stateful Node.js Runtimes)**:
16
+ - `Application`: Global server-level cache (`CApplicationCache`). Shared across all visitors on the Node.js server (e.g. homepage featured product lists). Never hydrated to the client. Note: In-memory server caches are not supported on stateless/serverless runtimes (e.g. Cloudflare Workers).
17
+ - `ServerSession`: Per-session server-side in-memory cache (`CServerSessionCache`). Emulates traditional server sessions (PHP-style) keyed by session ID. Confined strictly to the server — all methods are server-only with zero client execution paths. Never hydrated to the client. Uses lazy TTL eviction on `get()` and bounded LRU eviction (`MAX_SERVER_SESSIONS = 5000`) on `set()` — no background timers. Note: Not supported on stateless/serverless runtimes.
18
+ - **Client-Side Caches (Browser Execution)**:
19
+ - `BrowserSession`: Tab-lifetime browser cache (`CBrowserSessionCache`). Backed by `window.sessionStorage` with prefix `'bscache:'`. On the server during SSR, `set()` writes only to the SSR context payload; on first client-side `get()` miss, the entry is promoted from the payload into `sessionStorage` (hydration). All other server-side methods are no-ops.
20
+ - `Memory`: In-memory storage (`CMemoryCache`). Kept in client memory; cleared on page reload. On the server, strictly scoped to the per-request SSR payload for client hydration.
21
+ - `LocalStorage`: Browser `localStorage` (`CLocalStorageCache`). Persistent across browser restarts and tabs.
22
+ - `IndexedDB`: Large-scale browser storage (`CIndexedDBCache`, managed via `KatluxIndexedDB`).
23
+ - `Cookie`: Browser cookies with optional server-side read/write via `h3` (`CCookieCache`). Configurable `sameSite`, `secure` (auto-detected), `httpOnly`, `path` — see *Cookie Security Options* below.
24
+ - **Methods (All return `Promise`)**:
25
+ | Method | Params | Description |
26
+ | --- | --- | --- |
27
+ | `get<T>(key)` | `string` | Retrieves cached value |
28
+ | `set<T>(key, val, life)`| `string, any, number`| Persists value with lifetime (ms) |
29
+ | `remove(key)` | `string` | Evicts specific entry |
30
+ | `removeByPrefix(pre)`| `string` | Bulk eviction (e.g., by resource URL) |
31
+ | `getRemainingTime(key)`| `string` | Returns remaining TTL in ms |
32
+ | `cleanupExpired()` | None | Purges stale entries |
33
+ | `getKeyList()` | None | Returns all active cache keys |
34
+
35
+ #### Cookie Security Options (`CCookieCache`)
36
+ Cookie flags are plain constructor options on the cache itself; there is no separate session layer:
37
+
38
+ ```typescript
39
+ import { CCookieCache } from '@katlux/providers'
40
+
41
+ const cache = new CCookieCache({ sameSite: 'strict', path: '/app' })
42
+ ```
43
+
44
+ | Option | Default | Notes |
45
+ | --- | --- | --- |
46
+ | `sameSite` | `'lax'` | `'strict' \| 'lax' \| 'none'`. First line of CSRF defense for cookie-authenticated requests. |
47
+ | `secure` | auto | Follows the request protocol (https => `Secure`). On the server it uses h3 `getRequestProtocol` (honours `x-forwarded-proto`); on the client `location.protocol`. Set `true`/`false` to force. |
48
+ | `httpOnly` | `true` | **Server-written cookies only.** Browsers do not let `document.cookie` set `HttpOnly`, so client writes ignore it. Because of this, a cookie written on the server is not readable by `CCookieCache.get()` in the browser. |
49
+ | `path` | `'/'` | Cookie path scope. |
50
+
51
+ > [!WARNING]
52
+ > Do not keep auth tokens in `BrowserSession`, `LocalStorage`, `Memory`, or a client-written `Cookie`: any XSS can read them. Keep credentials in a server-set `HttpOnly` cookie. The cache strategies are for **application data** (query results, table pages, chart series), not identity. Cookies are also capped at ~4 KB and are sent on every request, so `CCookieCache` skips oversized writes.
53
+
54
+ > [!NOTE]
55
+ > CSRF tokens and Content Security Policy headers are application/server concerns and are intentionally not part of `@katlux/providers`. See the *Security* section in the `katlux-config` skill.
56
+
57
+ #### Registering a Custom Cache Strategy
58
+
59
+ To create a custom caching backend (e.g. Redis, WebWorker, LRU cache, or multi-tab BroadcastChannel), follow these three steps:
60
+
61
+ **Step 1 — Subclass `ACacheProvider`**:
62
+ Implement all abstract methods and provide a static `getInstance()` method.
63
+
64
+ ```typescript
65
+ import { ACacheProvider, type ICacheEntry } from '@katlux/providers'
66
+
67
+ export class CMyCustomCache extends ACacheProvider {
68
+ private static instance: CMyCustomCache | null = null
69
+ private storage = new Map<string, ICacheEntry<any>>()
70
+
71
+ public static getInstance(): CMyCustomCache {
72
+ if (!this.instance) {
73
+ this.instance = new CMyCustomCache()
74
+ }
75
+ return this.instance
76
+ }
77
+
78
+ async getKeyList(nuxtApp?: any): Promise<string[]> {
79
+ return Array.from(this.storage.keys())
80
+ }
81
+
82
+ async get<T>(key: string, nuxtApp?: any): Promise<T | null> {
83
+ const entry = this.storage.get(key)
84
+ if (!entry) return null
85
+ if (Date.now() > entry.timestamp + entry.lifetime) {
86
+ this.storage.delete(key)
87
+ return null
88
+ }
89
+ return entry.data as T
90
+ }
91
+
92
+ async set<T>(key: string, data: T, lifetime: number, nuxtApp?: any): Promise<void> {
93
+ this.storage.set(key, { data, timestamp: Date.now(), lifetime })
94
+ }
95
+
96
+ async remove(key: string, nuxtApp?: any): Promise<void> {
97
+ this.storage.delete(key)
98
+ }
99
+
100
+ async removeByPrefix(prefix: string, nuxtApp?: any): Promise<void> {
101
+ for (const key of this.storage.keys()) {
102
+ if (key.startsWith(prefix)) this.storage.delete(key)
103
+ }
104
+ }
105
+
106
+ async getRemainingTime(key: string, nuxtApp?: any): Promise<number | null> {
107
+ const entry = this.storage.get(key)
108
+ if (!entry) return null
109
+ const remaining = (entry.timestamp + entry.lifetime) - Date.now()
110
+ return remaining > 0 ? remaining : null
111
+ }
112
+
113
+ async cleanupExpired(): Promise<void> {
114
+ const now = Date.now()
115
+ for (const [key, entry] of this.storage.entries()) {
116
+ if (now > entry.timestamp + entry.lifetime) {
117
+ this.storage.delete(key)
118
+ }
119
+ }
120
+ }
121
+ }
122
+ ```
123
+
124
+ **Step 2 — Register with `CacheProviderFactory`**:
125
+ You can register custom drivers at app bootstrap or inside a Nuxt plugin.
126
+
127
+ - **Option A (Recommended for code-splitting)**: Register an async dynamic loader:
128
+ ```typescript
129
+ // plugins/custom-cache.ts
130
+ import { defineNuxtPlugin } from '#app'
131
+ import { CacheProviderFactory } from '@katlux/providers'
132
+
133
+ export default defineNuxtPlugin(() => {
134
+ CacheProviderFactory.registerDriver('MyCustom', async () => {
135
+ const { CMyCustomCache } = await import('~/services/cache/CMyCustomCache')
136
+ return CMyCustomCache
137
+ })
138
+ })
139
+ ```
140
+
141
+ - **Option B (Synchronous pre-loaded driver)**: Register the class directly:
142
+ ```typescript
143
+ import { CacheProviderFactory } from '@katlux/providers'
144
+ import { CMyCustomCache } from '~/services/cache/CMyCustomCache'
145
+
146
+ CacheProviderFactory.registerDriver('MyCustom', CMyCustomCache)
147
+ ```
148
+
149
+ **Step 3 — Consume the Strategy**:
150
+ Pass the strategy name to any provider or fetch directly via `CacheProviderFactory`:
151
+
152
+ ```typescript
153
+ // 1. With RequestProvider:
154
+ const request = new RequestProvider('MyCustom' as any, 60_000)
155
+ // or dynamically:
156
+ request.setCacheProvider('MyCustom' as any)
157
+
158
+ // 2. With Data Providers:
159
+ const dataProvider = new CAPIFlatServerDataProvider({
160
+ pageSize: 20,
161
+ cacheStrategy: 'MyCustom' as any,
162
+ cacheLifetime: 300_000
163
+ })
164
+
165
+ // 3. Directly via CacheProviderFactory:
166
+ const cache = await CacheProviderFactory.getProvider('MyCustom')
167
+ await cache?.set('my-key', { sample: 123 }, 60_000)
168
+ ```
169
+
170
+ ---
@@ -0,0 +1,107 @@
1
+ ## 3.7. Auto-Imported Composables
2
+
3
+ These composables are globally available in any Nuxt app that installs `@katlux/toolkit`. No import needed.
4
+
5
+ ### `useRequestProvider(provider, tags)`
6
+ Vue composable wrapper that registers a `RequestProvider` or `ADataProvider` with `RequestProviderRegistry` under the given tags. Automatically unregisters on component `onUnmounted` to prevent memory leaks in SPAs.
7
+
8
+ ```typescript
9
+ // Registers provider with 'invoices' tag, automatically unregisters on unmount
10
+ const provider = useRequestProvider(myInvoiceProvider, ['invoices'])
11
+ ```
12
+
13
+ ### `useUnregisterProvider(provider)`
14
+ Explicitly unregisters a provider instance from `RequestProviderRegistry`. Useful for mid-lifecycle opt-outs or `<keep-alive>` component deactivation hooks (`onDeactivated`).
15
+
16
+ ```typescript
17
+ onDeactivated(() => useUnregisterProvider(provider))
18
+ onActivated(() => RequestProviderRegistry.register(provider, ['invoices']))
19
+ ```
20
+
21
+ ### `useKatluxContext()`
22
+ Composable that returns the request-scoped H3 event context during SSR (`{ event }`), or `null` in client environments. Pass to server data providers (or `RequestProvider`) to ensure per-request in-flight deduplication isolation and prevent cookie / auth leaking across concurrent SSR user requests.
23
+
24
+ ```typescript
25
+ // Provides SSR request isolation
26
+ const context = useKatluxContext()
27
+ const provider = new CAPIFlatServerDataProvider({ context })
28
+ ```
29
+
30
+ ### `useFilterLogic()`
31
+ The same filter engine used internally by client-side data providers. Useful for custom filtering logic.
32
+ ```typescript
33
+ const { evaluateFilter, filterData, filterTreeData } = useFilterLogic()
34
+
35
+ // Filter a flat array
36
+ const { results } = filterData(myArray, myFilter)
37
+
38
+ // Filter a flat array representing a tree
39
+ const { results, expandedNodes } = filterData(myArray, myFilter, {
40
+ treeOptions: { idKey: 'id', parentKey: 'parentId' }
41
+ })
42
+ ```
43
+
44
+ ### `useSortLogic()`
45
+ The same stable merge-sort engine used internally by client-side providers.
46
+ ```typescript
47
+ const { sortData } = useSortLogic()
48
+ const sorted = sortData([{ field: 'name', direction: 'asc' }], myArray)
49
+ ```
50
+
51
+ ### `useDebounce(callback, delay)`
52
+ Returns a debounced version of any function.
53
+ ```typescript
54
+ const debouncedSearch = useDebounce((text: string) => { /* ... */ }, 300)
55
+ ```
56
+
57
+ ### `useRemainingTime()`
58
+ Returns remaining TTL for a cache key. See `ACacheProvider.getRemainingTime(key)`.
59
+
60
+ ### `useTemplate(options)`
61
+ Reactive template resolution for components.
62
+ ```typescript
63
+ const { metadata, isCustomTemplate, templateName, refreshTemplate } = useTemplate({
64
+ componentName: 'KButton',
65
+ fallbackToDefault: true
66
+ })
67
+ ```
68
+
69
+ ### `usePresetComponent(name, defaultComponent)`
70
+ Resolves which preset component implementation to render for a given component name across the active preset cascade. Used internally by all global components.
71
+ - **Fast-path**: Evaluates `'default'` preset synchronously with zero glob scanning or iterations.
72
+ - **Instance Caching**: Caches `defineAsyncComponent` instances in a module-level `Map` to preserve component identity and avoid re-wrapping across re-renders.
73
+ - **Synchronous & Asynchronous Support**: Accepts both pre-bundled Vue component objects (zero async suspense boundary overhead) and dynamic loader functions registered via `registerPresetComponents`.
74
+
75
+ ### `useKatluxI18n()`
76
+ Resilient, multi-tier internationalization composable providing the `$t` translation function for Katlux components and consumer applications.
77
+ - **Lookup Priority Order**:
78
+ 1. `nuxtApp.$t` or `nuxtApp.$i18n.t` (consumer's `@nuxtjs/i18n` or `vue-i18n` instance)
79
+ 2. Language-specific overrides: `appConfig.katluxToolkit.translations[locale][key]`
80
+ 3. Flat custom overrides: `appConfig.katluxToolkit.translations[key]`
81
+ 4. Built-in localized dictionaries (supports 23+ locales: `en`, `es`, `fr`, `de`, `pt`, `it`, `nl`, `pl`, `ru`, `uk`, `zh`, `ja`, `ko`, `hi`, `bn`, `id`, `vi`, `th`, `sv`, `da`, `fi`, `cs`, `el`, `tr`)
82
+ 5. Built-in English default dictionary fallback
83
+ 6. Raw key fallback
84
+ - **Usage**:
85
+ ```typescript
86
+ const { t } = useKatluxI18n()
87
+ const greeting = t('Welcome back, {name}!', { name: 'Alex' })
88
+ ```
89
+
90
+ ### `useRequestQueue()`
91
+ Vue composable interface for the offline mutation queue manager (`RequestQueue`). Enables queuing API mutations while offline and automatically flushing them when connectivity is restored.
92
+ - **Reactive State & Methods**:
93
+ ```typescript
94
+ const {
95
+ queue, // Ref<IQueuedOperation[]> - Pending queued mutations
96
+ deadLetterQueue, // Ref<IDeadLetterItem[]> - Permanently failed operations
97
+ isFlushing, // Ref<boolean> - True while active flush is in progress
98
+ enqueue, // (item: IQueuedOperationInput) => Promise<string>
99
+ flushAll, // (options?: { tag?: string }) => Promise<void>
100
+ flushOne, // (id: string) => Promise<void>
101
+ retryOne, // (id: string) => Promise<void>
102
+ discard, // (id: string) => Promise<void>
103
+ setStorageBackend// (type: EQueueStorage) => void
104
+ } = useRequestQueue()
105
+ ```
106
+
107
+ ---