commandkit 1.2.0-rc.2 → 1.2.0-rc.4

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 (178) hide show
  1. package/README.md +4 -12
  2. package/dist/ActionRow-CmTHbo2t.js.map +1 -1
  3. package/dist/CommandKitEventsChannel-Bgw0XCOl.js.map +1 -1
  4. package/dist/{CommandsRouter-Ci1Pe8Vd.js → CommandsRouter-tMAivEfv.js} +10 -7
  5. package/dist/{CommandsRouter-Ci1Pe8Vd.js.map → CommandsRouter-tMAivEfv.js.map} +1 -1
  6. package/dist/CompilerPlugin-CjoZAAR8.js.map +1 -1
  7. package/dist/{DefaultLogger-Cy55-uPl.d.ts → DefaultLogger-XCOl5nLd.d.ts} +19 -12
  8. package/dist/EventInterceptor-CQ4PBpBJ.js.map +1 -1
  9. package/dist/{EventWorkerContext-DJUi1W3T.d.ts → EventWorkerContext-BEezHh5-.d.ts} +2 -2
  10. package/dist/{EventWorkerContext-CSlD9rbx.js → EventWorkerContext-TZIKxVCu.js} +1 -1
  11. package/dist/{EventWorkerContext-CSlD9rbx.js.map → EventWorkerContext-TZIKxVCu.js.map} +1 -1
  12. package/dist/EventsRouter-C_J0M3uO.js.map +1 -1
  13. package/dist/ILogger-BW8GM-YZ.d.ts +64 -0
  14. package/dist/{Logger-iSjA-DWN.d.ts → Logger-DyfkPk7u.d.ts} +2 -2
  15. package/dist/{MessageCommandParser-B_BEQ3p8.js → MessageCommandParser-TPEPhjvx.js} +2 -2
  16. package/dist/{MessageCommandParser-B_BEQ3p8.js.map → MessageCommandParser-TPEPhjvx.js.map} +1 -1
  17. package/dist/PluginCommon-Di1xIa8d.js.map +1 -1
  18. package/dist/RuntimePlugin-CBgBLXTG.js.map +1 -1
  19. package/dist/analytics/analytics-engine.d.ts +2 -2
  20. package/dist/analytics/analytics-engine.js +7 -7
  21. package/dist/analytics/analytics-provider.d.ts +2 -2
  22. package/dist/analytics/constants.js +1 -1
  23. package/dist/analytics/utils.js +7 -7
  24. package/dist/{analytics-engine-vA4MaJYx.d.ts → analytics-engine-Iu_1uJop.d.ts} +84 -27
  25. package/dist/app/commands/AppCommandRunner.d.ts +2 -2
  26. package/dist/app/commands/AppCommandRunner.js +7 -7
  27. package/dist/app/commands/Context.d.ts +2 -2
  28. package/dist/app/commands/Context.js +7 -7
  29. package/dist/app/commands/MessageCommandParser.js +2 -2
  30. package/dist/app/events/EventWorkerContext.d.ts +3 -3
  31. package/dist/app/events/EventWorkerContext.js +1 -1
  32. package/dist/app/handlers/AppCommandHandler.d.ts +2 -2
  33. package/dist/app/handlers/AppCommandHandler.js +7 -7
  34. package/dist/app/handlers/AppEventsHandler.d.ts +2 -2
  35. package/dist/app/handlers/AppEventsHandler.js +7 -7
  36. package/dist/app/index.d.ts +3 -3
  37. package/dist/app/index.js +9 -9
  38. package/dist/app/interrupt/signals.d.ts +2 -2
  39. package/dist/app/interrupt/signals.js +5 -5
  40. package/dist/app/middlewares/permissions.d.ts +42 -0
  41. package/dist/app/middlewares/permissions.js +38 -0
  42. package/dist/app/register/CommandRegistrar.d.ts +2 -2
  43. package/dist/app/register/CommandRegistrar.js +7 -7
  44. package/dist/app/router/CommandsRouter.js +1 -1
  45. package/dist/app/router/index.js +1 -1
  46. package/dist/app-process-CjMovpoZ.js.map +1 -1
  47. package/dist/{build-DXl8uEv4.js → build-Yhb1VjD0.js} +2 -2
  48. package/dist/build-Yhb1VjD0.js.map +1 -0
  49. package/dist/cli/build.d.ts +2 -2
  50. package/dist/cli/build.js +8 -8
  51. package/dist/cli/common.d.ts +2 -2
  52. package/dist/cli/development.js +9 -9
  53. package/dist/cli/development.js.map +1 -1
  54. package/dist/cli/generators.js.map +1 -1
  55. package/dist/cli/information.js +1 -1
  56. package/dist/cli/information.js.map +1 -1
  57. package/dist/cli/init.js +8 -8
  58. package/dist/cli/production.js +8 -8
  59. package/dist/cli/production.js.map +1 -1
  60. package/dist/{commandkit-DMEW0kJg.js → commandkit-c0sAaK0G.js} +352 -202
  61. package/dist/commandkit-c0sAaK0G.js.map +1 -0
  62. package/dist/commandkit.d.ts +2 -2
  63. package/dist/commandkit.js +7 -7
  64. package/dist/common-DNADUU3_.js.map +1 -1
  65. package/dist/common-vnMIelAE.js.map +1 -1
  66. package/dist/components/index.js +7 -7
  67. package/dist/components/v1/button/Button.js +7 -7
  68. package/dist/components/v1/button/ButtonKit.js +7 -7
  69. package/dist/components/v1/modal/Modal.js +7 -7
  70. package/dist/components/v1/modal/ModalKit.js +7 -7
  71. package/dist/components/v1/select-menu/ChannelSelectMenuKit.js +7 -7
  72. package/dist/components/v1/select-menu/MentionableSelectMenuKit.js +7 -7
  73. package/dist/components/v1/select-menu/RoleSelectMenuKit.js +7 -7
  74. package/dist/components/v1/select-menu/SelectMenu.js +7 -7
  75. package/dist/components/v1/select-menu/StringSelectMenuKit.js +7 -7
  76. package/dist/components/v1/select-menu/UserSelectMenuKit.js +7 -7
  77. package/dist/config/config.d.ts +3 -3
  78. package/dist/config/config.js +7 -7
  79. package/dist/config/default.d.ts +2 -2
  80. package/dist/config/default.js +7 -7
  81. package/dist/config/loader.d.ts +2 -2
  82. package/dist/config/loader.js +7 -7
  83. package/dist/config/types.d.ts +2 -2
  84. package/dist/config/utils.d.ts +2 -2
  85. package/dist/{config-CcWJ-vz5.d.ts → config-ClEaYnf1.d.ts} +2 -2
  86. package/dist/constants-4oxxvaJA.js.map +1 -1
  87. package/dist/constants-B5_Ta7PR.js.map +1 -1
  88. package/dist/{constants-DrjIvQd6.d.ts → constants-D8PMA9on.d.ts} +1 -1
  89. package/dist/{constants-CUND8XkG.js → constants-DxfYtA6t.js} +1 -1
  90. package/dist/{constants-CUND8XkG.js.map → constants-DxfYtA6t.js.map} +1 -1
  91. package/dist/container-z621KfH5.js.map +1 -1
  92. package/dist/context/async-context.d.ts +2 -2
  93. package/dist/context/async-context.js +7 -7
  94. package/dist/context/environment.d.ts +2 -2
  95. package/dist/context/environment.js +7 -7
  96. package/dist/dotprops-C_4L7RPD.js.map +1 -1
  97. package/dist/element-Bak9llw_.js.map +1 -1
  98. package/dist/env-_68PRRoA.js.map +1 -1
  99. package/dist/error-codes-B4TyW4Ct.d.ts +54 -0
  100. package/dist/{error-codes-C-ViHyu-.js → error-codes-Ds0bnPvT.js} +2 -2
  101. package/dist/error-codes-Ds0bnPvT.js.map +1 -0
  102. package/dist/events/CommandKitEventsChannel.d.ts +2 -2
  103. package/dist/{feature-flags-Cxl9JtVG.js → feature-flags-Dxi9TI2e.js} +5 -5
  104. package/dist/{feature-flags-Cxl9JtVG.js.map → feature-flags-Dxi9TI2e.js.map} +1 -1
  105. package/dist/file-DVZC0QXI.js.map +1 -1
  106. package/dist/flags/FlagProvider.d.ts +2 -2
  107. package/dist/flags/FlagProvider.js.map +1 -1
  108. package/dist/flags/feature-flags.d.ts +2 -2
  109. package/dist/flags/feature-flags.js +8 -8
  110. package/dist/flags/store.d.ts +2 -2
  111. package/dist/helpers-BUlN3lIz.js.map +1 -1
  112. package/dist/index.d.ts +9 -8
  113. package/dist/index.js +22 -15
  114. package/dist/index.js.map +1 -0
  115. package/dist/{init-DTBFphOg.js → init-CrFvqdxZ.js} +2 -2
  116. package/dist/{init-DTBFphOg.js.map → init-CrFvqdxZ.js.map} +1 -1
  117. package/dist/kv/constants.d.ts +1 -1
  118. package/dist/kv/kv.d.ts +2 -2
  119. package/dist/kv/kv.js.map +1 -1
  120. package/dist/kv/serde.d.ts +2 -2
  121. package/dist/logger/DefaultLogger.d.ts +2 -2
  122. package/dist/logger/DefaultLogger.js +7 -7
  123. package/dist/logger/ILogger.d.ts +1 -1
  124. package/dist/logger/Logger.d.ts +2 -2
  125. package/dist/logger/Logger.js +7 -7
  126. package/dist/logger/NoopLogger.d.ts +41 -11
  127. package/dist/logger/NoopLogger.js +5 -25
  128. package/dist/logger/NoopLogger.js.map +1 -1
  129. package/dist/media-gallery-CIKypjbJ.js.map +1 -1
  130. package/dist/plugins/CompilerPlugin.d.ts +2 -2
  131. package/dist/plugins/PluginCommon.d.ts +2 -2
  132. package/dist/plugins/RuntimePlugin.d.ts +2 -2
  133. package/dist/plugins/index.d.ts +2 -2
  134. package/dist/plugins/index.js +7 -7
  135. package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.d.ts +2 -2
  136. package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js +7 -7
  137. package/dist/plugins/plugin-runtime/CompilerPluginRuntime.d.ts +2 -2
  138. package/dist/plugins/plugin-runtime/CompilerPluginRuntime.js +7 -7
  139. package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.d.ts +2 -2
  140. package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js +7 -7
  141. package/dist/plugins/plugin-runtime/builtin/MacroPlugin.d.ts +2 -2
  142. package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js +7 -7
  143. package/dist/plugins/plugin-runtime/runtime.d.ts +2 -2
  144. package/dist/plugins/types.d.ts +2 -2
  145. package/dist/resolve-file-url-DHTQj2mU.js.map +1 -1
  146. package/dist/section-CuYr0Inu.js.map +1 -1
  147. package/dist/separator-DLdWBjSN.js.map +1 -1
  148. package/dist/{serde-BUDI03pX.d.ts → serde-BYaKrsOV.d.ts} +2 -2
  149. package/dist/serde-CHySNpFr.js.map +1 -1
  150. package/dist/{signals-BQbEfy3X.d.ts → signals-SHg7J1U_.d.ts} +4 -7
  151. package/dist/{signals-DHdYrd-n.js → signals-r7qPAvOR.js} +12 -15
  152. package/dist/signals-r7qPAvOR.js.map +1 -0
  153. package/dist/store-CiqLHedg.js.map +1 -1
  154. package/dist/text-display--p2-BoUa.js.map +1 -1
  155. package/dist/type-checker-1Iu1jJcy.js.map +1 -1
  156. package/dist/types-package-DrnIdWLg.js.map +1 -1
  157. package/dist/types.d.ts +3 -3
  158. package/dist/utils/dev-hooks.d.ts +2 -2
  159. package/dist/utils/dev-hooks.js +7 -7
  160. package/dist/utils/error-codes.d.ts +2 -54
  161. package/dist/utils/error-codes.js +1 -1
  162. package/dist/utils/useful-stuff/async-queue.js.map +1 -1
  163. package/dist/utils/useful-stuff/mutex.js.map +1 -1
  164. package/dist/utils/useful-stuff/ratelimiter.js.map +1 -1
  165. package/dist/utils/useful-stuff/semaphore.js.map +1 -1
  166. package/dist/utils/utilities.js +7 -7
  167. package/dist/utils/warn-unstable.js.map +1 -1
  168. package/dist/utils-BnXM4eKk.js.map +1 -1
  169. package/dist/utils-DCSnVAZ6.js.map +1 -1
  170. package/dist/{version-Df1T7P2K.js → version-BoHnO-Go.js} +2 -2
  171. package/dist/{version-Df1T7P2K.js.map → version-BoHnO-Go.js.map} +1 -1
  172. package/dist/version.js +1 -1
  173. package/package.json +60 -59
  174. package/dist/ILogger-DBGON5wx.d.ts +0 -34
  175. package/dist/build-DXl8uEv4.js.map +0 -1
  176. package/dist/commandkit-DMEW0kJg.js.map +0 -1
  177. package/dist/error-codes-C-ViHyu-.js.map +0 -1
  178. package/dist/signals-DHdYrd-n.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"mutex.js","names":[],"sources":["../../../src/utils/useful-stuff/mutex.ts"],"sourcesContent":["/**\n * Async mutex implementation for coordinating access to shared resources.\n * Provides mutual exclusion to ensure only one task can access a resource at a time.\n */\n\n/**\n * Interface for mutex storage implementations.\n * Provides methods to store, retrieve, and delete mutex lock data.\n */\nexport interface MutexStorage {\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n isLocked(key: string): Promise<boolean>;\n}\n\n/**\n * Configuration options for mutex\n */\nexport interface MutexOptions {\n /** Default timeout in milliseconds for lock acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting mutex data. Default: {@link MemoryMutexStorage} */\n storage?: MutexStorage;\n}\n\n/**\n * In-memory storage implementation for mutex locks.\n * Suitable for single-instance applications.\n */\nexport class MemoryMutexStorage implements MutexStorage {\n private readonly locks = new Map<\n string,\n { holder: string; acquiredAt: number }\n >();\n\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const holder = this.generateHolderId();\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Lock acquisition was aborted');\n }\n\n if (!this.locks.has(key)) {\n this.locks.set(key, { holder, acquiredAt: Date.now() });\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n async release(key: string): Promise<void> {\n this.locks.delete(key);\n }\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n async isLocked(key: string): Promise<boolean> {\n return this.locks.has(key);\n }\n\n private generateHolderId(): string {\n return `holder_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async mutex implementation that provides mutual exclusion for shared resources.\n * Ensures only one task can access a protected resource at a time.\n */\nexport class Mutex {\n private storage: MutexStorage;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new mutex instance\n * @param options - Configuration options for the mutex\n */\n public constructor(options: MutexOptions = {}) {\n this.storage = options.storage || new MemoryMutexStorage();\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the mutex\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: MutexStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the mutex\n * @returns The storage implementation\n */\n public getStorage(): MutexStorage {\n return this.storage;\n }\n\n /**\n * Acquires a lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases the lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Checks if a lock is currently held for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n public async isLocked(key: string): Promise<boolean> {\n return this.storage.isLocked(key);\n }\n\n /**\n * Executes a function with exclusive access to the resource\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if lock acquisition fails or function execution fails\n */\n public async withLock<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire lock for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the mutex\n * @returns Object containing the current timeout value\n */\n public getConfig(): Omit<MutexOptions, 'storage'> {\n return {\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default mutex instance for global use\n */\nexport const defaultMutex = new Mutex();\n\n/**\n * Convenience function to execute a function with exclusive access using the default mutex.\n *\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withMutex('shared-resource', async () => {\n * // This code runs with exclusive access\n * return await updateSharedResource();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the lock acquisition\n * ```\n */\nexport async function withMutex<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultMutex.withLock(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new mutex instance with the specified configuration\n * @param options - Configuration options for the mutex\n * @returns New Mutex instance\n *\n * @example\n * ```typescript\n * const mutex = createMutex({\n * timeout: 60000,\n * storage: new RedisMutexStorage()\n * });\n * ```\n */\nexport function createMutex(options: MutexOptions): Mutex {\n return new Mutex(options);\n}\n\n/**\n * Acquires a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\nexport async function acquireLock(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultMutex.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\nexport async function releaseLock(key: string): Promise<void> {\n return defaultMutex.release(key);\n}\n\n/**\n * Checks if a lock is held using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\nexport async function isLocked(key: string): Promise<boolean>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,SAAS,KAA+B;AACnD,SAAO,KAAK,QAAQ,SAAS;CAC/B;;;;;;;;;;CAWA,MAAa,SACb,KACA,IACA,SACA,QACa;EACX,MAAM,WAAW,MAAM,KAAK,QAAQ,KAAK,SAAS;AAClD,MAAI,CAAC,SACH,OAAM,IAAI,MAAM,mCAAmC;AAGrD,MAAI;AACF,UAAO,MAAM;EACd,UAAS;AACR,SAAM,KAAK,QAAQ;EACrB;CACF;;;;;CAMA,AAAO,YAA2C;AAChD,SAAO,EACL,SAAS,KAAK,gBACf;CACH;AACF;;;;AAKA,MAAa,eAAe,IAAI;;;;;;;;;;;;;;;;;;;;AAqBhC,eAAsB,UACtB,KACA,IACA,SACA,QACa;AACX,QAAO,aAAa,SAAS,KAAK,IAAI,SAAS;AACjD;;;;;;;;;;;;;;AAeA,SAAgB,YAAY,SAA8B;AACxD,QAAO,IAAI,MAAM;AACnB;;;;;;;;AASA,eAAsB,YACtB,KACA,SACA,QACmB;AACjB,QAAO,aAAa,QAAQ,KAAK,SAAS;AAC5C;;;;;;AAOA,eAAsB,YAAY,KAA4B;AAC5D,QAAO,aAAa,QAAQ;AAC9B;;;;;;AAOA,eAAsB,SAAS,KAA+B;AAC5D,QAAO,aAAa,SAAS;AAC/B"}
