@cyberskill/shared 3.12.0 → 3.14.0

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 (254) hide show
  1. package/dist/config/commitlint/index.d.ts +5 -1
  2. package/dist/{src/config → config}/config.type.d.ts +1 -1
  3. package/dist/{src/config → config}/config.util.d.ts +1 -1
  4. package/dist/{src/config → config}/env/env.util.d.ts +5 -0
  5. package/dist/config/env/env.util.js +20 -16
  6. package/dist/config/env/env.util.js.map +1 -1
  7. package/dist/config/env/index.d.ts +3 -1
  8. package/dist/config/env/index.js +2 -2
  9. package/dist/config/eslint/index.d.ts +1198 -1
  10. package/dist/config/graphql-codegen/index.d.ts +2 -1
  11. package/dist/config/index.d.ts +2 -1
  12. package/dist/config/lint-staged/index.d.ts +5 -1
  13. package/dist/config/storybook/index.d.ts +2 -1
  14. package/dist/config/vitest/index.d.ts +3 -1
  15. package/dist/config/vitest/vitest.e2e.d.ts +20 -1
  16. package/dist/config/vitest/vitest.e2e.js +4 -4
  17. package/dist/config/vitest/vitest.e2e.js.map +1 -1
  18. package/dist/config/vitest/vitest.unit.d.ts +22 -1
  19. package/dist/config/vitest/vitest.unit.js +5 -5
  20. package/dist/config/vitest/vitest.unit.js.map +1 -1
  21. package/dist/config/vitest/vitest.unit.setup.js +10 -0
  22. package/dist/config/vitest/vitest.unit.setup.js.map +1 -0
  23. package/dist/constant/index.d.ts +5 -1
  24. package/dist/node/apollo-server/apollo-server.type.d.ts +20 -0
  25. package/dist/{src/node → node}/apollo-server/apollo-server.util.d.ts +1 -0
  26. package/dist/node/apollo-server/apollo-server.util.js +40 -16
  27. package/dist/node/apollo-server/apollo-server.util.js.map +1 -1
  28. package/dist/node/apollo-server/index.d.ts +2 -1
  29. package/dist/node/cli/index.d.ts +2 -1
  30. package/dist/node/cli/index.js +26 -28
  31. package/dist/node/cli/index.js.map +1 -1
  32. package/dist/{src/node → node}/command/command.util.d.ts +5 -0
  33. package/dist/node/command/command.util.js +49 -48
  34. package/dist/node/command/command.util.js.map +1 -1
  35. package/dist/node/command/index.d.ts +2 -1
  36. package/dist/node/command/index.js +2 -2
  37. package/dist/{src/node → node}/express/express.type.d.ts +11 -0
  38. package/dist/{src/node → node}/express/express.util.d.ts +34 -6
  39. package/dist/node/express/express.util.js +81 -56
  40. package/dist/node/express/express.util.js.map +1 -1
  41. package/dist/node/express/index.d.ts +2 -1
  42. package/dist/node/express/index.js +2 -2
  43. package/dist/node/fs/index.d.ts +2 -1
  44. package/dist/node/log/index.d.ts +2 -1
  45. package/dist/node/log/log.type.d.ts +46 -0
  46. package/dist/node/log/log.type.js.map +1 -1
  47. package/dist/{src/node → node}/log/log.util.d.ts +1 -1
  48. package/dist/node/log/log.util.js +25 -11
  49. package/dist/node/log/log.util.js.map +1 -1
  50. package/dist/node/mongo/index.d.ts +7 -1
  51. package/dist/node/mongo/index.js +7 -8
  52. package/dist/{src/node → node}/mongo/mongo.constant.d.ts +5 -0
  53. package/dist/node/mongo/mongo.constant.js +2 -2
  54. package/dist/node/mongo/mongo.constant.js.map +1 -1
  55. package/dist/{src/node → node}/mongo/mongo.controller.helpers.d.ts +1 -1
  56. package/dist/{src/node → node}/mongo/mongo.controller.mongoose.d.ts +4 -1
  57. package/dist/node/mongo/mongo.controller.mongoose.js +41 -55
  58. package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
  59. package/dist/{src/node → node}/mongo/mongo.controller.native.d.ts +30 -3
  60. package/dist/node/mongo/mongo.controller.native.js +31 -14
  61. package/dist/node/mongo/mongo.controller.native.js.map +1 -1
  62. package/dist/{src/node → node}/mongo/mongo.controller.type.d.ts +1 -1
  63. package/dist/{src/node → node}/mongo/mongo.type.d.ts +3 -1
  64. package/dist/{src/node → node}/mongo/mongo.util.d.ts +1 -0
  65. package/dist/node/mongo/mongo.util.js +38 -17
  66. package/dist/node/mongo/mongo.util.js.map +1 -1
  67. package/dist/node/package/index.d.ts +2 -1
  68. package/dist/{src/node → node}/package/package.util.d.ts +1 -1
  69. package/dist/node/package/package.util.js +47 -47
  70. package/dist/node/path/index.d.ts +2 -1
  71. package/dist/node/path/index.js +2 -2
  72. package/dist/{src/node → node}/path/path.constant.d.ts +4 -0
  73. package/dist/node/path/path.constant.js +75 -72
  74. package/dist/node/path/path.constant.js.map +1 -1
  75. package/dist/node/storage/index.d.ts +3 -1
  76. package/dist/{src/node → node}/storage/storage.util.d.ts +50 -1
  77. package/dist/node/storage/storage.util.js +79 -54
  78. package/dist/node/storage/storage.util.js.map +1 -1
  79. package/dist/node/upload/index.d.ts +3 -1
  80. package/dist/{src/node → node}/upload/upload.type.d.ts +2 -0
  81. package/dist/node/upload/upload.type.js.map +1 -1
  82. package/dist/{src/node → node}/upload/upload.util.d.ts +2 -1
  83. package/dist/node/upload/upload.util.js +62 -52
  84. package/dist/node/upload/upload.util.js.map +1 -1
  85. package/dist/node/ws/index.d.ts +2 -1
  86. package/dist/{src/node → node}/ws/ws.util.d.ts +7 -0
  87. package/dist/node/ws/ws.util.js +20 -19
  88. package/dist/node/ws/ws.util.js.map +1 -1
  89. package/dist/react/apollo-client/apollo-client.component.js.map +1 -1
  90. package/dist/{src/react → react}/apollo-client/apollo-client.type.d.ts +3 -1
  91. package/dist/react/apollo-client/apollo-client.util.js +6 -6
  92. package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
  93. package/dist/react/apollo-client/index.d.ts +9 -1
  94. package/dist/react/apollo-client/links/index.d.ts +1 -1
  95. package/dist/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +16 -1
  96. package/dist/react/apollo-client-nextjs/index.d.ts +2 -1
  97. package/dist/react/apollo-error/apollo-error.component.js +1 -1
  98. package/dist/react/apollo-error/apollo-error.component.js.map +1 -1
  99. package/dist/react/apollo-error/apollo-error.util.js.map +1 -1
  100. package/dist/react/apollo-error/index.d.ts +6 -1
  101. package/dist/react/i18next/i18next.server.d.ts +17 -0
  102. package/dist/react/i18next/i18next.server.js +9 -0
  103. package/dist/react/i18next/i18next.server.js.map +1 -0
  104. package/dist/react/i18next/index.d.ts +2 -1
  105. package/dist/react/loading/index.d.ts +5 -1
  106. package/dist/{src/react → react}/loading/loading.provider.d.ts +1 -1
  107. package/dist/react/log/index.d.ts +2 -1
  108. package/dist/react/log/log.type.d.ts +1 -0
  109. package/dist/{src/react → react}/log/log.util.d.ts +1 -1
  110. package/dist/react/next-intl/index.d.ts +6 -1
  111. package/dist/{src/react → react}/next-intl/next-intl.hoc.d.ts +5 -9
  112. package/dist/react/next-intl/next-intl.hoc.js +14 -10
  113. package/dist/react/next-intl/next-intl.hoc.js.map +1 -1
  114. package/dist/react/next-intl/next-intl.server.d.ts +10 -0
  115. package/dist/react/next-intl/next-intl.server.js +7 -0
  116. package/dist/react/next-intl/next-intl.server.js.map +1 -0
  117. package/dist/{src/react → react}/next-intl/next-intl.type.d.ts +1 -1
  118. package/dist/react/storage/index.d.ts +2 -1
  119. package/dist/{src/react → react}/storage/storage.hook.d.ts +1 -1
  120. package/dist/{src/react → react}/storage/storage.util.d.ts +34 -1
  121. package/dist/react/storage/storage.util.js +30 -5
  122. package/dist/react/storage/storage.util.js.map +1 -1
  123. package/dist/react/toast/index.d.ts +1 -1
  124. package/dist/react/userback/index.d.ts +2 -1
  125. package/dist/react/userback/userback.component.js.map +1 -1
  126. package/dist/{src/typescript → typescript}/common.type.d.ts +4 -0
  127. package/dist/typescript/common.type.js +2 -2
  128. package/dist/typescript/common.type.js.map +1 -1
  129. package/dist/typescript/index.d.ts +5 -1
  130. package/dist/typescript/index.js +2 -2
  131. package/dist/util/common/index.d.ts +5 -1
  132. package/dist/util/index.d.ts +9 -1
  133. package/dist/util/log/index.d.ts +2 -1
  134. package/dist/{src/util → util}/log/log.util.d.ts +1 -1
  135. package/dist/util/object/index.d.ts +4 -1
  136. package/dist/util/object/object.util.js +29 -18
  137. package/dist/util/object/object.util.js.map +1 -1
  138. package/dist/util/serializer/index.d.ts +2 -1
  139. package/dist/{src/util → util}/serializer/serializer.util.d.ts +8 -0
  140. package/dist/util/serializer/serializer.util.js +51 -64
  141. package/dist/util/serializer/serializer.util.js.map +1 -1
  142. package/dist/util/storage/storage-envelope.d.ts +25 -0
  143. package/dist/util/storage/storage-envelope.js +18 -0
  144. package/dist/util/storage/storage-envelope.js.map +1 -0
  145. package/dist/util/string/index.d.ts +5 -1
  146. package/dist/util/validate/index.d.ts +4 -1
  147. package/package.json +33 -12
  148. package/dist/node/mongo/mongo.type.js +0 -8
  149. package/dist/node/mongo/mongo.type.js.map +0 -1
  150. package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js +0 -8
  151. package/dist/node_modules/.pnpm/vitest@4.1.2_@types_node@25.5.0_jsdom@29.0.1_@noble_hashes@1.8.0__vite@8.0.3_@types_nod_0827261ede788764a5d99ac6bdf44bde/node_modules/vitest/dist/config.js.map +0 -1
  152. package/dist/src/config/commitlint/index.d.ts +0 -5
  153. package/dist/src/config/env/index.d.ts +0 -3
  154. package/dist/src/config/eslint/index.d.ts +0 -1198
  155. package/dist/src/config/graphql-codegen/index.d.ts +0 -2
  156. package/dist/src/config/index.d.ts +0 -2
  157. package/dist/src/config/lint-staged/index.d.ts +0 -5
  158. package/dist/src/config/storybook/index.d.ts +0 -2
  159. package/dist/src/config/vitest/index.d.ts +0 -3
  160. package/dist/src/config/vitest/vitest.e2e.d.ts +0 -20
  161. package/dist/src/config/vitest/vitest.unit.d.ts +0 -22
  162. package/dist/src/constant/index.d.ts +0 -5
  163. package/dist/src/node/apollo-server/apollo-server.type.d.ts +0 -8
  164. package/dist/src/node/apollo-server/index.d.ts +0 -2
  165. package/dist/src/node/cli/index.d.ts +0 -2
  166. package/dist/src/node/command/index.d.ts +0 -2
  167. package/dist/src/node/express/index.d.ts +0 -2
  168. package/dist/src/node/fs/index.d.ts +0 -2
  169. package/dist/src/node/log/index.d.ts +0 -2
  170. package/dist/src/node/log/log.type.d.ts +0 -29
  171. package/dist/src/node/mongo/index.d.ts +0 -6
  172. package/dist/src/node/package/index.d.ts +0 -2
  173. package/dist/src/node/path/index.d.ts +0 -2
  174. package/dist/src/node/storage/index.d.ts +0 -3
  175. package/dist/src/node/upload/index.d.ts +0 -3
  176. package/dist/src/node/ws/index.d.ts +0 -2
  177. package/dist/src/react/apollo-client/index.d.ts +0 -9
  178. package/dist/src/react/apollo-client/links/index.d.ts +0 -1
  179. package/dist/src/react/apollo-client-nextjs/apollo-client-nextjs.rsc.d.ts +0 -16
  180. package/dist/src/react/apollo-client-nextjs/index.d.ts +0 -2
  181. package/dist/src/react/apollo-error/index.d.ts +0 -6
  182. package/dist/src/react/i18next/index.d.ts +0 -2
  183. package/dist/src/react/loading/index.d.ts +0 -5
  184. package/dist/src/react/log/index.d.ts +0 -2
  185. package/dist/src/react/log/log.type.d.ts +0 -1
  186. package/dist/src/react/next-intl/index.d.ts +0 -6
  187. package/dist/src/react/storage/index.d.ts +0 -2
  188. package/dist/src/react/toast/index.d.ts +0 -1
  189. package/dist/src/react/userback/index.d.ts +0 -2
  190. package/dist/src/typescript/index.d.ts +0 -5
  191. package/dist/src/util/common/index.d.ts +0 -5
  192. package/dist/src/util/index.d.ts +0 -9
  193. package/dist/src/util/log/index.d.ts +0 -2
  194. package/dist/src/util/object/index.d.ts +0 -4
  195. package/dist/src/util/serializer/index.d.ts +0 -2
  196. package/dist/src/util/string/index.d.ts +0 -5
  197. package/dist/src/util/validate/index.d.ts +0 -4
  198. /package/dist/{src/config → config}/env/env.constant.d.ts +0 -0
  199. /package/dist/{src/config → config}/env/env.type.d.ts +0 -0
  200. /package/dist/{src/config → config}/graphql-codegen/graphql-codegen.type.d.ts +0 -0
  201. /package/dist/{src/config → config}/graphql-codegen/graphql-codegen.util.d.ts +0 -0
  202. /package/dist/{src/config → config}/storybook/storybook.main.d.ts +0 -0
  203. /package/dist/{src/config → config}/storybook/storybook.preview.d.ts +0 -0
  204. /package/dist/{src/config → config}/vitest/vitest.unit.setup.d.ts +0 -0
  205. /package/dist/{src/constant → constant}/common.d.ts +0 -0
  206. /package/dist/{src/constant → constant}/response-status.d.ts +0 -0
  207. /package/dist/{src/node → node}/command/command.type.d.ts +0 -0
  208. /package/dist/{src/node → node}/fs/fs.type.d.ts +0 -0
  209. /package/dist/{src/node → node}/fs/fs.util.d.ts +0 -0
  210. /package/dist/{src/node → node}/mongo/mongo.controller.d.ts +0 -0
  211. /package/dist/{src/node → node}/mongo/mongo.dynamic-populate.d.ts +0 -0
  212. /package/dist/{src/node → node}/mongo/mongo.internal-types.d.ts +0 -0
  213. /package/dist/{src/node → node}/mongo/mongo.populate.d.ts +0 -0
  214. /package/dist/{src/node → node}/package/package.type.d.ts +0 -0
  215. /package/dist/{src/node → node}/path/path.util.d.ts +0 -0
  216. /package/dist/{src/node → node}/storage/storage.constant.d.ts +0 -0
  217. /package/dist/{src/node → node}/storage/storage.type.d.ts +0 -0
  218. /package/dist/{src/node → node}/upload/upload.constant.d.ts +0 -0
  219. /package/dist/{src/node → node}/ws/ws.type.d.ts +0 -0
  220. /package/dist/{src/react → react}/apollo-client/apollo-client.component.d.ts +0 -0
  221. /package/dist/{src/react → react}/apollo-client/apollo-client.constant.d.ts +0 -0
  222. /package/dist/{src/react → react}/apollo-client/apollo-client.context.d.ts +0 -0
  223. /package/dist/{src/react → react}/apollo-client/apollo-client.hook.d.ts +0 -0
  224. /package/dist/{src/react → react}/apollo-client/apollo-client.util.d.ts +0 -0
  225. /package/dist/{src/react → react}/apollo-client/links/upload.d.ts +0 -0
  226. /package/dist/{src/react → react}/apollo-client-nextjs/apollo-client-nextjs.component.d.ts +0 -0
  227. /package/dist/{src/react → react}/apollo-client-nextjs/apollo-client-nextjs.util.d.ts +0 -0
  228. /package/dist/{src/react → react}/apollo-error/apollo-error.component.d.ts +0 -0
  229. /package/dist/{src/react → react}/apollo-error/apollo-error.context.d.ts +0 -0
  230. /package/dist/{src/react → react}/apollo-error/apollo-error.hook.d.ts +0 -0
  231. /package/dist/{src/react → react}/apollo-error/apollo-error.provider.d.ts +0 -0
  232. /package/dist/{src/react → react}/apollo-error/apollo-error.type.d.ts +0 -0
  233. /package/dist/{src/react → react}/apollo-error/apollo-error.util.d.ts +0 -0
  234. /package/dist/{src/react → react}/i18next/i18next.hook.d.ts +0 -0
  235. /package/dist/{src/react → react}/i18next/i18next.util.d.ts +0 -0
  236. /package/dist/{src/react → react}/loading/loading.component.d.ts +0 -0
  237. /package/dist/{src/react → react}/loading/loading.context.d.ts +0 -0
  238. /package/dist/{src/react → react}/loading/loading.hook.d.ts +0 -0
  239. /package/dist/{src/react → react}/loading/loading.type.d.ts +0 -0
  240. /package/dist/{src/react → react}/next-intl/next-intl.constant.d.ts +0 -0
  241. /package/dist/{src/react → react}/next-intl/next-intl.context.d.ts +0 -0
  242. /package/dist/{src/react → react}/next-intl/next-intl.hook.d.ts +0 -0
  243. /package/dist/{src/react → react}/next-intl/next-intl.provider.d.ts +0 -0
  244. /package/dist/{src/react → react}/userback/userback.component.d.ts +0 -0
  245. /package/dist/{src/react → react}/userback/userback.type.d.ts +0 -0
  246. /package/dist/{src/typescript → typescript}/react.type.d.ts +0 -0
  247. /package/dist/{src/util → util}/common/common.type.d.ts +0 -0
  248. /package/dist/{src/util → util}/common/common.util.d.ts +0 -0
  249. /package/dist/{src/util → util}/log/log.type.d.ts +0 -0
  250. /package/dist/{src/util → util}/object/object.util.d.ts +0 -0
  251. /package/dist/{src/util → util}/serializer/serializer.type.d.ts +0 -0
  252. /package/dist/{src/util → util}/string/string.type.d.ts +0 -0
  253. /package/dist/{src/util → util}/string/string.util.d.ts +0 -0
  254. /package/dist/{src/util → util}/validate/validate.util.d.ts +0 -0
