commandkit 1.2.0-rc.9 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +19 -3
- package/README.md +45 -26
- package/bin/index.mjs +1 -1
- package/cli.d.ts +19 -0
- package/config.cjs +3 -0
- package/config.d.ts +1 -0
- package/dist/{ActionRow-DKnFVDME.d.ts → ActionRow-Bt9qi0Mb.d.ts} +4 -5
- package/dist/{Button-4ZUXdA56.d.ts → Button-DxJLcZIU.d.ts} +7 -8
- package/dist/{ButtonKit-C7r7RPNf.d.ts → ButtonKit-BfcyvWfj.d.ts} +4 -5
- package/dist/{ChannelSelectMenuKit-BrXvBYNH.d.ts → ChannelSelectMenuKit-DYkudikb.d.ts} +5 -6
- package/dist/{CommandsRouter-CoOA7hkf.d.ts → CommandsRouter-DiNoF0dq.d.ts} +2 -3
- package/dist/{EventInterceptor-x-R2qshQ.d.ts → EventInterceptor-D9JKMcfi.d.ts} +2 -2
- package/dist/{EventsRouter-BacqK6z3.d.ts → EventsRouter-EuuSu6NH.d.ts} +2 -2
- package/dist/{MentionableSelectMenuKit-CPTKqx-O.d.ts → MentionableSelectMenuKit-Mu4xqP6B.d.ts} +5 -6
- package/dist/{MessageCommandParser-ROLibZPX.d.ts → MessageCommandParser-DPCbHXCS.d.ts} +4 -5
- package/dist/{Modal-C6UTRdYQ.d.ts → Modal-v9rrcMl-.d.ts} +25 -12
- package/dist/{ModalKit-Btz58KYn.d.ts → ModalKit-XJSM65SV.d.ts} +4 -5
- package/dist/{RoleSelectMenuKit-C26lU3sN.d.ts → RoleSelectMenuKit-CCjcp3HY.d.ts} +5 -6
- package/dist/{SelectMenu-Diy87_ba.d.ts → SelectMenu-CY0vvoSu.d.ts} +17 -14
- package/dist/{StringSelectMenuKit-Bhs8U6WI.d.ts → StringSelectMenuKit-G5nBTicX.d.ts} +5 -6
- package/dist/{UserSelectMenuKit-CfqFJdxz.d.ts → UserSelectMenuKit-D3SO_fXA.d.ts} +5 -6
- package/dist/analytics/analytics-engine.d.ts +1 -31
- package/dist/analytics/analytics-engine.js +2 -36
- package/dist/analytics/analytics-provider.d.ts +1 -31
- package/dist/analytics/analytics-provider.js +1 -0
- package/dist/analytics/constants.js +26 -3
- package/dist/analytics/constants.js.map +1 -0
- package/dist/analytics/utils.js +2 -36
- package/dist/{analytics-engine-B7JNRnEN.d.ts → analytics-engine-DnRsHBId.d.ts} +48 -34
- package/dist/app/commands/AppCommandRunner.d.ts +1 -31
- package/dist/app/commands/AppCommandRunner.js +2 -36
- package/dist/app/commands/Context.d.ts +1 -31
- package/dist/app/commands/Context.js +2 -36
- package/dist/app/commands/MessageCommandParser.d.ts +1 -1
- package/dist/app/commands/MessageCommandParser.js +261 -4
- package/dist/app/commands/MessageCommandParser.js.map +1 -0
- package/dist/app/commands/helpers.d.ts +1 -1
- package/dist/app/commands/helpers.js +25 -3
- package/dist/app/commands/helpers.js.map +1 -0
- package/dist/app/events/EventWorkerContext.d.ts +42 -33
- package/dist/app/events/EventWorkerContext.js +48 -5
- package/dist/app/events/EventWorkerContext.js.map +1 -0
- package/dist/app/handlers/AppCommandHandler.d.ts +1 -31
- package/dist/app/handlers/AppCommandHandler.js +2 -36
- package/dist/app/handlers/AppEventsHandler.d.ts +1 -31
- package/dist/app/handlers/AppEventsHandler.js +2 -36
- package/dist/app/index.d.ts +4 -31
- package/dist/app/index.js +13 -45
- package/dist/app/interrupt/signals.d.ts +1 -1
- package/dist/app/interrupt/signals.js +54 -7
- package/dist/app/interrupt/signals.js.map +1 -0
- package/dist/app/middlewares/permissions.d.ts +1 -31
- package/dist/app/middlewares/permissions.js +2 -36
- package/dist/app/register/CommandRegistrar.d.ts +1 -31
- package/dist/app/register/CommandRegistrar.js +2 -36
- package/dist/app/router/CommandsRouter.d.ts +1 -1
- package/dist/app/router/CommandsRouter.js +210 -2
- package/dist/app/router/CommandsRouter.js.map +1 -0
- package/dist/app/router/EventsRouter.d.ts +1 -1
- package/dist/app/router/EventsRouter.js +128 -2
- package/dist/app/router/EventsRouter.js.map +1 -0
- package/dist/app/router/index.d.ts +2 -3
- package/dist/app/router/index.js +5 -5
- package/dist/{chunk-nOFOJqeH.js → chunk-BE-pF4vm.js} +11 -7
- package/dist/cli/app-process.d.ts +2 -3
- package/dist/cli/app-process.js +60 -7
- package/dist/cli/app-process.js.map +1 -0
- package/dist/cli/build.d.ts +2 -31
- package/dist/cli/build.js +171 -41
- package/dist/cli/build.js.map +1 -0
- package/dist/cli/common.d.ts +10 -34
- package/dist/cli/common.js +182 -11
- package/dist/cli/common.js.map +1 -0
- package/dist/cli/development.d.ts +18 -1
- package/dist/cli/development.js +52 -78
- package/dist/cli/development.js.map +1 -1
- package/dist/cli/env.d.ts +4 -0
- package/dist/cli/env.js +73 -9
- package/dist/cli/env.js.map +1 -0
- package/dist/cli/generators.js +10 -13
- package/dist/cli/generators.js.map +1 -1
- package/dist/cli/information.js +11 -10
- package/dist/cli/information.js.map +1 -1
- package/dist/cli/init.d.ts +12 -2
- package/dist/cli/init.js +83 -38
- package/dist/cli/init.js.map +1 -0
- package/dist/cli/production.d.ts +2 -3
- package/dist/cli/production.js +19 -52
- package/dist/cli/production.js.map +1 -1
- package/dist/cli/type-checker.js +83 -6
- package/dist/cli/type-checker.js.map +1 -0
- package/dist/cli/utils.d.ts +0 -1
- package/dist/cli/utils.js +18 -2
- package/dist/cli/utils.js.map +1 -0
- package/dist/{commandkit-Bm0gLN8i.js → commandkit--k6yDJEr.js} +3219 -2616
- package/dist/commandkit--k6yDJEr.js.map +1 -0
- package/dist/commandkit.d.ts +1 -31
- package/dist/commandkit.js +2 -36
- package/dist/{common-DOCvOVC4.d.ts → common-CCvvgnxi.d.ts} +4 -5
- package/dist/components/common/EventInterceptor.d.ts +1 -1
- package/dist/components/common/EventInterceptor.js +137 -2
- package/dist/components/common/EventInterceptor.js.map +1 -0
- package/dist/components/common/element.d.ts +2 -5
- package/dist/components/common/element.js +10 -8
- package/dist/components/common/types.d.ts +1 -1
- package/dist/components/common/types.js +1 -1
- package/dist/components/{v2 → display}/common.d.ts +1 -2
- package/dist/components/display/common.js +4 -0
- package/dist/components/display/container.d.ts +2 -0
- package/dist/components/display/container.js +4 -0
- package/dist/components/display/file.d.ts +2 -0
- package/dist/{file-DVOELoNv.js → components/display/file.js} +5 -10
- package/dist/components/display/file.js.map +1 -0
- package/dist/components/display/index.d.ts +9 -0
- package/dist/components/display/index.js +19 -0
- package/dist/components/display/label.d.ts +2 -0
- package/dist/components/display/label.js +4 -0
- package/dist/components/display/media-gallery.d.ts +2 -0
- package/dist/components/display/media-gallery.js +5 -0
- package/dist/components/display/poll.d.ts +2 -0
- package/dist/components/display/poll.js +86 -0
- package/dist/components/display/poll.js.map +1 -0
- package/dist/components/display/section.d.ts +2 -0
- package/dist/components/display/section.js +5 -0
- package/dist/components/display/separator.d.ts +2 -0
- package/dist/{separator-DL6QH5H1.js → components/display/separator.js} +5 -10
- package/dist/components/display/separator.js.map +1 -0
- package/dist/components/display/text-display.d.ts +2 -0
- package/dist/{text-display-DbMumig_.js → components/display/text-display.js} +5 -10
- package/dist/components/display/text-display.js.map +1 -0
- package/dist/components/index.d.ts +23 -24
- package/dist/components/index.js +29 -53
- package/dist/components/interactive/action-row/ActionRow.d.ts +2 -0
- package/dist/{ActionRow-CbdGFWMT.js → components/interactive/action-row/ActionRow.js} +5 -10
- package/dist/components/interactive/action-row/ActionRow.js.map +1 -0
- package/dist/components/interactive/button/Button.d.ts +2 -0
- package/dist/components/interactive/button/Button.js +4 -0
- package/dist/components/interactive/button/ButtonKit.d.ts +2 -0
- package/dist/components/interactive/button/ButtonKit.js +4 -0
- package/dist/components/interactive/modal/Modal.d.ts +2 -0
- package/dist/components/interactive/modal/Modal.js +8 -0
- package/dist/components/interactive/modal/ModalKit.d.ts +2 -0
- package/dist/components/interactive/modal/ModalKit.js +4 -0
- package/dist/components/interactive/select-menu/ChannelSelectMenuKit.d.ts +2 -0
- package/dist/components/interactive/select-menu/ChannelSelectMenuKit.js +4 -0
- package/dist/components/interactive/select-menu/MentionableSelectMenuKit.d.ts +2 -0
- package/dist/components/interactive/select-menu/MentionableSelectMenuKit.js +4 -0
- package/dist/components/interactive/select-menu/RoleSelectMenuKit.d.ts +2 -0
- package/dist/components/interactive/select-menu/RoleSelectMenuKit.js +4 -0
- package/dist/components/interactive/select-menu/SelectMenu.d.ts +2 -0
- package/dist/components/interactive/select-menu/SelectMenu.js +9 -0
- package/dist/components/interactive/select-menu/StringSelectMenuKit.d.ts +2 -0
- package/dist/components/interactive/select-menu/StringSelectMenuKit.js +4 -0
- package/dist/components/interactive/select-menu/UserSelectMenuKit.d.ts +2 -0
- package/dist/components/interactive/select-menu/UserSelectMenuKit.js +4 -0
- package/dist/components/interactive/select-menu/common.d.ts +2 -0
- package/dist/components/interactive/select-menu/common.js +1 -0
- package/dist/config/config.d.ts +15 -33
- package/dist/config/config.js +2 -36
- package/dist/config/default.d.ts +1 -31
- package/dist/config/default.js +2 -36
- package/dist/config/loader.d.ts +1 -31
- package/dist/config/loader.js +2 -36
- package/dist/config/types.d.ts +1 -31
- package/dist/config/types.js +1 -0
- package/dist/config/utils.d.ts +1 -31
- package/dist/config/utils.js +29 -2
- package/dist/config/utils.js.map +1 -0
- package/dist/{constants-D8PMA9on.d.ts → constants-DqtJY0t-.d.ts} +3 -3
- package/dist/{constants-MKu-Q1jh.d.ts → constants-DwxpkIeH.d.ts} +8 -2
- package/dist/{container-DHBELeJ3.d.ts → container-CYojOA9d.d.ts} +3 -4
- package/dist/context/async-context.d.ts +1 -31
- package/dist/context/async-context.js +2 -36
- package/dist/context/environment.d.ts +1 -31
- package/dist/context/environment.js +2 -36
- package/dist/{element-CAXu1XtK.d.ts → element-DeLvTMfZ.d.ts} +5 -5
- package/dist/events/CommandKitEventsChannel.d.ts +1 -31
- package/dist/events/CommandKitEventsChannel.js +83 -2
- package/dist/events/CommandKitEventsChannel.js.map +1 -0
- package/dist/{file-DTrr-p09.d.ts → file-DLO1zEcH.d.ts} +3 -4
- package/dist/flags/FlagProvider.d.ts +1 -31
- package/dist/flags/FlagProvider.js +1 -0
- package/dist/flags/FlagProvider.js.map +1 -1
- package/dist/flags/feature-flags.d.ts +1 -31
- package/dist/flags/feature-flags.js +5 -40
- package/dist/flags/store.d.ts +1 -31
- package/dist/flags/store.js +13 -2
- package/dist/flags/store.js.map +1 -0
- package/dist/{helpers-Wg6P5fRQ.d.ts → helpers-zmC44Mcu.d.ts} +2 -3
- package/dist/index-BIsCUWAs.d.ts +1 -0
- package/dist/index-CwHYpK-f.d.ts +1 -0
- package/dist/index-DHrsNvX1.d.ts +1 -0
- package/dist/index.d.ts +41 -42
- package/dist/index.js +80 -98
- package/dist/kv/constants.d.ts +1 -1
- package/dist/kv/constants.js +22 -2
- package/dist/kv/constants.js.map +1 -0
- package/dist/kv/dotprops.js +26 -3
- package/dist/kv/dotprops.js.map +1 -0
- package/dist/kv/kv.d.ts +1 -2
- package/dist/kv/kv.js +15 -18
- package/dist/kv/kv.js.map +1 -1
- package/dist/kv/serde.d.ts +12 -3
- package/dist/kv/serde.js +87 -4
- package/dist/kv/serde.js.map +1 -0
- package/dist/label-DqGRqodo.d.ts +28 -0
- package/dist/logger/DefaultLogger.d.ts +66 -3
- package/dist/logger/DefaultLogger.js +2 -36
- package/dist/logger/ILogger.d.ts +64 -2
- package/dist/logger/ILogger.js +1 -1
- package/dist/logger/Logger.d.ts +36 -3
- package/dist/logger/Logger.js +2 -36
- package/dist/logger/NoopLogger.d.ts +1 -2
- package/dist/logger/NoopLogger.js +1 -0
- package/dist/logger/NoopLogger.js.map +1 -1
- package/dist/{media-gallery-BMsXSot3.d.ts → media-gallery-Ca8es-eB.d.ts} +3 -4
- package/dist/plugins/CompilerPlugin.d.ts +1 -31
- package/dist/plugins/CompilerPlugin.js +33 -4
- package/dist/plugins/CompilerPlugin.js.map +1 -0
- package/dist/plugins/PluginCommon.d.ts +1 -31
- package/dist/plugins/PluginCommon.js +55 -4
- package/dist/plugins/PluginCommon.js.map +1 -0
- package/dist/plugins/RuntimePlugin.d.ts +1 -31
- package/dist/plugins/RuntimePlugin.js +124 -4
- package/dist/plugins/RuntimePlugin.js.map +1 -0
- package/dist/plugins/index.d.ts +1 -31
- package/dist/plugins/index.js +8 -40
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.d.ts +1 -31
- package/dist/plugins/plugin-runtime/CommandKitPluginRuntime.js +2 -36
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.d.ts +1 -31
- package/dist/plugins/plugin-runtime/CompilerPluginRuntime.js +2 -36
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.d.ts +1 -31
- package/dist/plugins/plugin-runtime/builtin/CommonDirectiveTransformer.js +2 -36
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.d.ts +1 -31
- package/dist/plugins/plugin-runtime/builtin/MacroPlugin.js +2 -36
- package/dist/plugins/plugin-runtime/runtime.d.ts +1 -31
- package/dist/plugins/plugin-runtime/runtime.js +1 -1
- package/dist/plugins/types.d.ts +1 -31
- package/dist/plugins/types.js +1 -1
- package/dist/poll-DQ6DX_Tt.d.ts +88 -0
- package/dist/{section-Dh_FhPeC.d.ts → section-Q8nwx_-q.d.ts} +3 -4
- package/dist/{separator-CMf6Cyy5.d.ts → separator-B8P-kdIK.d.ts} +3 -4
- package/dist/{signals-SHg7J1U_.d.ts → signals-CBXwugBW.d.ts} +2 -2
- package/dist/{text-display-DRw3r_lK.d.ts → text-display-CL9C2yMc.d.ts} +3 -4
- package/dist/{types-CJ-XvOFN.d.ts → types-DZy7U-Ld.d.ts} +2 -2
- package/dist/types.d.ts +2 -32
- package/dist/types.js +1 -0
- package/dist/utils/colors.js +9 -3
- package/dist/utils/colors.js.map +1 -0
- package/dist/utils/constants.d.ts +2 -2
- package/dist/utils/constants.js +50 -7
- package/dist/utils/constants.js.map +1 -0
- package/dist/utils/dev-hooks.d.ts +1 -31
- package/dist/utils/dev-hooks.js +2 -36
- package/dist/utils/error-codes.d.ts +54 -2
- package/dist/utils/error-codes.js +53 -5
- package/dist/utils/error-codes.js.map +1 -0
- package/dist/utils/resolve-file-url.d.ts +11 -2
- package/dist/utils/resolve-file-url.js +18 -2
- package/dist/utils/resolve-file-url.js.map +1 -0
- package/dist/utils/types-package.js +61 -4
- package/dist/utils/types-package.js.map +1 -0
- package/dist/utils/useful-stuff/async-queue.js +2 -2
- package/dist/utils/useful-stuff/async-queue.js.map +1 -1
- package/dist/utils/useful-stuff/mutex.js +1 -0
- package/dist/utils/useful-stuff/mutex.js.map +1 -1
- package/dist/utils/useful-stuff/ratelimiter.js +2 -2
- package/dist/utils/useful-stuff/ratelimiter.js.map +1 -1
- package/dist/utils/useful-stuff/semaphore.js +2 -3
- package/dist/utils/useful-stuff/semaphore.js.map +1 -1
- package/dist/utils/utilities.d.ts +113 -2
- package/dist/utils/utilities.js +5 -37
- package/dist/utils/{warn-unstable.d.ts → warning.d.ts} +12 -3
- package/dist/utils/{warn-unstable.js → warning.js} +15 -2
- package/dist/utils/warning.js.map +1 -0
- package/dist/version.d.ts +8 -2
- package/dist/version.js +13 -2
- package/dist/version.js.map +1 -0
- package/hooks.cjs +11 -4
- package/package.json +22 -18
- package/dist/ActionRow-CbdGFWMT.js.map +0 -1
- package/dist/CommandKitEventsChannel-BtRzr3Tz.js +0 -88
- package/dist/CommandKitEventsChannel-BtRzr3Tz.js.map +0 -1
- package/dist/CommandsRouter-Cgcy6cK9.js +0 -220
- package/dist/CommandsRouter-Cgcy6cK9.js.map +0 -1
- package/dist/CompilerPlugin-M8r3yNAl.js +0 -43
- package/dist/CompilerPlugin-M8r3yNAl.js.map +0 -1
- package/dist/DefaultLogger-XCOl5nLd.d.ts +0 -67
- package/dist/EventInterceptor-CQEXyUTp.js +0 -142
- package/dist/EventInterceptor-CQEXyUTp.js.map +0 -1
- package/dist/EventWorkerContext-BMk7IXpC.d.ts +0 -43
- package/dist/EventWorkerContext-Dq29tieI.js +0 -69
- package/dist/EventWorkerContext-Dq29tieI.js.map +0 -1
- package/dist/EventsRouter-3Gygh-km.js +0 -137
- package/dist/EventsRouter-3Gygh-km.js.map +0 -1
- package/dist/ILogger-BW8GM-YZ.d.ts +0 -64
- package/dist/ILogger-dQ7Y9X1f.js +0 -0
- package/dist/Logger-DyfkPk7u.d.ts +0 -37
- package/dist/MessageCommandParser-CEuO6Ex3.js +0 -269
- package/dist/MessageCommandParser-CEuO6Ex3.js.map +0 -1
- package/dist/PluginCommon-Cvl5yYM_.js +0 -71
- package/dist/PluginCommon-Cvl5yYM_.js.map +0 -1
- package/dist/RuntimePlugin-BUecuBIU.js +0 -134
- package/dist/RuntimePlugin-BUecuBIU.js.map +0 -1
- package/dist/app-HN1cVg8J.js +0 -0
- package/dist/app-process-DoG6Spkf.js +0 -68
- package/dist/app-process-DoG6Spkf.js.map +0 -1
- package/dist/build-C9ltqPmn.js +0 -175
- package/dist/build-C9ltqPmn.js.map +0 -1
- package/dist/colors-DL3ucTiT.js +0 -15
- package/dist/colors-DL3ucTiT.js.map +0 -1
- package/dist/commandkit-Bm0gLN8i.js.map +0 -1
- package/dist/common-CcfjYnPG.js +0 -0
- package/dist/common-Dxr9-XPa.js +0 -211
- package/dist/common-Dxr9-XPa.js.map +0 -1
- package/dist/common-vnMIelAE.js +0 -17
- package/dist/common-vnMIelAE.js.map +0 -1
- package/dist/components/v1/action-row/ActionRow.d.ts +0 -6
- package/dist/components/v1/action-row/ActionRow.js +0 -3
- package/dist/components/v1/button/Button.d.ts +0 -7
- package/dist/components/v1/button/Button.js +0 -38
- package/dist/components/v1/button/ButtonKit.d.ts +0 -3
- package/dist/components/v1/button/ButtonKit.js +0 -38
- package/dist/components/v1/modal/Modal.d.ts +0 -7
- package/dist/components/v1/modal/Modal.js +0 -41
- package/dist/components/v1/modal/ModalKit.d.ts +0 -3
- package/dist/components/v1/modal/ModalKit.js +0 -38
- package/dist/components/v1/select-menu/ChannelSelectMenuKit.d.ts +0 -4
- package/dist/components/v1/select-menu/ChannelSelectMenuKit.js +0 -38
- package/dist/components/v1/select-menu/MentionableSelectMenuKit.d.ts +0 -4
- package/dist/components/v1/select-menu/MentionableSelectMenuKit.js +0 -38
- package/dist/components/v1/select-menu/RoleSelectMenuKit.d.ts +0 -4
- package/dist/components/v1/select-menu/RoleSelectMenuKit.js +0 -38
- package/dist/components/v1/select-menu/SelectMenu.d.ts +0 -10
- package/dist/components/v1/select-menu/SelectMenu.js +0 -43
- package/dist/components/v1/select-menu/StringSelectMenuKit.d.ts +0 -4
- package/dist/components/v1/select-menu/StringSelectMenuKit.js +0 -38
- package/dist/components/v1/select-menu/UserSelectMenuKit.d.ts +0 -4
- package/dist/components/v1/select-menu/UserSelectMenuKit.js +0 -38
- package/dist/components/v1/select-menu/common.d.ts +0 -3
- package/dist/components/v1/select-menu/common.js +0 -1
- package/dist/components/v2/common.js +0 -3
- package/dist/components/v2/container.d.ts +0 -2
- package/dist/components/v2/container.js +0 -4
- package/dist/components/v2/file.d.ts +0 -2
- package/dist/components/v2/file.js +0 -3
- package/dist/components/v2/index.d.ts +0 -8
- package/dist/components/v2/index.js +0 -17
- package/dist/components/v2/media-gallery.d.ts +0 -2
- package/dist/components/v2/media-gallery.js +0 -5
- package/dist/components/v2/section.d.ts +0 -2
- package/dist/components/v2/section.js +0 -5
- package/dist/components/v2/separator.d.ts +0 -2
- package/dist/components/v2/separator.js +0 -3
- package/dist/components/v2/text-display.d.ts +0 -2
- package/dist/components/v2/text-display.js +0 -3
- package/dist/config-BhVxyjmZ.d.ts +0 -16
- package/dist/constants-4oxxvaJA.js +0 -27
- package/dist/constants-4oxxvaJA.js.map +0 -1
- package/dist/constants-B5_Ta7PR.js +0 -70
- package/dist/constants-B5_Ta7PR.js.map +0 -1
- package/dist/constants-BOOGN85p.js +0 -37
- package/dist/constants-BOOGN85p.js.map +0 -1
- package/dist/container-C6GtfAPW.js +0 -44
- package/dist/container-C6GtfAPW.js.map +0 -1
- package/dist/dotprops-tnhpnszJ.js +0 -36
- package/dist/dotprops-tnhpnszJ.js.map +0 -1
- package/dist/element-Bak9llw_.js +0 -84
- package/dist/element-Bak9llw_.js.map +0 -1
- package/dist/env-_68PRRoA.js +0 -109
- package/dist/env-_68PRRoA.js.map +0 -1
- package/dist/error-codes-B4TyW4Ct.d.ts +0 -54
- package/dist/error-codes-Ds0bnPvT.js +0 -73
- package/dist/error-codes-Ds0bnPvT.js.map +0 -1
- package/dist/feature-flags-nZJB7-e5.js +0 -160
- package/dist/feature-flags-nZJB7-e5.js.map +0 -1
- package/dist/file-DVOELoNv.js.map +0 -1
- package/dist/helpers-BSwwrKJW.js +0 -36
- package/dist/helpers-BSwwrKJW.js.map +0 -1
- package/dist/index-DKcmsWXw.d.ts +0 -1
- package/dist/index-DSBMRX9A.d.ts +0 -1
- package/dist/index-DdqikUQD.d.ts +0 -1
- package/dist/index.js.map +0 -1
- package/dist/init-Cy_bcUt4.js +0 -95
- package/dist/init-Cy_bcUt4.js.map +0 -1
- package/dist/init-DOr-Y3GQ.d.ts +0 -13
- package/dist/media-gallery-zDtJ3kxb.js +0 -62
- package/dist/media-gallery-zDtJ3kxb.js.map +0 -1
- package/dist/resolve-file-url-ChIyw-Vf.js +0 -23
- package/dist/resolve-file-url-ChIyw-Vf.js.map +0 -1
- package/dist/resolve-file-url-yO8bUxok.d.ts +0 -11
- package/dist/router-Dn35v30f.js +0 -0
- package/dist/runtime-DB9CiPfe.js +0 -0
- package/dist/section-DlvrDoJK.js +0 -60
- package/dist/section-DlvrDoJK.js.map +0 -1
- package/dist/separator-DL6QH5H1.js.map +0 -1
- package/dist/serde-BYaKrsOV.d.ts +0 -12
- package/dist/serde-Cc8iUa9J.js +0 -97
- package/dist/serde-Cc8iUa9J.js.map +0 -1
- package/dist/signals-ChFMD7mB.js +0 -74
- package/dist/signals-ChFMD7mB.js.map +0 -1
- package/dist/store-CM6pWVZh.js +0 -19
- package/dist/store-CM6pWVZh.js.map +0 -1
- package/dist/text-display-DbMumig_.js.map +0 -1
- package/dist/type-checker-DR7RZFs5.js +0 -90
- package/dist/type-checker-DR7RZFs5.js.map +0 -1
- package/dist/types-CUZOquUl.js +0 -0
- package/dist/types-package-BWArjyBF.js +0 -75
- package/dist/types-package-BWArjyBF.js.map +0 -1
- package/dist/types-q0Nm882H.js +0 -0
- package/dist/utilities-DtdPlr4c.d.ts +0 -87
- package/dist/utils/warn-unstable.js.map +0 -1
- package/dist/utils-DCSnVAZ6.js +0 -23
- package/dist/utils-DCSnVAZ6.js.map +0 -1
- package/dist/utils-KsNof0Xz.js +0 -34
- package/dist/utils-KsNof0Xz.js.map +0 -1
- package/dist/v2-DofkPKHs.js +0 -0
- package/dist/version-CtJtBJXI.d.ts +0 -8
- package/dist/version-DRSQMx0w.js +0 -18
- package/dist/version-DRSQMx0w.js.map +0 -1
|
@@ -1,6 +1,54 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
//#region src/utils/error-codes.ts
|
|
4
|
+
/**
|
|
5
|
+
* The error codes used by CommandKit.
|
|
6
|
+
*/
|
|
7
|
+
const CommandKitErrorCodes = {
|
|
8
|
+
StopMiddlewares: Symbol("kStopMiddlewares"),
|
|
9
|
+
ForwardedCommand: Symbol("kForwardedCommand"),
|
|
10
|
+
InvalidCommandPrefix: Symbol("kInvalidCommandPrefix"),
|
|
11
|
+
PluginCaptureHandle: Symbol("kPluginCaptureHandle"),
|
|
12
|
+
StopEvents: Symbol("kStopEvents")
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Creates a new CommandKit error with the specified code.
|
|
16
|
+
* @param code The error code to assign to the error.
|
|
17
|
+
* @returns A new CommandKit error instance.
|
|
18
|
+
*/
|
|
19
|
+
function createCommandKitError(code) {
|
|
20
|
+
const error = /* @__PURE__ */ new Error();
|
|
21
|
+
Reflect.set(error, "code", code);
|
|
22
|
+
return error;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Checks if the given error is a CommandKit error.
|
|
26
|
+
* @param error The error to check.
|
|
27
|
+
* @returns True if the error is a CommandKit error, false otherwise.
|
|
28
|
+
*/
|
|
29
|
+
function isCommandKitError(error) {
|
|
30
|
+
if (!(error instanceof Error)) return false;
|
|
31
|
+
const code = Reflect.get(error, "code");
|
|
32
|
+
for (const key in CommandKitErrorCodes) if (CommandKitErrorCodes[key] === code) return true;
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Checks if the given error is of a specific CommandKit error type.
|
|
37
|
+
* @param error The error to check.
|
|
38
|
+
* @param code The error code or an array of error codes to check against.
|
|
39
|
+
* @returns True if the error matches the specified code(s), false otherwise.
|
|
40
|
+
*/
|
|
41
|
+
function isErrorType(error, code) {
|
|
42
|
+
if (!isCommandKitError(error)) return false;
|
|
43
|
+
const errorCode = Reflect.get(error, "code");
|
|
44
|
+
if (!errorCode) return false;
|
|
45
|
+
if (Array.isArray(code)) return code.includes(errorCode);
|
|
46
|
+
return errorCode === code;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
//#endregion
|
|
50
|
+
exports.CommandKitErrorCodes = CommandKitErrorCodes;
|
|
51
|
+
exports.createCommandKitError = createCommandKitError;
|
|
52
|
+
exports.isCommandKitError = isCommandKitError;
|
|
53
|
+
exports.isErrorType = isErrorType;
|
|
54
|
+
//# sourceMappingURL=error-codes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-codes.js","names":[],"sources":["../../src/utils/error-codes.ts"],"sourcesContent":["/**\n * The error codes used by CommandKit.\n */\nexport const CommandKitErrorCodes = {\n /**\n * Error code for exiting middleware.\n */\n StopMiddlewares: Symbol('kStopMiddlewares'),\n /**\n * Error code for forwarded commands.\n */\n ForwardedCommand: Symbol('kForwardedCommand'),\n /**\n * Error code for invalid command prefix.\n */\n InvalidCommandPrefix: Symbol('kInvalidCommandPrefix'),\n /**\n * Error code for plugin capture handle.\n */\n PluginCaptureHandle: Symbol('kPluginCaptureHandle'),\n /**\n * Error code for event interruption signal\n */\n StopEvents: Symbol('kStopEvents'),\n} as const;\n\n/**\n * The type for CommandKit errors.\n */\nexport type CommandKitError = Error & { code: symbol };\n\n/**\n * Creates a new CommandKit error with the specified code.\n * @param code The error code to assign to the error.\n * @returns A new CommandKit error instance.\n */\nexport function createCommandKitError(code: symbol): CommandKitError {\n const error = new Error() as CommandKitError;\n\n Reflect.set(error, 'code', code);\n\n return error;\n}\n\n/**\n * Checks if the given error is a CommandKit error.\n * @param error The error to check.\n * @returns True if the error is a CommandKit error, false otherwise.\n */\nexport function isCommandKitError(error: unknown): error is CommandKitError {\n if (!(error instanceof Error)) return false;\n const code = Reflect.get(error, 'code');\n\n for (const key in CommandKitErrorCodes) {\n if (CommandKitErrorCodes[key as keyof typeof CommandKitErrorCodes] === code)\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if the given error is of a specific CommandKit error type.\n * @param error The error to check.\n * @param code The error code or an array of error codes to check against.\n * @returns True if the error matches the specified code(s), false otherwise.\n */\nexport function isErrorType(error: unknown, code: symbol | symbol[]): boolean {\n if (!isCommandKitError(error)) return false;\n const errorCode = Reflect.get(error, 'code');\n\n if (!errorCode) return false;\n\n if (Array.isArray(code)) return code.includes(errorCode);\n\n return errorCode === code;\n}\n"],"mappings":";;;;;;AAGA,MAAa,uBAAuB;CAIlC,iBAAiB,OAAO,mBAAmB;CAI3C,kBAAkB,OAAO,oBAAoB;CAI7C,sBAAsB,OAAO,wBAAwB;CAIrD,qBAAqB,OAAO,uBAAuB;CAInD,YAAY,OAAO,cAAc;CAClC;;;;;;AAYD,SAAgB,sBAAsB,MAA+B;CACnE,MAAM,wBAAQ,IAAI,OAAO;AAEzB,SAAQ,IAAI,OAAO,QAAQ,KAAK;AAEhC,QAAO;;;;;;;AAQT,SAAgB,kBAAkB,OAA0C;AAC1E,KAAI,EAAE,iBAAiB,OAAQ,QAAO;CACtC,MAAM,OAAO,QAAQ,IAAI,OAAO,OAAO;AAEvC,MAAK,MAAM,OAAO,qBAChB,KAAI,qBAAqB,SAA8C,KACvE,QAAE;AAGJ,QAAO;;;;;;;;AAST,SAAgB,YAAY,OAAgB,MAAkC;AAC5E,KAAI,CAAC,kBAAkB,MAAM,CAAE,QAAO;CACtC,MAAM,YAAY,QAAQ,IAAI,OAAO,OAAO;AAE5C,KAAI,CAAC,UAAW,QAAO;AAEvB,KAAI,MAAM,QAAQ,KAAK,CAAE,QAAO,KAAK,SAAS,UAAU;AAExD,QAAO,cAAc"}
|
|
@@ -1,2 +1,11 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
//#region src/utils/resolve-file-url.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Convert a local file path to a file URL.
|
|
4
|
+
* @param filePath - The local file's path.
|
|
5
|
+
* @param withTs - Whether to append a timestamp to the URL.
|
|
6
|
+
* @returns - The converted file URL.
|
|
7
|
+
*/
|
|
8
|
+
declare function toFileURL(filePath: string, withTs?: boolean): string;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { toFileURL };
|
|
11
|
+
//# sourceMappingURL=resolve-file-url.d.ts.map
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_chunk = require('../chunk-BE-pF4vm.js');
|
|
3
|
+
let path = require("path");
|
|
4
|
+
path = require_chunk.__toESM(path);
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
//#region src/utils/resolve-file-url.ts
|
|
7
|
+
/**
|
|
8
|
+
* Convert a local file path to a file URL.
|
|
9
|
+
* @param filePath - The local file's path.
|
|
10
|
+
* @param withTs - Whether to append a timestamp to the URL.
|
|
11
|
+
* @returns - The converted file URL.
|
|
12
|
+
*/
|
|
13
|
+
function toFileURL(filePath, withTs = false) {
|
|
14
|
+
return `${"file://" + path.default.resolve(filePath).replace(/\\\\|\\/g, "/")}${withTs ? `?ts=${Date.now()}` : ""}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
//#endregion
|
|
18
|
+
exports.toFileURL = toFileURL;
|
|
19
|
+
//# sourceMappingURL=resolve-file-url.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-file-url.js","names":[],"sources":["../../src/utils/resolve-file-url.ts"],"sourcesContent":["import path from 'path';\n\n/**\n * Convert a local file path to a file URL.\n * @param filePath - The local file's path.\n * @param withTs - Whether to append a timestamp to the URL.\n * @returns - The converted file URL.\n */\nexport function toFileURL(filePath: string, withTs = false) {\n const resolvedPath = path.resolve(filePath);\n return `${'file://' + resolvedPath.replace(/\\\\\\\\|\\\\/g, '/')}${withTs ? `?ts=${Date.now()}` : ''}`;\n}\n"],"mappings":";;;;;;;;;;;;AAQA,SAAgB,UAAU,UAAkB,SAAS,OAAO;AAE1D,QAAO,GAAG,YADW,aAAK,QAAQ,SAAS,CACR,QAAQ,YAAY,IAAI,GAAG,SAAS,OAAO,KAAK,KAAK,KAAK"}
|
|
@@ -1,5 +1,62 @@
|
|
|
1
|
-
|
|
2
|
-
const
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_chunk = require('../chunk-BE-pF4vm.js');
|
|
3
|
+
const require_utils_constants = require('./constants.js');
|
|
4
|
+
let node_fs = require("node:fs");
|
|
5
|
+
let node_path = require("node:path");
|
|
6
|
+
let node_fs_promises = require("node:fs/promises");
|
|
3
7
|
|
|
4
|
-
|
|
5
|
-
|
|
8
|
+
//#region src/utils/types-package.ts
|
|
9
|
+
/**
|
|
10
|
+
* @private
|
|
11
|
+
*/
|
|
12
|
+
async function generateTypesPackage(force = false) {
|
|
13
|
+
const location = (0, node_path.join)(require_utils_constants.COMMANDKIT_CWD, "node_modules", "commandkit-types");
|
|
14
|
+
if (!require_utils_constants.COMMANDKIT_IS_DEV && !force) return location;
|
|
15
|
+
const packageJSON = (0, node_path.join)(location, "package.json");
|
|
16
|
+
const index = (0, node_path.join)(location, "index.js");
|
|
17
|
+
const types = (0, node_path.join)(location, "index.d.ts");
|
|
18
|
+
const command = (0, node_path.join)(location, "command.d.ts");
|
|
19
|
+
const packageJSONContent = {
|
|
20
|
+
name: "commandkit-types",
|
|
21
|
+
version: "1.0.0",
|
|
22
|
+
description: "CommandKit types package",
|
|
23
|
+
type: "commonjs",
|
|
24
|
+
main: "index.js",
|
|
25
|
+
types: "index.d.ts"
|
|
26
|
+
};
|
|
27
|
+
const indexContent = `module.exports = {};`;
|
|
28
|
+
const typesContent = `// Main types index file - imports all type declarations
|
|
29
|
+
import './command';
|
|
30
|
+
export {};
|
|
31
|
+
`;
|
|
32
|
+
const commandTypesContent = `// Auto-generated command types
|
|
33
|
+
export {};
|
|
34
|
+
declare module 'commandkit' {
|
|
35
|
+
type CommandTypeData = string
|
|
36
|
+
}`;
|
|
37
|
+
await (0, node_fs_promises.mkdir)(location, { recursive: true }).catch(() => {});
|
|
38
|
+
await (0, node_fs_promises.writeFile)(packageJSON, JSON.stringify(packageJSONContent, null, 2));
|
|
39
|
+
await (0, node_fs_promises.writeFile)(index, indexContent);
|
|
40
|
+
await (0, node_fs_promises.writeFile)(types, typesContent);
|
|
41
|
+
await (0, node_fs_promises.writeFile)(command, commandTypesContent);
|
|
42
|
+
return location;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* @private
|
|
46
|
+
*/
|
|
47
|
+
async function rewriteCommandDeclaration(data) {
|
|
48
|
+
const commandTypesContent = `// Auto-generated command types
|
|
49
|
+
declare module 'commandkit' {
|
|
50
|
+
${data}
|
|
51
|
+
}
|
|
52
|
+
export {};
|
|
53
|
+
`;
|
|
54
|
+
const location = (0, node_path.join)(require_utils_constants.COMMANDKIT_CWD, "node_modules", "commandkit-types");
|
|
55
|
+
if (!(0, node_fs.existsSync)(location)) return;
|
|
56
|
+
await (0, node_fs_promises.writeFile)((0, node_path.join)(location, "command.d.ts"), commandTypesContent, { encoding: "utf-8" });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
//#endregion
|
|
60
|
+
exports.generateTypesPackage = generateTypesPackage;
|
|
61
|
+
exports.rewriteCommandDeclaration = rewriteCommandDeclaration;
|
|
62
|
+
//# sourceMappingURL=types-package.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-package.js","names":[],"sources":["../../src/utils/types-package.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { COMMANDKIT_CWD, COMMANDKIT_IS_DEV } from './constants';\nimport { existsSync } from 'node:fs';\n\n/**\n * @private\n */\nexport async function generateTypesPackage(force = false) {\n const location = join(COMMANDKIT_CWD, 'node_modules', 'commandkit-types');\n if (!COMMANDKIT_IS_DEV && !force) return location;\n const packageJSON = join(location, 'package.json');\n const index = join(location, 'index.js');\n const types = join(location, 'index.d.ts');\n const command = join(location, 'command.d.ts');\n\n const packageJSONContent = {\n name: 'commandkit-types',\n version: '1.0.0',\n description: 'CommandKit types package',\n type: 'commonjs',\n main: 'index.js',\n types: 'index.d.ts',\n };\n\n const indexContent = `module.exports = {};`;\n\n // Restructuring the type declarations to properly extend rather than replace types\n const typesContent = `// Main types index file - imports all type declarations\nimport './command';\nexport {};\n`;\n\n // Properly set up command types to extend the CommandTypeData interface\n const commandTypesContent = `// Auto-generated command types\n export {};\ndeclare module 'commandkit' {\n type CommandTypeData = string\n}`;\n\n await mkdir(location, { recursive: true }).catch(() => {});\n await writeFile(packageJSON, JSON.stringify(packageJSONContent, null, 2));\n await writeFile(index, indexContent);\n await writeFile(types, typesContent);\n await writeFile(command, commandTypesContent);\n\n return location;\n}\n\n/**\n * @private\n */\nexport async function rewriteCommandDeclaration(data: string) {\n const commandTypesContent = `// Auto-generated command types\n declare module 'commandkit' {\n ${data}\n}\n export {};\n`;\n\n const location = join(COMMANDKIT_CWD, 'node_modules', 'commandkit-types');\n\n if (!existsSync(location)) return;\n\n const type = join(location, 'command.d.ts');\n\n await writeFile(type, commandTypesContent, { encoding: 'utf-8' });\n}\n"],"mappings":";;;;;;;;;;;AAQA,eAAsB,qBAAqB,QAAQ,OAAO;CACxD,MAAM,+BAAgB,wCAAgB,gBAAgB,mBAAmB;AACzE,KAAI,CAAC,6CAAqB,CAAC,MAAO,QAAO;CACzC,MAAM,kCAAmB,UAAU,eAAe;CAClD,MAAM,4BAAa,UAAU,WAAW;CACxC,MAAM,4BAAa,UAAU,aAAa;CAC1C,MAAM,8BAAe,UAAU,eAAe;CAE9C,MAAM,qBAAqB;EACzB,MAAM;EACN,SAAS;EACT,aAAa;EACb,MAAM;EACN,MAAM;EACN,OAAO;EACR;CAED,MAAM,eAAe;CAGrB,MAAM,eAAe;;;;CAMrB,MAAM,sBAAsB;;;;;AAM5B,mCAAY,UAAU,EAAE,WAAW,MAAM,CAAC,CAAC,YAAY,GAAG;AAC1D,uCAAgB,aAAa,KAAK,UAAU,oBAAoB,MAAM,EAAE,CAAC;AACzE,uCAAgB,OAAO,aAAa;AACpC,uCAAgB,OAAO,aAAa;AACpC,uCAAgB,SAAS,oBAAoB;AAE7C,QAAO;;;;;AAMT,eAAsB,0BAA0B,MAAc;CAC5D,MAAM,sBAAsB;;MAExB,KAAI;;;;CAKR,MAAM,+BAAgB,wCAAgB,gBAAgB,mBAAmB;AAEzE,KAAI,yBAAY,SAAS,CAAE;AAI3B,2DAFkB,UAAU,eAAe,EAErB,qBAAqB,EAAE,UAAU,SAAS,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
1
2
|
|
|
2
3
|
//#region src/utils/useful-stuff/async-queue.ts
|
|
3
4
|
var AsyncQueue = class {
|
|
@@ -37,8 +38,7 @@ var AsyncQueue = class {
|
|
|
37
38
|
}
|
|
38
39
|
this.running++;
|
|
39
40
|
try {
|
|
40
|
-
|
|
41
|
-
resolve(result);
|
|
41
|
+
resolve(await task());
|
|
42
42
|
} catch (err) {
|
|
43
43
|
reject(err);
|
|
44
44
|
} finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"async-queue.js","names":[],"sources":["../../../src/utils/useful-stuff/async-queue.ts"],"sourcesContent":["/**\n * Async queue implementation for processing tasks sequentially or with limited concurrency.\n * Useful for rate-limiting, batching, or controlling resource usage.\n */\n\nexport interface AsyncQueueOptions {\n /** Maximum number of concurrent tasks. Default: 1 (sequential) */\n concurrency?: number;\n /** Optional callback invoked when all tasks are completed */\n onDrain?: () => void | Promise<void>;\n /** Optional AbortSignal for cancelling the queue */\n signal?: AbortSignal;\n}\n\nexport type AsyncQueueTask<T> = () => Promise<T>;\n\nexport class AsyncQueue {\n private readonly concurrency: number;\n private readonly onDrain?: () => void | Promise<void>;\n private readonly signal?: AbortSignal;\n private running = 0;\n private paused = false;\n private aborted = false;\n private queue: Array<() => void> = [];\n\n constructor(options: AsyncQueueOptions = {}) {\n this.concurrency = options.concurrency ?? 1;\n this.onDrain = options.onDrain;\n this.signal = options.signal;\n\n if (this.signal) {\n this.signal.addEventListener('abort', () => {\n this.abort();\n });\n }\n }\n\n /**\n * Adds a task to the queue.\n * @param task - The async function to execute.\n * @param signal - Optional AbortSignal for cancelling this specific task.\n * @returns Promise resolving to the result of the task.\n */\n public add<T>(task: AsyncQueueTask<T>, signal?: AbortSignal): Promise<T> {\n if (this.aborted) {\n return Promise.reject(new Error('Queue has been aborted'));\n }\n\n return new Promise<T>((resolve, reject) => {\n const run = async () => {\n if (this.paused || this.aborted) {\n if (this.aborted) {\n reject(new Error('Queue has been aborted'));\n } else {\n this.queue.push(run);\n }\n return;\n }\n\n // Check if task-specific signal is aborted\n if (signal?.aborted) {\n reject(new Error('Task was aborted'));\n return;\n }\n\n this.running++;\n try {\n const result = await task();\n resolve(result);\n } catch (err) {\n reject(err);\n } finally {\n this.running--;\n this.next();\n }\n };\n\n if (this.running < this.concurrency && !this.paused && !this.aborted) {\n run();\n } else {\n this.queue.push(run);\n }\n });\n }\n\n /**\n * Pauses the queue. No new tasks will be started until resumed.\n */\n public pause() {\n this.paused = true;\n }\n\n /**\n * Resumes the queue and processes pending tasks.\n */\n public resume() {\n if (!this.paused) return;\n this.paused = false;\n this.next();\n }\n\n /**\n * Aborts the queue, rejecting all pending tasks.\n */\n public abort() {\n this.aborted = true;\n this.clear();\n }\n\n /**\n * Clears all pending tasks from the queue.\n */\n public clear() {\n this.queue = [];\n }\n\n /**\n * Returns the number of running tasks.\n */\n public getRunning(): number {\n return this.running;\n }\n\n /**\n * Returns the number of pending tasks in the queue.\n */\n public getPending(): number {\n return this.queue.length;\n }\n\n /**\n * Returns true if the queue is currently paused.\n */\n public isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Returns true if the queue has been aborted.\n */\n public isAborted(): boolean {\n return this.aborted;\n }\n\n private next() {\n if (this.paused || this.aborted) return;\n while (this.running < this.concurrency && this.queue.length > 0) {\n const fn = this.queue.shift();\n if (fn) fn();\n }\n if (this.running === 0 && this.queue.length === 0 && this.onDrain) {\n this.onDrain();\n }\n }\n}\n\n/**\n * Creates a new async queue instance with the specified configuration.\n * @param options - Configuration options for the async queue.\n * @returns New AsyncQueue instance.\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const queue = createAsyncQueue({\n * concurrency: 2,\n * signal: controller.signal\n * });\n * queue.add(async () => await doSomething());\n * controller.abort(); // Aborts the queue\n * ```\n */\nexport function createAsyncQueue(options?: AsyncQueueOptions): AsyncQueue {\n return new AsyncQueue(options);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"async-queue.js","names":[],"sources":["../../../src/utils/useful-stuff/async-queue.ts"],"sourcesContent":["/**\n * Async queue implementation for processing tasks sequentially or with limited concurrency.\n * Useful for rate-limiting, batching, or controlling resource usage.\n */\n\nexport interface AsyncQueueOptions {\n /** Maximum number of concurrent tasks. Default: 1 (sequential) */\n concurrency?: number;\n /** Optional callback invoked when all tasks are completed */\n onDrain?: () => void | Promise<void>;\n /** Optional AbortSignal for cancelling the queue */\n signal?: AbortSignal;\n}\n\nexport type AsyncQueueTask<T> = () => Promise<T>;\n\nexport class AsyncQueue {\n private readonly concurrency: number;\n private readonly onDrain?: () => void | Promise<void>;\n private readonly signal?: AbortSignal;\n private running = 0;\n private paused = false;\n private aborted = false;\n private queue: Array<() => void> = [];\n\n constructor(options: AsyncQueueOptions = {}) {\n this.concurrency = options.concurrency ?? 1;\n this.onDrain = options.onDrain;\n this.signal = options.signal;\n\n if (this.signal) {\n this.signal.addEventListener('abort', () => {\n this.abort();\n });\n }\n }\n\n /**\n * Adds a task to the queue.\n * @param task - The async function to execute.\n * @param signal - Optional AbortSignal for cancelling this specific task.\n * @returns Promise resolving to the result of the task.\n */\n public add<T>(task: AsyncQueueTask<T>, signal?: AbortSignal): Promise<T> {\n if (this.aborted) {\n return Promise.reject(new Error('Queue has been aborted'));\n }\n\n return new Promise<T>((resolve, reject) => {\n const run = async () => {\n if (this.paused || this.aborted) {\n if (this.aborted) {\n reject(new Error('Queue has been aborted'));\n } else {\n this.queue.push(run);\n }\n return;\n }\n\n // Check if task-specific signal is aborted\n if (signal?.aborted) {\n reject(new Error('Task was aborted'));\n return;\n }\n\n this.running++;\n try {\n const result = await task();\n resolve(result);\n } catch (err) {\n reject(err);\n } finally {\n this.running--;\n this.next();\n }\n };\n\n if (this.running < this.concurrency && !this.paused && !this.aborted) {\n run();\n } else {\n this.queue.push(run);\n }\n });\n }\n\n /**\n * Pauses the queue. No new tasks will be started until resumed.\n */\n public pause() {\n this.paused = true;\n }\n\n /**\n * Resumes the queue and processes pending tasks.\n */\n public resume() {\n if (!this.paused) return;\n this.paused = false;\n this.next();\n }\n\n /**\n * Aborts the queue, rejecting all pending tasks.\n */\n public abort() {\n this.aborted = true;\n this.clear();\n }\n\n /**\n * Clears all pending tasks from the queue.\n */\n public clear() {\n this.queue = [];\n }\n\n /**\n * Returns the number of running tasks.\n */\n public getRunning(): number {\n return this.running;\n }\n\n /**\n * Returns the number of pending tasks in the queue.\n */\n public getPending(): number {\n return this.queue.length;\n }\n\n /**\n * Returns true if the queue is currently paused.\n */\n public isPaused(): boolean {\n return this.paused;\n }\n\n /**\n * Returns true if the queue has been aborted.\n */\n public isAborted(): boolean {\n return this.aborted;\n }\n\n private next() {\n if (this.paused || this.aborted) return;\n while (this.running < this.concurrency && this.queue.length > 0) {\n const fn = this.queue.shift();\n if (fn) fn();\n }\n if (this.running === 0 && this.queue.length === 0 && this.onDrain) {\n this.onDrain();\n }\n }\n}\n\n/**\n * Creates a new async queue instance with the specified configuration.\n * @param options - Configuration options for the async queue.\n * @returns New AsyncQueue instance.\n *\n * @example\n * ```typescript\n * const controller = new AbortController();\n * const queue = createAsyncQueue({\n * concurrency: 2,\n * signal: controller.signal\n * });\n * queue.add(async () => await doSomething());\n * controller.abort(); // Aborts the queue\n * ```\n */\nexport function createAsyncQueue(options?: AsyncQueueOptions): AsyncQueue {\n return new AsyncQueue(options);\n}\n"],"mappings":";;;AAgBA,IAAa,aAAb,MAAwB;CACtB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAQ,UAAU;CAClB,AAAQ,SAAS;CACjB,AAAQ,UAAU;CAClB,AAAQ,QAA2B,EAAE;CAErC,YAAY,UAA6B,EAAE,EAAE;AAC3C,OAAK,cAAc,QAAQ,eAAe;AAC1C,OAAK,UAAU,QAAQ;AACvB,OAAK,SAAS,QAAQ;AAEtB,MAAI,KAAK,OACP,MAAK,OAAO,iBAAiB,eAAe;AAC1C,QAAK,OAAO;IACZ;;;;;;;;CAUN,AAAO,IAAO,MAAyB,QAAkC;AACvE,MAAI,KAAK,QACP,QAAO,QAAQ,uBAAO,IAAI,MAAM,yBAAyB,CAAC;AAG5D,SAAO,IAAI,SAAY,SAAS,WAAW;GACzC,MAAM,MAAM,YAAY;AACtB,QAAI,KAAK,UAAU,KAAK,SAAS;AAC/B,SAAI,KAAK,QACP,wBAAO,IAAI,MAAM,yBAAyB,CAAC;SAE3C,MAAK,MAAM,KAAK,IAAI;AAEtB;;AAIF,wDAAI,OAAQ,SAAS;AACnB,4BAAO,IAAI,MAAM,mBAAmB,CAAC;AACrC;;AAGF,SAAK;AACL,QAAI;AAEF,aADe,MAAM,MAAM,CACZ;aACR,KAAK;AACZ,YAAO,IAAI;cACH;AACR,UAAK;AACL,UAAK,MAAM;;;AAIf,OAAI,KAAK,UAAU,KAAK,eAAe,CAAC,KAAK,UAAU,CAAC,KAAK,QAC3D,MAAK;OAEL,MAAK,MAAM,KAAK,IAAI;IAEtB;;;;;CAMJ,AAAO,QAAQ;AACb,OAAK,SAAS;;;;;CAMhB,AAAO,SAAS;AACd,MAAI,CAAC,KAAK,OAAQ;AAClB,OAAK,SAAS;AACd,OAAK,MAAM;;;;;CAMb,AAAO,QAAQ;AACb,OAAK,UAAU;AACf,OAAK,OAAO;;;;;CAMd,AAAO,QAAQ;AACb,OAAK,QAAQ,EAAE;;;;;CAMjB,AAAO,aAAqB;AAC1B,SAAO,KAAK;;;;;CAMd,AAAO,aAAqB;AAC1B,SAAO,KAAK,MAAM;;;;;CAMpB,AAAO,WAAoB;AACzB,SAAO,KAAK;;;;;CAMd,AAAO,YAAqB;AAC1B,SAAO,KAAK;;CAGd,AAAQ,OAAO;AACb,MAAI,KAAK,UAAU,KAAK,QAAS;AACjC,SAAO,KAAK,UAAU,KAAK,eAAe,KAAK,MAAM,SAAS,GAAG;GAC/D,MAAM,KAAK,KAAK,MAAM,OAAO;AAC7B,OAAI,GAAI,KAAI;;AAEd,MAAI,KAAK,YAAY,KAAK,KAAK,MAAM,WAAW,KAAK,KAAK,QACxD,MAAK,SAAS;;;;;;;;;;;;;;;;;;;AAqBpB,SAAgB,iBAAiB,SAAyC;AACxE,QAAO,IAAI,WAAW,QAAQ"}
|
|
@@ -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> {\n return defaultMutex.isLocked(key);\n}\n"],"mappings":";;;;;;AAoDA,IAAa,qBAAb,MAAwD;CACtD,AAAiB,wBAAQ,IAAI,KAG5B;;;;;;;;CASD,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,SAAS,KAAK,kBAAkB;EACtC,MAAM,YAAY,KAAK,KAAK;AAE5B,SAAO,KAAK,KAAK,GAAG,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM,+BAA+B;AAGjD,OAAI,CAAC,KAAK,MAAM,IAAI,IAAI,EAAE;AACxB,SAAK,MAAM,IAAI,KAAK;KAAE;KAAQ,YAAY,KAAK,KAAK;KAAE,CAAC;AACvD,WAAO;;AAET,SAAM,KAAK,MAAM,GAAG;;AAGtB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;AACxC,OAAK,MAAM,OAAO,IAAI;;;;;;;CAQxB,MAAM,SAAS,KAA+B;AAC5C,SAAO,KAAK,MAAM,IAAI,IAAI;;CAG5B,AAAQ,mBAA2B;AACjC,SAAO,UAAU,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,OAAO,GAAG,EAAE;;CAGxE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;AAQ5D,IAAa,QAAb,MAAmB;CACjB,AAAQ;CACR,AAAiB;;;;;CAMjB,AAAO,YAAY,UAAwB,EAAE,EAAE;AAC7C,OAAK,UAAU,QAAQ,WAAW,IAAI,oBAAoB;AAC1D,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,OAAO;;;;;;;CAQ1E,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ,IAAI;;;;;;;CAQlC,MAAa,SAAS,KAA+B;AACnD,SAAO,KAAK,QAAQ,SAAS,IAAI;;;;;;;;;;;CAYnC,MAAa,SACb,KACA,IACA,SACA,QACa;AAEX,MAAI,CADa,MAAM,KAAK,QAAQ,KAAK,SAAS,OAAO,CAEvD,OAAM,IAAI,MAAM,mCAAmC,MAAM;AAG3D,MAAI;AACF,UAAO,MAAM,IAAI;YACT;AACR,SAAM,KAAK,QAAQ,IAAI;;;;;;;CAQ3B,AAAO,YAA2C;AAChD,SAAO,EACL,SAAS,KAAK,gBACf;;;;;;AAOL,MAAa,eAAe,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;AAqBvC,eAAsB,UACtB,KACA,IACA,SACA,QACa;AACX,QAAO,aAAa,SAAS,KAAK,IAAI,SAAS,OAAO;;;;;;;;;;;;;;;AAgBxD,SAAgB,YAAY,SAA8B;AACxD,QAAO,IAAI,MAAM,QAAQ;;;;;;;;;AAU3B,eAAsB,YACtB,KACA,SACA,QACmB;AACjB,QAAO,aAAa,QAAQ,KAAK,SAAS,OAAO;;;;;;;AAQnD,eAAsB,YAAY,KAA4B;AAC5D,QAAO,aAAa,QAAQ,IAAI;;;;;;;AAQlC,eAAsB,SAAS,KAA+B;AAC5D,QAAO,aAAa,SAAS,IAAI"}
|
|
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,KAG5B;;;;;;;;CASD,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,SAAS,KAAK,kBAAkB;EACtC,MAAM,YAAY,KAAK,KAAK;AAE5B,SAAO,KAAK,KAAK,GAAG,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM,+BAA+B;AAGjD,OAAI,CAAC,KAAK,MAAM,IAAI,IAAI,EAAE;AACxB,SAAK,MAAM,IAAI,KAAK;KAAE;KAAQ,YAAY,KAAK,KAAK;KAAE,CAAC;AACvD,WAAO;;AAET,SAAM,KAAK,MAAM,GAAG;;AAGtB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;AACxC,OAAK,MAAM,OAAO,IAAI;;;;;;;CAQxB,MAAM,SAAS,KAA+B;AAC5C,SAAO,KAAK,MAAM,IAAI,IAAI;;CAG5B,AAAQ,mBAA2B;AACjC,SAAO,UAAU,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,OAAO,GAAG,EAAE;;CAGxE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;AAQ5D,IAAa,QAAb,MAAmB;CACjB,AAAQ;CACR,AAAiB;;;;;CAMjB,AAAO,YAAY,UAAwB,EAAE,EAAE;AAC7C,OAAK,UAAU,QAAQ,WAAW,IAAI,oBAAoB;AAC1D,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,OAAO;;;;;;;CAQ1E,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ,IAAI;;;;;;;CAQlC,MAAa,SAAS,KAA+B;AACnD,SAAO,KAAK,QAAQ,SAAS,IAAI;;;;;;;;;;;CAYnC,MAAa,SACb,KACA,IACA,SACA,QACa;AAEX,MAAI,CADa,MAAM,KAAK,QAAQ,KAAK,SAAS,OAAO,CAEvD,OAAM,IAAI,MAAM,mCAAmC,MAAM;AAG3D,MAAI;AACF,UAAO,MAAM,IAAI;YACT;AACR,SAAM,KAAK,QAAQ,IAAI;;;;;;;CAQ3B,AAAO,YAA2C;AAChD,SAAO,EACL,SAAS,KAAK,gBACf;;;;;;AAOL,MAAa,eAAe,IAAI,OAAO;;;;;;;;;;;;;;;;;;;;AAqBvC,eAAsB,UACtB,KACA,IACA,SACA,QACa;AACX,QAAO,aAAa,SAAS,KAAK,IAAI,SAAS,OAAO;;;;;;;;;;;;;;;AAgBxD,SAAgB,YAAY,SAA8B;AACxD,QAAO,IAAI,MAAM,QAAQ;;;;;;;;;AAU3B,eAAsB,YACtB,KACA,SACA,QACmB;AACjB,QAAO,aAAa,QAAQ,KAAK,SAAS,OAAO;;;;;;;AAQnD,eAAsB,YAAY,KAA4B;AAC5D,QAAO,aAAa,QAAQ,IAAI;;;;;;;AAQlC,eAAsB,SAAS,KAA+B;AAC5D,QAAO,aAAa,SAAS,IAAI"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
1
2
|
|
|
2
3
|
//#region src/utils/useful-stuff/ratelimiter.ts
|
|
3
4
|
/**
|
|
@@ -81,8 +82,7 @@ var RateLimiter = class {
|
|
|
81
82
|
*/
|
|
82
83
|
async limit(key) {
|
|
83
84
|
const now = Date.now();
|
|
84
|
-
|
|
85
|
-
if (now - lastReset > this.resetInterval) {
|
|
85
|
+
if (now - (this.lastReset.get(key) || 0) > this.resetInterval) {
|
|
86
86
|
await this.storage.delete(key);
|
|
87
87
|
this.lastReset.set(key, now);
|
|
88
88
|
this.limits.set(key, 0);
|
|
@@ -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,KAAqB;;;;;;CAOlD,MAAM,IAAI,KAA8B;AACtC,SAAO,KAAK,MAAM,IAAI,IAAI,IAAI;;;;;;;;CAShC,MAAM,IAAI,KAAa,OAA8B;AACnD,OAAK,MAAM,IAAI,KAAK,MAAM;;;;;;;CAQ5B,MAAM,OAAO,KAA4B;AACvC,OAAK,MAAM,OAAO,IAAI;;;;;;;AAQ1B,IAAa,cAAb,MAAyB;CACvB,AAAiB,yBAA8B,IAAI,KAAK;CACxD,AAAiB,4BAAiC,IAAI,KAAK;CAC3D,AAAiB;;;;;;;CAQjB,AAAO,YACP,AAAiB,cAAsB,sBACvC,AAAiB,WAAmB,iBACpC,AAAQ,UAA4B,IAAI,wBAAwB,EAChE;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,KAAK;EACtB,MAAM,YAAY,KAAK,UAAU,IAAI,IAAI,IAAI;AAI7C,MAHuB,MAAM,YAGR,KAAK,eAAe;AACvC,SAAM,KAAK,QAAQ,OAAO,IAAI;AAC9B,QAAK,UAAU,IAAI,KAAK,IAAI;AAC5B,QAAK,OAAO,IAAI,KAAK,EAAE;;EAIzB,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI,IAAI;AAGhD,MAAI,gBAAgB,KAAK,YACvB,QAAO;EAIT,MAAM,WAAW,eAAe;AAChC,QAAM,KAAK,QAAQ,IAAI,KAAK,SAAS;AACrC,OAAK,OAAO,IAAI,KAAK,SAAS;AAE9B,SAAO;;;;;;;CAQT,MAAa,aAAa,KAA8B;EACtD,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI,IAAI;AAChD,SAAO,KAAK,IAAI,GAAG,KAAK,cAAc,aAAa;;;;;;;CAQrD,MAAa,aAAa,KAA8B;EACtD,MAAM,YAAY,KAAK,UAAU,IAAI,IAAI,IAAI;EAE7C,MAAM,iBADM,KAAK,KAAK,GACO;AAE7B,MAAI,kBAAkB,KAAK,cACzB,QAAO;AAGT,SAAO,KAAK,gBAAgB;;;;;;;CAQ9B,MAAa,MAAM,KAA4B;AAC7C,QAAM,KAAK,QAAQ,OAAO,IAAI;AAC9B,OAAK,OAAO,OAAO,IAAI;AACvB,OAAK,UAAU,OAAO,IAAI;;;;;;CAO5B,AAAO,YAA+C;AACpD,SAAO;GACL,aAAa,KAAK;GAClB,UAAU,KAAK;GAChB;;;;;;AAOL,MAAa,qBAAqB,IAAI,aAAa;;;;;;;;;;;;;;;;;;;;;;;;AAyBnD,eAAsB,UAAU,KAA+B;AAC7D,QAAO,mBAAmB,MAAM,IAAI;;;;;;;;;;;;;;;;AAiBtC,SAAgB,kBAAkB,SAAwC;AACxE,QAAO,IAAI,YACT,QAAQ,aACR,QAAQ,UACR,QAAQ,QACT;;;;;;;AAQH,eAAsB,qBAAqB,KAA8B;AACvE,QAAO,mBAAmB,aAAa,IAAI;;;;;;;AAQ7C,eAAsB,aAAa,KAA8B;AAC/D,QAAO,mBAAmB,aAAa,IAAI;;;;;;;AAQ7C,eAAsB,eAAe,KAA4B;AAC/D,QAAO,mBAAmB,MAAM,IAAI"}
|
|
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,KAAqB;;;;;;CAOlD,MAAM,IAAI,KAA8B;AACtC,SAAO,KAAK,MAAM,IAAI,IAAI,IAAI;;;;;;;;CAShC,MAAM,IAAI,KAAa,OAA8B;AACnD,OAAK,MAAM,IAAI,KAAK,MAAM;;;;;;;CAQ5B,MAAM,OAAO,KAA4B;AACvC,OAAK,MAAM,OAAO,IAAI;;;;;;;AAQ1B,IAAa,cAAb,MAAyB;CACvB,AAAiB,yBAA8B,IAAI,KAAK;CACxD,AAAiB,4BAAiC,IAAI,KAAK;CAC3D,AAAiB;;;;;;;CAQjB,AAAO,YACP,AAAU,cAA6B,sBACvC,AAAU,WAA0B,iBACpC,AAAE,UAAkC,IAAE,wBAA0B,EAChE;EAHU;EACA;EACR;AAEA,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,KAAK;AAKtB,MAHuB,OADL,KAAK,UAAU,IAAI,IAAI,IAAI,KAIxB,KAAK,eAAe;AACvC,SAAM,KAAK,QAAQ,OAAO,IAAI;AAC9B,QAAK,UAAU,IAAI,KAAK,IAAI;AAC5B,QAAK,OAAO,IAAI,KAAK,EAAE;;EAIzB,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI,IAAI;AAGhD,MAAI,gBAAgB,KAAK,YACvB,QAAO;EAIT,MAAM,WAAW,eAAe;AAChC,QAAM,KAAK,QAAQ,IAAI,KAAK,SAAS;AACrC,OAAK,OAAO,IAAI,KAAK,SAAS;AAE9B,SAAO;;;;;;;CAQT,MAAa,aAAa,KAA8B;EACtD,MAAM,eAAe,MAAM,KAAK,QAAQ,IAAI,IAAI;AAChD,SAAO,KAAK,IAAI,GAAG,KAAK,cAAc,aAAa;;;;;;;CAQrD,MAAa,aAAa,KAA8B;EACtD,MAAM,YAAY,KAAK,UAAU,IAAI,IAAI,IAAI;EAE7C,MAAM,iBADM,KAAK,KAAK,GACO;AAE7B,MAAI,kBAAkB,KAAK,cACzB,QAAO;AAGT,SAAO,KAAK,gBAAgB;;;;;;;CAQ9B,MAAa,MAAM,KAA4B;AAC7C,QAAM,KAAK,QAAQ,OAAO,IAAI;AAC9B,OAAK,OAAO,OAAO,IAAI;AACvB,OAAK,UAAU,OAAO,IAAI;;;;;;CAO5B,AAAO,YAA+C;AACpD,SAAO;GACL,aAAa,KAAK;GAClB,UAAU,KAAK;GAChB;;;;;;AAOL,MAAa,qBAAqB,IAAI,aAAa;;;;;;;;;;;;;;;;;;;;;;;;AAyBnD,eAAsB,UAAU,KAA+B;AAC7D,QAAO,mBAAmB,MAAM,IAAI;;;;;;;;;;;;;;;;AAiBtC,SAAgB,kBAAkB,SAAwC;AACxE,QAAO,IAAI,YACT,QAAQ,aACR,QAAQ,UACR,QAAQ,QACT;;;;;;;AAQH,eAAsB,qBAAqB,KAA8B;AACvE,QAAO,mBAAmB,aAAa,IAAI;;;;;;;AAQ7C,eAAsB,aAAa,KAA8B;AAC/D,QAAO,mBAAmB,aAAa,IAAI;;;;;;;AAQ7C,eAAsB,eAAe,KAA4B;AAC/D,QAAO,mBAAmB,MAAM,IAAI"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
1
2
|
|
|
2
3
|
//#region src/utils/useful-stuff/semaphore.ts
|
|
3
4
|
/**
|
|
@@ -142,9 +143,7 @@ var Semaphore = class {
|
|
|
142
143
|
* @returns Promise resolving to the number of acquired permits
|
|
143
144
|
*/
|
|
144
145
|
async getAcquiredPermits(key) {
|
|
145
|
-
|
|
146
|
-
const available = await this.getAvailablePermits(key);
|
|
147
|
-
return total - available;
|
|
146
|
+
return await this.getTotalPermits(key) - await this.getAvailablePermits(key);
|
|
148
147
|
}
|
|
149
148
|
/**
|
|
150
149
|
* Executes a function with a permit from the semaphore
|
|
@@ -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,KAGjC;;;;;;;;CASD,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,YAAY,KAAK,KAAK;AAE5B,SAAO,KAAK,KAAK,GAAG,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM,iCAAiC;GAGnD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,OAAI,aAAa,UAAU,YAAY,GAAG;AACxC,cAAU;AACV,WAAO;;AAET,SAAM,KAAK,MAAM,GAAG;;AAGtB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;EACxC,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,MAAI,aAAa,UAAU,YAAY,UAAU,MAC/C,WAAU;;;;;;;CASd,MAAM,oBAAoB,KAA8B;EACtD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,SAAO,YAAY,UAAU,YAAY;;;;;;;CAQ3C,MAAM,gBAAgB,KAA8B;EAClD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,SAAO,YAAY,UAAU,QAAQ;;;;;;;CAQvC,WAAW,KAAa,SAAuB;AAC7C,OAAK,WAAW,IAAI,KAAK;GAAE,OAAO;GAAS,WAAW;GAAS,CAAC;;CAGlE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;AAQ5D,IAAa,YAAb,MAAuB;CACrB,AAAQ;CACR,AAAiB;CACjB,AAAiB;;;;;CAMjB,AAAO,YAAY,UAA4B,EAAE,EAAE;AACjD,OAAK,UAAU,QAAQ,WAAW,IAAI,wBAAwB;AAC9D,OAAK,iBAAiB,QAAQ,WAAW;AACzC,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AAEjB,MAAI,KAAK,mBAAmB,wBAE1B;OADqB,MAAM,KAAK,QAAQ,gBAAgB,IAAI,KACvC,EACnB,CAAC,KAAK,QAAmC,WACvC,KACA,KAAK,eACN;;AAIL,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB,OAAO;;;;;;;CAQ1E,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ,IAAI;;;;;;;CAQlC,MAAa,oBAAoB,KAA8B;AAC7D,SAAO,KAAK,QAAQ,oBAAoB,IAAI;;;;;;;CAQ9C,MAAa,gBAAgB,KAA8B;AACzD,SAAO,KAAK,QAAQ,gBAAgB,IAAI;;;;;;;CAQ1C,MAAa,mBAAmB,KAA8B;EAC5D,MAAM,QAAQ,MAAM,KAAK,gBAAgB,IAAI;EAC7C,MAAM,YAAY,MAAM,KAAK,oBAAoB,IAAI;AACrD,SAAO,QAAQ;;;;;;;;;;;CAYjB,MAAa,WACb,KACA,IACA,SACA,QACa;AAEX,MAAI,CADa,MAAM,KAAK,QAAQ,KAAK,SAAS,OAAO,CAEvD,OAAM,IAAI,MAAM,qCAAqC,MAAM;AAG7D,MAAI;AACF,UAAO,MAAM,IAAI;YACT;AACR,SAAM,KAAK,QAAQ,IAAI;;;;;;;CAQ3B,AAAO,YAA+C;AACpD,SAAO;GACL,SAAS,KAAK;GACd,SAAS,KAAK;GACf;;;;;;AAOL,MAAa,mBAAmB,IAAI,WAAW;;;;;;;;;;;;;;;;;;;;AAqB/C,eAAsB,WACtB,KACA,IACA,SACA,QACa;AACX,QAAO,iBAAiB,WAAW,KAAK,IAAI,SAAS,OAAO;;;;;;;;;;;;;;;;AAiB9D,SAAgB,gBAAgB,SAAsC;AACpE,QAAO,IAAI,UAAU,QAAQ;;;;;;;;;AAU/B,eAAsB,cACtB,KACA,SACA,QACmB;AACjB,QAAO,iBAAiB,QAAQ,KAAK,SAAS,OAAO;;;;;;;AAQvD,eAAsB,cAAc,KAA4B;AAC9D,QAAO,iBAAiB,QAAQ,IAAI;;;;;;;AAQtC,eAAsB,oBAAoB,KAA8B;AACtE,QAAO,iBAAiB,oBAAoB,IAAI;;;;;;;AAQlD,eAAsB,mBAAmB,KAA8B;AACrE,QAAO,iBAAiB,mBAAmB,IAAI"}
|
|
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,KAGjC;;;;;;;;CASD,MAAM,QACN,KACA,UAAkB,KAClB,QACmB;EACjB,MAAM,YAAY,KAAK,KAAK;AAE5B,SAAO,KAAK,KAAK,GAAG,YAAY,SAAS;AAEvC,uDAAI,OAAQ,QACV,OAAM,IAAI,MAAM,iCAAiC;GAGnD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,OAAI,aAAa,UAAU,YAAY,GAAG;AACxC,cAAU;AACV,WAAO;;AAET,SAAM,KAAK,MAAM,GAAG;;AAGtB,SAAO;;;;;;;CAQT,MAAM,QAAQ,KAA4B;EACxC,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,MAAI,aAAa,UAAU,YAAY,UAAU,MAC/C,WAAU;;;;;;;CASd,MAAM,oBAAoB,KAA8B;EACtD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,SAAO,YAAY,UAAU,YAAY;;;;;;;CAQ3C,MAAM,gBAAgB,KAA8B;EAClD,MAAM,YAAY,KAAK,WAAW,IAAI,IAAI;AAC1C,SAAO,YAAY,UAAU,QAAQ;;;;;;;CAQvC,WAAW,KAAa,SAAuB;AAC7C,OAAK,WAAW,IAAI,KAAK;GAAE,OAAO;GAAS,WAAW;GAAS,CAAC;;CAGlE,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;;;;;;;AAQ5D,IAAa,YAAb,MAAuB;CACrB,AAAQ;CACR,AAAiB;CACjB,AAAiB;;;;;CAMjB,AAAO,YAAY,UAA4B,EAAE,EAAE;AACjD,OAAK,UAAU,QAAQ,WAAW,IAAI,wBAAwB;AAC9D,OAAK,iBAAiB,QAAQ,WAAW;AACzC,OAAK,iBAAiB,QAAQ,WAAW;;;;;;CAO3C,AAAO,WAAW,SAA2B;AAC3C,OAAK,UAAU;;;;;;CAOjB,AAAO,aAA+B;AACpC,SAAO,KAAK;;;;;;;;;CAUd,MAAa,QACb,KACA,SACA,QACmB;AAEjB,MAAI,KAAK,mBAAmB,wBAE1B;OADqB,MAAM,KAAK,QAAQ,gBAAgB,IAAI,KACvC,EACnB,CAAC,KAAK,QAAmC,WACvC,KACA,KAAK,eACN;;AAIL,SAAO,KAAK,QAAQ,QAAQ,KAAK,WAAW,KAAK,gBAAgB,OAAO;;;;;;;CAQ1E,MAAa,QAAQ,KAA4B;AAC/C,SAAO,KAAK,QAAQ,QAAQ,IAAI;;;;;;;CAQlC,MAAa,oBAAoB,KAA8B;AAC7D,SAAO,KAAK,QAAQ,oBAAoB,IAAI;;;;;;;CAQ9C,MAAa,gBAAgB,KAA8B;AACzD,SAAO,KAAK,QAAQ,gBAAgB,IAAI;;;;;;;CAQ1C,MAAa,mBAAmB,KAA8B;AAG5D,SAFc,MAAM,KAAK,gBAAgB,IAAI,GAC3B,MAAM,KAAK,oBAAoB,IAAI;;;;;;;;;;;CAavD,MAAa,WACb,KACA,IACA,SACA,QACa;AAEX,MAAI,CADa,MAAM,KAAK,QAAQ,KAAK,SAAS,OAAO,CAEvD,OAAM,IAAI,MAAM,qCAAqC,MAAM;AAG7D,MAAI;AACF,UAAO,MAAM,IAAI;YACT;AACR,SAAM,KAAK,QAAQ,IAAI;;;;;;;CAQ3B,AAAO,YAA+C;AACpD,SAAO;GACL,SAAS,KAAK;GACd,SAAS,KAAK;GACf;;;;;;AAOL,MAAa,mBAAmB,IAAI,WAAW;;;;;;;;;;;;;;;;;;;;AAqB/C,eAAsB,WACtB,KACA,IACA,SACA,QACa;AACX,QAAO,iBAAiB,WAAW,KAAK,IAAI,SAAS,OAAO;;;;;;;;;;;;;;;;AAiB9D,SAAgB,gBAAgB,SAAsC;AACpE,QAAO,IAAI,UAAU,QAAQ;;;;;;;;;AAU/B,eAAsB,cACtB,KACA,SACA,QACmB;AACjB,QAAO,iBAAiB,QAAQ,KAAK,SAAS,OAAO;;;;;;;AAQvD,eAAsB,cAAc,KAA4B;AAC9D,QAAO,iBAAiB,QAAQ,IAAI;;;;;;;AAQtC,eAAsB,oBAAoB,KAA8B;AACtE,QAAO,iBAAiB,oBAAoB,IAAI;;;;;;;AAQlD,eAAsB,mBAAmB,KAA8B;AACrE,QAAO,iBAAiB,mBAAmB,IAAI"}
|
|
@@ -1,2 +1,113 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
//#region src/utils/utilities.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Returns the current working directory of the CommandKit application.
|
|
4
|
+
* This is typically the directory where the source code is located.
|
|
5
|
+
*/
|
|
6
|
+
declare function getCurrentDirectory(): string;
|
|
7
|
+
/**
|
|
8
|
+
* Returns the possible source directories for the CommandKit application.
|
|
9
|
+
* This includes the `src`, `.commandkit`, and the distribution directory.
|
|
10
|
+
* @returns An array of possible source directories.
|
|
11
|
+
*/
|
|
12
|
+
declare function getSourceDirectories(): string[];
|
|
13
|
+
/**
|
|
14
|
+
* Returns the path to the app directory.
|
|
15
|
+
* @returns The path to the app directory or `null` if not found.
|
|
16
|
+
*/
|
|
17
|
+
declare function findAppDirectory(): string | null;
|
|
18
|
+
/**
|
|
19
|
+
* Debounces a function.
|
|
20
|
+
* @param fn The function to debounce.
|
|
21
|
+
* @param ms The debounce time in milliseconds.
|
|
22
|
+
* @returns The debounced function.
|
|
23
|
+
* @example
|
|
24
|
+
* const debouncedFn = debounce(() => {
|
|
25
|
+
* console.log('Debounced function called');
|
|
26
|
+
* }, 300);
|
|
27
|
+
*
|
|
28
|
+
* debouncedFn(); // Will only execute after 300ms of inactivity
|
|
29
|
+
* debouncedFn(); // Will reset the timer
|
|
30
|
+
* debouncedFn(); // Will reset the timer again
|
|
31
|
+
*/
|
|
32
|
+
declare function debounce<R, F extends (...args: any[]) => R>(fn: F, ms: number): F;
|
|
33
|
+
/**
|
|
34
|
+
* Defers the execution of a function.
|
|
35
|
+
* @param fn The function to defer.
|
|
36
|
+
* @param timeout The time in milliseconds to wait before executing the function. Defaults to 0.
|
|
37
|
+
* @example
|
|
38
|
+
* defer(() => {
|
|
39
|
+
* console.log('This will run after a delay');
|
|
40
|
+
* });
|
|
41
|
+
*
|
|
42
|
+
* console.log('This will run immediately');
|
|
43
|
+
*/
|
|
44
|
+
declare function defer<T>(fn: () => T, timeout?: number): void;
|
|
45
|
+
/**
|
|
46
|
+
* Serializes a value to JSON.
|
|
47
|
+
* @param value The value to serialize.
|
|
48
|
+
* @param defaultValue The default value to return if the value is not serializable.
|
|
49
|
+
* @returns The serialized value.
|
|
50
|
+
*/
|
|
51
|
+
declare function JsonSerialize<R = any>(value: any, defaultValue?: R): R;
|
|
52
|
+
/**
|
|
53
|
+
* Creates a function from the given function that runs only in development mode.
|
|
54
|
+
* @param fn The function to run in development mode.
|
|
55
|
+
* @returns The function that runs only in development mode.
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* const devOnlyFn = devOnly(() => {
|
|
59
|
+
* console.log('This function runs only in development mode');
|
|
60
|
+
* });
|
|
61
|
+
* devOnlyFn(); // This will log the message only in development mode
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
declare function devOnly<T extends (...args: any[]) => any>(fn: T): T;
|
|
65
|
+
/**
|
|
66
|
+
* Creates a function from the given function that runs only in build mode.
|
|
67
|
+
* @param fn The function to run in build mode.
|
|
68
|
+
* @returns The function that runs only in build mode.
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* const buildOnlyFn = buildOnly(() => {
|
|
72
|
+
* console.log('This function runs only in build mode');
|
|
73
|
+
* });
|
|
74
|
+
* buildOnlyFn(); // This will log the message only in build mode
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
declare function buildOnly<T extends (...args: any[]) => any>(fn: T): T;
|
|
78
|
+
/**
|
|
79
|
+
* Creates a function from the given function that runs only outside of build mode.
|
|
80
|
+
* @param fn The function to run outside of build mode.
|
|
81
|
+
* @returns The function that runs only outside of build mode.
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* const noBuildOnlyFn = noBuildOnly(() => {
|
|
85
|
+
* console.log('This function runs only outside of build mode');
|
|
86
|
+
* });
|
|
87
|
+
* noBuildOnlyFn(); // This will log the message only outside of build mode
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
declare function noBuildOnly<T extends (...args: any[]) => any>(fn: T): T;
|
|
91
|
+
/**
|
|
92
|
+
* Represents a simple proxy object that mirrors a target object.
|
|
93
|
+
*/
|
|
94
|
+
interface SimpleProxy<T extends object> {
|
|
95
|
+
/**
|
|
96
|
+
* The proxied object that mirrors the target.
|
|
97
|
+
*/
|
|
98
|
+
proxy: T;
|
|
99
|
+
/**
|
|
100
|
+
* Sets a new target object for the proxy.
|
|
101
|
+
* @param newTarget The new target object to set.
|
|
102
|
+
*/
|
|
103
|
+
setTarget(newTarget: T): void;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Creates a simple proxy object that mirrors the target object.
|
|
107
|
+
* @param target The target object to proxy.
|
|
108
|
+
* @returns The proxied object.
|
|
109
|
+
*/
|
|
110
|
+
declare function createProxy<T extends object>(target: T): SimpleProxy<T>;
|
|
111
|
+
//#endregion
|
|
112
|
+
export { JsonSerialize, SimpleProxy, buildOnly, createProxy, debounce, defer, devOnly, findAppDirectory, getCurrentDirectory, getSourceDirectories, noBuildOnly };
|
|
113
|
+
//# sourceMappingURL=utilities.d.ts.map
|
package/dist/utils/utilities.js
CHANGED
|
@@ -1,45 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
require('../
|
|
3
|
-
require('../error-codes-Ds0bnPvT.js');
|
|
4
|
-
const require_commandkit = require('../commandkit-Bm0gLN8i.js');
|
|
5
|
-
require('../common-CcfjYnPG.js');
|
|
6
|
-
require('../common-vnMIelAE.js');
|
|
7
|
-
require('../container-C6GtfAPW.js');
|
|
8
|
-
require('../file-DVOELoNv.js');
|
|
9
|
-
require('../media-gallery-zDtJ3kxb.js');
|
|
10
|
-
require('../section-DlvrDoJK.js');
|
|
11
|
-
require('../separator-DL6QH5H1.js');
|
|
12
|
-
require('../text-display-DbMumig_.js');
|
|
13
|
-
require('../v2-DofkPKHs.js');
|
|
14
|
-
require('../element-Bak9llw_.js');
|
|
15
|
-
require('../types-CUZOquUl.js');
|
|
16
|
-
require('../EventInterceptor-CQEXyUTp.js');
|
|
17
|
-
require('../constants-B5_Ta7PR.js');
|
|
18
|
-
require('../PluginCommon-Cvl5yYM_.js');
|
|
19
|
-
require('../CompilerPlugin-M8r3yNAl.js');
|
|
20
|
-
require('../RuntimePlugin-BUecuBIU.js');
|
|
21
|
-
require('../types-q0Nm882H.js');
|
|
22
|
-
require('../resolve-file-url-ChIyw-Vf.js');
|
|
23
|
-
require('../runtime-DB9CiPfe.js');
|
|
24
|
-
require('../utils-KsNof0Xz.js');
|
|
25
|
-
require('../types-package-BWArjyBF.js');
|
|
26
|
-
require('../constants-BOOGN85p.js');
|
|
27
|
-
require('../EventWorkerContext-Dq29tieI.js');
|
|
28
|
-
require('../signals-ChFMD7mB.js');
|
|
29
|
-
require('../MessageCommandParser-CEuO6Ex3.js');
|
|
30
|
-
require('../helpers-BSwwrKJW.js');
|
|
31
|
-
require('../CommandsRouter-Cgcy6cK9.js');
|
|
32
|
-
require('../EventsRouter-3Gygh-km.js');
|
|
33
|
-
require('../router-Dn35v30f.js');
|
|
34
|
-
require('../common-Dxr9-XPa.js');
|
|
35
|
-
require('../CommandKitEventsChannel-BtRzr3Tz.js');
|
|
36
|
-
require('../store-CM6pWVZh.js');
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_commandkit = require('../commandkit--k6yDJEr.js');
|
|
37
3
|
|
|
38
4
|
exports.JsonSerialize = require_commandkit.JsonSerialize;
|
|
5
|
+
exports.buildOnly = require_commandkit.buildOnly;
|
|
39
6
|
exports.createProxy = require_commandkit.createProxy;
|
|
40
7
|
exports.debounce = require_commandkit.debounce;
|
|
41
8
|
exports.defer = require_commandkit.defer;
|
|
42
9
|
exports.devOnly = require_commandkit.devOnly;
|
|
43
10
|
exports.findAppDirectory = require_commandkit.findAppDirectory;
|
|
44
11
|
exports.getCurrentDirectory = require_commandkit.getCurrentDirectory;
|
|
45
|
-
exports.getSourceDirectories = require_commandkit.getSourceDirectories;
|
|
12
|
+
exports.getSourceDirectories = require_commandkit.getSourceDirectories;
|
|
13
|
+
exports.noBuildOnly = require_commandkit.noBuildOnly;
|