1
+ {"version":3,"file":"mutex.js","names":[],"sources":["../../../src/utils/useful-stuff/mutex.ts"],"sourcesContent":["/**\n * Async mutex implementation for coordinating access to shared resources.\n * Provides mutual exclusion to ensure only one task can access a resource at a time.\n */\n\n/**\n * Interface for mutex storage implementations.\n * Provides methods to store, retrieve, and delete mutex lock data.\n */\nexport interface MutexStorage {\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n isLocked(key: string): Promise<boolean>;\n}\n\n/**\n * Configuration options for mutex\n */\nexport interface MutexOptions {\n /** Default timeout in milliseconds for lock acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting mutex data. Default: {@link MemoryMutexStorage} */\n storage?: MutexStorage;\n}\n\n/**\n * In-memory storage implementation for mutex locks.\n * Suitable for single-instance applications.\n */\nexport class MemoryMutexStorage implements MutexStorage {\n private readonly locks = new Map<\n string,\n { holder: string; acquiredAt: number }\n >();\n\n /**\n * Attempts to acquire a lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for the lock\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout or already locked\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const holder = this.generateHolderId();\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Lock acquisition was aborted');\n }\n\n if (!this.locks.has(key)) {\n this.locks.set(key, { holder, acquiredAt: Date.now() });\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases the lock for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n async release(key: string): Promise<void> {\n this.locks.delete(key);\n }\n\n /**\n * Checks if a lock is currently held for a given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n async isLocked(key: string): Promise<boolean> {\n return this.locks.has(key);\n }\n\n private generateHolderId(): string {\n return `holder_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async mutex implementation that provides mutual exclusion for shared resources.\n * Ensures only one task can access a protected resource at a time.\n */\nexport class Mutex {\n private storage: MutexStorage;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new mutex instance\n * @param options - Configuration options for the mutex\n */\n public constructor(options: MutexOptions = {}) {\n this.storage = options.storage || new MemoryMutexStorage();\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the mutex\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: MutexStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the mutex\n * @returns The storage implementation\n */\n public getStorage(): MutexStorage {\n return this.storage;\n }\n\n /**\n * Acquires a lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases the lock for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Checks if a lock is currently held for the given key\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\n public async isLocked(key: string): Promise<boolean> {\n return this.storage.isLocked(key);\n }\n\n /**\n * Executes a function with exclusive access to the resource\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if lock acquisition fails or function execution fails\n */\n public async withLock<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire lock for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the mutex\n * @returns Object containing the current timeout value\n */\n public getConfig(): Omit<MutexOptions, 'storage'> {\n return {\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default mutex instance for global use\n */\nexport const defaultMutex = new Mutex();\n\n/**\n * Convenience function to execute a function with exclusive access using the default mutex.\n *\n * @param key - The unique identifier for the mutex lock\n * @param fn - The function to execute with exclusive access\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the lock acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withMutex('shared-resource', async () => {\n * // This code runs with exclusive access\n * return await updateSharedResource();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the lock acquisition\n * ```\n */\nexport async function withMutex<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultMutex.withLock(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new mutex instance with the specified configuration\n * @param options - Configuration options for the mutex\n * @returns New Mutex instance\n *\n * @example\n * ```typescript\n * const mutex = createMutex({\n * timeout: 60000,\n * storage: new RedisMutexStorage()\n * });\n * ```\n */\nexport function createMutex(options: MutexOptions): Mutex {\n return new Mutex(options);\n}\n\n/**\n * Acquires a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @param timeout - Optional timeout in milliseconds for lock acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if lock was acquired, false if timeout\n */\nexport async function acquireLock(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultMutex.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a lock using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise that resolves when the lock is released\n */\nexport async function releaseLock(key: string): Promise<void> {\n return defaultMutex.release(key);\n}\n\n/**\n * Checks if a lock is held using the default mutex\n * @param key - The unique identifier for the mutex lock\n * @returns Promise resolving to true if the lock is held, false otherwise\n */\nexport async function isLocked(key: string): Promise<boolean> {\n return defaultMutex.isLocked(key);\n}\n"],"mappings":";;;;;;AAoDA,IAAa,qBAAb,MAAwD;CACtD,AAAiB,wBAAQ,IAAI;;;;;;;;CAY7B,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,SAAS,KAAK;EACpB,MAAM,YAAY,KAAK;AAEvB,SAAO,KAAK,QAAQ,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM;AAGlB,OAAI,CAAC,KAAK,MAAM,IAAI,MAAM;AACxB,SAAK,MAAM,IAAI,KAAK;KAAE;KAAQ,YAAY,KAAK;;AAC/C,WAAO;;AAET,SAAM,KAAK,MAAM;;AAGnB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;AACxC,OAAK,MAAM,OAAO;;;;;;;CAQpB,MAAM,SAAS,KAA+B;AAC5C,SAAO,KAAK,MAAM,IAAI;;CAGxB,AAAQ,mBAA2B;AACjC,SAAO,UAAU,KAAK,MAAM,GAAG,KAAK,SAAS,SAAS,IAAI,OAAO,GAAG;;CAGtE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS;;;;;;;AAQxD,IAAa,QAAb,MAAmB;CACjB,AAAQ;CACR,AAAiB;;;;;CAMjB,AAAO,YAAY,UAAwB,IAAI;AAC7C,OAAK,UAAU,QAAQ,WAAW,IAAI;AACtC,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAAuB;AACvC,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA2B;AAChC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AACjB,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB;;;;;;;CAQnE,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ;;;;;;;CAQ9B,MAAa,SAAS,KAA+B;AACnD,SAAO,KAAK,QAAQ,SAAS;;;;;;;;;;;CAY/B,MAAa,SACb,KACA,IACA,SACA,QACa;EACX,MAAM,WAAW,MAAM,KAAK,QAAQ,KAAK,SAAS;AAClD,MAAI,CAAC,SACH,OAAM,IAAI,MAAM,mCAAmC;AAGrD,MAAI;AACF,UAAO,MAAM;YACL;AACR,SAAM,KAAK,QAAQ;;;;;;;CAQvB,AAAO,YAA2C;AAChD,SAAO,EACL,SAAS,KAAK;;;;;;AAQpB,MAAa,eAAe,IAAI;;;;;;;;;;;;;;;;;;;;AAqBhC,eAAsB,UACtB,KACA,IACA,SACA,QACa;AACX,QAAO,aAAa,SAAS,KAAK,IAAI,SAAS;;;;;;;;;;;;;;;AAgBjD,SAAgB,YAAY,SAA8B;AACxD,QAAO,IAAI,MAAM;;;;;;;;;AAUnB,eAAsB,YACtB,KACA,SACA,QACmB;AACjB,QAAO,aAAa,QAAQ,KAAK,SAAS;;;;;;;AAQ5C,eAAsB,YAAY,KAA4B;AAC5D,QAAO,aAAa,QAAQ;;;;;;;AAQ9B,eAAsB,SAAS,KAA+B;AAC5D,QAAO,aAAa,SAAS"}
@@ -1 +1 @@
1
- {"version":3,"file":"ratelimiter.js","names":[],"sources":["../../../src/utils/useful-stuff/ratelimiter.ts"],"sourcesContent":["/**\n * Default timeout interval for rate limiting in milliseconds\n */\nexport const DEFAULT_TIMEOUT = 60000;\n\n/**\n * Default maximum number of requests allowed per interval\n */\nexport const DEFAULT_MAX_REQUESTS = 10;\n\n/**\n * Interface for rate limit storage implementations.\n * Provides methods to store, retrieve, and delete rate limit data.\n */\nexport interface RateLimitStorage {\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count\n */\n get(key: string): Promise<number>;\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves when the value is stored\n */\n set(key: string, value: number): Promise<void>;\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the entry is deleted\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Configuration options for rate limiting\n */\nexport interface RateLimitOptions {\n /** Maximum number of requests allowed per interval. Default: 10 */\n maxRequests?: number;\n /** Time interval in milliseconds for the rate limit window. Default: 60000 */\n interval?: number;\n /** Storage implementation for persisting rate limit data. Default: {@link MemoryRateLimitStorage} */\n storage?: RateLimitStorage;\n}\n\n/**\n * In-memory storage implementation for rate limiting.\n * Suitable for single-instance applications.\n */\nexport class MemoryRateLimitStorage implements RateLimitStorage {\n private readonly store = new Map<string, number>();\n\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count or 0 if not found\n */\n async get(key: string): Promise<number> {\n return this.store.get(key) || 0;\n }\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves immediately\n */\n async set(key: string, value: number): Promise<void> {\n this.store.set(key, value);\n }\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves immediately\n */\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n}\n\n/**\n * Rate limiter implementation that enforces request limits per key.\n * Supports configurable request limits and time intervals.\n */\nexport class RateLimiter {\n private readonly limits: Map<string, number> = new Map();\n private readonly lastReset: Map<string, number> = new Map();\n private readonly resetInterval: number;\n\n /**\n * Creates a new rate limiter instance\n * @param maxRequests - Maximum number of requests allowed per interval (default: 10)\n * @param interval - Time interval in milliseconds for the rate limit window (default: 60000)\n * @param storage - Optional storage implementation (default: MemoryRateLimitStorage)\n */\n public constructor(\n private readonly maxRequests: number = DEFAULT_MAX_REQUESTS,\n private readonly interval: number = DEFAULT_TIMEOUT,\n private storage: RateLimitStorage = new MemoryRateLimitStorage(),\n ) {\n this.resetInterval = interval;\n }\n\n /**\n * Sets the storage implementation for the rate limiter\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: RateLimitStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the rate limiter\n * @returns The storage implementation\n */\n public getStorage(): RateLimitStorage {\n return this.storage;\n }\n\n /**\n * Checks if a request is allowed for the given key and increments the counter if allowed\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n */\n public async limit(key: string): Promise<boolean> {\n const now = Date.now();\n const lastReset = this.lastReset.get(key) || 0;\n const timeSinceReset = now - lastReset;\n\n // Reset counter if interval has passed\n if (timeSinceReset > this.resetInterval) {\n await this.storage.delete(key);\n this.lastReset.set(key, now);\n this.limits.set(key, 0);\n }\n\n // Get current count from storage\n const currentCount = await this.storage.get(key);\n\n // Check if limit exceeded\n if (currentCount >= this.maxRequests) {\n return false;\n }\n\n // Increment counter\n const newCount = currentCount + 1;\n await this.storage.set(key, newCount);\n this.limits.set(key, newCount);\n\n return true;\n }\n\n /**\n * Gets the remaining requests allowed for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\n public async getRemaining(key: string): Promise<number> {\n const currentCount = await this.storage.get(key);\n return Math.max(0, this.maxRequests - currentCount);\n }\n\n /**\n * Gets the time until the rate limit resets for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset, or 0 if no limit is active\n */\n public async getResetTime(key: string): Promise<number> {\n const lastReset = this.lastReset.get(key) || 0;\n const now = Date.now();\n const timeSinceReset = now - lastReset;\n\n if (timeSinceReset >= this.resetInterval) {\n return 0;\n }\n\n return this.resetInterval - timeSinceReset;\n }\n\n /**\n * Resets the rate limit for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\n public async reset(key: string): Promise<void> {\n await this.storage.delete(key);\n this.limits.delete(key);\n this.lastReset.delete(key);\n }\n\n /**\n * Gets the current configuration of the rate limiter\n * @returns Object containing the current maxRequests and interval values\n */\n public getConfig(): Omit<RateLimitOptions, 'storage'> {\n return {\n maxRequests: this.maxRequests,\n interval: this.interval,\n };\n }\n}\n\n/**\n * Default rate limiter instance for global use\n */\nexport const defaultRateLimiter = new RateLimiter();\n\n/**\n * Convenience function to check if a request is allowed for a given key.\n * Uses the default rate limiter instance.\n *\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n *\n * @example\n * ```typescript\n * const allowed = await ratelimit('user:123');\n * // update the default rate limiter config\n * import { defaultRateLimiter } from 'commandkit/ratelimit';\n *\n * // update max allowed requests\n * defaultRateLimiter.setMaxRequests(10);\n *\n * // update the timeout interval\n * defaultRateLimiter.setInterval(30000);\n *\n * // update the storage implementation\n * defaultRateLimiter.setStorage(new RedisStorage());\n * ```\n */\nexport async function ratelimit(key: string): Promise<boolean> {\n return defaultRateLimiter.limit(key);\n}\n\n/**\n * Creates a new rate limiter instance with the specified configuration\n * @param options - Configuration options for the rate limiter\n * @returns New RateLimiter instance\n *\n * @example\n * ```typescript\n * const limiter = createRateLimiter({\n * maxRequests: 5,\n * interval: 30000,\n * storage: new CustomStorage()\n * });\n * ```\n */\nexport function createRateLimiter(options: RateLimitOptions): RateLimiter {\n return new RateLimiter(\n options.maxRequests,\n options.interval,\n options.storage,\n );\n}\n\n/**\n * Gets the remaining requests for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\nexport async function getRemainingRequests(key: string): Promise<number> {\n return defaultRateLimiter.getRemaining(key);\n}\n\n/**\n * Gets the reset time for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset\n */\nexport async function getResetTime(key: string): Promise<number> {\n return defaultRateLimiter.getResetTime(key);\n}\n\n/**\n * Resets the rate limit for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\nexport async function resetRateLimit(key: string): Promise<void> {\n return defaultRateLimiter.reset(key);\n}\n"],"mappings":";;;;;AAGA,MAAa,kBAAkB;;;;AAK/B,MAAa,uBAAuB;;;;;AA8CpC,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,wBAAQ,IAAI;;;;;;CAO7B,MAAM,IAAI,KAA8B;AACtC,SAAO,KAAK,MAAM,IAAI,QAAQ;CAChC;;;;;;;CAQA,MAAM,IAAI,KAAa,OAA8B;AACnD,OAAK,MAAM,IAAI,KAAK;CACtB;;;;;;CAOA,MAAM,OAAO,KAA4B;AACvC,OAAK,MAAM,OAAO;CACpB;AACF;;;;;AAMA,IAAa,cAAb,MAAyB;CACvB,AAAiB,yBAA8B,IAAI;CACnD,AAAiB,4BAAiC,IAAI;CACtD,AAAiB;;;;;;;CAQjB,AAAO,YACP,AAAiB,cAAsB,sBACvC,AAAiB,WAAmB,iBACpC,AAAQ,UAA4B,IAAI,0BACxC;EAHiB;EACA;EACT;AAEN,OAAK,gBAAgB;CACvB;;;;;CAMA,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;CACjB;;;;;CAMA,AAAO,aAA+B;AACpC,SAAO,KAAK;CACd;;;;;;CAOA,MAAa,MAAM,KAA+B;EAChD,MAAM,MAAM,KAAK;EACjB,MAAM,YAAY,KAAK,UAAU,IAAI,QAAQ;EAC7C,MAAM,iBAAiB,MAAM;AAG7B,MAAI,iBAAiB,KAAK,eAAe;AACvC,SAAM,KAAK,QAAQ,OAAO;AAC1B,QAAK,UAAU,IAAI,KAAK;AACxB,QAAK,OAAO,IAAI,KAAK;EACvB;EAGA,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI;AAG5C,MAAI,gBAAgB,KAAK,YACvB,QAAO;EAIT,MAAM,WAAW,eAAe;AAChC,QAAM,KAAK,QAAQ,IAAI,KAAK;AAC5B,OAAK,OAAO,IAAI,KAAK;AAErB,SAAO;CACT;;;;;;CAOA,MAAa,aAAa,KAA8B;EACtD,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI;AAC5C,SAAO,KAAK,IAAI,GAAG,KAAK,cAAc;CACxC;;;;;;CAOA,MAAa,aAAa,KAA8B;EACtD,MAAM,YAAY,KAAK,UAAU,IAAI,QAAQ;EAC7C,MAAM,MAAM,KAAK;EACjB,MAAM,iBAAiB,MAAM;AAE7B,MAAI,kBAAkB,KAAK,cACzB,QAAO;AAGT,SAAO,KAAK,gBAAgB;CAC9B;;;;;;CAOA,MAAa,MAAM,KAA4B;AAC7C,QAAM,KAAK,QAAQ,OAAO;AAC1B,OAAK,OAAO,OAAO;AACnB,OAAK,UAAU,OAAO;CACxB;;;;;CAMA,AAAO,YAA+C;AACpD,SAAO;GACL,aAAa,KAAK;GAClB,UAAU,KAAK;GAChB;CACH;AACF;;;;AAKA,MAAa,qBAAqB,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBtC,eAAsB,UAAU,KAA+B;AAC7D,QAAO,mBAAmB,MAAM;AAClC;;;;;;;;;;;;;;;AAgBA,SAAgB,kBAAkB,SAAwC;AACxE,QAAO,IAAI,YACT,QAAQ,aACR,QAAQ,UACR,QAAQ;AAEZ;;;;;;AAOA,eAAsB,qBAAqB,KAA8B;AACvE,QAAO,mBAAmB,aAAa;AACzC;;;;;;AAOA,eAAsB,aAAa,KAA8B;AAC/D,QAAO,mBAAmB,aAAa;AACzC;;;;;;AAOA,eAAsB,eAAe,KAA4B;AAC/D,QAAO,mBAAmB,MAAM;AAClC"}
1
+ {"version":3,"file":"ratelimiter.js","names":[],"sources":["../../../src/utils/useful-stuff/ratelimiter.ts"],"sourcesContent":["/**\n * Default timeout interval for rate limiting in milliseconds\n */\nexport const DEFAULT_TIMEOUT = 60000;\n\n/**\n * Default maximum number of requests allowed per interval\n */\nexport const DEFAULT_MAX_REQUESTS = 10;\n\n/**\n * Interface for rate limit storage implementations.\n * Provides methods to store, retrieve, and delete rate limit data.\n */\nexport interface RateLimitStorage {\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count\n */\n get(key: string): Promise<number>;\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves when the value is stored\n */\n set(key: string, value: number): Promise<void>;\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the entry is deleted\n */\n delete(key: string): Promise<void>;\n}\n\n/**\n * Configuration options for rate limiting\n */\nexport interface RateLimitOptions {\n /** Maximum number of requests allowed per interval. Default: 10 */\n maxRequests?: number;\n /** Time interval in milliseconds for the rate limit window. Default: 60000 */\n interval?: number;\n /** Storage implementation for persisting rate limit data. Default: {@link MemoryRateLimitStorage} */\n storage?: RateLimitStorage;\n}\n\n/**\n * In-memory storage implementation for rate limiting.\n * Suitable for single-instance applications.\n */\nexport class MemoryRateLimitStorage implements RateLimitStorage {\n private readonly store = new Map<string, number>();\n\n /**\n * Retrieves the current request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the current request count or 0 if not found\n */\n async get(key: string): Promise<number> {\n return this.store.get(key) || 0;\n }\n\n /**\n * Sets the request count for a given key\n * @param key - The unique identifier for the rate limit entry\n * @param value - The request count to store\n * @returns Promise that resolves immediately\n */\n async set(key: string, value: number): Promise<void> {\n this.store.set(key, value);\n }\n\n /**\n * Deletes the rate limit entry for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves immediately\n */\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n}\n\n/**\n * Rate limiter implementation that enforces request limits per key.\n * Supports configurable request limits and time intervals.\n */\nexport class RateLimiter {\n private readonly limits: Map<string, number> = new Map();\n private readonly lastReset: Map<string, number> = new Map();\n private readonly resetInterval: number;\n\n /**\n * Creates a new rate limiter instance\n * @param maxRequests - Maximum number of requests allowed per interval (default: 10)\n * @param interval - Time interval in milliseconds for the rate limit window (default: 60000)\n * @param storage - Optional storage implementation (default: MemoryRateLimitStorage)\n */\n public constructor(\n private readonly maxRequests: number = DEFAULT_MAX_REQUESTS,\n private readonly interval: number = DEFAULT_TIMEOUT,\n private storage: RateLimitStorage = new MemoryRateLimitStorage(),\n ) {\n this.resetInterval = interval;\n }\n\n /**\n * Sets the storage implementation for the rate limiter\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: RateLimitStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the rate limiter\n * @returns The storage implementation\n */\n public getStorage(): RateLimitStorage {\n return this.storage;\n }\n\n /**\n * Checks if a request is allowed for the given key and increments the counter if allowed\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n */\n public async limit(key: string): Promise<boolean> {\n const now = Date.now();\n const lastReset = this.lastReset.get(key) || 0;\n const timeSinceReset = now - lastReset;\n\n // Reset counter if interval has passed\n if (timeSinceReset > this.resetInterval) {\n await this.storage.delete(key);\n this.lastReset.set(key, now);\n this.limits.set(key, 0);\n }\n\n // Get current count from storage\n const currentCount = await this.storage.get(key);\n\n // Check if limit exceeded\n if (currentCount >= this.maxRequests) {\n return false;\n }\n\n // Increment counter\n const newCount = currentCount + 1;\n await this.storage.set(key, newCount);\n this.limits.set(key, newCount);\n\n return true;\n }\n\n /**\n * Gets the remaining requests allowed for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\n public async getRemaining(key: string): Promise<number> {\n const currentCount = await this.storage.get(key);\n return Math.max(0, this.maxRequests - currentCount);\n }\n\n /**\n * Gets the time until the rate limit resets for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset, or 0 if no limit is active\n */\n public async getResetTime(key: string): Promise<number> {\n const lastReset = this.lastReset.get(key) || 0;\n const now = Date.now();\n const timeSinceReset = now - lastReset;\n\n if (timeSinceReset >= this.resetInterval) {\n return 0;\n }\n\n return this.resetInterval - timeSinceReset;\n }\n\n /**\n * Resets the rate limit for a given key\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\n public async reset(key: string): Promise<void> {\n await this.storage.delete(key);\n this.limits.delete(key);\n this.lastReset.delete(key);\n }\n\n /**\n * Gets the current configuration of the rate limiter\n * @returns Object containing the current maxRequests and interval values\n */\n public getConfig(): Omit<RateLimitOptions, 'storage'> {\n return {\n maxRequests: this.maxRequests,\n interval: this.interval,\n };\n }\n}\n\n/**\n * Default rate limiter instance for global use\n */\nexport const defaultRateLimiter = new RateLimiter();\n\n/**\n * Convenience function to check if a request is allowed for a given key.\n * Uses the default rate limiter instance.\n *\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to true if the request is allowed, false if rate limited\n *\n * @example\n * ```typescript\n * const allowed = await ratelimit('user:123');\n * // update the default rate limiter config\n * import { defaultRateLimiter } from 'commandkit/ratelimit';\n *\n * // update max allowed requests\n * defaultRateLimiter.setMaxRequests(10);\n *\n * // update the timeout interval\n * defaultRateLimiter.setInterval(30000);\n *\n * // update the storage implementation\n * defaultRateLimiter.setStorage(new RedisStorage());\n * ```\n */\nexport async function ratelimit(key: string): Promise<boolean> {\n return defaultRateLimiter.limit(key);\n}\n\n/**\n * Creates a new rate limiter instance with the specified configuration\n * @param options - Configuration options for the rate limiter\n * @returns New RateLimiter instance\n *\n * @example\n * ```typescript\n * const limiter = createRateLimiter({\n * maxRequests: 5,\n * interval: 30000,\n * storage: new CustomStorage()\n * });\n * ```\n */\nexport function createRateLimiter(options: RateLimitOptions): RateLimiter {\n return new RateLimiter(\n options.maxRequests,\n options.interval,\n options.storage,\n );\n}\n\n/**\n * Gets the remaining requests for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the number of remaining requests\n */\nexport async function getRemainingRequests(key: string): Promise<number> {\n return defaultRateLimiter.getRemaining(key);\n}\n\n/**\n * Gets the reset time for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise resolving to the time in milliseconds until reset\n */\nexport async function getResetTime(key: string): Promise<number> {\n return defaultRateLimiter.getResetTime(key);\n}\n\n/**\n * Resets the rate limit for a key using the default rate limiter\n * @param key - The unique identifier for the rate limit entry\n * @returns Promise that resolves when the reset is complete\n */\nexport async function resetRateLimit(key: string): Promise<void> {\n return defaultRateLimiter.reset(key);\n}\n"],"mappings":";;;;;AAGA,MAAa,kBAAkB;;;;AAK/B,MAAa,uBAAuB;;;;;AA8CpC,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,wBAAQ,IAAI;;;;;;CAO7B,MAAM,IAAI,KAA8B;AACtC,SAAO,KAAK,MAAM,IAAI,QAAQ;;;;;;;;CAShC,MAAM,IAAI,KAAa,OAA8B;AACnD,OAAK,MAAM,IAAI,KAAK;;;;;;;CAQtB,MAAM,OAAO,KAA4B;AACvC,OAAK,MAAM,OAAO;;;;;;;AAQtB,IAAa,cAAb,MAAyB;CACvB,AAAiB,yBAA8B,IAAI;CACnD,AAAiB,4BAAiC,IAAI;CACtD,AAAiB;;;;;;;CAQjB,AAAO,YACP,AAAiB,cAAsB,sBACvC,AAAiB,WAAmB,iBACpC,AAAQ,UAA4B,IAAI,0BACxC;EAHiB;EACA;EACT;AAEN,OAAK,gBAAgB;;;;;;CAOvB,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;CAQd,MAAa,MAAM,KAA+B;EAChD,MAAM,MAAM,KAAK;EACjB,MAAM,YAAY,KAAK,UAAU,IAAI,QAAQ;EAC7C,MAAM,iBAAiB,MAAM;AAG7B,MAAI,iBAAiB,KAAK,eAAe;AACvC,SAAM,KAAK,QAAQ,OAAO;AAC1B,QAAK,UAAU,IAAI,KAAK;AACxB,QAAK,OAAO,IAAI,KAAK;;EAIvB,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI;AAG5C,MAAI,gBAAgB,KAAK,YACvB,QAAO;EAIT,MAAM,WAAW,eAAe;AAChC,QAAM,KAAK,QAAQ,IAAI,KAAK;AAC5B,OAAK,OAAO,IAAI,KAAK;AAErB,SAAO;;;;;;;CAQT,MAAa,aAAa,KAA8B;EACtD,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI;AAC5C,SAAO,KAAK,IAAI,GAAG,KAAK,cAAc;;;;;;;CAQxC,MAAa,aAAa,KAA8B;EACtD,MAAM,YAAY,KAAK,UAAU,IAAI,QAAQ;EAC7C,MAAM,MAAM,KAAK;EACjB,MAAM,iBAAiB,MAAM;AAE7B,MAAI,kBAAkB,KAAK,cACzB,QAAO;AAGT,SAAO,KAAK,gBAAgB;;;;;;;CAQ9B,MAAa,MAAM,KAA4B;AAC7C,QAAM,KAAK,QAAQ,OAAO;AAC1B,OAAK,OAAO,OAAO;AACnB,OAAK,UAAU,OAAO;;;;;;CAOxB,AAAO,YAA+C;AACpD,SAAO;GACL,aAAa,KAAK;GAClB,UAAU,KAAK;;;;;;;AAQrB,MAAa,qBAAqB,IAAI;;;;;;;;;;;;;;;;;;;;;;;;AAyBtC,eAAsB,UAAU,KAA+B;AAC7D,QAAO,mBAAmB,MAAM;;;;;;;;;;;;;;;;AAiBlC,SAAgB,kBAAkB,SAAwC;AACxE,QAAO,IAAI,YACT,QAAQ,aACR,QAAQ,UACR,QAAQ;;;;;;;AASZ,eAAsB,qBAAqB,KAA8B;AACvE,QAAO,mBAAmB,aAAa;;;;;;;AAQzC,eAAsB,aAAa,KAA8B;AAC/D,QAAO,mBAAmB,aAAa;;;;;;;AAQzC,eAAsB,eAAe,KAA4B;AAC/D,QAAO,mBAAmB,MAAM"}
@@ -1 +1 @@
1
- {"version":3,"file":"semaphore.js","names":[],"sources":["../../../src/utils/useful-stuff/semaphore.ts"],"sourcesContent":["/**\n * Async semaphore implementation for controlling access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\n\n/**\n * Interface for semaphore storage implementations.\n * Provides methods to store, retrieve, and manage semaphore permit data.\n */\nexport interface SemaphoreStorage {\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n getAvailablePermits(key: string): Promise<number>;\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n getTotalPermits(key: string): Promise<number>;\n}\n\n/**\n * Configuration options for semaphore\n */\nexport interface SemaphoreOptions {\n /** Maximum number of concurrent permits allowed. Default: 1 */\n permits?: number;\n /** Default timeout in milliseconds for permit acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting semaphore data. Default: {@link MemorySemaphoreStorage} */\n storage?: SemaphoreStorage;\n}\n\n/**\n * In-memory storage implementation for semaphore permits.\n * Suitable for single-instance applications.\n */\nexport class MemorySemaphoreStorage implements SemaphoreStorage {\n private readonly semaphores = new Map<\n string,\n { total: number; available: number }\n >();\n\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Permit acquisition was aborted');\n }\n\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available > 0) {\n semaphore.available--;\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n async release(key: string): Promise<void> {\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available < semaphore.total) {\n semaphore.available++;\n }\n }\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n async getAvailablePermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.available : 0;\n }\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n async getTotalPermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.total : 0;\n }\n\n /**\n * Initializes a semaphore with the specified number of permits\n * @param key - The unique identifier for the semaphore\n * @param permits - The total number of permits to allocate\n */\n initialize(key: string, permits: number): void {\n this.semaphores.set(key, { total: permits, available: permits });\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async semaphore implementation that controls access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\nexport class Semaphore {\n private storage: SemaphoreStorage;\n private readonly defaultPermits: number;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new semaphore instance\n * @param options - Configuration options for the semaphore\n */\n public constructor(options: SemaphoreOptions = {}) {\n this.storage = options.storage || new MemorySemaphoreStorage();\n this.defaultPermits = options.permits || 1;\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the semaphore\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: SemaphoreStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the semaphore\n * @returns The storage implementation\n */\n public getStorage(): SemaphoreStorage {\n return this.storage;\n }\n\n /**\n * Acquires a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n // Initialize semaphore if it doesn't exist\n if (this.storage instanceof MemorySemaphoreStorage) {\n const totalPermits = await this.storage.getTotalPermits(key);\n if (totalPermits === 0) {\n (this.storage as MemorySemaphoreStorage).initialize(\n key,\n this.defaultPermits,\n );\n }\n }\n\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Gets the number of available permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n public async getAvailablePermits(key: string): Promise<number> {\n return this.storage.getAvailablePermits(key);\n }\n\n /**\n * Gets the total number of permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n public async getTotalPermits(key: string): Promise<number> {\n return this.storage.getTotalPermits(key);\n }\n\n /**\n * Gets the number of acquired permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\n public async getAcquiredPermits(key: string): Promise<number> {\n const total = await this.getTotalPermits(key);\n const available = await this.getAvailablePermits(key);\n return total - available;\n }\n\n /**\n * Executes a function with a permit from the semaphore\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if permit acquisition fails or function execution fails\n */\n public async withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire permit for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the semaphore\n * @returns Object containing the current permits and timeout values\n */\n public getConfig(): Omit<SemaphoreOptions, 'storage'> {\n return {\n permits: this.defaultPermits,\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default semaphore instance for global use\n */\nexport const defaultSemaphore = new Semaphore();\n\n/**\n * Convenience function to execute a function with a permit using the default semaphore.\n *\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withPermit('database-connection', async () => {\n * // This code runs with a permit from the semaphore\n * return await executeDatabaseQuery();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the permit acquisition\n * ```\n */\nexport async function withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultSemaphore.withPermit(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new semaphore instance with the specified configuration\n * @param options - Configuration options for the semaphore\n * @returns New Semaphore instance\n *\n * @example\n * ```typescript\n * const semaphore = createSemaphore({\n * permits: 5,\n * timeout: 60000,\n * storage: new RedisSemaphoreStorage()\n * });\n * ```\n */\nexport function createSemaphore(options: SemaphoreOptions): Semaphore {\n return new Semaphore(options);\n}\n\n/**\n * Acquires a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\nexport async function acquirePermit(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultSemaphore.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\nexport async function releasePermit(key: string): Promise<void> {\n return defaultSemaphore.release(key);\n}\n\n/**\n * Gets the number of available permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\nexport async function getAvailablePermits(key: string): Promise<number> {\n return defaultSemaphore.getAvailablePermits(key);\n}\n\n/**\n * Gets the number of acquired permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\nexport async function getAcquiredPermits(key: string): Promise<number> {\n return defaultSemaphore.getAcquiredPermits(key);\n}\n"],"mappings":";;;;;;AA6DA,IAAa,yBAAb,MAAgE;CAC9D,AAAiB,6BAAa,IAAI;;;;;;;;CAYlC,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,YAAY,KAAK;AAEvB,SAAO,KAAK,QAAQ,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM;GAGlB,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,OAAI,aAAa,UAAU,YAAY,GAAG;AACxC,cAAU;AACV,WAAO;GACT;AACA,SAAM,KAAK,MAAM;EACnB;AAEA,SAAO;CACT;;;;;;CAOA,MAAM,QAAQ,KAA4B;EACxC,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,MAAI,aAAa,UAAU,YAAY,UAAU,MAC/C,WAAU;CAEd;;;;;;CAOA,MAAM,oBAAoB,KAA8B;EACtD,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,SAAO,YAAY,UAAU,YAAY;CAC3C;;;;;;CAOA,MAAM,gBAAgB,KAA8B;EAClD,MAAM,YAAY,KAAK,WAAW,IAAI;AACtC,SAAO,YAAY,UAAU,QAAQ;CACvC;;;;;;CAOA,WAAW,KAAa,SAAuB;AAC7C,OAAK,WAAW,IAAI,KAAK;GAAE,OAAO;GAAS,WAAW;GAAS;CACjE;CAEA,AAAQ,MAAM,IAA2B;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YAA+C;AACpD,SAAO;GACL,SAAS,KAAK;GACd,SAAS,KAAK;GACf;CACH;AACF;;;;AAKA,MAAa,mBAAmB,IAAI;;;;;;;;;;;;;;;;;;;;AAqBpC,eAAsB,WACtB,KACA,IACA,SACA,QACa;AACX,QAAO,iBAAiB,WAAW,KAAK,IAAI,SAAS;AACvD;;;;;;;;;;;;;;;AAgBA,SAAgB,gBAAgB,SAAsC;AACpE,QAAO,IAAI,UAAU;AACvB;;;;;;;;AASA,eAAsB,cACtB,KACA,SACA,QACmB;AACjB,QAAO,iBAAiB,QAAQ,KAAK,SAAS;AAChD;;;;;;AAOA,eAAsB,cAAc,KAA4B;AAC9D,QAAO,iBAAiB,QAAQ;AAClC;;;;;;AAOA,eAAsB,oBAAoB,KAA8B;AACtE,QAAO,iBAAiB,oBAAoB;AAC9C;;;;;;AAOA,eAAsB,mBAAmB,KAA8B;AACrE,QAAO,iBAAiB,mBAAmB;AAC7C"}
1
+ {"version":3,"file":"semaphore.js","names":[],"sources":["../../../src/utils/useful-stuff/semaphore.ts"],"sourcesContent":["/**\n * Async semaphore implementation for controlling access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\n\n/**\n * Interface for semaphore storage implementations.\n * Provides methods to store, retrieve, and manage semaphore permit data.\n */\nexport interface SemaphoreStorage {\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean>;\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n release(key: string): Promise<void>;\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n getAvailablePermits(key: string): Promise<number>;\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n getTotalPermits(key: string): Promise<number>;\n}\n\n/**\n * Configuration options for semaphore\n */\nexport interface SemaphoreOptions {\n /** Maximum number of concurrent permits allowed. Default: 1 */\n permits?: number;\n /** Default timeout in milliseconds for permit acquisition. Default: 30000 */\n timeout?: number;\n /** Storage implementation for persisting semaphore data. Default: {@link MemorySemaphoreStorage} */\n storage?: SemaphoreStorage;\n}\n\n/**\n * In-memory storage implementation for semaphore permits.\n * Suitable for single-instance applications.\n */\nexport class MemorySemaphoreStorage implements SemaphoreStorage {\n private readonly semaphores = new Map<\n string,\n { total: number; available: number }\n >();\n\n /**\n * Attempts to acquire a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout or no permits available\n */\n async acquire(\n key: string,\n timeout: number = 30000,\n signal?: AbortSignal,\n ): Promise<boolean> {\n const startTime = Date.now();\n\n while (Date.now() - startTime < timeout) {\n // Check if aborted\n if (signal?.aborted) {\n throw new Error('Permit acquisition was aborted');\n }\n\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available > 0) {\n semaphore.available--;\n return true;\n }\n await this.delay(10);\n }\n\n return false;\n }\n\n /**\n * Releases a permit for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n async release(key: string): Promise<void> {\n const semaphore = this.semaphores.get(key);\n if (semaphore && semaphore.available < semaphore.total) {\n semaphore.available++;\n }\n }\n\n /**\n * Gets the number of available permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n async getAvailablePermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.available : 0;\n }\n\n /**\n * Gets the total number of permits for a given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n async getTotalPermits(key: string): Promise<number> {\n const semaphore = this.semaphores.get(key);\n return semaphore ? semaphore.total : 0;\n }\n\n /**\n * Initializes a semaphore with the specified number of permits\n * @param key - The unique identifier for the semaphore\n * @param permits - The total number of permits to allocate\n */\n initialize(key: string, permits: number): void {\n this.semaphores.set(key, { total: permits, available: permits });\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Async semaphore implementation that controls access to a limited pool of resources.\n * Allows a specified number of concurrent operations while blocking additional requests.\n */\nexport class Semaphore {\n private storage: SemaphoreStorage;\n private readonly defaultPermits: number;\n private readonly defaultTimeout: number;\n\n /**\n * Creates a new semaphore instance\n * @param options - Configuration options for the semaphore\n */\n public constructor(options: SemaphoreOptions = {}) {\n this.storage = options.storage || new MemorySemaphoreStorage();\n this.defaultPermits = options.permits || 1;\n this.defaultTimeout = options.timeout || 30000;\n }\n\n /**\n * Sets the storage implementation for the semaphore\n * @param storage - The storage implementation to use\n */\n public setStorage(storage: SemaphoreStorage) {\n this.storage = storage;\n }\n\n /**\n * Gets the storage implementation for the semaphore\n * @returns The storage implementation\n */\n public getStorage(): SemaphoreStorage {\n return this.storage;\n }\n\n /**\n * Acquires a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\n public async acquire(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n // Initialize semaphore if it doesn't exist\n if (this.storage instanceof MemorySemaphoreStorage) {\n const totalPermits = await this.storage.getTotalPermits(key);\n if (totalPermits === 0) {\n (this.storage as MemorySemaphoreStorage).initialize(\n key,\n this.defaultPermits,\n );\n }\n }\n\n return this.storage.acquire(key, timeout || this.defaultTimeout, signal);\n }\n\n /**\n * Releases a permit for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\n public async release(key: string): Promise<void> {\n return this.storage.release(key);\n }\n\n /**\n * Gets the number of available permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\n public async getAvailablePermits(key: string): Promise<number> {\n return this.storage.getAvailablePermits(key);\n }\n\n /**\n * Gets the total number of permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the total number of permits\n */\n public async getTotalPermits(key: string): Promise<number> {\n return this.storage.getTotalPermits(key);\n }\n\n /**\n * Gets the number of acquired permits for the given key\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\n public async getAcquiredPermits(key: string): Promise<number> {\n const total = await this.getTotalPermits(key);\n const available = await this.getAvailablePermits(key);\n return total - available;\n }\n\n /**\n * Executes a function with a permit from the semaphore\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n * @throws Error if permit acquisition fails or function execution fails\n */\n public async withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n ): Promise<T> {\n const acquired = await this.acquire(key, timeout, signal);\n if (!acquired) {\n throw new Error(`Failed to acquire permit for key: ${key}`);\n }\n\n try {\n return await fn();\n } finally {\n await this.release(key);\n }\n }\n\n /**\n * Gets the current configuration of the semaphore\n * @returns Object containing the current permits and timeout values\n */\n public getConfig(): Omit<SemaphoreOptions, 'storage'> {\n return {\n permits: this.defaultPermits,\n timeout: this.defaultTimeout,\n };\n }\n}\n\n/**\n * Default semaphore instance for global use\n */\nexport const defaultSemaphore = new Semaphore();\n\n/**\n * Convenience function to execute a function with a permit using the default semaphore.\n *\n * @param key - The unique identifier for the semaphore\n * @param fn - The function to execute with a permit\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the permit acquisition\n * @returns Promise resolving to the result of the function execution\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const result = await withPermit('database-connection', async () => {\n * // This code runs with a permit from the semaphore\n * return await executeDatabaseQuery();\n * }, 30000, controller.signal);\n * controller.abort(); // Cancels the permit acquisition\n * ```\n */\nexport async function withPermit<T>(\n key: string,\n fn: () => Promise<T> | T,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<T> {\n return defaultSemaphore.withPermit(key, fn, timeout, signal);\n}\n\n/**\n * Creates a new semaphore instance with the specified configuration\n * @param options - Configuration options for the semaphore\n * @returns New Semaphore instance\n *\n * @example\n * ```typescript\n * const semaphore = createSemaphore({\n * permits: 5,\n * timeout: 60000,\n * storage: new RedisSemaphoreStorage()\n * });\n * ```\n */\nexport function createSemaphore(options: SemaphoreOptions): Semaphore {\n return new Semaphore(options);\n}\n\n/**\n * Acquires a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @param timeout - Optional timeout in milliseconds for permit acquisition\n * @param signal - Optional AbortSignal for cancelling the acquisition\n * @returns Promise resolving to true if permit was acquired, false if timeout\n */\nexport async function acquirePermit(\n key: string,\n timeout?: number,\n signal?: AbortSignal,\n): Promise<boolean> {\n return defaultSemaphore.acquire(key, timeout, signal);\n}\n\n/**\n * Releases a permit using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise that resolves when the permit is released\n */\nexport async function releasePermit(key: string): Promise<void> {\n return defaultSemaphore.release(key);\n}\n\n/**\n * Gets the number of available permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of available permits\n */\nexport async function getAvailablePermits(key: string): Promise<number> {\n return defaultSemaphore.getAvailablePermits(key);\n}\n\n/**\n * Gets the number of acquired permits using the default semaphore\n * @param key - The unique identifier for the semaphore\n * @returns Promise resolving to the number of acquired permits\n */\nexport async function getAcquiredPermits(key: string): Promise<number> {\n return defaultSemaphore.getAcquiredPermits(key);\n}\n"],"mappings":";;;;;;AA6DA,IAAa,yBAAb,MAAgE;CAC9D,AAA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B,mBAAmB"}
@@ -1,7 +1,7 @@
1
1
  require('../colors-Cd4Oz-r-.js');