@@ -1,17 +1,21 @@
1
1
  import { catchError as e } from "../log/log.util.js";
2
+ import { createTtlEnvelope as t, isExpiredEnvelope as n, isTtlEnvelope as r } from "../../util/storage/storage-envelope.js";
2
3
  //#region src/react/storage/storage.util.ts
3
- var t = {
4
+ var i = {
4
5
  async get(t) {
5
6
  try {
6
7
  let e = localStorage.getItem(t);
7
- return e === null ? null : JSON.parse(e);
8
+ if (e === null) return null;
9
+ let i = JSON.parse(e);
10
+ return r(i) ? n(i) ? (localStorage.removeItem(t), null) : i.value : i;
8
11
  } catch (t) {
9
12
  return e(t, { returnValue: null });
10
13
  }
11
14
  },
12
- async set(t, n) {
15
+ async set(n, r, i) {
13
16
  try {
14
- localStorage.setItem(t, JSON.stringify(n));
17
+ let e = r;
18
+ i?.ttlMs && (e = t(r, i.ttlMs)), localStorage.setItem(n, JSON.stringify(e));
15
19
  } catch (t) {
16
20
  e(t);
17
21
  }
@@ -34,9 +38,30 @@ var t = {
34
38
  } catch (t) {
35
39
  return e(t, { returnValue: [] });
36
40
  }
41
+ },
42
+ async has(t) {
43
+ try {
44
+ let e = localStorage.getItem(t);
45
+ if (e === null) return !1;
46
+ let i = JSON.parse(e);
47
+ return r(i) && n(i) ? (localStorage.removeItem(t), !1) : !0;
48
+ } catch (t) {
49
+ return e(t, { returnValue: !1 });
50
+ }
51
+ },
52
+ async clear() {
53
+ try {
54
+ localStorage.clear();
55
+ } catch (t) {
56
+ e(t);
57
+ }
58
+ },
59
+ async getOrSet(e, t, n) {
60
+ let r = await this.get(e);
61
+ return r === null && (r = await t(), await this.set(e, r, n)), r;
37
62
  }
38
63
  };
39
64
  //#endregion
40
- export { t as storage };
65
+ export { i as storage };
41
66
 
42
67
  //# sourceMappingURL=storage.util.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/react/storage/storage.util.ts"],"sourcesContent":["import { catchError } from '../log/index.js';\n\n/**\n * Browser storage utility object using native localStorage.\n * This object provides a unified interface for browser storage operations\n * with comprehensive error handling and type safety.\n * Values are stored as JSON strings for consistent serialization.\n */\nexport const storage = {\n /**\n * Retrieves a value from browser storage by key.\n * This method fetches data that was previously stored using the set method.\n * Returns null if the key doesn't exist or if an error occurs during retrieval.\n *\n * @param key - The unique identifier for the stored value.\n * @returns A promise that resolves to the stored value or null if not found.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return null;\n }\n\n return JSON.parse(raw) as T;\n }\n catch (error) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Stores a value in browser storage with a unique key.\n * This method saves data that can be retrieved later using the get method.\n * The data is automatically serialized to JSON.\n *\n * @param key - The unique identifier for the value to store.\n * @param value - The data to store (will be automatically serialized to JSON).\n * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T): Promise<void> {\n try {\n localStorage.setItem(key, JSON.stringify(value));\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Removes a value from browser storage by key.\n * This method permanently deletes the stored data associated with the specified key.\n * If the key doesn't exist, the operation completes successfully without error.\n *\n * @param key - The unique identifier of the value to remove.\n * @returns A promise that resolves when the removal operation is complete.\n */\n async remove(key: string): Promise<void> {\n try {\n localStorage.removeItem(key);\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Retrieves all storage keys.\n * This method returns an array of all keys that currently have stored values.\n * Returns an empty array if no keys exist or if an error occurs during retrieval.\n *\n * @returns A promise that resolves to an array of storage keys.\n */\n async keys(): Promise<string[]> {\n try {\n const keys: string[] = [];\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n\n if (key !== null) {\n keys.push(key);\n }\n }\n\n return keys;\n }\n catch (error) {\n return catchError(error, { returnValue: [] });\n }\n },\n};\n"],"mappings":";;AAQA,IAAa,IAAU;CASnB,MAAM,IAAiB,GAAgC;AACnD,MAAI;GACA,IAAM,IAAM,aAAa,QAAQ,EAAI;AAMrC,UAJI,MAAQ,OACD,OAGJ,KAAK,MAAM,EAAI;WAEnB,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAYvD,MAAM,IAAiB,GAAa,GAAyB;AACzD,MAAI;AACA,gBAAa,QAAQ,GAAK,KAAK,UAAU,EAAM,CAAC;WAE7C,GAAO;AACV,KAAW,EAAM;;;CAWzB,MAAM,OAAO,GAA4B;AACrC,MAAI;AACA,gBAAa,WAAW,EAAI;WAEzB,GAAO;AACV,KAAW,EAAM;;;CAUzB,MAAM,OAA0B;AAC5B,MAAI;GACA,IAAM,IAAiB,EAAE;AAEzB,QAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;IAC1C,IAAM,IAAM,aAAa,IAAI,EAAE;AAE/B,IAAI,MAAQ,QACR,EAAK,KAAK,EAAI;;AAItB,UAAO;WAEJ,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,EAAE,EAAE,CAAC;;;CAGxD"}
1
+ {"version":3,"file":"storage.util.js","names":[],"sources":["../../../src/react/storage/storage.util.ts"],"sourcesContent":["import { createTtlEnvelope, isExpiredEnvelope, isTtlEnvelope } from '../../util/storage/storage-envelope.js';\nimport { catchError } from '../log/index.js';\n\n/**\n * Browser storage utility object using native localStorage.\n * This object provides a unified interface for browser storage operations\n * with comprehensive error handling and type safety.\n * Values are stored as JSON strings for consistent serialization.\n */\nexport const storage = {\n /**\n * Retrieves a value from browser storage by key.\n * This method fetches data that was previously stored using the set method.\n * Returns null if the key doesn't exist or if an error occurs during retrieval.\n *\n * @param key - The unique identifier for the stored value.\n * @returns A promise that resolves to the stored value or null if not found.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return null;\n }\n\n const obj = JSON.parse(raw);\n\n if (isTtlEnvelope<T>(obj)) {\n if (isExpiredEnvelope(obj)) {\n localStorage.removeItem(key);\n\n return null;\n }\n\n return obj.value;\n }\n\n return obj as T;\n }\n catch (error) {\n return catchError(error, { returnValue: null });\n }\n },\n /**\n * Stores a value in browser storage with a unique key.\n * This method saves data that can be retrieved later using the get method.\n * The data is automatically serialized to JSON.\n *\n * @param key - The unique identifier for the value to store.\n * @param value - The data to store (will be automatically serialized to JSON).\n * @param options - Optional settings.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves when the storage operation is complete.\n */\n async set<T = unknown>(key: string, value: T, options?: { ttlMs?: number }): Promise<void> {\n try {\n let payloadToStore: unknown = value;\n\n if (options?.ttlMs) {\n payloadToStore = createTtlEnvelope(value, options.ttlMs);\n }\n\n localStorage.setItem(key, JSON.stringify(payloadToStore));\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Removes a value from browser storage by key.\n * This method permanently deletes the stored data associated with the specified key.\n * If the key doesn't exist, the operation completes successfully without error.\n *\n * @param key - The unique identifier of the value to remove.\n * @returns A promise that resolves when the removal operation is complete.\n */\n async remove(key: string): Promise<void> {\n try {\n localStorage.removeItem(key);\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Retrieves all storage keys.\n * This method returns an array of all keys that currently have stored values.\n * Returns an empty array if no keys exist or if an error occurs during retrieval.\n *\n * @returns A promise that resolves to an array of storage keys.\n */\n async keys(): Promise<string[]> {\n try {\n const keys: string[] = [];\n\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n\n if (key !== null) {\n keys.push(key);\n }\n }\n\n return keys;\n }\n catch (error) {\n return catchError(error, { returnValue: [] });\n }\n },\n /**\n * Checks if a key exists in browser storage.\n * This method efficiently checks for key existence without deserializing the value.\n * It also respects TTL — returns false if the key exists but has expired.\n *\n * @param key - The unique identifier to check.\n * @returns A promise that resolves to true if the key exists and has not expired.\n */\n async has(key: string): Promise<boolean> {\n try {\n const raw = localStorage.getItem(key);\n\n if (raw === null) {\n return false;\n }\n\n const obj = JSON.parse(raw);\n\n if (isTtlEnvelope<unknown>(obj)) {\n if (isExpiredEnvelope(obj)) {\n localStorage.removeItem(key);\n\n return false;\n }\n }\n\n return true;\n }\n catch (error) {\n return catchError(error, { returnValue: false });\n }\n },\n /**\n * Clears all values from browser storage.\n * This method permanently removes all stored data.\n *\n * @returns A promise that resolves when the clear operation is complete.\n */\n async clear(): Promise<void> {\n try {\n localStorage.clear();\n }\n catch (error) {\n catchError(error);\n }\n },\n /**\n * Retrieves a value from browser storage, or creates and stores it if it doesn't exist.\n * This method combines check, creation, and storage into a single convenient operation.\n *\n * @param key - The unique identifier for the value.\n * @param factory - A function (sync or async) that generates the value if it's missing or expired.\n * @param options - Optional storage options.\n * @param options.ttlMs - The time-to-live in milliseconds.\n * @returns A promise that resolves to the retrieved or newly created value.\n */\n async getOrSet<T = unknown>(key: string, factory: () => T | Promise<T>, options?: { ttlMs?: number }): Promise<T> {\n let value = await this.get<T>(key);\n\n if (value === null) {\n value = await factory();\n await this.set(key, value, options);\n }\n\n return value;\n },\n};\n"],"mappings":";;;AASA,IAAa,IAAU;CASnB,MAAM,IAAiB,GAAgC;AACnD,MAAI;GACA,IAAM,IAAM,aAAa,QAAQ,EAAI;AAErC,OAAI,MAAQ,KACR,QAAO;GAGX,IAAM,IAAM,KAAK,MAAM,EAAI;AAY3B,UAVI,EAAiB,EAAI,GACjB,EAAkB,EAAI,IACtB,aAAa,WAAW,EAAI,EAErB,QAGJ,EAAI,QAGR;WAEJ,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,MAAM,CAAC;;;CAcvD,MAAM,IAAiB,GAAa,GAAU,GAA6C;AACvF,MAAI;GACA,IAAI,IAA0B;AAM9B,GAJI,GAAS,UACT,IAAiB,EAAkB,GAAO,EAAQ,MAAM,GAG5D,aAAa,QAAQ,GAAK,KAAK,UAAU,EAAe,CAAC;WAEtD,GAAO;AACV,KAAW,EAAM;;;CAWzB,MAAM,OAAO,GAA4B;AACrC,MAAI;AACA,gBAAa,WAAW,EAAI;WAEzB,GAAO;AACV,KAAW,EAAM;;;CAUzB,MAAM,OAA0B;AAC5B,MAAI;GACA,IAAM,IAAiB,EAAE;AAEzB,QAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;IAC1C,IAAM,IAAM,aAAa,IAAI,EAAE;AAE/B,IAAI,MAAQ,QACR,EAAK,KAAK,EAAI;;AAItB,UAAO;WAEJ,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,EAAE,EAAE,CAAC;;;CAWrD,MAAM,IAAI,GAA+B;AACrC,MAAI;GACA,IAAM,IAAM,aAAa,QAAQ,EAAI;AAErC,OAAI,MAAQ,KACR,QAAO;GAGX,IAAM,IAAM,KAAK,MAAM,EAAI;AAU3B,UARI,EAAuB,EAAI,IACvB,EAAkB,EAAI,IACtB,aAAa,WAAW,EAAI,EAErB,MAIR;WAEJ,GAAO;AACV,UAAO,EAAW,GAAO,EAAE,aAAa,IAAO,CAAC;;;CASxD,MAAM,QAAuB;AACzB,MAAI;AACA,gBAAa,OAAO;WAEjB,GAAO;AACV,KAAW,EAAM;;;CAazB,MAAM,SAAsB,GAAa,GAA+B,GAA0C;EAC9G,IAAI,IAAQ,MAAM,KAAK,IAAO,EAAI;AAOlC,SALI,MAAU,SACV,IAAQ,MAAM,GAAS,EACvB,MAAM,KAAK,IAAI,GAAK,GAAO,EAAQ,GAGhC;;CAEd"}
@@ -1 +1 @@
1
- export {}
1
+ export { toast, Toaster } from 'react-hot-toast';
@@ -1 +1,2 @@
1
- export {}
1
+ export * from './userback.component.js';
2
+ export * from './userback.type.js';
@@ -1 +1 @@
1
- {"version":3,"file":"userback.component.js","names":[],"sources":["../../../src/react/userback/userback.component.tsx"],"sourcesContent":["import UserbackWidget from '@userback/widget';\nimport { useEffect } from 'react';\n\nimport type { I_UserBackProps } from './userback.type.js';\n\n/**\n * Userback feedback widget component for collecting user feedback.\n * This component integrates the Userback feedback widget into React applications,\n * providing a customizable feedback collection interface for users to submit\n * bug reports, feature requests, and general feedback.\n *\n * Features:\n * - Userback widget integration\n * - Customizable feedback collection\n * - Automatic widget initialization\n * - Token-based configuration\n * - Responsive design support\n *\n * @param props - Component props containing token and options.\n * @param props.token - The Userback token for widget authentication.\n * @param props.options - Optional configuration options for the Userback widget.\n * @returns A React component that renders the Userback feedback widget.\n */\nexport function Userback({ token, options }: I_UserBackProps) {\n useEffect(() => {\n if (!token) {\n return;\n }\n\n let observer: MutationObserver;\n\n const loadUserback = async () => {\n const { hide, ...rest } = options || {};\n\n await UserbackWidget(token, rest);\n\n if (hide && hide.length > 0) {\n hide.forEach((selector: string) => {\n document.querySelectorAll(selector).forEach(el => el.remove());\n });\n }\n\n observer = new MutationObserver(() => {\n if (hide && hide.length > 0) {\n hide.forEach((selector: string) => {\n document.querySelectorAll(selector).forEach(el => el.remove());\n });\n }\n });\n\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n });\n };\n\n loadUserback();\n\n return () => {\n observer?.disconnect();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- options is intentionally excluded to prevent infinite re-renders (object ref changes each render)\n }, [token]);\n\n return null;\n}\n"],"mappings":";;;AAuBA,SAAgB,EAAS,EAAE,UAAO,cAA4B;AAyC1D,QAxCA,QAAgB;AACZ,MAAI,CAAC,EACD;EAGJ,IAAI;AA6BJ,UA3BqB,YAAY;GAC7B,IAAM,EAAE,SAAM,GAAG,MAAS,KAAW,EAAE;AAkBvC,GAhBA,MAAM,EAAe,GAAO,EAAK,EAE7B,KAAQ,EAAK,SAAS,KACtB,EAAK,SAAS,MAAqB;AAC/B,aAAS,iBAAiB,EAAS,CAAC,SAAQ,MAAM,EAAG,QAAQ,CAAC;KAChE,EAGN,IAAW,IAAI,uBAAuB;AAClC,IAAI,KAAQ,EAAK,SAAS,KACtB,EAAK,SAAS,MAAqB;AAC/B,cAAS,iBAAiB,EAAS,CAAC,SAAQ,MAAM,EAAG,QAAQ,CAAC;MAChE;KAER,EAEF,EAAS,QAAQ,SAAS,MAAM;IAC5B,WAAW;IACX,SAAS;IACZ,CAAC;MAGQ,QAED;AACT,MAAU,YAAY;;IAG3B,CAAC,EAAM,CAAC,EAEJ"}
1
+ {"version":3,"file":"userback.component.js","names":[],"sources":["../../../src/react/userback/userback.component.tsx"],"sourcesContent":["import UserbackWidget from '@userback/widget';\nimport { useEffect } from 'react';\n\nimport type { I_UserBackProps } from './userback.type.js';\n\n/**\n * Userback feedback widget component for collecting user feedback.\n * This component integrates the Userback feedback widget into React applications,\n * providing a customizable feedback collection interface for users to submit\n * bug reports, feature requests, and general feedback.\n *\n * Features:\n * - Userback widget integration\n * - Customizable feedback collection\n * - Automatic widget initialization\n * - Token-based configuration\n * - Responsive design support\n *\n * @param props - Component props containing token and options.\n * @param props.token - The Userback token for widget authentication.\n * @param props.options - Optional configuration options for the Userback widget.\n * @returns A React component that renders the Userback feedback widget.\n */\nexport function Userback({ token, options }: I_UserBackProps) {\n useEffect(() => {\n if (!token) {\n return;\n }\n\n let observer: MutationObserver;\n\n const loadUserback = async () => {\n const { hide, ...rest } = options || {};\n\n await UserbackWidget(token, rest);\n\n if (hide && hide.length > 0) {\n hide.forEach((selector: string) => {\n document.querySelectorAll(selector).forEach(el => el.remove());\n });\n }\n\n observer = new MutationObserver(() => {\n if (hide && hide.length > 0) {\n hide.forEach((selector: string) => {\n document.querySelectorAll(selector).forEach(el => el.remove());\n });\n }\n });\n\n observer.observe(document.body, {\n childList: true,\n subtree: true,\n });\n };\n\n loadUserback();\n\n return () => {\n observer?.disconnect();\n };\n // eslint-disable-next-line react/exhaustive-deps -- intended to only load Userback on token change\n }, [token]);\n\n return null;\n}\n"],"mappings":";;;AAuBA,SAAgB,EAAS,EAAE,UAAO,cAA4B;AAyC1D,QAxCA,QAAgB;AACZ,MAAI,CAAC,EACD;EAGJ,IAAI;AA6BJ,UA3BqB,YAAY;GAC7B,IAAM,EAAE,SAAM,GAAG,MAAS,KAAW,EAAE;AAkBvC,GAhBA,MAAM,EAAe,GAAO,EAAK,EAE7B,KAAQ,EAAK,SAAS,KACtB,EAAK,SAAS,MAAqB;AAC/B,aAAS,iBAAiB,EAAS,CAAC,SAAQ,MAAM,EAAG,QAAQ,CAAC;KAChE,EAGN,IAAW,IAAI,uBAAuB;AAClC,IAAI,KAAQ,EAAK,SAAS,KACtB,EAAK,SAAS,MAAqB;AAC/B,cAAS,iBAAiB,EAAS,CAAC,SAAQ,MAAM,EAAG,QAAQ,CAAC;MAChE;KAER,EAEF,EAAS,QAAQ,SAAS,MAAM;IAC5B,WAAW;IACX,SAAS;IACZ,CAAC;MAGQ,QAED;AACT,MAAU,YAAY;;IAG3B,CAAC,EAAM,CAAC,EAEJ"}
@@ -85,6 +85,10 @@ export declare function isSuccess<T, E = unknown>(result: I_Return<T, E>): resul
85
85
  * @throws {Error} When the result is a failure.
86
86
  */
87
87
  export declare function unwrapResult<T, E = unknown>(result: I_Return<T, E>): T & E;
88
+ /**
89
+ * Alias for `unwrapResult` to improve discoverability.
90
+ */
91
+ export declare const unwrapOrThrow: typeof unwrapResult;
88
92
  export declare enum E_Environment {
89
93
  PRODUCTION = "production",
90
94
  STAGING = "staging",
@@ -6,10 +6,10 @@ function t(e) {
6
6
  if (!e.success) throw Error(e.message);
7
7
  return e.result;
8
8
  }
9
- var n = /* @__PURE__ */ function(e) {
9
+ var n = t, r = /* @__PURE__ */ function(e) {
10
10
  return e.PRODUCTION = "production", e.STAGING = "staging", e.DEVELOPMENT = "development", e;
11
11
  }({});
12
12
  //#endregion
13
- export { n as E_Environment, e as isSuccess, t as unwrapResult };
13
+ export { r as E_Environment, e as isSuccess, n as unwrapOrThrow, t as unwrapResult };
14
14
 
15
15
  //# sourceMappingURL=common.type.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"common.type.js","names":[],"sources":["../../src/typescript/common.type.ts"],"sourcesContent":["import type consola from 'consola';\n\n/**\n * Generic object type with string keys and values of type T (defaults to unknown).\n */\nexport type T_Object<T = unknown> = Record<string, T>;\n\n/**\n * Logging interface for browser and Node.js environments, compatible with consola.\n */\nexport interface I_Log {\n silent: typeof consola['silent'];\n level: typeof consola['level'];\n fatal: typeof consola['fatal'];\n error: typeof consola['error'];\n warn: typeof consola['warn'];\n log: typeof consola['log'];\n info: typeof consola['info'];\n success: typeof consola['success'];\n ready: typeof consola['ready'];\n start: typeof consola['start'];\n box: typeof consola['box'];\n debug: typeof consola['debug'];\n trace: typeof consola['trace'];\n verbose: typeof consola['verbose'];\n}\n\n/**\n * Base interface for return types with common properties.\n */\nexport interface I_ReturnBase {\n success: boolean;\n message?: string;\n code?: number | string;\n}\n\n/**\n * Success return type with result data.\n * @template T - The main result type\n * @template E - Additional properties to merge with the result (defaults to unknown)\n */\nexport interface I_ReturnSuccess<T, E = unknown> extends I_ReturnBase {\n success: true;\n result: T & E;\n /** True when results were limited by a default cap and may not include all matching documents. */\n truncated?: boolean;\n}\n\n/**\n * Failure return type with error information.\n */\nexport interface I_ReturnFailure extends I_ReturnBase {\n success: false;\n message: string;\n code: number | string;\n}\n\n/**\n * Discriminated union type for function return values.\n * Provides type-safe handling of success and failure cases.\n *\n * @template T - The success result type (defaults to void)\n * @template E - Additional properties to merge with the result (defaults to unknown)\n *\n * @example\n * ```typescript\n * function fetchUser(id: string): I_Return<User> {\n * try {\n * const user = await getUser(id);\n * return { success: true, result: user };\n * } catch (error) {\n * return { success: false, message: error.message, code: 'USER_NOT_FOUND' };\n * }\n * }\n * ```\n */\nexport type I_Return<T = void, E = unknown> = I_ReturnSuccess<T, E> | I_ReturnFailure;\n\n/**\n * Type guard that narrows an `I_Return` to `I_ReturnSuccess`.\n *\n * @param result - The result to check.\n * @returns True if the result is a success.\n */\nexport function isSuccess<T, E = unknown>(result: I_Return<T, E>): result is I_ReturnSuccess<T, E> {\n return result.success;\n}\n\n/**\n * Unwraps a successful `I_Return`, throwing an error for failure cases.\n * Useful when a failure is unexpected and should abort execution.\n *\n * @param result - The result to unwrap.\n * @returns The success result value.\n * @throws {Error} When the result is a failure.\n */\nexport function unwrapResult<T, E = unknown>(result: I_Return<T, E>): T & E {\n if (!result.success) {\n throw new Error(result.message);\n }\n\n return result.result;\n}\n\nexport enum E_Environment {\n PRODUCTION = 'production',\n STAGING = 'staging',\n DEVELOPMENT = 'development',\n}\n"],"mappings":";AAoFA,SAAgB,EAA0B,GAAyD;AAC/F,QAAO,EAAO;;AAWlB,SAAgB,EAA6B,GAA+B;AACxE,KAAI,CAAC,EAAO,QACR,OAAU,MAAM,EAAO,QAAQ;AAGnC,QAAO,EAAO;;AAGlB,IAAY,IAAL,yBAAA,GAAA;QACH,EAAA,aAAA,cACA,EAAA,UAAA,WACA,EAAA,cAAA;KACH"}
1
+ {"version":3,"file":"common.type.js","names":[],"sources":["../../src/typescript/common.type.ts"],"sourcesContent":["import type consola from 'consola';\n\n/**\n * Generic object type with string keys and values of type T (defaults to unknown).\n */\nexport type T_Object<T = unknown> = Record<string, T>;\n\n/**\n * Logging interface for browser and Node.js environments, compatible with consola.\n */\nexport interface I_Log {\n silent: typeof consola['silent'];\n level: typeof consola['level'];\n fatal: typeof consola['fatal'];\n error: typeof consola['error'];\n warn: typeof consola['warn'];\n log: typeof consola['log'];\n info: typeof consola['info'];\n success: typeof consola['success'];\n ready: typeof consola['ready'];\n start: typeof consola['start'];\n box: typeof consola['box'];\n debug: typeof consola['debug'];\n trace: typeof consola['trace'];\n verbose: typeof consola['verbose'];\n}\n\n/**\n * Base interface for return types with common properties.\n */\nexport interface I_ReturnBase {\n success: boolean;\n message?: string;\n code?: number | string;\n}\n\n/**\n * Success return type with result data.\n * @template T - The main result type\n * @template E - Additional properties to merge with the result (defaults to unknown)\n */\nexport interface I_ReturnSuccess<T, E = unknown> extends I_ReturnBase {\n success: true;\n result: T & E;\n /** True when results were limited by a default cap and may not include all matching documents. */\n truncated?: boolean;\n}\n\n/**\n * Failure return type with error information.\n */\nexport interface I_ReturnFailure extends I_ReturnBase {\n success: false;\n message: string;\n code: number | string;\n}\n\n/**\n * Discriminated union type for function return values.\n * Provides type-safe handling of success and failure cases.\n *\n * @template T - The success result type (defaults to void)\n * @template E - Additional properties to merge with the result (defaults to unknown)\n *\n * @example\n * ```typescript\n * function fetchUser(id: string): I_Return<User> {\n * try {\n * const user = await getUser(id);\n * return { success: true, result: user };\n * } catch (error) {\n * return { success: false, message: error.message, code: 'USER_NOT_FOUND' };\n * }\n * }\n * ```\n */\nexport type I_Return<T = void, E = unknown> = I_ReturnSuccess<T, E> | I_ReturnFailure;\n\n/**\n * Type guard that narrows an `I_Return` to `I_ReturnSuccess`.\n *\n * @param result - The result to check.\n * @returns True if the result is a success.\n */\nexport function isSuccess<T, E = unknown>(result: I_Return<T, E>): result is I_ReturnSuccess<T, E> {\n return result.success;\n}\n\n/**\n * Unwraps a successful `I_Return`, throwing an error for failure cases.\n * Useful when a failure is unexpected and should abort execution.\n *\n * @param result - The result to unwrap.\n * @returns The success result value.\n * @throws {Error} When the result is a failure.\n */\nexport function unwrapResult<T, E = unknown>(result: I_Return<T, E>): T & E {\n if (!result.success) {\n throw new Error(result.message);\n }\n\n return result.result;\n}\n\n/**\n * Alias for `unwrapResult` to improve discoverability.\n */\nexport const unwrapOrThrow = unwrapResult;\n\nexport enum E_Environment {\n PRODUCTION = 'production',\n STAGING = 'staging',\n DEVELOPMENT = 'development',\n}\n"],"mappings":";AAoFA,SAAgB,EAA0B,GAAyD;AAC/F,QAAO,EAAO;;AAWlB,SAAgB,EAA6B,GAA+B;AACxE,KAAI,CAAC,EAAO,QACR,OAAU,MAAM,EAAO,QAAQ;AAGnC,QAAO,EAAO;;AAMlB,IAAa,IAAgB,GAEjB,IAAL,yBAAA,GAAA;QACH,EAAA,aAAA,cACA,EAAA,UAAA,WACA,EAAA,cAAA;KACH"}
@@ -1 +1,5 @@
1
- export {}
1
+ /**
2
+ * Re-exports all common TypeScript types for shared usage across the codebase.
3
+ */
4
+ export * from './common.type.js';
5
+ export * from './react.type.js';
@@ -1,2 +1,2 @@
1
- import { E_Environment as e, isSuccess as t, unwrapResult as n } from "./common.type.js";
2
- export { e as E_Environment, t as isSuccess, n as unwrapResult };
1
+ import { E_Environment as e, isSuccess as t, unwrapOrThrow as n, unwrapResult as r } from "./common.type.js";
2
+ export { e as E_Environment, t as isSuccess, n as unwrapOrThrow, r as unwrapResult };
@@ -1 +1,5 @@
1
- export {}
1
+ /**
2
+ * Re-exports all common utility types for shared usage across the codebase.
3
+ */
4
+ export * from './common.type.js';
5
+ export * from './common.util.js';
@@ -1 +1,9 @@
1
- export {}
1
+ /**
2
+ * Re-exports all utility modules for shared usage across the codebase.
3
+ */
4
+ export * from './common/index.js';
5
+ export * from './log/index.js';
6
+ export * from './object/index.js';
7
+ export * from './serializer/index.js';
8
+ export * from './string/index.js';
9
+ export * from './validate/index.js';
@@ -1 +1,2 @@
1
- export {}
1
+ export type { I_CatchErrorOptions } from './log.type.js';
2
+ export { baseCatchError } from './log.util.js';
@@ -1,4 +1,4 @@
1
- import { I_Return } from '../../../typescript/index.js';
1
+ import { I_Return } from '../../typescript/index.js';
2
2
  import { I_CatchErrorOptions } from './log.type.js';
3
3
  /**
4
4
  * Core error-catching implementation shared between Node and React environments.
@@ -1 +1,4 @@
1
- export {}
1
+ /**
2
+ * Re-exports all object manipulation utilities.
3
+ */
4
+ export * from './object.util.js';
@@ -64,12 +64,12 @@ function o(...e) {
64
64
  for (let a of e) {
65
65
  if (r.has(a)) throw Error("deepMerge: Circular reference detected.");
66
66
  let e = a;
67
- for (let r in e) if (Object.hasOwn(e, r)) {
68
- let a = e[r];
69
- if (Object.hasOwn(i, r)) {
70
- let e = i[r];
71
- typeof a == "object" && a && typeof e == "object" && e ? Array.isArray(a) && Array.isArray(e) ? i[r] = [...e, ...a] : !Array.isArray(a) && !Array.isArray(e) ? i[r] = t([e, a], n + 1, /* @__PURE__ */ new WeakSet()) : i[r] = a : i[r] = a;
72
- } else i[r] = a;
67
+ for (let a in e) if (Object.hasOwn(e, a)) {
68
+ let o = e[a];
69
+ if (Object.hasOwn(i, a)) {
70
+ let e = i[a];
71
+ typeof o == "object" && o && typeof e == "object" && e ? Array.isArray(o) && Array.isArray(e) ? i[a] = [...e, ...o] : !Array.isArray(o) && !Array.isArray(e) ? i[a] = t([e, o], n + 1, r) : i[a] = o : i[a] = o;
72
+ } else i[a] = o;
73
73
  }
74
74
  }
75
75
  return i;
@@ -82,26 +82,37 @@ function o(...e) {
82
82
  }
83
83
  function s(e) {
84
84
  if (!e || typeof e != "object") return e;
85
- let t = {};
86
- function n(e, r) {
87
- for (let i in e) {
88
- if (!Object.hasOwn(e, i)) continue;
89
- let a = e[i], o = r ? `${r}.${i}` : i;
90
- if (a && typeof a == "object" && !Array.isArray(a)) {
91
- if (!(a.constructor === Object || Object.getPrototypeOf(a) === null)) {
92
- t[o] = a;
85
+ let t = !0;
86
+ for (let n in e) {
87
+ if (!Object.hasOwn(e, n)) continue;
88
+ let r = e[n];
89
+ if (r && typeof r == "object" && !Array.isArray(r)) {
90
+ t = !1;
91
+ break;
92
+ }
93
+ }
94
+ if (t) return e;
95
+ let n = {};
96
+ function r(e, t, i) {
97
+ if (i > 10) throw Error("normalizeMongoFilter: Maximum depth of 10 exceeded. Possible circular reference or excessively nested filter.");
98
+ for (let a in e) {
99
+ if (!Object.hasOwn(e, a)) continue;
100
+ let o = e[a], s = t ? `${t}.${a}` : a;
101
+ if (o && typeof o == "object" && !Array.isArray(o)) {
102
+ if (!(o.constructor === Object || Object.getPrototypeOf(o) === null)) {
103
+ n[s] = o;
93
104
  continue;
94
105
  }
95
106
  let e = !1;
96
- for (let t in a) if (Object.hasOwn(a, t) && t.startsWith("$")) {
107
+ for (let t in o) if (Object.hasOwn(o, t) && t.startsWith("$")) {
97
108
  e = !0;
98
109
  break;
99
110
  }
100
- e ? t[o] = a : n(a, o);
101
- } else t[o] = a;
111
+ e ? n[s] = o : r(o, s, i + 1);
112
+ } else n[s] = o;
102
113
  }
103
114
  }
104
- return n(e, ""), t;
115
+ return r(e, "", 0), n;
105
116
  }
106
117
  //#endregion
107
118
  export { i as deepClone, o as deepMerge, t as getNestedValue, e as isJSON, s as normalizeMongoFilter, r as setNestedValue };
@@ -1 +1 @@
1
- {"version":3,"file":"object.util.js","names":[],"sources":["../../../src/util/object/object.util.ts"],"sourcesContent":["/**\n * Check if a string is a valid JSON string.\n * This function attempts to parse the string as JSON and returns true if successful,\n * false if the string is not valid JSON.\n *\n * @param str - The string to check for valid JSON format.\n * @returns True if the string is a valid JSON string, false otherwise.\n */\nexport function isJSON(str: string): boolean {\n try {\n JSON.parse(str);\n return true;\n }\n catch {\n return false;\n }\n}\n\n/**\n * Gets a nested value from an object using a path array.\n * This function traverses the object following the provided path and returns\n * the value at the specified location, or undefined if the path doesn't exist.\n *\n * @param obj - The object to get the value from.\n * @param path - An array of keys representing the path to the desired value.\n * @returns The value at the specified path, or undefined if the path doesn't exist.\n */\nexport function getNestedValue<T>(obj: T, path: (string | number)[]): unknown {\n // Optimization: Loop is faster than reduce and allows early exit\n let current: unknown = obj;\n const len = path.length;\n\n for (let i = 0; i < len; i++) {\n // Optimization: Early return if current value is null/undefined or not an object\n // This avoids unnecessary key lookups and type checks\n if (current == null || typeof current !== 'object') {\n return undefined;\n }\n\n const key = path[i];\n\n if (key !== undefined && key in (current as Record<string | number, unknown>)) {\n current = (current as Record<string | number, unknown>)[key];\n }\n else {\n return undefined;\n }\n }\n\n return current;\n}\n\n/**\n * Recursively sets a value at a nested path within an object, creating intermediate objects as needed.\n *\n * @param obj - The source object.\n * @param path - Array of keys forming the path.\n * @param value - The value to set.\n * @param index - Current recursion depth.\n * @returns A new object with the value set at the specified path.\n */\nfunction setNestedValueHelper<T>(obj: T, path: (string | number)[], value: unknown, index: number): T {\n if (index >= path.length)\n return obj;\n\n const head = path[index];\n\n if (index === path.length - 1) {\n return {\n ...(obj as Record<string | number, unknown>),\n [head as string | number]: value,\n } as T;\n }\n\n const current = (obj as Record<string | number, unknown>)[head as string | number];\n\n return {\n ...(obj as Record<string | number, unknown>),\n [head as string | number | symbol]: setNestedValueHelper(\n typeof current === 'object' && current !== null\n ? (current as object)\n : {},\n path,\n value,\n index + 1,\n ),\n } as T;\n}\n\n/**\n * Sets a nested value in an object using a path array.\n * This function creates the path if it doesn't exist and sets the value at the specified location.\n * The function returns a new object with the updated value, maintaining immutability.\n *\n * @param obj - The object to set the value in.\n * @param path - An array of keys representing the path to the desired location.\n * @param value - The value to set at the specified path.\n * @returns A new object with the updated value at the specified path.\n */\nexport function setNestedValue<T>(obj: T, path: (string | number)[], value: unknown): T {\n if (path.length === 0)\n return obj;\n\n return setNestedValueHelper(obj, path, value, 0);\n}\n\n/**\n * Deep clones an object or array.\n * This function creates a deep copy of the input, recursively cloning objects and arrays.\n * Primitive values, dates, and other non-plain objects are returned as is (or cloned if supported).\n *\n * @remarks\n * **Non-POJO objects are NOT cloned.** Objects with custom prototypes (e.g., Mongoose ObjectId,\n * class instances, Map, Set, Buffer) are returned **by reference** to preserve driver\n * compatibility. Mutations to these nested references will affect the original.\n * If you need full deep cloning of complex types, use `structuredClone()` or a dedicated library.\n *\n * @param obj - The object to clone.\n * @returns A deep copy of the object (with non-POJO objects returned by reference).\n */\nexport function deepClone<T>(obj: T): T {\n return deepCloneInternal(obj, new WeakMap<object, unknown>());\n}\n\n/**\n * Internal recursive implementation of deepClone with shared-reference and circular-reference handling.\n *\n * Uses a WeakMap to track already-cloned objects. This correctly handles:\n * - **Shared references**: The same object appearing in multiple places returns\n * the same clone (preserving the shared-reference topology).\n * - **Circular references**: Detected because the object is added to the map\n * before* its children are recursed into; a back-edge will find itself in\n * the map and return the (partially constructed) clone rather than recursing\n * infinitely.\n *\n * @param obj - The value to clone.\n * @param seen - A WeakMap mapping original objects to their clones.\n * @returns A deep copy of the value.\n */\nfunction deepCloneInternal<T>(obj: T, seen: WeakMap<object, unknown>): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Return the already-cloned copy for shared (or circular) references\n if (seen.has(obj as object)) {\n return seen.get(obj as object) as T;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as unknown as T;\n }\n\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as unknown as T;\n }\n\n if (Array.isArray(obj)) {\n // Optimization: `new Array(len)` + `for` loop is ~10-15% faster than `Array.map` or `Array.from`\n // for large arrays since it avoids callback overhead and pre-allocates memory.\n const len = obj.length;\n // eslint-disable-next-line unicorn/no-new-array -- Pre-allocating array size for performance\n const arr = new Array(len);\n // Register before recursing to handle circular references within arrays\n seen.set(obj as object, arr);\n\n for (let i = 0; i < len; i++) {\n arr[i] = deepCloneInternal(obj[i], seen);\n }\n\n return arr as unknown as T;\n }\n\n // Handle Mongoose ObjectId and other custom classes by returning reference.\n // structuredClone is not used here because it silently corrupts nested non-POJO\n // types (e.g., ObjectId → plain object) and Date instances in jsdom environments.\n const proto = Object.getPrototypeOf(obj);\n\n if (proto !== Object.prototype && proto !== null) {\n return obj;\n }\n\n const result = {} as Record<string, unknown>;\n // Register before recursing to handle circular references within objects\n seen.set(obj as object, result);\n\n for (const key in obj) {\n if (Object.hasOwn(obj, key)) {\n result[key] = deepCloneInternal((obj as Record<string, unknown>)[key], seen);\n }\n }\n\n return result as T;\n}\n\n/**\n * Deep merges multiple objects into a single object.\n * @param args - The objects to merge. Can be empty, in which case returns an empty object.\n * @returns The merged object.\n */\nexport function deepMerge<T = Record<string, unknown>>(\n ...args: (object | null | undefined)[]\n): T;\n\n/**\n * Deep merges multiple arrays into a single array.\n * @param args - The arrays to merge. Can be empty, in which case returns an empty array.\n * @returns The merged array.\n */\nexport function deepMerge<T = unknown[]>(\n ...args: (unknown[] | null | undefined)[]\n): T;\n\n/**\n * Implementation of deepMerge function.\n * @param args - The objects or arrays to merge.\n * @returns The merged result.\n */\nexport function deepMerge<T = Record<string, unknown> | unknown[]>(\n ...args: (object | unknown[] | null | undefined)[]\n): T {\n const MAX_DEPTH = 20;\n\n /** Recursively merges an array of objects with depth and circular-reference tracking. */\n function mergeRecursive(\n validArgs: object[],\n depth: number,\n seen: WeakSet<object>,\n ): unknown {\n // Depth guard\n if (depth > MAX_DEPTH) {\n throw new Error(`deepMerge: Maximum depth of ${MAX_DEPTH} exceeded. Possible circular reference or excessively nested objects.`);\n }\n\n // Handle empty arguments\n if (validArgs.length === 0) {\n return {};\n }\n\n // If only one argument, return it directly\n if (validArgs.length === 1) {\n return validArgs[0];\n }\n\n // Check if all arguments are arrays\n if (validArgs.every(Array.isArray)) {\n return (validArgs as unknown[][]).flat();\n }\n\n // Check if all arguments are objects (but not arrays)\n if (validArgs.every(arg => typeof arg === 'object' && arg !== null && !Array.isArray(arg))) {\n const result = {} as Record<string, unknown>;\n\n for (const arg of validArgs) {\n // Circular reference protection (per-arg scope prevents false\n // positives when the same object appears in multiple branches)\n if (seen.has(arg)) {\n throw new Error('deepMerge: Circular reference detected.');\n }\n\n const obj = arg as Record<string, unknown>;\n for (const key in obj) {\n if (Object.hasOwn(obj, key)) {\n const value = obj[key];\n if (Object.hasOwn(result, key)) {\n const existingValue = result[key];\n if (\n typeof value === 'object' && value !== null\n && typeof existingValue === 'object' && existingValue !== null\n ) {\n if (Array.isArray(value) && Array.isArray(existingValue)) {\n result[key] = [...existingValue, ...value];\n }\n else if (!Array.isArray(value) && !Array.isArray(existingValue)) {\n result[key] = mergeRecursive(\n [existingValue as Record<string, unknown>, value as Record<string, unknown>],\n depth + 1,\n new WeakSet<object>(),\n );\n }\n else {\n // One is array, other is object — overwrite\n result[key] = value;\n }\n }\n else {\n result[key] = value;\n }\n }\n else {\n result[key] = value;\n }\n }\n }\n }\n return result;\n }\n\n // Check if all arguments are primitive values\n if (validArgs.every(arg => typeof arg !== 'object' || arg === null)) {\n throw new Error(\n 'deepMerge: Cannot merge primitive values. All arguments must be objects or arrays.',\n );\n }\n\n // Mixed types error\n const hasArrays = validArgs.some(Array.isArray);\n const hasObjects = validArgs.some(arg =>\n typeof arg === 'object' && arg !== null && !Array.isArray(arg),\n );\n\n if (hasArrays && hasObjects) {\n throw new Error(\n 'deepMerge: Cannot mix arrays and objects. All arguments must be either arrays or objects.',\n );\n }\n\n // Fallback for unexpected cases\n throw new Error(\n 'deepMerge: Invalid arguments provided. All arguments must be objects or arrays of the same type.',\n );\n }\n\n // Filter out null/undefined\n const validArgs = args.filter((arg): arg is object => arg !== null && arg !== undefined);\n\n return mergeRecursive(validArgs, 0, new WeakSet<object>()) as T;\n}\n\n/**\n * Normalizes MongoDB filters to support both dot notation strings and nested objects.\n * This function converts nested object filters to dot notation format while preserving\n * MongoDB operators to ensure consistent behavior across different filter input formats.\n *\n * @param filter - The filter object to normalize.\n * @returns A normalized filter object with nested objects converted to dot notation,\n * while preserving MongoDB operators as nested objects.\n *\n * @example\n * ```typescript\n * // Both of these will work the same way:\n * normalizeMongoFilter({ \"location.countryId\": \"240\" })\n * normalizeMongoFilter({ location: { countryId: \"240\" } })\n * // Both return: { \"location.countryId\": \"240\" }\n *\n * // MongoDB operators are preserved:\n * normalizeMongoFilter({ id: { $in: [\"240\", \"59\"] } })\n * // Returns: { id: { $in: [\"240\", \"59\"] } }\n * ```\n */\nexport function normalizeMongoFilter<T extends Record<string, unknown>>(filter: T): T {\n if (!filter || typeof filter !== 'object') {\n return filter;\n }\n\n const normalized: Record<string, unknown> = {};\n\n /**\n * Recursively flattens nested objects into dot-notation keys, preserving MongoDB operators.\n */\n function flatten(current: Record<string, unknown>, prefix: string) {\n for (const key in current) {\n if (!Object.hasOwn(current, key))\n continue;\n\n const value = current[key];\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n // Fast-path POJO check: `.constructor` is safe even on null-prototype objects\n // (returns undefined, so the === Object check simply fails and falls through\n // to the getPrototypeOf check which correctly identifies it as a POJO).\n const isPojo = (value as object).constructor === Object\n || Object.getPrototypeOf(value) === null;\n\n if (!isPojo) {\n normalized[newKey] = value;\n continue;\n }\n\n // Check for Mongo operator\n let hasMongoOperator = false;\n for (const subKey in value as Record<string, unknown>) {\n if (Object.hasOwn(value, subKey) && subKey.startsWith('$')) {\n hasMongoOperator = true;\n break;\n }\n }\n\n if (hasMongoOperator) {\n normalized[newKey] = value;\n }\n else {\n flatten(value as Record<string, unknown>, newKey);\n }\n }\n else {\n normalized[newKey] = value;\n }\n }\n }\n\n flatten(filter, '');\n\n return normalized as T;\n}\n"],"mappings":";AAQA,SAAgB,EAAO,GAAsB;AAC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.util.ts"],"sourcesContent":["/**\n * Check if a string is a valid JSON string.\n * This function attempts to parse the string as JSON and returns true if successful,\n * false if the string is not valid JSON.\n *\n * @param str - The string to check for valid JSON format.\n * @returns True if the string is a valid JSON string, false otherwise.\n */\nexport function isJSON(str: string): boolean {\n try {\n JSON.parse(str);\n return true;\n }\n catch {\n /* Intentionally empty — invalid JSON returns false */\n return false;\n }\n}\n\n/**\n * Gets a nested value from an object using a path array.\n * This function traverses the object following the provided path and returns\n * the value at the specified location, or undefined if the path doesn't exist.\n *\n * @param obj - The object to get the value from.\n * @param path - An array of keys representing the path to the desired value.\n * @returns The value at the specified path, or undefined if the path doesn't exist.\n */\nexport function getNestedValue<T>(obj: T, path: (string | number)[]): unknown {\n // Optimization: Loop is faster than reduce and allows early exit\n let current: unknown = obj;\n const len = path.length;\n\n for (let i = 0; i < len; i++) {\n // Optimization: Early return if current value is null/undefined or not an object\n // This avoids unnecessary key lookups and type checks\n if (current == null || typeof current !== 'object') {\n return undefined;\n }\n\n const key = path[i];\n\n if (key !== undefined && key in (current as Record<string | number, unknown>)) {\n current = (current as Record<string | number, unknown>)[key];\n }\n else {\n return undefined;\n }\n }\n\n return current;\n}\n\n/**\n * Recursively sets a value at a nested path within an object, creating intermediate objects as needed.\n *\n * @param obj - The source object.\n * @param path - Array of keys forming the path.\n * @param value - The value to set.\n * @param index - Current recursion depth.\n * @returns A new object with the value set at the specified path.\n */\nfunction setNestedValueHelper<T>(obj: T, path: (string | number)[], value: unknown, index: number): T {\n if (index >= path.length)\n return obj;\n\n const head = path[index];\n\n if (index === path.length - 1) {\n return {\n ...(obj as Record<string | number, unknown>),\n [head as string | number]: value,\n } as T;\n }\n\n const current = (obj as Record<string | number, unknown>)[head as string | number];\n\n return {\n ...(obj as Record<string | number, unknown>),\n [head as string | number | symbol]: setNestedValueHelper(\n typeof current === 'object' && current !== null\n ? (current as object)\n : {},\n path,\n value,\n index + 1,\n ),\n } as T;\n}\n\n/**\n * Sets a nested value in an object using a path array.\n * This function creates the path if it doesn't exist and sets the value at the specified location.\n * The function returns a new object with the updated value, maintaining immutability.\n *\n * @param obj - The object to set the value in.\n * @param path - An array of keys representing the path to the desired location.\n * @param value - The value to set at the specified path.\n * @returns A new object with the updated value at the specified path.\n */\nexport function setNestedValue<T>(obj: T, path: (string | number)[], value: unknown): T {\n if (path.length === 0)\n return obj;\n\n return setNestedValueHelper(obj, path, value, 0);\n}\n\n/**\n * Deep clones an object or array.\n * This function creates a deep copy of the input, recursively cloning objects and arrays.\n * Primitive values, dates, and other non-plain objects are returned as is (or cloned if supported).\n *\n * @remarks\n * **Non-POJO objects are NOT cloned.** Objects with custom prototypes (e.g., Mongoose ObjectId,\n * class instances, Map, Set, Buffer) are returned **by reference** to preserve driver\n * compatibility. Mutations to these nested references will affect the original.\n * If you need full deep cloning of complex types, use `structuredClone()` or a dedicated library.\n *\n * @param obj - The object to clone.\n * @returns A deep copy of the object (with non-POJO objects returned by reference).\n */\nexport function deepClone<T>(obj: T): T {\n return deepCloneInternal(obj, new WeakMap<object, unknown>());\n}\n\n/**\n * Internal recursive implementation of deepClone with shared-reference and circular-reference handling.\n *\n * Uses a WeakMap to track already-cloned objects. This correctly handles:\n * - **Shared references**: The same object appearing in multiple places returns\n * the same clone (preserving the shared-reference topology).\n * - **Circular references**: Detected because the object is added to the map\n * before* its children are recursed into; a back-edge will find itself in\n * the map and return the (partially constructed) clone rather than recursing\n * infinitely.\n *\n * @param obj - The value to clone.\n * @param seen - A WeakMap mapping original objects to their clones.\n * @returns A deep copy of the value.\n */\nfunction deepCloneInternal<T>(obj: T, seen: WeakMap<object, unknown>): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Return the already-cloned copy for shared (or circular) references\n if (seen.has(obj as object)) {\n return seen.get(obj as object) as T;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as unknown as T;\n }\n\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as unknown as T;\n }\n\n if (Array.isArray(obj)) {\n // Optimization: `new Array(len)` + `for` loop is ~10-15% faster than `Array.map` or `Array.from`\n // for large arrays since it avoids callback overhead and pre-allocates memory.\n const len = obj.length;\n // eslint-disable-next-line unicorn/no-new-array -- Pre-allocating array size for performance\n const arr = new Array(len);\n // Register before recursing to handle circular references within arrays\n seen.set(obj as object, arr);\n\n for (let i = 0; i < len; i++) {\n arr[i] = deepCloneInternal(obj[i], seen);\n }\n\n return arr as unknown as T;\n }\n\n // Handle Mongoose ObjectId and other custom classes by returning reference.\n // structuredClone is not used here because it silently corrupts nested non-POJO\n // types (e.g., ObjectId → plain object) and Date instances in jsdom environments.\n const proto = Object.getPrototypeOf(obj);\n\n if (proto !== Object.prototype && proto !== null) {\n return obj;\n }\n\n const result = {} as Record<string, unknown>;\n // Register before recursing to handle circular references within objects\n seen.set(obj as object, result);\n\n for (const key in obj) {\n if (Object.hasOwn(obj, key)) {\n result[key] = deepCloneInternal((obj as Record<string, unknown>)[key], seen);\n }\n }\n\n return result as T;\n}\n\n/**\n * Deep merges multiple objects into a single object.\n * @param args - The objects to merge. Can be empty, in which case returns an empty object.\n * @returns The merged object.\n */\nexport function deepMerge<T = Record<string, unknown>>(\n ...args: (object | null | undefined)[]\n): T;\n\n/**\n * Deep merges multiple arrays into a single array.\n * @param args - The arrays to merge. Can be empty, in which case returns an empty array.\n * @returns The merged array.\n */\nexport function deepMerge<T = unknown[]>(\n ...args: (unknown[] | null | undefined)[]\n): T;\n\n/**\n * Implementation of deepMerge function.\n * @param args - The objects or arrays to merge.\n * @returns The merged result.\n */\nexport function deepMerge<T = Record<string, unknown> | unknown[]>(\n ...args: (object | unknown[] | null | undefined)[]\n): T {\n const MAX_DEPTH = 20;\n\n /** Recursively merges an array of objects with depth and circular-reference tracking. */\n function mergeRecursive(\n validArgs: object[],\n depth: number,\n seen: WeakSet<object>,\n ): unknown {\n // Depth guard\n if (depth > MAX_DEPTH) {\n throw new Error(`deepMerge: Maximum depth of ${MAX_DEPTH} exceeded. Possible circular reference or excessively nested objects.`);\n }\n\n // Handle empty arguments\n if (validArgs.length === 0) {\n return {};\n }\n\n // If only one argument, return it directly\n if (validArgs.length === 1) {\n return validArgs[0];\n }\n\n // Check if all arguments are arrays\n if (validArgs.every(Array.isArray)) {\n return (validArgs as unknown[][]).flat();\n }\n\n // Check if all arguments are objects (but not arrays)\n if (validArgs.every(arg => typeof arg === 'object' && arg !== null && !Array.isArray(arg))) {\n const result = {} as Record<string, unknown>;\n\n for (const arg of validArgs) {\n // Circular reference protection (per-arg scope prevents false\n // positives when the same object appears in multiple branches)\n if (seen.has(arg)) {\n throw new Error('deepMerge: Circular reference detected.');\n }\n\n const obj = arg as Record<string, unknown>;\n\n for (const key in obj) {\n if (Object.hasOwn(obj, key)) {\n const value = obj[key];\n\n if (Object.hasOwn(result, key)) {\n const existingValue = result[key];\n\n if (\n typeof value === 'object' && value !== null\n && typeof existingValue === 'object' && existingValue !== null\n ) {\n if (Array.isArray(value) && Array.isArray(existingValue)) {\n result[key] = [...existingValue, ...value];\n }\n else if (!Array.isArray(value) && !Array.isArray(existingValue)) {\n result[key] = mergeRecursive(\n [existingValue as Record<string, unknown>, value as Record<string, unknown>],\n depth + 1,\n seen,\n );\n }\n else {\n // One is array, other is object — overwrite\n result[key] = value;\n }\n }\n else {\n result[key] = value;\n }\n }\n else {\n result[key] = value;\n }\n }\n }\n }\n\n return result;\n }\n\n // Check if all arguments are primitive values\n if (validArgs.every(arg => typeof arg !== 'object' || arg === null)) {\n throw new Error(\n 'deepMerge: Cannot merge primitive values. All arguments must be objects or arrays.',\n );\n }\n\n // Mixed types error\n const hasArrays = validArgs.some(Array.isArray);\n const hasObjects = validArgs.some(arg =>\n typeof arg === 'object' && arg !== null && !Array.isArray(arg),\n );\n\n if (hasArrays && hasObjects) {\n throw new Error(\n 'deepMerge: Cannot mix arrays and objects. All arguments must be either arrays or objects.',\n );\n }\n\n // Fallback for unexpected cases\n throw new Error(\n 'deepMerge: Invalid arguments provided. All arguments must be objects or arrays of the same type.',\n );\n }\n\n // Filter out null/undefined\n const validArgs = args.filter((arg): arg is object => arg !== null && arg !== undefined);\n\n return mergeRecursive(validArgs, 0, new WeakSet<object>()) as T;\n}\n\n/**\n * Normalizes MongoDB filters to support both dot notation strings and nested objects.\n * This function converts nested object filters to dot notation format while preserving\n * MongoDB operators to ensure consistent behavior across different filter input formats.\n *\n * @param filter - The filter object to normalize.\n * @returns A normalized filter object with nested objects converted to dot notation,\n * while preserving MongoDB operators as nested objects.\n *\n * @example\n * ```typescript\n * // Both of these will work the same way:\n * normalizeMongoFilter({ \"location.countryId\": \"240\" })\n * normalizeMongoFilter({ location: { countryId: \"240\" } })\n * // Both return: { \"location.countryId\": \"240\" }\n *\n * // MongoDB operators are preserved:\n * normalizeMongoFilter({ id: { $in: [\"240\", \"59\"] } })\n * // Returns: { id: { $in: [\"240\", \"59\"] } }\n * ```\n */\nexport function normalizeMongoFilter<T extends Record<string, unknown>>(filter: T): T {\n if (!filter || typeof filter !== 'object') {\n return filter;\n }\n\n let isFlat = true;\n\n for (const key in filter) {\n if (!Object.hasOwn(filter, key)) {\n continue;\n }\n const value = filter[key];\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n isFlat = false;\n break;\n }\n }\n\n if (isFlat) {\n return filter;\n }\n\n const normalized: Record<string, unknown> = {};\n const MAX_DEPTH = 10;\n\n /**\n * Recursively flattens nested objects into dot-notation keys, preserving MongoDB operators.\n */\n function flatten(current: Record<string, unknown>, prefix: string, depth: number) {\n if (depth > MAX_DEPTH) {\n throw new Error(`normalizeMongoFilter: Maximum depth of ${MAX_DEPTH} exceeded. Possible circular reference or excessively nested filter.`);\n }\n\n for (const key in current) {\n if (!Object.hasOwn(current, key)) {\n continue;\n }\n const value = current[key];\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n // Fast-path POJO check: `.constructor` is safe even on null-prototype objects\n // (returns undefined, so the === Object check simply fails and falls through\n // to the getPrototypeOf check which correctly identifies it as a POJO).\n const isPojo = (value as object).constructor === Object\n || Object.getPrototypeOf(value) === null;\n\n if (!isPojo) {\n normalized[newKey] = value;\n continue;\n }\n\n // Check for Mongo operator\n let hasMongoOperator = false;\n\n for (const subKey in value as Record<string, unknown>) {\n if (Object.hasOwn(value, subKey) && subKey.startsWith('$')) {\n hasMongoOperator = true;\n break;\n }\n }\n\n if (hasMongoOperator) {\n normalized[newKey] = value;\n }\n else {\n flatten(value as Record<string, unknown>, newKey, depth + 1);\n }\n }\n else {\n normalized[newKey] = value;\n }\n }\n }\n\n flatten(filter, '', 0);\n\n return normalized as T;\n}\n"],"mappings":";AAQA,SAAgB,EAAO,GAAsB;AACzC,KAAI;AAEA,SADA,KAAK,MAAM,EAAI,EACR;SAEL;AAEF,SAAO;;;AAaf,SAAgB,EAAkB,GAAQ,GAAoC;CAE1E,IAAI,IAAmB,GACjB,IAAM,EAAK;AAEjB,MAAK,IAAI,IAAI,GAAG,IAAI,GAAK,KAAK;AAG1B,MAAuB,OAAO,KAAY,aAAtC,EACA;EAGJ,IAAM,IAAM,EAAK;AAEjB,MAAI,MAAQ,KAAA,KAAa,KAAQ,EAC7B,KAAW,EAA6C;MAGxD;;AAIR,QAAO;;AAYX,SAAS,EAAwB,GAAQ,GAA2B,GAAgB,GAAkB;AAClG,KAAI,KAAS,EAAK,OACd,QAAO;CAEX,IAAM,IAAO,EAAK;AAElB,KAAI,MAAU,EAAK,SAAS,EACxB,QAAO;EACH,GAAI;GACH,IAA0B;EAC9B;CAGL,IAAM,IAAW,EAAyC;AAE1D,QAAO;EACH,GAAI;GACH,IAAmC,EAChC,OAAO,KAAY,YAAY,IACxB,IACD,EAAE,EACR,GACA,GACA,IAAQ,EACX;EACJ;;AAaL,SAAgB,EAAkB,GAAQ,GAA2B,GAAmB;AAIpF,QAHI,EAAK,WAAW,IACT,IAEJ,EAAqB,GAAK,GAAM,GAAO,EAAE;;AAiBpD,SAAgB,EAAa,GAAW;AACpC,QAAO,EAAk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CAM9C,SAAS,EAAQ,GAAkC,GAAgB,GAAe;AAC9E,MAAI,IAAQ,GACR,OAAU,MAAM,gHAA0H;AAG9I,OAAK,IAAM,KAAO,GAAS;AACvB,OAAI,CAAC,OAAO,OAAO,GAAS,EAAI,CAC5B;GAEJ,IAAM,IAAQ,EAAQ,IAChB,IAAS,IAAS,GAAG,EAAO,GAAG,MAAQ;AAE7C,OAAI,KAAS,OAAO,KAAU,YAAY,CAAC,MAAM,QAAQ,EAAM,EAAE;AAO7D,QAAI,EAHY,EAAiB,gBAAgB,UAC1C,OAAO,eAAe,EAAM,KAAK,OAE3B;AACT,OAAW,KAAU;AACrB;;IAIJ,IAAI,IAAmB;AAEvB,SAAK,IAAM,KAAU,EACjB,KAAI,OAAO,OAAO,GAAO,EAAO,IAAI,EAAO,WAAW,IAAI,EAAE;AACxD,SAAmB;AACnB;;AAIR,IAAI,IACA,EAAW,KAAU,IAGrB,EAAQ,GAAkC,GAAQ,IAAQ,EAAE;SAIhE,GAAW,KAAU;;;AAOjC,QAFA,EAAQ,GAAQ,IAAI,EAAE,EAEf"}
@@ -1 +1,2 @@
1
- export {}
1
+ export * from './serializer.type.js';
2
+ export * from './serializer.util.js';
@@ -16,6 +16,14 @@ import { I_Serializer } from './serializer.type.js';
16
16
  * - RegExp → `{ __type: 'RegExp', value: { source: '...', flags: '...' } }`
17
17
  * - BigInt → `{ __type: 'BigInt', value: '12345' }`
18
18
  *
19
+ * **Security:** Only types in the `ALLOWED_TYPES` allowlist are reconstructed during
20
+ * deserialization. Unknown `__type` values are returned as-is to prevent prototype pollution.
21
+ * RegExp sources are length-limited (1000 chars) and flags are validated to mitigate ReDoS.
22
+ *
23
+ * **⚠️ NOT for untrusted input:** This serializer is designed for internal service-to-service
24
+ * communication. Do NOT use it to deserialize user-controlled payloads (e.g., raw WebSocket
25
+ * messages, API request bodies from external clients) without additional validation.
26
+ *
19
27
  * **Cross-service compatibility:** Any service that deserializes data produced by this serializer
20
28
  * must use the same `__type` protocol. Plain `JSON.parse` will return the wrapper objects as-is
21
29
  * without reconstructing the original types.
@@ -1,74 +1,61 @@
1
1
  //#region src/util/serializer/serializer.util.ts
2
- var e = {
3
- Date: {
4
- is: (e) => e instanceof Date,
5
- serialize: (e) => ({
6
- __type: "Date",
7
- value: e.toISOString()
8
- }),
9
- deserialize: (e) => new Date(e)
10
- },
11
- Map: {
12
- is: (e) => e instanceof Map,
13
- serialize: (e) => ({
14
- __type: "Map",
15
- value: [...e.entries()]
16
- }),
17
- deserialize: (e) => new Map(e)
18
- },
19
- Set: {
20
- is: (e) => e instanceof Set,
21
- serialize: (e) => ({
22
- __type: "Set",
23
- value: [...e]
24
- }),
25
- deserialize: (e) => new Set(e)
26
- },
27
- RegExp: {
28
- is: (e) => e instanceof RegExp,
29
- serialize: (e) => ({
30
- __type: "RegExp",
31
- value: {
32
- source: e.source,
33
- flags: e.flags
34
- }
35
- }),
36
- deserialize: (e) => {
37
- let { source: t, flags: n } = e;
38
- return new RegExp(t, n);
39
- }
40
- },
41
- BigInt: {
42
- is: (e) => typeof e == "bigint",
43
- serialize: (e) => ({
44
- __type: "BigInt",
45
- value: e.toString()
46
- }),
47
- deserialize: (e) => BigInt(e)
48
- }
49
- }, t = Object.entries(e).filter(([e]) => e !== "Date").map(([, e]) => e), n = {
50
- serialize(n) {
51
- return JSON.stringify(n, function(n, r) {
52
- let i = this[n];
53
- if (i instanceof Date) return e.Date.serialize(i);
54
- for (let e = 0; e < t.length; e++) {
55
- let n = t[e];
56
- if (n.is(r)) return n.serialize(r);
57
- }
58
- return r;
2
+ var e = new Set([
3
+ "Date",
4
+ "Map",
5
+ "Set",
6
+ "RegExp",
7
+ "BigInt"
8
+ ]), t = 1e3, n = /^[dgimsuvy]*$/, r = {
9
+ serialize(e) {
10
+ return JSON.stringify(e, function(e, t) {
11
+ let n = this[e];
12
+ if (n instanceof Date) return {
13
+ __type: "Date",
14
+ value: n.toISOString()
15
+ };
16
+ if (typeof t == "object" && t) {
17
+ if (t instanceof Map) return {
18
+ __type: "Map",
19
+ value: Array.from(t.entries())
20
+ };
21
+ if (t instanceof Set) return {
22
+ __type: "Set",
23
+ value: Array.from(t)
24
+ };
25
+ if (t instanceof RegExp) return {
26
+ __type: "RegExp",
27
+ value: {
28
+ source: t.source,
29
+ flags: t.flags
30
+ }
31
+ };
32
+ } else if (typeof t == "bigint") return {
33
+ __type: "BigInt",
34
+ value: t.toString()
35
+ };
36
+ return t;
59
37
  });
60
38
  },
61
- deserialize(t) {
62
- return JSON.parse(t, (t, n) => {
63
- if (n && typeof n == "object" && "__type" in n && typeof n.__type == "string") {
64
- let t = e[n.__type];
65
- if (t) return t.deserialize(n.value);
39
+ deserialize(r) {
40
+ return JSON.parse(r, (r, i) => {
41
+ if (typeof i == "object" && i && typeof i.__type == "string") {
42
+ let r = i.__type;
43
+ if (!e.has(r)) return i;
44
+ let a = i.value;
45
+ if (r === "Date") return new Date(a);
46
+ if (r === "Map") return new Map(a);
47
+ if (r === "Set") return new Set(a);
48
+ if (r === "RegExp") {
49
+ let { source: e, flags: r } = a;
50
+ return typeof e != "string" || typeof r != "string" || e.length > t || !n.test(r) ? i : new RegExp(e, r);
51
+ }
52
+ if (r === "BigInt") return BigInt(a);
66
53
  }
67
- return n;
54
+ return i;
68
55
  });
69
56
  }
70
57
  };
71
58
  //#endregion
72
- export { n as serializer };
59
+ export { r as serializer };
73
60
 
74
61
  //# sourceMappingURL=serializer.util.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serializer.util.js","names":[],"sources":["../../../src/util/serializer/serializer.util.ts"],"sourcesContent":["import type {\n I_Serializer,\n I_SerializerTypeWrapper,\n I_SerializerValueMap,\n T_SerializerKnownTypes,\n} from './serializer.type.js';\n\n/**\n * Interface for handling serialization and deserialization of specific types.\n * Each handler provides methods to check if a value is of the specific type,\n * serialize it to a format that can be JSON stringified, and deserialize it back.\n */\ninterface I_Handler<T extends T_SerializerKnownTypes> {\n /** Checks if a value is of the specific type */\n is: (value: unknown) => value is I_SerializerValueMap[T];\n /** Serializes a value of the specific type to a format that can be JSON stringified */\n serialize: (value: I_SerializerValueMap[T]) => I_SerializerTypeWrapper<T>;\n /** Deserializes a value back to the specific type */\n deserialize: (value: unknown) => I_SerializerValueMap[T];\n}\n\n/**\n * Type handlers for different JavaScript types that cannot be directly serialized to JSON.\n * Each handler provides methods to serialize and deserialize specific types like Date, Map, Set, etc.\n */\nconst typeHandlers: {\n [K in T_SerializerKnownTypes]: I_Handler<K>;\n} = {\n Date: {\n is: (v): v is Date => v instanceof Date,\n serialize: v => ({ __type: 'Date', value: v.toISOString() }),\n deserialize: v => new Date(v as string),\n },\n Map: {\n is: (v): v is Map<unknown, unknown> => v instanceof Map,\n serialize: v => ({ __type: 'Map', value: [...v.entries()] }),\n deserialize: v => new Map(v as [unknown, unknown][]),\n },\n Set: {\n is: (v): v is Set<unknown> => v instanceof Set,\n serialize: v => ({ __type: 'Set', value: [...v] }),\n deserialize: v => new Set(v as unknown[]),\n },\n RegExp: {\n is: (v): v is RegExp => v instanceof RegExp,\n serialize: v => ({\n __type: 'RegExp',\n value: { source: v.source, flags: v.flags },\n }),\n deserialize: (v) => {\n const { source, flags } = v as { source: string; flags: string };\n return new RegExp(source, flags);\n },\n },\n BigInt: {\n is: (v): v is bigint => typeof v === 'bigint',\n serialize: v => ({ __type: 'BigInt', value: v.toString() }),\n deserialize: v => BigInt(v as string),\n },\n};\n\nconst typeHandlersValues = (Object.entries(typeHandlers) as [\n T_SerializerKnownTypes,\n I_Handler<T_SerializerKnownTypes>,\n][])\n .filter(([key]) => key !== 'Date')\n .map(([, handler]) => handler);\n\n/**\n * A serializer that can handle complex JavaScript types that cannot be directly JSON stringified.\n * This serializer extends JSON.stringify and JSON.parse to handle types like Date, Map, Set, RegExp, and BigInt.\n *\n * The serializer works by:\n * 1. During serialization: Wrapping special types with type information before JSON stringification\n * 2. During deserialization: Detecting wrapped types and reconstructing them to their original form\n *\n * @remarks\n * **Wire format protocol:** Non-JSON-native types are serialized as wrapper objects with the shape\n * `{ __type: string, value: unknown }`. For example:\n * - Date → `{ __type: 'Date', value: '2024-01-01T00:00:00.000Z' }`\n * - Map → `{ __type: 'Map', value: [['key', 'val']] }`\n * - Set → `{ __type: 'Set', value: [1, 2, 3] }`\n * - RegExp → `{ __type: 'RegExp', value: { source: '...', flags: '...' } }`\n * - BigInt → `{ __type: 'BigInt', value: '12345' }`\n *\n * **Cross-service compatibility:** Any service that deserializes data produced by this serializer\n * must use the same `__type` protocol. Plain `JSON.parse` will return the wrapper objects as-is\n * without reconstructing the original types.\n */\nexport const serializer: I_Serializer<unknown> = {\n /**\n * Serializes a value to a JSON string.\n * If the value is of a known type (Date, Map, Set, RegExp, BigInt),\n * it will be serialized using the corresponding handler.\n * Otherwise, it will be serialized as is.\n *\n * @param value - The value to serialize to a JSON string.\n * @returns The serialized JSON string that can be safely stored or transmitted.\n */\n serialize(value) {\n return JSON.stringify(value, function (_key, val) {\n // eslint-disable-next-line ts/no-this-alias\n const context = this;\n const originalValue = context[_key];\n\n if (originalValue instanceof Date) {\n return typeHandlers.Date.serialize(originalValue);\n }\n\n for (let i = 0; i < typeHandlersValues.length; i++) {\n const handler = typeHandlersValues[i]!;\n\n if (handler.is(val)) {\n return handler.serialize(val as I_SerializerValueMap[T_SerializerKnownTypes]);\n }\n }\n\n return val;\n });\n },\n /**\n * Deserializes a JSON string to its original value.\n * If the value is of a known type (Date, Map, Set, RegExp, BigInt),\n * it will be deserialized using the corresponding handler.\n * Otherwise, it will be deserialized as is.\n *\n * @param json - The JSON string to deserialize back to its original form.\n * @returns The deserialized value with all special types reconstructed.\n */\n deserialize(json) {\n return JSON.parse(json, (_key, val) => {\n if (\n val\n && typeof val === 'object'\n && '__type' in val\n && typeof val.__type === 'string'\n ) {\n const type = val.__type as T_SerializerKnownTypes;\n const handler = typeHandlers[type];\n\n if (handler) {\n return handler.deserialize(val.value);\n }\n }\n return val;\n });\n },\n};\n"],"mappings":";AAyBA,IAAM,IAEF;CACA,MAAM;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O;IACT;;CAWN,YAAY,GAAM;AACd,SAAO,KAAK,MAAM,IAAO,GAAM,MAAQ;AACnC,OACI,KACG,OAAO,KAAQ,YACf,YAAY,KACZ,OAAO,EAAI,UAAW,UAC3B;IAEE,IAAM,IAAU,EADH,EAAI;AAGjB,QAAI,EACA,QAAO,EAAQ,YAAY,EAAI,MAAM;;AAG7C,UAAO;IACT;;CAET"}
1
+ {"version":3,"file":"serializer.util.js","names":[],"sources":["../../../src/util/serializer/serializer.util.ts"],"sourcesContent":["import type {\n I_Serializer,\n} from './serializer.type.js';\n\nconst ALLOWED_TYPES = new Set(['Date', 'Map', 'Set', 'RegExp', 'BigInt']);\nconst MAX_REGEXP_SOURCE_LENGTH = 1_000;\nconst VALID_REGEXP_FLAGS = /^[dgimsuvy]*$/;\n\n/**\n * A serializer that can handle complex JavaScript types that cannot be directly JSON stringified.\n * This serializer extends JSON.stringify and JSON.parse to handle types like Date, Map, Set, RegExp, and BigInt.\n *\n * The serializer works by:\n * 1. During serialization: Wrapping special types with type information before JSON stringification\n * 2. During deserialization: Detecting wrapped types and reconstructing them to their original form\n *\n * @remarks\n * **Wire format protocol:** Non-JSON-native types are serialized as wrapper objects with the shape\n * `{ __type: string, value: unknown }`. For example:\n * - Date → `{ __type: 'Date', value: '2024-01-01T00:00:00.000Z' }`\n * - Map → `{ __type: 'Map', value: [['key', 'val']] }`\n * - Set → `{ __type: 'Set', value: [1, 2, 3] }`\n * - RegExp → `{ __type: 'RegExp', value: { source: '...', flags: '...' } }`\n * - BigInt → `{ __type: 'BigInt', value: '12345' }`\n *\n * **Security:** Only types in the `ALLOWED_TYPES` allowlist are reconstructed during\n * deserialization. Unknown `__type` values are returned as-is to prevent prototype pollution.\n * RegExp sources are length-limited (1000 chars) and flags are validated to mitigate ReDoS.\n *\n * **⚠️ NOT for untrusted input:** This serializer is designed for internal service-to-service\n * communication. Do NOT use it to deserialize user-controlled payloads (e.g., raw WebSocket\n * messages, API request bodies from external clients) without additional validation.\n *\n * **Cross-service compatibility:** Any service that deserializes data produced by this serializer\n * must use the same `__type` protocol. Plain `JSON.parse` will return the wrapper objects as-is\n * without reconstructing the original types.\n */\nexport const serializer: I_Serializer<unknown> = {\n /**\n * Serializes a value to a JSON string.\n * If the value is of a known type (Date, Map, Set, RegExp, BigInt),\n * it will be serialized using the corresponding handler.\n * Otherwise, it will be serialized as is.\n *\n * @param value - The value to serialize to a JSON string.\n * @returns The serialized JSON string that can be safely stored or transmitted.\n */\n serialize(value) {\n return JSON.stringify(value, function (this: Record<string, unknown>, _key, val) {\n // Date#toJSON fires before the replacer, converting a Date to an ISO string.\n // We must read this[_key] to detect the original Date object.\n const originalValue = this[_key];\n if (originalValue instanceof Date) {\n return { __type: 'Date', value: originalValue.toISOString() };\n }\n\n // For all other special types, val is already the original value\n // (they have no toJSON), so use val directly to avoid the extra property access.\n if (val !== null && typeof val === 'object') {\n if (val instanceof Map) {\n return { __type: 'Map', value: Array.from(val.entries()) };\n }\n if (val instanceof Set) {\n return { __type: 'Set', value: Array.from(val) };\n }\n if (val instanceof RegExp) {\n return { __type: 'RegExp', value: { source: val.source, flags: val.flags } };\n }\n }\n else if (typeof val === 'bigint') {\n return { __type: 'BigInt', value: val.toString() };\n }\n\n return val;\n });\n },\n /**\n * Deserializes a JSON string to its original value.\n * If the value is of a known type (Date, Map, Set, RegExp, BigInt),\n * it will be deserialized using the corresponding handler.\n * Otherwise, it will be deserialized as is.\n * Unknown `__type` values are ignored (returned as-is) for security.\n *\n * @param json - The JSON string to deserialize back to its original form.\n * @returns The deserialized value with all special types reconstructed.\n */\n deserialize(json) {\n return JSON.parse(json, (_key, val) => {\n if (val !== null && typeof val === 'object' && typeof val.__type === 'string') {\n const type = val.__type;\n\n // Security: Only reconstruct types in the allowlist\n if (!ALLOWED_TYPES.has(type)) {\n return val;\n }\n\n const value = val.value;\n\n if (type === 'Date') {\n return new Date(value as string);\n }\n if (type === 'Map') {\n return new Map(value as [unknown, unknown][]);\n }\n if (type === 'Set') {\n return new Set(value as unknown[]);\n }\n if (type === 'RegExp') {\n const { source, flags } = value as { source: string; flags: string };\n if (\n typeof source !== 'string'\n || typeof flags !== 'string'\n || source.length > MAX_REGEXP_SOURCE_LENGTH\n || !VALID_REGEXP_FLAGS.test(flags)\n ) {\n return val;\n }\n return new RegExp(source, flags);\n }\n if (type === 'BigInt') {\n return BigInt(value as string);\n }\n }\n return val;\n });\n },\n};\n"],"mappings":";AAIA,IAAM,IAAgB,IAAI,IAAI;CAAC;CAAQ;CAAO;CAAO;CAAU;CAAS,CAAC,EACnE,IAA2B,KAC3B,IAAqB,iBA+Bd,IAAoC;CAU7C,UAAU,GAAO;AACb,SAAO,KAAK,UAAU,GAAO,SAAyC,GAAM,GAAK;GAG7E,IAAM,IAAgB,KAAK;AAC3B,OAAI,aAAyB,KACzB,QAAO;IAAE,QAAQ;IAAQ,OAAO,EAAc,aAAa;IAAE;AAKjE,OAAoB,OAAO,KAAQ,YAA/B,GAAyC;AACzC,QAAI,aAAe,IACf,QAAO;KAAE,QAAQ;KAAO,OAAO,MAAM,KAAK,EAAI,SAAS,CAAC;KAAE;AAE9D,QAAI,aAAe,IACf,QAAO;KAAE,QAAQ;KAAO,OAAO,MAAM,KAAK,EAAI;KAAE;AAEpD,QAAI,aAAe,OACf,QAAO;KAAE,QAAQ;KAAU,OAAO;MAAE,QAAQ,EAAI;MAAQ,OAAO,EAAI;MAAO;KAAE;cAG3E,OAAO,KAAQ,SACpB,QAAO;IAAE,QAAQ;IAAU,OAAO,EAAI,UAAU;IAAE;AAGtD,UAAO;IACT;;CAYN,YAAY,GAAM;AACd,SAAO,KAAK,MAAM,IAAO,GAAM,MAAQ;AACnC,OAAoB,OAAO,KAAQ,YAA/B,KAA2C,OAAO,EAAI,UAAW,UAAU;IAC3E,IAAM,IAAO,EAAI;AAGjB,QAAI,CAAC,EAAc,IAAI,EAAK,CACxB,QAAO;IAGX,IAAM,IAAQ,EAAI;AAElB,QAAI,MAAS,OACT,QAAO,IAAI,KAAK,EAAgB;AAEpC,QAAI,MAAS,MACT,QAAO,IAAI,IAAI,EAA8B;AAEjD,QAAI,MAAS,MACT,QAAO,IAAI,IAAI,EAAmB;AAEtC,QAAI,MAAS,UAAU;KACnB,IAAM,EAAE,WAAQ,aAAU;AAS1B,YAPI,OAAO,KAAW,YACf,OAAO,KAAU,YACjB,EAAO,SAAS,KAChB,CAAC,EAAmB,KAAK,EAAM,GAE3B,IAEJ,IAAI,OAAO,GAAQ,EAAM;;AAEpC,QAAI,MAAS,SACT,QAAO,OAAO,EAAgB;;AAGtC,UAAO;IACT;;CAET"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Represents a wrapped storage value that includes Time-to-Live (TTL) expiration metadata.
3
+ * @since 3.13.0
4
+ */
5
+ export interface I_StorageEnvelope<T> {
6
+ __isTtlEnvelope: true;
7
+ expiresAt?: number;
8
+ value: T;
9
+ }
10
+ /**
11
+ * Checks whether an unknown storage payload is a valid TTL envelope.
12
+ * @since 3.13.0
13
+ */
14
+ export declare function isTtlEnvelope<T>(payload: unknown): payload is I_StorageEnvelope<T>;
15
+ /**
16
+ * Checks if a TTL envelope has expired based on its timestamp.
17
+ * Returns true if the envelope has an expiration time and that time has passed.
18
+ * @since 3.13.0
19
+ */
20
+ export declare function isExpiredEnvelope<T>(envelope: I_StorageEnvelope<T>): boolean;
21
+ /**
22
+ * Wraps a value in a TTL envelope with the specified expiration duration.
23
+ * @since 3.13.0
24
+ */
25
+ export declare function createTtlEnvelope<T>(value: T, ttlMs: number): I_StorageEnvelope<T>;