@dxtmisha/functional-basic 1.11.0 → 1.11.2

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.11.1] - 2026-10-04
6
+
7
+ ### Changed
8
+ - **`ErrorCenter`**:
9
+ - Implemented lazy singleton initialization for `ErrorCenter.getItem()`, avoiding premature top-level module instantiation of `ErrorCenterInstance` and improving tree-shaking and SSR execution safety.
10
+ - **Tree-Shaking & Top-Level Purity**:
11
+ - Replaced dynamic regular expressions (`new RegExp(...)`) with static regex literals in `addTagHighlightMatch` (`/___HIGHLIGHT_START___|___HIGHLIGHT_END___/g`) and `applyTemplate` (`/%(d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v)/g`) to eliminate module initialization side effects.
12
+ - Replaced dynamic `random()`-based tag generation in `addTagHighlightMatch` with static tags (`___HIGHLIGHT_START___` / `___HIGHLIGHT_END___`).
13
+ - Simplified `Icons.getUrlGlobal()` by removing unused `Api` import and redundant localhost ternary check.
14
+ - Extracted `API_CACHE_DEFAULT_STEP_AGE_CLEAR_OLD` constant in `ApiCache` for cache cleanup intervals.
15
+ - **AI Type Definitions**:
16
+ - Applied `// ai-none` annotations across secondary class files to optimize AI context window and documentation size.
17
+
5
18
  ## [1.11.0] - 2026-09-07
6
19
 
7
20
  ### Added
package/ai-description.md CHANGED
@@ -1,8 +1,8 @@
1
- This package provides a comprehensive isomorphic toolkit containing core services, state managers, and utilities for both browser and server-side runtimes. It includes integrated modules for HTTP requests with SSR hydration and caching, geographic localization, date and measurement unit formatting, dictionary translations, persistent storage, and URL state synchronization. An AI assistant should consult this package when implementing API integration layers, configuring SEO and social metadata, managing multi-locale formatting, or coordinating client-server storage and DOM utilities.
1
+ This package provides a comprehensive isomorphic foundational toolkit containing utilities for API communication, request lifecycle handling, storage management, and DOM manipulation. It includes robust internationalization and localization systems for date-time calculations, units, currencies, phone masks, and multi-language translations, alongside SEO meta tag generation and URL state synchronization. An AI assistant should study this package when implementing client-server data fetching with SSR hydration, browser storage persistence, localized data formatting, text search matching, or DOM event lifecycle control.
2
2
 
3
- Key Capabilities: API Client, Request Caching, SSR Hydration, API Mocking, Error Management, Geographic Localization, Locale Formatting, Translation Management, Phone Masking, Unit Conversion, DateTime Localization, Cookie Management, Server Storage, Browser Storage, URL State Sync, Broadcast Messaging, SEO Meta Management, Open Graph Metadata, Twitter Card Management, DOM Event Handling, Search List Filtering, Text Highlighting, Clipboard Utilities, Global Loading State
3
+ Key Capabilities: HTTP Client, SSR Hydration, API Caching, Request Interceptors, Cross-Tab Messaging, Cookie Management, Local Storage, Session Storage, In-Memory Caching, Date Manipulation, Locale Formatting, Currency Formatting, Unit Conversion, Phone Number Masking, Flag Icons, Translation Management, Meta Tag Management, Open Graph SEO, Twitter Cards, URL Query Management, URL Hash Routing, Search Highlighting, List Sorting, DOM Event Management, Global Loading State, Resumable Timer, Clipboard Utilities, Image Resizing, Scroll Control, Type Checking Utilities
4
4
  ## Mandatory Rules
5
5
  You MUST evaluate whether your task relates to any of the following topics (even if not working directly with this package). If related material is present, you are strictly obligated to read and study the corresponding file before proceeding:
6
- - 'node_modules/@dxtmisha/functional-basic/ai-resources/api-reference.md': API reference and code examples for HTTP client, storage, localization, DOM, and utility functions.
6
+ - 'node_modules/@dxtmisha/functional-basic/ai-resources/api-reference.md': Provides usage guidelines and API references for HTTP requests, caching, storage, localization, and DOM utility functions.
7
7
  - 'node_modules/@dxtmisha/functional-basic/ai-resources/design-config.md': Rules and schema for configuring design systems, TypeScript declaration scanning, AI generation, and package settings.
8
8
  - 'node_modules/@dxtmisha/functional-basic/ai-resources/error-center.md': Standards and APIs for centralized error handling, routing exceptions via ErrorCenter without direct console logging.
@@ -15,7 +15,7 @@
15
15
  "uri": "@dxtmisha/functional-basic/ai-resources/api-reference.md",
16
16
  "name": "Functional Basic API Reference (@dxtmisha/functional-basic)",
17
17
  "mimeType": "text/markdown",