2
2
  require('../ActionRow-CmTHbo2t.js');
3
- require('../error-codes-C-ViHyu-.js');
4
- const require_commandkit = require('../commandkit-DMEW0kJg.js');
3
+ require('../error-codes-Ds0bnPvT.js');
4
+ const require_commandkit = require('../commandkit-c0sAaK0G.js');
5
5
  require('../common-CcfjYnPG.js');
6
6
  require('../common-vnMIelAE.js');
7
7
  require('../container-z621KfH5.js');
@@ -23,11 +23,11 @@ require('../runtime-5fxB4uhe.js');
23
23
  require('../utils-BnXM4eKk.js');
24
24
  require('../resolve-file-url-DHTQj2mU.js');
25
25
  require('../types-package-DrnIdWLg.js');
26
- require('../EventWorkerContext-CSlD9rbx.js');
27
- require('../signals-DHdYrd-n.js');
28
- require('../constants-CUND8XkG.js');
29
- require('../MessageCommandParser-B_BEQ3p8.js');
30
- require('../CommandsRouter-Ci1Pe8Vd.js');
26
+ require('../constants-DxfYtA6t.js');
27
+ require('../EventWorkerContext-TZIKxVCu.js');
28
+ require('../signals-r7qPAvOR.js');
29
+ require('../MessageCommandParser-TPEPhjvx.js');
30
+ require('../CommandsRouter-tMAivEfv.js');
31
31
  require('../EventsRouter-C_J0M3uO.js');
