@kivacore/app-utils 0.0.0 → 0.22.1

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 (41) hide show
  1. package/README.md +1515 -1
  2. package/dist/index.d.ts +82 -0
  3. package/dist/index.js +2304 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.native.js +4695 -0
  6. package/dist/index.native.js.map +1 -0
  7. package/dist/query.d.ts +54 -0
  8. package/dist/query.js +269 -0
  9. package/dist/query.js.map +1 -0
  10. package/dist/types-GNkXRpu4.d.ts +754 -0
  11. package/package.json +57 -3
  12. package/src/app-config-client.ts +48 -0
  13. package/src/async-each-helper.ts +98 -0
  14. package/src/brand-client.ts +80 -0
  15. package/src/data-form-client.ts +85 -0
  16. package/src/data-source-client.ts +298 -0
  17. package/src/data-source-queries.ts +149 -0
  18. package/src/data-view-client.ts +92 -0
  19. package/src/date-utils.test.ts +48 -0
  20. package/src/date-utils.ts +146 -0
  21. package/src/envelope-interceptor.ts +65 -0
  22. package/src/get-tenant-preferences.test.ts +42 -0
  23. package/src/get-tenant-preferences.ts +30 -0
  24. package/src/handlebars-async-helpers.d.ts +12 -0
  25. package/src/index.native.ts +9 -0
  26. package/src/index.ts +88 -0
  27. package/src/inventory-client.ts +725 -0
  28. package/src/jsonata-helpers.ts +545 -0
  29. package/src/number-utils.ts +305 -0
  30. package/src/php-date-formatter.d.ts +8 -0
  31. package/src/query.ts +5 -0
  32. package/src/shims/stream.ts +11 -0
  33. package/src/template-engine.test.ts +47 -0
  34. package/src/template-engine.ts +298 -0
  35. package/src/types.ts +871 -0
  36. package/src/unwrap-envelope.ts +51 -0
  37. package/src/user-app-config-client.ts +44 -0
  38. package/src/user-identity-client.ts +21 -0
  39. package/tsconfig.json +9 -0
  40. package/tsup.config.ts +71 -0
  41. package/vitest.config.mts +13 -0
package/README.md CHANGED
@@ -1,3 +1,1517 @@
1
1
  # @kivacore/app-utils
2
2
 