18
- "description": "API reference and code examples for HTTP client, storage, localization, DOM, and utility functions."
18
+ "description": "Provides usage guidelines and API references for HTTP requests, caching, storage, localization, and DOM utility functions."
19
19
  },
20
20
  {
21
21
  "uri": "@dxtmisha/functional-basic/ai-resources/design-config.md",
@@ -12,6 +12,74 @@ const updated = await Api.post<User>({ path: 'profile', request: { name: 'New' }
12
12
  await ApiCache.set('k', { a: 1 }, 60000); const cache = await ApiCache.get<{a: number}>('k');
13
13
  ```
14
14
 
15
+ ### Error Responses & Return Types (`ApiData<T>`)
16
+
17
+ When an error occurs during an API call, `Api` behaves differently depending on whether it is an HTTP response error or a network/runtime failure:
18
+
19
+ #### 1. HTTP Errors (HTTP status >= 400)
20
+ `Api.request`, `Api.get`, `Api.post`, etc. do **NOT** throw an exception on HTTP errors (e.g. 400, 401, 403, 404, 500). Instead, they return the parsed response wrapped as `ApiData<T>` (`ApiDataItem<T>`), enriched with status and error metadata:
21
+
22
+ ```typescript
23
+ import { Api, ApiError, ApiMethodItem } from '@dxtmisha/functional-basic';
24
+
25
+ // Optional: register known error patterns in advance
26
+ ApiError.add({
27
+ url: 'users/login',
28
+ method: ApiMethodItem.post,
29
+ code: 'INVALID_CREDENTIALS',
30
+ message: 'Invalid email or password'
31
+ });
32
+
33
+ // Response returns ApiDataItem<T> with error metadata attached:
34
+ const response = await Api.get<User>({ path: 'users/999' });
35
+
36
+ // 1. Response status metadata: `statusObject` (ApiStatusItem)
37
+ response.statusObject?.status; // number - HTTP status code (e.g. 404, 500)
38
+ response.statusObject?.statusText; // string - HTTP status text (e.g. "Not Found")
39
+ response.statusObject?.lastStatus; // ApiStatusType ('error' | 'warning' | 'info' | 'success')
40
+ response.statusObject?.lastCode; // string | undefined - Server error code
41
+ response.statusObject?.lastMessage; // string | undefined - Error message or status text
42
+ response.statusObject?.error; // string | undefined - Error string if exception occurred
43
+
44
+ // 2. Structured error helper: `errorObject` (ApiErrorItem)
45
+ // Available when `initError: true` (default) and matching error found or response evaluated
46
+ response.errorObject?.getCode(); // string | undefined - Matched error code (e.g. 'INVALID_CREDENTIALS')
47
+ response.errorObject?.getMessage(); // string | undefined - Evaluated error message
48
+ response.errorObject?.getStatus(); // number - HTTP status code (e.g. 404)
49
+ response.errorObject?.getResponse(); // Response - Raw Fetch Response object
50
+ response.errorObject?.getMethod(); // ApiMethodItem - Request HTTP method
51
+
52
+ // 3. Extracted metadata fields (automatically merged if returned by backend):
53
+ response.success; // boolean - false on error
54
+ response.code; // string | number - Error code from backend
55
+ response.message; // string - Backend error message
56
+ response.error; // { code?: string | number, message?: string }
57
+
58
+ // 4. Global status inspection for the last executed request:
59
+ const status = Api.getStatus(); // ApiStatus instance
60
+ status.getStatus(); // number (e.g. 404)
61
+ status.getStatusType(); // 'error'
62
+ status.getMessage(); // Error message string
63
+ ```
64
+
65
+ #### 2. Network & Runtime Errors (Throws Exception)
66
+ Network failures (connection refused, DNS failure, offline mode, timeout via `AbortController`) throw an exception and must be handled with `try / catch`:
67
+
68
+ ```typescript
69
+ try {
70
+ await Api.get({ path: 'users', timeout: 5000 });
71
+ } catch (error) {
72
+ // Network failures, TimeoutError, or Offline
73
+ const lastError = Api.getStatus().getError(); // String error recorded in ApiStatus
74
+ }
75
+ ```
76
+
77
+ #### 3. Error Routing & Options
78
+ - **`ErrorCenter` Integration**: HTTP errors (status >= 400) and network exceptions are automatically dispatched to `ErrorCenter.on(...)` (groups: `'api'`, `'api-server'`).
79
+ - **`hideError?: boolean`**: Set to `true` in `apiFetch` configuration to suppress dispatching errors to `ErrorCenter`.
80
+ - **`initError?: boolean`**: Set to `false` in `apiFetch` configuration to disable extracting `ApiErrorItem` (`errorObject`).
81
+
82
+
15
83
  ## Storage & State
16
84
  ```typescript
17
85
  import { DataStorage, CookieStorage, Cookie, ServerStorage } from '@dxtmisha/functional-basic';