@fynixorg/ui 1.0.4 → 1.0.6
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/dist/build.d.ts +1 -0
- package/dist/context/context.d.ts +99 -0
- package/dist/context/context.js +3 -0
- package/dist/context/context.js.map +2 -2
- package/dist/custom/Outlet.d.ts +0 -0
- package/dist/custom/button.d.ts +62 -0
- package/dist/custom/button.js +3 -0
- package/dist/custom/button.js.map +2 -2
- package/dist/custom/index.d.ts +2 -0
- package/dist/custom/index.js.map +2 -2
- package/dist/custom/path.d.ts +71 -0
- package/dist/custom/path.js +3 -0
- package/dist/custom/path.js.map +2 -2
- package/dist/error/errorOverlay.d.ts +26 -0
- package/dist/error/errorOverlay.js +4 -0
- package/dist/error/errorOverlay.js.map +2 -2
- package/dist/fynix/index.d.ts +4 -0
- package/dist/hooks/nixAsync.d.ts +13 -0
- package/dist/hooks/nixAsync.js +7 -4
- package/dist/hooks/nixAsync.js.map +1 -1
- package/dist/hooks/nixAsyncCache.d.ts +7 -0
- package/dist/hooks/nixAsyncCache.js +7 -4
- package/dist/hooks/nixAsyncCache.js.map +1 -1
- package/dist/hooks/nixAsyncDebounce.d.ts +28 -0
- package/dist/hooks/nixAsyncDebounce.js +9 -6
- package/dist/hooks/nixAsyncDebounce.js.map +1 -1
- package/dist/hooks/nixAsyncQuery.d.ts +40 -0
- package/dist/hooks/nixAsyncQuery.js +7 -4
- package/dist/hooks/nixAsyncQuery.js.map +1 -1
- package/dist/hooks/nixCallback.d.ts +30 -0
- package/dist/hooks/nixCallback.js +4 -0
- package/dist/hooks/nixCallback.js.map +1 -1
- package/dist/hooks/nixComputed.d.ts +93 -0
- package/dist/hooks/nixComputed.js +4 -0
- package/dist/hooks/nixComputed.js.map +2 -2
- package/dist/hooks/nixDebounce.d.ts +32 -0
- package/dist/hooks/nixDebounce.js +7 -4
- package/dist/hooks/nixDebounce.js.map +2 -2
- package/dist/hooks/nixEffect.d.ts +64 -0
- package/dist/hooks/nixEffect.js +6 -0
- package/dist/hooks/nixEffect.js.map +1 -1
- package/dist/hooks/nixForm.d.ts +15 -0
- package/dist/hooks/nixForm.js +11 -0
- package/dist/hooks/nixForm.js.map +1 -1
- package/dist/hooks/nixFormAsync.d.ts +20 -0
- package/dist/hooks/nixFormAsync.js +12 -0
- package/dist/hooks/nixFormAsync.js.map +1 -1
- package/dist/hooks/nixInterval.d.ts +26 -0
- package/dist/hooks/nixInterval.js +6 -3
- package/dist/hooks/nixInterval.js.map +2 -2
- package/dist/hooks/nixLazy.d.ts +19 -0
- package/dist/hooks/nixLazy.js +6 -2
- package/dist/hooks/nixLazy.js.map +1 -1
- package/dist/hooks/nixLazyAsync.d.ts +26 -0
- package/dist/hooks/nixLazyAsync.js +10 -6
- package/dist/hooks/nixLazyAsync.js.map +1 -1
- package/dist/hooks/nixLazyFormAsync.d.ts +29 -0
- package/dist/hooks/nixLazyFormAsync.js +18 -6
- package/dist/hooks/nixLazyFormAsync.js.map +1 -1
- package/dist/hooks/nixLocalStorage.d.ts +22 -0
- package/dist/hooks/nixLocalStorage.js +5 -2
- package/dist/hooks/nixLocalStorage.js.map +2 -2
- package/dist/hooks/nixMemo.d.ts +8 -0
- package/dist/hooks/nixMemo.js +3 -0
- package/dist/hooks/nixMemo.js.map +1 -1
- package/dist/hooks/nixPrevious.d.ts +18 -0
- package/dist/hooks/nixPrevious.js +3 -0
- package/dist/hooks/nixPrevious.js.map +2 -2
- package/dist/hooks/nixRef.d.ts +10 -0
- package/dist/hooks/nixRef.js +3 -0
- package/dist/hooks/nixRef.js.map +1 -1
- package/dist/hooks/nixState.d.ts +73 -0
- package/dist/hooks/nixState.js +3 -0
- package/dist/hooks/nixState.js.map +1 -1
- package/dist/hooks/nixStore.d.ts +9 -0
- package/dist/hooks/nixStore.js +3 -0
- package/dist/hooks/nixStore.js.map +1 -1
- package/dist/plugins/vite-plugin-res.d.ts +16 -0
- package/dist/plugins/vite-plugin-res.js +80 -17
- package/dist/plugins/vite-plugin-res.js.map +2 -2
- package/dist/router/router.d.ts +53 -0
- package/dist/router/router.js +55 -8
- package/dist/router/router.js.map +2 -2
- package/dist/runtime.d.ts +91 -0
- package/dist/runtime.js +23 -4
- package/dist/runtime.js.map +2 -2
- package/package.json +4 -5
- package/types/global.d.ts +33 -20
- package/router/router.d.ts +0 -21
- package/router/router.js +0 -678
- package/runtime.d.ts +0 -83
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../hooks/nixAsyncDebounce.js"],
|
|
4
4
|
"sourcesContent": ["import { nixState } from \"./nixState\";\r\n\r\n/**\r\n * Debounced and cancellable async data fetcher with caching and deduping.\r\n *\r\n * @param {() => Promise<any>} promiseFactory - Async function that returns a promise.\r\n * @param {Object} [options={}] - Options for debounce, caching, and abort.\r\n * @param {number} [options.delay=300] - Debounce delay in ms.\r\n * @param {boolean} [options.leading=false] - Run on leading edge.\r\n * @param {boolean} [options.trailing=true] - Run on trailing edge.\r\n * @param {number} [options.maxWait] - Max wait time before forced invocation.\r\n * @param {boolean} [options.cache=true] - Enable caching of last result.\r\n * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel request.\r\n * @returns {Object} { data, error, loading, run, cancel }\r\n *\r\n * @example\r\n * const controller = new AbortController();\r\n * const { data, error, loading, run, cancel } = nixAsyncDebounce(\r\n * () => fetch('/api/data').then(r => r.json()),\r\n * { delay: 500, maxWait: 2000, leading: true, signal: controller.signal }\r\n * );\r\n */\r\nexport function nixAsyncDebounce(promiseFactory, options = {}) {\r\n const data = nixState(null);\r\n const error = nixState(null);\r\n const loading = nixState(false);\r\n\r\n const {\r\n delay = 300,\r\n leading = false,\r\n trailing = true,\r\n maxWait,\r\n cache = true,\r\n signal\r\n } = options;\r\n\r\n let lastResult = null;\r\n let lastError = null;\r\n let timerId = null;\r\n let lastInvokeTime = 0;\r\n let pendingPromise = null;\r\n\r\n const invoke = async () => {\r\n if (cache && lastResult !== null) {\r\n data.value = lastResult;\r\n error.value = lastError;\r\n loading.value = false;\r\n return lastResult;\r\n }\r\n\r\n loading.value = true;\r\n error.value = null;\r\n\r\n const abortController = new AbortController();\r\n if (signal) {\r\n signal.addEventListener(\"abort\", () => {\r\n abortController.abort();\r\n cancel();\r\n });\r\n }\r\n\r\n pendingPromise = promiseFactory();\r\n\r\n try {\r\n const result = await pendingPromise;\r\n lastResult = result;\r\n data.value = result;\r\n return result;\r\n } catch (e) {\r\n if (e.name !== \"AbortError\") {\r\n lastError = e;\r\n error.value = e;\r\n }\r\n throw e;\r\n } finally {\r\n loading.value = false;\r\n pendingPromise = null;\r\n lastInvokeTime = Date.now();\r\n }\r\n };\r\n\r\n const run = () => {\r\n const now = Date.now();\r\n const timeSinceLastInvoke = now - lastInvokeTime;\r\n const remainingTime = delay - timeSinceLastInvoke;\r\n\r\n const shouldInvokeLeading = leading && !timerId;\r\n\r\n if (maxWait !== undefined && timeSinceLastInvoke >= maxWait) {\r\n if (timerId) clearTimeout(timerId);\r\n timerId = null;\r\n return invoke();\r\n }\r\n\r\n if (timerId) clearTimeout(timerId);\r\n\r\n if (shouldInvokeLeading) return invoke();\r\n\r\n if (trailing) {\r\n timerId = setTimeout(() => {\r\n timerId = null;\r\n invoke();\r\n }, remainingTime > 0 ? remainingTime : delay);\r\n }\r\n };\r\n\r\n const cancel = () => {\r\n if (timerId) clearTimeout(timerId);\r\n timerId = pendingPromise = null;\r\n };\r\n\r\n return { data, error, loading, run, cancel };\r\n}\r\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gBAAgB;AAsBlB,SAAS,iBAAiB,gBAAgB,UAAU,CAAC,GAAG;AAC7D,QAAM,OAAO,SAAS,IAAI;AAC1B,QAAM,QAAQ,SAAS,IAAI;AAC3B,QAAM,UAAU,SAAS,KAAK;AAE9B,QAAM;AAAA,IACJ,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,WAAW;AAAA,IACX;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EACF,I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sB,MAAM;AAClC,UAAM,gBAAgB,QAAQ;AAE9B,UAAM,sBAAsB,WAAW,CAAC;AAExC,QAAI,YAAY,UAAa,uBAAuB,SAAS;AAC3D,UAAI;AAAS,qBAAa,OAAO;AACjC,gBAAU;AACV,aAAO,OAAO;AAAA,IAChB;AAEA,QAAI;AAAS,mBAAa,OAAO;AAEjC,QAAI;AAAqB,aAAO,OAAO;AAEvC,QAAI,UAAU;AACZ,gBAAU,WAAW,MAAM;AACzB,kBAAU;AACV,eAAO;AAAA,MACT,GAAG,gBAAgB,IAAI,gBAAgB,KAAK;AAAA,IAC9C;AAAA,EACF,GAvBY;AAyBZ,QAAM,SAAS,6BAAM;AACnB,QAAI;AAAS,mBAAa,OAAO;AACjC,cAAU,iBAAiB;AAAA,EAC7B,GAHe;AAKf,SAAO,EAAE,MAAM,OAAO,SAAS,KAAK,OAAO;AAC7C;AA1FgB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unified async query helper with:
|
|
3
|
+
* - AbortController cancellation
|
|
4
|
+
* - Request deduping
|
|
5
|
+
* - Shared caching
|
|
6
|
+
*
|
|
7
|
+
* @template T
|
|
8
|
+
* @param {string} key
|
|
9
|
+
* Unique cache key representing the request
|
|
10
|
+
*
|
|
11
|
+
* @param {(signal: AbortSignal) => Promise<T>} queryFn
|
|
12
|
+
* Function that performs the async operation
|
|
13
|
+
*
|
|
14
|
+
* @param {{
|
|
15
|
+
* ttl?: number
|
|
16
|
+
* }} [options]
|
|
17
|
+
*
|
|
18
|
+
* @returns {{
|
|
19
|
+
* data: { value: T | null },
|
|
20
|
+
* error: { value: Error | null },
|
|
21
|
+
* loading: { value: boolean },
|
|
22
|
+
* run: () => Promise<void>,
|
|
23
|
+
* cancel: () => void
|
|
24
|
+
* }}
|
|
25
|
+
*/
|
|
26
|
+
export function nixAsyncQuery<T>(key: string, queryFn: (signal: AbortSignal) => Promise<T>, options?: {
|
|
27
|
+
ttl?: number;
|
|
28
|
+
}): {
|
|
29
|
+
data: {
|
|
30
|
+
value: T | null;
|
|
31
|
+
};
|
|
32
|
+
error: {
|
|
33
|
+
value: Error | null;
|
|
34
|
+
};
|
|
35
|
+
loading: {
|
|
36
|
+
value: boolean;
|
|
37
|
+
};
|
|
38
|
+
run: () => Promise<void>;
|
|
39
|
+
cancel: () => void;
|
|
40
|
+
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
1
3
|
import { nixState } from "./nixState";
|
|
2
4
|
const asyncCache = /* @__PURE__ */ new Map();
|
|
3
5
|
function nixAsyncQuery(key, queryFn, options = {}) {
|
|
@@ -7,7 +9,7 @@ function nixAsyncQuery(key, queryFn, options = {}) {
|
|
|
7
9
|
const ttl = options.ttl ?? 0;
|
|
8
10
|
let active = true;
|
|
9
11
|
let callId = 0;
|
|
10
|
-
const run = async () => {
|
|
12
|
+
const run = /* @__PURE__ */ __name(async () => {
|
|
11
13
|
const id = ++callId;
|
|
12
14
|
loading.value = true;
|
|
13
15
|
error.value = null;
|
|
@@ -62,16 +64,17 @@ function nixAsyncQuery(key, queryFn, options = {}) {
|
|
|
62
64
|
if (active && id === callId)
|
|
63
65
|
loading.value = false;
|
|
64
66
|
}
|
|
65
|
-
};
|
|
66
|
-
const cancel = () => {
|
|
67
|
+
}, "run");
|
|
68
|
+
const cancel = /* @__PURE__ */ __name(() => {
|
|
67
69
|
active = false;
|
|
68
70
|
const cached = asyncCache.get(key);
|
|
69
71
|
if (cached?.controller) {
|
|
70
72
|
cached.controller.abort();
|
|
71
73
|
}
|
|
72
|
-
};
|
|
74
|
+
}, "cancel");
|
|
73
75
|
return { data, error, loading, run, cancel };
|
|
74
76
|
}
|
|
77
|
+
__name(nixAsyncQuery, "nixAsyncQuery");
|
|
75
78
|
export {
|
|
76
79
|
nixAsyncQuery
|
|
77
80
|
};
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../hooks/nixAsyncQuery.js"],
|
|
4
4
|
"sourcesContent": ["import { nixState } from \"./nixState\";\r\n\r\n/**\r\n * Global async cache.\r\n * key -> {\r\n * data?: any,\r\n * error?: Error,\r\n * promise?: Promise<any>,\r\n * controller?: AbortController,\r\n * timestamp?: number\r\n * }\r\n */\r\nconst asyncCache = new Map();\r\n\r\n/**\r\n * Unified async query helper with:\r\n * - AbortController cancellation\r\n * - Request deduping\r\n * - Shared caching\r\n *\r\n * @template T\r\n * @param {string} key\r\n * Unique cache key representing the request\r\n *\r\n * @param {(signal: AbortSignal) => Promise<T>} queryFn\r\n * Function that performs the async operation\r\n *\r\n * @param {{\r\n * ttl?: number\r\n * }} [options]\r\n *\r\n * @returns {{\r\n * data: { value: T | null },\r\n * error: { value: Error | null },\r\n * loading: { value: boolean },\r\n * run: () => Promise<void>,\r\n * cancel: () => void\r\n * }}\r\n */\r\nexport function nixAsyncQuery(key, queryFn, options = {}) {\r\n const data = nixState(null);\r\n const error = nixState(null);\r\n const loading = nixState(false);\r\n\r\n const ttl = options.ttl ?? 0;\r\n let active = true;\r\n let callId = 0;\r\n\r\n const run = async () => {\r\n const id = ++callId;\r\n loading.value = true;\r\n error.value = null;\r\n\r\n const now = Date.now();\r\n const cached = asyncCache.get(key);\r\n\r\n // Serve fresh cached data\r\n if (\r\n cached?.data &&\r\n (!ttl || now - cached.timestamp < ttl)\r\n ) {\r\n data.value = cached.data;\r\n loading.value = false;\r\n return;\r\n }\r\n\r\n // Deduping: reuse in-flight request\r\n if (cached?.promise) {\r\n try {\r\n const result = await cached.promise;\r\n if (!active || id !== callId) return;\r\n data.value = result;\r\n } catch (e) {\r\n if (!active || id !== callId) return;\r\n error.value = e;\r\n } finally {\r\n if (active && id === callId) loading.value = false;\r\n }\r\n return;\r\n }\r\n\r\n // New request\r\n const controller = new AbortController();\r\n const promise = (async () => {\r\n try {\r\n const result = await queryFn(controller.signal);\r\n asyncCache.set(key, {\r\n data: result,\r\n timestamp: Date.now()\r\n });\r\n return result;\r\n } catch (e) {\r\n asyncCache.delete(key);\r\n throw e instanceof Error ? e : new Error(String(e));\r\n }\r\n })();\r\n\r\n asyncCache.set(key, { promise, controller });\r\n\r\n try {\r\n const result = await promise;\r\n if (!active || id !== callId) return;\r\n data.value = result;\r\n } catch (e) {\r\n if (!active || id !== callId) return;\r\n error.value = e;\r\n } finally {\r\n if (active && id === callId) loading.value = false;\r\n }\r\n };\r\n\r\n /**\r\n * Cancels in-flight request and prevents state updates.\r\n */\r\n const cancel = () => {\r\n active = false;\r\n const cached = asyncCache.get(key);\r\n if (cached?.controller) {\r\n cached.controller.abort();\r\n }\r\n };\r\n\r\n return { data, error, loading, run, cancel };\r\n}\r\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,gBAAgB;AAYzB,MAAM,aAAa,oBAAI,IAAI;AA2BpB,SAAS,cAAc,KAAK,SAAS,UAAU,CAAC,GAAG;AACxD,QAAM,OAAO,SAAS,IAAI;AAC1B,QAAM,QAAQ,SAAS,IAAI;AAC3B,QAAM,UAAU,SAAS,KAAK;AAE9B,QAAM,MAAM,QAAQ,OAAO;AAC3B,MAAI,SAAS;AACb,MAAI,SAAS;AAEb,QAAM,MAAM,
|
|
5
|
+
"mappings": ";;AAAA,SAAS,gBAAgB;AAYzB,MAAM,aAAa,oBAAI,IAAI;AA2BpB,SAAS,cAAc,KAAK,SAAS,UAAU,CAAC,GAAG;AACxD,QAAM,OAAO,SAAS,IAAI;AAC1B,QAAM,QAAQ,SAAS,IAAI;AAC3B,QAAM,UAAU,SAAS,KAAK;AAE9B,QAAM,MAAM,QAAQ,OAAO;AAC3B,MAAI,SAAS;AACb,MAAI,SAAS;AAEb,QAAM,MAAM,mCAAY;AACtB,UAAM,KAAK,EAAE;AACb,YAAQ,QAAQ;AAChB,UAAM,QAAQ;AAEd,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM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AM;AAAA,IAC1B;AAAA,EACF,GANe;AAQf,SAAO,EAAE,MAAM,OAAO,SAAS,KAAK,OAAO;AAC7C;AApFgB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memoizes a callback function based on a dependency array.
|
|
3
|
+
* Similar to React's useCallback.
|
|
4
|
+
*
|
|
5
|
+
* @param {Function} fn
|
|
6
|
+
* Function to memoize. Should be pure and not mutate external state.
|
|
7
|
+
*
|
|
8
|
+
* @param {Array<any>} [deps=[]]
|
|
9
|
+
* Dependency array. Callback identity changes only when deps change.
|
|
10
|
+
*
|
|
11
|
+
* @returns {Function}
|
|
12
|
+
* Memoized callback function.
|
|
13
|
+
*
|
|
14
|
+
* @throws {Error}
|
|
15
|
+
* If called outside of a component context.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const onClick = nixCallback(() => {
|
|
19
|
+
* console.log(count.value);
|
|
20
|
+
* }, [count.value]);
|
|
21
|
+
*
|
|
22
|
+
* @security
|
|
23
|
+
* - Avoids JSON.stringify to prevent crashes on circular references
|
|
24
|
+
* - Limits dependency array size to prevent performance abuse
|
|
25
|
+
*
|
|
26
|
+
* @memory
|
|
27
|
+
* - Does not allocate large temporary strings
|
|
28
|
+
* - Reuses function reference when deps are unchanged
|
|
29
|
+
*/
|
|
30
|
+
export function nixCallback(fn: Function, deps?: Array<any>): Function;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
1
3
|
import { activeContext } from "../context/context";
|
|
2
4
|
function nixCallback(fn, deps = []) {
|
|
3
5
|
const ctx = activeContext;
|
|
@@ -25,6 +27,7 @@ function nixCallback(fn, deps = []) {
|
|
|
25
27
|
}
|
|
26
28
|
return ctx.hooks[idx].value;
|
|
27
29
|
}
|
|
30
|
+
__name(nixCallback, "nixCallback");
|
|
28
31
|
function shallowArrayEqual(a, b) {
|
|
29
32
|
if (a.length !== b.length)
|
|
30
33
|
return false;
|
|
@@ -34,6 +37,7 @@ function shallowArrayEqual(a, b) {
|
|
|
34
37
|
}
|
|
35
38
|
return true;
|
|
36
39
|
}
|
|
40
|
+
__name(shallowArrayEqual, "shallowArrayEqual");
|
|
37
41
|
export {
|
|
38
42
|
nixCallback
|
|
39
43
|
};
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../hooks/nixCallback.js"],
|
|
4
4
|
"sourcesContent": ["import { activeContext } from \"../context/context\";\r\n\r\n/**\r\n * Memoizes a callback function based on a dependency array.\r\n * Similar to React's useCallback.\r\n *\r\n * @param {Function} fn\r\n * Function to memoize. Should be pure and not mutate external state.\r\n *\r\n * @param {Array<any>} [deps=[]]\r\n * Dependency array. Callback identity changes only when deps change.\r\n *\r\n * @returns {Function}\r\n * Memoized callback function.\r\n *\r\n * @throws {Error}\r\n * If called outside of a component context.\r\n *\r\n * @example\r\n * const onClick = nixCallback(() => {\r\n * console.log(count.value);\r\n * }, [count.value]);\r\n *\r\n * @security\r\n * - Avoids JSON.stringify to prevent crashes on circular references\r\n * - Limits dependency array size to prevent performance abuse\r\n *\r\n * @memory\r\n * - Does not allocate large temporary strings\r\n * - Reuses function reference when deps are unchanged\r\n */\r\nexport function nixCallback(fn, deps = []) {\r\n const ctx = activeContext;\r\n if (!ctx) throw new Error(\"nixCallback() called outside component\");\r\n\r\n if (typeof fn !== \"function\") {\r\n console.error(\"[nixCallback] First argument must be a function\");\r\n return fn;\r\n }\r\n\r\n if (!Array.isArray(deps)) {\r\n console.error(\"[nixCallback] Second argument must be an array\");\r\n deps = [];\r\n }\r\n\r\n const MAX_DEPS = 100;\r\n if (deps.length > MAX_DEPS) {\r\n console.warn(\r\n `[nixCallback] Dependency array too large (${deps.length}). Limited to ${MAX_DEPS}.`\r\n );\r\n deps = deps.slice(0, MAX_DEPS);\r\n }\r\n\r\n const idx = ctx.hookIndex++;\r\n const prev = ctx.hooks[idx];\r\n\r\n if (!prev || !shallowArrayEqual(prev.deps, deps)) {\r\n ctx.hooks[idx] = { value: fn, deps };\r\n }\r\n\r\n return ctx.hooks[idx].value;\r\n}\r\n\r\n/**\r\n * Shallow comparison for dependency arrays.\r\n *\r\n * @param {Array<any>} a\r\n * @param {Array<any>} b\r\n * @returns {boolean}\r\n */\r\nfunction shallowArrayEqual(a, b) {\r\n if (a.length !== b.length) return false;\r\n for (let i = 0; i < a.length; i++) {\r\n if (!Object.is(a[i], b[i])) return false;\r\n }\r\n return true;\r\n}\r\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,qBAAqB;AA+BvB,SAAS,YAAY,IAAI,OAAO,CAAC,GAAG;AACzC,QAAM,MAAM;AACZ,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,wCAAwC;AAElE,MAAI,OAAO,OAAO,YAAY;AAC5B,YAAQ,MAAM,iDAAiD;AAC/D,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,MAAM,QAAQ,IAAI,GAAG;AACxB,YAAQ,MAAM,gDAAgD;AAC9D,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,WAAW;AACjB,MAAI,KAAK,SAAS,UAAU;AAC1B,YAAQ;AAAA,MACN,6CAA6C,KAAK,MAAM,iBAAiB,QAAQ;AAAA,IACnF;AACA,WAAO,KAAK,MAAM,GAAG,QAAQ;AAAA,EAC/B;AAEA,QAAM,MAAM,IAAI;AAChB,QAAM,OAAO,IAAI,MAAM,GAAG;AAE1B,MAAI,CAAC,QAAQ,CAAC,kBAAkB,KAAK,MAAM,IAAI,GAAG;AAChD,QAAI,MAAM,GAAG,IAAI,EAAE,OAAO,IAAI,KAAK;AAAA,EACrC;AAEA,SAAO,IAAI,MAAM,GAAG,EAAE;AACxB;
|
|
5
|
+
"mappings": ";;AAAA,SAAS,qBAAqB;AA+BvB,SAAS,YAAY,IAAI,OAAO,CAAC,GAAG;AACzC,QAAM,MAAM;AACZ,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,wCAAwC;AAElE,MAAI,OAAO,OAAO,YAAY;AAC5B,YAAQ,MAAM,iDAAiD;AAC/D,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,MAAM,QAAQ,IAAI,GAAG;AACxB,YAAQ,MAAM,gDAAgD;AAC9D,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,WAAW;AACjB,MAAI,KAAK,SAAS,UAAU;AAC1B,YAAQ;AAAA,MACN,6CAA6C,KAAK,MAAM,iBAAiB,QAAQ;AAAA,IACnF;AACA,WAAO,KAAK,MAAM,GAAG,QAAQ;AAAA,EAC/B;AAEA,QAAM,MAAM,IAAI;AAChB,QAAM,OAAO,IAAI,MAAM,GAAG;AAE1B,MAAI,CAAC,QAAQ,CAAC,kBAAkB,KAAK,MAAM,IAAI,GAAG;AAChD,QAAI,MAAM,GAAG,IAAI,EAAE,OAAO,IAAI,KAAK;AAAA,EACrC;AAEA,SAAO,IAAI,MAAM,GAAG,EAAE;AACxB;AA9BgB;AAuChB,SAAS,kBAAkB,GAAG,GAAG;AAC/B,MAAI,EAAE,WAAW,EAAE;AAAQ,WAAO;AAClC,WAAS,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK;AACjC,QAAI,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC;AAAG,aAAO;AAAA,EACrC;AACA,SAAO;AACT;AANS;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @template T
|
|
3
|
+
* @typedef {Object} ComputedState
|
|
4
|
+
* @property {T} value - Get the computed value (read-only)
|
|
5
|
+
* @property {(fn: (value: T) => void) => (() => void)} subscribe - Subscribe to computed value changes
|
|
6
|
+
* @property {() => void} cleanup - Cleanup all subscriptions and dependencies
|
|
7
|
+
* @property {() => number} getSubscriberCount - Get number of active subscribers (debugging)
|
|
8
|
+
* @property {() => number} getDependencyCount - Get number of tracked dependencies (debugging)
|
|
9
|
+
* @property {() => boolean} isDestroyed - Check if computed state has been destroyed
|
|
10
|
+
* @property {boolean} _isNixState - Internal flag (computed states behave like states)
|
|
11
|
+
* @property {boolean} _isComputed - Internal flag to identify computed states
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Create a derived/computed state from other states.
|
|
15
|
+
* Automatically tracks dependencies and updates when any dependency changes.
|
|
16
|
+
*
|
|
17
|
+
* @template T
|
|
18
|
+
* @param {() => T} computeFn - Function that computes the derived value
|
|
19
|
+
* @returns {ComputedState<T>} A reactive state object with the computed value
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* const count = nixState(5);
|
|
23
|
+
* const doubled = nixComputed(() => count.value * 2);
|
|
24
|
+
* console.log(doubled.value); // 10
|
|
25
|
+
* count.value = 10;
|
|
26
|
+
* console.log(doubled.value); // 20
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* // Multiple dependencies
|
|
30
|
+
* const a = nixState(5);
|
|
31
|
+
* const b = nixState(10);
|
|
32
|
+
* const sum = nixComputed(() => a.value + b.value);
|
|
33
|
+
* console.log(sum.value); // 15
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* // Conditional dependencies
|
|
37
|
+
* const flag = nixState(true);
|
|
38
|
+
* const x = nixState(1);
|
|
39
|
+
* const y = nixState(2);
|
|
40
|
+
* const result = nixComputed(() => flag.value ? x.value : y.value);
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* // With cleanup
|
|
44
|
+
* const MyComponent = () => {
|
|
45
|
+
* const count = nixState(0);
|
|
46
|
+
* const doubled = nixComputed(() => count.value * 2);
|
|
47
|
+
*
|
|
48
|
+
* nixEffect(() => {
|
|
49
|
+
* return () => {
|
|
50
|
+
* doubled.cleanup();
|
|
51
|
+
* count.cleanup();
|
|
52
|
+
* };
|
|
53
|
+
* }, []);
|
|
54
|
+
* };
|
|
55
|
+
*
|
|
56
|
+
* @throws {Error} If called outside a component context
|
|
57
|
+
* @throws {TypeError} If computeFn is not a function
|
|
58
|
+
*/
|
|
59
|
+
export function nixComputed<T>(computeFn: () => T): ComputedState<T>;
|
|
60
|
+
export type ComputedState<T> = {
|
|
61
|
+
/**
|
|
62
|
+
* - Get the computed value (read-only)
|
|
63
|
+
*/
|
|
64
|
+
value: T;
|
|
65
|
+
/**
|
|
66
|
+
* - Subscribe to computed value changes
|
|
67
|
+
*/
|
|
68
|
+
subscribe: (fn: (value: T) => void) => (() => void);
|
|
69
|
+
/**
|
|
70
|
+
* - Cleanup all subscriptions and dependencies
|
|
71
|
+
*/
|
|
72
|
+
cleanup: () => void;
|
|
73
|
+
/**
|
|
74
|
+
* - Get number of active subscribers (debugging)
|
|
75
|
+
*/
|
|
76
|
+
getSubscriberCount: () => number;
|
|
77
|
+
/**
|
|
78
|
+
* - Get number of tracked dependencies (debugging)
|
|
79
|
+
*/
|
|
80
|
+
getDependencyCount: () => number;
|
|
81
|
+
/**
|
|
82
|
+
* - Check if computed state has been destroyed
|
|
83
|
+
*/
|
|
84
|
+
isDestroyed: () => boolean;
|
|
85
|
+
/**
|
|
86
|
+
* - Internal flag (computed states behave like states)
|
|
87
|
+
*/
|
|
88
|
+
_isNixState: boolean;
|
|
89
|
+
/**
|
|
90
|
+
* - Internal flag to identify computed states
|
|
91
|
+
*/
|
|
92
|
+
_isComputed: boolean;
|
|
93
|
+
};
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
1
3
|
import { activeContext, setActiveContext } from "../context/context";
|
|
2
4
|
function nixComputed(computeFn) {
|
|
3
5
|
const ctx = activeContext;
|
|
@@ -69,6 +71,7 @@ function nixComputed(computeFn) {
|
|
|
69
71
|
}
|
|
70
72
|
return cachedValue;
|
|
71
73
|
};
|
|
74
|
+
__name(compute, "compute");
|
|
72
75
|
const subscribers = /* @__PURE__ */ new Set();
|
|
73
76
|
const dependencies = /* @__PURE__ */ new Set();
|
|
74
77
|
const unsubscribers = /* @__PURE__ */ new Map();
|
|
@@ -194,6 +197,7 @@ function nixComputed(computeFn) {
|
|
|
194
197
|
}
|
|
195
198
|
return ctx.hooks[idx];
|
|
196
199
|
}
|
|
200
|
+
__name(nixComputed, "nixComputed");
|
|
197
201
|
export {
|
|
198
202
|
nixComputed
|
|
199
203
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../hooks/nixComputed.js"],
|
|
4
|
-
"sourcesContent": ["/* ----------------------\r\n nixComputed - Computed/Derived State\r\n Memory Leaks & Security Issues Resolved\r\n---------------------- */\r\nimport { activeContext, setActiveContext } from \"../context/context\";\r\n\r\n/**\r\n * Create a derived/computed state from other states.\r\n * Automatically tracks dependencies and updates when any dependency changes.\r\n * \r\n * @param {() => any} computeFn - Function that computes the derived value\r\n * @returns {ComputedState} A reactive state object with the computed value\r\n * \r\n * @typedef {Object} ComputedState\r\n * @property {any} value - Get the computed value (read-only)\r\n * @property {(fn: Function) => Function} subscribe - Subscribe to computed value changes\r\n * @property {() => void} cleanup - Cleanup all subscriptions and dependencies\r\n * @property {() => number} getSubscriberCount - Get number of active subscribers (debugging)\r\n * @property {() => number} getDependencyCount - Get number of tracked dependencies (debugging)\r\n * @property {() => boolean} isDestroyed - Check if computed state has been destroyed\r\n * @property {boolean} _isNixState - Internal flag (computed states behave like states)\r\n * @property {boolean} _isComputed - Internal flag to identify computed states\r\n * \r\n * @example\r\n * const count = nixState(5);\r\n * const doubled = nixComputed(() => count.value * 2);\r\n * console.log(doubled.value); // 10\r\n * count.value = 10;\r\n * console.log(doubled.value); // 20\r\n * \r\n * @example\r\n * // Multiple dependencies\r\n * const a = nixState(5);\r\n * const b = nixState(10);\r\n * const sum = nixComputed(() => a.value + b.value);\r\n * console.log(sum.value); // 15\r\n * \r\n * @example\r\n * // Conditional dependencies\r\n * const flag = nixState(true);\r\n * const x = nixState(1);\r\n * const y = nixState(2);\r\n * const result = nixComputed(() => flag.value ? x.value : y.value);\r\n * \r\n * @example\r\n * // With cleanup\r\n * const MyComponent = () => {\r\n * const count = nixState(0);\r\n * const doubled = nixComputed(() => count.value * 2);\r\n * \r\n * nixEffect(() => {\r\n * return () => {\r\n * doubled.cleanup();\r\n * count.cleanup();\r\n * };\r\n * }, []);\r\n * };\r\n * \r\n * @throws {Error} If called outside a component context\r\n * @throws {TypeError} If computeFn is not a function\r\n */\r\nexport function nixComputed(computeFn) {\r\n const ctx = activeContext;\r\n if (!ctx) throw new Error(\"nixComputed() called outside component\");\r\n \r\n // Security: Validate compute function\r\n if (typeof computeFn !== 'function') {\r\n throw new TypeError('[nixComputed] First argument must be a function');\r\n }\r\n\r\n const idx = ctx.hookIndex++;\r\n if (!ctx.hooks[idx]) {\r\n const subscribers = new Set();\r\n const dependencies = new Set();\r\n const unsubscribers = new Map(); // Map<dependency, unsubscribe function>\r\n let cachedValue;\r\n let isStale = true;\r\n let isDestroyed = false;\r\n let isComputing = false; // Prevent infinite loops\r\n\r\n /**\r\n * Compute the value and track dependencies\r\n */\r\n function compute() {\r\n if (isDestroyed) return cachedValue;\r\n \r\n // Prevent infinite computation loops\r\n if (isComputing) {\r\n console.error('[nixComputed] Circular dependency detected');\r\n return cachedValue;\r\n }\r\n \r\n isComputing = true;\r\n \r\n // Create a mock context for dependency tracking\r\n const trackingContext = {\r\n _accessedStates: new Set(),\r\n hookIndex: 0,\r\n hooks: [],\r\n _subscriptions: new Set(),\r\n _subscriptionCleanups: [],\r\n };\r\n \r\n // Save the previous context\r\n const prevContext = activeContext;\r\n \r\n try {\r\n // Temporarily set the tracking context\r\n setActiveContext(trackingContext);\r\n \r\n // Compute the value - this will trigger state.value getters\r\n // which will add themselves to trackingContext._accessedStates\r\n cachedValue = computeFn();\r\n \r\n // Find dependencies that are no longer needed\r\n const oldDeps = Array.from(dependencies);\r\n oldDeps.forEach(dep => {\r\n if (!trackingContext._accessedStates.has(dep)) {\r\n // This dependency is no longer accessed - unsubscribe\r\n if (unsubscribers.has(dep)) {\r\n try {\r\n unsubscribers.get(dep)();\r\n } catch (e) {\r\n console.error('[nixComputed] Error unsubscribing from old dependency:', e);\r\n }\r\n unsubscribers.delete(dep);\r\n }\r\n dependencies.delete(dep);\r\n }\r\n });\r\n \r\n // Subscribe to new dependencies\r\n trackingContext._accessedStates.forEach(state => {\r\n if (!dependencies.has(state)) {\r\n // New dependency found - subscribe to it\r\n const unsub = state.subscribe(() => {\r\n // Mark computed value as stale when dependency changes\r\n isStale = true;\r\n \r\n // Notify computed subscribers\r\n const subsArray = Array.from(subscribers);\r\n subsArray.forEach(fn => {\r\n try { \r\n fn(s.value); \r\n } catch (e) { \r\n console.error('[nixComputed] Subscriber error:', e);\r\n subscribers.delete(fn);\r\n }\r\n });\r\n });\r\n \r\n // Store unsubscribe function\r\n unsubscribers.set(state, unsub);\r\n dependencies.add(state);\r\n }\r\n });\r\n \r\n isStale = false;\r\n } catch (err) {\r\n console.error('[nixComputed] Compute error:', err);\r\n isStale = false; // Don't retry immediately\r\n } finally {\r\n // Restore the previous context\r\n setActiveContext(prevContext);\r\n isComputing = false;\r\n }\r\n \r\n return cachedValue;\r\n }\r\n\r\n const s = {\r\n /**\r\n * Get the computed value (read-only).\r\n * Automatically recomputes if dependencies have changed.\r\n * @returns {any} The computed value\r\n */\r\n get value() {\r\n if (isDestroyed) {\r\n console.warn('[nixComputed] Accessing destroyed computed state');\r\n return cachedValue;\r\n }\r\n \r\n // Recompute if stale\r\n if (isStale) {\r\n compute();\r\n }\r\n \r\n // Track this computed state as a dependency if accessed in another computed\r\n if (activeContext && activeContext._accessedStates) {\r\n activeContext._accessedStates.add(s);\r\n }\r\n \r\n return cachedValue;\r\n },\r\n \r\n /**\r\n * Subscribe to computed value changes.\r\n * @param {(value: T) => void} fn - Callback function\r\n * @returns {() => void} Unsubscribe function\r\n */\r\n subscribe(fn) {\r\n // Security: Validate subscriber function\r\n if (typeof fn !== 'function') {\r\n console.error('[nixComputed] subscribe() requires a function');\r\n return () => {};\r\n }\r\n \r\n // Memory Leak Fix: Don't add subscribers to destroyed state\r\n if (isDestroyed) {\r\n console.warn('[nixComputed] Cannot subscribe to destroyed computed state');\r\n return () => {};\r\n }\r\n \r\n // Security: Limit number of subscribers to prevent DOS\r\n const MAX_SUBSCRIBERS = 1000;\r\n if (subscribers.size >= MAX_SUBSCRIBERS) {\r\n console.error('[nixComputed] Maximum subscriber limit reached');\r\n return () => {};\r\n }\r\n \r\n subscribers.add(fn);\r\n \r\n // Return unsubscribe function\r\n return () => {\r\n subscribers.delete(fn);\r\n };\r\n },\r\n \r\n /**\r\n * Cleanup all subscriptions and dependencies.\r\n * Call this when component unmounts to prevent memory leaks.\r\n * \r\n * @example\r\n * nixEffect(() => {\r\n * return () => myComputed.cleanup();\r\n * }, []);\r\n */\r\n cleanup() {\r\n if (isDestroyed) return;\r\n \r\n // Mark as destroyed to prevent further operations\r\n isDestroyed = true;\r\n \r\n // Unsubscribe from all dependencies\r\n unsubscribers.forEach((unsub, dep) => {\r\n try {\r\n unsub();\r\n } catch (e) {\r\n console.error('[nixComputed] Cleanup error:', e);\r\n }\r\n });\r\n \r\n // Clear all collections\r\n unsubscribers.clear();\r\n dependencies.clear();\r\n subscribers.clear();\r\n \r\n // Clear cached value to help garbage collection\r\n cachedValue = null;\r\n \r\n console.log('[nixComputed] Computed state cleaned up');\r\n },\r\n \r\n /**\r\n * Get the number of active subscribers (useful for debugging)\r\n * @returns {number} Number of active subscribers\r\n */\r\n getSubscriberCount() {\r\n return subscribers.size;\r\n },\r\n \r\n /**\r\n * Get the number of tracked dependencies (useful for debugging)\r\n * @returns {number} Number of dependencies\r\n */\r\n getDependencyCount() {\r\n return dependencies.size;\r\n },\r\n \r\n /**\r\n * Check if computed state has been destroyed\r\n * @returns {boolean} True if state is destroyed\r\n */\r\n isDestroyed() {\r\n return isDestroyed;\r\n },\r\n \r\n /**\r\n * Get information about current dependencies (debugging)\r\n * @returns {Array<{state: Object, hasCleanup: boolean}>} Dependency info\r\n */\r\n getDependencyInfo() {\r\n return Array.from(dependencies).map(dep => ({\r\n state: dep,\r\n hasCleanup: unsubscribers.has(dep),\r\n isComputed: !!dep._isComputed,\r\n }));\r\n },\r\n \r\n // Internal flags\r\n _isNixState: true, // Computed states behave like states\r\n _isComputed: true, // Flag to identify computed states\r\n };\r\n\r\n // Initial computation\r\n compute();\r\n \r\n // Store in hooks\r\n ctx.hooks[idx] = s;\r\n \r\n // Memory Leak Fix: Track for cleanup\r\n if (ctx.stateCleanups) {\r\n ctx.stateCleanups.push(() => s.cleanup());\r\n }\r\n }\r\n\r\n return ctx.hooks[idx];\r\n}"],
|
|
5
|
-
"mappings": "AAIA,SAAS,eAAe,wBAAwB;
|
|
4
|
+
"sourcesContent": ["/* ----------------------\r\n nixComputed - Computed/Derived State\r\n Memory Leaks & Security Issues Resolved\r\n---------------------- */\r\nimport { activeContext, setActiveContext } from \"../context/context\";\r\n\r\n/**\r\n * @template T\r\n * @typedef {Object} ComputedState\r\n * @property {T} value - Get the computed value (read-only)\r\n * @property {(fn: (value: T) => void) => (() => void)} subscribe - Subscribe to computed value changes\r\n * @property {() => void} cleanup - Cleanup all subscriptions and dependencies\r\n * @property {() => number} getSubscriberCount - Get number of active subscribers (debugging)\r\n * @property {() => number} getDependencyCount - Get number of tracked dependencies (debugging)\r\n * @property {() => boolean} isDestroyed - Check if computed state has been destroyed\r\n * @property {boolean} _isNixState - Internal flag (computed states behave like states)\r\n * @property {boolean} _isComputed - Internal flag to identify computed states\r\n */\r\n\r\n/**\r\n * Create a derived/computed state from other states.\r\n * Automatically tracks dependencies and updates when any dependency changes.\r\n * \r\n * @template T\r\n * @param {() => T} computeFn - Function that computes the derived value\r\n * @returns {ComputedState<T>} A reactive state object with the computed value\r\n * \r\n * @example\r\n * const count = nixState(5);\r\n * const doubled = nixComputed(() => count.value * 2);\r\n * console.log(doubled.value); // 10\r\n * count.value = 10;\r\n * console.log(doubled.value); // 20\r\n * \r\n * @example\r\n * // Multiple dependencies\r\n * const a = nixState(5);\r\n * const b = nixState(10);\r\n * const sum = nixComputed(() => a.value + b.value);\r\n * console.log(sum.value); // 15\r\n * \r\n * @example\r\n * // Conditional dependencies\r\n * const flag = nixState(true);\r\n * const x = nixState(1);\r\n * const y = nixState(2);\r\n * const result = nixComputed(() => flag.value ? x.value : y.value);\r\n * \r\n * @example\r\n * // With cleanup\r\n * const MyComponent = () => {\r\n * const count = nixState(0);\r\n * const doubled = nixComputed(() => count.value * 2);\r\n * \r\n * nixEffect(() => {\r\n * return () => {\r\n * doubled.cleanup();\r\n * count.cleanup();\r\n * };\r\n * }, []);\r\n * };\r\n * \r\n * @throws {Error} If called outside a component context\r\n * @throws {TypeError} If computeFn is not a function\r\n */\r\nexport function nixComputed(computeFn) {\r\n const ctx = activeContext;\r\n if (!ctx) throw new Error(\"nixComputed() called outside component\");\r\n\r\n // Security: Validate compute function\r\n if (typeof computeFn !== 'function') {\r\n throw new TypeError('[nixComputed] First argument must be a function');\r\n }\r\n\r\n const idx = ctx.hookIndex++;\r\n if (!ctx.hooks[idx]) {\r\n const subscribers = new Set();\r\n const dependencies = new Set();\r\n const unsubscribers = new Map(); // Map<dependency, unsubscribe function>\r\n let cachedValue;\r\n let isStale = true;\r\n let isDestroyed = false;\r\n let isComputing = false; // Prevent infinite loops\r\n\r\n /**\r\n * Compute the value and track dependencies\r\n */\r\n function compute() {\r\n if (isDestroyed) return cachedValue;\r\n\r\n // Prevent infinite computation loops\r\n if (isComputing) {\r\n console.error('[nixComputed] Circular dependency detected');\r\n return cachedValue;\r\n }\r\n\r\n isComputing = true;\r\n\r\n // Create a mock context for dependency tracking\r\n const trackingContext = {\r\n _accessedStates: new Set(),\r\n hookIndex: 0,\r\n hooks: [],\r\n _subscriptions: new Set(),\r\n _subscriptionCleanups: [],\r\n };\r\n\r\n // Save the previous context\r\n const prevContext = activeContext;\r\n\r\n try {\r\n // Temporarily set the tracking context\r\n // @ts-ignore - Internal tracking context doesn't need full ComponentContext properties\r\n setActiveContext(trackingContext);\r\n\r\n // Compute the value - this will trigger state.value getters\r\n // which will add themselves to trackingContext._accessedStates\r\n cachedValue = computeFn();\r\n\r\n // Find dependencies that are no longer needed\r\n const oldDeps = Array.from(dependencies);\r\n oldDeps.forEach(dep => {\r\n if (!trackingContext._accessedStates.has(dep)) {\r\n // This dependency is no longer accessed - unsubscribe\r\n if (unsubscribers.has(dep)) {\r\n try {\r\n unsubscribers.get(dep)();\r\n } catch (e) {\r\n console.error('[nixComputed] Error unsubscribing from old dependency:', e);\r\n }\r\n unsubscribers.delete(dep);\r\n }\r\n dependencies.delete(dep);\r\n }\r\n });\r\n\r\n // Subscribe to new dependencies\r\n trackingContext._accessedStates.forEach(state => {\r\n if (!dependencies.has(state)) {\r\n // New dependency found - subscribe to it\r\n const unsub = state.subscribe(() => {\r\n // Mark computed value as stale when dependency changes\r\n isStale = true;\r\n\r\n // Notify computed subscribers\r\n const subsArray = Array.from(subscribers);\r\n subsArray.forEach(fn => {\r\n try {\r\n fn(s.value);\r\n } catch (e) {\r\n console.error('[nixComputed] Subscriber error:', e);\r\n subscribers.delete(fn);\r\n }\r\n });\r\n });\r\n\r\n // Store unsubscribe function\r\n unsubscribers.set(state, unsub);\r\n dependencies.add(state);\r\n }\r\n });\r\n\r\n isStale = false;\r\n } catch (err) {\r\n console.error('[nixComputed] Compute error:', err);\r\n isStale = false; // Don't retry immediately\r\n } finally {\r\n // Restore the previous context\r\n setActiveContext(prevContext);\r\n isComputing = false;\r\n }\r\n\r\n return cachedValue;\r\n }\r\n\r\n const s = {\r\n /**\r\n * Get the computed value (read-only).\r\n * Automatically recomputes if dependencies have changed.\r\n * @returns {any} The computed value\r\n */\r\n get value() {\r\n if (isDestroyed) {\r\n console.warn('[nixComputed] Accessing destroyed computed state');\r\n return cachedValue;\r\n }\r\n\r\n // Recompute if stale\r\n if (isStale) {\r\n compute();\r\n }\r\n\r\n // Track this computed state as a dependency if accessed in another computed\r\n if (activeContext && activeContext._accessedStates) {\r\n activeContext._accessedStates.add(s);\r\n }\r\n\r\n return cachedValue;\r\n },\r\n\r\n /**\r\n * Subscribe to computed value changes.\r\n * @param {(value: T) => void} fn - Callback function\r\n * @returns {() => void} Unsubscribe function\r\n */\r\n subscribe(fn) {\r\n // Security: Validate subscriber function\r\n if (typeof fn !== 'function') {\r\n console.error('[nixComputed] subscribe() requires a function');\r\n return () => { };\r\n }\r\n\r\n // Memory Leak Fix: Don't add subscribers to destroyed state\r\n if (isDestroyed) {\r\n console.warn('[nixComputed] Cannot subscribe to destroyed computed state');\r\n return () => { };\r\n }\r\n\r\n // Security: Limit number of subscribers to prevent DOS\r\n const MAX_SUBSCRIBERS = 1000;\r\n if (subscribers.size >= MAX_SUBSCRIBERS) {\r\n console.error('[nixComputed] Maximum subscriber limit reached');\r\n return () => { };\r\n }\r\n\r\n subscribers.add(fn);\r\n\r\n // Return unsubscribe function\r\n return () => {\r\n subscribers.delete(fn);\r\n };\r\n },\r\n\r\n /**\r\n * Cleanup all subscriptions and dependencies.\r\n * Call this when component unmounts to prevent memory leaks.\r\n * \r\n * @example\r\n * nixEffect(() => {\r\n * return () => myComputed.cleanup();\r\n * }, []);\r\n */\r\n cleanup() {\r\n if (isDestroyed) return;\r\n\r\n // Mark as destroyed to prevent further operations\r\n isDestroyed = true;\r\n\r\n // Unsubscribe from all dependencies\r\n unsubscribers.forEach((unsub, dep) => {\r\n try {\r\n unsub();\r\n } catch (e) {\r\n console.error('[nixComputed] Cleanup error:', e);\r\n }\r\n });\r\n\r\n // Clear all collections\r\n unsubscribers.clear();\r\n dependencies.clear();\r\n subscribers.clear();\r\n\r\n // Clear cached value to help garbage collection\r\n cachedValue = null;\r\n\r\n console.log('[nixComputed] Computed state cleaned up');\r\n },\r\n\r\n /**\r\n * Get the number of active subscribers (useful for debugging)\r\n * @returns {number} Number of active subscribers\r\n */\r\n getSubscriberCount() {\r\n return subscribers.size;\r\n },\r\n\r\n /**\r\n * Get the number of tracked dependencies (useful for debugging)\r\n * @returns {number} Number of dependencies\r\n */\r\n getDependencyCount() {\r\n return dependencies.size;\r\n },\r\n\r\n /**\r\n * Check if computed state has been destroyed\r\n * @returns {boolean} True if state is destroyed\r\n */\r\n isDestroyed() {\r\n return isDestroyed;\r\n },\r\n\r\n /**\r\n * Get information about current dependencies (debugging)\r\n * @returns {Array<{state: Object, hasCleanup: boolean}>} Dependency info\r\n */\r\n getDependencyInfo() {\r\n return Array.from(dependencies).map(dep => ({\r\n state: dep,\r\n hasCleanup: unsubscribers.has(dep),\r\n isComputed: !!dep._isComputed,\r\n }));\r\n },\r\n\r\n // Internal flags\r\n _isNixState: true, // Computed states behave like states\r\n _isComputed: true, // Flag to identify computed states\r\n };\r\n\r\n // Initial computation\r\n compute();\r\n\r\n // Store in hooks\r\n ctx.hooks[idx] = s;\r\n\r\n // Memory Leak Fix: Track for cleanup\r\n if (ctx.stateCleanups) {\r\n ctx.stateCleanups.push(() => s.cleanup());\r\n }\r\n }\r\n\r\n return ctx.hooks[idx];\r\n}"],
|
|
5
|
+
"mappings": ";;AAIA,SAAS,eAAe,wBAAwB;AA6DzC,SAAS,YAAY,WAAW;AACrC,QAAM,MAAM;AACZ,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,wCAAwC;AAGlE,MAAI,OAAO,cAAc,YAAY;AACnC,UAAM,IAAI,UAAU,iDAAiD;AAAA,EACvE;AAEA,QAAM,MAAM,IAAI;AAChB,MAAI,CAAC,IAAI,MAAM,GAAG,GAAG;AAYnB,QAAS,UAAT,WAAmB;AACjB,UAAI;AAAa,eAAO;AAGxB,UAAI,aAAa;AACf,gBAAQ,MAAM,4CAA4C;AAC1D,eAAO;AAAA,MACT;AAEA,oBAAc;AAGd,YAAM,kBAAkB;AAAA,QACtB,iBAAiB,oBAAI,IAAI;AAAA,QACzB,WAAW;AAAA,QACX,OAAO,CAAC;AAAA,QACR,gBAAg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O,YAAY;AAAA,MACrB;AAAA;AAAA;AAAA;AAAA;AAAA,MAMA,qBAAqB;AACnB,eAAO,aAAa;AAAA,MACtB;AAAA;AAAA;AAAA;AAAA;AAAA,MAMA,cAAc;AACZ,eAAO;AAAA,MACT;AAAA;AAAA;AAAA;AAAA;AAAA,MAMA,oBAAoB;AAClB,eAAO,MAAM,KAAK,YAAY,EAAE,IAAI,UAAQ;AAAA,UAC1C,OAAO;AAAA,UACP,YAAY,cAAc,IAAI,GAAG;AAAA,UACjC,YAAY,CAAC,CAAC,IAAI;AAAA,QACpB,EAAE;AAAA,MACJ;AAAA;AAAA,MAGA,aAAa;AAAA;AAAA,MACb,aAAa;AAAA;AAAA,IACf;AAGA,YAAQ;AAGR,QAAI,MAAM,GAAG,IAAI;AAGjB,QAAI,IAAI,eAAe;AACrB,UAAI,cAAc,KAAK,MAAM,EAAE,QAAQ,CAAC;AAAA,IAC1C;AAAA,EACF;AAEA,SAAO,IAAI,MAAM,GAAG;AACtB;AAjQgB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Debounce utility function with advanced options.
|
|
3
|
+
* Supports leading/trailing edge invocation, maxWait, and AbortController.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Debounce a function with options for leading, trailing, maxWait, and AbortController support.
|
|
7
|
+
*
|
|
8
|
+
* @param {Function} fn - The function to debounce
|
|
9
|
+
* @param {number} [delay=300] - Delay in milliseconds
|
|
10
|
+
* @param {Object} [options={}] - Debounce options
|
|
11
|
+
* @param {boolean} [options.leading=false] - Invoke on the leading edge
|
|
12
|
+
* @param {boolean} [options.trailing=true] - Invoke on the trailing edge
|
|
13
|
+
* @param {number} [options.maxWait] - Maximum wait time before forced invocation
|
|
14
|
+
* @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel pending calls
|
|
15
|
+
* @returns {Function} Debounced function with `.cancel()` method
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const controller = new AbortController();
|
|
19
|
+
* const debounced = nixDebounce(() => console.log('Hello'), 500, {
|
|
20
|
+
* leading: true,
|
|
21
|
+
* maxWait: 2000,
|
|
22
|
+
* signal: controller.signal
|
|
23
|
+
* });
|
|
24
|
+
* debounced();
|
|
25
|
+
* controller.abort(); // Cancel pending invocation
|
|
26
|
+
*/
|
|
27
|
+
export function nixDebounce(fn: Function, delay?: number, options?: {
|
|
28
|
+
leading?: boolean;
|
|
29
|
+
trailing?: boolean;
|
|
30
|
+
maxWait?: number;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}): Function;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
1
3
|
function nixDebounce(fn, delay = 300, options = {}) {
|
|
2
4
|
let timerId = null;
|
|
3
5
|
let lastInvokeTime = 0;
|
|
@@ -14,14 +16,14 @@ function nixDebounce(fn, delay = 300, options = {}) {
|
|
|
14
16
|
lastThis = null;
|
|
15
17
|
});
|
|
16
18
|
}
|
|
17
|
-
const invoke = () => {
|
|
19
|
+
const invoke = /* @__PURE__ */ __name(() => {
|
|
18
20
|
lastInvokeTime = Date.now();
|
|
19
21
|
if (lastArgs) {
|
|
20
22
|
fn.apply(lastThis, lastArgs);
|
|
21
23
|
lastArgs = lastThis = null;
|
|
22
24
|
}
|
|
23
|
-
};
|
|
24
|
-
const debounced = function(...args) {
|
|
25
|
+
}, "invoke");
|
|
26
|
+
const debounced = /* @__PURE__ */ __name(function(...args) {
|
|
25
27
|
const now = Date.now();
|
|
26
28
|
lastArgs = args;
|
|
27
29
|
lastThis = this;
|
|
@@ -43,7 +45,7 @@ function nixDebounce(fn, delay = 300, options = {}) {
|
|
|
43
45
|
if (trailing) {
|
|
44
46
|
timerId = setTimeout(invoke, remainingTime > 0 ? remainingTime : delay);
|
|
45
47
|
}
|
|
46
|
-
};
|
|
48
|
+
}, "debounced");
|
|
47
49
|
debounced.cancel = () => {
|
|
48
50
|
if (timerId)
|
|
49
51
|
clearTimeout(timerId);
|
|
@@ -51,6 +53,7 @@ function nixDebounce(fn, delay = 300, options = {}) {
|
|
|
51
53
|
};
|
|
52
54
|
return debounced;
|
|
53
55
|
}
|
|
56
|
+
__name(nixDebounce, "nixDebounce");
|
|
54
57
|
export {
|
|
55
58
|
nixDebounce
|
|
56
59
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../hooks/nixDebounce.js"],
|
|
4
|
-
"sourcesContent": ["/**\r\n * Debounce a function with options for leading, trailing, maxWait, and AbortController support.\r\n *\r\n * @param {Function} fn - The function to debounce
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["/**\r\n * @fileoverview Debounce utility function with advanced options.\r\n * Supports leading/trailing edge invocation, maxWait, and AbortController.\r\n */\r\n\r\n/**\r\n * Debounce a function with options for leading, trailing, maxWait, and AbortController support.\r\n *\r\n * @param {Function} fn - The function to debounce\r\n * @param {number} [delay=300] - Delay in milliseconds\r\n * @param {Object} [options={}] - Debounce options\r\n * @param {boolean} [options.leading=false] - Invoke on the leading edge\r\n * @param {boolean} [options.trailing=true] - Invoke on the trailing edge\r\n * @param {number} [options.maxWait] - Maximum wait time before forced invocation\r\n * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel pending calls\r\n * @returns {Function} Debounced function with `.cancel()` method\r\n *\r\n * @example\r\n * const controller = new AbortController();\r\n * const debounced = nixDebounce(() => console.log('Hello'), 500, {\r\n * leading: true,\r\n * maxWait: 2000,\r\n * signal: controller.signal\r\n * });\r\n * debounced();\r\n * controller.abort(); // Cancel pending invocation\r\n */\r\nexport function nixDebounce(fn, delay = 300, options = {}) {\r\n let timerId = null;\r\n let lastInvokeTime = 0;\r\n let lastArgs;\r\n let lastThis;\r\n\r\n const { leading = false, trailing = true, maxWait, signal } = options;\r\n\r\n if (signal) {\r\n signal.addEventListener(\"abort\", () => {\r\n if (timerId) {\r\n clearTimeout(timerId);\r\n timerId = null;\r\n }\r\n lastArgs = null;\r\n lastThis = null;\r\n });\r\n }\r\n\r\n const invoke = () => {\r\n lastInvokeTime = Date.now();\r\n if (lastArgs) {\r\n fn.apply(lastThis, lastArgs);\r\n lastArgs = lastThis = null;\r\n }\r\n };\r\n\r\n const debounced = function (...args) {\r\n const now = Date.now();\r\n lastArgs = args;\r\n lastThis = this;\r\n\r\n const shouldInvokeLeading = leading && !timerId;\r\n const timeSinceLastInvoke = now - lastInvokeTime;\r\n const remainingTime = delay - timeSinceLastInvoke;\r\n\r\n if (maxWait !== undefined && timeSinceLastInvoke >= maxWait) {\r\n if (timerId) clearTimeout(timerId);\r\n timerId = null;\r\n invoke();\r\n return;\r\n }\r\n\r\n if (timerId) clearTimeout(timerId);\r\n\r\n if (shouldInvokeLeading) {\r\n invoke();\r\n }\r\n\r\n if (trailing) {\r\n timerId = setTimeout(invoke, remainingTime > 0 ? remainingTime : delay);\r\n }\r\n };\r\n\r\n debounced.cancel = () => {\r\n if (timerId) clearTimeout(timerId);\r\n timerId = lastArgs = lastThis = null;\r\n };\r\n\r\n return debounced;\r\n}\r\n"],
|
|
5
|
+
"mappings": ";;AA2BO,SAAS,YAAY,IAAI,QAAQ,KAAK,UAAU,CAAC,GAAG;AACzD,MAAI,UAAU;AACd,MAAI,iBAAiB;AACrB,MAAI;AACJ,MAAI;AAEJ,QAAM,EAAE,UAAU,OAAO,WAAW,MAAM,SAAS,OAAO,IAAI;AAE9D,MAAI,QAAQ;AACV,WAAO,iBAAiB,SAAS,MAAM;AACrC,UAAI,SAAS;AACX,qBAAa,OAAO;AACpB,kBAAU;AAAA,MACZ;AACA,iBAAW;AACX,iBAAW;AAAA,IACb,CAAC;AAAA,EACH;AAEA,QAAM,SAAS,6BAAM;AACnB,qBAAiB,KAAK,IAAI;AAC1B,QAAI,UAAU;AACZ,SAAG,MAAM,UAAU,QAAQ;AAC3B,iBAAW,WAAW;AAAA,IACxB;AAAA,EACF,GANe;AAQf,QAAM,YAAY,mCAAa,MAAM;AACnC,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW;AACX,eAAW;AAEX,UAAM,sBAAsB,WAAW,CAAC;AACxC,UAAM,sBAAsB,MAAM;AAClC,UAAM,gBAAgB,QAAQ;AAE9B,QAAI,YAAY,UAAa,uBAAuB,SAAS;AAC3D,UAAI;AAAS,qBAAa,OAAO;AACjC,gBAAU;AACV,aAAO;AACP;AAAA,IACF;AAEA,QAAI;AAAS,mBAAa,OAAO;AAEjC,QAAI,qBAAqB;AACvB,aAAO;AAAA,IACT;AAEA,QAAI,UAAU;AACZ,gBAAU,WAAW,QAAQ,gBAAgB,IAAI,gBAAgB,KAAK;AAAA,IACxE;AAAA,EACF,GAzBkB;AA2BlB,YAAU,SAAS,MAAM;AACvB,QAAI;AAAS,mBAAa,OAAO;AACjC,cAAU,WAAW,WAAW;AAAA,EAClC;AAEA,SAAO;AACT;AA5DgB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Execute side effects in a component with automatic cleanup.
|
|
3
|
+
* Similar to React's useEffect.
|
|
4
|
+
*
|
|
5
|
+
* @param {() => (void | (() => void))} effect - Effect function, optionally returns cleanup function
|
|
6
|
+
* @param {Array<any>} [deps=[]] - Dependency array. Effect re-runs when dependencies change.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* // Run once on mount
|
|
10
|
+
* nixEffect(() => {
|
|
11
|
+
* console.log('Component mounted');
|
|
12
|
+
* return () => console.log('Component unmounted');
|
|
13
|
+
* }, []);
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* // Run when count changes
|
|
17
|
+
* const count = nixState(0);
|
|
18
|
+
* nixEffect(() => {
|
|
19
|
+
* console.log('Count is:', count.value);
|
|
20
|
+
* }, [count.value]);
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* // Timer with cleanup
|
|
24
|
+
* nixEffect(() => {
|
|
25
|
+
* const timer = setInterval(() => console.log('tick'), 1000);
|
|
26
|
+
* return () => clearInterval(timer);
|
|
27
|
+
* }, []);
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* // Event listener with cleanup
|
|
31
|
+
* nixEffect(() => {
|
|
32
|
+
* const handler = (e) => console.log('clicked', e);
|
|
33
|
+
* document.addEventListener('click', handler);
|
|
34
|
+
* return () => document.removeEventListener('click', handler);
|
|
35
|
+
* }, []);
|
|
36
|
+
*
|
|
37
|
+
* @throws {Error} If called outside a component context
|
|
38
|
+
*/
|
|
39
|
+
export function nixEffect(effect: () => (void | (() => void)), deps?: Array<any>): void;
|
|
40
|
+
/**
|
|
41
|
+
* Run an effect only once on component mount.
|
|
42
|
+
* Convenience wrapper around nixEffect.
|
|
43
|
+
*
|
|
44
|
+
* @param {() => (void | (() => void))} effect - Effect function
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* nixEffectOnce(() => {
|
|
48
|
+
* console.log('Mounted');
|
|
49
|
+
* return () => console.log('Unmounted');
|
|
50
|
+
* });
|
|
51
|
+
*/
|
|
52
|
+
export function nixEffectOnce(effect: () => (void | (() => void))): void;
|
|
53
|
+
/**
|
|
54
|
+
* Run an effect every time the component renders.
|
|
55
|
+
* Use with caution - can cause performance issues.
|
|
56
|
+
*
|
|
57
|
+
* @param {() => (void | (() => void))} effect - Effect function
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* nixEffectAlways(() => {
|
|
61
|
+
* console.log('Component rendered');
|
|
62
|
+
* });
|
|
63
|
+
*/
|
|
64
|
+
export function nixEffectAlways(effect: () => (void | (() => void))): void;
|
package/dist/hooks/nixEffect.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
1
3
|
import { activeContext } from "../context/context";
|
|
2
4
|
function nixEffect(effect, deps = []) {
|
|
3
5
|
const ctx = activeContext;
|
|
@@ -48,6 +50,7 @@ function nixEffect(effect, deps = []) {
|
|
|
48
50
|
}
|
|
49
51
|
}
|
|
50
52
|
}
|
|
53
|
+
__name(nixEffect, "nixEffect");
|
|
51
54
|
function shallowArrayEqual(arr1, arr2) {
|
|
52
55
|
if (arr1.length !== arr2.length)
|
|
53
56
|
return false;
|
|
@@ -58,9 +61,11 @@ function shallowArrayEqual(arr1, arr2) {
|
|
|
58
61
|
}
|
|
59
62
|
return true;
|
|
60
63
|
}
|
|
64
|
+
__name(shallowArrayEqual, "shallowArrayEqual");
|
|
61
65
|
function nixEffectOnce(effect) {
|
|
62
66
|
return nixEffect(effect, []);
|
|
63
67
|
}
|
|
68
|
+
__name(nixEffectOnce, "nixEffectOnce");
|
|
64
69
|
function nixEffectAlways(effect) {
|
|
65
70
|
const ctx = activeContext;
|
|
66
71
|
if (!ctx)
|
|
@@ -71,6 +76,7 @@ function nixEffectAlways(effect) {
|
|
|
71
76
|
}
|
|
72
77
|
return nixEffect(effect, [ctx.version]);
|
|
73
78
|
}
|
|
79
|
+
__name(nixEffectAlways, "nixEffectAlways");
|
|
74
80
|
export {
|
|
75
81
|
nixEffect,
|
|
76
82
|
nixEffectAlways,
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../hooks/nixEffect.js"],
|
|
4
4
|
"sourcesContent": ["/* ----------------------\r\n nixEffect - Side Effects Hook\r\n Memory Leaks & Security Issues Resolved\r\n---------------------- */\r\nimport { activeContext } from \"../context/context\";\r\n\r\n/**\r\n * Execute side effects in a component with automatic cleanup.\r\n * Similar to React's useEffect.\r\n * \r\n * @param {() => (void | (() => void))} effect - Effect function, optionally returns cleanup function\r\n * @param {Array<any>} [deps=[]] - Dependency array. Effect re-runs when dependencies change.\r\n * \r\n * @example\r\n * // Run once on mount\r\n * nixEffect(() => {\r\n * console.log('Component mounted');\r\n * return () => console.log('Component unmounted');\r\n * }, []);\r\n * \r\n * @example\r\n * // Run when count changes\r\n * const count = nixState(0);\r\n * nixEffect(() => {\r\n * console.log('Count is:', count.value);\r\n * }, [count.value]);\r\n * \r\n * @example\r\n * // Timer with cleanup\r\n * nixEffect(() => {\r\n * const timer = setInterval(() => console.log('tick'), 1000);\r\n * return () => clearInterval(timer);\r\n * }, []);\r\n * \r\n * @example\r\n * // Event listener with cleanup\r\n * nixEffect(() => {\r\n * const handler = (e) => console.log('clicked', e);\r\n * document.addEventListener('click', handler);\r\n * return () => document.removeEventListener('click', handler);\r\n * }, []);\r\n * \r\n * @throws {Error} If called outside a component context\r\n */\r\nexport function nixEffect(effect, deps = []) {\r\n const ctx = activeContext;\r\n if (!ctx) throw new Error(\"nixEffect() called outside component\");\r\n\r\n // Security: Validate effect function\r\n if (typeof effect !== 'function') {\r\n console.error('[nixEffect] First argument must be a function');\r\n return;\r\n }\r\n\r\n // Security: Validate deps array\r\n if (!Array.isArray(deps)) {\r\n console.error('[nixEffect] Second argument must be an array');\r\n deps = [];\r\n }\r\n\r\n // Security: Limit dependency array size to prevent DOS\r\n const MAX_DEPS = 100;\r\n if (deps.length > MAX_DEPS) {\r\n console.warn(`[nixEffect] Dependency array too large (${deps.length}). Limited to ${MAX_DEPS}.`);\r\n deps = deps.slice(0, MAX_DEPS);\r\n }\r\n\r\n const idx = ctx.hookIndex++;\r\n const prev = ctx.hooks[idx];\r\n\r\n // Performance & Security: Deep comparison instead of JSON.stringify\r\n // JSON.stringify issues:\r\n // 1. Can throw on circular references\r\n // 2. Fails on undefined, functions, symbols\r\n // 3. Performance issue with large objects\r\n // 4. Security: Can expose internal object structure\r\n const hasChanged = !prev || !shallowArrayEqual(prev.deps, deps);\r\n\r\n if (hasChanged) {\r\n // Memory Leak Fix: Clean up previous effect\r\n if (prev?.cleanup) {\r\n try {\r\n if (typeof prev.cleanup === 'function') {\r\n prev.cleanup();\r\n }\r\n } catch (err) {\r\n console.error('[nixEffect] Cleanup error:', err);\r\n }\r\n }\r\n\r\n // Run the new effect\r\n let cleanup;\r\n try {\r\n cleanup = effect();\r\n \r\n // Validate cleanup return value\r\n if (cleanup !== undefined && typeof cleanup !== 'function') {\r\n console.warn('[nixEffect] Effect should return undefined or a cleanup function');\r\n cleanup = undefined;\r\n }\r\n } catch (err) {\r\n console.error('[nixEffect] Effect error:', err);\r\n cleanup = undefined;\r\n }\r\n\r\n // Store effect data\r\n ctx.hooks[idx] = { deps, cleanup };\r\n\r\n // Memory Leak Fix: Track cleanup for component unmount\r\n if (cleanup && typeof cleanup === 'function') {\r\n if (!ctx.cleanups) ctx.cleanups = [];\r\n ctx.cleanups.push(cleanup);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Shallow comparison of two arrays for dependency checking.\r\n * More reliable and secure than JSON.stringify.\r\n * \r\n * @param {Array<any>} arr1 - First array\r\n * @param {Array<any>} arr2 - Second array\r\n * @returns {boolean} True if arrays are shallowly equal\r\n */\r\nfunction shallowArrayEqual(arr1, arr2) {\r\n if (arr1.length !== arr2.length) return false;\r\n \r\n for (let i = 0; i < arr1.length; i++) {\r\n // Use Object.is for proper comparison (handles NaN, -0, +0)\r\n if (!Object.is(arr1[i], arr2[i])) {\r\n return false;\r\n }\r\n }\r\n \r\n return true;\r\n}\r\n\r\n/**\r\n * Run an effect only once on component mount.\r\n * Convenience wrapper around nixEffect.\r\n * \r\n * @param {() => (void | (() => void))} effect - Effect function\r\n * \r\n * @example\r\n * nixEffectOnce(() => {\r\n * console.log('Mounted');\r\n * return () => console.log('Unmounted');\r\n * });\r\n */\r\nexport function nixEffectOnce(effect) {\r\n return nixEffect(effect, []);\r\n}\r\n\r\n/**\r\n * Run an effect every time the component renders.\r\n * Use with caution - can cause performance issues.\r\n * \r\n * @param {() => (void | (() => void))} effect - Effect function\r\n * \r\n * @example\r\n * nixEffectAlways(() => {\r\n * console.log('Component rendered');\r\n * });\r\n */\r\nexport function nixEffectAlways(effect) {\r\n const ctx = activeContext;\r\n if (!ctx) throw new Error(\"nixEffectAlways() called outside component\");\r\n \r\n if (typeof effect !== 'function') {\r\n console.error('[nixEffectAlways] Argument must be a function');\r\n return;\r\n }\r\n\r\n // Always run by using a unique dependency each time\r\n return nixEffect(effect, [ctx.version]);\r\n}"],
|
|
5
|
-
"mappings": "AAIA,SAAS,qBAAqB;AAwCvB,SAAS,UAAU,QAAQ,OAAO,CAAC,GAAG;AAC3C,QAAM,MAAM;AACZ,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,sCAAsC;AAGhE,MAAI,OAAO,WAAW,YAAY;AAChC,YAAQ,MAAM,+CAA+C;AAC7D;AAAA,EACF;AAGA,MAAI,CAAC,MAAM,QAAQ,IAAI,GAAG;AACxB,YAAQ,MAAM,8CAA8C;AAC5D,WAAO,CAAC;AAAA,EACV;AAGA,QAAM,WAAW;AACjB,MAAI,KAAK,SAAS,UAAU;AAC1B,YAAQ,KAAK,2CAA2C,KAAK,MAAM,iBAAiB,QAAQ,GAAG;AAC/F,WAAO,KAAK,MAAM,GAAG,QAAQ;AAAA,EAC/B;AAEA,QAAM,MAAM,IAAI;AAChB,QAAM,OAAO,IAAI,MAAM,GAAG;AAQ1B,QAAM,aAAa,CAAC,QAAQ,CAAC,kBAAkB,KAAK,MAAM,IAAI;AAE9D,MAAI,YAAY;AAEd,QAAI,MAAM,SAAS;AACjB,UAAI;AACF,YAAI,OAAO,KAAK,YAAY,YAAY;AACtC,eAAK,QAAQ;AAAA,QACf;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,MAAM,8BAA8B,GAAG;AAAA,MACjD;AAAA,IACF;AAGA,QAAI;AACJ,QAAI;AACF,gBAAU,OAAO;AAGjB,UAAI,YAAY,UAAa,OAAO,YAAY,YAAY;AAC1D,gBAAQ,KAAK,kEAAkE;AAC/E,kBAAU;AAAA,MACZ;AAAA,IACF,SAAS,KAAK;AACZ,cAAQ,MAAM,6BAA6B,GA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AM,6BAA6B,GAAG;AAC9C,gBAAU;AAAA,IACZ;AAGA,QAAI,MAAM,GAAG,IAAI,EAAE,MAAM,QAAQ;AAGjC,QAAI,WAAW,OAAO,YAAY,YAAY;AAC5C,UAAI,CAAC,IAAI;AAAU,YAAI,WAAW,CAAC;AACnC,UAAI,SAAS,KAAK,OAAO;AAAA,IAC3B;AAAA,EACF;AACF;AAtEgB;AAgFhB,SAAS,kBAAkB,MAAM,MAAM;AACrC,MAAI,KAAK,WAAW,KAAK;AAAQ,WAAO;AAExC,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AAEpC,QAAI,CAAC,OAAO,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG;AAChC,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAXS;AAyBF,SAAS,cAAc,QAAQ;AACpC,SAAO,UAAU,QAAQ,CAAC,CAAC;AAC7B;AAFgB;AAeT,SAAS,gBAAgB,QAAQ;AACtC,QAAM,MAAM;AACZ,MAAI,CAAC;AAAK,UAAM,IAAI,MAAM,4CAA4C;AAEtE,MAAI,OAAO,WAAW,YAAY;AAChC,YAAQ,MAAM,+CAA+C;AAC7D;AAAA,EACF;AAGA,SAAO,UAAU,QAAQ,CAAC,IAAI,OAAO,CAAC;AACxC;AAXgB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reactive form handler with validation, reactive state, and safe async submit.
|
|
3
|
+
*
|
|
4
|
+
* @param {Object} [initialValues={}] - Initial values for form fields.
|
|
5
|
+
* @param {Object} [validationRules={}] - Validation rules for fields.
|
|
6
|
+
* @returns {Object} Form utilities: values, errors, touched, isSubmitting, isValid,
|
|
7
|
+
* handleChange, handleBlur, handleSubmit, reset, getFieldProps, cancelSubmit
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const form = nixForm({ email: "" }, {
|
|
11
|
+
* email: { required: true, pattern: /^\S+@\S+$/, message: "Invalid email" }
|
|
12
|
+
* });
|
|
13
|
+
* form.handleSubmit(async (values) => { await api.submit(values); });
|
|
14
|
+
*/
|
|
15
|
+
export function nixForm(initialValues?: any, validationRules?: any): any;
|