@dxtmisha/functional-basic 1.8.1 → 1.8.3

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/ai-description.md CHANGED
@@ -1,7 +1,5 @@
1
- An isomorphic TypeScript utility framework designed to provide core runtime services for web applications across browser and Server-Side Rendering (SSR) environments. Its primary functions include wrapping the Fetch API with request/response caching and hydration, state management isolated by request context, comprehensive internationalization (i18n, unit conversions, phone masking, date/number formatting), SEO meta tag synchronization, reactive URL hash and query parameter tracking, managed DOM event lifecycle handling, in-memory list search with string highlighting, and centralized error handling.
2
-
3
- Api and ApiInstance manage Fetch-based HTTP communication featuring retries, custom headers, preparation hooks, and mock response emulation. ApiCache handles client and server data caching. ServerStorage and DataStorage provide isomorphic request-isolated state retention and browser storage abstraction with SSR hydration support. CookieStorage and Cookie manage client/server cookies consistently. Geo, GeoIntl, GeoPhone, GeoUnit, and Datetime form a localization engine handling Intl formatting, country phone masking, unit conversions, and date calculations. Translate and TranslateInstance manage synchronous and asynchronous translation batching. Query, QueryInstance, Hash, and HashInstance offer reactive, watchable interfaces for URL query strings and hash parameters. EventItem wraps DOM event listeners with ResizeObserver and requestAnimationFrame scroll optimizations. SearchList provides in-memory text search, regex generation, and matching string highlights. Meta, MetaOg, and MetaTwitter manage standard HTML, Open Graph, and Twitter Card metadata tags in the DOM or as HTML strings. ErrorCenter provides centralized error tracking and routing.
4
-
5
- Studying ai-types.md is mandatory when implementing or typing API configurations (ApiFetch, ApiConfig, ApiHydrationItem), setting up application error handling (ErrorCenterCauseItem, ErrorCenterHandlerList), configuring complex list transformations (FormattersOptionsList, FormattersType), managing geographic and phone mask parameters (GeoItem, GeoDate, GeoPhoneValue), defining search parameters (SearchOptions, SearchColumns), configuring SEO meta types (MetaOpenGraphTag, MetaTwitterCard), or working with core generic utility types (ArrayToItem, NormalOrPromise, ObjectOrArray, NumberOrString).
6
-
7
- The library operates as a foundational layer directly above native browser and Node.js runtime APIs (Fetch API, Intl API, DOM Window/Element interfaces, ResizeObserver, BroadcastChannel, Web Storage). It integrates with frontend SSR frameworks (such as Vue, React, Nuxt, or Next.js) by decoupling server-side request state via ServerStorage and generating safe client hydration scripts (getElementSafeScript) to prevent client-server hydration mismatches.
1
+ This library is an isomorphic utility framework designed for full-stack JavaScript and TypeScript applications, providing unified abstractions for API data fetching, SSR hydration, state persistence, internationalization, DOM event management, and SEO metadata. The API and Network module manages HTTP requests via Fetch with automated retries, hook-based request preparation, response caching, SSR client hydration, error storage matching, and mock response emulation. The Storage module delivers cross-environment persistence across browser cookies, local or session storage, and request-isolated server rendering contexts. The Localization and Formatting module handles locale detection, phone number masking, localized unit conversions, translation retrieval, and date, number, or plural formatting using native Intl APIs. The DOM, Events, and Navigation module offers memory-safe event listening with automatic DOM removal checks, reactive URL query and hash state tracking, inter-tab broadcast messaging, global loading state coordination, and meta tag management for OpenGraph and Twitter cards. The Search and Utilities module facilitates in-memory multi-column searching with match highlighting, centralized error logging, resumable timers, and type-safe array or object transformations. Studying type definitions in ai-types.md is mandatory when constructing strongly typed API fetch parameters, handling custom response wrappers, defining error storage criteria, configuring complex list formatters, or supplying generic type arguments to search, storage, and event handlers. The library connects as a foundational utility layer bridging client-side UI frameworks with server-side rendering environments and REST backend endpoints.
2
+ ## Mandatory Rules
3
+ Read the corresponding file if your task relates to:
4
+ - 'node_modules/@dxtmisha/functional-basic/ai-prompts/api-reference.md': HTTP client, caching, storage management, geolocation, localization, DOM events, and general utilities
5
+ - 'node_modules/@dxtmisha/functional-basic/ai-prompts/coding-standards.md': Class structure, naming and typing standards, SSR safety, and primitive helper functions
package/ai-doc.md CHANGED
@@ -1,65 +1 @@
1
- # @dxtmisha/functional-basic Reference
2
-
3
- Framework-agnostic utility library. **Vue developers MUST search `@dxtmisha/functional` first**; use this ONLY if no reactive/Vue-specific analog exists.
4
-
5
- ## 1. Coding Standards & Conventions
6
- - **Class Structure**: Properties/Variables (`public`->`protected`->`private`) -> Constructor -> Public Methods (Getters -> Setters -> Core actions) -> Protected Methods -> Private Methods.
7
- - **Style/Types**: `PascalCase` classes, `camelCase` methods/props, `UPPER_SNAKE_CASE` constants. No `any` (use `unknown`/generics). Explicit return types for ALL methods. Export all interfaces. Type files: `*Types.ts`. Use `@effect/schema` for schemas.
8
- - **SSR Safety**: Isomorphic code. Do NOT store request state in globals. Use `isDomRuntime()` before `window`/`document`. Use `ServerStorage.get('key', () => new Class())` for request-isolated singletons.
9
- - **Utility & Primitive Functions**: ALWAYS use primitive helper functions from this package (e.g. `isFunction`, `executeFunction`, `isFilled`, `isObject`, `isString`, `isArray`, etc.) instead of writing custom inline checks or conditions.
10
-
11
- ## 2. API Reference & Examples
12
-
13
- ### HTTP Client & Caching
14
- ```typescript
15
- import { Api, ApiCache } from '@dxtmisha/functional-basic';
16
- Api.setOrigin('https://api.example.com'); Api.setUrl('/api/v1'); Api.setRequestDefault({ client: 'web' });
17
- Api.setHeaders(() => ({ Authorization: `Bearer ${localStorage.getItem('token') || ''}` }));
18
- Api.setPreparation(async (opts) => { if (opts.auth) opts.headers['X-Auth'] = '1'; });
19
- Api.setEnd(async (res) => res.status === 401 ? { reset: true } : {});
20
- const users = await Api.request<User[]>('users'); // GET
21
- const updated = await Api.post<User>({ path: 'profile', request: { name: 'New' } });
22
- await ApiCache.set('k', { a: 1 }, 60000); const cache = await ApiCache.get<{a: number}>('k');
23
- ```
24
-
25
- ### Storage & State
26
- ```typescript
27
- import { DataStorage, CookieStorage, Cookie, ServerStorage } from '@dxtmisha/functional-basic';
28
- DataStorage.setPrefix('app_');
29
- const ls = new DataStorage<{ id: string }>('user', false); ls.set({ id: '1' }); ls.get({ id: '0' }); ls.remove();
30
- CookieStorage.set('t', 'dark', { age: 31536000, secure: true }); CookieStorage.get<string>('t', 'light');
31
- const c = new Cookie<string>('auth'); c.set('xyz', { secure: true }); c.get();
32
- const srv = ServerStorage.get('svc', () => new Svc()); // SSR isolated
33
- ```
34
-
35
- ### Geolocation, Formatting & Localization
36
- ```typescript
37
- import { Geo, GeoIntl, GeoFlag, GeoPhone } from '@dxtmisha/functional-basic';
38
- const country = Geo.getCountry(); const lang = Geo.getLanguage(); Geo.set('en-US');
39
- const intl = new GeoIntl('en-US');
40
- intl.number(1234.5); intl.currency(99, 'USD'); intl.sizeFile(1024*1024); intl.date(new Date(), 'date');
41
- intl.relative(new Date(Date.now() - 3600000)); intl.plural(3, 'apple|apples');
42
- const flag = new GeoFlag().getFlag('VN');
43
- const phone = GeoPhone.getByPhone('+84900000000'); const mask = GeoPhone.toMask('84900000000');
44
- ```
45
-
46
- ### DOM, Events & Helpers
47
- ```typescript
48
- import { EventItem, goScrollSmooth, writeClipboardData, getClipboardData, SearchList, Formatters, FormattersType, isFilled, isFunction, executeFunction, isDomRuntime, copyObject, anyToString, sleep } from '@dxtmisha/functional-basic';
49
-
50
- // Safe Events (leak-proof)
51
- const listener = new EventItem(window, 'click', console.log, { passive: true }); listener.start(); listener.stop();
52
-
53
- // DOM / Clipboard
54
- goScrollSmooth(document.getElementById('t')); await writeClipboardData('txt'); await getClipboardData();
55
-
56
- // Search & Formatters
57
- const res = new SearchList([{ n: 'John' }], ['n'], 'jo').to(); // Highlights matches
58
- const fmt = new Formatters({ p: { type: FormattersType.currency, options: 'USD' } }, { p: 12 }).to();
59
-
60
- // General
61
- isFilled([]); // false (strings, arrays, objects, numbers, booleans)
62
- executeFunction(callbackOrValue, arg1); // Executes callback if function, or returns value as is
63
- isFunction(val); // Type-guard for functions
64
- isDomRuntime(); const cloned = copyObject({ a: 1 }); const str = anyToString(123); await sleep(500);
65
- ```
1
+ Framework-agnostic utility library. **Vue developers MUST search `@dxtmisha/functional` first**; use this ONLY if no reactive/Vue-specific analog exists.
package/ai-mcp.json ADDED
@@ -0,0 +1,14 @@
1
+ [
2
+ {
3
+ "uri": "@dxtmisha/functional-basic/ai-prompts/api-reference.md",
4
+ "name": "API Reference",
5
+ "mimeType": "text/markdown",
6
+ "description": "Comprehensive API reference and code examples for the functional-basic library, covering HTTP requests, state storage, localization, DOM manipulation, and utility helpers."
7
+ },
8
+ {
9
+ "uri": "@dxtmisha/functional-basic/ai-prompts/coding-standards.md",
10
+ "name": "Coding Standards",
11
+ "mimeType": "text/markdown",
12
+ "description": "Defines class structure ordering, TypeScript styling and typing conventions, isomorphic SSR safety rules, and standard primitive helper function usage."
13
+ }
14
+ ]
@@ -0,0 +1,55 @@
1
+ # API Reference & Examples
2
+
3
+ ## HTTP Client & Caching
4
+ ```typescript
5
+ import { Api, ApiCache } from '@dxtmisha/functional-basic';
6
+ Api.setOrigin('https://api.example.com'); Api.setUrl('/api/v1'); Api.setRequestDefault({ client: 'web' });
7
+ Api.setHeaders(() => ({ Authorization: `Bearer ${localStorage.getItem('token') || ''}` }));
8
+ Api.setPreparation(async (opts) => { if (opts.auth) opts.headers['X-Auth'] = '1'; });
9
+ Api.setEnd(async (res) => res.status === 401 ? { reset: true } : {});
10
+ const users = await Api.request<User[]>('users'); // GET
11
+ const updated = await Api.post<User>({ path: 'profile', request: { name: 'New' } });
12
+ await ApiCache.set('k', { a: 1 }, 60000); const cache = await ApiCache.get<{a: number}>('k');
13
+ ```
14
+
15
+ ## Storage & State
16
+ ```typescript
17
+ import { DataStorage, CookieStorage, Cookie, ServerStorage } from '@dxtmisha/functional-basic';
18
+ DataStorage.setPrefix('app_');
19
+ const ls = new DataStorage<{ id: string }>('user', false); ls.set({ id: '1' }); ls.get({ id: '0' }); ls.remove();
20
+ CookieStorage.set('t', 'dark', { age: 31536000, secure: true }); CookieStorage.get<string>('t', 'light');
21
+ const c = new Cookie<string>('auth'); c.set('xyz', { secure: true }); c.get();
22
+ const srv = ServerStorage.get('svc', () => new Svc()); // SSR isolated
23
+ ```
24
+
25
+ ## Geolocation, Formatting & Localization
26
+ ```typescript
27
+ import { Geo, GeoIntl, GeoFlag, GeoPhone } from '@dxtmisha/functional-basic';
28
+ const country = Geo.getCountry(); const lang = Geo.getLanguage(); Geo.set('en-US');
29
+ const intl = new GeoIntl('en-US');
30
+ intl.number(1234.5); intl.currency(99, 'USD'); intl.sizeFile(1024*1024); intl.date(new Date(), 'date');
31
+ intl.relative(new Date(Date.now() - 3600000)); intl.plural(3, 'apple|apples');
32
+ const flag = new GeoFlag().getFlag('VN');
33
+ const phone = GeoPhone.getByPhone('+84900000000'); const mask = GeoPhone.toMask('84900000000');
34
+ ```
35
+
36
+ ## DOM, Events & Helpers
37
+ ```typescript
38
+ import { EventItem, goScrollSmooth, writeClipboardData, getClipboardData, SearchList, Formatters, FormattersType, isFilled, isFunction, executeFunction, isDomRuntime, copyObject, anyToString, sleep } from '@dxtmisha/functional-basic';
39
+
40
+ // Safe Events (leak-proof)
41
+ const listener = new EventItem(window, 'click', console.log, { passive: true }); listener.start(); listener.stop();
42
+
43
+ // DOM / Clipboard
44
+ goScrollSmooth(document.getElementById('t')); await writeClipboardData('txt'); await getClipboardData();
45
+
46
+ // Search & Formatters
47
+ const res = new SearchList([{ n: 'John' }], ['n'], 'jo').to(); // Highlights matches
48
+ const fmt = new Formatters({ p: { type: FormattersType.currency, options: 'USD' } }, { p: 12 }).to();
49
+
50
+ // General
51
+ isFilled([]); // false (strings, arrays, objects, numbers, booleans)
52
+ executeFunction(callbackOrValue, arg1); // Executes callback if function, or returns value as is
53
+ isFunction(val); // Type-guard for functions
54
+ isDomRuntime(); const cloned = copyObject({ a: 1 }); const str = anyToString(123); await sleep(500);
55
+ ```
@@ -0,0 +1,6 @@
1
+ # Coding Standards & Conventions
2
+
3
+ - **Class Structure**: Properties/Variables (`public`->`protected`->`private`) -> Constructor -> Public Methods -> Protected Methods -> Private Methods. Within each method group, follow order: 1) `get` / `set` (getters/setters), 2) `is...` / `has...`, 3) `get...` / `set...`, 4) `add...` / `remove...`, 5) `update...` / `reset...`, 6) remaining methods. Within each subgroup, methods are grouped semantically by logical pairs and rules (e.g., `min` / `max`, `width` / `height`, `x` / `y` / `z`), and remaining methods are sorted alphabetically.
4
+ - **Style/Types**: `PascalCase` classes, `camelCase` methods/props, `UPPER_SNAKE_CASE` constants. No `any` (use `unknown`/generics). Explicit return types for ALL methods. Export all interfaces. Type files: `*Types.ts`. Use `@effect/schema` for schemas.
5
+ - **SSR Safety**: Isomorphic code. Do NOT store request state in globals. Use `isDomRuntime()` before `window`/`document`. Use `ServerStorage.get('key', () => new Class())` for request-isolated singletons.
6
+ - **Utility & Primitive Functions**: ALWAYS use primitive helper functions from this package (e.g. `isFunction`, `executeFunction`, `isFilled`, `isObject`, `isString`, `isArray`, etc.) instead of writing custom inline checks or conditions.