modern-ts 0.8.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 (261) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +223 -0
  3. package/README.zh-CN.md +223 -0
  4. package/dist/chunks/Errors-BWEYu-AB.cjs +2 -0
  5. package/dist/chunks/Errors-BWEYu-AB.cjs.map +1 -0
  6. package/dist/chunks/Errors-DwUAvFIF.mjs +63 -0
  7. package/dist/chunks/Errors-DwUAvFIF.mjs.map +1 -0
  8. package/dist/chunks/Math-CGEH1ClN.mjs +68 -0
  9. package/dist/chunks/Math-CGEH1ClN.mjs.map +1 -0
  10. package/dist/chunks/Math-CWZVxSF-.cjs +2 -0
  11. package/dist/chunks/Math-CWZVxSF-.cjs.map +1 -0
  12. package/dist/chunks/base-B9k8Lqvf.mjs +56 -0
  13. package/dist/chunks/base-B9k8Lqvf.mjs.map +1 -0
  14. package/dist/chunks/base-BTXL1y_I.cjs +2 -0
  15. package/dist/chunks/base-BTXL1y_I.cjs.map +1 -0
  16. package/dist/chunks/base-BpECeKwU.mjs +19 -0
  17. package/dist/chunks/base-BpECeKwU.mjs.map +1 -0
  18. package/dist/chunks/base-BvHqpP_s.cjs +2 -0
  19. package/dist/chunks/base-BvHqpP_s.cjs.map +1 -0
  20. package/dist/chunks/base-K-RHLZ-S.mjs +46 -0
  21. package/dist/chunks/base-K-RHLZ-S.mjs.map +1 -0
  22. package/dist/chunks/base-r6kn0B0D.cjs +2 -0
  23. package/dist/chunks/base-r6kn0B0D.cjs.map +1 -0
  24. package/dist/chunks/combine-async-DcG-3p8i.cjs +2 -0
  25. package/dist/chunks/combine-async-DcG-3p8i.cjs.map +1 -0
  26. package/dist/chunks/combine-async-Dcg4ya1R.mjs +236 -0
  27. package/dist/chunks/combine-async-Dcg4ya1R.mjs.map +1 -0
  28. package/dist/chunks/delay-CG3cD7bk.cjs +2 -0
  29. package/dist/chunks/delay-CG3cD7bk.cjs.map +1 -0
  30. package/dist/chunks/delay-CKIXpP71.mjs +32 -0
  31. package/dist/chunks/delay-CKIXpP71.mjs.map +1 -0
  32. package/dist/chunks/helper-BVabbpmX.mjs +165 -0
  33. package/dist/chunks/helper-BVabbpmX.mjs.map +1 -0
  34. package/dist/chunks/helper-tsqZMRHW.cjs +3 -0
  35. package/dist/chunks/helper-tsqZMRHW.cjs.map +1 -0
  36. package/dist/chunks/local-8JVtLN0O.mjs +10 -0
  37. package/dist/chunks/local-8JVtLN0O.mjs.map +1 -0
  38. package/dist/chunks/local-Da4yU-nE.cjs +2 -0
  39. package/dist/chunks/local-Da4yU-nE.cjs.map +1 -0
  40. package/dist/chunks/types-B7X_LBjM.cjs +2 -0
  41. package/dist/chunks/types-B7X_LBjM.cjs.map +1 -0
  42. package/dist/chunks/types-DE2SnSbz.mjs +5 -0
  43. package/dist/chunks/types-DE2SnSbz.mjs.map +1 -0
  44. package/dist/index.cjs +2 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.mjs +759 -0
  47. package/dist/index.mjs.map +1 -0
  48. package/dist/subpath/Arr.cjs +2 -0
  49. package/dist/subpath/Arr.cjs.map +1 -0
  50. package/dist/subpath/Arr.mjs +539 -0
  51. package/dist/subpath/Arr.mjs.map +1 -0
  52. package/dist/subpath/Concurrent.cjs +15 -0
  53. package/dist/subpath/Concurrent.cjs.map +1 -0
  54. package/dist/subpath/Concurrent.mjs +4044 -0
  55. package/dist/subpath/Concurrent.mjs.map +1 -0
  56. package/dist/subpath/FetchQ.cjs +2 -0
  57. package/dist/subpath/FetchQ.cjs.map +1 -0
  58. package/dist/subpath/FetchQ.mjs +519 -0
  59. package/dist/subpath/FetchQ.mjs.map +1 -0
  60. package/dist/subpath/Fit.cjs +2 -0
  61. package/dist/subpath/Fit.cjs.map +1 -0
  62. package/dist/subpath/Fit.mjs +914 -0
  63. package/dist/subpath/Fit.mjs.map +1 -0
  64. package/dist/subpath/Lazy.cjs +2 -0
  65. package/dist/subpath/Lazy.cjs.map +1 -0
  66. package/dist/subpath/Lazy.mjs +72 -0
  67. package/dist/subpath/Lazy.mjs.map +1 -0
  68. package/dist/subpath/Maps.cjs +2 -0
  69. package/dist/subpath/Maps.cjs.map +1 -0
  70. package/dist/subpath/Maps.mjs +123 -0
  71. package/dist/subpath/Maps.mjs.map +1 -0
  72. package/dist/subpath/Maybe.cjs +2 -0
  73. package/dist/subpath/Maybe.cjs.map +1 -0
  74. package/dist/subpath/Maybe.mjs +329 -0
  75. package/dist/subpath/Maybe.mjs.map +1 -0
  76. package/dist/subpath/Reactive.cjs +2 -0
  77. package/dist/subpath/Reactive.cjs.map +1 -0
  78. package/dist/subpath/Reactive.mjs +1204 -0
  79. package/dist/subpath/Reactive.mjs.map +1 -0
  80. package/dist/subpath/Reader.cjs +2 -0
  81. package/dist/subpath/Reader.cjs.map +1 -0
  82. package/dist/subpath/Reader.mjs +75 -0
  83. package/dist/subpath/Reader.mjs.map +1 -0
  84. package/dist/subpath/ReaderT.cjs +2 -0
  85. package/dist/subpath/ReaderT.cjs.map +1 -0
  86. package/dist/subpath/ReaderT.mjs +148 -0
  87. package/dist/subpath/ReaderT.mjs.map +1 -0
  88. package/dist/subpath/Resource.cjs +2 -0
  89. package/dist/subpath/Resource.cjs.map +1 -0
  90. package/dist/subpath/Resource.mjs +150 -0
  91. package/dist/subpath/Resource.mjs.map +1 -0
  92. package/dist/subpath/Result.cjs +2 -0
  93. package/dist/subpath/Result.cjs.map +1 -0
  94. package/dist/subpath/Result.mjs +337 -0
  95. package/dist/subpath/Result.mjs.map +1 -0
  96. package/dist/subpath/Sets.cjs +2 -0
  97. package/dist/subpath/Sets.cjs.map +1 -0
  98. package/dist/subpath/Sets.mjs +92 -0
  99. package/dist/subpath/Sets.mjs.map +1 -0
  100. package/dist/subpath/Str.cjs +2 -0
  101. package/dist/subpath/Str.cjs.map +1 -0
  102. package/dist/subpath/Str.mjs +114 -0
  103. package/dist/subpath/Str.mjs.map +1 -0
  104. package/dist/subpath/TxScope.cjs +2 -0
  105. package/dist/subpath/TxScope.cjs.map +1 -0
  106. package/dist/subpath/TxScope.mjs +138 -0
  107. package/dist/subpath/TxScope.mjs.map +1 -0
  108. package/dist/subpath/TypeTool.cjs +2 -0
  109. package/dist/subpath/TypeTool.cjs.map +1 -0
  110. package/dist/subpath/TypeTool.mjs +9 -0
  111. package/dist/subpath/TypeTool.mjs.map +1 -0
  112. package/dist/subpath/Utils.cjs +2 -0
  113. package/dist/subpath/Utils.cjs.map +1 -0
  114. package/dist/subpath/Utils.mjs +835 -0
  115. package/dist/subpath/Utils.mjs.map +1 -0
  116. package/dist/subpath/VirtualTime.cjs +2 -0
  117. package/dist/subpath/VirtualTime.cjs.map +1 -0
  118. package/dist/subpath/VirtualTime.mjs +1186 -0
  119. package/dist/subpath/VirtualTime.mjs.map +1 -0
  120. package/dist/types/Arr.d.ts +2 -0
  121. package/dist/types/Concurrent/Lock/condition_variable.d.ts +138 -0
  122. package/dist/types/Concurrent/Lock/mutex.d.ts +185 -0
  123. package/dist/types/Concurrent/Lock/rwlock.d.ts +253 -0
  124. package/dist/types/Concurrent/Lock/semaphore.d.ts +208 -0
  125. package/dist/types/Concurrent/Valve/__export__.d.ts +5 -0
  126. package/dist/types/Concurrent/Valve/circuit-breaker.d.ts +146 -0
  127. package/dist/types/Concurrent/Valve/leaky-bucket.d.ts +115 -0
  128. package/dist/types/Concurrent/Valve/sliding-window.d.ts +91 -0
  129. package/dist/types/Concurrent/Valve/token-bucket.d.ts +68 -0
  130. package/dist/types/Concurrent/__export__.d.ts +15 -0
  131. package/dist/types/Concurrent/barrier.d.ts +255 -0
  132. package/dist/types/Concurrent/channel.d.ts +239 -0
  133. package/dist/types/Concurrent/delay.d.ts +42 -0
  134. package/dist/types/Concurrent/ext/map.d.ts +82 -0
  135. package/dist/types/Concurrent/ext/other.d.ts +113 -0
  136. package/dist/types/Concurrent/ext/race.d.ts +31 -0
  137. package/dist/types/Concurrent/ext/some.d.ts +64 -0
  138. package/dist/types/Concurrent/limiter.d.ts +131 -0
  139. package/dist/types/Concurrent/scheduler.d.ts +171 -0
  140. package/dist/types/Concurrent/task-scope.d.ts +282 -0
  141. package/dist/types/Concurrent.d.ts +2 -0
  142. package/dist/types/Errors.d.ts +66 -0
  143. package/dist/types/FetchQ.d.ts +2 -0
  144. package/dist/types/Fit/__export__.d.ts +5 -0
  145. package/dist/types/Fit/base.d.ts +325 -0
  146. package/dist/types/Fit/parser.d.ts +110 -0
  147. package/dist/types/Fit/standard-schema.d.ts +127 -0
  148. package/dist/types/Fit/sugar.d.ts +274 -0
  149. package/dist/types/Fit/tool.d.ts +585 -0
  150. package/dist/types/Fit.d.ts +2 -0
  151. package/dist/types/Lazy.d.ts +2 -0
  152. package/dist/types/Maps.d.ts +2 -0
  153. package/dist/types/Maybe/__export__.d.ts +6 -0
  154. package/dist/types/Maybe/base.d.ts +62 -0
  155. package/dist/types/Maybe/consumers-async.d.ts +58 -0
  156. package/dist/types/Maybe/consumers.d.ts +63 -0
  157. package/dist/types/Maybe/operators-async.d.ts +145 -0
  158. package/dist/types/Maybe/operators.d.ts +177 -0
  159. package/dist/types/Maybe/types.d.ts +12 -0
  160. package/dist/types/Maybe.d.ts +2 -0
  161. package/dist/types/MockClock/Timeline.d.ts +392 -0
  162. package/dist/types/MockClock/TimerHandle.d.ts +159 -0
  163. package/dist/types/MockClock/TimerHeap.d.ts +21 -0
  164. package/dist/types/MockClock/VirtualTimeManager.d.ts +23 -0
  165. package/dist/types/MockClock/__export__.d.ts +104 -0
  166. package/dist/types/MockClock/hooks/__export__.d.ts +9 -0
  167. package/dist/types/MockClock/hooks/hookAbortSignal.d.ts +3 -0
  168. package/dist/types/MockClock/hooks/hookDate.d.ts +3 -0
  169. package/dist/types/MockClock/hooks/hookIntl.d.ts +3 -0
  170. package/dist/types/MockClock/hooks/hookMessageChannel.d.ts +3 -0
  171. package/dist/types/MockClock/hooks/hookMicrotasks.d.ts +3 -0
  172. package/dist/types/MockClock/hooks/hookOs.d.ts +3 -0
  173. package/dist/types/MockClock/hooks/hookPerformance.d.ts +3 -0
  174. package/dist/types/MockClock/hooks/hookProcess.d.ts +3 -0
  175. package/dist/types/MockClock/hooks/hookTimers.d.ts +3 -0
  176. package/dist/types/MockClock/types.d.ts +103 -0
  177. package/dist/types/Other/FetchQ.d.ts +320 -0
  178. package/dist/types/Other/deque.d.ts +59 -0
  179. package/dist/types/Other/disjointSet.d.ts +53 -0
  180. package/dist/types/Other/heap.d.ts +41 -0
  181. package/dist/types/Other/lazy.d.ts +127 -0
  182. package/dist/types/Other/queue.d.ts +42 -0
  183. package/dist/types/Other/secret.d.ts +111 -0
  184. package/dist/types/Other/stack.d.ts +40 -0
  185. package/dist/types/Reactive/__export__.d.ts +4 -0
  186. package/dist/types/Reactive/event_emitter.d.ts +195 -0
  187. package/dist/types/Reactive/flow-combination.d.ts +74 -0
  188. package/dist/types/Reactive/flow.d.ts +180 -0
  189. package/dist/types/Reactive/pace.d.ts +80 -0
  190. package/dist/types/Reactive.d.ts +2 -0
  191. package/dist/types/Reader/__export-readerT__.d.ts +4 -0
  192. package/dist/types/Reader/__export-reader__.d.ts +4 -0
  193. package/dist/types/Reader/local.d.ts +39 -0
  194. package/dist/types/Reader/reader-async.d.ts +84 -0
  195. package/dist/types/Reader/reader.d.ts +96 -0
  196. package/dist/types/Reader/readerT-async.d.ts +186 -0
  197. package/dist/types/Reader/readerT.d.ts +178 -0
  198. package/dist/types/Reader/types.d.ts +37 -0
  199. package/dist/types/Reader.d.ts +2 -0
  200. package/dist/types/ReaderT.d.ts +2 -0
  201. package/dist/types/Resource/TxScope-async.d.ts +86 -0
  202. package/dist/types/Resource/TxScope.d.ts +85 -0
  203. package/dist/types/Resource/__export-TxScope__.d.ts +2 -0
  204. package/dist/types/Resource/__export-resource__.d.ts +2 -0
  205. package/dist/types/Resource/resource-async.d.ts +79 -0
  206. package/dist/types/Resource/resource.d.ts +78 -0
  207. package/dist/types/Resource/types.d.ts +79 -0
  208. package/dist/types/Resource.d.ts +2 -0
  209. package/dist/types/Result/Consumers/branch-async.d.ts +77 -0
  210. package/dist/types/Result/Consumers/branch.d.ts +70 -0
  211. package/dist/types/Result/Consumers/inspect.d.ts +66 -0
  212. package/dist/types/Result/Operators/Async/combine-async.d.ts +69 -0
  213. package/dist/types/Result/Operators/Async/partition-async.d.ts +29 -0
  214. package/dist/types/Result/Operators/Async/reduce-async.d.ts +15 -0
  215. package/dist/types/Result/Operators/Async/transform-async.d.ts +90 -0
  216. package/dist/types/Result/Operators/combine.d.ts +60 -0
  217. package/dist/types/Result/Operators/flatten.d.ts +26 -0
  218. package/dist/types/Result/Operators/partition.d.ts +25 -0
  219. package/dist/types/Result/Operators/reduce.d.ts +12 -0
  220. package/dist/types/Result/Operators/transform.d.ts +70 -0
  221. package/dist/types/Result/__export__.d.ts +14 -0
  222. package/dist/types/Result/base.d.ts +115 -0
  223. package/dist/types/Result/types.d.ts +34 -0
  224. package/dist/types/Result.d.ts +2 -0
  225. package/dist/types/Sets.d.ts +2 -0
  226. package/dist/types/Str.d.ts +2 -0
  227. package/dist/types/TxScope.d.ts +2 -0
  228. package/dist/types/TypeTool.d.ts +2 -0
  229. package/dist/types/Utils/Array/__export__.d.ts +10 -0
  230. package/dist/types/Utils/Array/filtering.d.ts +89 -0
  231. package/dist/types/Utils/Array/flatten.d.ts +45 -0
  232. package/dist/types/Utils/Array/grouping.d.ts +44 -0
  233. package/dist/types/Utils/Array/iteration.d.ts +86 -0
  234. package/dist/types/Utils/Array/operators.d.ts +62 -0
  235. package/dist/types/Utils/Array/randomization.d.ts +76 -0
  236. package/dist/types/Utils/Array/set.d.ts +108 -0
  237. package/dist/types/Utils/Array/slice.d.ts +189 -0
  238. package/dist/types/Utils/Array/sorting.d.ts +55 -0
  239. package/dist/types/Utils/Array/zip.d.ts +93 -0
  240. package/dist/types/Utils/Functions/__export__.d.ts +5 -0
  241. package/dist/types/Utils/Functions/base.d.ts +157 -0
  242. package/dist/types/Utils/Functions/curry.d.ts +73 -0
  243. package/dist/types/Utils/Functions/debounce.d.ts +240 -0
  244. package/dist/types/Utils/Functions/defer.d.ts +43 -0
  245. package/dist/types/Utils/Functions/pipe.d.ts +205 -0
  246. package/dist/types/Utils/Map.d.ts +284 -0
  247. package/dist/types/Utils/Math.d.ts +225 -0
  248. package/dist/types/Utils/Object/__export__.d.ts +2 -0
  249. package/dist/types/Utils/Object/base.d.ts +131 -0
  250. package/dist/types/Utils/Object/clone.d.ts +81 -0
  251. package/dist/types/Utils/Predicates.d.ts +361 -0
  252. package/dist/types/Utils/Set.d.ts +105 -0
  253. package/dist/types/Utils/String.d.ts +217 -0
  254. package/dist/types/Utils/__export__.d.ts +9 -0
  255. package/dist/types/Utils/type-tool.d.ts +168 -0
  256. package/dist/types/Utils.d.ts +2 -0
  257. package/dist/types/VirtualTime.d.ts +2 -0
  258. package/dist/types/helper.d.ts +71 -0
  259. package/dist/types/index.d.ts +21 -0
  260. package/dist/types/unknown-error.d.ts +98 -0
  261. package/package.json +179 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Arr.mjs","sources":["../../src/Utils/Array/flatten.ts","../../src/Utils/Array/grouping.ts","../../src/Utils/Array/operators.ts","../../src/Utils/Array/set.ts","../../src/Utils/Array/slice.ts","../../src/Utils/Array/zip.ts","../../src/Utils/Array/filtering.ts","../../src/Utils/Array/iteration.ts","../../src/Utils/Array/sorting.ts","../../src/Utils/Array/randomization.ts"],"sourcesContent":["// ========================================\r\n// ./src/Utils/Array/flatten.ts\r\n// ========================================\r\n\r\n/**\r\n * Extracts deepest type from nested array structure.\r\n * @typeParam T - Input type (possibly nested array).\r\n * @example\r\n * // Returns: number\r\n * type Example = DeepExtract<number[][][]>;\r\n */\r\ntype DeepExtract<T> =\r\n T extends ReadonlyArray<infer Inner> ? DeepExtract<Inner> : T;\r\n\r\n/**\r\n * Recursively flattens array while **skipping sparse holes** (not converting to undefined).\r\n * Implementation: Manual stack-based iteration (no recursion risk) + explicit hole skipping.\r\n * Hole behavior: `i in array` check ensures holes are **completely skipped**\r\n * Order preserved: DFS with index tracking maintains original element order\r\n * @param array - Array with arbitrary nesting and possible sparse holes.\r\n * @returns Fully flattened array with all holes skipped at every nesting level.\r\n * @example\r\n * flattenDeep([1, , [2, , [3]]]) // => [1, 2, 3] (holes at all levels skipped!)\r\n */\r\nexport const flattenDeep = <T>(array: readonly T[]): DeepExtract<T>[] => {\r\n const result: DeepExtract<T>[] = [];\r\n const stack: Array<{array: readonly unknown[]; nextIndex: number}> = [\r\n {array, nextIndex: 0},\r\n ];\r\n\r\n while (stack.length > 0) {\r\n const frame = stack[stack.length - 1];\r\n const {array: current} = frame;\r\n\r\n if (frame.nextIndex >= current.length) {\r\n stack.pop();\r\n continue;\r\n }\r\n\r\n const currentIndex = frame.nextIndex++;\r\n\r\n if (!(currentIndex in current)) {\r\n continue;\r\n }\r\n\r\n const element = current[currentIndex];\r\n\r\n if (Array.isArray(element)) {\r\n stack.push({array: element, nextIndex: 0});\r\n } else {\r\n result.push(element as DeepExtract<T>);\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * Maps each element then fully flattens while **skipping sparse holes**.\r\n * Hole behavior: Original array holes skipped BEFORE mapping (callback never sees holes)\r\n * Nested holes: flattenDeep() skips holes in mapped arrays too\r\n * @param array - Source array (may be sparse).\r\n * @param callback - Mapping function (receives ONLY existing elements + their real index).\r\n * @returns Fully flattened mapped array with all holes skipped.\r\n * @example\r\n * flatMapDeep([1, , 2], x => [x, , x*10]) // => [1, 10, 2, 20] (all holes skipped!)\r\n */\r\nexport const flatMapDeep = <T, U>(\r\n array: readonly T[],\r\n callback: (item: T, index: number) => U,\r\n): DeepExtract<U>[] => {\r\n const mapped: DeepExtract<U>[] = [];\r\n\r\n for (let i = 0; i < array.length; i++) {\r\n if (i in array) {\r\n const value = callback(array[i], i);\r\n if (Array.isArray(value)) {\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\r\n mapped.push(...flattenDeep(value));\r\n } else {\r\n mapped.push(value as DeepExtract<U>);\r\n }\r\n }\r\n }\r\n\r\n return mapped;\r\n};\r\n\r\n/**\r\n * Async mapped flattening with concurrency limit + **strict hole skipping**.\r\n * Hole behavior: ONLY existing indices trigger callback (holes completely ignored)\r\n * Order preserved: Results inserted at original non-hole positions\r\n * No wasted work: Zero callbacks for hole positions\r\n * @param array - Source array (may be sparse).\r\n * @param callback - Async mapper (called ONLY for existing elements).\r\n * @param concurrency - Max parallel operations (default: Infinity).\r\n * @returns Promise of flattened results with all holes skipped.\r\n * @example\r\n * await flatMapAsync([1, , 2], async x => [x, , x*10], 2)\r\n * // => [1, 10, 2, 20] (no callbacks for holes!)\r\n */\r\nexport const flatMapAsync = async <T, U>(\r\n array: readonly T[],\r\n callback: (item: T, index: number) => Promise<U | readonly U[]>,\r\n concurrency: number = Infinity,\r\n): Promise<U[]> => {\r\n const existingIndices: number[] = [];\r\n for (let i = 0; i < array.length; i++) {\r\n if (i in array) existingIndices.push(i);\r\n }\r\n\r\n const total = existingIndices.length;\r\n if (total === 0) return [];\r\n\r\n const safeConcurrency = Math.max(\r\n 1,\r\n Math.floor(isNaN(concurrency) ? 1 : concurrency),\r\n );\r\n const results = new Array<U | readonly U[]>(total);\r\n let cursor = 0;\r\n\r\n const worker = async () => {\r\n let pos: number;\r\n while ((pos = cursor++) < total) {\r\n const origIdx = existingIndices[pos];\r\n results[pos] = await callback(array[origIdx], origIdx);\r\n }\r\n };\r\n\r\n const workers = Array.from({length: Math.min(safeConcurrency, total)}, () =>\r\n worker(),\r\n );\r\n await Promise.all(workers);\r\n\r\n const final: U[] = [];\r\n for (const res of results) {\r\n if (Array.isArray(res)) final.push(...res);\r\n else final.push(res as U);\r\n }\r\n return final;\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/grouping.ts\r\n// ========================================\r\n\r\n/**\r\n * Groups array items by a computed key. Keys are converted to strings -\r\n * distinct original keys that stringify to the same value will merge groups.\r\n * @param list Array to group\r\n * @param keyGetter Function extracting grouping key from each item\r\n * @returns Object with stringified keys mapping to arrays of grouped items\r\n */\r\nexport const groupBy = <T, K extends string | number | boolean>(\r\n list: readonly T[],\r\n keyGetter: (item: T) => K,\r\n): Record<string | number, T[]> => {\r\n return list.reduce<Record<string | number, T[]>>(\r\n (acc, item) => {\r\n const rawKey = keyGetter(item);\r\n const key = String(rawKey);\r\n\r\n if (!acc[key]) {\r\n acc[key] = [];\r\n }\r\n acc[key].push(item);\r\n return acc;\r\n },\r\n {} as Record<string | number, T[]>,\r\n );\r\n};\r\n\r\n/**\r\n * Creates object lookup by computed key. Last item wins for duplicate keys\r\n * after string conversion. Returns empty object for empty array.\r\n * @param list Array to index\r\n * @param keyGetter Function extracting key from each item\r\n * @returns Object with stringified keys mapping to the last corresponding item\r\n */\r\nexport const keyBy = <T, K extends string | number | boolean>(\r\n list: readonly T[],\r\n keyGetter: (item: T) => K,\r\n): Record<string | number, T> => {\r\n return list.reduce<Record<string | number, T>>(\r\n (acc, item) => {\r\n const key = String(keyGetter(item));\r\n acc[key] = item;\r\n return acc;\r\n },\r\n {} as Record<string | number, T>,\r\n );\r\n};\r\n\r\n/**\r\n * Splits array into two groups based on predicate. Always returns tuple of\r\n * two arrays (truthy group first). Both arrays are empty for empty input.\r\n * @param list Array to partition\r\n * @param predicate Filtering function\r\n * @returns Tuple where first array contains items satisfying predicate\r\n */\r\nexport const partition = <T>(\r\n list: readonly T[],\r\n predicate: (item: T) => boolean,\r\n): [T[], T[]] => {\r\n return list.reduce(\r\n (acc, item) => {\r\n acc[predicate(item) ? 0 : 1].push(item);\r\n return acc;\r\n },\r\n [[], []] as [T[], T[]],\r\n );\r\n};\r\n\r\n/**\r\n * Splits an array into chunks of the specified size. Returns an empty array\r\n * if the input array is empty or chunk size is zero. Negative sizes are\r\n * treated as zero. The final chunk may be smaller than the specified size.\r\n *\r\n * @param array - The array to process\r\n * @param size - The length of each chunk (default: 1)\r\n * @returns A new array of chunks\r\n */\r\nexport const chunk = <T>(array: readonly T[], size: number = 1): T[][] => {\r\n const chunk_size = Math.max(Math.floor(size), 0);\r\n const array_length = array.length;\r\n if (array_length === 0 || chunk_size === 0) return [];\r\n\r\n const result: T[][] = [];\r\n for (let i = 0; i < array_length; i += chunk_size) {\r\n result.push(array.slice(i, i + chunk_size));\r\n }\r\n return result;\r\n};\r\n\r\n/**\r\n * Creates an object composed of keys generated from iteratee results,\r\n * with corresponding values counting their occurrences in the array.\r\n * String and number keys are supported; other types will be coerced to strings.\r\n *\r\n * @param array - The array to iterate over\r\n * @param iteratee - The function to generate keys from elements\r\n * @returns An object with keys and their counts\r\n */\r\nexport const countBy = <T>(\r\n array: readonly T[],\r\n iteratee: (value: T) => string | number,\r\n): Record<string, number> => {\r\n const result: Record<string, number> = {};\r\n for (const item of array) {\r\n const key = iteratee(item);\r\n if (result[key]) {\r\n result[key]++;\r\n } else {\r\n result[key] = 1;\r\n }\r\n }\r\n return result;\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/operators.ts\r\n// ========================================\r\n\r\n/**\r\n * Maps array in-place within specified range. Clamps indices to valid array bounds.\r\n * Negative start/end count from array end. Returns modified original array.\r\n * @param array - Array to modify (mutated)\r\n * @param transform - Mapping function receiving current index\r\n * @param start - Start index (clamped, negative counts from end)\r\n * @param end - End index (clamped, negative counts from end)\r\n * @returns Mutated original array with mixed types\r\n */\r\nexport const mapInPlace = <T, R>(\r\n array: readonly T[],\r\n transform: (index: number) => R,\r\n start = 0,\r\n end = array.length,\r\n): readonly (T | R)[] => {\r\n const len = array.length;\r\n const relative_start =\r\n start < 0 ? Math.max(len + start, 0) : Math.min(start, len);\r\n const relative_end = end < 0 ? Math.max(len + end, 0) : Math.min(end, len);\r\n\r\n for (let i = relative_start; i < relative_end; i++) {\r\n (array as (T | R)[])[i] = transform(i);\r\n }\r\n return array as (T | R)[];\r\n};\r\n\r\n/**\r\n * Creates new array mapped within specified range. Clamps indices to valid bounds.\r\n * Negative start/end count from array end. Original array remains unchanged.\r\n * @param array - Source array (not mutated)\r\n * @param transform - Mapping function receiving current index\r\n * @param start - Start index (clamped, negative counts from end)\r\n * @param end - End index (clamped, negative counts from end)\r\n * @returns New array with mixed types\r\n */\r\nexport const mapToNewArray = <T, R>(\r\n array: readonly T[],\r\n transform: (index: number) => R,\r\n start = 0,\r\n end = array.length,\r\n): readonly (T | R)[] => mapInPlace([...array], transform, start, end);\r\n\r\n/**\r\n * Returns all arrays with minimum length. Empty arrays included in comparison.\r\n * Returns single array if unique minimum, multiple arrays if tie.\r\n * Returns empty array if no input arrays provided.\r\n * @param arrays - Arrays to compare\r\n * @returns Array of shortest arrays\r\n */\r\nexport const shortest = <T>(...arrays: readonly T[][]): readonly T[][] => {\r\n let min_len = Infinity;\r\n let result: T[][] = [];\r\n\r\n for (const arr of arrays) {\r\n const len = arr.length;\r\n if (len < min_len) {\r\n min_len = len;\r\n result = [arr];\r\n } else if (len === min_len) {\r\n result.push(arr);\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * Moves element between positions using circular indexing. Returns original array.\r\n * No-op for single-element arrays or identical source/destination.\r\n * Uses copyWithin for optimal performance. Handles both forward and backward moves.\r\n * @param array - Array to modify (mutated)\r\n * @param from - Source index (wraps circularly)\r\n * @param to - Destination index (wraps circularly)\r\n * @returns Mutated original array\r\n */\r\nexport const move = <T>(array: T[], from: number, to: number): T[] => {\r\n const len = array.length;\r\n if (len <= 1) return array;\r\n\r\n const start = ((from % len) + len) % len;\r\n const end = ((to % len) + len) % len;\r\n\r\n if (start === end) return array;\r\n const item = array[start];\r\n\r\n if (start < end) array.copyWithin(start, start + 1, end + 1);\r\n else array.copyWithin(end + 1, end, start);\r\n\r\n array[end] = item;\r\n return array;\r\n};\r\n\r\n/**\r\n * Finds the element with maximum value according to the iteratee function\r\n *\r\n * @template T - The type of elements in the array\r\n * @param array - The array to search (readonly, accepts sparse arrays)\r\n * @param iteratee - Function that returns a numeric value for each element\r\n * @returns The element with maximum iteratee value, or undefined for empty array\r\n * @remarks - Returns undefined for empty arrays. Handles sparse arrays by skipping missing indices.\r\n * - If multiple elements have the same maximum value, returns the first found.\r\n * - Iteratee is called only for existing elements in sparse arrays.\r\n */\r\nexport const maxBy = <T>(\r\n array: readonly T[],\r\n iteratee: (value: T) => number,\r\n): T | undefined => {\r\n if (array.length === 0) {\r\n return undefined;\r\n }\r\n\r\n let result: T | undefined = undefined;\r\n let max_score = -Infinity;\r\n\r\n for (let i = 0; i < array.length; i++) {\r\n if (i in array) {\r\n const current_item = array[i];\r\n const current_score = iteratee(current_item);\r\n\r\n if (current_score > max_score) {\r\n max_score = current_score;\r\n result = current_item;\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * Finds the element with minimum value according to the iteratee function\r\n *\r\n * @template T - The type of elements in the array\r\n * @param array - The array to search (readonly, accepts sparse arrays)\r\n * @param iteratee - Function that returns a numeric value for each element\r\n * @returns The element with minimum iteratee value, or undefined for empty array\r\n * @remarks - Returns undefined for empty arrays. Handles sparse arrays by skipping missing indices.\r\n * - If multiple elements have the same minimum value, returns the first found.\r\n * - Iteratee is called only for existing elements in sparse arrays.\r\n */\r\nexport const minBy = <T>(\r\n array: readonly T[],\r\n iteratee: (value: T) => number,\r\n): T | undefined => {\r\n if (array.length === 0) {\r\n return undefined;\r\n }\r\n\r\n let result: T | undefined = undefined;\r\n let min_score = Infinity;\r\n\r\n for (let i = 0; i < array.length; i++) {\r\n if (i in array) {\r\n const current_item = array[i];\r\n const current_score = iteratee(current_item);\r\n\r\n if (current_score < min_score) {\r\n min_score = current_score;\r\n result = current_item;\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/set.ts\r\n// ========================================\r\n\r\ntype Comparator<T> = (a: T, b: T) => boolean;\r\ntype Iteratee<T, V> = (value: T) => V;\r\n\r\n// ========================================\r\n// 差集\r\n// ========================================\r\n\r\n/**\r\n * Returns the difference between two arrays (elements in array1 but not in array2)\r\n * @param array - The source array\r\n * @param values - Arrays to exclude values from\r\n * @returns Array containing elements present only in the first array\r\n */\r\nexport const difference = <T>(\r\n array: readonly T[],\r\n ...values: (readonly T[])[]\r\n): T[] => {\r\n const restSet = new Set(values.flat());\r\n return array.filter((item) => !restSet.has(item));\r\n};\r\n\r\n/**\r\n * Returns the difference between arrays using an iteratee function\r\n * @param array - The source array\r\n * @param values - Array to exclude values from\r\n * @param iteratee - Function to transform values before comparison\r\n * @returns Array containing elements with unique transformed values\r\n */\r\nexport const differenceBy = <T, V>(\r\n array: readonly T[],\r\n values: readonly T[],\r\n iteratee: Iteratee<T, V>,\r\n): T[] => {\r\n const restSet = new Set(values.map(iteratee));\r\n return array.filter((item) => !restSet.has(iteratee(item)));\r\n};\r\n\r\n/**\r\n * Returns the difference between arrays using a comparator function\r\n * @param array - The source array\r\n * @param values - Array to exclude values from\r\n * @param comparator - Function to compare two elements\r\n * @returns Array containing elements not matching any in values\r\n */\r\nexport const differenceWith = <T>(\r\n array: readonly T[],\r\n values: readonly T[],\r\n comparator: Comparator<T>,\r\n): T[] => {\r\n return array.filter((a) => !values.some((b) => comparator(a, b)));\r\n};\r\n\r\n// ========================================\r\n// 交集\r\n// ========================================\r\n\r\n/**\r\n * Returns the intersection of multiple arrays\r\n * @param arrays - Arrays to find common elements from\r\n * @returns Array containing elements present in all arrays\r\n */\r\nexport const intersection = <T>(...arrays: (readonly T[])[]): T[] => {\r\n if (arrays.length === 0) return [];\r\n if (arrays.length === 1) return [...arrays[0]];\r\n\r\n // 找到最短的数组作为基准\r\n const shortest = arrays.reduce((a, b) => (a.length < b.length ? a : b));\r\n // 将其他数组预处理成 Set\r\n const otherSets = arrays.filter((a) => a !== shortest).map((a) => new Set(a));\r\n\r\n return shortest.filter((item) => otherSets.every((set) => set.has(item)));\r\n};\r\n\r\n/**\r\n * Returns the intersection of two arrays using an iteratee function\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @param iteratee - Function to transform values before comparison\r\n * @returns Array containing elements with matching transformed values\r\n */\r\nexport const intersectionBy = <T, V>(\r\n array1: readonly T[],\r\n array2: readonly T[],\r\n iteratee: Iteratee<T, V>,\r\n): T[] => {\r\n const set2 = new Set(array2.map(iteratee));\r\n return array1.filter((item) => set2.has(iteratee(item)));\r\n};\r\n\r\n/**\r\n * Returns the intersection of two arrays using a comparator function\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @param comparator - Function to compare two elements\r\n * @returns Array containing elements matching at least one in both arrays\r\n */\r\nexport const intersectionWith = <T>(\r\n array1: readonly T[],\r\n array2: readonly T[],\r\n comparator: Comparator<T>,\r\n): T[] => {\r\n return array1.filter((a) => array2.some((b) => comparator(a, b)));\r\n};\r\n\r\n// ========================================\r\n// 并集\r\n// ========================================\r\n\r\n/**\r\n * Returns the union of multiple arrays\r\n * @param arrays - Arrays to combine\r\n * @returns Array containing unique elements from all arrays\r\n */\r\nexport const union = <T>(...arrays: (readonly T[])[]): T[] => {\r\n return Array.from(new Set(arrays.flat()));\r\n};\r\n\r\n/**\r\n * Returns the union of two arrays using an iteratee function\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @param iteratee - Function to transform values before deduplication\r\n * @returns Array containing unique elements based on transformed values\r\n */\r\nexport const unionBy = <T, V>(\r\n array1: readonly T[],\r\n array2: readonly T[],\r\n iteratee: Iteratee<T, V>,\r\n): T[] => {\r\n const map = new Map<V, T>();\r\n [...array1, ...array2].forEach((item) => {\r\n const key = iteratee(item);\r\n if (!map.has(key)) map.set(key, item);\r\n });\r\n return Array.from(map.values());\r\n};\r\n\r\n/**\r\n * Returns the union of two arrays using a comparator function\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @param comparator - Function to determine equality between elements\r\n * @returns Array containing elements considered unique by the comparator\r\n */\r\nexport const unionWith = <T>(\r\n array1: readonly T[],\r\n array2: readonly T[],\r\n comparator: Comparator<T>,\r\n): T[] => {\r\n const result = [...array1];\r\n for (const item of array2) {\r\n if (!result.some((r) => comparator(r, item))) {\r\n result.push(item);\r\n }\r\n }\r\n return result;\r\n};\r\n\r\n// ========================================\r\n// 对称差集\r\n// ========================================\r\n\r\n/**\r\n * Returns the symmetric difference between two arrays\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @returns Array containing elements present in only one of the arrays\r\n */\r\nexport const xor = <T>(array1: readonly T[], array2: readonly T[]): T[] => {\r\n return [...difference(array1, array2), ...difference(array2, array1)];\r\n};\r\n\r\n/**\r\n * Returns the symmetric difference using an iteratee function\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @param iteratee - Function to transform values before comparison\r\n * @returns Array containing elements with unique transformed values\r\n */\r\nexport const xorBy = <T, V>(\r\n array1: readonly T[],\r\n array2: readonly T[],\r\n iteratee: Iteratee<T, V>,\r\n): T[] => {\r\n return [\r\n ...differenceBy(array1, array2, iteratee),\r\n ...differenceBy(array2, array1, iteratee),\r\n ];\r\n};\r\n\r\n/**\r\n * Returns the symmetric difference using a comparator function\r\n * @param array1 - First array\r\n * @param array2 - Second array\r\n * @param comparator - Function to compare two elements\r\n * @returns Array containing elements not matching any in the other array\r\n */\r\nexport const xorWith = <T>(\r\n array1: readonly T[],\r\n array2: readonly T[],\r\n comparator: Comparator<T>,\r\n): T[] => {\r\n return [\r\n ...differenceWith(array1, array2, comparator),\r\n ...differenceWith(array2, array1, comparator),\r\n ];\r\n};\r\n\r\n// ========================================\r\n// 子集判断\r\n// ========================================\r\n\r\n/**\r\n * Checks if one array is a subset of another\r\n * @param subset - Array to check as subset\r\n * @param superset - Array to check as superset\r\n * @returns True if all elements of subset exist in superset\r\n */\r\nexport const isSubset = <T>(\r\n subset: readonly T[],\r\n superset: readonly T[],\r\n): boolean => {\r\n const superSetObj = new Set(superset);\r\n return subset.every((item) => superSetObj.has(item));\r\n};\r\n\r\n/**\r\n * Checks if one array is a subset of another using a comparator\r\n * @param subset - Array to check as subset\r\n * @param superset - Array to check as superset\r\n * @param comparator - Function to compare two elements\r\n * @returns True if all elements of subset have matches in superset\r\n */\r\nexport const isSubsetWith = <T>(\r\n subset: readonly T[],\r\n superset: readonly T[],\r\n comparator: Comparator<T>,\r\n): boolean => {\r\n return subset.every((subItem) =>\r\n superset.some((superItem) => comparator(subItem, superItem)),\r\n );\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/slice.ts\r\n// ========================================\r\n\r\n/**\r\n * Gets the first element of an array.\r\n * @param array - The array to query.\r\n * @returns The first element, or undefined if array is empty.\r\n * @example\r\n * head([1, 2, 3]) // => 1\r\n * head([]) // => undefined\r\n */\r\nexport const head = <T>(array: readonly T[]) => array[0];\r\n\r\n/**\r\n * Gets the last element of an array.\r\n * @param array - The array to query.\r\n * @returns The last element, or undefined if array is empty.\r\n * @example\r\n * last([1, 2, 3]) // => 3\r\n * last([]) // => undefined\r\n */\r\nexport const last = <T>(array: readonly T[]): T | undefined =>\r\n array.at?.(-1) ?? array[array.length - 1];\r\n\r\n/**\r\n * Gets all but the last element of an array.\r\n * @param array - The array to query.\r\n * @returns A new array excluding the last element.\r\n * @remarks\r\n * - Returns empty array if input array has 0 or 1 elements\r\n * - Non-integer array length is handled by slice()\r\n * @example\r\n * initial([1, 2, 3]) // => [1, 2]\r\n * initial([1]) // => []\r\n * initial([]) // => []\r\n */\r\nexport const initial = <T>(array: readonly T[]) => array.slice(0, -1);\r\n\r\n/**\r\n * Gets all but the first element of an array.\r\n * @param array - The array to query.\r\n * @returns A new array excluding the first element.\r\n * @remarks\r\n * - Returns empty array if input array has 0 or 1 elements\r\n * - Non-integer array length is handled by slice()\r\n * @example\r\n * tail([1, 2, 3]) // => [2, 3]\r\n * tail([1]) // => []\r\n * tail([]) // => []\r\n */\r\nexport const tail = <T>(array: readonly T[]) => array.slice(1);\r\n\r\n/**\r\n * Takes n elements from the beginning.\r\n * @param array - The array to query.\r\n * @param n - Number of elements to take (default: 1).\r\n * @returns A new array of taken elements.\r\n * @remarks\r\n * - n <= 0: returns empty array\r\n * - n is not an integer: converted to integer via slice()\r\n * - n > array.length: returns entire array copy\r\n * - NaN or Infinity n: behavior depends on slice() conversion\r\n * @example\r\n * take([1, 2, 3], 2) // => [1, 2]\r\n * take([1, 2, 3], 0) // => []\r\n * take([1, 2, 3], -1) // => []\r\n * take([1, 2, 3], 5) // => [1, 2, 3]\r\n */\r\nexport const take = <T>(array: readonly T[], n = 1) => {\r\n if (n <= 0) return [];\r\n return array.slice(0, n);\r\n};\r\n\r\n/**\r\n * Takes n elements from the end.\r\n * @param array - The array to query.\r\n * @param n - Number of elements to take (default: 1).\r\n * @returns A new array of taken elements.\r\n * @remarks\r\n * - n <= 0: returns empty array\r\n * - n is not an integer: converted to integer via slice()\r\n * - n > array.length: returns entire array copy\r\n * - NaN or Infinity n: behavior depends on slice() conversion\r\n * @example\r\n * takeRight([1, 2, 3], 2) // => [2, 3]\r\n * takeRight([1, 2, 3], 0) // => []\r\n * takeRight([1, 2, 3], -1) // => []\r\n */\r\nexport const takeRight = <T>(array: readonly T[], n = 1) => {\r\n if (n <= 0) return [];\r\n return array.slice(-n);\r\n};\r\n\r\n/**\r\n * Drops n elements from the beginning.\r\n * @param array - The array to query.\r\n * @param n - Number of elements to drop (default: 1).\r\n * @returns A new array of remaining elements.\r\n * @remarks\r\n * - n <= 0: returns full array copy\r\n * - n is not an integer: converted to integer via slice()\r\n * - n >= array.length: returns empty array\r\n * - NaN or Infinity n: behavior depends on slice() conversion\r\n * @example\r\n * drop([1, 2, 3], 2) // => [3]\r\n * drop([1, 2, 3], 0) // => [1, 2, 3]\r\n * drop([1, 2, 3], 5) // => []\r\n */\r\nexport const drop = <T>(array: readonly T[], n = 1) => {\r\n if (n <= 0) return [...array];\r\n return array.slice(n);\r\n};\r\n\r\n/**\r\n * Drops n elements from the end.\r\n * @param array - The array to query.\r\n * @param n - Number of elements to drop (default: 1).\r\n * @returns A new array of remaining elements.\r\n * @remarks\r\n * - n <= 0: returns full array copy\r\n * - n is not an integer: converted to integer via slice()\r\n * - n >= array.length: returns empty array\r\n * - NaN or Infinity n: behavior depends on slice() conversion\r\n * @example\r\n * dropRight([1, 2, 3], 2) // => [1]\r\n * dropRight([1, 2, 3], 0) // => [1, 2, 3]\r\n * dropRight([1, 2, 3], 5) // => []\r\n */\r\nexport const dropRight = <T>(array: readonly T[], n = 1) => {\r\n if (n <= 0) return [...array];\r\n return array.slice(0, -n);\r\n};\r\n\r\ntype Predicate<T> = (value: T) => boolean;\r\n\r\n/**\r\n * Takes elements from the beginning while predicate returns true.\r\n * @param array - The array to query.\r\n * @param predicate - The function invoked per iteration.\r\n * @returns A new array of taken elements.\r\n * @remarks\r\n * - Empty array: returns empty array\r\n * - All elements satisfy predicate: returns full array copy\r\n * - No elements satisfy predicate: returns empty array\r\n * - Predicate throws: iteration stops at exception\r\n * @example\r\n * takeWhile([1, 2, 3, 4], x => x < 3) // => [1, 2]\r\n * takeWhile([], x => x < 3) // => []\r\n * takeWhile([1, 2, 3], x => x < 5) // => [1, 2, 3]\r\n */\r\nexport const takeWhile = <T>(\r\n array: readonly T[],\r\n predicate: Predicate<T>,\r\n): T[] => {\r\n const index = array.findIndex((value) => !predicate(value));\r\n if (index === -1) return [...array];\r\n return array.slice(0, index);\r\n};\r\n\r\n/**\r\n * Takes elements from the end while predicate returns true.\r\n * @param array - The array to query.\r\n * @param predicate - The function invoked per iteration.\r\n * @returns A new array of taken elements.\r\n * @remarks\r\n * - Empty array: returns empty array\r\n * - All elements satisfy predicate: returns full array copy\r\n * - No elements satisfy predicate: returns empty array\r\n * - Iterates from end; predicate called for each element until false\r\n * @example\r\n * takeRightWhile([1, 2, 3, 4], x => x > 2) // => [3, 4]\r\n * takeRightWhile([], x => x > 2) // => []\r\n */\r\nexport const takeRightWhile = <T>(\r\n array: readonly T[],\r\n predicate: Predicate<T>,\r\n): T[] => {\r\n let i = array.length;\r\n while (i-- > 0 && predicate(array[i]));\r\n return array.slice(i + 1);\r\n};\r\n\r\n/**\r\n * Drops elements from the beginning while predicate returns true.\r\n * @param array - The array to query.\r\n * @param predicate - The function invoked per iteration.\r\n * @returns A new array of remaining elements.\r\n * @remarks\r\n * - Empty array: returns empty array\r\n * - All elements satisfy predicate: returns empty array\r\n * - No elements satisfy predicate: returns full array copy\r\n * @example\r\n * dropWhile([1, 2, 3, 4], x => x < 3) // => [3, 4]\r\n * dropWhile([], x => x < 3) // => []\r\n * dropWhile([1, 2, 3], x => x < 5) // => []\r\n */\r\nexport const dropWhile = <T>(\r\n array: readonly T[],\r\n predicate: Predicate<T>,\r\n): T[] => {\r\n const index = array.findIndex((value) => !predicate(value));\r\n if (index === -1) return [];\r\n return array.slice(index);\r\n};\r\n\r\n/**\r\n * Drops elements from the end while predicate returns true.\r\n * @param array - The array to query.\r\n * @param predicate - The function invoked per iteration.\r\n * @returns A new array of remaining elements.\r\n * @remarks\r\n * - Empty array: returns empty array\r\n * - All elements satisfy predicate: returns empty array\r\n * - No elements satisfy predicate: returns full array copy\r\n * - Iterates from end; predicate called for each element until false\r\n * @example\r\n * dropRightWhile([1, 2, 3, 4], x => x > 2) // => [1, 2]\r\n * dropRightWhile([], x => x > 2) // => []\r\n */\r\nexport const dropRightWhile = <T>(\r\n array: readonly T[],\r\n predicate: Predicate<T>,\r\n): T[] => {\r\n let i = array.length;\r\n while (i-- > 0 && predicate(array[i]));\r\n return array.slice(0, i + 1);\r\n};\r\n\r\n/**\r\n * Collects elements at specified indices. Returns empty array if either array or indices are empty.\r\n * When circular is true, indices wrap around array bounds using modulo arithmetic.\r\n * @param array - Source array\r\n * @param indices - Target indices to collect\r\n * @param circular - Enable circular indexing (default: false)\r\n * @returns Array of collected elements, undefined for out-of-bounds non-circular indices\r\n */\r\nexport const collectAt = <T>(\r\n array: T[],\r\n indices: number[],\r\n circular = false,\r\n): (T | undefined)[] => {\r\n const len = array.length;\r\n if (!len || !indices.length) return [];\r\n const getIdx = circular\r\n ? (idx: number) => ((idx % len) + len) % len\r\n : (idx: number) => idx;\r\n\r\n return indices.map((idx) => array[getIdx(idx)]);\r\n};\r\n\r\n/**\r\n * Gets element at circular index. Returns undefined for empty array.\r\n * Implements modulo arithmetic: negative indices wrap from end, positive from start.\r\n * @param array - Source array\r\n * @param index - Target index (wraps circularly)\r\n * @returns Element at circular index or undefined if array empty\r\n */\r\nexport const circularAt = <T>(array: T[], index: number): T | undefined => {\r\n if (!array.length) return undefined;\r\n const len = array.length;\r\n return array[((index % len) + len) % len];\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/zip.ts\r\n// ========================================\r\n\r\n/**\r\n * Creates an array of grouped elements, where each element contains one element from each input array.\r\n * The length of the result equals the length of the longest input array.\r\n * Missing elements from shorter arrays are filled with `undefined`.\r\n *\r\n * @template T - Tuple type representing element types of each array\r\n * @param arrays - Arrays to zip together\r\n * @returns Array of tuples containing elements from each input array\r\n *\r\n * @example\r\n * zip([1, 2], ['a', 'b']); // returns [[1, 'a'], [2, 'b']]\r\n * zip([1], ['a', 'b']); // returns [[1, 'a'], [undefined, 'b']]\r\n */\r\nexport const zip = <T extends unknown[]>(\r\n ...arrays: {[K in keyof T]: T[K][]}\r\n): T[] => {\r\n const array_count = arrays.length;\r\n if (array_count === 0) return [];\r\n\r\n const max_length = Math.max(...arrays.map((arr) => arr.length));\r\n const result: T[] = [];\r\n\r\n for (let i = 0; i < max_length; i++) {\r\n const group = [] as unknown as T;\r\n for (let j = 0; j < array_count; j++) {\r\n group[j] = arrays[j][i];\r\n }\r\n result.push(group);\r\n }\r\n return result;\r\n};\r\n\r\n/**\r\n * Creates an object with keys from `keys` array and values from `values` array.\r\n * Stops when either array is exhausted (uses minimum length).\r\n *\r\n * @template K - Key type (string | number | symbol)\r\n * @template V - Value type\r\n * @param keys - Array of keys\r\n * @param values - Array of values\r\n * @returns Object with key-value pairs from both arrays\r\n *\r\n * @example\r\n * zipObject(['a', 'b'], [1, 2]); // returns {a: 1, b: 2}\r\n * zipObject(['a', 'b', 'c'], [1]); // returns {a: 1}\r\n */\r\nexport const zipObject = <K extends string | number | symbol, V>(\r\n keys: readonly K[],\r\n values: readonly V[],\r\n): Record<K, V> => {\r\n const result = {} as Record<K, V>;\r\n\r\n const loop_limit = Math.min(keys.length, values.length);\r\n\r\n for (let i = 0; i < loop_limit; i++) {\r\n result[keys[i]] = values[i];\r\n }\r\n return result;\r\n};\r\n\r\n/**\r\n * Creates an array of results by applying `iteratee` to grouped elements from input arrays.\r\n * The length of the result equals the length of the shortest input array.\r\n *\r\n * @template T - Tuple type for iteratee parameters\r\n * @template R - Return type of iteratee\r\n * @param iteratee - Function to apply to grouped elements\r\n * @param arrays - Arrays to zip together\r\n * @returns Array of results from applying iteratee\r\n *\r\n * @example\r\n * zipWith((a, b) => a + b, [1, 2], [10, 20]); // returns [11, 22]\r\n * zipWith((a, b) => a + b, [1], [10, 20]); // returns [11]\r\n */\r\nexport const zipWith = <T extends unknown[], R>(\r\n iteratee: (...args: T) => R,\r\n ...arrays: {[K in keyof T]: T[K][]}\r\n): R[] => {\r\n const array_count = arrays.length;\r\n if (array_count === 0) return [];\r\n\r\n const min_length = Math.min(...arrays.map((arr) => arr.length));\r\n const result: R[] = [];\r\n\r\n for (let i = 0; i < min_length; i++) {\r\n const args = [] as unknown as T;\r\n for (let j = 0; j < array_count; j++) {\r\n args[j] = arrays[j][i];\r\n }\r\n result.push(iteratee(...args));\r\n }\r\n return result;\r\n};\r\n\r\n/**\r\n * Inverse of `zip`: splits array of tuples into separate arrays.\r\n * Returns empty array if input is empty.\r\n *\r\n * @template T - Tuple type\r\n * @param array - Array of tuples to unzip\r\n * @returns Array of arrays where each contains elements from one position\r\n *\r\n * @example\r\n * unzip([[1, 'a'], [2, 'b']]); // returns [[1, 2], ['a', 'b']]\r\n * unzip([]); // returns []\r\n */\r\nexport const unzip = <T extends unknown[]>(\r\n array: readonly T[],\r\n): {[K in keyof T[number]]: T[number][K][]} => {\r\n if (array.length === 0) {\r\n return [] as unknown as {[K in keyof T[number]]: T[number][K][]};\r\n }\r\n return zip(...array) as {[K in keyof T[number]]: T[number][K][]};\r\n};\r\n\r\n/**\r\n * Inverse of `zipWith`: splits array and applies iteratee to resulting groups.\r\n * Returns empty array if input is empty.\r\n *\r\n * @template T - Tuple type for iteratee parameters\r\n * @template R - Return type of iteratee\r\n * @param array - Array of arrays to unzip\r\n * @param iteratee - Function to apply to unzipped groups\r\n * @returns Array of results from applying iteratee\r\n *\r\n * @example\r\n * unzipWith([[1, 10], [2, 20]], (a, b) => a + b); // returns [3, 30]\r\n * unzipWith([], (a, b) => a + b); // returns []\r\n */\r\nexport const unzipWith = <T extends unknown[], R>(\r\n array: readonly (readonly [...unknown[]])[],\r\n iteratee: (...args: T) => R,\r\n): R[] => {\r\n if (!array || array.length === 0) return [];\r\n const unzipped = unzip(array as unknown[][]);\r\n return zipWith(iteratee, ...(unzipped as {[K in keyof T]: T[K][]}));\r\n};\r\n\r\n/**\r\n * Generates sliding windows of elements from an array.\r\n *\r\n * @param arr - The source array. Returns empty array if not an array.\r\n * @param size - Window size (positive integer). Returns empty array if invalid.\r\n * @param step - Step between windows (positive integer). Defaults to 1.\r\n * @param partial_windows - Include incomplete trailing windows. Defaults to false.\r\n * @returns Array of windows. Returns empty array for invalid inputs.\r\n *\r\n * @remarks\r\n * - Returns empty array if `arr` is not an array\r\n * - Returns empty array if `size` or `step` are non-positive or non-integers\r\n * - When `partial_windows` is false (default):\r\n * - Returns empty array if `size > arr.length`\r\n * - Only windows of exact `size` are included\r\n * - Stops before incomplete trailing windows\r\n * - When `partial_windows` is true:\r\n * - Allows windows smaller than `size` at array end\r\n * - Processes until array start is exhausted\r\n */\r\nexport const windowed = <T>(\r\n arr: T[],\r\n size: number,\r\n step: number = 1,\r\n partial_windows: boolean = false,\r\n): T[][] => {\r\n if (\r\n size <= 0 ||\r\n step <= 0 ||\r\n !Number.isInteger(size) ||\r\n !Number.isInteger(step)\r\n ) {\r\n return [];\r\n }\r\n\r\n const result: T[][] = [];\r\n const len = arr.length;\r\n\r\n for (let i = 0; i < len; i += step) {\r\n const chunk = arr.slice(i, i + size);\r\n if (!partial_windows && chunk.length < size) {\r\n break;\r\n }\r\n\r\n result.push(chunk);\r\n }\r\n\r\n return result;\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/filtering.ts\r\n// ========================================\r\n\r\n/**\r\n * Filters out falsy values: false, null, undefined, '', 0. Returns new array.\r\n * Preserves truthy values including objects, arrays, and other non-falsy primitives.\r\n * @param array - Source array\r\n * @returns New array without falsy values\r\n */\r\nexport const compact = <T>(\r\n array: T[],\r\n): Array<Exclude<T, false | null | undefined | '' | 0>> => {\r\n return array.filter(\r\n (val): val is Exclude<T, false | null | undefined | '' | 0> => Boolean(val),\r\n );\r\n};\r\n\r\n/**\r\n * Filters out null and undefined values. Returns new array.\r\n * Preserves all other values including falsy values like 0, false, ''.\r\n * @param array - Source array\r\n * @returns New array without null/undefined\r\n */\r\nexport const nonNullable = <T>(array: T[]): Array<NonNullable<T>> => {\r\n return array.filter(\r\n (val): val is NonNullable<T> => val !== null && val !== undefined,\r\n );\r\n};\r\n\r\n/**\r\n * Returns new array without specified values. Uses Set for O(1) lookups.\r\n * Preserves original order and empty slots. Original array unchanged.\r\n * @param arr - Source array\r\n * @param values - Values to exclude\r\n * @returns New filtered array\r\n */\r\nexport const without = <T>(arr: T[], ...values: T[]) => {\r\n const cache = new Set(values);\r\n return arr.filter((item) => !cache.has(item));\r\n};\r\n\r\n/**\r\n * Removes all specified values in-place. Returns mutated original array.\r\n * Uses two-pointer algorithm, O(n) time, O(k) space for value Set.\r\n * Preserves order of remaining elements.\r\n * @param arr - Array to modify (mutated)\r\n * @param values - Values to remove\r\n * @returns Mutated original array\r\n */\r\nexport const pull = <T>(arr: T[], ...values: T[]): T[] => {\r\n const cache = new Set(values);\r\n let write_idx = 0;\r\n for (let read_idx = 0; read_idx < arr.length; read_idx++) {\r\n if (!cache.has(arr[read_idx])) {\r\n arr[write_idx] = arr[read_idx];\r\n write_idx++;\r\n }\r\n }\r\n arr.length = write_idx;\r\n return arr;\r\n};\r\n\r\n/**\r\n * Removes elements at specified indices in-place. Returns array of removed elements.\r\n * Invalid indices and duplicates are ignored. Preserves order in both removed and remaining elements.\r\n * Returns empty array if source array empty or no valid indices provided.\r\n * @param arr - Array to modify (mutated)\r\n * @param indexes - Indices to remove (negative indices not supported)\r\n * @returns Array of removed elements\r\n */\r\nexport const pullAt = <T>(arr: T[], indexes: number[]): T[] => {\r\n if (!arr.length || !indexes.length) return [];\r\n const unique_indexes = new Set<number>();\r\n\r\n const valid_indexes: number[] = [];\r\n for (const i of indexes) {\r\n if (i >= 0 && i < arr.length && !unique_indexes.has(i)) {\r\n unique_indexes.add(i);\r\n valid_indexes.push(i);\r\n }\r\n }\r\n\r\n if (!valid_indexes.length) return [];\r\n const result = valid_indexes.map((i) => arr[i]);\r\n\r\n const delete_set = new Set(valid_indexes);\r\n let write_idx = 0;\r\n\r\n for (let read_idx = 0; read_idx < arr.length; read_idx++)\r\n if (!delete_set.has(read_idx)) arr[write_idx++] = arr[read_idx];\r\n\r\n arr.length = write_idx;\r\n return result;\r\n};\r\n\r\n/**\r\n * Special symbol used in `remove` function to indicate sparse array holes should be preserved.\r\n * Return this symbol from the `on_hole` callback to keep the hole in the resulting array.\r\n */\r\nexport const KEEP_HOLE = Symbol('Keep hole');\r\n\r\n/**\r\n * Removes elements matching predicate in-place. Returns array of removed elements.\r\n * Handles sparse arrays: on_hole callback determines hole behavior (keep, fill, or skip).\r\n * KEEP_HOLE symbol preserves holes, undefined skips, any other value fills the position.\r\n * @param array - Array to modify (mutated)\r\n * @param predicate - Removal condition function\r\n * @param on_hole - Callback for sparse positions (optional)\r\n * @returns Array of removed elements\r\n */\r\nexport const remove = <T, R = T>(\r\n array: T[],\r\n predicate: (val: T, index: number) => boolean,\r\n on_hole?: (index: number) => R | typeof KEEP_HOLE | undefined,\r\n): T[] => {\r\n const removed: T[] = [];\r\n let slow = 0;\r\n\r\n for (let fast = 0; fast < array.length; fast++) {\r\n if (!(fast in array)) {\r\n const action = on_hole ? on_hole(fast) : KEEP_HOLE;\r\n\r\n if (action === KEEP_HOLE) {\r\n // eslint-disable-next-line @typescript-eslint/no-array-delete\r\n delete array[slow++];\r\n } else if (action !== undefined) {\r\n (array as (T | R)[])[slow++] = action;\r\n }\r\n continue;\r\n }\r\n\r\n const element = array[fast];\r\n if (predicate(element, fast)) {\r\n removed.push(element);\r\n } else {\r\n if (slow !== fast) array[slow] = element;\r\n slow++;\r\n }\r\n }\r\n\r\n array.length = slow;\r\n return removed;\r\n};\r\n\r\n/**\r\n * Creates a duplicate-free version of an array using strict equality (`===`) for comparisons.\r\n * Preserves the first occurrence of each value. Maintains the relative order of first occurrences.\r\n * @template T - Array element type\r\n * @param array - The array to inspect\r\n * @returns Returns the new duplicate-free array\r\n * @example\r\n * ```ts\r\n * uniq([2, 1, 2, 3]) // => [2, 1, 3]\r\n * ```\r\n */\r\nexport const uniq = <T>(array: T[]): T[] => {\r\n return [...new Set(array)];\r\n};\r\n\r\n/**\r\n * Creates a duplicate-free array by computing a transformation for each element.\r\n * Uniqueness is determined by the result of `iteratee`. Preserves the first occurrence where the computed value appears. Maintains relative order.\r\n * @template T - Array element type\r\n * @param array - The array to inspect\r\n * @param iteratee - The function to transform elements\r\n * @returns Returns the new duplicate-free array\r\n * @example\r\n * ```ts\r\n * uniqBy([{x:1}, {x:2}, {x:1}], o => o.x) // => [{x:1}, {x:2}]\r\n * ```\r\n */\r\nexport const uniqBy = <T>(array: T[], iteratee: (value: T) => unknown): T[] => {\r\n const seen = new Set();\r\n return array.filter((item) => {\r\n const computed = iteratee(item);\r\n if (seen.has(computed)) {\r\n return false;\r\n }\r\n seen.add(computed);\r\n return true;\r\n });\r\n};\r\n\r\n/**\r\n * Creates a duplicate-free array using a custom comparator function.\r\n * Uniqueness is determined by the `comparator` returning `true` for any pair. Preserves the first occurrence. Performs O(n²) comparisons in worst case. Maintains relative order.\r\n * @template T - Array element type\r\n * @param array - The array to inspect\r\n * @param comparator - The function to compare elements (should return `true` for equality)\r\n * @returns Returns the new duplicate-free array\r\n */\r\nexport const uniqWith = <T>(\r\n array: T[],\r\n comparator: (a: T, b: T) => boolean,\r\n): T[] => {\r\n const result: T[] = [];\r\n\r\n for (const item of array) {\r\n const is_duplicate = result.some((existing) => comparator(existing, item));\r\n if (!is_duplicate) {\r\n result.push(item);\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/iteration.ts\r\n// ========================================\r\n\r\nimport type {MaybePromise} from '../type-tool';\r\n\r\n/**\r\n * Iterates over array elements from right to left (last to first).\r\n * Executes the iteratee function for each element.\r\n *\r\n * @param array - The array to iterate over\r\n * @param iteratee - Function invoked per iteration with (value, index, collection)\r\n * @returns void\r\n *\r\n * @remarks\r\n * - For empty arrays, no iterations occur\r\n * - Iteration order is reversed: array[length-1] to array[0]\r\n * - Original array modifications during iteration affect the iteration\r\n */\r\nexport const forEachRight = <T>(\r\n array: T[],\r\n iteratee: (value: T, index: number, collection: T[]) => void,\r\n): void => {\r\n for (let i = array.length - 1; i >= 0; i--) {\r\n iteratee(array[i], i, array);\r\n }\r\n};\r\n\r\n/**\r\n * Asynchronously iterates over array elements with controlled concurrency.\r\n * Executes callbacks concurrently up to the concurrency limit.\r\n *\r\n * @param array - The array to iterate over\r\n * @param callback - Async function invoked per element with (value, index, array)\r\n * @param concurrency - Maximum number of concurrent executions (default: Infinity)\r\n * @returns Promise that resolves when all callbacks complete\r\n *\r\n * @remarks\r\n * - Empty arrays resolve immediately\r\n * - Concurrency values < 1 behave as concurrency=Infinity\r\n * - If concurrency >= array.length, uses Promise.all for optimization\r\n * - Callback exceptions cause immediate rejection; pending callbacks continue\r\n * - Execution order starts from index 0, but completion order varies\r\n */\r\nexport const forEachAsync = async <T>(\r\n array: T[],\r\n callback: (value: T, index: number, array: T[]) => Promise<void>,\r\n concurrency: number = Infinity,\r\n): Promise<void> => {\r\n if (array.length === 0) return;\r\n\r\n if (concurrency >= array.length) {\r\n await Promise.all(array.map((item, index) => callback(item, index, array)));\r\n return;\r\n }\r\n const executing: Promise<void>[] = [];\r\n const pool = new Set<Promise<void>>();\r\n\r\n for (let i = 0; i < array.length; i++) {\r\n const task = callback(array[i], i, array).then(() => {\r\n pool.delete(task);\r\n });\r\n\r\n pool.add(task);\r\n executing.push(task);\r\n if (pool.size >= concurrency) {\r\n await Promise.race(pool);\r\n }\r\n }\r\n\r\n await Promise.all(executing);\r\n};\r\n\r\n/**\r\n * Asynchronously maps array elements with controlled concurrency.\r\n * Returns new array with mapped values in original indices.\r\n *\r\n * @template T - Input array element type\r\n * @template U - Output array element type\r\n * @param array - Source array to map\r\n * @param callback - Async mapping function with (value, index, array)\r\n * @param concurrency - Maximum concurrent executions (default: Infinity)\r\n * @returns Promise resolving to new array of mapped values\r\n *\r\n * @remarks\r\n * - Empty arrays resolve to empty array\r\n * - Concurrency behavior matches forEachAsync\r\n * - Output array length equals input array length\r\n * - Original indices are preserved regardless of execution timing\r\n * - Any rejection immediately rejects the entire operation\r\n */\r\nexport const mapAsync = async <T, U>(\r\n array: T[],\r\n callback: (value: T, index: number, array: T[]) => MaybePromise<U>,\r\n concurrency: number = Infinity,\r\n): Promise<U[]> => {\r\n const result_array = new Array<U>(array.length);\r\n\r\n await forEachAsync(\r\n array,\r\n async (item, index, arr) => {\r\n result_array[index] = await callback(item, index, arr);\r\n },\r\n concurrency,\r\n );\r\n\r\n return result_array;\r\n};\r\n\r\n/**\r\n * Asynchronously filters array elements with controlled concurrency.\r\n * Returns new array containing elements where predicate returns truthy.\r\n *\r\n * @param array - Array to filter\r\n * @param predicate - Async function returning truthy/falsy with (value, index, array)\r\n * @param concurrency - Maximum concurrent executions (default: Infinity)\r\n * @returns Promise resolving to filtered array\r\n *\r\n * @remarks\r\n * - Empty arrays resolve to empty array\r\n * - Concurrency behavior matches mapAsync\r\n * - Output array order preserves original relative order\r\n * - Predicate is called for every element (no short-circuiting)\r\n * - All predicates execute before filtering occurs\r\n */\r\nexport const filterAsync = async <T>(\r\n array: T[],\r\n predicate: (value: T, index: number, array: T[]) => MaybePromise<boolean>,\r\n concurrency: number = Infinity,\r\n): Promise<T[]> => {\r\n const bool_results = await mapAsync(array, predicate, concurrency);\r\n return array.filter((_, index) => bool_results[index]);\r\n};\r\n\r\n/**\r\n * Asynchronously reduces array to single value using callback.\r\n * Executes callbacks sequentially from left to right.\r\n *\r\n * @template T - Array element type\r\n * @template U - Accumulator type\r\n * @param array - Array to reduce\r\n * @param callback - Async reducer with (accumulator, value, index, array)\r\n * @param initial_value - Initial accumulator value\r\n * @returns Promise resolving to final accumulator value\r\n *\r\n * @remarks\r\n * - Empty arrays with initial_value return initial_value\r\n * - Execution is strictly sequential (no concurrency)\r\n * - Reduction order: array[0] to array[length-1]\r\n * - Callback awaited before processing next element\r\n */\r\nexport const reduceAsync = async <T, U>(\r\n array: T[],\r\n callback: (\r\n accumulator: U,\r\n value: T,\r\n index: number,\r\n array: T[],\r\n ) => MaybePromise<U>,\r\n initial_value: U,\r\n): Promise<U> => {\r\n let accumulator = initial_value;\r\n for (let i = 0; i < array.length; i++) {\r\n accumulator = await callback(accumulator, array[i], i, array);\r\n }\r\n return accumulator;\r\n};\r\n","// ========================================\r\n// ./src/Utils/Array/sorting.ts\r\n// ========================================\r\n\r\n/**\r\n * Extracts a comparable value from an item for sorting\r\n * @template T - The type of items being sorted\r\n */\r\nexport type Iteratee<T> = (item: T) => string | number | boolean | Date;\r\n\r\n/**\r\n * Sort order direction\r\n */\r\nexport type Order = 'asc' | 'desc';\r\n\r\n/**\r\n * Core sorting function with full configuration\r\n * @template T - Array element type\r\n * @param array - Source array to sort\r\n * @param iteratees - Functions to extract sort values\r\n * @param orders - Sort directions for each iteratee\r\n * @param inplace - Modify original array if true\r\n * @returns Sorted array (original if inplace)\r\n */\r\nexport const coreSort = <T>(\r\n array: T[],\r\n iteratees: Array<Iteratee<T>>,\r\n orders: Array<Order>,\r\n inplace: boolean,\r\n): T[] => {\r\n const target = inplace ? array : [...array];\r\n return target.sort((a, b) => {\r\n for (let i = 0; i < iteratees.length; i++) {\r\n const valA = iteratees[i](a);\r\n const valB = iteratees[i](b);\r\n if (valA === valB) continue;\r\n\r\n const dir = orders[i] ?? 'asc';\r\n const compA = valA instanceof Date ? valA.getTime() : valA;\r\n const compB = valB instanceof Date ? valB.getTime() : valB;\r\n\r\n if (typeof compA !== typeof compB) {\r\n // 如果类型不同,按类型的字符串名称排序\r\n const typeOrder = typeof compA > typeof compB ? 1 : -1;\r\n return dir === 'asc' ? typeOrder : -typeOrder;\r\n }\r\n\r\n if (compA > compB) {\r\n return dir === 'asc' ? 1 : -1;\r\n } else {\r\n return dir === 'asc' ? -1 : 1;\r\n }\r\n }\r\n return 0;\r\n });\r\n};\r\n\r\n/**\r\n * Returns a new sorted array by multiple criteria\r\n * @template T - Array element type\r\n * @param array - Source array\r\n * @param iteratees - Value extraction functions\r\n * @param orders - Sort directions\r\n * @returns New sorted array\r\n */\r\nexport const orderBy = <T>(\r\n array: T[],\r\n iteratees: Array<Iteratee<T>>,\r\n orders: Array<Order>,\r\n): T[] => coreSort(array, iteratees, orders, false);\r\n\r\n/**\r\n * Sorts array in-place by multiple criteria\r\n * @template T - Array element type\r\n * @param array - Array to sort (modified)\r\n * @param iteratees - Value extraction functions\r\n * @param orders - Sort directions\r\n * @returns Original sorted array\r\n */\r\nexport const orderByInplace = <T>(\r\n array: T[],\r\n iteratees: Array<Iteratee<T>>,\r\n orders: Array<Order>,\r\n): T[] => coreSort(array, iteratees, orders, true);\r\n\r\n/**\r\n * Returns new array sorted by single criterion\r\n * @template T - Array element type\r\n * @param array - Source array\r\n * @param iteratee - Value extraction function\r\n * @param order - Sort direction (defaults to 'asc')\r\n * @returns New sorted array\r\n */\r\nexport const sortBy = <T>(\r\n array: T[],\r\n iteratee: Iteratee<T>,\r\n order: Order = 'asc',\r\n): T[] => coreSort(array, [iteratee], [order], false);\r\n\r\n/**\r\n * Sorts array in-place by single criterion\r\n * @template T - Array element type\r\n * @param array - Array to sort (modified)\r\n * @param iteratee - Value extraction function\r\n * @param order - Sort direction (defaults to 'asc')\r\n * @returns Original sorted array\r\n */\r\nexport const sortByInplace = <T>(\r\n array: T[],\r\n iteratee: Iteratee<T>,\r\n order: Order = 'asc',\r\n): T[] => coreSort(array, [iteratee], [order], true);\r\n","// ========================================\r\n// ./src/Utils/Array/randomization.ts\r\n// ========================================\r\n\r\n/**\r\n * Returns a new array with elements randomly shuffled using Fisher-Yates algorithm\r\n * @template T - Array element type\r\n * @param {T[]} array - Input array to shuffle (will not be modified)\r\n * @returns {T[]} New shuffled array. Empty array returns empty array.\r\n */\r\nexport const shuffle = <T>(array: T[]): T[] => {\r\n const result_array = [...array];\r\n for (let i = result_array.length - 1; i > 0; i--) {\r\n const j = Math.floor(Math.random() * (i + 1));\r\n [result_array[i], result_array[j]] = [result_array[j], result_array[i]];\r\n }\r\n return result_array;\r\n};\r\n\r\n/**\r\n * Xorshift32 Pseudo-random number generator\r\n * A small, fast PRNG that provides deterministic sequences based on a seed.\r\n */\r\nexport class Xorshift32 {\r\n private seed_state: number;\r\n\r\n /**\r\n * @param {number} seed - Initial seed (must be a non-zero 32-bit integer)\r\n */\r\n constructor(seed: number) {\r\n // 种子不能为0,否则算法会卡死在0输出\r\n this.seed_state = seed === 0 ? 1 : seed >>> 0;\r\n }\r\n\r\n /**\r\n * Generates the next raw 32-bit unsigned integer\r\n * @returns {number} 32-bit unsigned integer\r\n */\r\n nextUint32(): number {\r\n let x = this.seed_state;\r\n x ^= x << 13;\r\n x ^= x >>> 17;\r\n x ^= x << 5;\r\n this.seed_state = x >>> 0; // 确保保持为无符号32位\r\n return this.seed_state;\r\n }\r\n\r\n /**\r\n * Returns a random float between [0, 1)\r\n * @returns {number}\r\n */\r\n nextFloat(): number {\r\n return this.nextUint32() / 4294967296;\r\n }\r\n}\r\n\r\n/**\r\n * Shuffles array in-place using Fisher-Yates algorithm\r\n * @template T - Array element type\r\n * @param {T[]} array - Array to shuffle (will be modified)\r\n * @returns {T[]} The same array reference, now shuffled. Empty array returns same empty array.\r\n */\r\nexport const shuffleInplace = <T>(array: T[]): T[] => {\r\n for (let i = array.length - 1; i > 0; i--) {\r\n const j = Math.floor(Math.random() * (i + 1));\r\n [array[i], array[j]] = [array[j], array[i]];\r\n }\r\n return array;\r\n};\r\n\r\n/**\r\n * Returns a random element from array\r\n * @template T - Array element type\r\n * @param {T[]} collection - Input array\r\n * @returns {T | undefined} Random element, or undefined if array is empty\r\n */\r\nexport const sample = <T>(collection: T[]): T | undefined => {\r\n if (collection.length === 0) return undefined;\r\n const random_index = Math.floor(Math.random() * collection.length);\r\n return collection[random_index];\r\n};\r\n\r\n/**\r\n * Returns n random unique elements from array\r\n * @template T - Array element type\r\n * @param {T[]} collection - Input array (will not be modified)\r\n * @param {number} n - Number of elements to sample\r\n * @returns {T[]} Array of n random unique elements. Returns empty array if:\r\n * - Input array is empty\r\n * - n ≤ 0\r\n * - n > collection.length: returns shuffled copy of entire array\r\n */\r\nexport const sampleSize = <T>(collection: T[], n: number): T[] => {\r\n const actual_n = Math.max(0, Math.min(n, collection.length));\r\n if (actual_n === 0) return [];\r\n return shuffle(collection).slice(0, actual_n);\r\n};\r\n\r\n/**\r\n * Returns n random elements with replacement (duplicates possible)\r\n * @template T - Array element type\r\n * @param {T[]} collection - Input array\r\n * @param {number} n - Number of elements to pick\r\n * @returns {T[]} Array of n random elements. Returns empty array if:\r\n * - Input array is empty\r\n * - n ≤ 0\r\n */\r\nexport const choices = <T>(collection: T[], n: number): T[] => {\r\n if (collection.length === 0 || n <= 0) return [];\r\n const result_list: T[] = [];\r\n for (let i = 0; i < n; i++) result_list.push(sample(collection) as T);\r\n return result_list;\r\n};\r\n\r\n/**\r\n * Returns n random elements based on weights\r\n * @template T - Array element type\r\n * @param {T[]} collection - Input array\r\n * @param {number[]} weights - Corresponding weights for each element\r\n * @param {number} n - Number of elements to pick\r\n * @returns {T[]} Array of n random weighted elements. Returns empty array if:\r\n * - Input array is empty\r\n * - Weights array length doesn't match collection length\r\n * - n ≤ 0\r\n * @throws No explicit error, but will return empty array for invalid inputs\r\n */\r\nexport const weightedChoices = <T>(\r\n collection: T[],\r\n weights: number[],\r\n n: number,\r\n): T[] => {\r\n if (\r\n collection.length === 0 ||\r\n collection.length !== weights.length ||\r\n n <= 0\r\n ) {\r\n return [];\r\n }\r\n\r\n const cumulative_weights: number[] = [];\r\n let total_weight = 0;\r\n for (const w of weights) {\r\n total_weight += w;\r\n cumulative_weights.push(total_weight);\r\n }\r\n\r\n const result: T[] = [];\r\n for (let i = 0; i < n; i++) {\r\n const target = Math.random() * total_weight;\r\n let low = 0;\r\n let high = cumulative_weights.length - 1;\r\n let index = high;\r\n\r\n while (low <= high) {\r\n const mid = Math.floor((low + high) / 2);\r\n if (cumulative_weights[mid] >= target) {\r\n index = mid;\r\n high = mid - 1;\r\n } else {\r\n low = mid + 1;\r\n }\r\n }\r\n result.push(collection[index]);\r\n }\r\n\r\n return result;\r\n};\r\n"],"names":["flattenDeep","array","result","stack","frame","current","currentIndex","element","flatMapDeep","callback","mapped","i","value","flatMapAsync","concurrency","existingIndices","total","safeConcurrency","results","cursor","worker","pos","origIdx","workers","final","res","groupBy","list","keyGetter","acc","item","rawKey","key","keyBy","partition","predicate","chunk","size","chunk_size","array_length","countBy","iteratee","mapInPlace","transform","start","end","len","relative_start","relative_end","mapToNewArray","shortest","arrays","min_len","arr","move","from","to","maxBy","max_score","current_item","current_score","minBy","min_score","difference","values","restSet","differenceBy","differenceWith","comparator","a","b","intersection","otherSets","set","intersectionBy","array1","array2","set2","intersectionWith","union","unionBy","map","unionWith","r","xor","xorBy","xorWith","isSubset","subset","superset","superSetObj","isSubsetWith","subItem","superItem","head","last","initial","tail","take","n","takeRight","drop","dropRight","takeWhile","index","takeRightWhile","dropWhile","dropRightWhile","collectAt","indices","circular","getIdx","idx","circularAt","zip","array_count","max_length","group","j","zipObject","keys","loop_limit","zipWith","min_length","args","unzip","unzipWith","unzipped","windowed","step","partial_windows","compact","val","nonNullable","without","cache","pull","write_idx","read_idx","pullAt","indexes","unique_indexes","valid_indexes","delete_set","KEEP_HOLE","remove","on_hole","removed","slow","fast","action","uniq","uniqBy","seen","computed","uniqWith","existing","forEachRight","forEachAsync","executing","pool","task","mapAsync","result_array","filterAsync","bool_results","_","reduceAsync","initial_value","accumulator","coreSort","iteratees","orders","inplace","valA","valB","dir","compA","compB","typeOrder","orderBy","orderByInplace","sortBy","order","sortByInplace","shuffle","Xorshift32","seed","x","shuffleInplace","sample","collection","random_index","sampleSize","actual_n","choices","result_list","weightedChoices","weights","cumulative_weights","total_weight","w","target","low","high","mid"],"mappings":"AAwBO,MAAMA,IAAc,CAAIC,MAA0C;AACvE,QAAMC,IAA2B,CAAA,GAC3BC,IAA+D;AAAA,IACnE,EAAC,OAAAF,GAAO,WAAW,EAAA;AAAA,EAAC;AAGtB,SAAOE,EAAM,SAAS,KAAG;AACvB,UAAMC,IAAQD,EAAMA,EAAM,SAAS,CAAC,GAC9B,EAAC,OAAOE,EAAA,IAAWD;AAEzB,QAAIA,EAAM,aAAaC,EAAQ,QAAQ;AACrC,MAAAF,EAAM,IAAA;AACN;AAAA,IACF;AAEA,UAAMG,IAAeF,EAAM;AAE3B,QAAI,EAAEE,KAAgBD;AACpB;AAGF,UAAME,IAAUF,EAAQC,CAAY;AAEpC,IAAI,MAAM,QAAQC,CAAO,IACvBJ,EAAM,KAAK,EAAC,OAAOI,GAAS,WAAW,GAAE,IAEzCL,EAAO,KAAKK,CAAyB;AAAA,EAEzC;AAEA,SAAOL;AACT,GAYaM,IAAc,CACzBP,GACAQ,MACqB;AACrB,QAAMC,IAA2B,CAAA;AAEjC,WAASC,IAAI,GAAGA,IAAIV,EAAM,QAAQU;AAChC,QAAIA,KAAKV,GAAO;AACd,YAAMW,IAAQH,EAASR,EAAMU,CAAC,GAAGA,CAAC;AAClC,MAAI,MAAM,QAAQC,CAAK,IAErBF,EAAO,KAAK,GAAGV,EAAYY,CAAK,CAAC,IAEjCF,EAAO,KAAKE,CAAuB;AAAA,IAEvC;AAGF,SAAOF;AACT,GAeaG,IAAe,OAC1B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,KAC7BlG,IAAQqG,GACRD,IAAOC,IAAM,KAEbF,IAAME,IAAM;AAAA,IAEhB;AACA,IAAA3M,EAAO,KAAK6L,EAAWvF,CAAK,CAAC;AAAA,EAC/B;AAEA,SAAOtG;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,15 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("../chunks/Errors-BWEYu-AB.cjs"),u=require("../chunks/helper-tsqZMRHW.cjs"),re=require("../chunks/Math-CWZVxSF-.cjs"),H=require("../chunks/base-r6kn0B0D.cjs"),q=require("../chunks/delay-CG3cD7bk.cjs");class D{static MIN_QUEUE_SIZE_FOR_COMPACTION=64;static WASTE_RATIO_THRESHOLD=.65;concurrency_limit;active_count=0;pending_count=0;queue=[];queue_head=0;is_paused=!1;idle_resolvers=[];constructor(e){if(!Number.isInteger(e)&&e!==1/0||e<0||Number.isNaN(e))throw new l.ParameterError("Concurrency must be a non-negative integer");this.concurrency_limit=e}getConcurrency(){return this.concurrency_limit}get stats(){return{concurrency:this.concurrency_limit,active:this.active_count,pending:this.pending_count,isPaused:this.is_paused}}shouldCompact(){if(this.queue_head<D.MIN_QUEUE_SIZE_FOR_COMPACTION)return!1;const e=this.queue_head/Math.max(1,this.queue.length);return this.queue_head>D.MIN_QUEUE_SIZE_FOR_COMPACTION&&e>D.WASTE_RATIO_THRESHOLD}compactQueue(){let e=0;for(let t=this.queue_head;t<this.queue.length;t++){const i=this.queue[t];i!==null&&(this.queue[e]=i,i.queue_index=e,e++)}this.queue.length=e,this.queue_head=0}removeItemFromQueue(e){this.queue[e.queue_index]=null,this.pending_count--}cleanupItem(e){e.queue_index=-1,e.signal=void 0,e.task=null,e.resolve=null,e.reject=null}tryStartNext(){if(!this.is_paused)for(;this.active_count<this.concurrency_limit;){let e=null;for(;this.queue_head<this.queue.length;)if(e=this.queue[this.queue_head],this.queue[this.queue_head]=null,this.queue_head++,e!==null){this.pending_count--;break}if(e===null){this.queue.length>1024?this.queue=[]:this.queue.length=0,this.queue_head=0;break}this.active_count++,e.is_wait?(e.resolve(void 0),this.cleanupItem(e)):this.executeTask(e),this.shouldCompact()&&this.compactQueue()}}executeTask(e){e.signal?.removeEventListener("abort",e.on_abort),(async()=>{try{const i=e.task,s=await i();e.resolve(s)}catch(i){e.reject(i)}finally{this.cleanupItem(e),this.active_count--,this.tryStartNext(),this.checkIdle()}})()}checkIdle(){if(this.active_count===0&&this.stats.pending===0){const e=this.idle_resolvers;this.idle_resolvers=[];for(const t of e)t()}}add(e,t){return t?.aborted?Promise.reject(u.ensureDOMException(t.reason)):new Promise((i,s)=>{const r=this.queue,n=()=>{this.removeItemFromQueue(o),t.removeEventListener("abort",n),s(u.ensureDOMException(t.reason))},o={resolve:a=>{t?.removeEventListener("abort",n),i(a)},reject:a=>{t?.removeEventListener("abort",n),s(a)},signal:t,task:e,queue_index:r.length,is_wait:!1,on_abort:n};t&&t.addEventListener("abort",n,{once:!0}),r.push(o),this.pending_count++,this.tryStartNext()})}async wait(e){if(e?.aborted)throw u.ensureDOMException(e.reason);return new Promise((t,i)=>{const s=this.queue,r=()=>{this.removeItemFromQueue(n),e.removeEventListener("abort",r),i(u.ensureDOMException(e.reason))},n={resolve:()=>{e?.removeEventListener("abort",r),t(a)},reject:h=>{e?.removeEventListener("abort",r),i(h)},signal:e,task:null,queue_index:s.length,is_wait:!0,on_abort:r};let o=!1;const a=()=>{o||(o=!0,this.active_count--,this.tryStartNext(),this.checkIdle())};e&&e.addEventListener("abort",r,{once:!0}),s.push(n),this.pending_count++,this.tryStartNext()})}resetLimits(e){if(!Number.isInteger(e)&&e!==1/0||e<0||Number.isNaN(e))throw new l.ParameterError("Concurrency must be a non-negative integer");this.concurrency_limit=e,this.tryStartNext()}async onIdle(){if(!(this.active_count===0&&this.stats.pending===0))return new Promise(e=>{this.idle_resolvers.push(e)})}clear(){for(let e=this.queue_head;e<this.queue.length;e++){const t=this.queue[e];t!==null&&(t.reject(new DOMException("The operation was aborted","AbortError")),this.cleanupItem(t))}this.queue.length>1024?this.queue=[]:this.queue.length=0,this.queue_head=0,this.pending_count=0,this.checkIdle()}pause(){this.is_paused=!0}resume(){this.is_paused=!1,this.tryStartNext()}}const ne=.001,I=63,C=64,F=7,N=(1<<25)-1,G=1e5,oe=7,K=1e-6,ae=64,U=new Uint32Array([88761,71755,56483,46273,36291,29154,23254,18705,14949,11916,9548,7620,6100,4904,3906,3121,2501,1991,1586,1277,1024,820,655,526,423,335,272,215,172,137,110,87,70,56,45,36,29,23,18,15]),ue=U[20],ee=new Float64Array(U.length);for(let d=0;d<U.length;d++)ee[d]=ue/U[d];class g{concurrency;active_count=0;is_paused=!1;idle_resolvers=[];heap=[];min_vruntime=0;last_update_time=0;static FRAME_DURATION=1e3/60;static SCHEDULER_YIELD_THRESHOLD=g.FRAME_DURATION/4;last_yield_time=performance.now();v_runtimes=[];flags=[];handles=[];free_slots=[];constructor(e){if(e<0||Number.isNaN(e))throw new l.ParameterError("Scheduler: `concurrency` must be non-negative");this.concurrency=e,this.last_update_time=performance.now(),this.last_yield_time=this.last_update_time}getNiceIndex(e){return Number.isNaN(e)?20:Math.floor(re.clamp(e,-20,19))+20}packFlags(e,t,i){return e<<F|t|(i?C:0)}recordExecution(e,t){const i=this.v_runtimes,r=this.flags[e]&I,n=Math.max(t,ne)*ee[r];i[e]+=n,this.min_vruntime=Math.max(this.min_vruntime,i[e])}applyPriorityUpdate(e,t){if(!t)return;const i=this.v_runtimes,s=this.flags,r=s[e];let n=r&I,o=(r&C)!==0,a=!1;if(t.nice!==void 0&&!Number.isNaN(t.nice)){const h=this.getNiceIndex(t.nice);h!==n&&(n=h,a=!0)}t.guaranteed!==void 0&&t.guaranteed!==o&&(o=t.guaranteed,i[e]+=o?-G:G,a=!0),a&&(s[e]=r&~I&~C|n|(o?C:0))}scheduleExecution(e){performance.now()-this.last_yield_time<g.SCHEDULER_YIELD_THRESHOLD?queueMicrotask(e):u.queueMacroTask(()=>{this.last_yield_time=performance.now(),e()})}resetLimits(e){if(e<0||Number.isNaN(e))throw new l.ParameterError("Scheduler: `new_concurrency` must be non-negative");this.concurrency=e,this.next()}async add(e,t){const{signal:i,nice:s=0,guaranteed:r=!1}=t??{};if(i?.aborted)return Promise.reject(u.ensureDOMException(i.reason));const n=this.getNiceIndex(s);return new Promise((o,a)=>{const h=this.allocSlot();this.advanceTime();const c=n*oe,_=r?-G:0,w=this.v_runtimes,b=this.flags,m=this.handles;w[h]=this.min_vruntime+c+_,b[h]=this.packFlags(N,n,r);const f=()=>{if(m[h]?.resume)return;const p=this.getHeapIndex(h);p!==N?(this.removeFromHeap(p),i?.removeEventListener("abort",f),a(u.ensureDOMException(i.reason)),this.cleanupHandle(h),this.next()):a(u.ensureDOMException(i.reason))};m[h]={fn:e,resolve:p=>{i?.removeEventListener("abort",f),o(p)},reject:p=>{i?.removeEventListener("abort",f),a(p)},signal:i},i?.addEventListener("abort",f,{once:!0}),this.push(h),this.next()})}pause(){this.is_paused=!0}resume(){this.is_paused&&(this.is_paused=!1,this.next())}onIdle(){return this.active_count===0&&this.heap.length===0?Promise.resolve():new Promise(e=>{this.idle_resolvers.push(e)})}get stats(){const e=this.heap[0];return{concurrency:this.concurrency,active:this.active_count,pending:this.heap.length,isPaused:this.is_paused,min_vruntime:this.min_vruntime,next_task_nice:e!==void 0?(this.flags[e]&I)-20:void 0,next_task_vruntime:e!==void 0?this.v_runtimes[e]:void 0}}advanceTime(){if(this.active_count===0&&this.heap.length===0){const i=performance.now();return this.last_update_time=i,this.last_yield_time=i,this.min_vruntime=0,!0}const e=performance.now(),t=e-this.last_update_time;return this.last_update_time=e,this.active_count===0&&t>0&&(this.min_vruntime+=t),!1}next(){if(this.advanceTime()){this.resolveIdle();return}if(!this.is_paused)for(;this.active_count<this.concurrency;){const e=this.heap[0];if(e===void 0)break;this.pop(),this.active_count++;const t=this.handles[e];if(t?.resume){const i=t.resume;t.resume=void 0,this.scheduleExecution(i)}else this.scheduleExecution(()=>void this.runTask(e))}}async runTask(e){const i=this.handles[e];let s=performance.now(),r=s+g.FRAME_DURATION;const n=async a=>{const h=performance.now(),c=h-s;this.recordExecution(e,c),this.applyPriorityUpdate(e,a);const _=this.heap.length>0,w=h-this.last_yield_time,b=!_&&this.concurrency>0;if(b&&w<g.SCHEDULER_YIELD_THRESHOLD){s=performance.now(),r=s+g.FRAME_DURATION;return}if(b){await new Promise((f,p)=>{let v;i.signal&&(v=()=>p(u.ensureDOMException(i.signal?.reason)),i.signal.addEventListener("abort",v,{once:!0})),u.queueMacroTask(()=>{v&&i.signal?.removeEventListener("abort",v),this.last_yield_time=performance.now(),f()})}),s=performance.now(),r=s+g.FRAME_DURATION;return}let m;try{await new Promise((f,p)=>{if(i.resume=f,m=()=>{const v=this.getHeapIndex(e);v!==N&&(this.removeFromHeap(v),this.cleanupHandle(e),this.next()),i.resume=void 0,p(u.ensureDOMException(i.signal?.reason))},i.signal?.aborted)return m();i.signal?.addEventListener("abort",m,{once:!0}),this.push(e),this.active_count--,this.next()})}finally{i.signal?.removeEventListener("abort",m)}s=performance.now(),r=s+g.FRAME_DURATION},o=()=>performance.now()>=r;try{const a=await i.fn(o,n);i.resolve(a)}catch(a){i.reject(a)}finally{this.handles[e]&&(this.recordExecution(e,performance.now()-s),this.active_count--,this.cleanupHandle(e),this.next())}}compareIds(e,t){const i=this.v_runtimes,s=this.flags,r=i[e]-i[t];return r>K?1:r<-K?-1:(s[e]&I)-(s[t]&I)}resolveIdle(){if(this.idle_resolvers.length>0){const e=this.idle_resolvers;this.idle_resolvers=[];for(let t=0;t<e.length;t++)e[t]()}this.handles.length>ae&&(this.handles.length=0,this.v_runtimes.length=0,this.flags.length=0,this.free_slots.length=0)}getHeapIndex(e){return this.flags[e]>>>F}setHeapIndex(e,t){const i=this.flags;i[e]=t<<F|i[e]&(1<<F)-1}allocSlot(){return this.free_slots.length>0?this.free_slots.pop():this.handles.length}cleanupHandle(e){const t=this.handles,i=this.v_runtimes,s=this.flags;t[e]=null,i[e]=0,s[e]=0,this.free_slots.push(e)}pop(){const e=this.heap,t=e[0],i=e.pop();return e.length>0&&(e[0]=i,this.setHeapIndex(i,0),this.bubbleDown(0)),this.setHeapIndex(t,N),t}push(e){const t=this.heap,i=t.length;t.push(e),this.setHeapIndex(e,i),this.bubbleUp(i)}removeFromHeap(e){const t=this.heap,i=t[e],s=t.pop();if(e<t.length){t[e]=s,this.setHeapIndex(s,e);const r=e-1>>1;e>0&&this.compareIds(s,t[r])<0?this.bubbleUp(e):this.bubbleDown(e)}this.setHeapIndex(i,N)}bubbleUp(e){const t=this.heap,i=t[e];for(;e>0;){const s=e-1>>1,r=t[s];if(this.compareIds(r,i)<=0)break;t[e]=r,this.setHeapIndex(r,e),e=s}t[e]=i,this.setHeapIndex(i,e)}bubbleDown(e){const t=this.heap,i=t.length,s=t[e];for(;;){const r=(e<<1)+1,n=r+1;let o=e;if(r<i&&this.compareIds(t[r],s)<0&&(o=r),n<i&&this.compareIds(t[n],t[o])<0&&(o=n),o===e)break;const a=t[o];t[e]=a,this.setHeapIndex(a,e),e=o}t[e]=s,this.setHeapIndex(s,e)}}function te(){let d,e;return{promise:new Promise((i,s)=>{d=i,e=s}),resolve:d,reject:e}}class ie{abort_signal;abortHandler=null;constructor(e){this.abort_signal=e}setupAbortHandler(e){if(this.abort_signal){if(this.abort_signal.aborted){e(u.ensureDOMException(this.abort_signal.reason));return}this.abortHandler=()=>{e(u.ensureDOMException(this.abort_signal.reason))},this.abort_signal.addEventListener("abort",this.abortHandler)}}cleanupAbortHandler(){this.abort_signal&&this.abortHandler&&this.abort_signal.removeEventListener("abort",this.abortHandler),this.abortHandler=null}}class he extends ie{count;deferred=te();promise;constructor(e,t){if(super(t),e<0)throw new l.ParameterError("Barrier: `initial_count` must be a non-negative number.");this.count=e,this.promise=this.deferred.promise,this.setupAbortHandler(this.handleAbort.bind(this)),this.count===0&&this.trigger()}handleAbort(e){this.deferred.reject(e),this.dispose()}resize(e){this.is_disposed||(this.count=Math.max(0,Math.floor(e)),this.count===0&&this.trigger())}discard(e=1){this.resize(this.count=Math.max(0,this.count-e))}arrive(){this.is_disposed||--this.count<=0&&this.trigger()}trigger(){this.deferred.resolve(),this.dispose()}dispose(){this.cleanupAbortHandler(),this.deferred=null}[Symbol.dispose](){this.dispose()}get is_disposed(){return this.deferred===null}get remaining(){return this.count}}class ce extends ie{initial_count;count;is_broken=!1;break_reason=null;current_deferred=null;constructor(e,t){if(super(t),e<1)throw new l.ParameterError("CyclicBarrier: `count` must be at least 1");this.initial_count=e,this.count=this.initial_count,this.initializeGeneration(),this.setupAbortHandler(this.handleAbort.bind(this))}initializeGeneration(){this.count=this.initial_count,this.current_deferred=te()}async wait(){if(this.is_broken)throw this.break_reason;const{promise:e}=this.current_deferred;return--this.count<=0&&this.triggerNextGeneration(),e}triggerNextGeneration(){const{resolve:e}=this.current_deferred;this.cleanupAbortHandler(),this.initializeGeneration(),e(),this.abort_signal&&!this.is_broken&&this.setupAbortHandler(this.handleAbort.bind(this))}handleAbort(e){if(this.is_broken)return;this.is_broken=!0,this.break_reason=e;const t=this.current_deferred;this.current_deferred=null,this.cleanupAbortHandler(),t?.reject(e),t?.promise.catch(H.noop)}get is_disposed(){return this.current_deferred===null}get remaining(){return this.count}get parties(){return this.initial_count}get broken(){return this.is_broken}[Symbol.dispose](){this.handleAbort(new Error("CyclicBarrier disposed"))}}const x=Symbol("Channel closed"),E=Symbol("Channel empty");class T{static COMPACTION_THRESHOLD=64;static MIN_QUEUE_SIZE_FOR_COMPACTION=128;buffer;buffer_head=0;buffer_tail=0;buffer_size=0;_capacity;state=0;senders=[];sender_head=0;receivers=[];receiver_head=0;constructor(e=0){this._capacity=Math.max(0,e),this.buffer=new Array(this._capacity).fill(E)}throwIfDisposed(){if(this.state>=2)throw new l.UseAfterFreeError("Channel has been disposed and cannot be used.")}throwIfClosedOrDisposed(){if(this.state>=1)throw new l.UseAfterFreeError("Channel is closed and cannot accept new sends.")}cleanupSender(e){e.signal=void 0,e.resolve=null,e.reject=null}cleanupReceiver(e){e.signal=void 0,e.resolve=null,e.reject=null}handleSenderAbort(e,t){this.senders[e.index]=null,e.reject(u.ensureDOMException(t?.reason)),this.cleanupSender(e)}handleReceiverAbort(e,t){this.receivers[e.index]=null,e.reject(u.ensureDOMException(t.reason)),this.cleanupReceiver(e)}processReceiver(e,t){return e?(e.resolve({value:t}),this.cleanupReceiver(e),!0):!1}processSender(e){return e?(e.resolve(),this.cleanupSender(e),!0):!1}resize(e,t={}){this.throwIfDisposed(),this.throwIfClosedOrDisposed();const{strategy:i="error",flush_pending:s=!0}=t;if(e=Math.max(0,e),e===this._capacity)return!0;if(e<this.buffer_size){if(i==="error")throw new l.ParameterError(`Cannot resize channel: new capacity (${e}) is smaller than current buffered items (${this.buffer_size}). Use { strategy: 'discard-oldest' | 'discard-newest' } to force resize.`);const n=this.buffer_size-e;if(i==="discard-oldest")for(let o=0;o<n;o++)this.buffer[this.buffer_head]=E,this.buffer_head=(this.buffer_head+1)%this._capacity;if(i==="discard-newest")for(let o=0;o<n;o++)this.buffer_tail=(this.buffer_tail-1+this._capacity)%this._capacity,this.buffer[this.buffer_tail]=E;this.buffer_size=e}const r=new Array(e).fill(E);if(this.buffer_size>0)if(this.buffer_head+this.buffer_size<=this._capacity)for(let n=0;n<this.buffer_size;n++)r[n]=this.buffer[this.buffer_head+n];else{const n=this._capacity-this.buffer_head;for(let a=0;a<n;a++)r[a]=this.buffer[this.buffer_head+a];const o=this.buffer_size-n;for(let a=0;a<o;a++)r[n+a]=this.buffer[a]}return this.buffer=r,this.buffer_head=0,this.buffer_tail=e===0?0:this.buffer_size%e,this._capacity=e,s&&e>0&&this.sender_head<this.senders.length&&this.processPendingSenders(),!0}tryResize(e,t={}){this.throwIfDisposed();try{return this.resize(e,t)}catch{return!1}}async send(e,t){if(this.throwIfDisposed(),this.throwIfClosedOrDisposed(),t?.aborted)throw u.ensureDOMException(t?.reason);for(;this.receiver_head<this.receivers.length;){const i=this.receivers[this.receiver_head];if(this.receivers[this.receiver_head++]=null,this.processReceiver(i,e)){this.compactReceiverQueueIfNeeded();return}}if(this.buffer_size<this._capacity){this.buffer[this.buffer_tail]=e,this.buffer_tail=(this.buffer_tail+1)%this._capacity,this.buffer_size++;return}return new Promise((i,s)=>{const r={resolve:()=>{t?.removeEventListener("abort",n),i(),this.cleanupSender(r)},reject:o=>{t?.removeEventListener("abort",n),s(u.ensureError(o)),this.cleanupSender(r)},value:e,signal:t,index:-1},n=()=>{this.handleSenderAbort(r,t)};t?.addEventListener("abort",n,{once:!0}),r.index=this.senders.length,this.senders.push(r)})}sendSync(e){for(this.throwIfDisposed(),this.throwIfClosedOrDisposed();this.receiver_head<this.receivers.length;){const t=this.receivers[this.receiver_head];if(this.receivers[this.receiver_head++]=null,this.processReceiver(t,e))return this.compactReceiverQueueIfNeeded(),!0}return this._capacity>0&&this.buffer_size<this._capacity?(this.buffer[this.buffer_tail]=e,this.buffer_tail=(this.buffer_tail+1)%this._capacity,this.buffer_size++,!0):!1}trySend(e){return this.state>=1?!1:this.sendSync(e)}async receive(e){if(this.throwIfDisposed(),e?.aborted)throw u.ensureDOMException(e?.reason);const t=this.dequeueBuffer();if(t!==E)return t;if(this.state>=1&&this.buffer_size===0)return x;for(;this.sender_head<this.senders.length;){const i=this.senders[this.sender_head];if(this.senders[this.sender_head++]=null,this.processSender(i))return i.value}return new Promise((i,s)=>{const r={resolve:o=>{e?.removeEventListener("abort",n),i(o.done?x:o.value),this.cleanupReceiver(r)},reject:o=>{e?.removeEventListener("abort",n),s(o),this.cleanupReceiver(r)},index:this.receivers.length,signal:e},n=()=>{this.handleReceiverAbort(r,e)};e?.addEventListener("abort",n,{once:!0}),this.receivers.push(r)})}tryReceive(){this.throwIfDisposed();const e=this.dequeueBuffer();if(e!==E)return e;if(this.state>=1&&this.buffer_size===0)return x;for(;this.sender_head<this.senders.length;){const t=this.senders[this.sender_head];if(this.senders[this.sender_head++]=null,this.processSender(t))return t.value}}drain(){this.throwIfDisposed(),this.throwIfClosedOrDisposed();const e=this.buffer_size;return this.buffer.fill(E),this.buffer_size=this.buffer_head=this.buffer_tail=0,this._capacity>0&&this.sender_head<this.senders.length&&this.processPendingSenders(),e}close(){if(!(this.state>=1)){this.state=1;for(let e=this.sender_head;e<this.senders.length;e++){const t=this.senders[e];t&&(t.reject(new l.UseAfterFreeError("Channel is closed")),this.senders[e]=null)}this.senders.length=0,this.sender_head=0;for(let e=this.receiver_head;e<this.receivers.length;e++){const t=this.receivers[e];t&&(t.resolve({value:void 0,done:!0}),this.receivers[e]=null)}this.receivers.length=0,this.receiver_head=0}}dispose(){this.state>=2||(this.close(),this.state=2,this.buffer.fill(E),this.buffer_size=this.buffer_head=this.buffer_tail=0,this.buffer=[])}dequeueBuffer(){if(this.buffer_size===0)return E;const e=this.buffer[this.buffer_head];return this.buffer[this.buffer_head]=E,this.buffer_head=(this.buffer_head+1)%this._capacity,this.buffer_size--,this._capacity>0&&this.sender_head<this.senders.length&&this.processPendingSenders(),e}processPendingSenders(){for(;this.buffer_size<this._capacity&&this.sender_head<this.senders.length;){const t=this.senders[this.sender_head];this.senders[this.sender_head++]=null,t&&(t.index=-1,this.buffer[this.buffer_tail]=t.value,this.buffer_tail=(this.buffer_tail+1)%this._capacity,this.buffer_size++,queueMicrotask(t.resolve))}const e=this.sender_head;e>T.COMPACTION_THRESHOLD&&this.senders.length>T.MIN_QUEUE_SIZE_FOR_COMPACTION&&(this.compactQueue(this.senders,e),this.sender_head=0)}compactReceiverQueueIfNeeded(){const e=this.receiver_head;e>T.COMPACTION_THRESHOLD&&this.receivers.length>T.MIN_QUEUE_SIZE_FOR_COMPACTION&&(this.compactQueue(this.receivers,e),this.receiver_head=0)}compactQueue(e,t){const i=e.length-t;if(i===0){e.length=0;return}e.copyWithin(0,t,e.length),e.length=i;for(let s=0;s<i;s++){const r=e[s];r&&(r.index=s)}}get stats(){let e=0;for(let i=this.sender_head;i<this.senders.length;i++)this.senders[i]!==null&&e++;let t=0;for(let i=this.receiver_head;i<this.receivers.length;i++)this.receivers[i]!==null&&t++;return{capacity:this._capacity,buffered:this.buffer_size,waiting_senders:e,waiting_receivers:t,closed:this.state>=1,disposed:this.state>=2}}get capacity(){return this._capacity}get isClosed(){return this.state>=1}get isDisposed(){return this.state>=2}get buffered(){return this.buffer_size}async*[Symbol.asyncIterator](){for(;;){const e=await this.receive();if(e===x)return;yield e}}async*receiveBatch(e=1/0,t){let i=[];try{for(;;){if(t?.aborted)throw u.ensureDOMException(t?.reason);const s=await this.receive(t);if(s===x)break;i.push(s),i.length>=e&&(yield i,i=[])}}finally{i.length>0&&(yield i,i=[])}}[Symbol.dispose](){this.dispose()}}async function le(d,e,t){const i=d.length,s=Math.floor(Math.random()*i);for(let a=0;a<i;a++){const h=(s+a)%i,c=d[h];if(c.op==="send"){if(c.channel.trySend(c.value))return c}else{const _=c.channel.tryReceive();if(_!==void 0)return{...c,value:_}}}if(e?.aborted)throw u.ensureDOMException(e.reason);if(t?.default)return t.default(),{op:"default"};const r=new AbortController,n=()=>r.abort();e?.addEventListener("abort",n,{once:!0});const o=d.map(a=>a.op==="send"?a.channel.send(a.value,r.signal).then(()=>a):a.channel.receive(r.signal).then(h=>({...a,value:h})));try{return await Promise.race(o)}finally{e?.removeEventListener("abort",n),r.abort()}}const de=2147483647;class z{tokens;last_refill_time;max_tokens;refill_rate;static getTime=typeof performance<"u"?performance.now.bind(performance):Date.now;constructor(e){const{limit:t,interval:i}=e;if(!Number.isFinite(t)||t<=0||t>Number.MAX_SAFE_INTEGER){const r=t>Number.MAX_SAFE_INTEGER?`must be less than or equal to Number.MAX_SAFE_INTEGER (${Number.MAX_SAFE_INTEGER}) to ensure precision`:"must be a positive finite number";throw new l.ParameterError(`TokenBucket: \`limit\` ${r}, but got ${t}`)}if(!Number.isFinite(i)||i<=0)throw new l.ParameterError(`TokenBucket: \`interval\` must be a positive finite number, but got ${i}`);const s=t/i;if(!Number.isFinite(s)||s>t)throw new l.ParameterError(`TokenBucket: \`interval\` (${i}) is too small, causing \`refill_rate\` (${s}) to exceed \`limit\` (${t}). Use a larger interval value.`);this.max_tokens=t,this.refill_rate=s,this.tokens=t,this.last_refill_time=z.getTime()}resetRate(e){const{limit:t,interval:i}=e;if(!Number.isFinite(t)||t<=0||t>Number.MAX_SAFE_INTEGER){const r=t>Number.MAX_SAFE_INTEGER?`must be less than or equal to Number.MAX_SAFE_INTEGER (${Number.MAX_SAFE_INTEGER}) to ensure precision`:"must be a positive finite number";throw new l.ParameterError(`TokenBucket: \`limit\` ${r}, but got ${t}`)}if(!Number.isFinite(i)||i<=0)throw new l.ParameterError(`TokenBucket: \`interval\` must be a positive finite number, but got ${i}`);const s=t/i;if(!Number.isFinite(s)||s>t)throw new l.ParameterError(`TokenBucket: \`interval\` (${i}) is too small, causing \`refill_rate\` (${s}) to exceed \`limit\` (${t}). Use a larger interval value.`);this.refill(),this.max_tokens=t,this.refill_rate=s,this.tokens>this.max_tokens&&(this.tokens=this.max_tokens)}async wait(e=1,t){if(!Number.isFinite(e)||e<=0)throw new l.ParameterError(`TokenBucket: \`weight\` must be a positive finite number, but got ${e}`);if(e>this.max_tokens)throw new l.ParameterError(`TokenBucket: \`weight\` (${e}) cannot exceed \`max_tokens\` (${this.max_tokens}).`);if(t?.aborted)throw u.ensureDOMException(t.reason);for(this.refill(),this.tokens-=e;this.tokens<0;){const i=-this.tokens,s=Math.ceil(i/this.refill_rate),r=Math.min(s,de),n=await q.delaySafe(r,t);if(n)throw this.tokens+=e,n;this.refill()}}get stats(){return this.refill(),{tokens:this.tokens,max_tokens:this.max_tokens,refill_rate:this.refill_rate,last_refill_time:this.last_refill_time}}refill(){const e=z.getTime(),t=e-this.last_refill_time;if(t<=0){t<0&&(this.last_refill_time=e);return}if(this.tokens>=this.max_tokens){this.last_refill_time=e;return}const i=t*this.refill_rate;this.tokens+=i,this.tokens=Math.min(this.tokens,this.max_tokens),this.last_refill_time=e}}const J=2147483647;class j extends Error{constructor(e){super(e),this.name="LeakyBucketReject",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,j)}}class M{static MIN_QUEUE_SIZE_FOR_COMPACTION=64;static WASTE_RATIO_THRESHOLD=.65;waiting_queue=[];queue_head=0;active_count=0;next_process_time;max_queue_size;interval;timer_id=null;is_disposed=!1;get isDisposed(){return this.is_disposed}constructor(e){const{limit:t,interval:i}=e;this.validateConfig(t,i),this.max_queue_size=t,this.interval=i,this.next_process_time=performance.now()}resetRate(e){if(this.is_disposed)return;const{limit:t,interval:i}=e;this.validateConfig(t,i),this.max_queue_size=t,this.interval=i,this.scheduleNextProcess()}wait(e){return this.is_disposed?Promise.reject(new l.UseAfterFreeError("LeakyBucket has been disposed.")):e?.aborted?Promise.reject(u.ensureDOMException(e.reason)):this.active_count>=this.max_queue_size?Promise.reject(new j(`LeakyBucket: queue is full (${this.max_queue_size}), cannot accept more requests`)):this._enqueue(e)}tryWait(e){return this.is_disposed?Promise.reject(new l.UseAfterFreeError("LeakyBucket has been disposed.")):e?.aborted?Promise.reject(u.ensureDOMException(e.reason)):this.active_count>=this.max_queue_size?!1:this._enqueue(e)}getStats(){return{queue_size:this.active_count,queue_capacity:this.waiting_queue.length,max_queue_size:this.max_queue_size,interval:this.interval,next_process_time:this.next_process_time,isDisposed:this.is_disposed}}dispose(){if(!this.is_disposed){this.is_disposed=!0,this.timer_id!==null&&(clearTimeout(this.timer_id),this.timer_id=null);for(let e=this.queue_head;e<this.waiting_queue.length;e++){const t=this.waiting_queue[e];t!==null&&(t.reject(new DOMException("LeakyBucket disposed","AbortError")),this.cleanupTask(t))}this.waiting_queue=[],this.queue_head=0,this.active_count=0}}[Symbol.dispose](){this.dispose()}validateConfig(e,t){if(!Number.isFinite(e)||e<=0||e>Number.MAX_SAFE_INTEGER||!Number.isInteger(e)){const i=e>Number.MAX_SAFE_INTEGER?"must be less than or equal to Number.MAX_SAFE_INTEGER":"must be a positive finite number";throw new l.ParameterError(`LeakyBucket: \`limit\` ${i}, but got ${e}`)}if(!Number.isFinite(t)||t<=0)throw new l.ParameterError(`LeakyBucket: \`interval\` must be a positive finite number, but got ${t}`);if(t>J)throw new l.ParameterError(`LeakyBucket: \`interval\` exceeds the maximum safe timer delay (${J}ms).`)}_enqueue(e){return new Promise((t,i)=>{const s=this.waiting_queue,r=()=>{this.removeTaskFromQueue(n),e.removeEventListener("abort",r),i(u.ensureDOMException(e.reason))},n={resolve:()=>{e?.removeEventListener("abort",r),t(),this.cleanupTask(n)},reject:o=>{e?.removeEventListener("abort",r),i(o),this.cleanupTask(n)},signal:e,queue_index:s.length};e&&e.addEventListener("abort",r,{once:!0}),s.push(n),this.active_count++,this.scheduleNextProcess()})}cleanupTask(e){e.queue_index=-1,e.signal=void 0,e.reject=null,e.resolve=null}shouldCompact(){if(this.queue_head<M.MIN_QUEUE_SIZE_FOR_COMPACTION)return!1;const e=this.waiting_queue,t=this.queue_head/Math.max(1,e.length);return this.queue_head>M.MIN_QUEUE_SIZE_FOR_COMPACTION&&t>M.WASTE_RATIO_THRESHOLD}compactQueue(){const e=this.waiting_queue;let t=0;for(let i=this.queue_head;i<e.length;i++){const s=e[i];s!==null&&(e[t]=s,s.queue_index=t,t++)}e.length=t,this.queue_head=0}removeTaskFromQueue(e){const t=this.waiting_queue;e.queue_index>=this.queue_head&&e.queue_index<t.length&&(t[e.queue_index]=null,this.active_count--,this.active_count===0&&(clearTimeout(this.timer_id),this.timer_id=null,t.length>1024&&(this.waiting_queue=[],this.queue_head=0)))}scheduleNextProcess(){if(this.active_count===0||this.is_disposed)return;const e=performance.now(),t=Math.max(0,this.next_process_time-e);this.timer_id!==null&&clearTimeout(this.timer_id),this.timer_id=setTimeout(()=>this.processOne(),t)}processOne(){this.timer_id=null;const e=this.waiting_queue;for(;this.queue_head<e.length;){const t=e[this.queue_head];if(e[this.queue_head]=null,this.queue_head++,t!==null){this.active_count--,t.resolve(),this.next_process_time=performance.now()+this.interval,this.shouldCompact()&&this.compactQueue(),this.scheduleNextProcess();return}}}}const _e=2147483647;class fe{limit;window_size;timestamps;head=0;count=0;constructor(e){const{limit:t,window_size:i}=e;if(!Number.isFinite(t)||t<=0||!Number.isInteger(t))throw new l.ParameterError(`SlidingWindow: \`limit\` must be a positive integer, but got ${t}`);if(!Number.isFinite(i)||i<=0)throw new l.ParameterError(`SlidingWindow: \`window_size\` must be a positive finite number, but got ${i}`);this.limit=t,this.window_size=i,this.timestamps=new Array(t)}resetRate(e){const{limit:t,window_size:i}=e;if(!Number.isFinite(t)||t<=0||!Number.isInteger(t))throw new l.ParameterError(`SlidingWindow: \`limit\` must be a positive integer, but got ${t}`);if(!Number.isFinite(i)||i<=0)throw new l.ParameterError(`SlidingWindow: \`window_size\` must be a positive finite number, but got ${i}`);if(this.limit=t,this.window_size=i,this.timestamps.length!==t){const s=this.timestamps,r=this.count,n=this.head,o=s.length;this.timestamps=new Array(t);const h=performance.now()-this.window_size,c=[];for(let _=1;_<=r;_++){const w=(n-_+o)%o,b=s[w];if(b>h&&c.push(b),c.length>=t)break}c.reverse(),this.count=c.length;for(let _=0;_<this.count;_++)this.timestamps[_]=c[_];this.head=this.count%t}}tryAcquire(e=1){if(!Number.isFinite(e)||e<=0||!Number.isInteger(e))throw new l.ParameterError(`SlidingWindow: \`weight\` must be a positive integer, but got ${e}`);if(e>this.limit)throw new l.ParameterError(`SlidingWindow: \`weight\` (${e}) cannot exceed \`limit\` (${this.limit}).`);const t=performance.now(),i=t-this.window_size;if(this.cleanExpired(i),this.count+e>this.limit)return!1;for(let s=0;s<e;s++)this.recordTimestamp(t);return!0}async wait(e=1,t){if(!Number.isFinite(e)||e<=0||!Number.isInteger(e))throw new l.ParameterError(`SlidingWindow: \`weight\` must be a positive integer, but got ${e}`);if(e>this.limit)throw new l.ParameterError(`SlidingWindow: \`weight\` (${e}) cannot exceed \`limit\` (${this.limit}).`);if(t?.aborted)throw u.ensureDOMException(t.reason);for(;;){const i=performance.now(),s=i-this.window_size;if(this.cleanExpired(s),this.count+e<=this.limit){for(let h=0;h<e;h++)this.recordTimestamp(i);return}const n=this.getOldestTimestamp()+this.window_size-i,o=Math.min(n,_e),a=await q.delaySafe(o,t);if(a)throw a}}get available(){const t=performance.now()-this.window_size;return this.cleanExpired(t),this.limit-this.count}get current(){const t=performance.now()-this.window_size;return this.cleanExpired(t),this.count}get stats(){const t=performance.now()-this.window_size;return this.cleanExpired(t),{limit:this.limit,window_size:this.window_size,count:this.count,available:this.limit-this.count,head:this.head}}cleanExpired(e){for(;this.count>0;){const t=(this.head-this.count+this.limit)%this.limit;if(this.timestamps[t]>e)break;this.count--}}recordTimestamp(e){const t=this.head;this.timestamps[t]=e,this.head=(this.head+1)%this.limit,this.count++}getOldestTimestamp(){const e=(this.head-this.count+this.limit)%this.limit;return this.timestamps[e]}}class P extends Error{constructor(e){super(`Circuit breaker is open. Retry after ${e}ms.`),this.reset_timeout=e,this.name="CircuitBreakerOpenError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,P)}}class me{state=0;failure_count=0;success_count=0;last_failure_time=0;failure_threshold;reset_timeout;success_threshold;constructor(e={}){const{failure_threshold:t=5,reset_timeout:i=3e4,success_threshold:s=3}=e;if(!Number.isFinite(t)||t<=0)throw new l.ParameterError(`CircuitBreaker: \`failure_threshold\` must be a positive finite number, but got ${t}`);if(!Number.isFinite(i)||i<=0)throw new l.ParameterError(`CircuitBreaker: \`reset_timeout\` must be a positive finite number, but got ${i}`);if(!Number.isFinite(s)||s<=0)throw new l.ParameterError(`CircuitBreaker: \`success_threshold\` must be a positive finite number, but got ${s}`);this.failure_threshold=t,this.reset_timeout=i,this.success_threshold=s}async execute(e,t){if(t?.aborted)throw u.ensureDOMException(t.reason);if(this.getCurrentState()===1){const s=this.getRemainingTimeout();throw new P(s)}try{const s=await e(t);return this.onSuccess(),s}catch(s){throw s instanceof DOMException&&s.name==="AbortError"||this.onFailure(),s}}async tryExecute(e,t){try{return{value:await this.execute(e,t),success:!0,state:this.state}}catch(i){return i instanceof P?{error:i,success:!1,state:1}:{error:i,success:!1,state:this.state}}}async waitForRecovery(e){for(;this.getCurrentState()===1;){const t=this.getRemainingTimeout(),i=await q.delaySafe(t,e);if(i)throw i}}reset(){this.state=0,this.failure_count=0,this.success_count=0,this.last_failure_time=0}trip(){this.state=1,this.last_failure_time=performance.now()}getState(){return this.getCurrentState()}getStats(){return{state:this.getCurrentState(),failure_count:this.failure_count,success_count:this.success_count,failure_threshold:this.failure_threshold,success_threshold:this.success_threshold,reset_timeout:this.reset_timeout,last_failure_time:this.last_failure_time,remaining_timeout:this.getRemainingTimeout()}}getCurrentState(){return this.state===1&&performance.now()-this.last_failure_time>=this.reset_timeout&&(this.state=2,this.success_count=0),this.state}getRemainingTimeout(){if(this.state!==1)return 0;const e=performance.now()-this.last_failure_time;return Math.max(0,this.reset_timeout-e)}onSuccess(){this.failure_count=0,this.state===2&&(this.success_count++,this.success_count>=this.success_threshold&&(this.state=0,this.success_count=0))}onFailure(){this.failure_count++,this.last_failure_time=performance.now(),this.state===2?(this.state=1,this.success_count=0):this.failure_count>=this.failure_threshold&&(this.state=1)}}class Z{tasks=new Set;finalizers=[];link_groups=[];is_disposed=!1;_abort_promise=null;_wait_promise=null;_resolve_wait=null;_resolve_dispose=null;controller=new AbortController;signal=this.controller.signal;constructor(e){if(e)if(e.aborted)this.is_disposed=!0,this.controller.abort(u.ensureDOMException(e.reason));else{const t=()=>{this.dispose(e.reason)};e.addEventListener("abort",t,{once:!0}),this.defer(()=>e.removeEventListener("abort",t))}}get isDisposed(){return this.is_disposed}throwIfDisposed(){if(this.is_disposed)throw new l.UseAfterFreeError("TaskScope is disposed")}getAbortPromise(){return this._abort_promise?this._abort_promise:(this._abort_promise=new Promise((e,t)=>{this.signal.addEventListener("abort",()=>{t(u.ensureDOMException(this.signal.reason))},{once:!0})}),this._abort_promise)}notifyTaskRemoved(){this.tasks.size===0&&(this._resolve_wait&&(this._resolve_wait(),this._wait_promise=null,this._resolve_wait=null),this._resolve_dispose&&(this._resolve_dispose(),this._resolve_dispose=null))}async executeTracked(e){const t=Promise.resolve(e(this.signal));this.tasks.add(t);try{return await t}finally{this.tasks.delete(t),this.notifyTaskRemoved()}}go(e,t){if(this.throwIfDisposed(),this.signal.aborted){t&&Promise.resolve(t(u.ensureDOMException(this.signal.reason)));return}this.executeTracked(e).catch(i=>{t&&t(i)})}async run(e){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);return Promise.race([this.executeTracked(e),this.getAbortPromise()])}async wait(){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);if(this.tasks.size!==0)return this._wait_promise||(this._wait_promise=new Promise(e=>{this._resolve_wait=e})),this._wait_promise}defer(e){return this.throwIfDisposed(),this.finalizers.push(e),()=>{const t=this.finalizers.indexOf(e);t!==-1&&this.finalizers.splice(t,1)}}async all(e){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);return Promise.race([Promise.all(e.map(t=>this.executeTracked(t))),this.getAbortPromise()])}async allSettled(e){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);return Promise.race([Promise.allSettled(e.map(t=>this.executeTracked(t))),this.getAbortPromise()])}async any(e){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);return Promise.race([Promise.any(e.map(t=>this.executeTracked(t))),this.getAbortPromise()])}async race(e){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);return Promise.race([Promise.race(e.map(t=>this.executeTracked(t))),this.getAbortPromise()])}async select(e){if(this.throwIfDisposed(),this.signal.aborted)throw u.ensureDOMException(this.signal.reason);const t=e.map(async(i,s)=>{try{const r=await this.executeTracked(i);return{index:s,status:"fulfilled",value:r}}catch(r){return{index:s,status:"rejected",reason:r}}});return Promise.race([Promise.race(t),this.getAbortPromise()])}spawn(e){this.throwIfDisposed();const t=e(this.signal),i=(async()=>{let s,r;for(;;){if(this.signal.aborted)throw t.return(void 0),u.ensureDOMException(this.signal.reason);const n=r?t.throw(r):t.next(s);if(r=void 0,n.done)return n.value;try{s=await n.value}catch(o){r=o}}})();return this.tasks.add(i),i.finally(()=>{this.tasks.delete(i),this.notifyTaskRemoved()}).catch(H.noop),i}async link(...e){this.throwIfDisposed();for(const s of e)if(s.aborted)return await this.dispose(s.reason),H.noop;const t=[];this.link_groups.push(t);const i=()=>{const s=this.link_groups.indexOf(t);if(s!==-1){this.link_groups.splice(s,1);for(const{signal:r,listener:n}of t)r.removeEventListener("abort",n);t.length=0}};for(const s of e){const r=()=>{i(),this.dispose(s.reason)};s.addEventListener("abort",r,{once:!0}),t.push({signal:s,listener:r})}return i}fork(){this.throwIfDisposed();const e=new Z(this.signal),t=this.defer(()=>e.dispose(this.signal.reason)),i=(async()=>{try{await e.wait()}finally{t()}})();return this.tasks.add(i),i.finally(()=>{this.tasks.delete(i),this.notifyTaskRemoved()}).catch(H.noop),e}async dispose(e){if(this.is_disposed)return;this.is_disposed=!0,this._resolve_wait&&(this._resolve_wait(),this._wait_promise=null,this._resolve_wait=null);for(const i of this.link_groups)for(const{signal:s,listener:r}of i)s.removeEventListener("abort",r);this.link_groups.length=0,this.controller.abort(e);const t=[];for(;this.finalizers.length>0;){const i=this.finalizers.pop();try{await i()}catch(s){t.push(s)}}if(this.tasks.size>0&&await new Promise(i=>{this._resolve_dispose=i}),this._abort_promise=null,t.length>0)throw new AggregateError(t,"TaskScope dispose errors")}async[Symbol.asyncDispose](){await this.dispose()}}class O{static MIN_QUEUE_SIZE_FOR_COMPACTION=64;static WASTE_RATIO_THRESHOLD=.65;is_locked=!1;waiting_queue=[];queue_head=0;is_disposed=!1;get isDisposed(){return this.is_disposed}get isLocked(){return this.is_locked}throwIfDisposed(){if(this.is_disposed)throw new l.UseAfterFreeError("Mutex has been disposed and cannot be used.")}constructor(e){}cleanupTask(e){e.queue_index=-1,e.signal=void 0,e.resolve=null,e.reject=null}shouldCompact(){if(this.queue_head<O.MIN_QUEUE_SIZE_FOR_COMPACTION)return!1;const e=this.waiting_queue,t=this.queue_head/Math.max(1,e.length);return this.queue_head>O.MIN_QUEUE_SIZE_FOR_COMPACTION&&t>O.WASTE_RATIO_THRESHOLD}compactQueue(){const e=this.waiting_queue;let t=0;for(let i=this.queue_head;i<e.length;i++){const s=e[i];s!==null&&(e[t]=s,s.queue_index=t,t++)}e.length=t,this.queue_head=0}removeTaskFromQueue(e){const t=this.waiting_queue;t[e.queue_index]=null}async lock(e){if(this.throwIfDisposed(),e?.aborted)throw u.ensureDOMException(e.reason);if(!this.is_locked){this.is_locked=!0;return}return new Promise((t,i)=>{const s=this.waiting_queue,r=()=>{this.removeTaskFromQueue(n),e.removeEventListener("abort",r),i(u.ensureDOMException(e.reason))},n={resolve:()=>{e?.removeEventListener("abort",r),t(),this.cleanupTask(n)},reject:o=>{e?.removeEventListener("abort",r),i(o),this.cleanupTask(n)},signal:e,queue_index:s.length};e&&e.addEventListener("abort",r,{once:!0}),s.push(n)})}unlock(){if(this.throwIfDisposed(),!this.is_locked)throw new l.MutexError("Mutex is not locked!");const e=this.waiting_queue;for(;this.queue_head<e.length;){const t=e[this.queue_head];if(e[this.queue_head]=null,this.queue_head++,t!==null){t.resolve(),this.shouldCompact()&&this.compactQueue();return}}e.length>1024?this.waiting_queue=[]:e.length=0,this.queue_head=0,this.is_locked=!1}async withLock(e,t){this.throwIfDisposed(),await this.lock(t);try{return await e()}finally{this.unlock()}}tryLock(){return this.throwIfDisposed(),this.is_locked?!1:(this.is_locked=!0,!0)}getStats(){if(this.is_disposed||!this.waiting_queue)return{waitingQueueLength:0,queueCapacity:0,queueHead:0,isLocked:this.is_locked,isDisposed:!0,compactionCounter:0};let e=0;for(let t=this.queue_head;t<this.waiting_queue.length;t++)this.waiting_queue[t]!==null&&e++;return{waitingQueueLength:e,queueCapacity:this.waiting_queue.length,queueHead:this.queue_head,isLocked:this.is_locked,isDisposed:this.is_disposed}}dispose(){if(this.is_disposed)return;this.is_disposed=!0;const e=this.waiting_queue;for(let t=this.queue_head;t<e.length;t++){const i=e[t];i!==null&&(i.reject(new DOMException("Mutex disposed","AbortError")),this.cleanupTask(i))}this.waiting_queue=null,this.is_locked=!1}[Symbol.dispose](){this.dispose()}}class ${#e;constructor(e){this.#e=e}static acquire(e){if(!e.tryLock())throw new l.MutexError("Failed to acquire mutex immediately (already locked)");return new $(e)}static async acquireAsync(e,t){return await e.lock(t),new $(e)}[Symbol.dispose](){this.release()}release(){this.#e!==null&&(this.#e.unlock(),this.#e=null)}}class pe extends O{owner_stack=void 0;timeout_ms;constructor(e=5e3){super(),this.timeout_ms=e}async lock(e){const t=new Error().stack,i=new AbortController,s=setTimeout(()=>{i.abort()},this.timeout_ms),r=e?AbortSignal.any([e,i.signal]):i.signal;try{await super.lock(r)}catch(n){throw i.signal.aborted&&n instanceof DOMException&&n.name==="AbortError"?new l.MutexError(`[Mutex Deadlock/Timeout] (${this.timeout_ms}ms)