32
32
  require('../router-DHnFRADH.js');
33
33
  require('../common-DNADUU3_.js');
@@ -1 +1 @@
1
- {"version":3,"file":"warn-unstable.js","names":[],"sources":["../../src/utils/warn-unstable.ts"],"sourcesContent":["const WARNED_KEYS = new Set<string>();\n\n/**\n * Emit a warning message to the console as a CommandKitWarning.\n * @param message - The warning message to emit.\n * @param code - The warning code (default is 'CommandKitWarning').\n */\nexport function emitWarning(message: string, code = 'CommandKitWarning') {\n process.emitWarning(message, { code });\n}\n\n/**\n * Emit a warning for unstable features in CommandKit.\n * @param name - The name of the unstable feature.\n * @example warnUnstable('MyUnstableFeature');\n */\nexport function warnUnstable(name: string) {\n if (WARNED_KEYS.has(name)) return;\n\n WARNED_KEYS.add(name);\n\n emitWarning(\n `${name} is unstable and may change in future versions.`,\n 'CommandKitUnstableWarning',\n );\n}\n"],"mappings":";;AAAA,MAAM,8BAAc,IAAI;;;;;;AAOxB,SAAgB,YAAY,SAAiB,OAAO,qBAAqB;AACvE,SAAQ,YAAY,SAAS,EAAE,MAAM;AACvC;;;;;;AAOA,SAAgB,aAAa,MAAc;AACzC,KAAI,YAAY,IAAI,MAAO;AAE3B,aAAY,IAAI;AAEhB,aACE,GAAG,KAAK,kDACR;AAEJ"}
1
+ {"version":3,"file":"warn-unstable.js","names":[],"sources":["../../src/utils/warn-unstable.ts"],"sourcesContent":["const WARNED_KEYS = new Set<string>();\n\n/**\n * Emit a warning message to the console as a CommandKitWarning.\n * @param message - The warning message to emit.\n * @param code - The warning code (default is 'CommandKitWarning').\n */\nexport function emitWarning(message: string, code = 'CommandKitWarning') {\n process.emitWarning(message, { code });\n}\n\n/**\n * Emit a warning for unstable features in CommandKit.\n * @param name - The name of the unstable feature.\n * @example warnUnstable('MyUnstableFeature');\n */\nexport function warnUnstable(name: string) {\n if (WARNED_KEYS.has(name)) return;\n\n WARNED_KEYS.add(name);\n\n emitWarning(\n `${name} is unstable and may change in future versions.`,\n 'CommandKitUnstableWarning',\n );\n}\n"],"mappings":";;AAAA,MAAM,8BAAc,IAAI;;;;;;AAOxB,SAAgB,YAAY,SAAiB,OAAO,qBAAqB;AACvE,SAAQ,YAAY,SAAS,EAAE;;;;;;;AAQjC,SAAgB,aAAa,MAAc;AACzC,KAAI,YAAY,IAAI,MAAO;AAE3B,aAAY,IAAI;AAEhB,aACE,GAAG,KAAK,kDACR"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils-BnXM4eKk.js","names":[],"sources":["../src/config/utils.ts"],"sourcesContent":["import { CommandKitConfig } from './types';\n\n/**\n * @private\n */\nexport type DeepRequired<T, OptionalKeys extends keyof T = never> = {\n [P in keyof T]-?: P extends OptionalKeys ? Partial<T[P]> : DeepRequired<T[P]>;\n};\n\n/**\n * @private\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: DeepPartial<T[P]>;\n};\n\n/**\n * @private\n * @example\n * ```ts\n * const target = { a: 1, b: { c: 2 } };\n * const source = { b: { d: 3 } };\n * const result = mergeDeep(target, source);\n * // result = { a: 1, b: { c: 2, d: 3 } }\n * ```\n */\nexport const mergeDeep = <T extends Record<string, any>>(\n target: T,\n source?: T,\n tracker = new WeakMap<object, boolean>(),\n): T => {\n if (!source) return target;\n const isObject = (obj: unknown) =>\n obj && typeof obj === 'object' && !Array.isArray(obj);\n\n // Prevent infinite recursion\n if (tracker.has(target)) {\n return target;\n }\n\n // Mark the target as visited\n tracker.set(target, true);\n\n const output: T = { ...target };\n if (isObject(target) && isObject(source)) {\n Object.keys(source).forEach((key) => {\n if (isObject(source[key])) {\n if (!(key in target)) {\n Object.assign(output, { [key]: source[key] });\n } else {\n output[key as keyof T] = mergeDeep(target[key], source[key], tracker);\n }\n } else {\n Object.assign(output, { [key]: source[key] });\n }\n });\n }\n\n return output as T;\n};\n\nexport type ResolvedCommandKitConfig = DeepRequired<\n CommandKitConfig,\n 'compilerOptions'\n>;\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAa,aACb,QACA,QACA,0BAAU,IAAI,cACP;AACL,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,YAAY,QAClB,OAAO,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ;AAGjD,KAAI,QAAQ,IAAI,QACd,QAAO;AAIT,SAAQ,IAAI,QAAQ;CAEpB,MAAM,SAAY,EAAE,GAAG,QAAQ;AAC/B,KAAI,SAAS,WAAW,SAAS,QAC/B,QAAO,KAAK,QAAQ,SAAS,QAAQ;AACnC,MAAI,SAAS,OAAO,MAClB,KAAI,EAAE,OAAO,QACX,QAAO,OAAO,QAAQ,GAAG,MAAM,OAAO,MAAM;MAE5C,QAAO,OAAkB,UAAU,OAAO,MAAM,OAAO,MAAM;MAG/D,QAAO,OAAO,QAAQ,GAAG,MAAM,OAAO,MAAM;CAE/C;AAGH,QAAO;AACR"}
1
+ {"version":3,"file":"utils-BnXM4eKk.js","names":[],"sources":["../src/config/utils.ts"],"sourcesContent":["import { CommandKitConfig } from './types';\n\n/**\n * @private\n */\nexport type DeepRequired<T, OptionalKeys extends keyof T = never> = {\n [P in keyof T]-?: P extends OptionalKeys ? Partial<T[P]> : DeepRequired<T[P]>;\n};\n\n/**\n * @private\n */\nexport type DeepPartial<T> = {\n [P in keyof T]?: DeepPartial<T[P]>;\n};\n\n/**\n * @private\n * @example\n * ```ts\n * const target = { a: 1, b: { c: 2 } };\n * const source = { b: { d: 3 } };\n * const result = mergeDeep(target, source);\n * // result = { a: 1, b: { c: 2, d: 3 } }\n * ```\n */\nexport const mergeDeep = <T extends Record<string, any>>(\n target: T,\n source?: T,\n tracker = new WeakMap<object, boolean>(),\n): T => {\n if (!source) return target;\n const isObject = (obj: unknown) =>\n obj && typeof obj === 'object' && !Array.isArray(obj);\n\n // Prevent infinite recursion\n if (tracker.has(target)) {\n return target;\n }\n\n // Mark the target as visited\n tracker.set(target, true);\n\n const output: T = { ...target };\n if (isObject(target) && isObject(source)) {\n Object.keys(source).forEach((key) => {\n if (isObject(source[key])) {\n if (!(key in target)) {\n Object.assign(output, { [key]: source[key] });\n } else {\n output[key as keyof T] = mergeDeep(target[key], source[key], tracker);\n }\n } else {\n Object.assign(output, { [key]: source[key] });\n }\n });\n }\n\n return output as T;\n};\n\nexport type ResolvedCommandKitConfig = DeepRequired<\n CommandKitConfig,\n 'compilerOptions'\n>;\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAa,aACb,QACA,QACA,0BAAU,IAAI,cACP;AACL,KAAI,CAAC,OAAQ,QAAO;CACpB,MAAM,YAAY,QAClB,OAAO,OAAO,QAAQ,YAAY,CAAC,MAAM,QAAQ;AAGjD,KAAI,QAAQ,IAAI,QACd,QAAO;AAIT,SAAQ,IAAI,QAAQ;CAEpB,MAAM,SAAY,EAAE,GAAG;AACvB,KAAI,SAAS,WAAW,SAAS,QAC/B,QAAO,KAAK,QAAQ,SAAS,QAAQ;AACnC,MAAI,SAAS,OAAO,MAClB,KAAI,EAAE,OAAO,QACX,QAAO,OAAO,QAAQ,GAAG,MAAM,OAAO;MAEtC,QAAO,OAAkB,UAAU,OAAO,MAAM,OAAO,MAAM;MAG/D,QAAO,OAAO,QAAQ,GAAG,MAAM,OAAO;;AAK5C,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"utils-DCSnVAZ6.js","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["import type { Ora } from 'ora';\n\nlet ora: typeof import('ora') | undefined;\n\n/**\n * @private\n * @internal\n */\nexport async function createSpinner(text: string): Promise<Ora> {\n if (!ora) {\n ora = await import('ora');\n }\n\n return (ora.default || ora)({\n text,\n color: 'cyan',\n });\n}\n"],"mappings":";;AAEA,IAAI;;;;;AAMJ,eAAsB,cAAc,MAA4B;AAC9D,KAAI,CAAC,IACH,OAAM,MAAM,OAAO;AAGrB,SAAQ,IAAI,WAAW,KAAK;EAC1B;EACA,OAAO;EACR;AACH"}
1
+ {"version":3,"file":"utils-DCSnVAZ6.js","names":[],"sources":["../src/cli/utils.ts"],"sourcesContent":["import type { Ora } from 'ora';\n\nlet ora: typeof import('ora') | undefined;\n\n/**\n * @private\n * @internal\n */\nexport async function createSpinner(text: string): Promise<Ora> {\n if (!ora) {\n ora = await import('ora');\n }\n\n return (ora.default || ora)({\n text,\n color: 'cyan',\n });\n}\n"],"mappings":";;AAEA,IAAI;;;;;AAMJ,eAAsB,cAAc,MAA4B;AAC9D,KAAI,CAAC,IACH,OAAM,MAAM,OAAO;AAGrB,SAAQ,IAAI,WAAW,KAAK;EAC1B;EACA,OAAO"}
@@ -6,7 +6,7 @@
6
6
  /**
7
7
  * The current version of CommandKit.
8
8
  */
9
- const version = "1.2.0-rc.2";
9
+ const version = "1.2.0-rc.4";
10
10
 
11
11
  //#endregion
12
12
  Object.defineProperty(exports, 'version', {
@@ -15,4 +15,4 @@ Object.defineProperty(exports, 'version', {
15
15
  return version;
16
16
  }
17
17
  });
18
- //# sourceMappingURL=version-Df1T7P2K.js.map
18
+ //# sourceMappingURL=version-BoHnO-Go.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version-Df1T7P2K.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["/**\n * @private\n */\nfunction $version(): string {\n 'use macro';\n return require('../package.json').version;\n}\n\n/**\n * The current version of CommandKit.\n */\nexport const version: string = $version();\n"],"mappings":";;;;;;;;AAWA,MAAa,UAA4B"}
1
+ {"version":3,"file":"version-BoHnO-Go.js","names":[],"sources":["../src/version.ts"],"sourcesContent":["/**\n * @private\n */\nfunction $version(): string {\n 'use macro';\n return require('../package.json').version;\n}\n\n/**\n * The current version of CommandKit.\n */\nexport const version: string = $version();\n"],"mappings":";;;;;;;;AAWA,MAAa,UAA4B"}
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
- const require_version = require('./version-Df1T7P2K.js');
1
+ const require_version = require('./version-BoHnO-Go.js');
2
2
 
3
3
  exports.version = require_version.version;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "commandkit",
3
3
  "description": "Beginner friendly command & event handler for Discord.js",
4
- "version": "1.2.0-rc.2",
4
+ "version": "1.2.0-rc.4",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
7
7
  "main": "./dist/index.js",
@@ -54,75 +54,85 @@
54
54
  "import": "./dist/index.js",
55
55
  "types": "./dist/index.d.ts"
56
56
  },
57
- "./jsx-runtime": {
58
- "require": "./jsx-runtime.cjs",
59
- "import": "./jsx-runtime.cjs",
60
- "types": "./jsx-runtime.d.ts"
57
+ "./ai": {
58
+ "require": "./ai.cjs",
59
+ "import": "./ai.cjs",
60
+ "types": "./ai.d.ts"
61
61
  },
62
- "./hooks": {
63
- "require": "./hooks.cjs",
64
- "import": "./hooks.cjs",
65
- "types": "./hooks.d.ts"
62
+ "./analytics": {
63
+ "require": "./analytics.cjs",
64
+ "import": "./analytics.cjs",
65
+ "types": "./analytics.d.ts"
66
66
  },
67
- "./plugin": {
68
- "require": "./plugin.cjs",
69
- "import": "./plugin.cjs",
70
- "types": "./plugin.d.ts"
67
+ "./async-queue": {
68
+ "require": "./async-queue.cjs",
69
+ "import": "./async-queue.cjs",
70
+ "types": "./async-queue.d.ts"
71
71
  },
72
- "./config": {
73
- "require": "./config.cjs",
74
- "import": "./config.cjs",
75
- "types": "./config.d.ts"
72
+ "./cache": {
73
+ "require": "./cache.cjs",
74
+ "import": "./cache.cjs",
75
+ "types": "./cache.d.ts"
76
76
  },
77
77
  "./components": {
78
78
  "require": "./components.cjs",
79
79
  "import": "./components.cjs",
80
80
  "types": "./components.d.ts"
81
81
  },
82
+ "./config": {
83
+ "require": "./config.cjs",
84
+ "import": "./config.cjs",
85
+ "types": "./config.d.ts"
86
+ },
87
+ "./env": {
88
+ "require": "./env.cjs",
89
+ "import": "./env.cjs",
90
+ "types": "./env.d.ts"
91
+ },
92
+ "./events": {
93
+ "require": "./events.cjs",
94
+ "import": "./events.cjs",
95
+ "types": "./events.d.ts"
96
+ },
82
97
  "./flag": {
83
98
  "require": "./flag.cjs",
84
99
  "import": "./flag.cjs",
85
100
  "types": "./flag.d.ts"
86
101
  },
87
- "./cache": {
88
- "require": "./cache.cjs",
89
- "import": "./cache.cjs",
90
- "types": "./cache.d.ts"
102
+ "./hooks": {
103
+ "require": "./hooks.cjs",
104
+ "import": "./hooks.cjs",
105
+ "types": "./hooks.d.ts"
91
106
  },
92
107
  "./i18n": {
93
108
  "require": "./i18n.cjs",
94
109
  "import": "./i18n.cjs",
95
110
  "types": "./i18n.d.ts"
96
111
  },
112
+ "./jsx-runtime": {
113
+ "require": "./jsx-runtime.cjs",
114
+ "import": "./jsx-runtime.cjs",
115
+ "types": "./jsx-runtime.d.ts"
116
+ },
117
+ "./kv": {
118
+ "require": "./kv.cjs",
119
+ "import": "./kv.cjs",
120
+ "types": "./kv.d.ts"
121
+ },
97
122
  "./logger": {
98
123
  "require": "./logger.cjs",
99
124
  "import": "./logger.cjs",
100
125
  "types": "./logger.d.ts"
101
126
  },
102
- "./events": {
103
- "require": "./events.cjs",
104
- "import": "./events.cjs",
105
- "types": "./events.d.ts"
106
- },
107
- "./analytics": {
108
- "require": "./analytics.cjs",
109
- "import": "./analytics.cjs",
110
- "types": "./analytics.d.ts"
111
- },
112
- "./ai": {
113
- "require": "./ai.cjs",
114
- "import": "./ai.cjs",
115
- "types": "./ai.d.ts"
116
- },
117
- "./env": {
118
- "require": "./env.cjs",
119
- "import": "./env.cjs",
120
- "types": "./env.d.ts"
127
+ "./mutex": {
128
+ "require": "./mutex.cjs",
129
+ "import": "./mutex.cjs",
130
+ "types": "./mutex.d.ts"
121
131
  },
122
- "./async-queue": {
123
- "require": "./async-queue.cjs",
124
- "import": "./async-queue.cjs",
125
- "types": "./async-queue.d.ts"
132
+ "./plugin": {
133
+ "require": "./plugin.cjs",
134
+ "import": "./plugin.cjs",
135
+ "types": "./plugin.d.ts"
126
136
  },
127
137
  "./ratelimit": {
128
138
  "require": "./ratelimit.cjs",
@@ -133,16 +143,6 @@
133
143
  "require": "./semaphore.cjs",
134
144
  "import": "./semaphore.cjs",
135
145
  "types": "./semaphore.d.ts"
136
- },
137
- "./mutex": {
138
- "require": "./mutex.cjs",
139
- "import": "./mutex.cjs",
140
- "types": "./mutex.d.ts"
141
- },
142
- "./kv": {
143
- "require": "./kv.cjs",
144
- "import": "./kv.cjs",
145
- "types": "./kv.d.ts"
146
146
  }
147
147
  },
148
148
  "repository": {
@@ -154,7 +154,9 @@
154
154
  "keywords": [
155
155
  "discord.js",
156
156
  "command handler",
157
- "event handler"
157
+ "event handler",
158
+ "framework",
159
+ "discord.js 14"
158
160
  ],
159
161
  "dependencies": {
160
162
  "@rollup/plugin-json": "^6.1.0",
@@ -167,25 +169,24 @@
167
169
  "picocolors": "^1.1.1",
168
170
  "rfdc": "^1.3.1",
169
171
  "rimraf": "^6.0.0",
170
- "tsdown": "^0.14.0",
172
+ "tsdown": "^0.14.2",
171
173
  "use-macro": "^1.1.0"
172
174
  },
173
175
  "devDependencies": {
174
176
  "@types/ms": "^2.0.0",
175
177
  "@types/node": "^22.10.2",
176
178
  "@types/yargs": "^17.0.32",
177
- "discord.js": "^14.21.0",
179
+ "discord.js": "^14.22.1",
178
180
  "tsx": "^4.19.2",
179
181
  "typescript": "^5.7.3",
180
182
  "vitest": "^3.0.5",
181
- "tsconfig": "0.0.0-rc.2"
183
+ "tsconfig": "0.0.0-rc.4"
182
184
  },
183
185
  "engines": {
184
186
  "node": ">=24"
185
187
  },
186
188
  "scripts": {
187
189
  "check-types": "tsc --noEmit",
188
- "dev": "pnpm run --filter=test-bot dev",
189
190
  "build": "tsdown",
190
191
  "test": "vitest"
191
192
  }
@@ -1,34 +0,0 @@
1
- //#region src/logger/ILogger.d.ts
2
- /**
3
- * ILogger interface for logging functionality.
4
- */
5
- interface ILogger {
6
- /**
7
- * Logs a message with the default log level.
8
- * @param args The message to log.
9
- */
10
- log(...args: any[]): void;
11
- /**
12
- * Logs an error message.
13
- * @param args The error message to log.
14
- */
15
- error(...args: any[]): void;
16
- /**
17
- * Logs a warning message.
18
- * @param args The warning message to log.
19
- */
20
- warn(...args: any[]): void;
21
- /**
22
- * Logs an informational message.
23
- * @param args The informational message to log.
24
- */
25
- info(...args: any[]): void;
26
- /**
27
- * Logs a debug message.
28
- * @param args The debug message to log.
29
- */
30
- debug(...args: any[]): void;
31
- }
32
- //#endregion
33
- export { ILogger };
34
- //# sourceMappingURL=ILogger-DBGON5wx.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"build-DXl8uEv4.js","names":[],"sources":["../src/cli/build.ts"],"sourcesContent":["import { build, Options } from 'tsdown';\nimport { CompilerPlugin, CompilerPluginRuntime } from '../plugins';\nimport { loadConfigFile } from '../config/loader';\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { DevEnv, devEnvFileArgs, ProdEnv, prodEnvFileArgs } from './env';\nimport { rimraf } from 'rimraf';\nimport { performTypeCheck } from './type-checker';\nimport { copyLocaleFiles } from './common';\nimport { MaybeArray } from '../components';\nimport { COMMANDKIT_CWD } from '../utils/constants';\nimport { mergeDeep } from '../config/utils';\nimport { existsSync } from 'node:fs';\n\n/**\n * @private\n * @internal\n */\nexport interface ApplicationBuildOptions {\n plugins?: MaybeArray<CompilerPlugin>[] | Array<CompilerPlugin>;\n rolldownPlugins?: any[];\n isDev?: boolean;\n configPath?: string;\n}\n\n// emit public env variables and given env variables\n/**\n * @private\n * @internal\n */\nfunction mergeDefinitionsIfNeeded(env: Record<string, string>, isDev: boolean) {\n const values = Object.fromEntries(\n Object.entries(process.env).filter(\n ([k]) => !(k in env) && k.startsWith('COMMANDKIT_PUBLIC_'),\n ),\n );\n\n return {\n ...env,\n ...values,\n ...(isDev\n ? {\n NODE_ENV: 'development',\n COMMANDKIT_BOOTSTRAP_MODE: 'development',\n COMMANDKIT_IS_DEV: 'true',\n COMMANDKIT_IS_TEST: 'false',\n }\n : {\n NODE_ENV: 'production',\n COMMANDKIT_BOOTSTRAP_MODE: 'production',\n COMMANDKIT_IS_DEV: 'false',\n COMMANDKIT_IS_TEST: 'false',\n }),\n };\n}\n\n/**\n * @private\n * @internal\n */\nexport async function buildApplication({\n plugins,\n rolldownPlugins,\n isDev,\n configPath,\n}: ApplicationBuildOptions) {\n const config = await loadConfigFile(configPath);\n\n if (!isDev && !config?.typescript?.ignoreBuildErrors) {\n await performTypeCheck(configPath || COMMANDKIT_CWD);\n }\n\n const pluginRuntime = new CompilerPluginRuntime(\n (plugins || []) as CompilerPlugin[],\n );\n\n rolldownPlugins ??= [];\n\n rolldownPlugins.push(pluginRuntime.toJSON());\n\n try {\n const dest = isDev ? '.commandkit' : config.distDir;\n\n // Clean the destination directory\n await rimraf(dest);\n\n await pluginRuntime.init();\n\n await build(\n mergeDeep(\n {\n watch: false,\n dts: false,\n clean: true,\n format: ['esm'],\n shims: true,\n minify: false,\n silent: !!isDev,\n inputOptions: {\n transform: {\n jsx: {\n runtime: 'automatic',\n importSource: 'commandkit',\n },\n },\n checks: {\n circularDependency: true,\n },\n onwarn: (warning, defaultWarn) => {\n if (warning?.message?.includes('compilerOptions.jsx')) return;\n\n return defaultWarn(warning);\n },\n onLog: (level, log, defaultLog) => {\n if (isDev) return;\n\n return defaultLog(level, log);\n },\n moduleTypes: {\n '.json': 'js',\n '.node': 'binary',\n },\n },\n plugins: rolldownPlugins,\n platform: 'node',\n skipNodeModulesBundle: true,\n sourcemap:\n config.sourceMap?.[isDev ? 'development' : 'production'] ?? true,\n target: 'node16',\n outDir: dest,\n env: mergeDefinitionsIfNeeded(config.env || {}, !!isDev),\n entry: Array.from(\n new Set([\n 'src/**/*.{js,cjs,mjs,ts,cts,mts,jsx,tsx}',\n `!${config.distDir}`,\n '!.commandkit',\n '!**/*.test.*',\n '!**/*.spec.*',\n ...(config.entrypoints ?? []),\n ]),\n ),\n unbundle: isDev\n ? true\n : (config.compilerOptions?.disableChunking ?? false),\n } satisfies Options,\n config.compilerOptions?.tsdown,\n ),\n );\n\n await copyLocaleFiles('src', dest);\n await injectEntryFile(\n configPath || COMMANDKIT_CWD,\n !!isDev,\n !!(\n config.antiCrashScript?.[isDev ? 'development' : 'production'] ??\n (isDev ? true : false)\n ),\n config.distDir,\n );\n } catch (error) {\n console.error('Build failed:', error);\n if (error instanceof Error) {\n console.error('Error details:', error.stack);\n }\n process.exit(1); // Force exit on error\n } finally {\n // Ensure plugins are cleaned up\n await pluginRuntime.destroy();\n }\n}\n\nconst envScript = (dev: boolean) => `// --- Environment Variables Loader ---\nconst $env = [${(dev ? devEnvFileArgs : prodEnvFileArgs).map((p) => `\"${p}\"`).join(', ')}];\nfor (const file of $env) {\n try {\n process.loadEnvFile(file);\n console.log('\\\\x1b[36m✔ Loaded \\\\x1b[0m\\\\x1b[33m%s\\\\x1b[0m', file);\n } catch {}\n}\n`;\n\nconst antiCrashScript = [\n '// --- CommandKit Anti-Crash Monitor ---',\n \" // 'uncaughtException' event is supposed to be used to perform synchronous cleanup before shutting down the process\",\n ' // instead of using it as a means to resume operation.',\n ' // But it exists here due to compatibility reasons with discord bot ecosystem.',\n \" const p = (t) => `\\\\x1b[31m${t}\\\\x1b[0m`, b = '[CommandKit Anti-Crash Monitor]', l = console.log, e1 = 'uncaughtException', e2 = 'unhandledRejection';\",\n ' if (!process.eventNames().includes(e1)) // skip if it is already handled',\n ' process.on(e1, (e) => {',\n ' l(p(`${b} Uncaught Exception`)); l(p(b), p(e.stack || e));',\n ' })',\n ' if (!process.eventNames().includes(e2)) // skip if it is already handled',\n ' process.on(e2, (r) => {',\n ' l(p(`${b} Unhandled promise rejection`)); l(p(`${b} ${r.stack || r}`));',\n ' });',\n '// --- CommandKit Anti-Crash Monitor ---',\n].join('\\n');\n\nconst wrapInAsyncIIFE = (code: string[]) =>\n `;await (async () => {\\n${code.join('\\n\\n')}\\n})();`;\n\nasync function injectEntryFile(\n configPath: string,\n isDev: boolean,\n emitAntiCrashScript: boolean,\n distDir?: string,\n) {\n const dist = isDev ? '.commandkit' : distDir || 'dist';\n const entryFilePath = join(configPath, dist, 'index.js');\n\n // skip if the entry file already exists\n if (existsSync(entryFilePath)) return;\n\n const code = `/* Entrypoint File Generated By CommandKit */\n${isDev ? `\\n\\n// Injected for development\\n${wrapInAsyncIIFE([envScript(isDev), emitAntiCrashScript ? antiCrashScript : ''])}\\n\\n` : wrapInAsyncIIFE([envScript(isDev)])}\n\nimport { commandkit } from 'commandkit';\nimport { Client } from 'discord.js';\n\nasync function bootstrap() {\n const app = await import('./app.js').then((m) => m.default ?? m);\n\n if (!app || !(app instanceof Client)) {\n throw new Error('The app file must default export the discord.js client instance');\n }\n\n commandkit.setClient(app);\n\n await commandkit.start();\n}\n\nawait bootstrap().catch((e) => {\n console.error('Failed to bootstrap CommandKit application:\\\\n', e.stack);\n})\n`;\n\n await writeFile(entryFilePath, code);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,SAAS,yBAAyB,KAA6B,OAAgB;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