3
- Placeholder. Install the latest version.
3
+ Framework-agnostic utility functions for frontend applications using Docyrus as backend. Provides date/number formatting, template compilation (Handlebars + JSONata), and a comprehensive set of expression helpers — all configured from tenant preferences.
4
+
5
+ ## Features
6
+
7
+ - **Tenant Preferences**: Fetch tenant configuration from the Docyrus API
8
+ - **Date Formatting**: PHP-style date formatting with timezone support (`Y-m-d`, `H:i:s`, etc.)
9
+ - **Number Formatting**: Locale-aware number formatting with custom separators and precision
10
+ - **Number to Words**: Convert numbers to words in Turkish and English with currency labels
11
+ - **Duration Formatting**: Format seconds as `HH:MM`, decimal hours, or human-readable words
12
+ - **App Config**: Get, upsert, and delete a per-app JSON configuration (1:1 per app)
13
+ - **User App Config**: Get, upsert, and delete a per-user JSON configuration scoped to an app (1:1 per user per app)
14
+ - **Data Views**: CRUD for saved data source view configurations (columns, filters, sort, color rules)
15
+ - **Data Forms**: CRUD for dynamic form designs attached to a data source (layout JSON, title, icon, color, default flag, soft-archive)
16
+ - **Data Source Metadata**: Read data source metadata across apps, by app, by ID, or by slug with optional expansions like `fields`, plus field & enum-option helpers (`getFields`, `getFieldById`, `getFieldBySlug`, `getEnumsByFieldId`, `getEnumById`) and relation helpers for parent/child data-source & field selectors (`listParentDataSources`, `listChildDataSources`, `listParentDataSourceFields`, `listChildDataSourceFields`)
17
+ - **Inventory Cache**: Tenant-wide cache of apps, data sources (with embedded views/forms/fields), users, brands, tenant preferences, and per-app config — with request de-dup, TTL, direct cache patches shared across all inventory-backed clients, a `load()` warm-up that emits progress events for a post-sign-in progress bar, and **optional `localStorage` / `sessionStorage` persistence** so the cache survives page reloads
18
+ - **Brands**: CRUD for tenant brand records (colors, typography, spacing, logos, voice & messaging, slide / chart styling), plus a website-scrape RPC that fills the brand from a configured URL
19
+ - **User Identity**: Persist decoded OIDC ID-token payloads from Microsoft (Graph) and Google after a frontend OAuth2 flow — writes both `tenant_user.identity_*` and the matching `tenant_connection_user` row
20
+ - **TanStack Query Integration** (optional, via `@kivacore/app-utils/query`): Prebuilt `queryOptions` factories and a query-key registry for data source metadata, with reactive caching and per-resource invalidation helpers
21
+ - **Envelope Unwrapping**: `envelopeUnwrapInterceptor` (a `RestApiClient` interceptor) and `unwrapEnvelope` (a per-call helper) for handling Docyrus' `{ success, data }` API envelope — both shape-strict so domain payloads with their own `data` column stay safe
22
+ - **Template Engine**: Handlebars compilation with async support and inline JSONata formulas
23
+ - **Formula Evaluation**: JSONata expression evaluation with 70+ built-in helper functions
24
+ - **JSONata Helpers**: Date arithmetic (date-fns), string manipulation, number formatting, equality checks, and more
25
+ - **TypeScript**: Full type definitions included
26
+ - **Framework-Agnostic**: No Vue, React, or Angular dependency — works everywhere
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ npm install @kivacore/app-utils
32
+ ```
33
+
34
+ ```bash
35
+ pnpm add @kivacore/app-utils
36
+ ```
37
+
38
+ ### Peer Dependencies
39
+
40
+ | Package | Version | Required |
41
+ |---------|---------|----------|
42
+ | `@kivacore/api-client` | >= 0.1.0 | Yes (for `getTenantPreferences`) |
43
+ | `handlebars` | >= 4.7.0 | Yes (for template engine) |
44
+ | `jsonata` | >= 2.0.0 | Yes (for formula evaluation) |
45
+ | `date-fns` | >= 3.0.0 | Yes (for JSONata date helpers) |
46
+ | `@tanstack/query-core` | >= 5.17.0 | Optional (only for `@kivacore/app-utils/query`) |
47
+
48
+ ### React Native
49
+
50
+ The package ships a dedicated React Native build (`dist/index.native.js`), picked up automatically by Metro through the `react-native` export condition — no Metro config is needed. It exposes the same API as the web build; `handlebars-async-helpers` and `jsonpath-plus` are bundled into it with their Node-only imports (`stream`, `vm`) redirected to React Native–safe code, so an Expo / React Native app can import `@kivacore/app-utils` directly.
51
+
52
+ ## Quick Start
53
+
54
+ ```ts
55
+ import {
56
+ getTenantPreferences,
57
+ createDateUtils,
58
+ createNumberUtils,
59
+ createTemplateEngine,
60
+ createDataSourceClient
61
+ } from '@kivacore/app-utils';
62
+
63
+ // 1. Fetch tenant preferences
64
+ const preferences = await getTenantPreferences(apiClient);
65
+
66
+ // 2. Create utility instances
67
+ const dateUtils = createDateUtils({
68
+ preferences,
69
+ userTimezone: currentUser.timeZone?.id // e.g. 'Europe/Istanbul'
70
+ });
71
+
72
+ const numberUtils = createNumberUtils({ preferences });
73
+ const dataSources = createDataSourceClient(apiClient);
74
+
75
+ // 3. Create template engine (optional)
76
+ const engine = createTemplateEngine({
77
+ dateUtils,
78
+ numberUtils,
79
+ user: currentUser,
80
+ extraJsonataBindings: { hasRole }
81
+ });
82
+
83
+ // 4. Use utilities
84
+ dateUtils.formatDate('2024-01-15'); // '15.01.2024' (tenant format)
85
+ numberUtils.formatNumber(1234.5); // '1.234,50' (tenant locale)
86
+ await engine.compileFormula('$sum(items.price)', data);
87
+
88
+ // 5. Read app and data source metadata
89
+ const apps = await dataSources.listApps();
90
+ const sources = await dataSources.list({ expand: 'fields' });
91
+ const contacts = await dataSources.getBySlug('crm', 'contacts', {
92
+ expand: 'fields'
93
+ });
94
+
95
+ // 6. Use metadata
96
+ const appSlugs = apps.map(app => app.slug);
97
+ const fieldSlugs = contacts.fields?.map(field => field.slug) ?? [];
98
+ const requiredFields = contacts.fields?.filter(field => field.required) ?? [];
99
+ ```
100
+
101
+ ## Envelope handling
102
+
103
+ Docyrus REST endpoints wrap their payload in a `{ success, data }` envelope (optionally with `meta` for pagination, or `error` / `message` for controller-level errors). `@kivacore/app-utils` provides two ways to handle that — both are tolerant of pre-stripped envelopes (i.e. idempotent), and both refuse to falsely unwrap domain payloads that carry their own `data` field (`AppConfig`, `UserAppConfig`, records with a `data` column).
104
+
105
+ ### `envelopeUnwrapInterceptor` — global, conservative
106
+
107
+ A `RestApiClient` response interceptor. After it runs, `client.get/post/put/delete` returns the inner payload directly (so generated TanStack DB collections, hand-written calls, and app-utils clients all see bare values). **Required** when using `@kivacore/tanstack-db-generator` collections — the generator emits methods that don't read `.data` themselves.
108
+
109
+ ```ts
110
+ import { RestApiClient } from '@kivacore/api-client';
111
+ import { envelopeUnwrapInterceptor } from '@kivacore/app-utils';
112
+
113
+ const client = new RestApiClient({ baseURL: 'https://api.example.com' });
114
+ client.addInterceptor(envelopeUnwrapInterceptor);
115
+
116
+ // Now plain envelopes unwrap automatically:
117
+ const views = await client.get<DataView[]>('/v1/apps/crm/data-sources/contacts/views');
118
+ // ^ DataView[] (from { success, data: [...] })
119
+ ```
120
+
121
+ It's deliberately **shape-strict and lossless** — it strips only when the envelope's only top-level keys are `data` and optionally `success`. Envelopes that carry sidecar information are left intact so callers can read them:
122
+
123
+ | Response shape | Behaviour | Why |
124
+ |---|---|---|
125
+ | `{ data }` | unwrap → `data` | Bare envelope. |
126
+ | `{ success, data }` | unwrap → `data` | Most endpoints. |
127
+ | `{ data, meta }` / `{ success, data, meta }` | left alone | Paginated lists — `meta.count`/`meta.total` needed by data grids. |
128
+ | `{ success: false, data, error, message }` | left alone | Controller-level error envelope — error info preserved. |
129
+ | `{ id, data, status, tenant_app_id, … }` | left alone | Domain record (e.g. `AppConfig`) carrying its own `data` column. |
130
+
131
+ For paginated endpoints, read both the array and the page total off the envelope:
132
+
133
+ ```ts
134
+ const { data: rows, meta } = await client.get<{
135
+ data: Record[];
136
+ meta?: { count?: number; total?: number };
137
+ }>('/v1/apps/crm/data-sources/contacts/items');
138
+ ```
139
+
140
+ ### `unwrapEnvelope<T>(value)` — per-call, aggressive
141
+
142
+ A small helper for ad-hoc unwrap at known sites. It's **wider** than the interceptor — it also strips envelopes carrying `meta` / `error` / `message` because the caller has explicitly typed the return as `T` and isn't surfacing sidecar fields. This is exactly what app-utils' built-in clients (`createDataSourceClient`, `createDataViewClient`, `createDataFormClient`, `createAppConfigClient`, `createUserAppConfigClient`) use internally, so they keep working whether or not you've registered the interceptor globally.
143
+
144
+ ```ts
145
+ import { unwrapEnvelope } from '@kivacore/app-utils';
146
+
147
+ const records = unwrapEnvelope<Record[]>(
148
+ await client.get('/v1/apps/crm/data-sources/contacts/items')
149
+ );
150
+ // → Record[] (meta intentionally discarded)
151
+ ```
152
+
153
+ Domain payloads with a `data` column are still safe — the closed-set check (`{ data, success, meta, error, message }`) rejects records that carry off-set keys like `id` / `status`.
154
+
155
+ ## App Config & Data Views
156
+
157
+ ### `createAppConfigClient(client, appId, options?)`
158
+
159
+ Manages the single JSON configuration object for an app (1:1 relationship — no config IDs).
160
+
161
+ ```ts
162
+ import { createAppConfigClient } from '@kivacore/app-utils';
163
+
164
+ const config = createAppConfigClient(apiClient, appId);
165
+ ```
166
+
167
+ Pass an `InventoryClient` to read `get` from the inventory's per-app config cache and patch it after `upsert` / `remove` (`setAppConfig`). When the inventory has cached `null` (no config exists), `get` falls through to the API so you still receive a real `404`:
168
+
169
+ ```ts
170
+ const config = createAppConfigClient(apiClient, appId, { inventory });
171
+ ```
172
+
173
+ #### `config.get()`
174
+
175
+ Returns the app's configuration. Throws `404` if none exists.
176
+
177
+ ```ts
178
+ const appConfig = await config.get();
179
+ // { id: '...', data: { theme: 'dark', ... }, status: 1, tenant_app_id: '...', ... }
180
+ ```
181
+
182
+ #### `config.upsert(body)`
183
+
184
+ Creates the config if it doesn't exist, or updates it if it does.
185
+
186
+ ```ts
187
+ const updated = await config.upsert({
188
+ data: { theme: 'dark', sidebar: { collapsed: false } },
189
+ status: 1
190
+ });
191
+ ```
192
+
193
+ #### `config.remove()`
194
+
195
+ Hard deletes the config (irreversible).
196
+
197
+ ```ts
198
+ await config.remove();
199
+ ```
200
+
201
+ ---
202
+
203
+ ### `createUserAppConfigClient(client, appId, options?)`
204
+
205
+ Manages the per-user JSON configuration object for an app (1:1 per user per app). Useful for storing user preferences, UI state, or personalisation that should persist per user independently of the shared app config.
206
+
207
+ ```ts
208
+ import { createUserAppConfigClient } from '@kivacore/app-utils';
209
+
210
+ const userConfig = createUserAppConfigClient(apiClient, appId);
211
+ ```
212
+
213
+ Pass an `InventoryClient` to read `get` from the inventory's per-app user-config cache and patch it after `upsert` / `remove` (`setUserAppConfig`), mirroring `createAppConfigClient`:
214
+
215
+ ```ts
216
+ const userConfig = createUserAppConfigClient(apiClient, appId, { inventory });
217
+ ```
218
+
219
+ #### `userConfig.get()`
220
+
221
+ Returns the current user's configuration for the app. Throws `404` if none exists.
222
+
223
+ ```ts
224
+ const config = await userConfig.get();
225
+ // { id: '...', data: { theme: 'dark', ... }, status: 1, tenant_app_id: '...', user_id: '...', ... }
226
+ ```
227
+
228
+ #### `userConfig.upsert(body)`
229
+
230
+ Creates the config if it doesn't exist, or updates it if it does.
231
+
232
+ ```ts
233
+ const updated = await userConfig.upsert({
234
+ data: { theme: 'dark', sidebarCollapsed: true },
235
+ status: 1
236
+ });
237
+ ```
238
+
239
+ #### `userConfig.remove()`
240
+
241
+ Hard deletes the user config (irreversible).
242
+
243
+ ```ts
244
+ await userConfig.remove();
245
+ ```
246
+
247
+ ---
248
+
249
+ ### `createDataViewClient(client, appSlug, dataSourceSlug, options?)`
250
+
251
+ Manages saved view configurations for a specific data source (1:many). Views define columns, filters, sorting, color rules, and quick-filter shortcuts.
252
+
253
+ ```ts
254
+ import { createDataViewClient } from '@kivacore/app-utils';
255
+
256
+ const dataViews = createDataViewClient(apiClient, 'my-app', 'my-data-source');
257
+ ```
258
+
259
+ Pass an `InventoryClient` to read `list` / `get` from the cached data source's embedded `views` array, and patch the cache in place after every mutation:
260
+
261
+ ```ts
262
+ const dataViews = createDataViewClient(apiClient, 'crm', 'invoices', { inventory });
263
+
264
+ await dataViews.list(); // reads from inventory cache (no network)
265
+ await dataViews.create({ name: 'Overdue' }); // POST, then inventory.upsertDataView(result)
266
+ await dataViews.update(id, { is_default: true }); // PUT, then inventory.upsertDataView(result)
267
+ await dataViews.update(id, { archived: true }); // PUT, then inventory.removeDataView(id)
268
+ await dataViews.remove(id); // DELETE, then inventory.removeDataView(id)
269
+ ```
270
+
271
+ #### `dataViews.list(params?)`
272
+
273
+ Returns all non-archived views. Optionally pass `appId` to filter views configured for a specific app (different from the data source's owning app).
274
+
275
+ ```ts
276
+ const views = await dataViews.list();
277
+ const forSpecificApp = await dataViews.list({ appId: 'other-app-uuid' });
278
+ ```
279
+
280
+ #### `dataViews.get(viewId)`
281
+
282
+ Returns a single non-archived view by ID.
283
+
284
+ ```ts
285
+ const view = await dataViews.get('view-uuid');
286
+ ```
287
+
288
+ #### `dataViews.create(body)`
289
+
290
+ Creates a new data view. `name` is required. The data source is determined by the `dataSourceSlug` passed to the client factory.
291
+
292
+ ```ts
293
+ const view = await dataViews.create({
294
+ name: 'High Priority',
295
+ columns: { visible: ['title', 'priority', 'assignee'] },
296
+ filters: { priority: 'high' },
297
+ sort: { field: 'due_date', direction: 'asc' },
298
+ color: '#E74C3C',
299
+ icon: 'alert-triangle',
300
+ is_default: false,
301
+ sort_order: 2
302
+ });
303
+ ```
304
+
305
+ #### `dataViews.update(viewId, body)`
306
+
307
+ Partially updates a view. Use `archived: true` to soft-delete.
308
+
309
+ ```ts
310
+ await dataViews.update('view-uuid', { name: 'Renamed View' });
311
+ await dataViews.update('view-uuid', { archived: true }); // soft-delete
312
+ ```
313
+
314
+ #### `dataViews.remove(viewId)`
315
+
316
+ Hard deletes a view (irreversible).
317
+
318
+ ```ts
319
+ await dataViews.remove('view-uuid');
320
+ ```
321
+
322
+ ---
323
+
324
+ ### `createDataFormClient(client, appSlug, dataSourceSlug, options?)`
325
+
326
+ Manages dynamic form designs attached to a data source (1:many). Forms describe the editable layout used to view and edit records of a data source — title, icon, color, the layout JSON itself (sections / fields / tabs), default selection, and soft-archive state.
327
+
328
+ ```ts
329
+ import { createDataFormClient } from '@kivacore/app-utils';
330
+
331
+ const dataForms = createDataFormClient(apiClient, 'crm', 'contacts');
332
+ ```
333
+
334
+ Pass an `InventoryClient` to read `list` / `get` from the cached data source's embedded `forms` array, and patch the cache in place after every mutation:
335
+
336
+ ```ts
337
+ const dataForms = createDataFormClient(apiClient, 'crm', 'contacts', { inventory });
338
+
339
+ await dataForms.list(); // reads from inventory cache (no network)
340
+ await dataForms.create({ name: 'Compact' }); // POST, then inventory.upsertDataForm(result)
341
+ await dataForms.update(id, { title: 'Customer' }); // PUT, then inventory.upsertDataForm(result)
342
+ await dataForms.update(id, { archived: true }); // PUT, then inventory.removeDataForm(id)
343
+ await dataForms.remove(id); // DELETE, then inventory.removeDataForm(id)
344
+ ```
345
+
346
+ Note: embedded forms carry the layout/display fields needed for rendering, but **not** `description`, `status`, or audit timestamps. If you need those, create a non-inventory-backed `createDataFormClient` and call `get(id)` against the standalone endpoint.
347
+
348
+ #### `dataForms.list()`
349
+
350
+ Returns all non-archived forms for the data source, ordered by `created_on` ascending.
351
+
352
+ ```ts
353
+ const forms = await dataForms.list();
354
+ ```
355
+
356
+ #### `dataForms.get(formId)`
357
+
358
+ Returns a single non-archived form by ID. Throws `404` if the form does not exist or is archived.
359
+
360
+ ```ts
361
+ const form = await dataForms.get('form-uuid');
362
+ ```
363
+
364
+ #### `dataForms.create(body)`
365
+
366
+ Creates a new form. `name` is required; everything else is optional. The data source is determined by the `dataSourceSlug` passed to the client factory — `tenant_data_source_id`, tenant scope, and the `created_by` audit fields are populated server-side.
367
+
368
+ ```ts
369
+ const form = await dataForms.create({
370
+ name: 'Compact contact form',
371
+ title: 'Contact',
372
+ icon: 'user',
373
+ color: '#4F46E5',
374
+ layout: {
375
+ sections: [
376
+ { id: 'main', fields: ['name', 'email', 'phone'] }
377
+ ]
378
+ },
379
+ is_default: false,
380
+ status: 1
381
+ });
382
+ ```
383
+
384
+ #### `dataForms.update(formId, body)`
385
+
386
+ Partially updates a form. Only the fields present in the body are written; omitted fields are preserved. `layout` is replaced wholesale when provided. Use `archived: true` to soft-archive (the row is then excluded from list/get).
387
+
388
+ ```ts
389
+ await dataForms.update('form-uuid', {
390
+ title: 'Customer Contact',
391
+ icon: 'address-book',
392
+ layout: { sections: [/* updated sections */] }
393
+ });
394
+
395
+ await dataForms.update('form-uuid', { archived: true }); // soft-delete
396
+ ```
397
+
398
+ #### `dataForms.remove(formId)`
399
+
400
+ Hard deletes a form (irreversible). Use `update(formId, { archived: true })` instead if you want a recoverable soft-delete.
401
+
402
+ ```ts
403
+ await dataForms.remove('form-uuid');
404
+ ```
405
+
406
+ ---
407
+
408
+ ### `createBrandClient(client, options?)`
409
+
410
+ Manages tenant brand records — the visual identity, voice / messaging, and slide / chart styling configuration used to render brand-aware UI, presentation templates, and AI-generated content. Records are tenant-scoped automatically; cross-tenant access is impossible.
411
+
412
+ ```ts
413
+ import { createBrandClient } from '@kivacore/app-utils';
414
+
415
+ const brands = createBrandClient(apiClient);
416
+ ```
417
+
418
+ Pass an `InventoryClient` to read `list` / `get` from the cached brand list and patch the cache after every mutation (`create` / `update` → `upsertBrand`, `remove` / `update({ archived: true })` → `removeBrand`, `fetchFromWebsite` → merges the returned partial):
419
+
420
+ ```ts
421
+ const brands = createBrandClient(apiClient, { inventory });
422
+ ```
423
+
424
+ #### `brands.list()`
425
+
426
+ Returns all non-archived brands for the active tenant, with the default brand first and then by creation date ascending.
427
+
428
+ ```ts
429
+ const brands = await brands.list();
430
+ ```
431
+
432
+ #### `brands.get(brandId)`
433
+
434
+ Returns a single brand by ID. Throws `404` if the brand does not exist or belongs to another tenant.
435
+
436
+ ```ts
437
+ const brand = await brands.get('brand-uuid');
438
+ ```
439
+
440
+ #### `brands.create(body)`
441
+
442
+ Creates a new brand. Only `name` is required; everything else is optional and defaults to `null` (or the column default). `tenant_id` and the `created_by` / `last_modified_by` audit fields are populated server-side.
443
+
444
+ ```ts
445
+ const brand = await brands.create({
446
+ name: 'Acme Corp',
447
+ description: 'Primary marketing brand',
448
+ website_url: 'https://acme.com',
449
+ color_primary: '#FF6600',
450
+ color_secondary: '#1E1E1E',
451
+ font_family_primary: 'Inter',
452
+ is_default: true
453
+ });
454
+ ```
455
+
456
+ > Note: the API does not enforce a single default brand per tenant — the caller is responsible for clearing `is_default` on the previous default when promoting a new one.
457
+
458
+ #### `brands.update(brandId, body)`
459
+
460
+ Partially updates a brand. Only the fields present in the body are written; omitted fields are preserved. Setting a field to `null` clears it. Use `archived: true` to soft-archive (archived rows are excluded from `list()`).
461
+
462
+ ```ts
463
+ await brands.update('brand-uuid', {
464
+ color_primary: '#0044CC',
465
+ logo_url: 'https://cdn.example.com/logos/acme-v2.svg',
466
+ is_default: false
467
+ });
468
+
469
+ await brands.update('brand-uuid', { archived: true }); // soft-archive
470
+ ```
471
+
472
+ #### `brands.remove(brandId)`
473
+
474
+ Hard deletes the brand (irreversible). Use `update(brandId, { archived: true })` for a recoverable soft delete.
475
+
476
+ ```ts
477
+ await brands.remove('brand-uuid');
478
+ ```
479
+
480
+ #### `brands.fetchFromWebsite(brandId)`
481
+
482
+ Scrapes the brand's configured `website_url` with Firecrawl and merges the extracted branding (colors, typography, spacing, components, images, voice / personality, fonts, icons, animations, layout) into the brand record. Only fields detected by the scraper are overwritten — existing values for missing fields are preserved.
483
+
484
+ This is a **synchronous** RPC — the request blocks until Firecrawl returns, so expect several seconds of latency. The response is intentionally a flat top-level object (not the standard `{ data }` envelope) so callers can preview the raw scraper output alongside the persisted summary.
485
+
486
+ ```ts
487
+ const { brand, scrapedBranding } = await brands.fetchFromWebsite('brand-uuid');
488
+ ```
489
+
490
+ Throws `400` if the brand has no `website_url` configured, `404` if the brand doesn't exist, or `500` if Firecrawl is unconfigured or returns no branding data.
491
+
492
+ ---
493
+
494
+ ### `createUserIdentityClient(client)`
495
+
496
+ Persists the **decoded** OIDC ID-token payload from Microsoft (Graph) or Google for the authenticated user. Designed to be called from the frontend right after a successful OAuth2 flow (e.g. `msal-browser`, `google-identity-services`, `nimbus-auth-js`) — pass the verified ID-token claims and the backend writes the payload into `tenant_user.identity_microsoft` / `identity_google` **and** upserts the matching `tenant_connection_user` row so the provider connection is recorded alongside the identity claims.
497
+
498
+ These endpoints are hidden from Swagger, which is exactly why this helper exists — typed wrappers make them safer to call than hand-rolled `fetch`. They require the `User.ReadWrite` (or `Users.ReadWrite.All`) scope.
499
+
500
+ ```ts
501
+ import { createUserIdentityClient } from '@kivacore/app-utils';
502
+
503
+ const userIdentity = createUserIdentityClient(apiClient);
504
+ ```
505
+
506
+ #### `userIdentity.saveMicrosoft(payload)`
507
+
508
+ Persists a Microsoft / Entra ID-token payload. `sub` is required; all other well-known claims (`oid`, `tid`, `email`, `name`, `preferred_username`) are typed but optional, and any additional claims (`aud`, `iss`, `iat`, `exp`, …) pass through verbatim.
509
+
510
+ ```ts
511
+ await userIdentity.saveMicrosoft({
512
+ sub: '6zIRb2daYqUXVlg-xu4dA3nLsJekGkVhZxIg2GLpn2I',
513
+ oid: 'f0ea18f8-cf7d-4695-8d9e-d9674127b343',
514
+ tid: 'a2b0309e-37c1-486d-bdbd-4d91b7d25cd5',
515
+ email: 'anil.beyazoglu@docy.team',
516
+ name: 'Anıl Beyazoğlu',
517
+ preferred_username: 'anil.beyazoglu@docy.team',
518
+ iss: 'https://login.microsoftonline.com/.../v2.0',
519
+ aud: '0380d712-0e97-431f-b343-76604e1cfcd1',
520
+ iat: 1754578886,
521
+ exp: 1754582786
522
+ });
523
+ ```
524
+
525
+ #### `userIdentity.saveGoogle(payload)`
526
+
527
+ Persists a Google ID-token payload. `sub` is required; `email` and `name` are typed but optional, and any additional claims pass through verbatim.
528
+
529
+ ```ts
530
+ await userIdentity.saveGoogle({
531
+ sub: '110169484474386276334',
532
+ email: 'anil@example.com',
533
+ name: 'Anıl Beyazoğlu'
534
+ });
535
+ ```
536
+
537
+ #### Behaviour notes
538
+
539
+ - Both calls return `void` — the server responds with `{ success: true }` and nothing useful to surface.
540
+ - Pass the **decoded ID-token payload only**, not the raw OAuth2 access / refresh tokens. The endpoints intentionally do **not** touch the `access_token` / `refresh_token` columns on the connection row.
541
+ - The connection record uses the well-known provider slug (`microsoft` / `google`), so consumers like the chat-platform webhook can match users via `identity_microsoft->>'tid'`, `'oid'`, `'sub'`, `'preferred_username'`, `'email'` and `identity_google->>'sub'`, `'email'`.
542
+ - Throws `404` if the active product has no provider-auth row for the slug, or `422` if `sub` is missing.
543
+
544
+ ---
545
+
546
+ ### `createDataSourceClient(client, options?)`
547
+
548
+ Reads Docyrus app and data source metadata across apps or for a specific app. This is useful when you need schema-aware UI behavior such as loading available apps, reading field definitions, or resolving a data source by slug.
549
+
550
+ ```ts
551
+ import { createDataSourceClient } from '@kivacore/app-utils';
552
+
553
+ const dataSources = createDataSourceClient(apiClient);
554
+ ```
555
+
556
+ #### Backing the client with an inventory cache
557
+
558
+ Pass an `InventoryClient` (see [`createInventoryClient`](#createinventoryclientclient-options)) to read every list/get method through the inventory cache instead of hitting the network on every call:
559
+
560
+ ```ts
561
+ import { createInventoryClient, createDataSourceClient } from '@kivacore/app-utils';
562
+
563
+ const inventory = createInventoryClient(apiClient);
564
+ const dataSources = createDataSourceClient(apiClient, { inventory });
565
+
566
+ // First call populates the inventory cache (one network request).
567
+ // Subsequent calls — including from other clients sharing the same inventory — are cache hits.
568
+ await dataSources.listApps();
569
+ await dataSources.listByAppSlug('crm');
570
+ await dataSources.getBySlug('crm', 'contacts');
571
+ ```
572
+
573
+ Cache resolution rules:
574
+ - If `params.expand` is **omitted**, the cached entry (fetched with the inventory's `dataSourcesExpand`, default `'views,forms,fields'`) is used — every returned data source already carries its embedded `views`, `forms`, and `fields` (with `enums`).
575
+ - If `params.expand` is **provided**, the request bypasses the cache and hits the API directly — the cached entry may not include the requested expansions.
576
+ - `getById` / `getBySlug` fall back to the API when the lookup misses the cache (e.g. an entry that was created after the cache was populated).
577
+
578
+ #### Expand options
579
+
580
+ The metadata endpoints support comma-separated expansions via `expand`.
581
+
582
+ Available values:
583
+ - `children`
584
+ - `fields`
585
+ - `forms`
586
+ - `acl`
587
+ - `templates`
588
+ - `client-configuration`
589
+ - `misc`
590
+
591
+ Example:
592
+
593
+ ```ts
594
+ const sources = await dataSources.list({
595
+ expand: 'fields,forms'
596
+ });
597
+ ```
598
+
599
+ #### `dataSources.listApps()`
600
+
601
+ Lists apps available to the current tenant.
602
+
603
+ ```ts
604
+ const apps = await dataSources.listApps();
605
+ // [{ id: 'uuid', name: 'CRM', slug: 'crm', logo_url: '...', status: 'active' }]
606
+ ```
607
+
608
+ #### `dataSources.list(params?)`
609
+
610
+ Lists all data sources the current tenant can access across all apps.
611
+
612
+ ```ts
613
+ const all = await dataSources.list();
614
+ const allWithFields = await dataSources.list({ expand: 'fields' });
615
+ ```
616
+
617
+ #### `dataSources.listByAppSlug(appSlug, params?)`
618
+
619
+ Lists all data sources for a specific app slug.
620
+
621
+ ```ts
622
+ const crmSources = await dataSources.listByAppSlug('crm');
623
+ const crmWithFields = await dataSources.listByAppSlug('crm', {
624
+ expand: 'fields,acl'
625
+ });
626
+ ```
627
+
628
+ #### `dataSources.listByAppId(appId, params?)`
629
+
630
+ Lists all data sources for a specific app ID.
631
+
632
+ ```ts
633
+ const appSources = await dataSources.listByAppId('app-uuid');
634
+ const appSourcesWithFields = await dataSources.listByAppId('app-uuid', {
635
+ expand: 'fields'
636
+ });
637
+ ```
638
+
639
+ #### `dataSources.getById(dataSourceId, params?)`
640
+
641
+ Returns a single data source metadata object by data source ID.
642
+
643
+ ```ts
644
+ const contacts = await dataSources.getById('data-source-uuid');
645
+ const contactsWithFields = await dataSources.getById('data-source-uuid', {
646
+ expand: 'fields'
647
+ });
648
+ ```
649
+
650
+ #### `dataSources.getBySlug(appSlug, dataSourceSlug, params?)`
651
+
652
+ Returns a single data source metadata object by app slug and data source slug.
653
+
654
+ ```ts
655
+ const contacts = await dataSources.getBySlug('crm', 'contacts');
656
+ const contactsWithFields = await dataSources.getBySlug('crm', 'contacts', {
657
+ expand: 'fields,forms'
658
+ });
659
+ ```
660
+
661
+ #### Response shape
662
+
663
+ Basic responses include fields such as:
664
+
665
+ ```ts
666
+ {
667
+ id: 'uuid',
668
+ name: 'Contacts',
669
+ slug: 'contacts',
670
+ appSlug: 'crm'
671
+ }
672
+ ```
673
+
674
+ When `expand=fields` is used, the response can include `fields` metadata as well.
675
+
676
+ #### Field & enum helpers
677
+
678
+ Convenience readers that resolve a data source's fields and their enum options. When the client is [backed by an inventory](#backing-the-client-with-an-inventory-cache), they read straight from the cache (fields + enums are embedded via `dataSourcesExpand`, so **no extra network call**); otherwise they fetch the data source once with `expand=fields`.
679
+
680
+ ```ts
681
+ const fields = await dataSources.getFields('data-source-uuid');
682
+ const status = await dataSources.getFieldBySlug('data-source-uuid', 'status');
683
+ const field = await dataSources.getFieldById('data-source-uuid', 'field-uuid');
684
+
685
+ const options = await dataSources.getEnumsByFieldId('data-source-uuid', 'status-field-uuid');
686
+ const won = await dataSources.getEnumById('data-source-uuid', 'status-field-uuid', 'enum-uuid');
687
+ ```
688
+
689
+ | Method | Returns |
690
+ |--------|---------|
691
+ | `getFields(dataSourceId)` | `DataSourceField[]` — `[]` when the data source has none |
692
+ | `getFieldById(dataSourceId, fieldId)` | `DataSourceField \| undefined` |
693
+ | `getFieldBySlug(dataSourceId, fieldSlug)` | `DataSourceField \| undefined` |
694
+ | `getEnumsByFieldId(dataSourceId, fieldId)` | `DataSourceEnumOption[]` — `[]` when the field has none or isn't found |
695
+ | `getEnumById(dataSourceId, fieldId, enumId)` | `DataSourceEnumOption \| undefined` |
696
+
697
+ #### Relation helpers (parent / child selectors)
698
+
699
+ Docyrus models a relationship with a `relation` field on the **child** whose `relation_data_source_id` points at the **parent**. These helpers resolve those edges so you can build parent/child data-source and field pickers:
700
+
701
+ ```ts
702
+ // Given a data source, what does it link to (parents) and what links to it (children)?
703
+ const parents = await dataSources.listParentDataSources('contacts-ds-id'); // e.g. [Accounts]
704
+ const children = await dataSources.listChildDataSources('accounts-ds-id'); // e.g. [Contacts, Deals]
705
+
706
+ // Flattened fields for a field selector on the related side:
707
+ const parentFields = await dataSources.listParentDataSourceFields('contacts-ds-id');
708
+ const childFields = await dataSources.listChildDataSourceFields('accounts-ds-id');
709
+ ```
710
+
711
+ | Method | Returns |
712
+ |--------|---------|
713
+ | `listParentDataSources(dataSourceId)` | `DataSource[]` — the `relation` targets (parents), distinct, self-links excluded |
714
+ | `listChildDataSources(dataSourceId)` | `DataSource[]` — data sources whose `relation` field targets this one (children) |
715
+ | `listParentDataSourceFields(dataSourceId)` | `DataSourceField[]` — parents' fields, flattened (ids are unique, no dupes) |
716
+ | `listChildDataSourceFields(dataSourceId)` | `DataSourceField[]` — children's fields, flattened |
717
+
718
+ These are built from a **memoized relation index** over the cached data sources: with an inventory wired in, the index is computed once and reused until the cache changes — so calls are effectively O(1) lookups with no network. Without an inventory they fall back to one `GET .../data-sources?expand=fields` per call (rebuilding the index each time), so **pass an inventory** for the "fast" path. Requires field metadata in the cache (the inventory's default `dataSourcesExpand` includes `fields`). Need the fields grouped by their owning data source? Use `listParentDataSources` / `listChildDataSources` and read each result's `.fields`.
719
+
720
+ ---
721
+
722
+ ### `createInventoryClient(client, options?)`
723
+
724
+ A tenant-wide inventory cache of the data a Docyrus app needs at startup — installed apps, data sources (with their embedded views/forms/fields), tenant users, brands, tenant preferences, and per-app config — with **no app or data source scope** required. Useful for global pickers, sync caches, admin dashboards, post-sign-in warm-up, or any UI that needs to enumerate everything the tenant can see. Each resource is cached independently (same TTL, request de-dup) and shared across every inventory-backed client (`createDataSourceClient`, `createDataViewClient`, `createDataFormClient`, `createBrandClient`, `createAppConfigClient`, `createUserAppConfigClient`) when you pass **one** instance to all of them.
725
+
726
+ ```ts
727
+ import { createInventoryClient } from '@kivacore/app-utils';
728
+
729
+ const inventory = createInventoryClient(apiClient);
730
+ ```
731
+
732
+ #### Recommended usage: one shared inventory, warmed after sign-in
733
+
734
+ The inventory pays off when you create it **once** and pass that single instance
735
+ to every client, then warm it a single time right after sign-in. From then on
736
+ the whole app reads metadata from memory instead of the network.
737
+
738
+ **1. Create one instance at bootstrap and wire every client to it.** Put this in
739
+ a module the rest of the app imports (or a DI container / React context) so
740
+ there is exactly one cache:
741
+
742
+ ```ts
743
+ // services/docyrus.ts
744
+ import {
745
+ createInventoryClient,
746
+ createDataSourceClient,
747
+ createDataViewClient,
748
+ createDataFormClient,
749
+ createBrandClient,
750
+ createAppConfigClient,
751
+ createUserAppConfigClient
752
+ } from '@kivacore/app-utils';
753
+
754
+ const appId = import.meta.env.VITE_APP_ID;
755
+
756
+ // The one cache. Every client below shares it.
757
+ export const inventory = createInventoryClient(apiClient);
758
+
759
+ export const dataSources = createDataSourceClient(apiClient, { inventory });
760
+ export const brands = createBrandClient(apiClient, { inventory });
761
+ export const appConfig = createAppConfigClient(apiClient, appId, { inventory });
762
+ export const userAppConfig = createUserAppConfigClient(apiClient, appId, { inventory });
763
+
764
+ // View / form clients are per data source — construct them on demand, always
765
+ // passing the same `inventory`:
766
+ export const viewsFor = (appSlug: string, dsSlug: string) =>
767
+ createDataViewClient(apiClient, appSlug, dsSlug, { inventory });
768
+ export const formsFor = (appSlug: string, dsSlug: string) =>
769
+ createDataFormClient(apiClient, appSlug, dsSlug, { inventory });
770
+ ```
771
+
772
+ **2. Warm the cache once after sign-in, behind a progress bar.** Call `load()`
773
+ as soon as you have an authenticated client and before routing to the home
774
+ page. With `VITE_APP_ID` set, this also warms the current app's config and
775
+ user-config (see [`load()`](#inventoryloadoptions)):
776
+
777
+ ```ts
778
+ // Runs after @kivacore/signin reports an authenticated session.
779
+ async function bootstrapAfterSignIn(setProgress: (p: { label: string; value: number }) => void) {
780
+ try {
781
+ await inventory.load({
782
+ onProgress: ({ message, ratio, phase }) => {
783
+ setProgress({ label: message, value: Math.round(ratio * 100) });
784
+ if (phase === 'complete') setProgress({ label: 'Ready', value: 100 });
785
+ }
786
+ });
787
+ } catch (error) {
788
+ // A step failed (network, or a missing scope — see below). Surface it and
789
+ // let the user retry; the app can still run, reads just fall back to the API.
790
+ reportBootstrapError(error);
791
+ }
792
+
793
+ navigateToHome();
794
+ }
795
+ ```
796
+
797
+ **3. Read everywhere through the wired clients — every call is now a cache hit:**
798
+
799
+ ```ts
800
+ const sources = await dataSources.list(); // from cache
801
+ const statusField = await dataSources.getFieldBySlug(dsId, 'status');
802
+ const options = await dataSources.getEnumsByFieldId(dsId, statusFieldId);
803
+ const cfg = await appConfig.get(); // from cache (warmed via VITE_APP_ID)
804
+ const tenantBrands = await brands.list(); // from cache
805
+ ```
806
+
807
+ **Handling limited scopes.** `listUsers()` needs the `Users.Read.All` scope; if
808
+ the signed-in user may lack it, drop that step so `load()` doesn't reject:
809
+
810
+ ```ts
811
+ await inventory.load({
812
+ include: ['apps', 'data-sources', 'brands', 'preferences'], // no 'users'
813
+ onProgress
814
+ });
815
+ ```
816
+
817
+ **Keeping the cache correct over a session.** Mutations made through the wired
818
+ clients patch the cache automatically. For external changes, drop the stale
819
+ slice; on **tenant switch** call `refresh()` (or rebuild the inventory) so the
820
+ new tenant's data replaces the old:
821
+
822
+ ```ts
823
+ await inventory.refresh(); // after a tenant switch: drop all, re-fetch apps + data sources
824
+ inventory.invalidateBrands(); // e.g. brands changed elsewhere — next read re-fetches
825
+ inventory.invalidateAppConfig(); // drop every cached app config
826
+ ```
827
+
828
+ > By default the cache is in-memory per instance, so a full page reload starts
829
+ > cold — that is exactly why the post-sign-in `load()` exists. To carry the cache
830
+ > across reloads, pass a `storage` option (see
831
+ > [Persisting the cache](#persisting-the-cache-localstorage--sessionstorage)). On
832
+ > a tenant switch that does **not** reload, `refresh()` is required to avoid
833
+ > serving the previous tenant's metadata.
834
+
835
+ #### One fetch, everything cached
836
+
837
+ `listDataSources` is the single source of truth. It calls `GET /v1/apps/data-sources?expand=views,forms,fields` once and caches every data source together with its embedded views, forms (with `actions`), and fields (with enum options). `listDataViews` and `listDataForms` are **derived projections** over that cache — they trigger no extra HTTP calls.
838
+
839
+ | Option | Default | Description |
840
+ |---------------------|-------------------------|--------------------------------------------------------------------------------------------------------|
841
+ | `ttlMs` | `300_000` (5 min) | Cache time-to-live. Pass `Infinity` to keep entries until `refresh()` / `invalidate*()`. |
842
+ | `dataSourcesExpand` | `'views,forms,fields'` | Comma-separated `expand`. Override to include extras (e.g. `'views,forms,fields,acl'`) — keep `views`, `forms`, `fields` so derived views / form clients still work. |
843
+ | `storage` | — (in-memory only) | Persist the cache so it survives page reloads: `'local'` (`localStorage`), `'session'` (`sessionStorage`), or a custom `InventoryStorage` adapter. See [Persisting the cache](#persisting-the-cache-localstorage--sessionstorage). |
844
+ | `storageKey` | `'docyrus:inventory'` | Key the snapshot is stored under. Namespace it per tenant/user so separate sessions don't collide. Ignored when `storage` is unset. |
845
+
846
+ The embedded form payload (camelCased, reduced) is **normalized on cache write** to the canonical `DataForm` shape — `isDefault` → `is_default`, missing `tenant_data_source_id` is backfilled from the parent data source, `archived` defaults to `false`. Embedded extras (`ownership`, `ownerProductId`, `customized`) are preserved as optional fields on `DataForm`.
847
+
848
+ Alongside data sources, the inventory caches five more resources, each fetched by a single request and cached independently:
849
+
850
+ | Method | Endpoint | Cached as | Notes |
851
+ |--------|----------|-----------|-------|
852
+ | `listUsers()` | `GET /v1/users` | `User[]` | Requires the `Users.Read.All` scope. |
853
+ | `listBrands()` | `GET /v1/tenant/brands` | `Brand[]` | Patchable via `upsertBrand` / `removeBrand`. |
854
+ | `getPreferences()` | `GET /v1/tenant/preferences` | `TenantPreferences` | |
855
+ | `getAppConfig(appId)` | `GET /v1/tenant/apps/{appId}/config` | `AppConfig \| null` per app id | `null` (a `404`) is cached too. |
856
+ | `getUserAppConfig(appId)` | `GET /v1/tenant/apps/{appId}/user-config` | `UserAppConfig \| null` per app id | `null` (a `404`) is cached too. |
857
+
858
+ ```ts
859
+ const inventory = createInventoryClient(apiClient, {
860
+ ttlMs: 10 * 60 * 1000,
861
+ dataSourcesExpand: 'views,forms,fields,acl'
862
+ });
863
+
864
+ // Cache management
865
+ await inventory.refresh(); // drop every cache and re-fetch apps + data sources
866
+ inventory.invalidateApps(); // selectively drop apps
867
+ inventory.invalidateDataSources(); // selectively drop data sources (and the derived views/forms)
868
+ inventory.invalidateUsers();
869
+ inventory.invalidateBrands();
870
+ inventory.invalidatePreferences();
871
+ inventory.invalidateAppConfig(appId); // one app, or omit appId to drop all app configs
872
+ inventory.invalidateUserAppConfig(appId); // one app, or omit appId to drop all user configs
873
+
874
+ // Direct cache patches (used by the inventory-backed clients after mutations)
875
+ inventory.upsertDataView(view); // insert or replace by id, routed via view.tenant_data_source_id
876
+ inventory.removeDataView(viewId);
877
+ inventory.upsertDataForm(form);
878
+ inventory.removeDataForm(formId);
879
+ inventory.upsertBrand(brand); // insert or replace by id (no-op until listBrands ran)
880
+ inventory.removeBrand(brandId);
881
+ inventory.setAppConfig(appId, config); // set (or clear with null)
882
+ inventory.setUserAppConfig(appId, config);
883
+ ```
884
+
885
+ Filters passed to `listDataViews({ appId, dataSourceId })` / `listDataForms({ dataSourceId })` are applied client-side over the cached data sources — they never refetch.
886
+
887
+ #### Persisting the cache (localStorage / sessionStorage)
888
+
889
+ By default the cache lives only in memory, so a full page reload starts cold. Pass a `storage` option to persist it — the whole cache is serialized to a single snapshot on every write and rehydrated when the client is constructed, so reads survive reloads:
890
+
891
+ ```ts
892
+ // localStorage — survives tab close and browser restart
893
+ const inventory = createInventoryClient(apiClient, {
894
+ storage: 'local',
895
+ // Namespace per tenant/user so sessions don't share or overwrite one another.
896
+ storageKey: `docyrus:inventory:${tenantId}`
897
+ });
898
+
899
+ // sessionStorage — cleared when the tab closes
900
+ const inventory = createInventoryClient(apiClient, { storage: 'session' });
901
+
902
+ // Or bring your own adapter (anything with getItem / setItem / removeItem):
903
+ const inventory = createInventoryClient(apiClient, { storage: myStorageAdapter });
904
+ ```
905
+
906
+ > **To actually skip the refetch on reload, warm with `load({ force: false })`.**
907
+ > `load()` defaults to `force: true`, which invalidates every cache before
908
+ > fetching — so it discards the hydrated snapshot and always hits the network,
909
+ > persistence or not. Pass `force: false` so still-fresh (including just-hydrated)
910
+ > entries are reused, and pair it with a `ttlMs` that outlives the reload
911
+ > (`Infinity` is the natural fit for `sessionStorage` — the tab session already
912
+ > bounds the cache):
913
+ >
914
+ > ```ts
915
+ > const inventory = createInventoryClient(apiClient, { storage: 'session', ttlMs: Infinity });
916
+ > await inventory.load({ force: false }); // hydrated? serve it, no network. cold? fetch once.
917
+ > ```
918
+ >
919
+ > Reach for `refresh()` (or `load()` with the default `force: true`) only when you
920
+ > explicitly want fresh data — a "reload" button, a tenant switch, etc.
921
+
922
+ Behavior and guarantees:
923
+
924
+ - **TTL still applies across reloads.** Persisted entries keep their `fetchedAt`, so a hydrated snapshot older than `ttlMs` is treated as stale and refetched on first read. Combine `storage` with `ttlMs: Infinity` to cache until you explicitly `refresh()` / `invalidate*()`.
925
+ - **Every mutation persists.** The loaders, the `invalidate*` methods, the direct cache patches (`upsertDataView`, `upsertBrand`, `setAppConfig`, …), and `refresh()` all rewrite the snapshot, so storage never lags memory.
926
+ - **Defensive by design — never throws.** If the chosen storage is unavailable (SSR / no `window`, private mode, disabled cookies, a `SecurityError`, or a quota-exceeded write) the client silently falls back to in-memory. A corrupt or version-mismatched snapshot is ignored and refetched cleanly.
927
+ - **Namespace the key.** Different tenants/users sharing one `storageKey` would overwrite each other's cache — include a tenant or user id in `storageKey`. On a tenant switch, either use a new key or call `refresh()`.
928
+ - **Custom adapter.** `storage` also accepts any object implementing the `InventoryStorage` interface (`getItem` / `setItem` / `removeItem`) — an in-memory shim for tests, a namespaced wrapper, or a mirror over another store.
929
+
930
+ ```ts
931
+ import type { InventoryStorage } from '@kivacore/app-utils';
932
+ ```
933
+
934
+ #### `inventory.load(options?)`
935
+
936
+ Warms the inventory in one sequence and emits progress events per step. Designed to run once right after sign-in, behind a progress dialog, so that every later read (from the inventory itself and from any inventory-backed client) is a cache hit. By default it warms **apps, data sources, users, brands, and preferences**, plus the **current app's config + user-config** when the `VITE_APP_ID` env var is set (see `configAppIds` below). Resolves with an `InventoryLoadResult`; rejects — after emitting an `error` event — if a step fails.
937
+
938
+ ```ts
939
+ const { apps, dataSources, users, brands, preferences, appConfigs, userAppConfigs } =
940
+ await inventory.load({
941
+ onProgress: ({ step, appId, message, current, total, ratio, phase }) => {
942
+ // Drive a determinate progress bar. `phase` is 'start' | 'success' | 'error' | 'complete'.
943
+ // Map `step` (see step ids below, or `null` on 'complete') to your own i18n if you
944
+ // don't want the default English `message`. `appId` is set on config steps.
945
+ setProgress({ label: message, value: Math.round(ratio * 100) });
946
+ }
947
+ });
948
+ // → navigate to home; all inventory-backed reads are now cache hits
949
+ ```
950
+
951
+ Default event sequence (`total` is `5`): a `start`/`success` pair for each of `apps`, `data-sources`, `users`, `brands`, `preferences` (with `ratio` stepping `0 → 0.2 → … → 1`), then a terminal `{ step: null, phase: 'complete', ratio: 1 }`.
952
+
953
+ | Option | Default | Description |
954
+ |--------|---------|-------------|
955
+ | `onProgress` | — | Callback fired for each lifecycle event (`start`/`success` per step, `error` on failure, one terminal `complete`). |
956
+ | `force` | `true` | Invalidate the to-be-loaded caches first so the load always issues fresh network calls. Set to `false` to reuse still-fresh entries (steps then resolve instantly but events are still emitted). |
957
+ | `include` | `['apps', 'data-sources', 'users', 'brands', 'preferences']` | Which tenant-wide steps to run, in order. Narrow it when the user lacks a scope — e.g. drop `'users'` (needs `Users.Read.All`) — or when you only need a subset. |
958
+ | `configAppIds` | `VITE_APP_ID` (if set) else `[]` | App ids whose config **and** user-config to warm, appended as two extra steps per id (`step: 'app-config'` / `'user-app-config'`, each carrying `appId`). When omitted, defaults to the current app from `VITE_APP_ID` (read from `import.meta.env` or `process.env`); pass an explicit `[]` to skip config warm-up. Missing configs cache as `null` — a `404` is not an error. |
959
+
960
+ Step ids (`InventoryLoadStepId`): `'apps' | 'data-sources' | 'users' | 'brands' | 'preferences' | 'app-config' | 'user-app-config'`.
961
+
962
+ ```ts
963
+ // Warm everything the current app's home page needs, including its config:
964
+ await inventory.load({ configAppIds: [currentAppId], onProgress });
965
+
966
+ // A viewer without the users scope:
967
+ await inventory.load({ include: ['apps', 'data-sources', 'brands', 'preferences'], onProgress });
968
+ ```
969
+
970
+ #### `inventory.listApps()`
971
+
972
+ Lists every app the current tenant can access. Backed by `GET /v1/apps`. Cached separately from data sources.
973
+
974
+ ```ts
975
+ const apps = await inventory.listApps();
976
+ // [{ id: 'uuid', name: 'CRM', slug: 'crm', logo_url: '...', status: 'active' }]
977
+ ```
978
+
979
+ #### `inventory.listDataSources()`
980
+
981
+ Lists every data source the current tenant can access across all apps, with `views`, `forms`, and `fields` (with `enums`) embedded inline. Triggers exactly **one** network call per cache window.
982
+
983
+ ```ts
984
+ const sources = await inventory.listDataSources();
985
+ // sources[0].views — DataView[]
986
+ // sources[0].forms — DataForm[] (normalized from the embedded camelCased shape)
987
+ // sources[0].fields[i].enums — DataSourceEnumOption[] for select-type fields
988
+ ```
989
+
990
+ #### `inventory.listUsers()` / `listBrands()` / `getPreferences()`
991
+
992
+ Tenant-wide singletons, each backed by one request and cached independently (same TTL + request de-dup as the data-source cache).
993
+
994
+ ```ts
995
+ const users = await inventory.listUsers(); // GET /v1/users (needs Users.Read.All)
996
+ const brands = await inventory.listBrands(); // GET /v1/tenant/brands
997
+ const preferences = await inventory.getPreferences(); // GET /v1/tenant/preferences
998
+ ```
999
+
1000
+ #### `inventory.getAppConfig(appId)` / `getUserAppConfig(appId)`
1001
+
1002
+ Per-app config, cached in a map keyed by app id. Resolve to `null` when no config exists — a `404` is treated as a valid empty state and the `null` is cached, so repeat calls don't re-hit the API.
1003
+
1004
+ ```ts
1005
+ const config = await inventory.getAppConfig(appId); // AppConfig | null
1006
+ const userConfig = await inventory.getUserAppConfig(appId); // UserAppConfig | null
1007
+ ```
1008
+
1009
+ #### `inventory.listDataViews(params?)`
1010
+
1011
+ Flattens every cached data source's `views` array into a single list. No network call. `params.appId` matches against `tenant_app_id`; `params.dataSourceId` matches against the data source's `id`.
1012
+
1013
+ ```ts
1014
+ const allViews = await inventory.listDataViews();
1015
+
1016
+ const crmViews = await inventory.listDataViews({
1017
+ appId: 'fbeebd52-98ff-11ed-93e6-37fc9e45fc08'
1018
+ });
1019
+
1020
+ const viewsForSpecificDataSources = await inventory.listDataViews({
1021
+ dataSourceId: ['019c48d0-506a-7ad1-9a4d-20acbc82f300', '010e9ce2-ca44-11ed-bda6-6b0c6905cf5e']
1022
+ });
1023
+ ```
1024
+
1025
+ Both filters accept either a single id or an array.
1026
+
1027
+ #### `inventory.listDataForms(params?)`
1028
+
1029
+ Same flattening for forms.
1030
+
1031
+ ```ts
1032
+ const allForms = await inventory.listDataForms();
1033
+ const formsForApp = await inventory.listDataForms({ appId: ['fbeebd52-...'] });
1034
+ ```
1035
+
1036
+ ---
1037
+
1038
+ ### `createDataSourceQueries(client)` — TanStack Query integration
1039
+
1040
+ Returns prebuilt [`queryOptions`](https://tanstack.com/query/latest/docs/framework/react/reference/queryOptions)-style factories and a query-key registry, so you get caching, deduplication, and reactive auto-invalidation for free. Works with `@tanstack/react-query`, `@tanstack/vue-query`, `@tanstack/solid-query`, etc. — only `@tanstack/query-core` is required at runtime.
1041
+
1042
+ Imported from a separate entrypoint to keep the optional `@tanstack/query-core` peer dep out of the main bundle:
1043
+
1044
+ ```ts
1045
+ import { createDataSourceQueries } from '@kivacore/app-utils/query';
1046
+
1047
+ const queries = createDataSourceQueries(apiClient);
1048
+ ```
1049
+
1050
+ #### Usage with React
1051
+
1052
+ ```tsx
1053
+ import { useQuery, useQueryClient } from '@tanstack/react-query';
1054
+ import { createDataSourceQueries } from '@kivacore/app-utils/query';
1055
+
1056
+ const queries = createDataSourceQueries(apiClient);
1057
+
1058
+ function ContactsTable() {
1059
+ const { data: contacts } = useQuery(
1060
+ queries.getBySlugOptions('crm', 'contacts', { expand: 'fields,forms' })
1061
+ );
1062
+
1063
+ const queryClient = useQueryClient();
1064
+ const handleSchemaChange = () => queries.invalidateBySlug(queryClient, 'crm', 'contacts');
1065
+
1066
+ // ...
1067
+ }
1068
+ ```
1069
+
1070
+ #### Available `*Options` factories
1071
+
1072
+ Each factory mirrors the corresponding `createDataSourceClient` method and produces a `{ queryKey, queryFn }` object you pass straight to `useQuery` (or `useSuspenseQuery`, `prefetchQuery`, etc.):
1073
+
1074
+ | Factory | Wraps |
1075
+ |---------|-------|
1076
+ | `listAppsOptions()` | `dataSources.listApps()` |
1077
+ | `listOptions(params?)` | `dataSources.list(params)` |
1078
+ | `listByAppSlugOptions(appSlug, params?)` | `dataSources.listByAppSlug(...)` |
1079
+ | `listByAppIdOptions(appId, params?)` | `dataSources.listByAppId(...)` |
1080
+ | `getByIdOptions(dataSourceId, params?)` | `dataSources.getById(...)` |
1081
+ | `getBySlugOptions(appSlug, dataSourceSlug, params?)` | `dataSources.getBySlug(...)` |
1082
+
1083
+ Per-request options (`staleTime`, `enabled`, `select`, `placeholderData`, …) are passed at the call site:
1084
+
1085
+ ```ts
1086
+ useQuery({
1087
+ ...queries.listOptions({ expand: 'fields' }),
1088
+ staleTime: 5 * 60 * 1000,
1089
+ enabled: isAuthenticated
1090
+ });
1091
+ ```
1092
+
1093
+ #### Invalidation helpers
1094
+
1095
+ All take a `QueryClient` so consumers can call them anywhere (event handlers, mutation `onSuccess`, etc.).
1096
+
1097
+ | Helper | Invalidates |
1098
+ |--------|-------------|
1099
+ | `invalidateAll(qc)` | Every cached data-source query (apps + lists + details) |
1100
+ | `invalidateApps(qc)` | Cached app list |
1101
+ | `invalidateLists(qc)` | All `list*` variants (across apps and params) |
1102
+ | `invalidateDetails(qc)` | All `getById` / `getBySlug` results |
1103
+ | `invalidateById(qc, dataSourceId)` | Every cached detail for a single data source ID (any `expand`) |
1104
+ | `invalidateBySlug(qc, appSlug, dataSourceSlug)` | Every cached detail for a single app+slug pair (any `expand`) |
1105
+ | `invalidateForAppSlug(qc, appSlug)` | All list queries scoped to an app slug |
1106
+ | `invalidateForAppId(qc, appId)` | All list queries scoped to an app ID |
1107
+
1108
+ ```ts
1109
+ import { useMutation, useQueryClient } from '@tanstack/react-query';
1110
+
1111
+ const queryClient = useQueryClient();
1112
+
1113
+ const updateSchema = useMutation({
1114
+ mutationFn: (changes) => api.patchSchema(changes),
1115
+ onSuccess: () => queries.invalidateBySlug(queryClient, 'crm', 'contacts')
1116
+ });
1117
+ ```
1118
+
1119
+ #### `dataSourceKeys` registry
1120
+
1121
+ The same query keys used internally are exported as `dataSourceKeys` (and as `queries.keys`). Use them when you need to read or set cache entries directly:
1122
+
1123
+ ```ts
1124
+ import { dataSourceKeys } from '@kivacore/app-utils/query';
1125
+
1126
+ queryClient.setQueryData(
1127
+ dataSourceKeys.bySlug('crm', 'contacts', { expand: 'fields' }),
1128
+ optimisticData
1129
+ );
1130
+ ```
1131
+
1132
+ The key shape is stable: every key starts with `['docyrus', 'data-sources', ...]`, so `queryClient.invalidateQueries({ queryKey: dataSourceKeys.all() })` clears everything this module owns.
1133
+
1134
+ ---
1135
+
1136
+ ## API Reference
1137
+
1138
+ ### `getTenantPreferences(client)`
1139
+
1140
+ Fetches tenant preferences from the Docyrus API.
1141
+
1142
+ ```ts
1143
+ import { getTenantPreferences } from '@kivacore/app-utils';
1144
+
1145
+ const preferences = await getTenantPreferences(apiClient);
1146
+ // { date_format: 'd.m.Y', decimal_separator: ',', thousand_separator: '.', ... }
1147
+ ```
1148
+
1149
+ **Parameters:**
1150
+ - `client` — A configured `RestApiClient` from `@kivacore/api-client`
1151
+
1152
+ **Returns:** `Promise<TenantPreferences>`
1153
+
1154
+ ---
1155
+
1156
+ ### `createDateUtils(config)`
1157
+
1158
+ Creates date formatting utilities configured from tenant preferences.
1159
+
1160
+ ```ts
1161
+ import { createDateUtils } from '@kivacore/app-utils';
1162
+
1163
+ const dateUtils = createDateUtils({
1164
+ preferences,
1165
+ userTimezone: 'Europe/Istanbul', // defaults to 'UTC'
1166
+ locale: 'tr' // day/month names; defaults to English
1167
+ });
1168
+ ```
1169
+
1170
+ `locale` sets the language of day and month names (`l`, `D`, `F`, `M`), so
1171
+ `j F Y` renders as `31 Aralık 2026` for `tr`. It accepts `tr`, `tr_TR` or
1172
+ `tr-TR`; an unknown tag falls back to English. AM/PM (`A`, `a`) and ordinal
1173
+ suffixes (`S`) stay English.
1174
+
1175
+ #### `dateUtils.formatDate(date, options?)`
1176
+
1177
+ Formats a date using the tenant's `date_format` (default `Y-m-d`).
1178
+
1179
+ ```ts
1180
+ dateUtils.formatDate('2024-06-15'); // uses tenant format
1181
+ dateUtils.formatDate(new Date(), { format: 'd/m/Y' }); // custom format
1182
+ dateUtils.formatDate('2024-06-15', { timezone: 'US/Eastern' }); // custom timezone
1183
+ ```
1184
+
1185
+ #### `dateUtils.formatDateTime(date, options?)`
1186
+
1187
+ Formats a datetime using the tenant's `date_time_format` (default `Y-m-d H:i:s`). Handles timezone-aware parsing — appends `Z` to strings without a timezone suffix.
1188
+
1189
+ ```ts
1190
+ dateUtils.formatDateTime('2024-06-15T14:30:00'); // parses as UTC
1191
+ dateUtils.formatDateTime('2024-06-15T14:30:00+03:00'); // respects offset
1192
+ ```
1193
+
1194
+ #### `dateUtils.formatDateLong(date, options?)`
1195
+
1196
+ Formats a date using the tenant's `long_date_format` (default `Y-m-d H:i:s`).
1197
+
1198
+ #### `dateUtils.toUserTimezone(date)`
1199
+
1200
+ Converts a date to the user's timezone without formatting.
1201
+
1202
+ ```ts
1203
+ const localDate = dateUtils.toUserTimezone('2024-06-15T12:00:00Z');
1204
+ ```
1205
+
1206
+ **Format strings** use PHP date format syntax (via `php-date-formatter`):
1207
+ | Token | Output | Example |
1208
+ |-------|--------|---------|
1209
+ | `Y` | 4-digit year | `2024` |
1210
+ | `m` | Month (01-12) | `06` |
1211
+ | `d` | Day (01-31) | `15` |
1212
+ | `H` | Hours 24h (00-23) | `14` |
1213
+ | `i` | Minutes (00-59) | `30` |
1214
+ | `s` | Seconds (00-59) | `00` |
1215
+ | `D` | Short day name | `Sat` |
1216
+ | `l` | Full day name | `Saturday` |
1217
+ | `F` | Full month name | `June` |
1218
+
1219
+ ---
1220
+
1221
+ ### `createNumberUtils(config)`
1222
+
1223
+ Creates number formatting utilities configured from tenant preferences.
1224
+
1225
+ ```ts
1226
+ import { createNumberUtils } from '@kivacore/app-utils';
1227
+
1228
+ const numberUtils = createNumberUtils({ preferences });
1229
+ ```
1230
+
1231
+ #### `numberUtils.formatNumber(value, options?)`
1232
+
1233
+ Formats a number using the tenant's locale, separators, and precision.
1234
+
1235
+ ```ts
1236
+ numberUtils.formatNumber(1234567.89);
1237
+ // With tenant settings: thousand_separator='.', decimal_separator=',', decimal_precision=2
1238
+ // → '1.234.567,89'
1239
+
1240
+ // Override per call:
1241
+ numberUtils.formatNumber(1234.5, {
1242
+ decimalPrecision: 3,
1243
+ decimalSeparator: '.',
1244
+ thousandSeparator: ','
1245
+ });
1246
+ // → '1,234.500'
1247
+ ```
1248
+
1249
+ **Formatting logic:**
1250
+ - If both `thousandSeparator` and `decimalSeparator` are set → manual formatting with regex
1251
+ - Otherwise → `toLocaleString()` with the tenant's `locale`
1252
+ - Pass `thousandSeparator: ''` to disable grouping
1253
+
1254
+ ---
1255
+
1256
+ ### `formatNumberToWords(value, options?)`
1257
+
1258
+ Converts a number to words with currency labels. Standalone function (no config needed).
1259
+
1260
+ ```ts
1261
+ import { formatNumberToWords } from '@kivacore/app-utils';
1262
+
1263
+ formatNumberToWords(1234.56);
1264
+ // → 'BİNİKİYÜZOTUZDÖRT TÜRK LİRASI ELLİALTI KURUŞ'
1265
+
1266
+ formatNumberToWords(1234.56, { lang: 'EN', currency: 'USD' });
1267
+ // → 'ONE THOUSAND TWO HUNDRED THIRTY FOUR DOLAR FIFTY SIX CENT'
1268
+
1269
+ formatNumberToWords(1234.56, { lang: 'TR', currency: 'EUR', useSpaces: true });
1270
+ // → 'BİN İKİ YÜZ OTUZ DÖRT EURO ELLİ ALTI CENT'
1271
+ ```
1272
+
1273
+ **Options:**
1274
+ | Option | Type | Default | Description |
1275
+ |--------|------|---------|-------------|
1276
+ | `lang` | `'TR' \| 'EN'` | `'TR'` | Word language |
1277
+ | `currency` | `'TRY' \| 'EUR' \| 'USD' \| 'GBP' \| 'JPY'` | `'TRY'` | Currency labels |
1278
+ | `useSpaces` | `boolean` | `false` | Add spaces between word groups |
1279
+
1280
+ ---
1281
+
1282
+ ### Duration Formatters
1283
+
1284
+ Standalone functions for formatting durations (in seconds).
1285
+
1286
+ ```ts
1287
+ import {
1288
+ formatDurationAsTime,
1289
+ formatDurationAsHours,
1290
+ formatDurationAsWords
1291
+ } from '@kivacore/app-utils';
1292
+
1293
+ formatDurationAsTime(5461); // → '01:31'
1294
+ formatDurationAsHours(5461); // → '1.52'
1295
+ formatDurationAsHours(5461, 1); // → '1.5'
1296
+ formatDurationAsWords(5461); // → '1 hr 31 mins'
1297
+ formatDurationAsWords(45); // → '0 mins'
1298
+ ```
1299
+
1300
+ ---
1301
+
1302
+ ### `createTemplateEngine(config?)`
1303
+
1304
+ Creates a template engine combining Handlebars (with async support) and JSONata formula evaluation.
1305
+
1306
+ ```ts
1307
+ import { createTemplateEngine } from '@kivacore/app-utils';
1308
+
1309
+ const engine = createTemplateEngine({
1310
+ dateUtils, // from createDateUtils()
1311
+ numberUtils, // from createNumberUtils()
1312
+ user: currentUser, // injected as metadata.user in formulas
1313
+ extraJsonataBindings: { hasRole } // additional JSONata bindings
1314
+ });
1315
+ ```
1316
+
1317
+ Each `createTemplateEngine` call creates an **isolated Handlebars instance**, so multiple engines (e.g., different tenants) won't conflict.
1318
+
1319
+ #### `engine.compileTpl(templateString)`
1320
+
1321
+ Preprocesses and compiles a Handlebars template. Returns an async function.
1322
+
1323
+ ```ts
1324
+ const tpl = engine.compileTpl('Hello {{name}}, total: {{formatNumber amount}}');
1325
+ const html = await tpl({ name: 'John', amount: 1234.5 });
1326
+ // → 'Hello John, total: 1.234,50'
1327
+ ```
1328
+
1329
+ **Template preprocessing:**
1330
+ 1. `{{formula $expr}}` → wraps expression in quotes for the formula helper
1331
+ 2. `{{#if $expr}}` → converts to `{{#if (formula '$expr')}}` for JSONata evaluation
1332
+ 3. `{{<content}}` → strips HTML tags from inline content
1333
+
1334
+ #### `engine.compileFormula(expression, data?)`
1335
+
1336
+ Evaluates a JSONata expression with all helpers bound. Injects `metadata.user` from config.
1337
+
1338
+ ```ts
1339
+ const total = await engine.compileFormula('$sum(items.price)', { items });
1340
+ const greeting = await engine.compileFormula('"Hello " & name', { name: 'World' });
1341
+ ```
1342
+
1343
+ #### `engine.jsonataHelpers`
1344
+
1345
+ Direct access to the full bindings object (all built-in helpers + `extraJsonataBindings`).
1346
+
1347
+ ---
1348
+
1349
+ ### Handlebars Helpers
1350
+
1351
+ The following helpers are registered automatically when using `compileTpl`:
1352
+
1353
+ #### Formatting Helpers
1354
+
1355
+ | Helper | Usage | Description |
1356
+ |--------|-------|-------------|
1357
+ | `formatDate` | `{{formatDate dateField format="d/m/Y"}}` | Format date (uses tenant `date_format` by default) |
1358
+ | `formatDateTime` | `{{formatDateTime dateField}}` | Format datetime (uses tenant `date_time_format`) |
1359
+ | `formatNumber` | `{{formatNumber amount decimalPrecision=2}}` | Format number with tenant settings |
1360
+ | `formatNumberToWords` | `{{formatNumberToWords amount lang="TR" currency="TRY"}}` | Number to words |
1361
+ | `formatDurationAsTime` | `{{formatDurationAsTime seconds}}` | Duration as `HH:MM` |
1362
+ | `formatDurationAsWords` | `{{formatDurationAsWords seconds}}` | Duration as `X hrs Y mins` |
1363
+ | `formatDurationAsHours` | `{{formatDurationAsHours seconds decimalPrecision=1}}` | Duration as decimal hours |
1364
+
1365
+ #### Logic & Data Helpers
1366
+
1367
+ | Helper | Usage | Description |
1368
+ |--------|-------|-------------|
1369
+ | `formula` | `{{formula "$sum(items.price)"}}` or `{{#formula}}$expr{{/formula}}` | Evaluate JSONata expression |
1370
+ | `path` | `{{#path "$.items[0]"}}...{{/path}}` | JSONPath query — sets context to result |
1371
+ | `repeat` | `{{#repeat 5}}...{{/repeat}}` | Repeat block N times |
1372
+ | `sum` | `{{sum items "price"}}` or `{{sum 1 2 3}}` | Sum array field or values |
1373
+ | `json` | `{{json data}}` | Pretty-print JSON |
1374
+
1375
+ ---
1376
+
1377
+ ### JSONata Helpers
1378
+
1379
+ All helpers are available inside `compileFormula` and `{{formula}}` blocks. They are also exported as `jsonataHelpers` for direct use.
1380
+
1381
+ ```ts
1382
+ import { jsonataHelpers } from '@kivacore/app-utils';
1383
+ ```
1384
+
1385
+ #### Date Functions (date-fns, null-safe wrapped)
1386
+
1387
+ All date functions accept strings or Date objects. Returns `null` for null/empty input.
1388
+
1389
+ **Formatting:**
1390
+ `formatDate`, `formatDistance`, `formatDistanceStrict`, `formatDistanceToNow`, `formatDistanceToNowStrict`, `formatDuration`, `formatISO`, `formatRelative`
1391
+
1392
+ **Arithmetic:**
1393
+ `addYears`, `addMonths`, `addWeeks`, `addDays`, `addHours`, `addMinutes`, `addSeconds`, `addMilliseconds`, `subYears`, `subMonths`, `subWeeks`, `subDays`, `subHours`, `subMinutes`, `subSeconds`, `subMilliseconds`
1394
+
1395
+ **Comparison:**
1396
+ `isAfter`, `isBefore`, `isDatesEqual`, `isPast`
1397
+
1398
+ **Difference:**
1399
+ `differenceInYears`, `differenceInMonths`, `differenceInWeeks`, `differenceInDays`, `differenceInHours`, `differenceInMinutes`, `differenceInSeconds`, `differenceInBusinessDays`, `differenceInBusinessDaysCustom`
1400
+
1401
+ **Period boundaries:**
1402
+ `startOfDay`, `startOfMonth`, `startOfWeek`, `startOfToday`, `startOfQuarter`, `endOfDay`, `endOfMonth`, `endOfWeek`, `endOfToday`, `endOfQuarter`
1403
+
1404
+ #### `differenceInBusinessDaysCustom(startDate, endDate, options?)`
1405
+
1406
+ Calculates business days with configurable work hours and lunch breaks.
1407
+
1408
+ ```jsonata
1409
+ $differenceInBusinessDaysCustom(startDate, endDate, {
1410
+ "workStartHour": 9,
1411
+ "workEndHour": 18,
1412
+ "lunchBreakHours": 1,
1413
+ "lunchStartHour": 12.5,
1414
+ "lunchEndHour": 13.5,
1415
+ "includePartialDays": true
1416
+ })
1417
+ ```
1418
+
1419
+ #### Number / Format Functions
1420
+
1421
+ | Function | Signature | Description |
1422
+ |----------|-----------|-------------|
1423
+ | `formatDecimal` | `(number, precision?, decSep?, thousandSep?)` | Format decimal with separators |
1424
+ | `formatMoney` | `(number, precision?, decSep?, thousandSep?, currency?, position?)` | Format as currency |
1425
+ | `percentage` | `(value, total, decimals)` | Calculate percentage |
1426
+ | `truncate` | `(text, limit)` | Truncate with `...` |
1427
+ | `join` | `(array, separator)` | Join array to string |
1428
+ | `formatDurationInSeconds` | `(seconds)` | Human-readable duration via date-fns |
1429
+
1430
+ #### String Functions
1431
+
1432
+ | Function | Signature | Description |
1433
+ |----------|-----------|-------------|
1434
+ | `sha256` | `(message)` | SHA-256 hash (async) |
1435
+ | `ascii` | `(str)` | Strip accents and non-ASCII characters |
1436
+ | `slug` | `(str, separator?)` | URL-friendly slug |
1437
+ | `extractNameFromEmail` | `(email, fallback?)` | Extract name from email (e.g. `john.doe@...` → `John Doe`) |
1438
+ | `filterEmpty` | `(array)` | Remove null/undefined/empty from array |
1439
+ | `padLeft` | `(value, length, char?)` | Left-pad string |
1440
+ | `padRight` | `(value, length, char?)` | Right-pad string |
1441
+ | `ifNull` | `(value, alternative)` | Null coalescing |
1442
+ | `objectToString` | `(object)` | Convert object to `key:value` string |
1443
+ | `startsWith` | `(haystack, needle)` | String starts with |
1444
+ | `endsWith` | `(haystack, needle)` | String ends with |
1445
+ | `includes` | `(haystack, needle)` | String includes (null-safe) |
1446
+
1447
+ #### Equality / DB Helpers
1448
+
1449
+ | Function | Signature | Description |
1450
+ |----------|-----------|-------------|
1451
+ | `isEqual` | `(a, b)` | Deep equality — compares by `id`, Date, JSON, or strict |
1452
+ | `isEqualOrContained` | `(needle, haystack)` | Check if value is equal to or contained in array |
1453
+ | `isNotEqualOrContained` | `(needle, haystack)` | Negation of `isEqualOrContained` |
1454
+ | `getDbValue` | `(value)` | Extract `id` from object or first item of array |
1455
+
1456
+ ## TypeScript
1457
+
1458
+ All types are exported:
1459
+
1460
+ ```ts
1461
+ import type {
1462
+ TenantPreferences,
1463
+ DateUtils,
1464
+ DateUtilsConfig,
1465
+ FormatOptions,
1466
+ NumberUtils,
1467
+ NumberUtilsConfig,
1468
+ NumberFormatOptions,
1469
+ NumberToWordsOptions,
1470
+ NumberWordLang,
1471
+ CurrencyCode,
1472
+ TemplateEngine,
1473
+ TemplateEngineConfig,
1474
+ AppConfig,
1475
+ UpsertAppConfigBody,
1476
+ AppConfigClient,
1477
+ UserAppConfig,
1478
+ UpsertUserAppConfigBody,
1479
+ UserAppConfigClient,
1480
+ DataView,
1481
+ CreateDataViewBody,
1482
+ UpdateDataViewBody,
1483
+ ListDataViewsParams,
1484
+ DataViewClient,
1485
+ DataForm,
1486
+ CreateDataFormBody,
1487
+ UpdateDataFormBody,
1488
+ DataFormClient,
1489
+ DataSourceExpand,
1490
+ DataSourceField,
1491
+ DataSource,
1492
+ DataSourceApp,
1493
+ DataSourceListParams,
1494
+ DataSourceClient,
1495
+ Brand,
1496
+ BrandColorScheme,
1497
+ BrandActiveVoicePreference,
1498
+ BrandDirectness,
1499
+ BrandEmojiPolicy,
1500
+ BrandFormalityLevel,
1501
+ BrandMetricEmphasis,
1502
+ BrandSlideDensity,
1503
+ BrandIllustrationStyle,
1504
+ CreateBrandBody,
1505
+ UpdateBrandBody,
1506
+ FetchBrandFromWebsiteResponse,
1507
+ BrandClient,
1508
+ MicrosoftIdentityPayload,
1509
+ GoogleIdentityPayload,
1510
+ UserIdentityClient,
1511
+ AppUtilsConfig
1512
+ } from '@kivacore/app-utils';
1513
+ ```
1514
+
1515
+ ## License
1516
+
1517
+ MIT