2
+ [Current Request Location]: ${t}
3
+ Holder stack: ${this.owner_stack||"Unknown"}`):n}finally{clearTimeout(s),i.abort()}this.owner_stack=t}unlock(){super.unlock(),this.owner_stack=void 0}[Symbol.dispose](){super.dispose(),this.owner_stack=void 0}}class L{static MIN_QUEUE_SIZE_FOR_COMPACTION=32;static WASTE_RATIO_THRESHOLD=.7;waiting_queue=[];queue_head=0;is_disposed=!1;get isDisposed(){return this.is_disposed}constructor(e){}throwIfDisposed(){if(this.is_disposed)throw new l.UseAfterFreeError("ConditionVariable has been disposed and cannot be used")}cleanupTask(e){e.signal=void 0,e.queue_index=-1,e.resolve=null,e.reject=null}shouldCompact(){return this.queue_head<L.MIN_QUEUE_SIZE_FOR_COMPACTION?!1:this.queue_head/Math.max(1,this.waiting_queue.length)>L.WASTE_RATIO_THRESHOLD}compactQueue(){const e=this.waiting_queue;let t=0;for(let i=this.queue_head;i<e.length;i++){const s=e[i];s!==null&&(e[t]=s,s.queue_index=t,t++)}e.length=t,this.queue_head=0}removeTaskFromQueue(e){this.waiting_queue[e.queue_index]=null}async wait(e,t){if(this.throwIfDisposed(),!e.isLocked)throw new l.LockError("ConditionVariable.wait() called without holding the mutex lock! This is a critical synchronization bug.");if(t?.aborted)throw u.ensureDOMException(t.reason);const i={signal:t,queue_index:this.waiting_queue.length},s=()=>{this.removeTaskFromQueue(i),t.removeEventListener("abort",s),i.reject(u.ensureDOMException(t.reason))},r=new Promise((h,c)=>{i.resolve=()=>{t?.removeEventListener("abort",s),h(),this.cleanupTask(i)},i.reject=_=>{t?.removeEventListener("abort",s),c(_),this.cleanupTask(i)},t&&t.addEventListener("abort",s,{once:!0})});this.waiting_queue.push(i);try{e.unlock()}catch(h){throw t?.removeEventListener("abort",s),this.removeTaskFromQueue(i),this.cleanupTask(i),h}let n=null;try{await r}catch(h){n=u.ensureError(h)}let o=null;try{await e.lock()}catch(h){o=h}const a=n||o;if(a)throw n&&o&&(n.cause=o),a}notifyOne(){for(this.throwIfDisposed();this.queue_head<this.waiting_queue.length;){const e=this.waiting_queue[this.queue_head];if(this.waiting_queue[this.queue_head]=null,this.queue_head++,e!==null){e.resolve(),this.shouldCompact()&&this.compactQueue();return}}this.waiting_queue.length>1024?this.waiting_queue=[]:this.waiting_queue.length=0,this.queue_head=0}notifyAll(){this.throwIfDisposed();for(let e=this.queue_head;e<this.waiting_queue.length;e++){const t=this.waiting_queue[e];t!==null&&(this.waiting_queue[e]=null,t.resolve())}this.waiting_queue=[],this.queue_head=0}getStats(){if(this.is_disposed)return{waitingCount:0,queueCapacity:0,queueHead:0,isDisposed:!0};let e=0;for(let t=this.queue_head;t<this.waiting_queue.length;t++)this.waiting_queue[t]!==null&&e++;return{waitingCount:e,queueCapacity:this.waiting_queue.length,queueHead:this.queue_head,isDisposed:!1}}dispose(){if(!this.is_disposed){this.is_disposed=!0;for(let e=this.queue_head;e<this.waiting_queue.length;e++){const t=this.waiting_queue[e];t!==null&&(t.reject(new DOMException("ConditionVariable disposed","AbortError")),this.cleanupTask(t))}this.waiting_queue=null}}[Symbol.dispose](){this.dispose()}}class we extends L{last_notify_stack=void 0;timeout_ms;constructor(e=3e3){super(),this.timeout_ms=e}async wait(e,t){const i=new Error().stack,s=new AbortController,r=setTimeout(()=>s.abort(),this.timeout_ms),n=t?AbortSignal.any([t,s.signal]):s.signal;try{await super.wait(e,n)}catch(o){const a=t?.aborted,h=s.signal.aborted;throw!a&&h&&o instanceof DOMException&&o.name==="AbortError"?new l.LockError(`[ConditionVariable Timeout] (${this.timeout_ms}ms)
4
+ Waiting at:
5
+ ${i}
6
+ Last notify at:
7
+ ${this.last_notify_stack||"Never notified"}`):o}finally{clearTimeout(r),s.abort()}}notifyOne(){this.last_notify_stack=new Error().stack,super.notifyOne()}notifyAll(){this.last_notify_stack=new Error().stack,super.notifyAll()}dispose(){this.last_notify_stack=void 0,super.dispose()}}async function be(d,e,t,i,s){await d.lock(s);try{for(;!await t();)await e.wait(d,s);return await i()}finally{d.unlock()}}class A{static MIN_QUEUE_SIZE_FOR_COMPACTION=64;static WASTE_RATIO_THRESHOLD=.65;active_readers=0;active_writer=!1;waiting_queue=[];queue_head=0;is_disposed=!1;get isDisposed(){return this.is_disposed}get isLocked(){return this.active_writer||this.active_readers>0}get isWriteLocked(){return this.active_writer}get readerCount(){return this.active_readers}throwIfDisposed(){if(this.is_disposed)throw new l.UseAfterFreeError("ReadWriteLock has been disposed and cannot be used.")}constructor(e){}cleanupTask(e){e.queue_index=-1,e.signal=void 0,e.resolve=null,e.reject=null}shouldCompact(){if(this.queue_head<A.MIN_QUEUE_SIZE_FOR_COMPACTION)return!1;const e=this.waiting_queue,t=this.queue_head/Math.max(1,e.length);return this.queue_head>A.MIN_QUEUE_SIZE_FOR_COMPACTION&&t>A.WASTE_RATIO_THRESHOLD}compactQueue(){const e=this.waiting_queue;let t=0;for(let i=this.queue_head;i<e.length;i++){const s=e[i];s!==null&&(e[t]=s,s.queue_index=t,t++)}e.length=t,this.queue_head=0}removeTaskFromQueue(e){const t=this.waiting_queue;t[e.queue_index]=null}drainQueue(){const e=this.waiting_queue;for(;this.queue_head<e.length;){const t=e[this.queue_head];if(t===null){this.queue_head++;continue}if(t.mode===1){if(this.active_readers>0)break;e[this.queue_head]=null,this.queue_head++,this.active_writer=!0,t.resolve();break}else e[this.queue_head]=null,this.queue_head++,this.active_readers++,t.resolve()}this.queue_head>=e.length?(e.length>1024?this.waiting_queue=[]:e.length=0,this.queue_head=0):this.shouldCompact()&&this.compactQueue()}enqueueTask(e,t){return new Promise((i,s)=>{const r=this.waiting_queue,n={resolve:()=>{t?.removeEventListener("abort",o),i(),this.cleanupTask(n)},reject:a=>{t?.removeEventListener("abort",o),s(a),this.cleanupTask(n)},signal:t,mode:e,queue_index:r.length},o=()=>{this.removeTaskFromQueue(n),s(u.ensureDOMException(t?.reason))};t&&t.addEventListener("abort",o,{once:!0}),r.push(n)})}async readLock(e){if(this.throwIfDisposed(),e?.aborted)throw u.ensureDOMException(e.reason);if(!this.active_writer&&this.queue_head===this.waiting_queue.length){this.active_readers++;return}await this.enqueueTask(0,e)}async writeLock(e){if(this.throwIfDisposed(),e?.aborted)throw u.ensureDOMException(e.reason);if(!this.active_writer&&this.active_readers===0&&this.queue_head===this.waiting_queue.length){this.active_writer=!0;return}await this.enqueueTask(1,e)}unlock(){if(this.throwIfDisposed(),this.active_writer)this.active_writer=!1,this.drainQueue();else if(this.active_readers>0)this.active_readers--,this.active_readers===0&&this.drainQueue();else throw new l.RWLockError("ReadWriteLock is not locked!")}async withReadLock(e,t){this.throwIfDisposed(),await this.readLock(t);try{return await e()}finally{this.unlock()}}async withWriteLock(e,t){this.throwIfDisposed(),await this.writeLock(t);try{return await e()}finally{this.unlock()}}tryReadLock(){return this.throwIfDisposed(),!this.active_writer&&this.queue_head===this.waiting_queue.length?(this.active_readers++,!0):!1}tryWriteLock(){return this.throwIfDisposed(),!this.active_writer&&this.active_readers===0&&this.queue_head===this.waiting_queue.length?(this.active_writer=!0,!0):!1}getStats(){if(this.is_disposed||!this.waiting_queue)return{activeReaders:0,activeWriter:!1,waitingReaders:0,waitingWriters:0,queueLength:0,isDisposed:!0};let e=0,t=0;for(let i=this.queue_head;i<this.waiting_queue.length;i++){const s=this.waiting_queue[i];s!==null&&(s.mode===0?e++:t++)}return{activeReaders:this.active_readers,activeWriter:this.active_writer,waitingReaders:e,waitingWriters:t,queueLength:this.waiting_queue.length-this.queue_head,isDisposed:this.is_disposed}}dispose(){if(this.is_disposed)return;this.is_disposed=!0;const e=this.waiting_queue;for(let t=this.queue_head;t<e.length;t++){const i=e[t];i!==null&&(i.reject(new DOMException("ReadWriteLock disposed","AbortError")),this.cleanupTask(i))}this.waiting_queue=null,this.active_readers=0,this.active_writer=!1}[Symbol.dispose](){this.dispose()}}class W{#e;constructor(e){this.#e=e}static async acquire(e,t){return await e.readLock(t),new W(e)}static tryAcquire(e){return e.tryReadLock()?new W(e):null}[Symbol.dispose](){this.release()}release(){this.#e!==null&&(this.#e.unlock(),this.#e=null)}}class Q{#e;constructor(e){this.#e=e}static async acquire(e,t){return await e.writeLock(t),new Q(e)}static tryAcquire(e){return e.tryWriteLock()?new Q(e):null}[Symbol.dispose](){this.release()}release(){this.#e!==null&&(this.#e.unlock(),this.#e=null)}}class ve extends A{writer_stack=void 0;reader_stacks=[];timeout_ms;constructor(e=5e3){super(),this.timeout_ms=e}createTimeoutWrapper(e,t){const i=new AbortController,s=setTimeout(()=>{i.abort()},this.timeout_ms);return{controller:i,cleanup:()=>{clearTimeout(s),i.abort()},getError:r=>{if(i.signal.aborted&&r instanceof DOMException&&r.name==="AbortError"){const n=e===1?`Writer Holder: ${this.writer_stack||"None"}`:`Active Readers: ${this.active_readers}
8
+ One Reader Stack: ${this.reader_stacks[0]||"Unknown"}`;return new l.RWLockError(`[RWLock Deadlock/Timeout] (${this.timeout_ms}ms)
9
+ [Waiting Mode]: ${e===0?"read":"write"}
10
+ [Request Location]: ${t}
11
+ `+n)}return r}}}async readLock(e){const t=new Error().stack,{controller:i,cleanup:s,getError:r}=this.createTimeoutWrapper(0,t);try{const n=e?AbortSignal.any([e,i.signal]):i.signal;await super.readLock(n)}catch(n){throw r(n)}finally{s()}this.reader_stacks.push(t)}async writeLock(e){const t=new Error().stack,{controller:i,cleanup:s,getError:r}=this.createTimeoutWrapper(1,t);try{const n=e?AbortSignal.any([e,i.signal]):i.signal;await super.writeLock(n)}catch(n){throw r(n)}finally{s()}this.writer_stack=t}unlock(){this.active_writer?this.writer_stack=void 0:this.active_readers>0&&this.reader_stacks.pop(),super.unlock()}[Symbol.dispose](){super.dispose(),this.writer_stack=void 0,this.reader_stacks=[]}}class S{static MIN_QUEUE_SIZE_FOR_COMPACTION=64;static WASTE_RATIO_THRESHOLD=.65;permits;waiting_queue=[];queue_head=0;is_disposed=!1;get isDisposed(){return this.is_disposed}constructor(e=1,t){if(e<0||Number.isNaN(e))throw new l.ParameterError(`Semaphore: \`initialPermits\` must be a non-negative number, but got ${e}`);this.permits=e}throwIfDisposed(){if(this.is_disposed)throw new l.UseAfterFreeError("Semaphore has been disposed and cannot be used.")}cleanup_task(e){e.signal=void 0,e.queue_index=-1,e.reject=null,e.resolve=null}should_compact(){if(this.queue_head<S.MIN_QUEUE_SIZE_FOR_COMPACTION)return!1;const e=this.waiting_queue,t=this.queue_head/Math.max(1,e.length);return this.queue_head>S.MIN_QUEUE_SIZE_FOR_COMPACTION&&t>S.WASTE_RATIO_THRESHOLD}compact_queue(){const e=this.waiting_queue;let t=0;for(let i=this.queue_head;i<e.length;i++){const s=e[i];s!==null&&(e[t]=s,s.queue_index=t,t++)}e.length=t,this.queue_head=0}remove_task_from_queue(e){const t=this.waiting_queue;t[e.queue_index]=null}async acquire(e){if(this.throwIfDisposed(),e?.aborted)throw u.ensureDOMException(e.reason);if(this.permits>0){this.permits--;return}return new Promise((t,i)=>{const s=this.waiting_queue,r=()=>{this.remove_task_from_queue(n),e.removeEventListener("abort",r),i(u.ensureDOMException(e.reason))},n={resolve:()=>{e?.removeEventListener("abort",r),t(),this.cleanup_task(n)},reject:o=>{e?.removeEventListener("abort",r),i(o),this.cleanup_task(n)},signal:e,queue_index:s.length};e&&e.addEventListener("abort",r,{once:!0}),s.push(n)})}release(e=1){if(this.throwIfDisposed(),e<1)throw new l.ParameterError(`Semaphore: \`count\` must be at least 1, but got ${e}`);const t=this.waiting_queue;let i=0;for(;i<e&&this.queue_head<t.length;){const s=t[this.queue_head];t[this.queue_head]=null,this.queue_head++,s!==null&&(s.resolve(),i++)}this.permits+=e-i,i>0&&this.should_compact()&&this.compact_queue(),this.queue_head>=t.length&&(t.length>1024?this.waiting_queue=[]:t.length=0,this.queue_head=0)}tryAcquire(){return this.throwIfDisposed(),this.permits>0?(this.permits--,!0):!1}resetPermits(e){if(this.throwIfDisposed(),e<0||Number.isNaN(e))throw new l.ParameterError(`Semaphore: \`new_permits\` must be a non-negative number, but got ${e}`);const t=this.permits;this.permits=e,e>t&&e>0&&this.wakeWaiters()}getPermits(){return this.throwIfDisposed(),this.permits}wakeWaiters(){const e=this.waiting_queue;for(;this.permits>0&&this.queue_head<e.length;){const t=e[this.queue_head];e[this.queue_head]=null,this.queue_head++,t!==null&&(this.permits--,t.resolve())}this.queue_head>=e.length&&(e.length>1024?this.waiting_queue=[]:e.length=0,this.queue_head=0)}async withPermit(e,t){this.throwIfDisposed(),await this.acquire(t);try{return await e()}finally{this.release()}}getStats(){if(this.is_disposed||!this.waiting_queue)return{availablePermits:0,waitingQueueLength:0,queueCapacity:0,queueHead:0,isDisposed:!0,compactionCounter:0};let e=0;for(let t=this.queue_head;t<this.waiting_queue.length;t++)this.waiting_queue[t]!==null&&e++;return{availablePermits:this.permits,waitingQueueLength:e,queueCapacity:this.waiting_queue.length,queueHead:this.queue_head,isDisposed:this.is_disposed}}dispose(){if(this.is_disposed)return;this.is_disposed=!0;const e=this.waiting_queue;for(let t=this.queue_head;t<e.length;t++){const i=e[t];i!==null&&i.reject(new DOMException("Semaphore disposed","AbortError"))}this.waiting_queue=null,this.permits=0}[Symbol.dispose](){this.dispose()}}class B{#e;#t=!1;constructor(e){this.#e=e}static acquire(e){if(!e.tryAcquire())throw new l.LockError("Failed to acquire semaphore permit immediately (no permits available)");return new B(e)}static async acquireAsync(e,t){return await e.acquire(t),new B(e)}[Symbol.dispose](){this.release()}release(){!this.#t&&this.#e!==null&&(this.#e.release(),this.#e=null,this.#t=!0)}}class Ee extends S{timeout_ms;constructor(e=1,t=5e3){super(e),this.timeout_ms=t}async acquire(e){const t=new Error().stack,i=new AbortController,s=setTimeout(()=>{i.abort()},this.timeout_ms),r=e?AbortSignal.any([e,i.signal]):i.signal;try{await super.acquire(r)}catch(n){throw i.signal.aborted&&n instanceof DOMException&&n.name==="AbortError"?new l.LockError(`[Semaphore Timeout] (${this.timeout_ms}ms) - No permits available
12
+ [Current Request Location]: ${t}
13
+ Available Permits: ${this.permits}
14
+ Waiting Queue Length: ${this.getStats().waitingQueueLength}`):n}finally{clearTimeout(s),i.abort()}}[Symbol.dispose](){super.dispose()}}const V=Symbol("Map Skip");async function ge(d,e,{concurrency:t=1/0,stopOnError:i=!0,signal:s}={}){if(!(Number.isSafeInteger(t)&&t>=1||t===1/0))throw new l.ParameterError(`asyncMap: Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\``);return new Promise((r,n)=>{const o=d[Symbol.asyncIterator]?.()??d[Symbol.iterator](),a=[],h=[],c=new Set;let _=!1,w=null;const b=()=>{if(s?.removeEventListener("abort",m),typeof o.return=="function")try{const f=o.return();f instanceof Promise&&f.catch(()=>{})}catch{}},m=()=>{b(),n(u.ensureDOMException(s.reason))};if(s){if(s.aborted){m();return}s.addEventListener("abort",m,{once:!0})}(async()=>{let f=0;try{for(;!(s?.aborted||_||(c.size>=t&&await Promise.race(c),s?.aborted||_));){const{done:p,value:v}=await o.next();if(p)break;const R=f++,y=(async()=>{try{const k=await v;if(s?.aborted||_)return;const X=await e(k,R);X!==V&&(a[R]=X)}catch(k){i?(_=!0,w||(w=k)):h.push(k)}})();c.add(y),y.finally(()=>c.delete(y))}await Promise.allSettled(c),w?n(u.ensureError(w)):h.length>0?n(new AggregateError(h)):r(a.filter(()=>!0))}catch(p){n(u.ensureError(p))}finally{b()}})()})}async function*ye(d,e,{concurrency:t=1/0,backpressure:i=t,signal:s}={}){if(!(Number.isSafeInteger(t)&&t>=1||t===1/0))throw new l.ParameterError(`asyncMapIterable: Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\``);if(!(Number.isSafeInteger(i)&&i>=t||i===1/0))throw new l.ParameterError(`asyncMapIterable: Expected \`backpressure\` to be an integer >= \`concurrency\` or \`Infinity\`, got \`${i}\``);const r=d[Symbol.asyncIterator]?.()??d[Symbol.iterator](),n=[];let o=0,a=0,h=!1,c,_;if(s){if(s.aborted){const m=r.return?.();throw m instanceof Promise&&m.catch(()=>{}),u.ensureDOMException(s.reason)}c=new Promise((m,f)=>{_=()=>f(u.ensureDOMException(s.reason)),s.addEventListener("abort",_)})}const w=()=>{if(s&&_&&s.removeEventListener("abort",_),typeof r.return=="function"){const m=r.return();m instanceof Promise&&m.catch(()=>{})}},b=async()=>{for(;!h&&!s?.aborted&&o<t&&n.length<i;){const m=r.next(),{done:f,value:p}=await(c?Promise.race([m,c]):m);if(f){h=!0;break}o++;const v=a++,R=Promise.resolve(p).then(async y=>{const k=await(c?Promise.race([e(y,v),c]):e(y,v));return{value:k,skip:k===V}}).catch(y=>({error:y})).finally(()=>{o--});n.push(R)}};try{for(;;){if(s?.aborted)throw u.ensureDOMException(s.reason);if(await b(),n.length===0)return;const m=n.shift(),f=await(c?Promise.race([m,c]):m);if(f.error)throw u.ensureError(f.error);f.skip||(yield f.value)}}finally{w()}}function qe(d,e){const{ms:t,fallback:i,signal:s}=e;if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<=0)throw new l.ParameterError(`asyncTimeout: \`ms\` must be a positive integer, but got ${t}`);let r=null,n=null,o;const a=()=>{r!==null&&(clearTimeout(r),r=null)},h=()=>{a(),n&&s&&(s.removeEventListener("abort",n),n=null)},c=b=>{h(),o(b)},w=new Promise((b,m)=>{if(o=m,s?.aborted)return c(u.ensureDOMException(s.reason));r=setTimeout(()=>{if(i)try{b(i()),h()}catch(f){c(f)}else c(new DOMException(`Promise timed out after ${t}ms`,"TimeoutError"))},t),s&&(n=()=>c(u.ensureDOMException(s.reason)),s.addEventListener("abort",n,{once:!0})),d.then(f=>{h(),b(f)},f=>{c(f)})}).finally(()=>{h()});return w.clear=()=>{c(new DOMException("Timeout cleared by user","AbortError"))},w}async function ke(d,e){const{concurrency:t=1/0,mapper:i,signal:s}=e;if(!(Number.isSafeInteger(t)&&t>=1||t===1/0))throw new l.ParameterError(`asyncSettle: Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${t}\``);if(s?.aborted)throw u.ensureDOMException(s.reason);const r=new Array(d.length);let n=0;const o=async()=>{for(;n<d.length&&!s?.aborted;){const h=n++;try{const c=await i(d[h],h);r[h]={status:"fulfilled",value:c}}catch(c){r[h]={status:"rejected",reason:c}}}},a=Array.from({length:Math.min(t,d.length)},()=>o());if(await Promise.all(a),s?.aborted)throw u.ensureDOMException(s.reason);return r}const Y=Symbol("done value");async function se(d,e={}){const{interval:t=20,timeout:i=Number.POSITIVE_INFINITY,before:s=!0,signal:r}=e;if(!Number.isFinite(t)||t<0)throw new l.ParameterError("asyncWaitFor: Expected `interval` to be a finite non-negative number");const n=typeof i=="number"?i:i?.ms??Number.POSITIVE_INFINITY;if(Number.isNaN(n)||n<0)throw new l.ParameterError("asyncWaitFor: Expected `timeout` to be a non-negative number");if(r?.aborted)throw u.ensureDOMException(r.reason);const o=n===Number.POSITIVE_INFINITY?void 0:AbortSignal.timeout(n),a=o&&r?AbortSignal.any([o,r]):o??r,h=()=>{if(o?.aborted){const c=typeof i=="object"?i.fallback:void 0;if(c)return c();throw new DOMException(typeof i=="object"&&i.message?i.message:`Promise timed out after ${n}ms`,"TimeoutError")}throw u.ensureDOMException(a.reason)};if(!s&&await q.delaySafe(t,a)!==void 0)return h();for(;;){let c;try{c=await d()}catch(_){if(_===a?.reason)return h();throw _}if(typeof c=="object"&&c!==null&&Y in c)return c[Y];if(c===!0)return;if(c===!1){if(await q.delaySafe(t,a)!==void 0)return h();continue}throw new l.ParameterError("asyncWaitFor: Expected condition to return a boolean")}}se.done=d=>({[Y]:d});async function Ie(d){const e=new AbortController,t=e.signal,i=typeof d=="function"?d(t):d;if(!Array.isArray(i)||i.length===0)throw new l.ParameterError("asyncRace: Must provide a non-empty array of tasks for a fair race!");return new Promise((s,r)=>{const n=o=>{t.aborted||(e.abort(),o())};for(const o of i)Promise.resolve(o).then(a=>n(()=>s(a)),a=>n(()=>r(u.ensureError(a))))})}async function xe(d,e){const t=new AbortController;return new Promise((i,s)=>{const r=()=>{t.abort(),s(u.ensureDOMException(e.reason))};if(e){if(e.aborted)throw t.abort(),u.ensureDOMException(e.reason);e.addEventListener("abort",r,{once:!0})}let n=0;const o=h=>{e&&!e.aborted&&e.removeEventListener("abort",r),!t.signal.aborted&&(h(),t.abort())};(async()=>{try{const h=d[Symbol.asyncIterator]?.()??d[Symbol.iterator]();for(;;){if(t.signal.aborted)return;const{value:c,done:_}=await h.next();if(_)break;n++,Promise.resolve(c).then(w=>o(()=>i(w)),w=>{n--,o(()=>s(u.ensureError(w)))})}n===0&&!t.signal.aborted&&s(new l.ParameterError("asyncFirst: No tasks were provided."))}catch(h){o(()=>s(u.ensureError(h)))}})()})}async function Te(d,e,t={}){const{concurrency:i=Number.POSITIVE_INFINITY,signal:s}=t;if(i<1||!Number.isInteger(i)&&i!==Number.POSITIVE_INFINITY)throw new l.ParameterError(`asyncEvery: Invalid concurrency ${i}`);if(s?.aborted)throw u.ensureDOMException(s.reason);const r=Array.isArray(d)?d:[...d];if(r.length===0)return!0;let n=!1,o=0;const a=async()=>{for(;o<r.length&&!n;){if(s?.aborted)throw u.ensureDOMException(s.reason);const _=o++,w=await r[_];if(n||s?.aborted)return;if(!await u.dynamicAwait(e(w,_))){n=!0;return}}},h=Math.min(i,r.length),c=Array.from({length:h},a);try{if(await Promise.all(c),s?.aborted)throw u.ensureDOMException(s.reason);return!n}catch(_){throw n=!0,_}}async function Oe(d,e){const{count:t=1,concurrency:i=Number.POSITIVE_INFINITY,filter:s=()=>!0,signal:r}=e;if(t<1||!Number.isInteger(t))throw new l.ParameterError(`asyncSome: Invalid count ${t}`);if(i<1||!Number.isInteger(i)&&i!==Number.POSITIVE_INFINITY)throw new l.ParameterError(`asyncSome: Invalid concurrency ${i}`);if(r?.aborted)throw u.ensureDOMException(r.reason);const n=Array.isArray(d)?d:[...d];if(n.length<t)throw new RangeError(`asyncSome: Expected at least ${t} items, but only ${n.length} provided`);const o=[],a=[];let h=!1,c=0,_=n.length;const w=async()=>{for(;c<n.length&&!h;){if(r?.aborted)throw u.ensureDOMException(r.reason);const f=c++;try{const p=await n[f];if(h||r?.aborted)return;if(await u.dynamicAwait(s(p))&&!h&&(o.push(p),o.length===t)){h=!0;return}}catch(p){h||a.push(p)}finally{_--,!h&&_+o.length<t&&(h=!0)}}},b=Math.min(i,n.length),m=Array.from({length:b},w);try{if(await Promise.all(m),r?.aborted)throw u.ensureDOMException(r.reason);if(o.length===t)return o;throw new AggregateError(a,`asyncSome: Could not collect ${t} valid values`)}catch(f){throw h=!0,f}}async function Ae(d,e={}){const{concurrency:t=Number.POSITIVE_INFINITY,filter:i=()=>!0,signal:s}=e;if(t<1||!Number.isInteger(t)&&t!==Number.POSITIVE_INFINITY)throw new l.ParameterError(`asyncAny: Invalid concurrency ${t}`);if(s?.aborted)throw u.ensureDOMException(s.reason);const r=Array.isArray(d)?d:[...d];if(r.length===0)throw new AggregateError([],"asyncAny: No elements provided");const n=[];let o=!1,a=0,h=r.length,c,_=!1;const w=async()=>{for(;a<r.length&&!o;){if(s?.aborted)throw u.ensureDOMException(s.reason);const f=a++;try{const p=await r[f];if(o||s?.aborted)return;if(await u.dynamicAwait(i(p))&&!o){c=p,_=!0,o=!0;return}}catch(p){o||n.push(p)}finally{h--,!o&&h===0&&(o=!0)}}},b=Math.min(t,r.length),m=Array.from({length:b},w);try{if(await Promise.all(m),s?.aborted)throw u.ensureDOMException(s.reason);if(_)return c;throw new AggregateError(n.length>0?n:[],"asyncAny: No elements passed the filter")}catch(f){throw o=!0,f}}exports.delay=q.delay;exports.delaySafe=q.delaySafe;exports.sleep=q.sleep;exports.Barrier=he;exports.CHANNEL_CLOSED=x;exports.Channel=T;exports.CircuitBreaker=me;exports.CircuitBreakerOpenError=P;exports.ConditionVariable=L;exports.CyclicBarrier=ce;exports.DEBUG_CONDITION_VARIABLE=we;exports.DEBUG_MUTEX=pe;exports.DEBUG_RW_LOCK=ve;exports.DEBUG_SEMAPHORE=Ee;exports.LeakyBucket=M;exports.LeakyBucketReject=j;exports.Limiter=D;exports.LockGuard=$;exports.MAP_SKIP=V;exports.Mutex=O;exports.PermitGuard=B;exports.ReadLockGuard=W;exports.ReadWriteLock=A;exports.Scheduler=g;exports.Semaphore=S;exports.SlidingWindow=fe;exports.TaskScope=Z;exports.TokenBucket=z;exports.WriteLockGuard=Q;exports.asyncAny=Ae;exports.asyncEvery=Te;exports.asyncFirst=xe;exports.asyncMap=ge;exports.asyncMapIterable=ye;exports.asyncRace=Ie;exports.asyncSettle=ke;exports.asyncSome=Oe;exports.asyncTimeout=qe;exports.asyncWaitFor=se;exports.select=le;exports.withCondition=be;
15
+ //# sourceMappingURL=Concurrent.cjs.map